From 1bb02f6d44357cbe0492929d2cfdcd319041c1fc Mon Sep 17 00:00:00 2001 From: Poiana Date: Tue, 10 Sep 2024 14:52:23 +0000 Subject: [PATCH] chore(libs): apply code formatting Signed-off-by: Poiana --- CMakeLists.txt | 71 +- CMakeListsGtestInclude.cmake | 37 +- benchmark/CMakeLists.txt | 12 +- benchmark/libsinsp/utils.cpp | 36 +- benchmark/main.cpp | 2 +- cmake/modules/CompilerFlags.cmake | 91 +- cmake/modules/FindMakedev.cmake | 46 +- cmake/modules/Findbs_threadpool.cmake | 38 +- cmake/modules/Findvalijson.cmake | 43 +- cmake/modules/GetVersionFromGit.cmake | 338 +- cmake/modules/bs_threadpool.cmake | 19 +- cmake/modules/cares.cmake | 40 +- cmake/modules/compute_versions.cmake | 62 +- cmake/modules/curl.cmake | 81 +- cmake/modules/engine_config.cmake | 7 +- cmake/modules/googleBenchmark.cmake | 19 +- cmake/modules/grpc.cmake | 89 +- cmake/modules/gtest.cmake | 60 +- cmake/modules/jsoncpp.cmake | 109 +- cmake/modules/libbpf.cmake | 87 +- cmake/modules/libelf.cmake | 120 +- cmake/modules/libscap.cmake | 246 +- cmake/modules/libsinsp.cmake | 193 +- cmake/modules/openssl.cmake | 45 +- cmake/modules/protobuf.cmake | 62 +- cmake/modules/re2.cmake | 103 +- cmake/modules/tbb.cmake | 111 +- cmake/modules/uthash.cmake | 27 +- cmake/modules/valijson.cmake | 17 +- cmake/modules/versions.cmake | 72 +- cmake/modules/zlib.cmake | 75 +- driver/CMakeLists.txt | 137 +- driver/bpf/CMakeLists.txt | 53 +- driver/bpf/bpf_helpers.h | 171 +- driver/bpf/builtins.h | 2 +- driver/bpf/configure/RSS_STAT_ARRAY/test.c | 6 +- driver/bpf/filler_helpers.h | 664 ++-- driver/bpf/fillers.h | 2874 +++++++--------- driver/bpf/maps.h | 98 +- driver/bpf/missing_definitions.h | 10 +- driver/bpf/plumbing_helpers.h | 326 +- driver/bpf/probe.c | 187 +- driver/bpf/quirks.h | 14 +- driver/bpf/ring_helpers.h | 57 +- driver/bpf/types.h | 45 +- driver/capture_macro.h | 2 +- driver/configure/ACCESS_OK_2/test.c | 7 +- driver/configure/CLASS_CREATE_1/test.c | 10 +- driver/configure/DEVNODE_ARG1_CONST/test.c | 14 +- driver/dynamic_params_table.c | 18 +- driver/event_table.c | 2808 +++++++++++++--- driver/feature_gates.h | 129 +- driver/fillers_table.c | 696 ++-- driver/flags_table.c | 1217 ++++--- driver/kernel_hacks.h | 13 +- driver/main.c | 1367 ++++---- driver/modern_bpf/CMakeLists.txt | 345 +- .../definitions/events_dimensions.h | 55 +- .../definitions/missing_definitions.h | 474 +-- .../modern_bpf/definitions/struct_flavors.h | 33 +- driver/modern_bpf/helpers/base/common.h | 21 +- driver/modern_bpf/helpers/base/maps_getters.h | 75 +- driver/modern_bpf/helpers/base/push_data.h | 102 +- .../modern_bpf/helpers/base/read_from_task.h | 57 +- driver/modern_bpf/helpers/base/shared_size.h | 6 +- driver/modern_bpf/helpers/base/stats.h | 14 +- .../helpers/extract/extract_from_kernel.h | 396 +-- .../helpers/interfaces/attached_programs.h | 31 +- .../helpers/interfaces/syscalls_dispatcher.h | 13 +- .../helpers/store/auxmap_store_params.h | 740 ++--- .../helpers/store/ringbuf_store_params.h | 121 +- driver/modern_bpf/maps/maps.h | 32 +- .../attached/dispatchers/syscall_enter.bpf.c | 34 +- .../attached/dispatchers/syscall_exit.bpf.c | 48 +- .../attached/events/page_fault_kernel.bpf.c | 11 +- .../attached/events/page_fault_user.bpf.c | 11 +- .../attached/events/sched_process_exec.bpf.c | 96 +- .../attached/events/sched_process_exit.bpf.c | 66 +- .../attached/events/sched_process_fork.bpf.c | 42 +- .../attached/events/sched_switch.bpf.c | 13 +- .../attached/events/signal_deliver.bpf.c | 29 +- .../events/custom_logic/drop.bpf.c | 12 +- .../events/custom_logic/hotplug.bpf.c | 15 +- .../syscall_dispatched_events/accept.bpf.c | 32 +- .../syscall_dispatched_events/accept4.bpf.c | 32 +- .../syscall_dispatched_events/access.bpf.c | 16 +- .../syscall_dispatched_events/bind.bpf.c | 19 +- .../syscall_dispatched_events/bpf.bpf.c | 19 +- .../syscall_dispatched_events/brk.bpf.c | 16 +- .../syscall_dispatched_events/capset.bpf.c | 16 +- .../syscall_dispatched_events/chdir.bpf.c | 16 +- .../syscall_dispatched_events/chmod.bpf.c | 16 +- .../syscall_dispatched_events/chown.bpf.c | 16 +- .../syscall_dispatched_events/chroot.bpf.c | 16 +- .../syscall_dispatched_events/clone.bpf.c | 52 +- .../syscall_dispatched_events/clone3.bpf.c | 59 +- .../syscall_dispatched_events/close.bpf.c | 38 +- .../syscall_dispatched_events/connect.bpf.c | 23 +- .../copy_file_range.bpf.c | 22 +- .../syscall_dispatched_events/creat.bpf.c | 26 +- .../delete_module.bpf.c | 12 +- .../syscall_dispatched_events/dup.bpf.c | 16 +- .../syscall_dispatched_events/dup2.bpf.c | 16 +- .../syscall_dispatched_events/dup3.bpf.c | 16 +- .../epoll_create.bpf.c | 68 +- .../epoll_create1.bpf.c | 24 +- .../epoll_wait.bpf.c | 16 +- .../syscall_dispatched_events/eventfd.bpf.c | 16 +- .../syscall_dispatched_events/eventfd2.bpf.c | 16 +- .../syscall_dispatched_events/execve.bpf.c | 124 +- .../syscall_dispatched_events/execveat.bpf.c | 127 +- .../syscall_dispatched_events/fchdir.bpf.c | 16 +- .../syscall_dispatched_events/fchmod.bpf.c | 17 +- .../syscall_dispatched_events/fchmodat.bpf.c | 19 +- .../syscall_dispatched_events/fchown.bpf.c | 17 +- .../syscall_dispatched_events/fchownat.bpf.c | 19 +- .../syscall_dispatched_events/fcntl.bpf.c | 28 +- .../finit_module.bpf.c | 19 +- .../syscall_dispatched_events/flock.bpf.c | 18 +- .../syscall_dispatched_events/fork.bpf.c | 52 +- .../syscall_dispatched_events/fsconfig.bpf.c | 29 +- .../syscall_dispatched_events/fstat.bpf.c | 17 +- .../syscall_dispatched_events/futex.bpf.c | 16 +- .../syscall_dispatched_events/generic.bpf.c | 22 +- .../syscall_dispatched_events/getcwd.bpf.c | 26 +- .../syscall_dispatched_events/getdents.bpf.c | 16 +- .../getdents64.bpf.c | 16 +- .../syscall_dispatched_events/getegid.bpf.c | 39 +- .../syscall_dispatched_events/geteuid.bpf.c | 39 +- .../syscall_dispatched_events/getgid.bpf.c | 39 +- .../getpeername.bpf.c | 16 +- .../syscall_dispatched_events/getresgid.bpf.c | 32 +- .../syscall_dispatched_events/getresuid.bpf.c | 32 +- .../syscall_dispatched_events/getrlimit.bpf.c | 23 +- .../getsockname.bpf.c | 16 +- .../getsockopt.bpf.c | 16 +- .../syscall_dispatched_events/getuid.bpf.c | 39 +- .../init_module.bpf.c | 19 +- .../inotify_init.bpf.c | 16 +- .../inotify_init1.bpf.c | 16 +- .../io_uring_enter.bpf.c | 22 +- .../io_uring_register.bpf.c | 22 +- .../io_uring_setup.bpf.c | 33 +- .../syscall_dispatched_events/ioctl.bpf.c | 16 +- .../syscall_dispatched_events/kill.bpf.c | 16 +- .../syscall_dispatched_events/lchown.bpf.c | 16 +- .../syscall_dispatched_events/link.bpf.c | 16 +- .../syscall_dispatched_events/linkat.bpf.c | 24 +- .../syscall_dispatched_events/listen.bpf.c | 16 +- .../syscall_dispatched_events/llseek.bpf.c | 16 +- .../syscall_dispatched_events/lseek.bpf.c | 16 +- .../syscall_dispatched_events/lstat.bpf.c | 17 +- .../memfd_create.bpf.c | 56 +- .../syscall_dispatched_events/mkdir.bpf.c | 16 +- .../syscall_dispatched_events/mkdirat.bpf.c | 19 +- .../syscall_dispatched_events/mknod.bpf.c | 21 +- .../syscall_dispatched_events/mknodat.bpf.c | 22 +- .../syscall_dispatched_events/mlock.bpf.c | 16 +- .../syscall_dispatched_events/mlock2.bpf.c | 16 +- .../syscall_dispatched_events/mlockall.bpf.c | 16 +- .../syscall_dispatched_events/mmap.bpf.c | 16 +- .../syscall_dispatched_events/mmap2.bpf.c | 16 +- .../syscall_dispatched_events/mount.bpf.c | 19 +- .../syscall_dispatched_events/mprotect.bpf.c | 22 +- .../syscall_dispatched_events/munlock.bpf.c | 16 +- .../munlockall.bpf.c | 16 +- .../syscall_dispatched_events/munmap.bpf.c | 16 +- .../syscall_dispatched_events/nanosleep.bpf.c | 23 +- .../newfstatat.bpf.c | 24 +- .../syscall_dispatched_events/open.bpf.c | 26 +- .../open_by_handle_at.bpf.c | 52 +- .../syscall_dispatched_events/openat.bpf.c | 32 +- .../syscall_dispatched_events/openat2.bpf.c | 40 +- .../pidfd_getfd.bpf.c | 64 +- .../pidfd_open.bpf.c | 67 +- .../syscall_dispatched_events/pipe.bpf.c | 22 +- .../syscall_dispatched_events/pipe2.bpf.c | 22 +- .../syscall_dispatched_events/poll.bpf.c | 20 +- .../syscall_dispatched_events/ppoll.bpf.c | 45 +- .../syscall_dispatched_events/prctl.bpf.c | 62 +- .../syscall_dispatched_events/pread64.bpf.c | 26 +- .../syscall_dispatched_events/preadv.bpf.c | 26 +- .../syscall_dispatched_events/prlimit64.bpf.c | 33 +- .../process_vm_readv.bpf.c | 30 +- .../process_vm_writev.bpf.c | 30 +- .../syscall_dispatched_events/ptrace.bpf.c | 16 +- .../syscall_dispatched_events/pwrite64.bpf.c | 19 +- .../syscall_dispatched_events/pwritev.bpf.c | 19 +- .../syscall_dispatched_events/quotactl.bpf.c | 80 +- .../syscall_dispatched_events/read.bpf.c | 26 +- .../syscall_dispatched_events/readv.bpf.c | 26 +- .../syscall_dispatched_events/recv.bpf.c | 26 +- .../syscall_dispatched_events/recvfrom.bpf.c | 26 +- .../syscall_dispatched_events/recvmmsg.bpf.c | 16 +- .../syscall_dispatched_events/recvmsg.bpf.c | 38 +- .../syscall_dispatched_events/rename.bpf.c | 16 +- .../syscall_dispatched_events/renameat.bpf.c | 22 +- .../syscall_dispatched_events/renameat2.bpf.c | 22 +- .../syscall_dispatched_events/rmdir.bpf.c | 16 +- .../syscall_dispatched_events/seccomp.bpf.c | 16 +- .../syscall_dispatched_events/select.bpf.c | 16 +- .../syscall_dispatched_events/semctl.bpf.c | 19 +- .../syscall_dispatched_events/semget.bpf.c | 16 +- .../syscall_dispatched_events/semop.bpf.c | 31 +- .../syscall_dispatched_events/send.bpf.c | 19 +- .../syscall_dispatched_events/sendfile.bpf.c | 16 +- .../syscall_dispatched_events/sendmmsg.bpf.c | 16 +- .../syscall_dispatched_events/sendmsg.bpf.c | 28 +- .../syscall_dispatched_events/sendto.bpf.c | 26 +- .../syscall_dispatched_events/setgid.bpf.c | 16 +- .../syscall_dispatched_events/setns.bpf.c | 18 +- .../syscall_dispatched_events/setpgid.bpf.c | 16 +- .../syscall_dispatched_events/setregid.bpf.c | 16 +- .../syscall_dispatched_events/setresgid.bpf.c | 16 +- .../syscall_dispatched_events/setresuid.bpf.c | 16 +- .../syscall_dispatched_events/setreuid.bpf.c | 16 +- .../syscall_dispatched_events/setrlimit.bpf.c | 16 +- .../syscall_dispatched_events/setsid.bpf.c | 16 +- .../setsockopt.bpf.c | 16 +- .../syscall_dispatched_events/setuid.bpf.c | 16 +- .../syscall_dispatched_events/shutdown.bpf.c | 16 +- .../syscall_dispatched_events/signalfd.bpf.c | 16 +- .../syscall_dispatched_events/signalfd4.bpf.c | 16 +- .../syscall_dispatched_events/socket.bpf.c | 27 +- .../socketpair.bpf.c | 22 +- .../syscall_dispatched_events/splice.bpf.c | 16 +- .../syscall_dispatched_events/stat.bpf.c | 17 +- .../syscall_dispatched_events/symlink.bpf.c | 16 +- .../syscall_dispatched_events/symlinkat.bpf.c | 19 +- .../syscall_dispatched_events/tgkill.bpf.c | 16 +- .../timerfd_create.bpf.c | 22 +- .../syscall_dispatched_events/tkill.bpf.c | 16 +- .../syscall_dispatched_events/umount.bpf.c | 16 +- .../syscall_dispatched_events/umount2.bpf.c | 16 +- .../syscall_dispatched_events/unlink.bpf.c | 16 +- .../syscall_dispatched_events/unlinkat.bpf.c | 21 +- .../syscall_dispatched_events/unshare.bpf.c | 18 +- .../userfaultfd.bpf.c | 16 +- .../syscall_dispatched_events/vfork.bpf.c | 52 +- .../syscall_dispatched_events/write.bpf.c | 19 +- .../syscall_dispatched_events/writev.bpf.c | 19 +- .../shared_definitions/struct_definitions.h | 42 +- driver/ppm.h | 22 +- driver/ppm_api_version.h | 45 +- driver/ppm_consumer.h | 4 +- driver/ppm_cputime.c | 184 +- driver/ppm_events.c | 693 ++-- driver/ppm_events.h | 49 +- driver/ppm_events_public.h | 2145 ++++++------ driver/ppm_fillers.c | 2446 ++++++-------- driver/ppm_fillers.h | 363 +- driver/ppm_flag_helpers.h | 1103 +++---- driver/ppm_ringbuffer.h | 28 +- driver/ppm_tp.c | 2 +- driver/ppm_tp.h | 7 +- driver/ppm_version.h | 4 +- driver/socketcall_to_syscall.h | 9 +- driver/systype_compat.h | 9 +- test/drivers/CMakeLists.txt | 74 +- test/drivers/event_class/event_class.cpp | 1039 +++--- test/drivers/event_class/event_class.h | 194 +- test/drivers/event_class/network_utils.h | 18 +- test/drivers/flags/capabilities.cpp | 3 +- test/drivers/helpers/file_opener.cpp | 79 +- test/drivers/helpers/file_opener.h | 27 +- test/drivers/helpers/ia32.c | 126 +- test/drivers/helpers/proc_parsing.cpp | 83 +- test/drivers/helpers/proc_parsing.h | 5 +- test/drivers/start_tests.cpp | 170 +- .../test_suites/actions_suite/drop_failed.cpp | 11 +- .../actions_suite/dynamic_snaplen.cpp | 455 +-- .../test_suites/actions_suite/ring_buffer.cpp | 7 +- .../actions_suite/sampling_ratio.cpp | 60 +- .../page_fault_kernel.cpp | 18 +- .../page_fault_user.cpp | 18 +- .../sched_process_exec.cpp | 103 +- .../sched_process_exit.cpp | 143 +- .../sched_process_fork.cpp | 176 +- .../sched_switch.cpp | 15 +- .../signal_deliver.cpp | 19 +- .../syscall_enter_suite/accept4_e.cpp | 12 +- .../syscall_enter_suite/accept_e.cpp | 8 +- .../syscall_enter_suite/access_e.cpp | 6 +- .../syscall_enter_suite/bind_e.cpp | 6 +- .../test_suites/syscall_enter_suite/bpf_e.cpp | 25 +- .../test_suites/syscall_enter_suite/brk_e.cpp | 10 +- .../syscall_enter_suite/capset_e.cpp | 6 +- .../syscall_enter_suite/chdir_e.cpp | 6 +- .../syscall_enter_suite/chmod_e.cpp | 6 +- .../syscall_enter_suite/chown_e.cpp | 6 +- .../syscall_enter_suite/chroot_e.cpp | 7 +- .../syscall_enter_suite/clone3_e.cpp | 10 +- .../syscall_enter_suite/clone_e.cpp | 41 +- .../syscall_enter_suite/close_e.cpp | 6 +- .../syscall_enter_suite/connect_e.cpp | 125 +- .../syscall_enter_suite/copy_file_range_e.cpp | 10 +- .../syscall_enter_suite/creat_e.cpp | 12 +- .../syscall_enter_suite/dup2_e.cpp | 6 +- .../syscall_enter_suite/dup3_e.cpp | 6 +- .../test_suites/syscall_enter_suite/dup_e.cpp | 6 +- .../syscall_enter_suite/epoll_create1_e.cpp | 6 +- .../syscall_enter_suite/epoll_create_e.cpp | 6 +- .../syscall_enter_suite/epoll_wait_e.cpp | 10 +- .../syscall_enter_suite/eventfd2_e.cpp | 6 +- .../syscall_enter_suite/eventfd_e.cpp | 6 +- .../syscall_enter_suite/execve_e.cpp | 10 +- .../syscall_enter_suite/execveat_e.cpp | 10 +- .../syscall_enter_suite/fchdir_e.cpp | 6 +- .../syscall_enter_suite/fchmod_e.cpp | 6 +- .../syscall_enter_suite/fchmodat_e.cpp | 10 +- .../syscall_enter_suite/fchown_e.cpp | 6 +- .../syscall_enter_suite/fchownat_e.cpp | 10 +- .../syscall_enter_suite/fcntl_e.cpp | 6 +- .../syscall_enter_suite/finit_module_e.cpp | 12 +- .../syscall_enter_suite/flock_e.cpp | 6 +- .../syscall_enter_suite/fork_e.cpp | 15 +- .../syscall_enter_suite/fsconfig_e.cpp | 10 +- .../syscall_enter_suite/fstat_e.cpp | 6 +- .../syscall_enter_suite/futex_e.cpp | 10 +- .../syscall_enter_suite/generic_e.cpp | 6 +- .../syscall_enter_suite/getcwd_e.cpp | 6 +- .../syscall_enter_suite/getdents64_e.cpp | 10 +- .../syscall_enter_suite/getdents_e.cpp | 10 +- .../syscall_enter_suite/getegid_e.cpp | 6 +- .../syscall_enter_suite/geteuid_e.cpp | 6 +- .../syscall_enter_suite/getgid_e.cpp | 6 +- .../syscall_enter_suite/getpeername_e.cpp | 10 +- .../syscall_enter_suite/getresgid_e.cpp | 12 +- .../syscall_enter_suite/getresuid_e.cpp | 12 +- .../syscall_enter_suite/getrlimit_e.cpp | 6 +- .../syscall_enter_suite/getsockname_e.cpp | 10 +- .../syscall_enter_suite/getsockopt_e.cpp | 11 +- .../syscall_enter_suite/getuid_e.cpp | 6 +- .../syscall_enter_suite/init_module_e.cpp | 12 +- .../syscall_enter_suite/inotify_init1_e.cpp | 6 +- .../syscall_enter_suite/inotify_init_e.cpp | 7 +- .../syscall_enter_suite/io_uring_enter_e.cpp | 11 +- .../io_uring_register_e.cpp | 10 +- .../syscall_enter_suite/io_uring_setup_e.cpp | 10 +- .../syscall_enter_suite/ioctl_e.cpp | 25 +- .../syscall_enter_suite/kill_e.cpp | 12 +- .../syscall_enter_suite/lchown_e.cpp | 6 +- .../syscall_enter_suite/link_e.cpp | 6 +- .../syscall_enter_suite/linkat_e.cpp | 10 +- .../syscall_enter_suite/listen_e.cpp | 6 +- .../syscall_enter_suite/llseek_e.cpp | 6 +- .../syscall_enter_suite/lseek_e.cpp | 6 +- .../syscall_enter_suite/lstat_e.cpp | 7 +- .../syscall_enter_suite/memfd_create_e.cpp | 37 +- .../syscall_enter_suite/mkdir_e.cpp | 6 +- .../syscall_enter_suite/mkdirat_e.cpp | 6 +- .../syscall_enter_suite/mlock2_e.cpp | 10 +- .../syscall_enter_suite/mlock_e.cpp | 6 +- .../syscall_enter_suite/mlockall_e.cpp | 6 +- .../syscall_enter_suite/mmap2_e.cpp | 16 +- .../syscall_enter_suite/mmap_e.cpp | 18 +- .../syscall_enter_suite/mount_e.cpp | 10 +- .../syscall_enter_suite/mprotect_e.cpp | 10 +- .../syscall_enter_suite/munlock_e.cpp | 10 +- .../syscall_enter_suite/munlockall_e.cpp | 6 +- .../syscall_enter_suite/munmap_e.cpp | 6 +- .../syscall_enter_suite/nanosleep_e.cpp | 18 +- .../syscall_enter_suite/newfstatat_e.cpp | 16 +- .../open_by_handle_at_e.cpp | 10 +- .../syscall_enter_suite/open_e.cpp | 16 +- .../syscall_enter_suite/openat2_e.cpp | 21 +- .../syscall_enter_suite/openat_e.cpp | 20 +- .../syscall_enter_suite/pidfd_getfd_e.cpp | 40 +- .../syscall_enter_suite/pidfd_open_e.cpp | 36 +- .../syscall_enter_suite/pipe2_e.cpp | 6 +- .../syscall_enter_suite/pipe_e.cpp | 6 +- .../syscall_enter_suite/poll_e.cpp | 55 +- .../syscall_enter_suite/ppoll_e.cpp | 23 +- .../syscall_enter_suite/prctl_e.cpp | 11 +- .../syscall_enter_suite/pread64_e.cpp | 6 +- .../syscall_enter_suite/preadv_e.cpp | 6 +- .../syscall_enter_suite/prlimit64_e.cpp | 10 +- .../syscall_enter_suite/ptrace_e.cpp | 6 +- .../syscall_enter_suite/pwrite64_e.cpp | 10 +- .../syscall_enter_suite/pwritev_e.cpp | 20 +- .../syscall_enter_suite/quotactl_e.cpp | 10 +- .../syscall_enter_suite/read_e.cpp | 10 +- .../syscall_enter_suite/readv_e.cpp | 6 +- .../syscall_enter_suite/recv_e.cpp | 10 +- .../syscall_enter_suite/recvfrom_e.cpp | 18 +- .../syscall_enter_suite/recvmmsg_e.cpp | 10 +- .../syscall_enter_suite/recvmsg_e.cpp | 6 +- .../syscall_enter_suite/rename_e.cpp | 6 +- .../syscall_enter_suite/renameat2_e.cpp | 10 +- .../syscall_enter_suite/renameat_e.cpp | 10 +- .../syscall_enter_suite/rmdir_e.cpp | 6 +- .../syscall_enter_suite/seccomp_e.cpp | 6 +- .../syscall_enter_suite/select_e.cpp | 10 +- .../syscall_enter_suite/semctl_e.cpp | 8 +- .../syscall_enter_suite/semget_e.cpp | 8 +- .../syscall_enter_suite/semop_e.cpp | 6 +- .../syscall_enter_suite/send_e.cpp | 10 +- .../syscall_enter_suite/sendfile_e.cpp | 20 +- .../syscall_enter_suite/sendmmsg_e.cpp | 10 +- .../syscall_enter_suite/sendmsg_e.cpp | 71 +- .../syscall_enter_suite/sendto_e.cpp | 75 +- .../syscall_enter_suite/setgid_e.cpp | 6 +- .../syscall_enter_suite/setns_e.cpp | 6 +- .../syscall_enter_suite/setpgid_e.cpp | 6 +- .../syscall_enter_suite/setregid_e.cpp | 44 +- .../syscall_enter_suite/setresgid_e.cpp | 12 +- .../syscall_enter_suite/setresuid_e.cpp | 12 +- .../syscall_enter_suite/setreuid_e.cpp | 44 +- .../syscall_enter_suite/setrlimit_e.cpp | 6 +- .../syscall_enter_suite/setsid_e.cpp | 6 +- .../syscall_enter_suite/setsockopt_e.cpp | 11 +- .../syscall_enter_suite/setuid_e.cpp | 6 +- .../syscall_enter_suite/shutdown_e.cpp | 6 +- .../syscall_enter_suite/signalfd4_e.cpp | 10 +- .../syscall_enter_suite/signalfd_e.cpp | 10 +- .../syscall_enter_suite/socket_e.cpp | 25 +- .../syscall_enter_suite/socketcall_e.cpp | 264 +- .../syscall_enter_suite/socketpair_e.cpp | 10 +- .../syscall_enter_suite/splice_e.cpp | 10 +- .../syscall_enter_suite/stat_e.cpp | 7 +- .../syscall_enter_suite/symlink_e.cpp | 6 +- .../syscall_enter_suite/symlinkat_e.cpp | 10 +- .../syscall_enter_suite/tgkill_e.cpp | 10 +- .../syscall_enter_suite/timerfd_create_e.cpp | 10 +- .../syscall_enter_suite/tkill_e.cpp | 6 +- .../syscall_enter_suite/ugetrlimit_e.cpp | 6 +- .../syscall_enter_suite/umount2_e.cpp | 10 +- .../syscall_enter_suite/umount_e.cpp | 6 +- .../syscall_enter_suite/unlink_e.cpp | 6 +- .../syscall_enter_suite/unlinkat_e.cpp | 10 +- .../syscall_enter_suite/unshare_e.cpp | 6 +- .../syscall_enter_suite/userfaultfd_e.cpp | 6 +- .../syscall_enter_suite/vfork_e.cpp | 3 +- .../syscall_enter_suite/write_e.cpp | 10 +- .../syscall_enter_suite/writev_e.cpp | 12 +- .../syscall_exit_suite/accept4_x.cpp | 72 +- .../syscall_exit_suite/accept_x.cpp | 59 +- .../syscall_exit_suite/access_x.cpp | 6 +- .../test_suites/syscall_exit_suite/bind_x.cpp | 45 +- .../test_suites/syscall_exit_suite/bpf_x.cpp | 54 +- .../test_suites/syscall_exit_suite/brk_x.cpp | 10 +- .../syscall_exit_suite/capset_x.cpp | 21 +- .../syscall_exit_suite/chdir_x.cpp | 6 +- .../syscall_exit_suite/chmod_x.cpp | 6 +- .../syscall_exit_suite/chown_x.cpp | 6 +- .../syscall_exit_suite/chroot_x.cpp | 7 +- .../syscall_exit_suite/clock_gettime_x.cpp | 6 +- .../syscall_exit_suite/clone3_x.cpp | 181 +- .../syscall_exit_suite/clone_x.cpp | 73 +- .../syscall_exit_suite/close_x.cpp | 6 +- .../syscall_exit_suite/connect_x.cpp | 154 +- .../syscall_exit_suite/copy_file_range_x.cpp | 10 +- .../syscall_exit_suite/creat_x.cpp | 21 +- .../syscall_exit_suite/delete_module_x.cpp | 12 +- .../test_suites/syscall_exit_suite/dup2_x.cpp | 6 +- .../test_suites/syscall_exit_suite/dup3_x.cpp | 6 +- .../test_suites/syscall_exit_suite/dup_x.cpp | 6 +- .../syscall_exit_suite/epoll_create1_x.cpp | 6 +- .../syscall_exit_suite/epoll_create_x.cpp | 6 +- .../syscall_exit_suite/epoll_wait_x.cpp | 10 +- .../syscall_exit_suite/eventfd2_x.cpp | 12 +- .../syscall_exit_suite/eventfd_x.cpp | 6 +- .../syscall_exit_suite/execve_x.cpp | 559 ++-- .../syscall_exit_suite/execveat_x.cpp | 264 +- .../syscall_exit_suite/fchdir_x.cpp | 6 +- .../syscall_exit_suite/fchmod_x.cpp | 6 +- .../syscall_exit_suite/fchmodat_x.cpp | 10 +- .../syscall_exit_suite/fchown_x.cpp | 6 +- .../syscall_exit_suite/fchownat_x.cpp | 10 +- .../syscall_exit_suite/fcntl_x.cpp | 6 +- .../syscall_exit_suite/finit_module_x.cpp | 45 +- .../syscall_exit_suite/flock_x.cpp | 6 +- .../test_suites/syscall_exit_suite/fork_x.cpp | 44 +- .../syscall_exit_suite/fsconfig_x.cpp | 16 +- .../syscall_exit_suite/fstat_x.cpp | 6 +- .../syscall_exit_suite/futex_x.cpp | 12 +- .../syscall_exit_suite/generic_x.cpp | 6 +- .../syscall_exit_suite/getcpu_x.cpp | 6 +- .../syscall_exit_suite/getcwd_x.cpp | 12 +- .../syscall_exit_suite/getdents64_x.cpp | 10 +- .../syscall_exit_suite/getdents_x.cpp | 10 +- .../syscall_exit_suite/getegid_x.cpp | 6 +- .../syscall_exit_suite/geteuid_x.cpp | 6 +- .../syscall_exit_suite/getgid_x.cpp | 6 +- .../syscall_exit_suite/getpeername_x.cpp | 10 +- .../syscall_exit_suite/getresgid_x.cpp | 10 +- .../syscall_exit_suite/getresuid_x.cpp | 10 +- .../syscall_exit_suite/getrlimit_x.cpp | 24 +- .../syscall_exit_suite/getsockname_x.cpp | 10 +- .../syscall_exit_suite/getsockopt_x.cpp | 95 +- .../syscall_exit_suite/gettimeofday_x.cpp | 6 +- .../syscall_exit_suite/getuid_x.cpp | 6 +- .../syscall_exit_suite/init_module_x.cpp | 10 +- .../syscall_exit_suite/inotify_init1_x.cpp | 12 +- .../syscall_exit_suite/inotify_init_x.cpp | 7 +- .../syscall_exit_suite/io_uring_enter_x.cpp | 11 +- .../io_uring_register_x.cpp | 10 +- .../syscall_exit_suite/io_uring_setup_x.cpp | 20 +- .../syscall_exit_suite/ioctl_x.cpp | 25 +- .../test_suites/syscall_exit_suite/kill_x.cpp | 12 +- .../syscall_exit_suite/lchown_x.cpp | 6 +- .../test_suites/syscall_exit_suite/link_x.cpp | 6 +- .../syscall_exit_suite/linkat_x.cpp | 10 +- .../syscall_exit_suite/listen_x.cpp | 6 +- .../syscall_exit_suite/llseek_x.cpp | 6 +- .../syscall_exit_suite/lseek_x.cpp | 6 +- .../syscall_exit_suite/lstat_x.cpp | 6 +- .../syscall_exit_suite/memfd_create_x.cpp | 110 +- .../syscall_exit_suite/mkdir_x.cpp | 6 +- .../syscall_exit_suite/mkdirat_x.cpp | 6 +- .../syscall_exit_suite/mknod_e.cpp | 12 +- .../syscall_exit_suite/mknod_x.cpp | 72 +- .../syscall_exit_suite/mknodat_e.cpp | 12 +- .../syscall_exit_suite/mknodat_x.cpp | 72 +- .../syscall_exit_suite/mlock2_x.cpp | 10 +- .../syscall_exit_suite/mlock_x.cpp | 6 +- .../syscall_exit_suite/mlockall_x.cpp | 6 +- .../syscall_exit_suite/mmap2_x.cpp | 16 +- .../test_suites/syscall_exit_suite/mmap_x.cpp | 16 +- .../syscall_exit_suite/mount_x.cpp | 10 +- .../syscall_exit_suite/mprotect_x.cpp | 10 +- .../syscall_exit_suite/munlock_x.cpp | 6 +- .../syscall_exit_suite/munlockall_x.cpp | 6 +- .../syscall_exit_suite/munmap_x.cpp | 6 +- .../syscall_exit_suite/nanosleep_x.cpp | 6 +- .../syscall_exit_suite/newfstatat_x.cpp | 14 +- .../open_by_handle_at_x.cpp | 109 +- .../test_suites/syscall_exit_suite/open_x.cpp | 41 +- .../syscall_exit_suite/openat2_x.cpp | 42 +- .../syscall_exit_suite/openat_x.cpp | 50 +- .../syscall_exit_suite/pidfd_getfd_x.cpp | 70 +- .../syscall_exit_suite/pidfd_open_x.cpp | 128 +- .../syscall_exit_suite/pipe2_x.cpp | 6 +- .../test_suites/syscall_exit_suite/pipe_x.cpp | 18 +- .../test_suites/syscall_exit_suite/poll_x.cpp | 12 +- .../syscall_exit_suite/ppoll_x.cpp | 10 +- .../syscall_exit_suite/prctl_x.cpp | 88 +- .../syscall_exit_suite/pread64_x.cpp | 8 +- .../syscall_exit_suite/preadv_x.cpp | 8 +- .../syscall_exit_suite/prlimit64_x.cpp | 28 +- .../syscall_exit_suite/process_vm_readv_x.cpp | 26 +- .../process_vm_writev_x.cpp | 29 +- .../syscall_exit_suite/ptrace_x.cpp | 6 +- .../syscall_exit_suite/pwrite64_x.cpp | 32 +- .../syscall_exit_suite/pwritev_x.cpp | 32 +- .../syscall_exit_suite/quotactl_x.cpp | 10 +- .../test_suites/syscall_exit_suite/read_x.cpp | 92 +- .../syscall_exit_suite/readv_x.cpp | 30 +- .../test_suites/syscall_exit_suite/recv_x.cpp | 10 +- .../syscall_exit_suite/recvfrom_x.cpp | 349 +- .../syscall_exit_suite/recvmmsg_x.cpp | 10 +- .../syscall_exit_suite/recvmsg_x.cpp | 283 +- .../syscall_exit_suite/rename_x.cpp | 6 +- .../syscall_exit_suite/renameat2_x.cpp | 10 +- .../syscall_exit_suite/renameat_x.cpp | 10 +- .../syscall_exit_suite/rmdir_x.cpp | 6 +- .../syscall_exit_suite/seccomp_x.cpp | 6 +- .../syscall_exit_suite/select_x.cpp | 12 +- .../syscall_exit_suite/semctl_x.cpp | 8 +- .../syscall_exit_suite/semget_x.cpp | 8 +- .../syscall_exit_suite/semop_x.cpp | 40 +- .../test_suites/syscall_exit_suite/send_x.cpp | 10 +- .../syscall_exit_suite/sendfile_x.cpp | 20 +- .../syscall_exit_suite/sendmmsg_x.cpp | 10 +- .../syscall_exit_suite/sendmsg_x.cpp | 116 +- .../syscall_exit_suite/sendto_x.cpp | 150 +- .../syscall_exit_suite/setgid_x.cpp | 6 +- .../syscall_exit_suite/setns_x.cpp | 6 +- .../syscall_exit_suite/setpgid_x.cpp | 6 +- .../syscall_exit_suite/setregid_x.cpp | 56 +- .../syscall_exit_suite/setresgid_x.cpp | 12 +- .../syscall_exit_suite/setresuid_x.cpp | 12 +- .../syscall_exit_suite/setreuid_x.cpp | 56 +- .../syscall_exit_suite/setrlimit_x.cpp | 18 +- .../syscall_exit_suite/setsid_x.cpp | 6 +- .../syscall_exit_suite/setsockopt_x.cpp | 77 +- .../syscall_exit_suite/setuid_x.cpp | 6 +- .../syscall_exit_suite/shutdown_x.cpp | 6 +- .../syscall_exit_suite/signalfd4_x.cpp | 10 +- .../syscall_exit_suite/signalfd_x.cpp | 10 +- .../syscall_exit_suite/socket_x.cpp | 25 +- .../syscall_exit_suite/socketcall_x.cpp | 733 +++-- .../syscall_exit_suite/socketpair_x.cpp | 22 +- .../syscall_exit_suite/splice_x.cpp | 12 +- .../test_suites/syscall_exit_suite/stat_x.cpp | 6 +- .../syscall_exit_suite/symlink_x.cpp | 6 +- .../syscall_exit_suite/symlinkat_x.cpp | 10 +- .../syscall_exit_suite/tgkill_x.cpp | 10 +- .../test_suites/syscall_exit_suite/time_x.cpp | 6 +- .../syscall_exit_suite/timerfd_create_x.cpp | 12 +- .../syscall_exit_suite/tkill_x.cpp | 8 +- .../syscall_exit_suite/ugetrlimit_x.cpp | 18 +- .../syscall_exit_suite/umount2_x.cpp | 6 +- .../syscall_exit_suite/umount_x.cpp | 6 +- .../syscall_exit_suite/unlink_x.cpp | 6 +- .../syscall_exit_suite/unlinkat_x.cpp | 10 +- .../syscall_exit_suite/unshare_x.cpp | 6 +- .../syscall_exit_suite/userfaultfd_x.cpp | 8 +- .../syscall_exit_suite/write_x.cpp | 49 +- .../syscall_exit_suite/writev_x.cpp | 24 +- test/e2e/CMakeLists.txt | 65 +- test/libscap/CMakeLists.txt | 73 +- test/libscap/helpers/engines.cpp | 160 +- test/libscap/test_suites/engines/bpf/bpf.cpp | 175 +- .../engines/gvisor/gvisor_parsers.cpp | 844 ++--- .../engines/gvisor/gvisor_platform.cpp | 18 +- .../libscap/test_suites/engines/kmod/kmod.cpp | 212 +- .../engines/modern_bpf/modern_bpf.cpp | 257 +- .../test_suites/userspace/common_strl.cpp | 25 +- .../test_suites/userspace/event_table.cpp | 86 +- .../userspace/linux/scap_cgroup.cpp | 51 +- .../userspace/ppm_sc_names_table.cpp | 3 +- .../test_suites/userspace/scap_event.cpp | 256 +- .../test_suites/userspace/scap_ppm_sc.cpp | 91 +- .../test_suites/userspace/syscall_table.cpp | 23 +- test/libsinsp_e2e/CMakeLists.txt | 122 +- test/libsinsp_e2e/capture_to_file_test.cpp | 28 +- test/libsinsp_e2e/container/container.cpp | 449 +-- .../container/container_cgroup.cpp | 58 +- test/libsinsp_e2e/container/docker_utils.cpp | 77 +- test/libsinsp_e2e/container/docker_utils.h | 34 +- test/libsinsp_e2e/event_capture.cpp | 227 +- test/libsinsp_e2e/event_capture.h | 120 +- test/libsinsp_e2e/forking.cpp | 420 +-- test/libsinsp_e2e/fs.cpp | 780 ++--- test/libsinsp_e2e/ipv6.cpp | 224 +- test/libsinsp_e2e/main.cpp | 103 +- test/libsinsp_e2e/paths.cpp | 280 +- test/libsinsp_e2e/process.cpp | 398 +-- test/libsinsp_e2e/resources/CMakeLists.txt | 31 +- test/libsinsp_e2e/resources/chname.cpp | 18 +- .../docker/health_dockerfiles/CMakeLists.txt | 24 +- test/libsinsp_e2e/resources/execve.c | 13 +- .../resources/forking_main_thread_exit.c | 12 +- test/libsinsp_e2e/resources/forking_nested.c | 55 +- test/libsinsp_e2e/scap_file_reader.h | 33 +- test/libsinsp_e2e/subprocess.cpp | 219 +- test/libsinsp_e2e/subprocess.h | 44 +- test/libsinsp_e2e/suppress_events.cpp | 177 +- test/libsinsp_e2e/sys_call_test.cpp | 1331 +++----- test/libsinsp_e2e/sys_call_test.h | 41 +- test/libsinsp_e2e/tcp_client_server.cpp | 287 +- test/libsinsp_e2e/tcp_client_server.h | 174 +- .../tcp_client_server_ipv4_mapped.cpp | 371 +-- test/libsinsp_e2e/test_helper.cpp | 341 +- test/libsinsp_e2e/thread_state.cpp | 83 +- test/libsinsp_e2e/threadinfo.cpp | 110 +- test/libsinsp_e2e/udp_client_server.cpp | 1021 +++--- test/libsinsp_e2e/unix_client_server.cpp | 117 +- test/libsinsp_e2e/utils.h | 21 +- test/libsinsp_e2e/vtidcollision.c | 57 +- test/vm/CMakeLists.txt | 93 +- userspace/libpman/CMakeLists.txt | 71 +- userspace/libpman/include/libpman.h | 859 ++--- userspace/libpman/src/configuration.c | 175 +- userspace/libpman/src/events_prog_names.h | 672 ++-- userspace/libpman/src/lifecycle.c | 36 +- userspace/libpman/src/maps.c | 173 +- userspace/libpman/src/programs.c | 137 +- userspace/libpman/src/ringbuffer.c | 163 +- .../libpman/src/ringbuffer_debug_macro.h | 13 +- .../libpman/src/ringbuffer_definitions.h | 25 +- userspace/libpman/src/sc_set.c | 33 +- userspace/libpman/src/state.c | 26 +- userspace/libpman/src/state.h | 51 +- userspace/libpman/src/stats.c | 249 +- userspace/libscap/CMakeLists.txt | 145 +- userspace/libscap/clock_helpers.h | 13 +- userspace/libscap/compat/bpf.h | 1366 ++++---- userspace/libscap/compat/bpf_common.h | 78 +- userspace/libscap/compat/misc.h | 4 +- userspace/libscap/compat/perf_event.h | 828 +++-- userspace/libscap/debug_log_helpers.h | 12 +- userspace/libscap/emscripten/gettimeofday.h | 6 +- userspace/libscap/emscripten/sleep.h | 3 +- userspace/libscap/engine/bpf/CMakeLists.txt | 27 +- userspace/libscap/engine/bpf/attached_prog.c | 120 +- userspace/libscap/engine/bpf/attached_prog.h | 21 +- userspace/libscap/engine/bpf/bpf.h | 5 +- userspace/libscap/engine/bpf/bpf_public.h | 14 +- userspace/libscap/engine/bpf/scap_bpf.c | 1483 +++++---- userspace/libscap/engine/bpf/scap_bpf.h | 87 +- userspace/libscap/engine/bpf/scap_bpf_stats.h | 2 +- .../libscap/engine/gvisor/CMakeLists.txt | 127 +- userspace/libscap/engine/gvisor/fillers.cpp | 2098 ++++++------ userspace/libscap/engine/gvisor/fillers.h | 1001 +++--- userspace/libscap/engine/gvisor/gvisor.cpp | 184 +- userspace/libscap/engine/gvisor/gvisor.h | 251 +- .../libscap/engine/gvisor/gvisor_platform.h | 8 +- .../libscap/engine/gvisor/gvisor_public.h | 25 +- userspace/libscap/engine/gvisor/parsers.cpp | 1892 +++++------ userspace/libscap/engine/gvisor/parsers.h | 211 +- userspace/libscap/engine/gvisor/runsc.cpp | 122 +- .../libscap/engine/gvisor/scap_gvisor.cpp | 373 +-- .../engine/gvisor/scap_gvisor_platform.cpp | 67 +- .../libscap/engine/gvisor/scap_gvisor_stats.h | 18 +- userspace/libscap/engine/kmod/CMakeLists.txt | 20 +- userspace/libscap/engine/kmod/kmod.h | 4 +- userspace/libscap/engine/kmod/kmod_public.h | 16 +- userspace/libscap/engine/kmod/scap_kmod.c | 820 +++-- .../libscap/engine/kmod/scap_kmod_stats.h | 2 +- .../libscap/engine/modern_bpf/CMakeLists.txt | 62 +- .../engine/modern_bpf/modern_bpf_public.h | 24 +- .../engine/modern_bpf/scap_modern_bpf.c | 241 +- .../engine/modern_bpf/scap_modern_bpf.h | 7 +- .../libscap/engine/nodriver/CMakeLists.txt | 16 +- userspace/libscap/engine/nodriver/nodriver.c | 51 +- userspace/libscap/engine/nodriver/nodriver.h | 3 +- userspace/libscap/engine/noop/CMakeLists.txt | 28 +- userspace/libscap/engine/noop/noop.c | 97 +- userspace/libscap/engine/noop/noop.h | 15 +- .../libscap/engine/savefile/CMakeLists.txt | 33 +- userspace/libscap/engine/savefile/savefile.h | 74 +- .../engine/savefile/savefile_platform.h | 3 +- .../libscap/engine/savefile/savefile_public.h | 26 +- .../libscap/engine/savefile/scap_reader.h | 101 +- .../engine/savefile/scap_reader_buffered.c | 201 +- .../engine/savefile/scap_reader_gzfile.c | 117 +- .../libscap/engine/savefile/scap_savefile.c | 1080 +++--- .../engine/source_plugin/CMakeLists.txt | 16 +- .../engine/source_plugin/plugin_info.h | 16 +- .../engine/source_plugin/source_plugin.c | 244 +- .../engine/source_plugin/source_plugin.h | 4 +- .../source_plugin/source_plugin_public.h | 14 +- .../source_plugin/source_plugin_stats.h | 2 +- .../libscap/engine/test_input/CMakeLists.txt | 16 +- .../libscap/engine/test_input/scap_test.h | 14 +- .../libscap/engine/test_input/test_input.c | 71 +- .../engine/test_input/test_input_platform.c | 69 +- .../engine/test_input/test_input_platform.h | 4 +- .../engine/test_input/test_input_public.h | 17 +- .../libscap/examples/01-open/CMakeLists.txt | 22 +- .../libscap/examples/01-open/scap_open.c | 658 ++-- .../examples/02-validatebuffer/CMakeLists.txt | 22 +- .../libscap/examples/02-validatebuffer/test.c | 118 +- userspace/libscap/linux/CMakeLists.txt | 23 +- userspace/libscap/linux/gettimeofday.h | 6 +- userspace/libscap/linux/scap_cgroup.c | 491 ++- userspace/libscap/linux/scap_cgroup.h | 79 +- userspace/libscap/linux/scap_fds.c | 672 ++-- userspace/libscap/linux/scap_iflist.c | 145 +- .../linux/scap_linux_hostinfo_platform.c | 27 +- userspace/libscap/linux/scap_linux_int.h | 41 +- userspace/libscap/linux/scap_linux_platform.c | 73 +- userspace/libscap/linux/scap_linux_platform.h | 21 +- userspace/libscap/linux/scap_machine_info.c | 83 +- userspace/libscap/linux/scap_ppm_sc.c | 1482 ++++++--- userspace/libscap/linux/scap_procs.c | 903 +++-- userspace/libscap/linux/scap_userlist.c | 190 +- userspace/libscap/linux/sleep.h | 3 +- userspace/libscap/linux/unixid.h | 10 +- userspace/libscap/macos/gettimeofday.h | 6 +- userspace/libscap/macos/sleep.h | 3 +- userspace/libscap/metrics_v2.h | 13 +- userspace/libscap/ppm_sc_names.c | 20 +- userspace/libscap/ringbuffer/devset.c | 23 +- userspace/libscap/ringbuffer/devset.h | 42 +- userspace/libscap/ringbuffer/ringbuffer.c | 27 +- userspace/libscap/ringbuffer/ringbuffer.h | 141 +- .../libscap/ringbuffer/ringbuffer_dump.c | 234 +- userspace/libscap/scap-int.h | 23 +- userspace/libscap/scap.c | 364 +-- userspace/libscap/scap.h | 460 +-- userspace/libscap/scap_api_version.c | 80 +- userspace/libscap/scap_api_version.h | 14 +- userspace/libscap/scap_assert.h | 6 +- userspace/libscap/scap_cgroup_set.h | 14 +- userspace/libscap/scap_const.h | 1 - userspace/libscap/scap_engine_util.c | 22 +- userspace/libscap/scap_engine_util.h | 5 +- userspace/libscap/scap_event.c | 281 +- userspace/libscap/scap_fds.c | 21 +- userspace/libscap/scap_iflist.c | 12 +- userspace/libscap/scap_log.h | 7 +- userspace/libscap/scap_machine_info.h | 32 +- userspace/libscap/scap_open.h | 40 +- userspace/libscap/scap_platform.c | 81 +- userspace/libscap/scap_platform.h | 13 +- userspace/libscap/scap_platform_api.c | 93 +- userspace/libscap/scap_platform_api.h | 18 +- userspace/libscap/scap_platform_impl.h | 34 +- userspace/libscap/scap_proc_util.c | 39 +- userspace/libscap/scap_proc_util.h | 12 +- userspace/libscap/scap_procs.c | 106 +- userspace/libscap/scap_procs.h | 37 +- userspace/libscap/scap_savefile.c | 820 ++--- userspace/libscap/scap_savefile.h | 121 +- userspace/libscap/scap_savefile_api.h | 63 +- userspace/libscap/scap_userlist.c | 6 +- userspace/libscap/scap_vtable.h | 27 +- userspace/libscap/scap_zlib.h | 9 +- userspace/libscap/strerror.c | 9 +- userspace/libscap/strerror.h | 9 +- userspace/libscap/strl.h | 60 +- userspace/libscap/userspace_flag_helpers.h | 12 +- userspace/libscap/uthash_ext.h | 14 +- userspace/libscap/win32/gettimeofday.h | 9 +- userspace/libscap/win32/sleep.h | 3 +- userspace/libsinsp/CMakeLists.txt | 199 +- .../libsinsp/async/async_key_value_source.h | 68 +- userspace/libsinsp/base64.h | 120 +- userspace/libsinsp/capture_stats_source.h | 7 +- userspace/libsinsp/cgroup_limits.cpp | 234 +- userspace/libsinsp/cgroup_limits.h | 83 +- userspace/libsinsp/cgroup_list_counter.h | 73 +- userspace/libsinsp/container.cpp | 435 ++- userspace/libsinsp/container.h | 93 +- userspace/libsinsp/container_engine/bpm.cpp | 27 +- userspace/libsinsp/container_engine/bpm.h | 12 +- .../container_engine/container_async_source.h | 18 +- .../container_cache_interface.h | 24 +- .../container_engine_base.cpp | 22 +- .../container_engine/container_engine_base.h | 15 +- userspace/libsinsp/container_engine/cri.cpp | 271 +- userspace/libsinsp/container_engine/cri.h | 54 +- .../container_engine/docker/async_source.cpp | 739 ++--- .../container_engine/docker/async_source.h | 50 +- .../libsinsp/container_engine/docker/base.cpp | 63 +- .../libsinsp/container_engine/docker/base.h | 17 +- .../container_engine/docker/connection.h | 23 +- .../docker/connection_linux.cpp | 137 +- .../container_engine/docker/docker_linux.cpp | 42 +- .../container_engine/docker/docker_linux.h | 13 +- .../container_engine/docker/lookup_request.h | 59 +- .../container_engine/docker/podman.cpp | 97 +- .../libsinsp/container_engine/docker/podman.h | 9 +- .../libsinsp/container_engine/libvirt_lxc.cpp | 35 +- .../libsinsp/container_engine/libvirt_lxc.h | 13 +- userspace/libsinsp/container_engine/lxc.cpp | 28 +- userspace/libsinsp/container_engine/lxc.h | 10 +- userspace/libsinsp/container_engine/mesos.cpp | 84 +- userspace/libsinsp/container_engine/mesos.h | 14 +- userspace/libsinsp/container_engine/rkt.cpp | 181 +- userspace/libsinsp/container_engine/rkt.h | 26 +- .../container_engine/sinsp_container_type.h | 3 +- .../container_engine/static_container.cpp | 21 +- .../container_engine/static_container.h | 9 +- userspace/libsinsp/container_info.cpp | 161 +- userspace/libsinsp/container_info.h | 211 +- userspace/libsinsp/cri.h | 164 +- userspace/libsinsp/cri.hpp | 601 ++-- userspace/libsinsp/cri_settings.cpp | 32 +- userspace/libsinsp/dns_manager.cpp | 108 +- userspace/libsinsp/dns_manager.h | 63 +- userspace/libsinsp/dumper.cpp | 95 +- userspace/libsinsp/dumper.h | 20 +- userspace/libsinsp/event.cpp | 1863 +++++------ userspace/libsinsp/event.h | 523 ++- userspace/libsinsp/eventformatter.cpp | 223 +- userspace/libsinsp/eventformatter.h | 55 +- userspace/libsinsp/events/sinsp_events.cpp | 123 +- userspace/libsinsp/events/sinsp_events.h | 183 +- .../libsinsp/events/sinsp_events_ppm_sc.cpp | 390 +-- userspace/libsinsp/events/sinsp_events_set.h | 217 +- userspace/libsinsp/examples/CMakeLists.txt | 37 +- userspace/libsinsp/examples/test.cpp | 299 +- userspace/libsinsp/examples/util.cpp | 77 +- userspace/libsinsp/fdinfo.cpp | 279 +- userspace/libsinsp/fdinfo.h | 368 +-- userspace/libsinsp/filter.cpp | 563 ++-- userspace/libsinsp/filter.h | 134 +- userspace/libsinsp/filter/ast.cpp | 473 ++- userspace/libsinsp/filter/ast.h | 914 +++--- userspace/libsinsp/filter/escaping.cpp | 126 +- userspace/libsinsp/filter/escaping.h | 11 +- userspace/libsinsp/filter/parser.cpp | 458 +-- userspace/libsinsp/filter/parser.h | 87 +- userspace/libsinsp/filter/ppm_codes.cpp | 389 +-- userspace/libsinsp/filter/ppm_codes.h | 6 +- userspace/libsinsp/filter_cache.h | 432 ++- userspace/libsinsp/filter_check_list.cpp | 37 +- userspace/libsinsp/filter_check_list.h | 10 +- userspace/libsinsp/filter_compare.cpp | 550 ++-- userspace/libsinsp/filter_compare.h | 24 +- userspace/libsinsp/filter_field.h | 105 +- userspace/libsinsp/filter_value.h | 18 +- userspace/libsinsp/grpc_channel_registry.cpp | 25 +- userspace/libsinsp/grpc_channel_registry.h | 14 +- userspace/libsinsp/gvisor_config.cpp | 452 +-- userspace/libsinsp/gvisor_config.h | 5 +- userspace/libsinsp/ifinfo.cpp | 291 +- userspace/libsinsp/ifinfo.h | 18 +- userspace/libsinsp/logger.cpp | 194 +- userspace/libsinsp/logger.h | 9 +- userspace/libsinsp/logger_macros.h | 124 +- userspace/libsinsp/memmem.h | 19 +- userspace/libsinsp/metrics_collector.cpp | 726 ++-- userspace/libsinsp/metrics_collector.h | 275 +- userspace/libsinsp/mpsc_priority_queue.h | 62 +- userspace/libsinsp/mutex.h | 128 +- userspace/libsinsp/parsers.cpp | 2905 +++++++---------- userspace/libsinsp/parsers.h | 71 +- userspace/libsinsp/plugin.cpp | 833 ++--- userspace/libsinsp/plugin.h | 327 +- userspace/libsinsp/plugin_filtercheck.cpp | 189 +- userspace/libsinsp/plugin_filtercheck.h | 23 +- userspace/libsinsp/plugin_manager.h | 97 +- userspace/libsinsp/plugin_parser.h | 80 +- userspace/libsinsp/plugin_table_api.cpp | 1341 ++++---- userspace/libsinsp/prefix_search.cpp | 43 +- userspace/libsinsp/prefix_search.h | 247 +- userspace/libsinsp/procfs_utils.cpp | 39 +- userspace/libsinsp/procfs_utils.h | 15 +- userspace/libsinsp/runc.cpp | 53 +- userspace/libsinsp/runc.h | 23 +- userspace/libsinsp/scap_open_exception.h | 20 +- userspace/libsinsp/settings.h | 1 - userspace/libsinsp/sinsp.cpp | 1181 +++---- userspace/libsinsp/sinsp.h | 568 ++-- userspace/libsinsp/sinsp_cgroup.cpp | 48 +- userspace/libsinsp/sinsp_cgroup.h | 5 +- userspace/libsinsp/sinsp_cycledumper.cpp | 173 +- userspace/libsinsp/sinsp_cycledumper.h | 173 +- userspace/libsinsp/sinsp_debug/CMakeLists.txt | 33 +- .../libsinsp/sinsp_debug/sinsp_debug.cpp | 102 +- userspace/libsinsp/sinsp_errno.h | 280 +- userspace/libsinsp/sinsp_exception.h | 11 +- userspace/libsinsp/sinsp_external_processor.h | 9 +- .../libsinsp/sinsp_filter_transformer.cpp | 347 +- userspace/libsinsp/sinsp_filter_transformer.h | 38 +- userspace/libsinsp/sinsp_filtercheck.cpp | 1459 ++++----- userspace/libsinsp/sinsp_filtercheck.h | 96 +- .../libsinsp/sinsp_filtercheck_container.cpp | 571 ++-- .../libsinsp/sinsp_filtercheck_container.h | 10 +- .../libsinsp/sinsp_filtercheck_event.cpp | 2235 +++++++------ userspace/libsinsp/sinsp_filtercheck_event.h | 25 +- .../libsinsp/sinsp_filtercheck_evtin.cpp | 337 +- userspace/libsinsp/sinsp_filtercheck_evtin.h | 10 +- userspace/libsinsp/sinsp_filtercheck_fd.cpp | 2395 +++++++------- userspace/libsinsp/sinsp_filtercheck_fd.h | 31 +- .../libsinsp/sinsp_filtercheck_fdlist.cpp | 247 +- userspace/libsinsp/sinsp_filtercheck_fdlist.h | 6 +- .../libsinsp/sinsp_filtercheck_fspath.cpp | 374 +-- userspace/libsinsp/sinsp_filtercheck_fspath.h | 24 +- .../libsinsp/sinsp_filtercheck_gen_event.cpp | 249 +- .../libsinsp/sinsp_filtercheck_gen_event.h | 6 +- .../libsinsp/sinsp_filtercheck_group.cpp | 54 +- userspace/libsinsp/sinsp_filtercheck_group.h | 7 +- userspace/libsinsp/sinsp_filtercheck_k8s.cpp | 479 ++- userspace/libsinsp/sinsp_filtercheck_k8s.h | 13 +- .../libsinsp/sinsp_filtercheck_mesos.cpp | 156 +- userspace/libsinsp/sinsp_filtercheck_mesos.h | 10 +- .../libsinsp/sinsp_filtercheck_rawstring.cpp | 31 +- .../libsinsp/sinsp_filtercheck_rawstring.h | 7 +- .../libsinsp/sinsp_filtercheck_reference.cpp | 325 +- .../libsinsp/sinsp_filtercheck_reference.h | 24 +- .../libsinsp/sinsp_filtercheck_syslog.cpp | 90 +- userspace/libsinsp/sinsp_filtercheck_syslog.h | 6 +- .../libsinsp/sinsp_filtercheck_thread.cpp | 2697 ++++++++------- userspace/libsinsp/sinsp_filtercheck_thread.h | 25 +- .../libsinsp/sinsp_filtercheck_tracer.cpp | 255 +- userspace/libsinsp/sinsp_filtercheck_tracer.h | 14 +- userspace/libsinsp/sinsp_filtercheck_user.cpp | 94 +- userspace/libsinsp/sinsp_filtercheck_user.h | 6 +- .../libsinsp/sinsp_filtercheck_utils.cpp | 40 +- userspace/libsinsp/sinsp_filtercheck_utils.h | 6 +- userspace/libsinsp/sinsp_inet.h | 4 +- userspace/libsinsp/sinsp_observer.h | 33 +- userspace/libsinsp/sinsp_public.h | 6 +- userspace/libsinsp/sinsp_signal.h | 70 +- userspace/libsinsp/sinsp_suppress.cpp | 71 +- userspace/libsinsp/sinsp_suppress.h | 8 +- userspace/libsinsp/sinsp_syslog.cpp | 85 +- userspace/libsinsp/sinsp_syslog.h | 37 +- userspace/libsinsp/state/dynamic_struct.h | 847 +++-- userspace/libsinsp/state/static_struct.h | 437 ++- userspace/libsinsp/state/table.h | 334 +- userspace/libsinsp/state/table_adapters.h | 148 +- userspace/libsinsp/state/table_registry.h | 140 +- userspace/libsinsp/state/type_info.h | 282 +- userspace/libsinsp/test/CMakeLists.txt | 103 +- userspace/libsinsp/test/ast_exprs.ut.cpp | 6 +- .../test/async_key_value_source.ut.cpp | 229 +- .../libsinsp/test/cgroup_list_counter.ut.cpp | 20 +- userspace/libsinsp/test/classes/sinsp.cpp | 3 +- .../test/classes/sinsp_thread_manager.cpp | 42 +- .../test/classes/sinsp_threadinfo.cpp | 25 +- .../test/classes/thread_group_info.cpp | 6 +- userspace/libsinsp/test/classes/versions.cpp | 102 +- .../container_engine/container_cache.ut.cpp | 74 +- .../container_image_splitting.ut.cpp | 113 +- .../container_engine/container_info.ut.cpp | 30 +- .../container_parser_cri_containerd.ut.cpp | 387 ++- .../container_parser_cri_crio.ut.cpp | 402 ++- .../test/container_engine/cri_settings.ut.cpp | 16 +- userspace/libsinsp/test/dns_manager.ut.cpp | 17 +- userspace/libsinsp/test/eventformatter.ut.cpp | 139 +- userspace/libsinsp/test/events_evt.ut.cpp | 91 +- userspace/libsinsp/test/events_file.ut.cpp | 331 +- userspace/libsinsp/test/events_fspath.ut.cpp | 876 +++-- .../libsinsp/test/events_injection.ut.cpp | 59 +- userspace/libsinsp/test/events_net.ut.cpp | 527 ++- userspace/libsinsp/test/events_param.ut.cpp | 248 +- userspace/libsinsp/test/events_plugin.ut.cpp | 116 +- userspace/libsinsp/test/events_proc.ut.cpp | 901 ++++- userspace/libsinsp/test/events_user.ut.cpp | 8 +- .../libsinsp/test/external_processor.ut.cpp | 6 +- .../libsinsp/test/filter_compiler.ut.cpp | 316 +- .../libsinsp/test/filter_escaping.ut.cpp | 37 +- .../libsinsp/test/filter_op_bcontains.ut.cpp | 10 +- .../libsinsp/test/filter_op_contains.ut.cpp | 14 +- .../test/filter_op_net_compare.ut.cpp | 73 +- .../test/filter_op_numeric_compare.ut.cpp | 25 +- .../libsinsp/test/filter_op_pmatch.ut.cpp | 15 +- userspace/libsinsp/test/filter_parser.ut.cpp | 395 +-- .../libsinsp/test/filter_ppm_codes.ut.cpp | 574 ++-- .../libsinsp/test/filter_transformer.ut.cpp | 505 ++- .../libsinsp/test/filtercheck_has_args.ut.cpp | 39 +- userspace/libsinsp/test/filterchecks/evt.cpp | 111 +- userspace/libsinsp/test/filterchecks/fd.cpp | 41 +- userspace/libsinsp/test/filterchecks/k8s.cpp | 50 +- userspace/libsinsp/test/filterchecks/mock.cpp | 230 +- userspace/libsinsp/test/filterchecks/proc.cpp | 161 +- userspace/libsinsp/test/gvisor_config.ut.cpp | 6 +- .../test/helpers/scap_file_helpers.cpp | 23 +- .../libsinsp/test/helpers/scap_file_helpers.h | 5 +- .../test/helpers/scoped_file_descriptor.cpp | 17 +- .../test/helpers/scoped_file_descriptor.h | 6 +- .../libsinsp/test/helpers/scoped_pipe.cpp | 15 +- userspace/libsinsp/test/helpers/scoped_pipe.h | 6 +- .../libsinsp/test/helpers/threads_helpers.h | 545 ++-- userspace/libsinsp/test/ifinfo.ut.cpp | 151 +- .../libsinsp/test/mpsc_priority_queue.ut.cpp | 318 +- .../libsinsp/test/parsers/parse_clone.cpp | 128 +- .../libsinsp/test/parsers/parse_connect.cpp | 41 +- .../libsinsp/test/parsers/parse_execve.cpp | 83 +- .../libsinsp/test/parsers/parse_prctl.cpp | 93 +- .../libsinsp/test/parsers/parse_proc_exit.cpp | 24 +- .../libsinsp/test/parsers/parse_setregid.cpp | 23 +- .../libsinsp/test/parsers/parse_setreuid.cpp | 23 +- userspace/libsinsp/test/plugin_manager.ut.cpp | 34 +- userspace/libsinsp/test/plugins.ut.cpp | 436 ++- userspace/libsinsp/test/plugins/metrics.cpp | 144 +- .../libsinsp/test/plugins/plugin_extract.cpp | 218 +- .../libsinsp/test/plugins/plugin_source.cpp | 175 +- userspace/libsinsp/test/plugins/routines.cpp | 206 +- .../libsinsp/test/plugins/sample_table.h | 538 ++- .../libsinsp/test/plugins/syscall_async.cpp | 264 +- .../libsinsp/test/plugins/syscall_extract.cpp | 565 ++-- .../libsinsp/test/plugins/syscall_parse.cpp | 397 ++- .../libsinsp/test/plugins/syscall_source.cpp | 183 +- .../test/plugins/syscall_subtables.cpp | 165 +- .../test/plugins/syscall_subtables_array.cpp | 155 +- .../libsinsp/test/plugins/syscall_tables.cpp | 478 +-- .../libsinsp/test/ppm_api_version.ut.cpp | 6 +- userspace/libsinsp/test/prefix_search.ut.cpp | 28 +- userspace/libsinsp/test/procfs_utils.ut.cpp | 7 +- .../test/public_sinsp_API/event_related.cpp | 11 +- .../test/public_sinsp_API/events_set.cpp | 266 +- .../public_sinsp_API/interesting_syscalls.cpp | 276 +- .../test/public_sinsp_API/ppm_sc_codes.cpp | 1081 +++--- .../test/public_sinsp_API/sinsp_logger.cpp | 129 +- .../scap_files/cycledumper/cycledumper.cpp | 74 +- .../scap_files/kexec_arm64/kexec_arm64.cpp | 28 +- .../test/scap_files/kexec_x86/kexec_x86.cpp | 40 +- userspace/libsinsp/test/sinsp_metrics.ut.cpp | 437 ++- userspace/libsinsp/test/sinsp_utils.ut.cpp | 37 +- .../libsinsp/test/sinsp_with_test_input.cpp | 458 ++- .../libsinsp/test/sinsp_with_test_input.h | 294 +- userspace/libsinsp/test/state.ut.cpp | 929 +++--- userspace/libsinsp/test/string_visitor.ut.cpp | 160 +- userspace/libsinsp/test/test_utils.cpp | 227 +- userspace/libsinsp/test/test_utils.h | 71 +- userspace/libsinsp/test/thread_pool.ut.cpp | 96 +- userspace/libsinsp/test/thread_table.ut.cpp | 125 +- userspace/libsinsp/test/token_bucket.ut.cpp | 21 +- userspace/libsinsp/test/user.ut.cpp | 35 +- userspace/libsinsp/thread_group_info.h | 49 +- userspace/libsinsp/thread_pool.h | 37 +- userspace/libsinsp/thread_pool_bs.cpp | 78 +- userspace/libsinsp/thread_pool_bs.h | 18 +- userspace/libsinsp/threadinfo.cpp | 1265 +++---- userspace/libsinsp/threadinfo.h | 639 ++-- userspace/libsinsp/token_bucket.cpp | 29 +- userspace/libsinsp/token_bucket.h | 3 +- userspace/libsinsp/tuples.cpp | 73 +- userspace/libsinsp/tuples.h | 88 +- userspace/libsinsp/user.cpp | 467 ++- userspace/libsinsp/user.h | 124 +- userspace/libsinsp/utils.cpp | 1020 +++--- userspace/libsinsp/utils.h | 165 +- userspace/libsinsp/value_parser.cpp | 401 ++- userspace/libsinsp/value_parser.h | 11 +- userspace/libsinsp/version.h | 97 +- userspace/plugin/plugin_api.h | 268 +- userspace/plugin/plugin_loader.c | 479 ++- userspace/plugin/plugin_loader.h | 28 +- userspace/plugin/plugin_types.h | 80 +- 1088 files changed, 66343 insertions(+), 70981 deletions(-) mode change 100755 => 100644 userspace/libsinsp/plugin.cpp mode change 100755 => 100644 userspace/libsinsp/plugin.h mode change 100755 => 100644 userspace/libsinsp/plugin_filtercheck.cpp mode change 100755 => 100644 userspace/libsinsp/plugin_filtercheck.h mode change 100755 => 100644 userspace/libsinsp/plugin_manager.h mode change 100755 => 100644 userspace/libsinsp/plugin_table_api.cpp mode change 100755 => 100644 userspace/libsinsp/version.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e7b29f0cd..03af22f2b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,33 +2,32 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -# Prior to doing anything, we make sure that we aren't trying to -# run cmake in-tree. +# Prior to doing anything, we make sure that we aren't trying to run cmake in-tree. if(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/CMakeLists.txt) - message(FATAL_ERROR - "Looks like you are trying to run CMake from the base source directory.\n" - "** RUNNING CMAKE FROM THE BASE DIRECTORY WILL NOT WORK **\n" - "To Fix:\n" - " 1. Remove the CMakeCache.txt file in this directory. ex: rm CMakeCache.txt\n" - " 2. Create a build directory from here. ex: mkdir build\n" - " 3. cd into that directory. ex: cd build\n" - " 4. Run cmake from the build directory. ex: cmake ..\n" - " 5. Run make from the build directory. ex: make\n" - "Full paste-able example:\n" - "( rm -f CMakeCache.txt; mkdir build; cd build; cmake ..; make )") + message( + FATAL_ERROR + "Looks like you are trying to run CMake from the base source directory.\n" + "** RUNNING CMAKE FROM THE BASE DIRECTORY WILL NOT WORK **\n" + "To Fix:\n" + " 1. Remove the CMakeCache.txt file in this directory. ex: rm CMakeCache.txt\n" + " 2. Create a build directory from here. ex: mkdir build\n" + " 3. cd into that directory. ex: cd build\n" + " 4. Run cmake from the build directory. ex: cmake ..\n" + " 5. Run make from the build directory. ex: make\n" + "Full paste-able example:\n" + "( rm -f CMakeCache.txt; mkdir build; cd build; cmake ..; make )" + ) endif() cmake_minimum_required(VERSION 3.12) @@ -38,8 +37,8 @@ if(POLICY CMP0042) cmake_policy(SET CMP0042 NEW) endif() -# Enable CMAKE_MSVC_RUNTIME_LIBRARY on Windows + CMake >= 3.15 and link -# with the static (MultiThreaded) CRT unless instructed otherwise. +# Enable CMAKE_MSVC_RUNTIME_LIBRARY on Windows + CMake >= 3.15 and link with the static +# (MultiThreaded) CRT unless instructed otherwise. if(NOT (CMAKE_MSVC_RUNTIME_LIBRARY OR BUILD_SHARED_LIBS)) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() @@ -54,9 +53,13 @@ endif() project(falcosecurity-libs) option(USE_BUNDLED_DEPS "Enable bundled dependencies instead of using the system ones" ON) -option(MINIMAL_BUILD "Produce a minimal build with only the essential features (no container metadata)" OFF) +option(MINIMAL_BUILD + "Produce a minimal build with only the essential features (no container metadata)" OFF +) option(MUSL_OPTIMIZED_BUILD "Enable if you want a musl optimized build" OFF) -option(USE_BUNDLED_DRIVER "Use the driver/ subdirectory in the build process (only available in Linux)" ON) +option(USE_BUNDLED_DRIVER + "Use the driver/ subdirectory in the build process (only available in Linux)" ON +) option(ENABLE_DRIVERS_TESTS "Enable driver tests (bpf, kernel module, modern bpf)" OFF) option(ENABLE_LIBSCAP_TESTS "Enable libscap unit tests" OFF) option(ENABLE_LIBSINSP_E2E_TESTS "Enable libsinsp e2e tests" OFF) @@ -76,8 +79,7 @@ endif() include(GNUInstallDirs) # Add path for custom CMake modules. -list(APPEND CMAKE_MODULE_PATH - "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") include(versions) @@ -113,7 +115,7 @@ if(CREATE_TEST_TARGETS) include(gtest) endif() -if (BUILD_SHARED_LIBS) +if(BUILD_SHARED_LIBS) get_shared_libs_versions(FALCOSECURITY_SHARED_LIBS_VERSION FALCOSECURITY_SHARED_LIBS_SOVERSION) message(STATUS "Shared library version: ${FALCOSECURITY_SHARED_LIBS_VERSION}") message(STATUS "Shared library soversion: ${FALCOSECURITY_SHARED_LIBS_SOVERSION}") @@ -123,12 +125,9 @@ include(libscap) include(libsinsp) if(CREATE_TEST_TARGETS) - # Add command to run all unit tests at once via the make system. - # This is preferred vs using ctest's add_test because it will build - # the code and output to stdout. - add_custom_target(run-unit-tests - COMMAND ${CMAKE_MAKE_PROGRAM} run-unit-test-libsinsp - ) + # Add command to run all unit tests at once via the make system. This is preferred vs using + # ctest's add_test because it will build the code and output to stdout. + add_custom_target(run-unit-tests COMMAND ${CMAKE_MAKE_PROGRAM} run-unit-test-libsinsp) add_subdirectory(test/e2e) @@ -155,4 +154,4 @@ endif() option(ENABLE_BENCHMARKS "Enable Benchmarks" OFF) if(ENABLE_BENCHMARKS) add_subdirectory(benchmark) -endif() \ No newline at end of file +endif() diff --git a/CMakeListsGtestInclude.cmake b/CMakeListsGtestInclude.cmake index 01f6e5ed26..565dcf6a22 100644 --- a/CMakeListsGtestInclude.cmake +++ b/CMakeListsGtestInclude.cmake @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # cmake_minimum_required(VERSION 3.12) @@ -20,14 +18,15 @@ cmake_minimum_required(VERSION 3.12) project(googletest-download NONE) include(ExternalProject) -ExternalProject_Add(googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG "release-1.12.1" - SOURCE_DIR "${PROJECT_BINARY_DIR}/googletest-src" - BINARY_DIR "${PROJECT_BINARY_DIR}/googletest-build" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - UPDATE_COMMAND "" - TEST_COMMAND "" +ExternalProject_Add( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG "release-1.12.1" + SOURCE_DIR "${PROJECT_BINARY_DIR}/googletest-src" + BINARY_DIR "${PROJECT_BINARY_DIR}/googletest-build" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + UPDATE_COMMAND "" + TEST_COMMAND "" ) diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt index 37ce498970..e8c3279ccc 100644 --- a/benchmark/CMakeLists.txt +++ b/benchmark/CMakeLists.txt @@ -2,16 +2,14 @@ # # Copyright (C) 2024 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under # the License. # diff --git a/benchmark/libsinsp/utils.cpp b/benchmark/libsinsp/utils.cpp index 3837c1a8e9..dce35b44d9 100644 --- a/benchmark/libsinsp/utils.cpp +++ b/benchmark/libsinsp/utils.cpp @@ -19,56 +19,48 @@ limitations under the License. #include #include -static void BM_sinsp_split(benchmark::State& state) -{ +static void BM_sinsp_split(benchmark::State& state) { std::string str = "hello,world,"; - for(auto _ : state) - { + for(auto _ : state) { sinsp_split(str, ','); } } BENCHMARK(BM_sinsp_split); -static void BM_sinsp_concatenate_paths_relative_path(benchmark::State& state) -{ +static void BM_sinsp_concatenate_paths_relative_path(benchmark::State& state) { std::string path1 = "/tmp/"; std::string path2 = "foo/bar"; - for(auto _ : state) - { + for(auto _ : state) { sinsp_utils::concatenate_paths(path1, path2); } } BENCHMARK(BM_sinsp_concatenate_paths_relative_path); -static void BM_sinsp_concatenate_paths_empty_path(benchmark::State& state) -{ +static void BM_sinsp_concatenate_paths_empty_path(benchmark::State& state) { std::string path1 = "/tmp/"; std::string path2 = ""; - for(auto _ : state) - { + for(auto _ : state) { sinsp_utils::concatenate_paths(path1, path2); } } BENCHMARK(BM_sinsp_concatenate_paths_empty_path); -static void BM_sinsp_concatenate_paths_absolute_path(benchmark::State& state) -{ +static void BM_sinsp_concatenate_paths_absolute_path(benchmark::State& state) { std::string path1 = "/tmp/"; std::string path2 = "/foo/bar"; - for(auto _ : state) - { + for(auto _ : state) { sinsp_utils::concatenate_paths(path1, path2); } } BENCHMARK(BM_sinsp_concatenate_paths_absolute_path); -static void BM_sinsp_split_container_image(benchmark::State& state) -{ - std::string container_image = "localhost:12345/library/busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"; +static void BM_sinsp_split_container_image(benchmark::State& state) { + std::string container_image = + "localhost:12345/library/" + "busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"; std::string hostname, port, name, tag, digest; - for(auto _ : state) - { + for(auto _ : state) { sinsp_utils::split_container_image(container_image, hostname, port, name, tag, digest); } } -BENCHMARK(BM_sinsp_split_container_image); \ No newline at end of file +BENCHMARK(BM_sinsp_split_container_image); diff --git a/benchmark/main.cpp b/benchmark/main.cpp index 8660d26f29..0c9b9320a7 100644 --- a/benchmark/main.cpp +++ b/benchmark/main.cpp @@ -18,4 +18,4 @@ limitations under the License. #include -BENCHMARK_MAIN(); \ No newline at end of file +BENCHMARK_MAIN(); diff --git a/cmake/modules/CompilerFlags.cmake b/cmake/modules/CompilerFlags.cmake index 619874aaf7..8247486806 100644 --- a/cmake/modules/CompilerFlags.cmake +++ b/cmake/modules/CompilerFlags.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(BUILD_WARNINGS_AS_ERRORS "Enable building with -Wextra -Werror flags") @@ -34,7 +35,7 @@ if(NOT MSVC) set(FALCOSECURITY_LIBS_RELEASE_FLAGS "-O3 -fno-strict-aliasing -DNDEBUG") if(MINIMAL_BUILD) - set(FALCOSECURITY_LIBS_COMMON_FLAGS "${FALCOSECURITY_LIBS_COMMON_FLAGS} -DMINIMAL_BUILD") + set(FALCOSECURITY_LIBS_COMMON_FLAGS "${FALCOSECURITY_LIBS_COMMON_FLAGS} -DMINIMAL_BUILD") endif() if(MUSL_OPTIMIZED_BUILD) @@ -43,47 +44,72 @@ if(NOT MSVC) if(BUILD_WARNINGS_AS_ERRORS) set(CMAKE_COMPILE_WARNING_AS_ERROR ON) - set(CMAKE_SUPPRESSED_WARNINGS "-Wno-unused-parameter -Wno-sign-compare -Wno-implicit-fallthrough -Wno-format-truncation") - if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - # Clang needs these for suppressing these warnings: - # - C++20 array designators used with C++17 - # - C99 array designators used in C++ - # - avoid complaining about the option above `-Wno-format-truncation` - set(CMAKE_SUPPRESSED_WARNINGS "${CMAKE_SUPPRESSED_WARNINGS} -Wno-c++20-designator -Wno-c99-designator -Wno-unknown-warning-option") + set(CMAKE_SUPPRESSED_WARNINGS + "-Wno-unused-parameter -Wno-sign-compare -Wno-implicit-fallthrough -Wno-format-truncation" + ) + if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + # Clang needs these for suppressing these warnings: - C++20 array designators used with + # C++17 - C99 array designators used in C++ - avoid complaining about the option above + # `-Wno-format-truncation` + set(CMAKE_SUPPRESSED_WARNINGS + "${CMAKE_SUPPRESSED_WARNINGS} -Wno-c++20-designator -Wno-c99-designator -Wno-unknown-warning-option" + ) endif() - set(FALCOSECURITY_LIBS_COMMON_FLAGS "${FALCOSECURITY_LIBS_COMMON_FLAGS} -Werror -Wextra ${CMAKE_SUPPRESSED_WARNINGS}") + set(FALCOSECURITY_LIBS_COMMON_FLAGS + "${FALCOSECURITY_LIBS_COMMON_FLAGS} -Werror -Wextra ${CMAKE_SUPPRESSED_WARNINGS}" + ) endif() if(USE_ASAN) - set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fsanitize=address") - set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS};-fsanitize=address;-lpthread") + set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fsanitize=address" + ) + set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS};-fsanitize=address;-lpthread" + ) endif() if(USE_UBSAN) - set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fsanitize=undefined") - set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS};-fsanitize=undefined") + set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fsanitize=undefined" + ) + set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS};-fsanitize=undefined" + ) if(UBSAN_HALT_ON_ERROR) - set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fno-sanitize-recover=undefined") + set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fno-sanitize-recover=undefined" + ) endif() endif() if(USE_TSAN) - set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fsanitize=thread") - set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS};-fsanitize=thread") + set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};-fsanitize=thread" + ) + set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS};-fsanitize=thread" + ) endif() if(ENABLE_COVERAGE) - set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};--coverage") - set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};--coverage") + set(FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};--coverage" + ) + set(FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS + "${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS};--coverage" + ) endif() if(ENABLE_THREAD_POOL) - set(FALCOSECURITY_LIBS_COMMON_FLAGS "${FALCOSECURITY_LIBS_COMMON_FLAGS} -DENABLE_THREAD_POOL") + set(FALCOSECURITY_LIBS_COMMON_FLAGS + "${FALCOSECURITY_LIBS_COMMON_FLAGS} -DENABLE_THREAD_POOL" + ) endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${FALCOSECURITY_LIBS_COMMON_FLAGS}") - # we need also `-std=c++17` here beacuse `set(CMAKE_CXX_STANDARD 17)` is not enough to enforce c++17 - # with some Cmake versions: https://github.com/falcosecurity/libs/pull/950 + # we need also `-std=c++17` here beacuse `set(CMAKE_CXX_STANDARD 17)` is not enough to enforce + # c++17 with some Cmake versions: https://github.com/falcosecurity/libs/pull/950 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FALCOSECURITY_LIBS_COMMON_FLAGS} -std=c++17") set(CMAKE_C_FLAGS_DEBUG "${FALCOSECURITY_LIBS_DEBUG_FLAGS}") @@ -97,7 +123,9 @@ if(NOT MSVC) else() # MSVC set(MINIMAL_BUILD ON) - set(FALCOSECURITY_LIBS_COMMON_FLAGS "-D_CRT_SECURE_NO_WARNINGS -DWIN32 -DMINIMAL_BUILD /EHsc /W3 /Zi /std:c++17") + set(FALCOSECURITY_LIBS_COMMON_FLAGS + "-D_CRT_SECURE_NO_WARNINGS -DWIN32 -DMINIMAL_BUILD /EHsc /W3 /Zi /std:c++17" + ) if(CMAKE_VERSION VERSION_LESS 3.15.0) set(FALCOSECURITY_LIBS_DEBUG_FLAGS "/MTd /Od") set(FALCOSECURITY_LIBS_RELEASE_FLAGS "/MT") @@ -115,12 +143,9 @@ else() # MSVC set(CMAKE_C_FLAGS_RELEASE "${FALCOSECURITY_LIBS_RELEASE_FLAGS}") set(CMAKE_CXX_FLAGS_RELEASE "${FALCOSECURITY_LIBS_RELEASE_FLAGS}") - # "_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR" enables a - # workaround for windows GH runner issue, see - # https://github.com/actions/runner-images/issues/10004 + # "_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR" enables a workaround for windows GH runner issue, see + # https://github.com/actions/runner-images/issues/10004 add_compile_definitions( - _HAS_STD_BYTE=0 - WIN32_LEAN_AND_MEAN - _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR + _HAS_STD_BYTE=0 WIN32_LEAN_AND_MEAN _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR ) endif() diff --git a/cmake/modules/FindMakedev.cmake b/cmake/modules/FindMakedev.cmake index db1b6ba41e..b5bd325f6d 100644 --- a/cmake/modules/FindMakedev.cmake +++ b/cmake/modules/FindMakedev.cmake @@ -2,43 +2,33 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -# This module is used to understand where the makedev function -# is defined in the glibc in use. -# see 'man 3 makedev' -# Usage: -# In your CMakeLists.txt -# include(FindMakedev) -# -# In your source code: -# -# #if HAVE_SYS_MKDEV_H -# #include -# #endif -# #ifdef HAVE_SYS_SYSMACROS_H -# #include -# #endif +# This module is used to understand where the makedev function is defined in the glibc in use. see +# 'man 3 makedev' Usage: In your CMakeLists.txt include(FindMakedev) +# +# In your source code: +# +# #if HAVE_SYS_MKDEV_H #include #endif #ifdef HAVE_SYS_SYSMACROS_H #include +# #endif # include(${CMAKE_ROOT}/Modules/CheckIncludeFile.cmake) check_include_file("sys/mkdev.h" HAVE_SYS_MKDEV_H) check_include_file("sys/sysmacros.h" HAVE_SYS_SYSMACROS_H) -if (HAVE_SYS_MKDEV_H) - add_definitions(-DHAVE_SYS_MKDEV_H) +if(HAVE_SYS_MKDEV_H) + add_definitions(-DHAVE_SYS_MKDEV_H) endif() -if (HAVE_SYS_SYSMACROS_H) - add_definitions(-DHAVE_SYS_SYSMACROS_H) +if(HAVE_SYS_SYSMACROS_H) + add_definitions(-DHAVE_SYS_SYSMACROS_H) endif() diff --git a/cmake/modules/Findbs_threadpool.cmake b/cmake/modules/Findbs_threadpool.cmake index 6d9bfd3605..314505a4ee 100644 --- a/cmake/modules/Findbs_threadpool.cmake +++ b/cmake/modules/Findbs_threadpool.cmake @@ -2,30 +2,28 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # find_path(BS_THREADPOOL_INCLUDE NAMES BS_thread_pool.hpp) -if (BS_THREADPOOL_INCLUDE) - if (NOT bs_threadpool_FIND_QUIETLY) - message(STATUS "Found bs_threadpool: include: ${BS_THREADPOOL_INCLUDE}.") - endif() +if(BS_THREADPOOL_INCLUDE) + if(NOT bs_threadpool_FIND_QUIETLY) + message(STATUS "Found bs_threadpool: include: ${BS_THREADPOOL_INCLUDE}.") + endif() else() - if (bs_threadpool_FIND_REQUIRED) - message(FATAL_ERROR "Required component bs_threadpool missing.") - endif() - if (NOT bs_threadpool_FIND_QUIETLY) - message(WARNING "bs_threadpool not found.") - endif() -endif() \ No newline at end of file + if(bs_threadpool_FIND_REQUIRED) + message(FATAL_ERROR "Required component bs_threadpool missing.") + endif() + if(NOT bs_threadpool_FIND_QUIETLY) + message(WARNING "bs_threadpool not found.") + endif() +endif() diff --git a/cmake/modules/Findvalijson.cmake b/cmake/modules/Findvalijson.cmake index 0fdefdc4a1..5c4a03f90b 100644 --- a/cmake/modules/Findvalijson.cmake +++ b/cmake/modules/Findvalijson.cmake @@ -2,35 +2,32 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -# This module is used to find where the valijson headers are installed -# on the system. This is required up to v0.6, since package config -# files are not provided. This is fixed in master though, and this -# file shall be automatically ignored for later versions. +# This module is used to find where the valijson headers are installed on the system. This is +# required up to v0.6, since package config files are not provided. This is fixed in master though, +# and this file shall be automatically ignored for later versions. find_path(VALIJSON_INCLUDE NAMES valijson/validator.hpp validator.hpp) -if (VALIJSON_INCLUDE) - if (NOT valijson_FIND_QUIETLY) - message(STATUS "Found valijson: include: ${VALIJSON_INCLUDE}.") - endif() +if(VALIJSON_INCLUDE) + if(NOT valijson_FIND_QUIETLY) + message(STATUS "Found valijson: include: ${VALIJSON_INCLUDE}.") + endif() else() - if (valijson_FIND_REQUIRED) - message(FATAL_ERROR "Required component valijson missing.") - endif() - if (NOT valijson_FIND_QUIETLY) - message(WARNING "Valijson not found.") - endif() + if(valijson_FIND_REQUIRED) + message(FATAL_ERROR "Required component valijson missing.") + endif() + if(NOT valijson_FIND_QUIETLY) + message(WARNING "Valijson not found.") + endif() endif() diff --git a/cmake/modules/GetVersionFromGit.cmake b/cmake/modules/GetVersionFromGit.cmake index bfe487c41b..8a0210e629 100644 --- a/cmake/modules/GetVersionFromGit.cmake +++ b/cmake/modules/GetVersionFromGit.cmake @@ -2,191 +2,225 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # if(_falcosecurity_get_version_from_git) - return() + return() endif() set(_falcosecurity_get_version_from_git TRUE) if(NOT FALCOSECURITY_RELEASE_BRANCH_REGEX) - set(FALCOSECURITY_RELEASE_BRANCH_REGEX "^release/") + set(FALCOSECURITY_RELEASE_BRANCH_REGEX "^release/") endif() function(_falcosecurity_execute_git _out) - if(NOT GIT_FOUND) - find_package(Git QUIET) - endif() - - execute_process(COMMAND - "${GIT_EXECUTABLE}" - ${ARGN} - WORKING_DIRECTORY - "${CMAKE_CURRENT_SOURCE_DIR}" - RESULT_VARIABLE - res - OUTPUT_VARIABLE - out - ERROR_QUIET - OUTPUT_STRIP_TRAILING_WHITESPACE) - - if(NOT res EQUAL 0) - set(out "") - endif() - - set(${_out} "${out}" PARENT_SCOPE) + if(NOT GIT_FOUND) + find_package(Git QUIET) + endif() + + execute_process( + COMMAND "${GIT_EXECUTABLE}" ${ARGN} + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE res + OUTPUT_VARIABLE out + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + if(NOT res EQUAL 0) + set(out "") + endif() + + set(${_out} + "${out}" + PARENT_SCOPE + ) endfunction() function(_falcosecurity_extract_version version_str x y z found) - string(REGEX MATCH "^([0-9]+)\\.([0-9]+)\\.([0-9]+)" match_result ${version_str}) - - if(match_result) - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\1" x_val ${match_result}) - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\2" y_val ${match_result}) - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\3" z_val ${match_result}) - set(${x} ${x_val} PARENT_SCOPE) - set(${y} ${y_val} PARENT_SCOPE) - set(${z} ${z_val} PARENT_SCOPE) - set(${found} TRUE PARENT_SCOPE) - else() - set(${found} FALSE PARENT_SCOPE) - endif() + string(REGEX MATCH "^([0-9]+)\\.([0-9]+)\\.([0-9]+)" match_result ${version_str}) + + if(match_result) + string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\1" x_val ${match_result}) + string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\2" y_val ${match_result}) + string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\3" z_val ${match_result}) + set(${x} + ${x_val} + PARENT_SCOPE + ) + set(${y} + ${y_val} + PARENT_SCOPE + ) + set(${z} + ${z_val} + PARENT_SCOPE + ) + set(${found} + TRUE + PARENT_SCOPE + ) + else() + set(${found} + FALSE + PARENT_SCOPE + ) + endif() endfunction() # get_version_from_git() provides a basic implementation of the Falco versioning convention. # -# The primary convention is that all version numbers should be a SemVer2.0-compatible string. -# The version number for the development build must follow a pre-release version pattern. -# To accomplish this, we use Git as the primary data source to construct the version number -# automatically. In this regard, the convention assumes that: -# any Git tag represents an officially released build, -# and each Git commit could potentially be a development build. +# The primary convention is that all version numbers should be a SemVer2.0-compatible string. The +# version number for the development build must follow a pre-release version pattern. To accomplish +# this, we use Git as the primary data source to construct the version number automatically. In this +# regard, the convention assumes that: any Git tag represents an officially released build, and each +# Git commit could potentially be a development build. # -# With those assumptions, the build system will return a version number based on one of -# the following cases: +# With those assumptions, the build system will return a version number based on one of the +# following cases: # -# - If the current Git checkout points to an exact Git tag, -# we assume it is an officially released version (either a release or a pre-release). +# * If the current Git checkout points to an exact Git tag, we assume it is an officially released +# version (either a release or a pre-release). # -# - If we are in a release branch (with the suffix `release/`), -# we assume that each commit (i.e., each development build) represents a potential new patch version. +# * If we are in a release branch (with the suffix `release/`), we assume that each commit (i.e., +# each development build) represents a potential new patch version. # -# - If we are in any other branch, -# we assume that each commit (i.e., each development build) represents a potential new minor version. +# * If we are in any other branch, we assume that each commit (i.e., each development build) +# represents a potential new minor version. # -# - In any other case (for example, if there's no git information available), -# version `0.0.0` will be returned as a fallback. +# * In any other case (for example, if there's no git information available), version `0.0.0` will +# be returned as a fallback. # # For the officially released versions, we assume the Git tag will carry on the correct information, # so we return it as-is. # -# For development versions, the string is built as follows: -# `..-+[suffix]` -# Where: -# - `..` represents the next version number, reflecting either a patch for release branches -# or a minor version for development branches. -# - `` is the number of commits ahead from either: -# - the latest tag on the branch, for release branches; or -# - the closest common ancestor with the branch holding the latest tagged version, -# for development branches. -# - `` refers to the first 7 digits of the commit hash. -# - `[suffix]` the value of `match_suffix`, if any. +# For development versions, the string is built as follows: `..-+[suffix]` +# Where: - `..` represents the next version number, reflecting either a patch for release +# branches or a minor version for development branches. - `` is the number of commits ahead +# from either: - the latest tag on the branch, for release branches; or - the closest common +# ancestor with the branch holding the latest tagged version, for development branches. - `` +# refers to the first 7 digits of the commit hash. - `[suffix]` the value of `match_suffix`, if any. # Note: all non-alphanumerics will be converted to hyphens. # -# # This function sets the resulting version string to a variable in the parent scope. # -# Arguments: -# - _var Variable to store the resulting version string. -# - match_suffix Only consider Git references with this suffix. -# - exclude_suffix Ignore Git references with this suffix. +# Arguments: - _var Variable to store the resulting version string. - match_suffix Only +# consider Git references with this suffix. - exclude_suffix Ignore Git references with this +# suffix. function(get_version_from_git _var match_suffix exclude_suffix) - # Release version - # Try to obtain the exact git tag - if(exclude_suffix) - _falcosecurity_execute_git(tag describe --tags --exact-match --match "*${match_suffix}" --exclude "*${exclude_suffix}" HEAD) - else() - _falcosecurity_execute_git(tag describe --tags --exact-match --match "*${match_suffix}" HEAD) - endif() - - if(tag) - # A tag has been found: use it as the libs version - set(${_var} - "${tag}" - PARENT_SCOPE) - return() - endif() - - # Otherwise, we are on a dev version - _falcosecurity_execute_git(current_hash rev-parse HEAD) - _falcosecurity_execute_git(current_hash_short rev-parse --short=7 HEAD) - _falcosecurity_execute_git(current_branch rev-parse --abbrev-ref HEAD) - - set(dev_version "0.0.0") - - # dev version / in a `release/M.m.x` branch - if(current_branch MATCHES "${FALCOSECURITY_RELEASE_BRANCH_REGEX}") - # get the latest tag on the release branch - set(_options --match "*.*.*${match_suffix}") - - if(exclude_suffix) - set(_options ${_options} --exclude "*${exclude_suffix}") - endif() - - _falcosecurity_execute_git(tag describe --tags ${_options} --abbrev=0 "${current_branch}") - - if(tag) - _falcosecurity_extract_version("${tag}" x y z match_found) - - if(match_found) - math(EXPR z_plus_one "${z} + 1") - set(dev_version "${x}.${y}.${z_plus_one}") - endif() - endif() - endif() - - # dev version / all other cases (and fallback) - if(dev_version MATCHES "0.0.0") - # get the latest tag that exactly matches a version number, sorted by version number in descending order - _falcosecurity_execute_git(tag for-each-ref --count=1 --sort=-version:refname --format "%(refname:short)" refs/tags/[0-9]*.[0-9]*.[0-9]${match_suffix}) - - if(tag) - _falcosecurity_extract_version("${tag}" x y z match_found) - - if(match_found) - math(EXPR y_plus_one "${y} + 1") - set(dev_version "${x}.${y_plus_one}.0") - endif() - endif() - endif() - - # complete dev version with count and hash - if(NOT dev_version MATCHES "0.0.0") - _falcosecurity_execute_git(tag_commit rev-list -n 1 "${tag}") - _falcosecurity_execute_git(tag_common_ancestor merge-base "${current_hash}" "${tag_commit}") - _falcosecurity_execute_git(commits_count rev-list --count "${tag_common_ancestor}..${current_hash}") - - set(dev_version "${dev_version}-${commits_count}+${current_hash_short}") - - if(match_suffix) - string(REGEX REPLACE "[^0-9A-Za-z-]" "-" suffix "${match_suffix}") - set(dev_version "${dev_version}${suffix}") - endif() - endif() - - set(${_var} - "${dev_version}" - PARENT_SCOPE) + # Release version Try to obtain the exact git tag + if(exclude_suffix) + _falcosecurity_execute_git( + tag + describe + --tags + --exact-match + --match + "*${match_suffix}" + --exclude + "*${exclude_suffix}" + HEAD + ) + else() + _falcosecurity_execute_git( + tag + describe + --tags + --exact-match + --match + "*${match_suffix}" + HEAD + ) + endif() + + if(tag) + # A tag has been found: use it as the libs version + set(${_var} + "${tag}" + PARENT_SCOPE + ) + return() + endif() + + # Otherwise, we are on a dev version + _falcosecurity_execute_git(current_hash rev-parse HEAD) + _falcosecurity_execute_git(current_hash_short rev-parse --short=7 HEAD) + _falcosecurity_execute_git(current_branch rev-parse --abbrev-ref HEAD) + + set(dev_version "0.0.0") + + # dev version / in a `release/M.m.x` branch + if(current_branch MATCHES "${FALCOSECURITY_RELEASE_BRANCH_REGEX}") + # get the latest tag on the release branch + set(_options --match "*.*.*${match_suffix}") + + if(exclude_suffix) + set(_options ${_options} --exclude "*${exclude_suffix}") + endif() + + _falcosecurity_execute_git(tag describe --tags ${_options} --abbrev=0 "${current_branch}") + + if(tag) + _falcosecurity_extract_version("${tag}" x y z match_found) + + if(match_found) + math(EXPR z_plus_one "${z} + 1") + set(dev_version "${x}.${y}.${z_plus_one}") + endif() + endif() + endif() + + # dev version / all other cases (and fallback) + if(dev_version MATCHES "0.0.0") + # get the latest tag that exactly matches a version number, sorted by version number in + # descending order + _falcosecurity_execute_git( + tag + for-each-ref + --count=1 + --sort=-version:refname + --format + "%(refname:short)" + refs/tags/[0-9]*.[0-9]*.[0-9]${match_suffix} + ) + + if(tag) + _falcosecurity_extract_version("${tag}" x y z match_found) + + if(match_found) + math(EXPR y_plus_one "${y} + 1") + set(dev_version "${x}.${y_plus_one}.0") + endif() + endif() + endif() + + # complete dev version with count and hash + if(NOT dev_version MATCHES "0.0.0") + _falcosecurity_execute_git(tag_commit rev-list -n 1 "${tag}") + _falcosecurity_execute_git(tag_common_ancestor merge-base "${current_hash}" "${tag_commit}") + _falcosecurity_execute_git( + commits_count rev-list --count "${tag_common_ancestor}..${current_hash}" + ) + + set(dev_version "${dev_version}-${commits_count}+${current_hash_short}") + + if(match_suffix) + string(REGEX REPLACE "[^0-9A-Za-z-]" "-" suffix "${match_suffix}") + set(dev_version "${dev_version}${suffix}") + endif() + endif() + + set(${_var} + "${dev_version}" + PARENT_SCOPE + ) endfunction() diff --git a/cmake/modules/bs_threadpool.cmake b/cmake/modules/bs_threadpool.cmake index c493107a8e..f1204e1e03 100644 --- a/cmake/modules/bs_threadpool.cmake +++ b/cmake/modules/bs_threadpool.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2024 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # # @@ -28,17 +29,19 @@ else() message(STATUS "Using bundled bs_threadpool in '${BS_THREADPOOL_SRC}'") - ExternalProject_Add(bs_threadpool + ExternalProject_Add( + bs_threadpool PREFIX "${PROJECT_BINARY_DIR}/bs_threadpool-prefix" URL "https://github.com/bshoshany/thread-pool/archive/refs/tags/v4.1.0.tar.gz" URL_HASH "SHA256=be7abecbc420bb87919eeef729b13ff7c29d5ce547bdae284923296c695415bd" CONFIGURE_COMMAND "" BUILD_COMMAND "" - INSTALL_COMMAND "") + INSTALL_COMMAND "" + ) endif() if(NOT TARGET bs_threadpool) add_custom_target(bs_threadpool) endif() -include_directories("${BS_THREADPOOL_INCLUDE}") \ No newline at end of file +include_directories("${BS_THREADPOOL_INCLUDE}") diff --git a/cmake/modules/cares.cmake b/cmake/modules/cares.cmake index 3765367b19..c53e1b65c3 100644 --- a/cmake/modules/cares.cmake +++ b/cmake/modules/cares.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_CARES "Enable building of the bundled c-ares" ${USE_BUNDLED_DEPS}) @@ -27,8 +28,8 @@ elseif(NOT USE_BUNDLED_CARES) else() if(BUILD_SHARED_LIBS) set(CARES_LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) - set(CARES_CPPFLAGS ) - set(CARES_STATIC_OPTION ) + set(CARES_CPPFLAGS) + set(CARES_STATIC_OPTION) else() set(CARES_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) set(CARES_CPPFLAGS -DCARES_STATICLIB) @@ -41,25 +42,34 @@ else() if(NOT TARGET c-ares) if(NOT ENABLE_PIC) - set(CARES_PIC_OPTION ) + set(CARES_PIC_OPTION) else() set(CARES_PIC_OPTION "--with-pic=yes") endif() message(STATUS "Using bundled c-ares in '${CARES_SRC}'") - ExternalProject_Add(c-ares + ExternalProject_Add( + c-ares PREFIX "${PROJECT_BINARY_DIR}/c-ares-prefix" URL "https://github.com/c-ares/c-ares/releases/download/v1.30.0/c-ares-1.30.0.tar.gz" URL_HASH "SHA256=4fea312112021bcef081203b1ea020109842feb58cd8a36a3d3f7e0d8bc1138c" - CONFIGURE_COMMAND CPPFLAGS=${CARES_CPPFLAGS} ./configure ${CARES_STATIC_OPTION} ${CARES_PIC_OPTION} --prefix=${CARES_INSTALL_DIR} + CONFIGURE_COMMAND CPPFLAGS=${CARES_CPPFLAGS} ./configure ${CARES_STATIC_OPTION} + ${CARES_PIC_OPTION} --prefix=${CARES_INSTALL_DIR} BUILD_COMMAND make BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${CARES_INCLUDE} ${CARES_LIB} - INSTALL_COMMAND make install) - install(FILES "${CARES_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${CARES_INCLUDE}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + INSTALL_COMMAND make install + ) + install( + FILES "${CARES_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + DIRECTORY "${CARES_INCLUDE}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() endif() diff --git a/cmake/modules/compute_versions.cmake b/cmake/modules/compute_versions.cmake index 456dfc05a5..5b8ca90630 100644 --- a/cmake/modules/compute_versions.cmake +++ b/cmake/modules/compute_versions.cmake @@ -2,38 +2,50 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # # Computes API/SCHEMA major, minor, patch and git commit macro(compute_versions api_version_path schema_version_path) - - # API VERSION - file(STRINGS ${api_version_path} DRIVER_API_VERSION LIMIT_COUNT 1) - string(REGEX MATCHALL "[0-9]+" DRIVER_API_COMPONENTS "${DRIVER_API_VERSION}") - list(GET DRIVER_API_COMPONENTS 0 PPM_API_CURRENT_VERSION_MAJOR) - list(GET DRIVER_API_COMPONENTS 1 PPM_API_CURRENT_VERSION_MINOR) - list(GET DRIVER_API_COMPONENTS 2 PPM_API_CURRENT_VERSION_PATCH) - message(STATUS "Driver API version ${PPM_API_CURRENT_VERSION_MAJOR}.${PPM_API_CURRENT_VERSION_MINOR}.${PPM_API_CURRENT_VERSION_PATCH}") - # SCHEMA VERSION - file(STRINGS ${schema_version_path} DRIVER_SCHEMA_VERSION LIMIT_COUNT 1) - string(REGEX MATCHALL "[0-9]+" DRIVER_SCHEMA_COMPONENTS "${DRIVER_SCHEMA_VERSION}") - list(GET DRIVER_SCHEMA_COMPONENTS 0 PPM_SCHEMA_CURRENT_VERSION_MAJOR) - list(GET DRIVER_SCHEMA_COMPONENTS 1 PPM_SCHEMA_CURRENT_VERSION_MINOR) - list(GET DRIVER_SCHEMA_COMPONENTS 2 PPM_SCHEMA_CURRENT_VERSION_PATCH) - message(STATUS "Driver schema version ${PPM_SCHEMA_CURRENT_VERSION_MAJOR}.${PPM_SCHEMA_CURRENT_VERSION_MINOR}.${PPM_SCHEMA_CURRENT_VERSION_PATCH}") + # API VERSION + file(STRINGS ${api_version_path} DRIVER_API_VERSION LIMIT_COUNT 1) + string(REGEX MATCHALL "[0-9]+" DRIVER_API_COMPONENTS "${DRIVER_API_VERSION}") + list(GET DRIVER_API_COMPONENTS 0 PPM_API_CURRENT_VERSION_MAJOR) + list(GET DRIVER_API_COMPONENTS 1 PPM_API_CURRENT_VERSION_MINOR) + list(GET DRIVER_API_COMPONENTS 2 PPM_API_CURRENT_VERSION_PATCH) + message( + STATUS + "Driver API version ${PPM_API_CURRENT_VERSION_MAJOR}.${PPM_API_CURRENT_VERSION_MINOR}.${PPM_API_CURRENT_VERSION_PATCH}" + ) - # GIT COMMIT - if(NOT DEFINED GIT_COMMIT) - execute_process(COMMAND git rev-parse HEAD OUTPUT_VARIABLE GIT_COMMIT ERROR_QUIET WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - endif() - string(STRIP "${GIT_COMMIT}" GIT_COMMIT) + # SCHEMA VERSION + file(STRINGS ${schema_version_path} DRIVER_SCHEMA_VERSION LIMIT_COUNT 1) + string(REGEX MATCHALL "[0-9]+" DRIVER_SCHEMA_COMPONENTS "${DRIVER_SCHEMA_VERSION}") + list(GET DRIVER_SCHEMA_COMPONENTS 0 PPM_SCHEMA_CURRENT_VERSION_MAJOR) + list(GET DRIVER_SCHEMA_COMPONENTS 1 PPM_SCHEMA_CURRENT_VERSION_MINOR) + list(GET DRIVER_SCHEMA_COMPONENTS 2 PPM_SCHEMA_CURRENT_VERSION_PATCH) + message( + STATUS + "Driver schema version ${PPM_SCHEMA_CURRENT_VERSION_MAJOR}.${PPM_SCHEMA_CURRENT_VERSION_MINOR}.${PPM_SCHEMA_CURRENT_VERSION_PATCH}" + ) + + # GIT COMMIT + if(NOT DEFINED GIT_COMMIT) + execute_process( + COMMAND git rev-parse HEAD + OUTPUT_VARIABLE GIT_COMMIT + ERROR_QUIET + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + ) + endif() + string(STRIP "${GIT_COMMIT}" GIT_COMMIT) endmacro() diff --git a/cmake/modules/curl.cmake b/cmake/modules/curl.cmake index 4df9307773..a7c69d0db1 100644 --- a/cmake/modules/curl.cmake +++ b/cmake/modules/curl.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_CURL "Enable building of the bundled curl" ${USE_BUNDLED_DEPS}) @@ -25,7 +26,7 @@ elseif(NOT USE_BUNDLED_CURL) else() if(BUILD_SHARED_LIBS) set(CURL_LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) - set(CURL_STATIC_OPTION ) + set(CURL_STATIC_OPTION) else() set(CURL_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) set(CURL_STATIC_OPTION --disable-shared) @@ -50,7 +51,7 @@ else() message(STATUS "Using bundled curl in '${CURL_BUNDLE_DIR}'") if(NOT ENABLE_PIC) - set(CURL_PIC_OPTION ) + set(CURL_PIC_OPTION) else() set(CURL_PIC_OPTION "--with-pic") endif() @@ -63,54 +64,32 @@ else() URL "https://github.com/curl/curl/releases/download/curl-8_7_1/curl-8.7.1.tar.bz2" URL_HASH "SHA256=05bbd2b698e9cfbab477c33aa5e99b4975501835a41b7ca6ca71de03d8849e76" CONFIGURE_COMMAND - ./configure - ${CURL_SSL_OPTION} - ${CURL_ZLIB_OPTION} - ${CURL_STATIC_OPTION} - ${CURL_PIC_OPTION} - --enable-optimize - --disable-curldebug - --disable-rt - --enable-http - --disable-ftp - --disable-file - --disable-ldap - --disable-ldaps - --disable-rtsp - --disable-telnet - --disable-tftp - --disable-pop3 - --disable-imap - --disable-smb - --disable-smtp - --disable-gopher - --disable-sspi - --disable-ntlm-wb - --disable-tls-srp - --without-winssl - --without-polarssl - --without-cyassl - --without-nss - --without-axtls - --without-librtmp - --without-winidn - --without-libidn2 - --without-libpsl - --without-nghttp2 - --without-libssh2 - --with-ca-path=/etc/ssl/certs/ - --disable-threaded-resolver - --without-brotli - --without-zstd + ./configure ${CURL_SSL_OPTION} ${CURL_ZLIB_OPTION} ${CURL_STATIC_OPTION} + ${CURL_PIC_OPTION} --enable-optimize --disable-curldebug --disable-rt --enable-http + --disable-ftp --disable-file --disable-ldap --disable-ldaps --disable-rtsp + --disable-telnet --disable-tftp --disable-pop3 --disable-imap --disable-smb + --disable-smtp --disable-gopher --disable-sspi --disable-ntlm-wb --disable-tls-srp + --without-winssl --without-polarssl --without-cyassl --without-nss --without-axtls + --without-librtmp --without-winidn --without-libidn2 --without-libpsl + --without-nghttp2 --without-libssh2 --with-ca-path=/etc/ssl/certs/ + --disable-threaded-resolver --without-brotli --without-zstd BUILD_COMMAND make BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${CURL_LIBRARIES} - INSTALL_COMMAND "") - install(FILES "${CURL_LIBRARIES}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${CURL_INCLUDE_DIRS}curl" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + INSTALL_COMMAND "" + ) + install( + FILES "${CURL_LIBRARIES}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" COMPONENT "libs-deps" - FILES_MATCHING PATTERN "*.h") + ) + install( + DIRECTORY "${CURL_INCLUDE_DIRS}curl" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + FILES_MATCHING + PATTERN "*.h" + ) endif() endif() diff --git a/cmake/modules/engine_config.cmake b/cmake/modules/engine_config.cmake index 26c87020ab..499047939a 100644 --- a/cmake/modules/engine_config.cmake +++ b/cmake/modules/engine_config.cmake @@ -23,9 +23,12 @@ if(CMAKE_SYSTEM_NAME MATCHES "Linux") endif() # gVisor is currently only supported on Linux x86_64 -if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" AND CMAKE_SYSTEM_NAME MATCHES "Linux" AND NOT MINIMAL_BUILD) +if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" + AND CMAKE_SYSTEM_NAME MATCHES "Linux" + AND NOT MINIMAL_BUILD +) option(BUILD_LIBSCAP_GVISOR "Build gVisor support" ON) - if (BUILD_LIBSCAP_GVISOR) + if(BUILD_LIBSCAP_GVISOR) set(HAS_ENGINE_GVISOR On) endif() endif() diff --git a/cmake/modules/googleBenchmark.cmake b/cmake/modules/googleBenchmark.cmake index d2fb9a0a70..399a4744ef 100644 --- a/cmake/modules/googleBenchmark.cmake +++ b/cmake/modules/googleBenchmark.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2024 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # # Disable the Google Benchmark requirement on Google Test @@ -18,9 +19,9 @@ set(BENCHMARK_ENABLE_TESTING OFF) include(FetchContent) FetchContent_Declare( - googlebenchmark - GIT_REPOSITORY https://github.com/google/benchmark.git - GIT_TAG v1.9.0 + googlebenchmark + GIT_REPOSITORY https://github.com/google/benchmark.git + GIT_TAG v1.9.0 ) -FetchContent_MakeAvailable(googlebenchmark) \ No newline at end of file +FetchContent_MakeAvailable(googlebenchmark) diff --git a/cmake/modules/grpc.cmake b/cmake/modules/grpc.cmake index d802901d45..7eb395814b 100644 --- a/cmake/modules/grpc.cmake +++ b/cmake/modules/grpc.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_GRPC "Enable building of the bundled grpc" ${USE_BUNDLED_DEPS}) @@ -33,14 +34,22 @@ elseif(NOT USE_BUNDLED_GRPC) # gRPC include dir + properly handle grpc{++,pp} get_target_property(GRPC_INCLUDE gRPC::grpc++ INTERFACE_INCLUDE_DIRECTORIES) - find_path(GRPCXX_INCLUDE NAMES grpc++/grpc++.h PATHS ${GRPC_INCLUDE}) + find_path( + GRPCXX_INCLUDE + NAMES grpc++/grpc++.h + PATHS ${GRPC_INCLUDE} + ) if(NOT GRPCXX_INCLUDE) - find_path(GRPCPP_INCLUDE NAMES grpcpp/grpcpp.h PATHS ${GRPC_INCLUDE}) + find_path( + GRPCPP_INCLUDE + NAMES grpcpp/grpcpp.h + PATHS ${GRPC_INCLUDE} + ) add_definitions(-DGRPC_INCLUDE_IS_GRPCPP=1) endif() else() - # Fallback to manually find libraries; - # Some distro, namely Ubuntu focal, do not install gRPC config cmake module + # Fallback to manually find libraries; Some distro, namely Ubuntu focal, do not install gRPC + # config cmake module find_library(GPR_LIB NAMES gpr) if(GPR_LIB) message(STATUS "Found gpr lib: ${GPR_LIB}") @@ -57,8 +66,14 @@ elseif(NOT USE_BUNDLED_GRPC) endif() find_library(GRPC_LIB NAMES grpc) find_library(GRPCPP_LIB NAMES grpc++) - if(GRPC_INCLUDE AND GRPC_LIB AND GRPCPP_LIB) - message(STATUS "Found grpc: include: ${GRPC_INCLUDE}, C lib: ${GRPC_LIB}, C++ lib: ${GRPCPP_LIB}") + if(GRPC_INCLUDE + AND GRPC_LIB + AND GRPCPP_LIB + ) + message( + STATUS + "Found grpc: include: ${GRPC_INCLUDE}, C lib: ${GRPC_LIB}, C++ lib: ${GRPCPP_LIB}" + ) else() message(FATAL_ERROR "Couldn't find system grpc") endif() @@ -80,17 +95,17 @@ else() include(re2) set(GRPC_SRC "${PROJECT_BINARY_DIR}/grpc-prefix/src/grpc") set(GRPC_INSTALL_DIR "${GRPC_SRC}/target") - set(GRPC_INCLUDE - "${GRPC_INSTALL_DIR}/include" - "${GRPC_SRC}/third_party/abseil-cpp") + set(GRPC_INCLUDE "${GRPC_INSTALL_DIR}/include" "${GRPC_SRC}/third_party/abseil-cpp") set(GPR_LIB "${GRPC_SRC}/libgpr.a") set(GRPC_LIB "${GRPC_SRC}/libgrpc.a") set(GRPCPP_LIB "${GRPC_SRC}/libgrpc++.a") set(GRPC_CPP_PLUGIN "${GRPC_SRC}/grpc_cpp_plugin") set(GRPC_MAIN_LIBS "") - list(APPEND GRPC_MAIN_LIBS - "${GPR_LIB}" - "${GRPC_LIB}" + list( + APPEND + GRPC_MAIN_LIBS + "${GPR_LIB}" + "${GRPC_LIB}" "${GRPCPP_LIB}" "${GRPC_SRC}/libgrpc++_alts.a" "${GRPC_SRC}/libgrpc++_error_details.a" @@ -106,11 +121,13 @@ else() if(NOT TARGET grpc) message(STATUS "Using bundled grpc in '${GRPC_SRC}'") - # fixme(leogr): this workaround is required to inject the missing deps (built by gRCP cmakefiles) - # into target_link_libraries later - # note: the list below is manually generated starting from the output of pkg-config --libs grpc++ + # fixme(leogr): this workaround is required to inject the missing deps (built by gRCP + # cmakefiles) into target_link_libraries later note: the list below is manually generated + # starting from the output of pkg-config --libs grpc++ set(GRPC_LIBRARIES "") - list(APPEND GRPC_LIBRARIES + list( + APPEND + GRPC_LIBRARIES "${GRPC_SRC}/libaddress_sorting.a" "${GRPC_SRC}/libupb.a" "${GRPC_SRC}/third_party/abseil-cpp/absl/hash/libabsl_hash.a" @@ -156,8 +173,9 @@ else() "${GRPC_SRC}/third_party/abseil-cpp/absl/random/libabsl_random_internal_platform.a" "${GRPC_SRC}/third_party/abseil-cpp/absl/random/libabsl_random_seed_gen_exception.a" ) - - ExternalProject_Add(grpc + + ExternalProject_Add( + grpc PREFIX "${PROJECT_BINARY_DIR}/grpc-prefix" DEPENDS openssl protobuf c-ares zlib re2 GIT_REPOSITORY https://github.com/grpc/grpc.git @@ -202,17 +220,26 @@ else() -Dre2_DIR:PATH=${RE2_DIR} BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${GRPC_LIB} ${GRPCPP_LIB} ${GPR_LIB} ${GRPC_LIBRARIES} - # Keep installation files into the local ${GRPC_INSTALL_DIR} - # since here is the case when we are embedding gRPC + # Keep installation files into the local ${GRPC_INSTALL_DIR} since here is the case when + # we are embedding gRPC UPDATE_COMMAND "" INSTALL_COMMAND DESTDIR= ${CMAKE_MAKE_PROGRAM} install ) - install(FILES ${GRPC_MAIN_LIBS} DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(FILES ${GRPC_LIBRARIES} DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${GRPC_SRC}/target/include/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + install( + FILES ${GRPC_MAIN_LIBS} + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + FILES ${GRPC_LIBRARIES} + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + DIRECTORY "${GRPC_SRC}/target/include/" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() endif() diff --git a/cmake/modules/gtest.cmake b/cmake/modules/gtest.cmake index a94ed62828..8613bbce19 100644 --- a/cmake/modules/gtest.cmake +++ b/cmake/modules/gtest.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_GTEST "Enable building of the bundled gtest" ${USE_BUNDLED_DEPS}) @@ -17,41 +18,60 @@ option(USE_BUNDLED_GTEST "Enable building of the bundled gtest" ${USE_BUNDLED_DE if(GTEST_INCLUDE_DIR) # we already have gtest elseif(NOT USE_BUNDLED_GTEST) - find_path(GTEST_INCLUDE_DIR PATH_SUFFIXES gtest NAMES gtest.h) + find_path( + GTEST_INCLUDE_DIR + PATH_SUFFIXES gtest + NAMES gtest.h + ) find_library(GTEST_LIB NAMES gtest) find_library(GTEST_MAIN_LIB NAMES gtest_main) - if(GTEST_INCLUDE_DIR AND GTEST_LIB AND GTEST_MAIN_LIB) - message(STATUS "Found gtest: include: ${GTEST_INCLUDE_DIR}, lib: ${GTEST_LIB}, main lib: ${GTEST_MAIN_LIB}") + if(GTEST_INCLUDE_DIR + AND GTEST_LIB + AND GTEST_MAIN_LIB + ) + message( + STATUS + "Found gtest: include: ${GTEST_INCLUDE_DIR}, lib: ${GTEST_LIB}, main lib: ${GTEST_MAIN_LIB}" + ) else() message(FATAL_ERROR "Couldn't find system gtest") endif() else() # https://github.com/google/googletest/tree/main/googletest#incorporating-into-an-existing-cmake-project # Download and unpack googletest at configure time - configure_file(CMakeListsGtestInclude.cmake ${PROJECT_BINARY_DIR}/googletest-download/CMakeLists.txt) - execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . + configure_file( + CMakeListsGtestInclude.cmake ${PROJECT_BINARY_DIR}/googletest-download/CMakeLists.txt + ) + execute_process( + COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . RESULT_VARIABLE result - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/googletest-download ) + WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/googletest-download + ) if(result) message(FATAL_ERROR "CMake step for googletest failed: ${result}") endif() - execute_process(COMMAND ${CMAKE_COMMAND} --build . + execute_process( + COMMAND ${CMAKE_COMMAND} --build . RESULT_VARIABLE result - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/googletest-download ) + WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/googletest-download + ) if(result) message(FATAL_ERROR "Build step for googletest failed: ${result}") endif() - # Add googletest directly to our build. This defines - # the gtest and gtest_main targets. - add_subdirectory(${PROJECT_BINARY_DIR}/googletest-src - ${PROJECT_BINARY_DIR}/googletest-build - EXCLUDE_FROM_ALL) + # Add googletest directly to our build. This defines the gtest and gtest_main targets. + add_subdirectory( + ${PROJECT_BINARY_DIR}/googletest-src ${PROJECT_BINARY_DIR}/googletest-build + EXCLUDE_FROM_ALL + ) set(GTEST_INCLUDE_DIR "${gtest_SOURCE_DIR}/include") set(GTEST_MAIN_LIB "gtest_main") - install(DIRECTORY "${GTEST_INCLUDE_DIR}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + install( + DIRECTORY "${GTEST_INCLUDE_DIR}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() if(NOT TARGET gtest) diff --git a/cmake/modules/jsoncpp.cmake b/cmake/modules/jsoncpp.cmake index 970aba0411..4e48ae7e06 100644 --- a/cmake/modules/jsoncpp.cmake +++ b/cmake/modules/jsoncpp.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_JSONCPP "Enable building of the bundled jsoncpp" ${USE_BUNDLED_DEPS}) @@ -44,68 +45,70 @@ else() message(STATUS "Using bundled jsoncpp in '${JSONCPP_SRC}'") if(NOT WIN32) ExternalProject_Add( - jsoncpp - PREFIX "${PROJECT_BINARY_DIR}/jsoncpp-prefix" - URL "https://github.com/open-source-parsers/jsoncpp/archive/refs/tags/1.9.5.tar.gz" - URL_HASH - "SHA256=f409856e5920c18d0c2fb85276e24ee607d2a09b5e7d5f0a371368903c275da2" - CMAKE_ARGS - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DBUILD_OBJECT_LIBS=Off - ${JSONCPP_STATIC_OPTION} - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DJSONCPP_WITH_TESTS=Off - -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off - -DCMAKE_INSTALL_PREFIX=${JSONCPP_SRC} - -DCMAKE_INSTALL_LIBDIR=lib - BUILD_BYPRODUCTS ${JSONCPP_LIB} + jsoncpp + PREFIX "${PROJECT_BINARY_DIR}/jsoncpp-prefix" + URL "https://github.com/open-source-parsers/jsoncpp/archive/refs/tags/1.9.5.tar.gz" + URL_HASH "SHA256=f409856e5920c18d0c2fb85276e24ee607d2a09b5e7d5f0a371368903c275da2" + CMAKE_ARGS -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DBUILD_OBJECT_LIBS=Off + ${JSONCPP_STATIC_OPTION} + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DJSONCPP_WITH_TESTS=Off + -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off + -DCMAKE_INSTALL_PREFIX=${JSONCPP_SRC} + -DCMAKE_INSTALL_LIBDIR=lib + BUILD_BYPRODUCTS ${JSONCPP_LIB} ) else() # see: https://cmake.org/cmake/help/latest/policy/CMP0091.html if(CMAKE_VERSION VERSION_LESS 3.15.0) ExternalProject_Add( - jsoncpp - PREFIX "${PROJECT_BINARY_DIR}/jsoncpp-prefix" - URL "https://github.com/open-source-parsers/jsoncpp/archive/refs/tags/1.9.5.tar.gz" - URL_HASH + jsoncpp + PREFIX "${PROJECT_BINARY_DIR}/jsoncpp-prefix" + URL "https://github.com/open-source-parsers/jsoncpp/archive/refs/tags/1.9.5.tar.gz" + URL_HASH "SHA256=f409856e5920c18d0c2fb85276e24ee607d2a09b5e7d5f0a371368903c275da2" - CMAKE_ARGS - -DCMAKE_CXX_FLAGS_DEBUG=${FALCOSECURITY_LIBS_DEBUG_FLAGS} - -DCMAKE_CXX_FLAGS_RELEASE=${FALCOSECURITY_LIBS_RELEASE_FLAGS} - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DBUILD_OBJECT_LIBS=Off - ${JSONCPP_STATIC_OPTION} - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DJSONCPP_WITH_TESTS=Off - -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off - -DCMAKE_INSTALL_PREFIX=${JSONCPP_SRC} - -DCMAKE_INSTALL_LIBDIR=lib + CMAKE_ARGS -DCMAKE_CXX_FLAGS_DEBUG=${FALCOSECURITY_LIBS_DEBUG_FLAGS} + -DCMAKE_CXX_FLAGS_RELEASE=${FALCOSECURITY_LIBS_RELEASE_FLAGS} + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DBUILD_OBJECT_LIBS=Off + ${JSONCPP_STATIC_OPTION} + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DJSONCPP_WITH_TESTS=Off + -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off + -DCMAKE_INSTALL_PREFIX=${JSONCPP_SRC} + -DCMAKE_INSTALL_LIBDIR=lib ) else() ExternalProject_Add( - jsoncpp - PREFIX "${PROJECT_BINARY_DIR}/jsoncpp-prefix" - URL "https://github.com/open-source-parsers/jsoncpp/archive/refs/tags/1.9.5.tar.gz" - URL_HASH + jsoncpp + PREFIX "${PROJECT_BINARY_DIR}/jsoncpp-prefix" + URL "https://github.com/open-source-parsers/jsoncpp/archive/refs/tags/1.9.5.tar.gz" + URL_HASH "SHA256=f409856e5920c18d0c2fb85276e24ee607d2a09b5e7d5f0a371368903c275da2" - CMAKE_ARGS - -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW - -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} - -DBUILD_OBJECT_LIBS=Off - ${JSONCPP_STATIC_OPTION} - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DJSONCPP_WITH_TESTS=Off - -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off - -DCMAKE_INSTALL_PREFIX=${JSONCPP_SRC} - -DCMAKE_INSTALL_LIBDIR=lib + CMAKE_ARGS -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW + -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} + -DBUILD_OBJECT_LIBS=Off + ${JSONCPP_STATIC_OPTION} + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DJSONCPP_WITH_TESTS=Off + -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off + -DCMAKE_INSTALL_PREFIX=${JSONCPP_SRC} + -DCMAKE_INSTALL_LIBDIR=lib ) endif() endif() - install(FILES "${JSONCPP_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${JSONCPP_INCLUDE}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + install( + FILES "${JSONCPP_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + DIRECTORY "${JSONCPP_INCLUDE}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() endif() diff --git a/cmake/modules/libbpf.cmake b/cmake/modules/libbpf.cmake index a2f5a0328c..39e1408bc3 100644 --- a/cmake/modules/libbpf.cmake +++ b/cmake/modules/libbpf.cmake @@ -2,57 +2,68 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_LIBBPF "Enable building of the bundled libbpf" ${USE_BUNDLED_DEPS}) if(LIBBPF_INCLUDE) - # we already have libbpf + # we already have libbpf elseif(NOT USE_BUNDLED_LIBBPF) - find_path(LIBBPF_INCLUDE bpf/libbpf.h) - find_library(LIBBPF_LIB NAMES bpf) - if(LIBBPF_INCLUDE AND LIBBPF_LIB) - message(STATUS "Found libbpf: include: ${LIBBPF_INCLUDE}, lib: ${LIBBPF_LIB}") - else() - message(FATAL_ERROR "Couldn't find system libbpf") - endif() + find_path(LIBBPF_INCLUDE bpf/libbpf.h) + find_library(LIBBPF_LIB NAMES bpf) + if(LIBBPF_INCLUDE AND LIBBPF_LIB) + message(STATUS "Found libbpf: include: ${LIBBPF_INCLUDE}, lib: ${LIBBPF_LIB}") + else() + message(FATAL_ERROR "Couldn't find system libbpf") + endif() else() - include(zlib) - include(libelf) - set(LIBBPF_SRC "${PROJECT_BINARY_DIR}/libbpf-prefix/src") - set(LIBBPF_BUILD_DIR "${LIBBPF_SRC}/libbpf-build") - set(LIBBPF_INCLUDE "${LIBBPF_BUILD_DIR}/root/usr/include") - set(LIBBPF_LIB "${LIBBPF_BUILD_DIR}/root/usr/lib64/libbpf.a") - ExternalProject_Add( - libbpf - PREFIX "${PROJECT_BINARY_DIR}/libbpf-prefix" - DEPENDS zlib libelf - URL "https://github.com/libbpf/libbpf/archive/refs/tags/v1.3.0.tar.gz" - URL_HASH - "SHA256=11db86acd627e468bc48b7258c1130aba41a12c4d364f78e184fd2f5a913d861" - CONFIGURE_COMMAND mkdir -p build root - BUILD_COMMAND make BUILD_STATIC_ONLY=y OBJDIR=${LIBBPF_BUILD_DIR}/build DESTDIR=${LIBBPF_BUILD_DIR}/root NO_PKG_CONFIG=1 "EXTRA_CFLAGS=-fPIC -I${LIBELF_INCLUDE} -I${ZLIB_INCLUDE}" "LDFLAGS=-Wl,-Bstatic" "EXTRA_LDFLAGS=-L${LIBELF_SRC}/libelf/libelf -L${ZLIB_SRC}" -C ${LIBBPF_SRC}/libbpf/src install install_uapi_headers - INSTALL_COMMAND "" - UPDATE_COMMAND "" - BUILD_BYPRODUCTS ${LIBBPF_LIB} - ) - message(STATUS "Using bundled libbpf: include'${LIBBPF_INCLUDE}', lib: ${LIBBPF_LIB}") - install(FILES "${LIBBPF_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${LIBBPF_INCLUDE}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + include(zlib) + include(libelf) + set(LIBBPF_SRC "${PROJECT_BINARY_DIR}/libbpf-prefix/src") + set(LIBBPF_BUILD_DIR "${LIBBPF_SRC}/libbpf-build") + set(LIBBPF_INCLUDE "${LIBBPF_BUILD_DIR}/root/usr/include") + set(LIBBPF_LIB "${LIBBPF_BUILD_DIR}/root/usr/lib64/libbpf.a") + ExternalProject_Add( + libbpf + PREFIX "${PROJECT_BINARY_DIR}/libbpf-prefix" + DEPENDS zlib libelf + URL "https://github.com/libbpf/libbpf/archive/refs/tags/v1.3.0.tar.gz" + URL_HASH "SHA256=11db86acd627e468bc48b7258c1130aba41a12c4d364f78e184fd2f5a913d861" + CONFIGURE_COMMAND mkdir -p build root + BUILD_COMMAND + make BUILD_STATIC_ONLY=y OBJDIR=${LIBBPF_BUILD_DIR}/build + DESTDIR=${LIBBPF_BUILD_DIR}/root NO_PKG_CONFIG=1 + "EXTRA_CFLAGS=-fPIC -I${LIBELF_INCLUDE} -I${ZLIB_INCLUDE}" "LDFLAGS=-Wl,-Bstatic" + "EXTRA_LDFLAGS=-L${LIBELF_SRC}/libelf/libelf -L${ZLIB_SRC}" -C ${LIBBPF_SRC}/libbpf/src + install install_uapi_headers + INSTALL_COMMAND "" + UPDATE_COMMAND "" + BUILD_BYPRODUCTS ${LIBBPF_LIB} + ) + message(STATUS "Using bundled libbpf: include'${LIBBPF_INCLUDE}', lib: ${LIBBPF_LIB}") + install( + FILES "${LIBBPF_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + DIRECTORY "${LIBBPF_INCLUDE}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() if(NOT TARGET libbpf) - add_custom_target(libbpf) + add_custom_target(libbpf) endif() include_directories(${LIBBPF_INCLUDE}) diff --git a/cmake/modules/libelf.cmake b/cmake/modules/libelf.cmake index 1b7311f733..809acf7e3f 100644 --- a/cmake/modules/libelf.cmake +++ b/cmake/modules/libelf.cmake @@ -2,75 +2,85 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_LIBELF "Enable building of the bundled libelf" ${USE_BUNDLED_DEPS}) option(USE_SHARED_LIBELF "When not using bundled libelf, link it dynamically" ON) if(LIBELF_INCLUDE) - # we already have LIBELF + # we already have LIBELF elseif(NOT USE_BUNDLED_LIBELF) - find_path(LIBELF_INCLUDE elf.h PATH_SUFFIXES elf) - if(BUILD_SHARED_LIBS OR USE_SHARED_LIBELF) - set(LIBELF_LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) - else() - set(LIBELF_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) - endif() - find_library(LIBELF_LIB NAMES libelf${LIBELF_LIB_SUFFIX}) - if(LIBELF_LIB) - message(STATUS "Found LIBELF: include: ${LIBELF_INCLUDE}, lib: ${LIBELF_LIB}") - else() - message(FATAL_ERROR "Couldn't find system libelf") - endif() - # We add a custom target, in this way we can always depend on `libelf` - # without distinguishing between "bundled" and "not-bundled" case - add_custom_target(libelf) + find_path(LIBELF_INCLUDE elf.h PATH_SUFFIXES elf) + if(BUILD_SHARED_LIBS OR USE_SHARED_LIBELF) + set(LIBELF_LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) + else() + set(LIBELF_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) + endif() + find_library(LIBELF_LIB NAMES libelf${LIBELF_LIB_SUFFIX}) + if(LIBELF_LIB) + message(STATUS "Found LIBELF: include: ${LIBELF_INCLUDE}, lib: ${LIBELF_LIB}") + else() + message(FATAL_ERROR "Couldn't find system libelf") + endif() + # We add a custom target, in this way we can always depend on `libelf` without distinguishing + # between "bundled" and "not-bundled" case + add_custom_target(libelf) else() - if(BUILD_SHARED_LIBS) - set(LIBELF_LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) - else() - set(LIBELF_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) - endif() - set(LIBELF_CFLAGS "-I${ZLIB_INCLUDE}") - if (ENABLE_PIC) - set(LIBELF_CFLAGS "${LIBELF_CFLAGS} -fPIC") - endif() - set(LIBELF_SRC "${PROJECT_BINARY_DIR}/libelf-prefix/src") - set(LIBELF_INCLUDE "${LIBELF_SRC}/libelf/libelf") - set(LIBELF_LIB "${LIBELF_SRC}/libelf/libelf/libelf${LIBELF_LIB_SUFFIX}") - ExternalProject_Add( - libelf - PREFIX "${PROJECT_BINARY_DIR}/libelf-prefix" - DEPENDS zlib - URL "https://sourceware.org/elfutils/ftp/0.189/elfutils-0.189.tar.bz2" - URL_HASH "SHA256=39bd8f1a338e2b7cd4abc3ff11a0eddc6e690f69578a57478d8179b4148708c8" - CONFIGURE_COMMAND ./configure LDFLAGS=-L${ZLIB_SRC} "CFLAGS=${LIBELF_CFLAGS}" --enable-deterministic-archives --disable-debuginfod --disable-libdebuginfod --without-zstd - BUILD_IN_SOURCE 1 - BUILD_COMMAND make -C lib libeu.a - COMMAND make -C libelf libelf${LIBELF_LIB_SUFFIX} - INSTALL_COMMAND "" - UPDATE_COMMAND "" - BUILD_BYPRODUCTS ${LIBELF_LIB} - ) - message(STATUS "Using bundled libelf: include'${LIBELF_INCLUDE}', lib: ${LIBELF_LIB}") - install(FILES "${LIBELF_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${LIBELF_INCLUDE}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + if(BUILD_SHARED_LIBS) + set(LIBELF_LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) + else() + set(LIBELF_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) + endif() + set(LIBELF_CFLAGS "-I${ZLIB_INCLUDE}") + if(ENABLE_PIC) + set(LIBELF_CFLAGS "${LIBELF_CFLAGS} -fPIC") + endif() + set(LIBELF_SRC "${PROJECT_BINARY_DIR}/libelf-prefix/src") + set(LIBELF_INCLUDE "${LIBELF_SRC}/libelf/libelf") + set(LIBELF_LIB "${LIBELF_SRC}/libelf/libelf/libelf${LIBELF_LIB_SUFFIX}") + ExternalProject_Add( + libelf + PREFIX "${PROJECT_BINARY_DIR}/libelf-prefix" + DEPENDS zlib + URL "https://sourceware.org/elfutils/ftp/0.189/elfutils-0.189.tar.bz2" + URL_HASH "SHA256=39bd8f1a338e2b7cd4abc3ff11a0eddc6e690f69578a57478d8179b4148708c8" + CONFIGURE_COMMAND + ./configure LDFLAGS=-L${ZLIB_SRC} "CFLAGS=${LIBELF_CFLAGS}" + --enable-deterministic-archives --disable-debuginfod --disable-libdebuginfod + --without-zstd + BUILD_IN_SOURCE 1 + BUILD_COMMAND make -C lib libeu.a + COMMAND make -C libelf libelf${LIBELF_LIB_SUFFIX} + INSTALL_COMMAND "" + UPDATE_COMMAND "" + BUILD_BYPRODUCTS ${LIBELF_LIB} + ) + message(STATUS "Using bundled libelf: include'${LIBELF_INCLUDE}', lib: ${LIBELF_LIB}") + install( + FILES "${LIBELF_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + DIRECTORY "${LIBELF_INCLUDE}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() -# We add a custom target, in this way we can always depend on `libelf` -# without distinguishing between "bundled" and "not-bundled" case +# We add a custom target, in this way we can always depend on `libelf` without distinguishing +# between "bundled" and "not-bundled" case if(NOT TARGET libelf) - add_custom_target(libelf) + add_custom_target(libelf) endif() include_directories(${LIBELF_INCLUDE}) diff --git a/cmake/modules/libscap.cmake b/cmake/modules/libscap.cmake index 81ad2d28df..b41b12ff37 100644 --- a/cmake/modules/libscap.cmake +++ b/cmake/modules/libscap.cmake @@ -2,141 +2,165 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # if(NOT HAVE_LIBSCAP) -set(HAVE_LIBSCAP On) + set(HAVE_LIBSCAP On) -if(NOT LIBS_DIR) - get_filename_component(LIBS_DIR ${CMAKE_CURRENT_LIST_DIR}/../.. ABSOLUTE) -endif() - -option(USE_BUNDLED_DEPS "Enable bundled dependencies instead of using the system ones" ON) + if(NOT LIBS_DIR) + get_filename_component(LIBS_DIR ${CMAKE_CURRENT_LIST_DIR}/../.. ABSOLUTE) + endif() -include(GNUInstallDirs) + option(USE_BUNDLED_DEPS "Enable bundled dependencies instead of using the system ones" ON) -include(ExternalProject) + include(GNUInstallDirs) -include(uthash) + include(ExternalProject) -include(CheckSymbolExists) -check_symbol_exists(strlcpy "string.h" HAVE_STRLCPY) -check_symbol_exists(strlcat "string.h" HAVE_STRLCAT) + include(uthash) -if(HAVE_STRLCPY) - message(STATUS "Existing strlcpy found, will *not* use local definition") -else() - message(STATUS "No strlcpy found, will use local definition") -endif() + include(CheckSymbolExists) + check_symbol_exists(strlcpy "string.h" HAVE_STRLCPY) + check_symbol_exists(strlcat "string.h" HAVE_STRLCAT) -if(HAVE_STRLCAT) - message(STATUS "Existing strlcat found, will *not* use local definition") -else() - message(STATUS "No strlcat found, will use local definition") -endif() + if(HAVE_STRLCPY) + message(STATUS "Existing strlcpy found, will *not* use local definition") + else() + message(STATUS "No strlcpy found, will use local definition") + endif() -add_definitions(-DPLATFORM_NAME="${CMAKE_SYSTEM_NAME}") + if(HAVE_STRLCAT) + message(STATUS "Existing strlcat found, will *not* use local definition") + else() + message(STATUS "No strlcat found, will use local definition") + endif() -if(CMAKE_SYSTEM_NAME MATCHES "Linux") - get_filename_component(DRIVER_CONFIG_DIR ${CMAKE_BINARY_DIR}/driver/src ABSOLUTE) -else() - # This doesn't install all of the driver headers but seems to be sufficient for - # non-Linux platforms. - get_filename_component(DRIVER_CONFIG_DIR ${PROJECT_SOURCE_DIR}/driver ABSOLUTE) -endif() + add_definitions(-DPLATFORM_NAME="${CMAKE_SYSTEM_NAME}") -get_filename_component(LIBSCAP_INCLUDE_DIR ${LIBS_DIR}/userspace/libscap ABSOLUTE) -set(LIBSCAP_INCLUDE_DIRS ${LIBSCAP_INCLUDE_DIR} ${PROJECT_BINARY_DIR} ${DRIVER_CONFIG_DIR}) + if(CMAKE_SYSTEM_NAME MATCHES "Linux") + get_filename_component(DRIVER_CONFIG_DIR ${CMAKE_BINARY_DIR}/driver/src ABSOLUTE) + else() + # This doesn't install all of the driver headers but seems to be sufficient for non-Linux + # platforms. + get_filename_component(DRIVER_CONFIG_DIR ${PROJECT_SOURCE_DIR}/driver ABSOLUTE) + endif() -function(set_scap_target_properties target) - set_target_properties(${target} PROPERTIES - VERSION ${FALCOSECURITY_SHARED_LIBS_VERSION} - SOVERSION ${FALCOSECURITY_SHARED_LIBS_SOVERSION} - ) -endfunction() + get_filename_component(LIBSCAP_INCLUDE_DIR ${LIBS_DIR}/userspace/libscap ABSOLUTE) + set(LIBSCAP_INCLUDE_DIRS ${LIBSCAP_INCLUDE_DIR} ${PROJECT_BINARY_DIR} ${DRIVER_CONFIG_DIR}) -add_subdirectory(${LIBS_DIR}/userspace/libscap ${PROJECT_BINARY_DIR}/libscap) + function(set_scap_target_properties target) + set_target_properties( + ${target} PROPERTIES VERSION ${FALCOSECURITY_SHARED_LIBS_VERSION} + SOVERSION ${FALCOSECURITY_SHARED_LIBS_SOVERSION} + ) + endfunction() -set(LIBSCAP_INSTALL_LIBS) + add_subdirectory(${LIBS_DIR}/userspace/libscap ${PROJECT_BINARY_DIR}/libscap) -# All of the targets in userspace/libscap -get_directory_property(libscap_subdirs DIRECTORY ${LIBS_DIR}/userspace/libscap SUBDIRECTORIES) -set(libscap_subdir_targets) -foreach(libscap_subdir ${LIBS_DIR}/userspace/libscap ${libscap_subdirs}) - get_directory_property(subdir_targets DIRECTORY ${libscap_subdir} BUILDSYSTEM_TARGETS) - list(APPEND libscap_subdir_targets ${subdir_targets}) -endforeach() + set(LIBSCAP_INSTALL_LIBS) -set(install_lib_type STATIC_LIBRARY) -if (BUILD_SHARED_LIBS) - set(install_lib_type SHARED_LIBRARY) -endif() + # All of the targets in userspace/libscap + get_directory_property(libscap_subdirs DIRECTORY ${LIBS_DIR}/userspace/libscap SUBDIRECTORIES) + set(libscap_subdir_targets) + foreach(libscap_subdir ${LIBS_DIR}/userspace/libscap ${libscap_subdirs}) + get_directory_property(subdir_targets DIRECTORY ${libscap_subdir} BUILDSYSTEM_TARGETS) + list(APPEND libscap_subdir_targets ${subdir_targets}) + endforeach() -# Installation targets only -foreach(libscap_subdir_target ${libscap_subdir_targets}) - get_target_property(cl_target_type ${libscap_subdir_target} TYPE) - if (${cl_target_type} STREQUAL ${install_lib_type}) - list(APPEND LIBSCAP_INSTALL_LIBS ${libscap_subdir_target}) + set(install_lib_type STATIC_LIBRARY) + if(BUILD_SHARED_LIBS) + set(install_lib_type SHARED_LIBRARY) endif() -endforeach() - -# Installation targets and their dependencies -set(libscap_link_libraries) -set(libscap_link_libdirs) -foreach(libscap_install_lib ${LIBSCAP_INSTALL_LIBS}) - list(APPEND libscap_link_libraries ${libscap_install_lib}) - get_target_property(install_lib_link_libraries ${libscap_install_lib} LINK_LIBRARIES) - foreach (install_lib_link_library ${install_lib_link_libraries}) - if (NOT ${install_lib_link_library} IN_LIST libscap_subdir_targets) - if(${install_lib_link_library} MATCHES "/") - # We have a path. Convert it to -L + -l. - get_filename_component(scap_lib_dir ${install_lib_link_library} DIRECTORY) - list(APPEND libscap_link_libdirs -L${scap_lib_dir}) - get_filename_component(scap_lib_base ${install_lib_link_library} NAME_WE) - string(REGEX REPLACE "^lib" "" scap_lib_base ${scap_lib_base}) - list(APPEND libscap_link_libraries ${scap_lib_base}) - else() - list(APPEND libscap_link_libraries ${install_lib_link_library}) - endif() + + # Installation targets only + foreach(libscap_subdir_target ${libscap_subdir_targets}) + get_target_property(cl_target_type ${libscap_subdir_target} TYPE) + if(${cl_target_type} STREQUAL ${install_lib_type}) + list(APPEND LIBSCAP_INSTALL_LIBS ${libscap_subdir_target}) endif() endforeach() -endforeach() -list(REMOVE_DUPLICATES libscap_link_libraries) - -set(libscap_link_flags) -foreach(libscap_link_library ${libscap_link_libraries}) - list(APPEND libscap_link_flags "-l${libscap_link_library}") -endforeach() - -string(REPLACE ";" " " LIBSCAP_LINK_LIBRARIES_FLAGS "${libscap_link_flags}") -string(REPLACE ";" " " LIBSCAP_LINK_LIBDIRS_FLAGS "${libscap_link_libdirs}") -configure_file(${LIBS_DIR}/userspace/libscap/libscap.pc.in ${PROJECT_BINARY_DIR}/libscap/libscap.pc @ONLY) - -install(TARGETS ${LIBSCAP_INSTALL_LIBS} - ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" - LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" - RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" - COMPONENT "scap" OPTIONAL) -install(DIRECTORY "${LIBSCAP_INCLUDE_DIR}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "scap" - FILES_MATCHING PATTERN "*.h" - PATTERN "*examples*" EXCLUDE - PATTERN "*doxygen*" EXCLUDE) -install(DIRECTORY "${DRIVER_CONFIG_DIR}/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/driver" - COMPONENT "scap" - FILES_MATCHING PATTERN "*.h") -install(DIRECTORY "${LIBS_DIR}/userspace/plugin" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + + # Installation targets and their dependencies + set(libscap_link_libraries) + set(libscap_link_libdirs) + foreach(libscap_install_lib ${LIBSCAP_INSTALL_LIBS}) + list(APPEND libscap_link_libraries ${libscap_install_lib}) + get_target_property(install_lib_link_libraries ${libscap_install_lib} LINK_LIBRARIES) + foreach(install_lib_link_library ${install_lib_link_libraries}) + if(NOT ${install_lib_link_library} IN_LIST libscap_subdir_targets) + if(${install_lib_link_library} MATCHES "/") + # We have a path. Convert it to -L + -l. + get_filename_component(scap_lib_dir ${install_lib_link_library} DIRECTORY) + list(APPEND libscap_link_libdirs -L${scap_lib_dir}) + get_filename_component(scap_lib_base ${install_lib_link_library} NAME_WE) + string(REGEX REPLACE "^lib" "" scap_lib_base ${scap_lib_base}) + list(APPEND libscap_link_libraries ${scap_lib_base}) + else() + list(APPEND libscap_link_libraries ${install_lib_link_library}) + endif() + endif() + endforeach() + endforeach() + list(REMOVE_DUPLICATES libscap_link_libraries) + + set(libscap_link_flags) + foreach(libscap_link_library ${libscap_link_libraries}) + list(APPEND libscap_link_flags "-l${libscap_link_library}") + endforeach() + + string(REPLACE ";" " " LIBSCAP_LINK_LIBRARIES_FLAGS "${libscap_link_flags}") + string(REPLACE ";" " " LIBSCAP_LINK_LIBDIRS_FLAGS "${libscap_link_libdirs}") + configure_file( + ${LIBS_DIR}/userspace/libscap/libscap.pc.in ${PROJECT_BINARY_DIR}/libscap/libscap.pc @ONLY + ) + + install( + TARGETS ${LIBSCAP_INSTALL_LIBS} + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + COMPONENT "scap" + OPTIONAL + ) + install( + DIRECTORY "${LIBSCAP_INCLUDE_DIR}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" COMPONENT "scap" - FILES_MATCHING PATTERN "*.h") -install(FILES ${PROJECT_BINARY_DIR}/libscap/scap_config.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/libscap) -install(FILES ${PROJECT_BINARY_DIR}/libscap/scap_strl_config.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/libscap) -install(FILES ${PROJECT_BINARY_DIR}/libscap/libscap.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) + FILES_MATCHING + PATTERN "*.h" + PATTERN "*examples*" EXCLUDE + PATTERN "*doxygen*" EXCLUDE + ) + install( + DIRECTORY "${DRIVER_CONFIG_DIR}/" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/driver" + COMPONENT "scap" + FILES_MATCHING + PATTERN "*.h" + ) + install( + DIRECTORY "${LIBS_DIR}/userspace/plugin" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "scap" + FILES_MATCHING + PATTERN "*.h" + ) + install(FILES ${PROJECT_BINARY_DIR}/libscap/scap_config.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/libscap + ) + install(FILES ${PROJECT_BINARY_DIR}/libscap/scap_strl_config.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/libscap + ) + install(FILES ${PROJECT_BINARY_DIR}/libscap/libscap.pc + DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig + ) endif() diff --git a/cmake/modules/libsinsp.cmake b/cmake/modules/libsinsp.cmake index 815130de09..ff336e27f2 100644 --- a/cmake/modules/libsinsp.cmake +++ b/cmake/modules/libsinsp.cmake @@ -2,102 +2,127 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # if(NOT HAVE_LIBSINSP) -set(HAVE_LIBSINSP On) - -if(NOT LIBS_DIR) - get_filename_component(LIBS_DIR ${CMAKE_CURRENT_LIST_DIR}/../.. ABSOLUTE) -endif() - -option(USE_BUNDLED_DEPS "Enable bundled dependencies instead of using the system ones" ON) -option(ENABLE_THREAD_POOL "Enable inspector thread pool" OFF) - -if(DEFINED LIBSINSP_USER_AGENT) - add_definitions(-DLIBSINSP_USER_AGENT="${LIBSINSP_USER_AGENT}") -endif() - -include(ExternalProject) -include(libscap) -if (NOT EMSCRIPTEN) - include(tbb) -endif() -if(NOT WIN32 AND NOT APPLE AND NOT MINIMAL_BUILD AND NOT EMSCRIPTEN) - include(cares) - include(curl) -endif() -include(jsoncpp) -include(valijson) -include(re2) - -if(ENABLE_THREAD_POOL AND NOT EMSCRIPTEN) - include(bs_threadpool) -endif() - -set(LIBSINSP_INCLUDE_DIRS ${LIBS_DIR} ${LIBS_DIR}/userspace ${LIBSCAP_INCLUDE_DIRS} ${DRIVER_CONFIG_DIR}) - -if (NOT EMSCRIPTEN) - get_filename_component(TBB_ABSOLUTE_INCLUDE_DIR ${TBB_INCLUDE_DIR} ABSOLUTE) - list(APPEND LIBSINSP_INCLUDE_DIRS ${TBB_ABSOLUTE_INCLUDE_DIR}) -endif() - -get_filename_component(JSONCPP_ABSOLUTE_INCLUDE_DIR ${JSONCPP_INCLUDE} ABSOLUTE) -list(APPEND LIBSINSP_INCLUDE_DIRS ${JSONCPP_ABSOLUTE_INCLUDE_DIR}) + set(HAVE_LIBSINSP On) + + if(NOT LIBS_DIR) + get_filename_component(LIBS_DIR ${CMAKE_CURRENT_LIST_DIR}/../.. ABSOLUTE) + endif() + + option(USE_BUNDLED_DEPS "Enable bundled dependencies instead of using the system ones" ON) + option(ENABLE_THREAD_POOL "Enable inspector thread pool" OFF) + + if(DEFINED LIBSINSP_USER_AGENT) + add_definitions(-DLIBSINSP_USER_AGENT="${LIBSINSP_USER_AGENT}") + endif() + + include(ExternalProject) + include(libscap) + if(NOT EMSCRIPTEN) + include(tbb) + endif() + if(NOT WIN32 + AND NOT APPLE + AND NOT MINIMAL_BUILD + AND NOT EMSCRIPTEN + ) + include(cares) + include(curl) + endif() + include(jsoncpp) + include(valijson) + include(re2) + + if(ENABLE_THREAD_POOL AND NOT EMSCRIPTEN) + include(bs_threadpool) + endif() + + set(LIBSINSP_INCLUDE_DIRS ${LIBS_DIR} ${LIBS_DIR}/userspace ${LIBSCAP_INCLUDE_DIRS} + ${DRIVER_CONFIG_DIR} + ) -get_filename_component(VALIJSON_ABSOLUTE_INCLUDE_DIR ${VALIJSON_INCLUDE} ABSOLUTE) -list(APPEND LIBSINSP_INCLUDE_DIRS ${VALIJSON_ABSOLUTE_INCLUDE_DIR}) + if(NOT EMSCRIPTEN) + get_filename_component(TBB_ABSOLUTE_INCLUDE_DIR ${TBB_INCLUDE_DIR} ABSOLUTE) + list(APPEND LIBSINSP_INCLUDE_DIRS ${TBB_ABSOLUTE_INCLUDE_DIR}) + endif() -get_filename_component(RE2_ABSOLUTE_INCLUDE_DIR ${RE2_INCLUDE} ABSOLUTE) -list(APPEND LIBSINSP_INCLUDE_DIRS ${RE2_ABSOLUTE_INCLUDE_DIR}) + get_filename_component(JSONCPP_ABSOLUTE_INCLUDE_DIR ${JSONCPP_INCLUDE} ABSOLUTE) + list(APPEND LIBSINSP_INCLUDE_DIRS ${JSONCPP_ABSOLUTE_INCLUDE_DIR}) -if (ENABLE_THREAD_POOL AND NOT EMSCRIPTEN) - get_filename_component(BS_THREADPOOL_ABSOLUTE_INCLUDE_DIR ${BS_THREADPOOL_INCLUDE} ABSOLUTE) - list(APPEND LIBSINSP_INCLUDE_DIRS ${BS_THREADPOOL_ABSOLUTE_INCLUDE_DIR}) -endif() + get_filename_component(VALIJSON_ABSOLUTE_INCLUDE_DIR ${VALIJSON_INCLUDE} ABSOLUTE) + list(APPEND LIBSINSP_INCLUDE_DIRS ${VALIJSON_ABSOLUTE_INCLUDE_DIR}) -if(NOT MINIMAL_BUILD AND NOT EMSCRIPTEN AND NOT APPLE) - get_filename_component(CARES_ABSOLUTE_INCLUDE_DIR ${CARES_INCLUDE} ABSOLUTE) - list(APPEND LIBSINSP_INCLUDE_DIRS ${CARES_ABSOLUTE_INCLUDE_DIR}) -endif() + get_filename_component(RE2_ABSOLUTE_INCLUDE_DIR ${RE2_INCLUDE} ABSOLUTE) + list(APPEND LIBSINSP_INCLUDE_DIRS ${RE2_ABSOLUTE_INCLUDE_DIR}) -if(NOT WIN32 AND NOT APPLE AND NOT MINIMAL_BUILD AND NOT EMSCRIPTEN) - get_filename_component(CURL_ABSOLUTE_INCLUDE_DIR ${CURL_INCLUDE_DIRS} ABSOLUTE) - list(APPEND LIBSINSP_INCLUDE_DIRS ${CURL_ABSOLUTE_INCLUDE_DIR}) -endif() + if(ENABLE_THREAD_POOL AND NOT EMSCRIPTEN) + get_filename_component(BS_THREADPOOL_ABSOLUTE_INCLUDE_DIR ${BS_THREADPOOL_INCLUDE} ABSOLUTE) + list(APPEND LIBSINSP_INCLUDE_DIRS ${BS_THREADPOOL_ABSOLUTE_INCLUDE_DIR}) + endif() -function(set_sinsp_target_properties target) - set_target_properties(${target} PROPERTIES - VERSION ${FALCOSECURITY_SHARED_LIBS_VERSION} - SOVERSION ${FALCOSECURITY_SHARED_LIBS_SOVERSION} + if(NOT MINIMAL_BUILD + AND NOT EMSCRIPTEN + AND NOT APPLE + ) + get_filename_component(CARES_ABSOLUTE_INCLUDE_DIR ${CARES_INCLUDE} ABSOLUTE) + list(APPEND LIBSINSP_INCLUDE_DIRS ${CARES_ABSOLUTE_INCLUDE_DIR}) + endif() + + if(NOT WIN32 + AND NOT APPLE + AND NOT MINIMAL_BUILD + AND NOT EMSCRIPTEN + ) + get_filename_component(CURL_ABSOLUTE_INCLUDE_DIR ${CURL_INCLUDE_DIRS} ABSOLUTE) + list(APPEND LIBSINSP_INCLUDE_DIRS ${CURL_ABSOLUTE_INCLUDE_DIR}) + endif() + + function(set_sinsp_target_properties target) + set_target_properties( + ${target} PROPERTIES VERSION ${FALCOSECURITY_SHARED_LIBS_VERSION} + SOVERSION ${FALCOSECURITY_SHARED_LIBS_SOVERSION} + ) + endfunction() + + add_subdirectory(${LIBS_DIR}/userspace/libsinsp ${CMAKE_BINARY_DIR}/libsinsp) + install( + TARGETS sinsp + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" COMPONENT "sinsp" + ) + install( + DIRECTORY "${LIBS_DIR}/userspace/libsinsp" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "sinsp" + FILES_MATCHING + PATTERN "*.h" + PATTERN "*third_party*" EXCLUDE + PATTERN "*examples*" EXCLUDE + PATTERN "*doxygen*" EXCLUDE + PATTERN "*scripts*" EXCLUDE + PATTERN "*test*" EXCLUDE + ) + install( + DIRECTORY "${LIBS_DIR}/userspace/async" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "sinsp" + FILES_MATCHING + PATTERN "*.h" + ) + install(FILES ${PROJECT_BINARY_DIR}/libsinsp/libsinsp.pc + DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) -endfunction() - -add_subdirectory(${LIBS_DIR}/userspace/libsinsp ${CMAKE_BINARY_DIR}/libsinsp) -install(TARGETS sinsp - ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" - LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" - RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" - COMPONENT "sinsp") -install(DIRECTORY "${LIBS_DIR}/userspace/libsinsp" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "sinsp" - FILES_MATCHING PATTERN "*.h" - PATTERN "*third_party*" EXCLUDE - PATTERN "*examples*" EXCLUDE - PATTERN "*doxygen*" EXCLUDE - PATTERN "*scripts*" EXCLUDE - PATTERN "*test*" EXCLUDE) -install(DIRECTORY "${LIBS_DIR}/userspace/async" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "sinsp" - FILES_MATCHING PATTERN "*.h") -install(FILES ${PROJECT_BINARY_DIR}/libsinsp/libsinsp.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) endif() diff --git a/cmake/modules/openssl.cmake b/cmake/modules/openssl.cmake index ca07902b79..06def028bd 100644 --- a/cmake/modules/openssl.cmake +++ b/cmake/modules/openssl.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_OPENSSL "Enable building of the bundled OpenSSL" ${USE_BUNDLED_DEPS}) @@ -32,32 +33,44 @@ else() set(OPENSSL_INCLUDE_DIR "${PROJECT_BINARY_DIR}/openssl-prefix/src/openssl/include/") set(OPENSSL_LIBRARY_SSL "${OPENSSL_INSTALL_DIR}/lib/libssl${OPENSSL_LIB_SUFFIX}") set(OPENSSL_LIBRARY_CRYPTO "${OPENSSL_INSTALL_DIR}/lib/libcrypto${OPENSSL_LIB_SUFFIX}") - set(OPENSSL_LIBRARIES ${OPENSSL_LIBRARY_SSL} ${OPENSSL_LIBRARY_CRYPTO}) + set(OPENSSL_LIBRARIES ${OPENSSL_LIBRARY_SSL} ${OPENSSL_LIBRARY_CRYPTO}) if(NOT TARGET openssl) if(NOT ENABLE_PIC) - set(OPENSSL_PIC_OPTION ) + set(OPENSSL_PIC_OPTION) else() set(OPENSSL_PIC_OPTION "-fPIC") endif() message(STATUS "Using bundled openssl in '${OPENSSL_BUNDLE_DIR}'") - ExternalProject_Add(openssl + ExternalProject_Add( + openssl PREFIX "${PROJECT_BINARY_DIR}/openssl-prefix" URL "https://github.com/openssl/openssl/releases/download/openssl-3.1.4/openssl-3.1.4.tar.gz" URL_HASH "SHA256=840af5366ab9b522bde525826be3ef0fb0af81c6a9ebd84caa600fea1731eee3" - CONFIGURE_COMMAND ./config ${OPENSSL_SHARED_OPTION} ${OPENSSL_PIC_OPTION} --prefix=${OPENSSL_INSTALL_DIR} --libdir=lib + CONFIGURE_COMMAND ./config ${OPENSSL_SHARED_OPTION} ${OPENSSL_PIC_OPTION} + --prefix=${OPENSSL_INSTALL_DIR} --libdir=lib BUILD_COMMAND make BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${OPENSSL_LIBRARY_SSL} ${OPENSSL_LIBRARY_CRYPTO} - INSTALL_COMMAND make install_sw) - install(FILES "${OPENSSL_LIBRARY_SSL}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(FILES "${OPENSSL_LIBRARY_CRYPTO}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${OPENSSL_INCLUDE_DIR}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + INSTALL_COMMAND make install_sw + ) + install( + FILES "${OPENSSL_LIBRARY_SSL}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + FILES "${OPENSSL_LIBRARY_CRYPTO}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + DIRECTORY "${OPENSSL_INCLUDE_DIR}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() endif() diff --git a/cmake/modules/protobuf.cmake b/cmake/modules/protobuf.cmake index b9a1e2d379..d5bcb1b090 100644 --- a/cmake/modules/protobuf.cmake +++ b/cmake/modules/protobuf.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_PROTOBUF "Enable building of the bundled protobuf" ${USE_BUNDLED_DEPS}) @@ -20,8 +21,14 @@ elseif(NOT USE_BUNDLED_PROTOBUF) find_program(PROTOC NAMES protoc) find_path(PROTOBUF_INCLUDE NAMES google/protobuf/message.h) find_library(PROTOBUF_LIB NAMES protobuf) - if(PROTOC AND PROTOBUF_INCLUDE AND PROTOBUF_LIB) - message(STATUS "Found protobuf: compiler: ${PROTOC}, include: ${PROTOBUF_INCLUDE}, lib: ${PROTOBUF_LIB}") + if(PROTOC + AND PROTOBUF_INCLUDE + AND PROTOBUF_LIB + ) + message( + STATUS + "Found protobuf: compiler: ${PROTOC}, include: ${PROTOBUF_INCLUDE}, lib: ${PROTOBUF_LIB}" + ) else() message(FATAL_ERROR "Couldn't find system protobuf") endif() @@ -38,39 +45,56 @@ else() set(PROTOBUF_SRC "${PROJECT_BINARY_DIR}/protobuf-prefix/src/protobuf") set(PROTOC "${PROTOBUF_SRC}/target/bin/protoc") set(PROTOBUF_INCLUDE "${PROTOBUF_SRC}/target/include/") - set(PROTOBUF_LIB "${PROTOBUF_SRC}/target/lib/libprotobuf${PROTOBUF_LIB_SUFFIX}" CACHE PATH "Path to libprotobuf") + set(PROTOBUF_LIB + "${PROTOBUF_SRC}/target/lib/libprotobuf${PROTOBUF_LIB_SUFFIX}" + CACHE PATH "Path to libprotobuf" + ) set(PROTOC_LIB "${PROTOBUF_SRC}/target/lib/libprotoc${PROTOBUF_LIB_SUFFIX}") set(PROTOBUF_INSTALL_DIR "${PROTOBUF_SRC}/target") if(NOT TARGET protobuf) if(NOT ENABLE_PIC) - set(PROTOBUF_PIC_OPTION ) + set(PROTOBUF_PIC_OPTION) else() set(PROTOBUF_PIC_OPTION "--with-pic=yes") endif() - if (CMAKE_BUILD_TYPE STREQUAL "Release") + if(CMAKE_BUILD_TYPE STREQUAL "Release") set(PROTOBUF_CXXFLAGS "-O2 -std=c++11 -DNDEBUG") else() set(PROTOBUF_CXXFLAGS "-g -std=c++11") endif() message(STATUS "Using bundled protobuf in '${PROTOBUF_SRC}'") - ExternalProject_Add(protobuf + ExternalProject_Add( + protobuf PREFIX "${PROJECT_BINARY_DIR}/protobuf-prefix" DEPENDS zlib URL "https://github.com/protocolbuffers/protobuf/releases/download/v3.20.3/protobuf-cpp-3.20.3.tar.gz" URL_HASH "SHA256=e51cc8fc496f893e2a48beb417730ab6cbcb251142ad8b2cd1951faa5c76fe3d" # TODO what if using system zlib? - CONFIGURE_COMMAND CPPFLAGS=-I${ZLIB_INCLUDE} LDFLAGS=-L${ZLIB_SRC} ./configure CXXFLAGS=${PROTOBUF_CXXFLAGS} --with-zlib ${PROTOBUF_CONFIGURE_FLAGS} ${PROTOBUF_PIC_OPTION} --prefix=${PROTOBUF_INSTALL_DIR} + CONFIGURE_COMMAND + CPPFLAGS=-I${ZLIB_INCLUDE} LDFLAGS=-L${ZLIB_SRC} ./configure + CXXFLAGS=${PROTOBUF_CXXFLAGS} --with-zlib ${PROTOBUF_CONFIGURE_FLAGS} + ${PROTOBUF_PIC_OPTION} --prefix=${PROTOBUF_INSTALL_DIR} BUILD_COMMAND make BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${PROTOC} ${PROTOBUF_INCLUDE} ${PROTOBUF_LIB} - INSTALL_COMMAND make install) - install(FILES "${PROTOBUF_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(FILES "${PROTOC_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(DIRECTORY "${PROTOBUF_INCLUDE}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + INSTALL_COMMAND make install + ) + install( + FILES "${PROTOBUF_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + FILES "${PROTOC_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + DIRECTORY "${PROTOBUF_INCLUDE}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() endif() diff --git a/cmake/modules/re2.cmake b/cmake/modules/re2.cmake index 55c368d47b..5724e72181 100644 --- a/cmake/modules/re2.cmake +++ b/cmake/modules/re2.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_RE2 "Enable building of the bundled RE2" ${USE_BUNDLED_DEPS}) @@ -42,80 +43,90 @@ else() set(RE2_LIB "${RE2_SRC}/lib/libre2${RE2_LIB_SUFFIX}") set(RE2_LIB_PATTERN "libre2*") if(CMAKE_VERSION VERSION_LESS 3.29.1) - ExternalProject_Add(re2 + ExternalProject_Add( + re2 PREFIX "${PROJECT_BINARY_DIR}/re2-prefix" URL "${RE2_URL}" URL_HASH "${RE2_URL_HASH}" BINARY_DIR "${PROJECT_BINARY_DIR}/re2-prefix/build" BUILD_BYPRODUCTS ${RE2_LIB} - CMAKE_ARGS - -DCMAKE_INSTALL_LIBDIR=lib - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DRE2_BUILD_TESTING=OFF - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_INSTALL_PREFIX=${RE2_SRC}) + CMAKE_ARGS -DCMAKE_INSTALL_LIBDIR=lib + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DRE2_BUILD_TESTING=OFF + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_INSTALL_PREFIX=${RE2_SRC} + ) else() - # CMake 3.29.1 removed the support for the `PACKAGE_PREFIX_DIR` - # variable. The patch command just applies the same patch applied - # by re2 to solve the issue: + # CMake 3.29.1 removed the support for the `PACKAGE_PREFIX_DIR` variable. The patch + # command just applies the same patch applied by re2 to solve the issue: # https://github.com/google/re2/commit/9ebe4a22cad8a025b68a9594bdff3c047a111333 - ExternalProject_Add(re2 + ExternalProject_Add( + re2 PREFIX "${PROJECT_BINARY_DIR}/re2-prefix" URL "${RE2_URL}" URL_HASH "${RE2_URL_HASH}" BINARY_DIR "${PROJECT_BINARY_DIR}/re2-prefix/build" BUILD_BYPRODUCTS ${RE2_LIB} PATCH_COMMAND - COMMAND sed -i".bak" "/set_and_check/d" re2Config.cmake.in - CMAKE_ARGS - -DCMAKE_INSTALL_LIBDIR=lib - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DRE2_BUILD_TESTING=OFF - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_INSTALL_PREFIX=${RE2_SRC}) + COMMAND sed -i".bak" "/set_and_check/d" re2Config.cmake.in + CMAKE_ARGS -DCMAKE_INSTALL_LIBDIR=lib + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DRE2_BUILD_TESTING=OFF + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_INSTALL_PREFIX=${RE2_SRC} + ) endif() else() set(RE2_LIB "${RE2_SRC}/lib/re2.lib") set(RE2_LIB_PATTERN "re2.lib") # see: https://cmake.org/cmake/help/latest/policy/CMP0091.html if(CMAKE_VERSION VERSION_LESS 3.15.0) - ExternalProject_Add(re2 + ExternalProject_Add( + re2 PREFIX "${PROJECT_BINARY_DIR}/re2-prefix" URL "${RE2_URL}" URL_HASH "${RE2_URL_HASH}" BINARY_DIR "${PROJECT_BINARY_DIR}/re2-prefix/build" BUILD_BYPRODUCTS ${RE2_LIB} - CMAKE_ARGS - -DCMAKE_CXX_FLAGS_DEBUG=${FALCOSECURITY_LIBS_DEBUG_FLAGS} - -DCMAKE_CXX_FLAGS_RELEASE=${FALCOSECURITY_LIBS_RELEASE_FLAGS} - -DCMAKE_INSTALL_LIBDIR=lib - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DRE2_BUILD_TESTING=OFF - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_INSTALL_PREFIX=${RE2_SRC}) + CMAKE_ARGS -DCMAKE_CXX_FLAGS_DEBUG=${FALCOSECURITY_LIBS_DEBUG_FLAGS} + -DCMAKE_CXX_FLAGS_RELEASE=${FALCOSECURITY_LIBS_RELEASE_FLAGS} + -DCMAKE_INSTALL_LIBDIR=lib + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DRE2_BUILD_TESTING=OFF + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_INSTALL_PREFIX=${RE2_SRC} + ) else() - ExternalProject_Add(re2 + ExternalProject_Add( + re2 PREFIX "${PROJECT_BINARY_DIR}/re2-prefix" URL "${RE2_URL}" URL_HASH "${RE2_URL_HASH}" BINARY_DIR "${PROJECT_BINARY_DIR}/re2-prefix/build" BUILD_BYPRODUCTS ${RE2_LIB} - CMAKE_ARGS - -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW - -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} - -DCMAKE_INSTALL_LIBDIR=lib - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DRE2_BUILD_TESTING=OFF - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_INSTALL_PREFIX=${RE2_SRC}) + CMAKE_ARGS -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW + -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} + -DCMAKE_INSTALL_LIBDIR=lib + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DRE2_BUILD_TESTING=OFF + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_INSTALL_PREFIX=${RE2_SRC} + ) endif() endif() - install(DIRECTORY ${RE2_SRC}/lib/ DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps" - FILES_MATCHING PATTERN ${RE2_LIB_PATTERN}) - install(DIRECTORY "${RE2_INCLUDE}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + install( + DIRECTORY ${RE2_SRC}/lib/ + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + FILES_MATCHING + PATTERN ${RE2_LIB_PATTERN} + ) + install( + DIRECTORY "${RE2_INCLUDE}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() if(NOT TARGET re2) diff --git a/cmake/modules/tbb.cmake b/cmake/modules/tbb.cmake index b586f45c23..3e90f04739 100644 --- a/cmake/modules/tbb.cmake +++ b/cmake/modules/tbb.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_TBB "Enable building of the bundled tbb" ${USE_BUNDLED_DEPS}) @@ -52,81 +53,95 @@ else() else() set(TBB_LIB_BASENAME "tbb12") endif() - endif() + endif() set(TBB_LIB "${TBB_LIB_BASEDIR}/${TBB_LIB_PREFIX}${TBB_LIB_BASENAME}${TBB_LIB_SUFFIX}") if(NOT TARGET tbb) message(STATUS "Using bundled tbb in '${TBB_SRC}'") set(TBB_SRC_URL "https://github.com/oneapi-src/oneTBB/archive/refs/tags/v2021.9.0.tar.gz") - set(TBB_SRC_URL_HASH "SHA256=1ce48f34dada7837f510735ff1172f6e2c261b09460e3bf773b49791d247d24e") + set(TBB_SRC_URL_HASH + "SHA256=1ce48f34dada7837f510735ff1172f6e2c261b09460e3bf773b49791d247d24e" + ) set(TBB_FLAGS "") - if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - # latest TBB has issues with GCC >= 12 - # see: https://github.com/oneapi-src/oneTBB/issues/843#issuecomment-1152646035 + if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + # latest TBB has issues with GCC >= 12 see: + # https://github.com/oneapi-src/oneTBB/issues/843#issuecomment-1152646035 set(TBB_FLAGS "-Wno-error=stringop-overflow") endif() - if(NOT WIN32) - ExternalProject_Add(tbb + if(NOT WIN32) + ExternalProject_Add( + tbb PREFIX "${PROJECT_BINARY_DIR}/tbb-prefix" URL "${TBB_SRC_URL}" URL_HASH "${TBB_SRC_URL_HASH}" BUILD_IN_SOURCE 1 BUILD_COMMAND ${CMAKE_COMMAND} --build . --target tbb - CMAKE_ARGS - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} - -DTBB_OUTPUT_DIR_BASE=lib - -DCMAKE_CXX_FLAGS="${TBB_FLAGS}" - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} + CMAKE_ARGS -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DTBB_OUTPUT_DIR_BASE=lib + -DCMAKE_CXX_FLAGS="${TBB_FLAGS}" + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} + -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} BUILD_BYPRODUCTS ${TBB_LIB} - INSTALL_COMMAND "") + INSTALL_COMMAND "" + ) else() # see: https://cmake.org/cmake/help/latest/policy/CMP0091.html if(CMAKE_VERSION VERSION_LESS 3.15.0) - ExternalProject_Add(tbb + ExternalProject_Add( + tbb PREFIX "${PROJECT_BINARY_DIR}/tbb-prefix" URL "${TBB_SRC_URL}" URL_HASH "${TBB_SRC_URL_HASH}" BUILD_IN_SOURCE 1 - BUILD_COMMAND ${CMAKE_COMMAND} --build . --target tbb --config ${CMAKE_BUILD_TYPE} - CMAKE_ARGS - -DCMAKE_CXX_FLAGS_DEBUG=${FALCOSECURITY_LIBS_DEBUG_FLAGS} - -DCMAKE_CXX_FLAGS_RELEASE=${FALCOSECURITY_LIBS_RELEASE_FLAGS} - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} - -DTBB_OUTPUT_DIR_BASE=lib - -DCMAKE_CXX_FLAGS="${TBB_FLAGS}" - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + BUILD_COMMAND ${CMAKE_COMMAND} --build . --target tbb --config + ${CMAKE_BUILD_TYPE} + CMAKE_ARGS -DCMAKE_CXX_FLAGS_DEBUG=${FALCOSECURITY_LIBS_DEBUG_FLAGS} + -DCMAKE_CXX_FLAGS_RELEASE=${FALCOSECURITY_LIBS_RELEASE_FLAGS} + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DTBB_OUTPUT_DIR_BASE=lib + -DCMAKE_CXX_FLAGS="${TBB_FLAGS}" + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} BUILD_BYPRODUCTS ${TBB_LIB} - INSTALL_COMMAND "") + INSTALL_COMMAND "" + ) else() - ExternalProject_Add(tbb + ExternalProject_Add( + tbb PREFIX "${PROJECT_BINARY_DIR}/tbb-prefix" URL "${TBB_SRC_URL}" URL_HASH "${TBB_SRC_URL_HASH}" BUILD_IN_SOURCE 1 - BUILD_COMMAND ${CMAKE_COMMAND} --build . --target tbb --config ${CMAKE_BUILD_TYPE} - CMAKE_ARGS - -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW - -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} - -DTBB_OUTPUT_DIR_BASE=lib - -DCMAKE_CXX_FLAGS="${TBB_FLAGS}" - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + BUILD_COMMAND ${CMAKE_COMMAND} --build . --target tbb --config + ${CMAKE_BUILD_TYPE} + CMAKE_ARGS -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW + -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DTBB_OUTPUT_DIR_BASE=lib + -DCMAKE_CXX_FLAGS="${TBB_FLAGS}" + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} BUILD_BYPRODUCTS ${TBB_LIB} - INSTALL_COMMAND "") + INSTALL_COMMAND "" + ) endif() endif() - install(DIRECTORY "${TBB_LIB_BASEDIR}/" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps" - FILES_MATCHING PATTERN "${TBB_LIB_PREFIX}tbb*") - install(DIRECTORY "${TBB_INCLUDE_DIR}/tbb" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") + install( + DIRECTORY "${TBB_LIB_BASEDIR}/" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + FILES_MATCHING + PATTERN "${TBB_LIB_PREFIX}tbb*" + ) + install( + DIRECTORY "${TBB_INCLUDE_DIR}/tbb" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) endif() endif() diff --git a/cmake/modules/uthash.cmake b/cmake/modules/uthash.cmake index 13125491c8..4bdff11471 100644 --- a/cmake/modules/uthash.cmake +++ b/cmake/modules/uthash.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_UTHASH "Enable downloading of the bundled uthash library" ${USE_BUNDLED_DEPS}) @@ -31,13 +32,15 @@ else() message(STATUS "Using bundled uthash in '${UTHASH_SRC}'") - ExternalProject_Add(uthash - PREFIX "${PROJECT_BINARY_DIR}/uthash-prefix" - URL "https://github.com/troydhanson/uthash/archive/refs/tags/v1.9.8.tar.gz" - URL_HASH "SHA256=d9d123ce81c5d127442876fc3b12fab3ad632bee6aca685be7d461c08e24c046" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "") + ExternalProject_Add( + uthash + PREFIX "${PROJECT_BINARY_DIR}/uthash-prefix" + URL "https://github.com/troydhanson/uthash/archive/refs/tags/v1.9.8.tar.gz" + URL_HASH "SHA256=d9d123ce81c5d127442876fc3b12fab3ad632bee6aca685be7d461c08e24c046" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + ) endif() if(NOT TARGET uthash) diff --git a/cmake/modules/valijson.cmake b/cmake/modules/valijson.cmake index 99d3df5831..e2a26fcf2d 100644 --- a/cmake/modules/valijson.cmake +++ b/cmake/modules/valijson.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # # @@ -28,13 +29,15 @@ else() message(STATUS "Using bundled valijson in '${VALIJSON_SRC}'") - ExternalProject_Add(valijson + ExternalProject_Add( + valijson PREFIX "${PROJECT_BINARY_DIR}/valijson-prefix" URL "https://github.com/tristanpenman/valijson/archive/refs/tags/v1.0.2.tar.gz" URL_HASH "SHA256=35d86e54fc727f1265226434dc996e33000a570f833537a25c8b702b0b824431" CONFIGURE_COMMAND "" BUILD_COMMAND "" - INSTALL_COMMAND "") + INSTALL_COMMAND "" + ) endif() if(NOT TARGET valijson) diff --git a/cmake/modules/versions.cmake b/cmake/modules/versions.cmake index 682f8cc478..b80d490fda 100644 --- a/cmake/modules/versions.cmake +++ b/cmake/modules/versions.cmake @@ -2,51 +2,57 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # include(GetVersionFromGit) function(get_libs_version _var) - # `+driver` is given to ignore drivers tags when fetching the version of libs - get_version_from_git(ver "" "+driver") - - set(${_var} - "${ver}" - PARENT_SCOPE) - return() + # `+driver` is given to ignore drivers tags when fetching the version of libs + get_version_from_git(ver "" "+driver") + + set(${_var} + "${ver}" + PARENT_SCOPE + ) + return() endfunction() function(get_drivers_version _var) - # `+driver` is given to only fetch drivers tags, thus excluding libs ones - get_version_from_git(ver "+driver" "") - - set(${_var} - "${ver}" - PARENT_SCOPE) - return() + # `+driver` is given to only fetch drivers tags, thus excluding libs ones + get_version_from_git(ver "+driver" "") + + set(${_var} + "${ver}" + PARENT_SCOPE + ) + return() endfunction() function(get_shared_libs_versions _var _sovar) - string(REGEX MATCH "^[0-9]+\\.[0-9]+\\.[0-9]+" sl_ver ${FALCOSECURITY_LIBS_VERSION}) - - if(NOT sl_ver) - set(sl_ver "0.0.0") - endif() - - set(${_var} ${sl_ver} PARENT_SCOPE) - string(REPLACE "." ";" sl_ver_list ${sl_ver}) - list(GET sl_ver_list 0 so_ver) - set(${_sovar} ${so_ver} PARENT_SCOPE) - return() + string(REGEX MATCH "^[0-9]+\\.[0-9]+\\.[0-9]+" sl_ver ${FALCOSECURITY_LIBS_VERSION}) + + if(NOT sl_ver) + set(sl_ver "0.0.0") + endif() + + set(${_var} + ${sl_ver} + PARENT_SCOPE + ) + string(REPLACE "." ";" sl_ver_list ${sl_ver}) + list(GET sl_ver_list 0 so_ver) + set(${_sovar} + ${so_ver} + PARENT_SCOPE + ) + return() endfunction() diff --git a/cmake/modules/zlib.cmake b/cmake/modules/zlib.cmake index 506d5256a6..29682699d1 100644 --- a/cmake/modules/zlib.cmake +++ b/cmake/modules/zlib.cmake @@ -2,14 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_ZLIB "Enable building of the bundled zlib" ${USE_BUNDLED_DEPS}) @@ -28,7 +29,9 @@ else() set(ZLIB_SRC "${PROJECT_BINARY_DIR}/zlib-prefix/src/zlib") set(ZLIB_INCLUDE "${ZLIB_SRC}") set(ZLIB_HEADERS "") - list(APPEND ZLIB_HEADERS + list( + APPEND + ZLIB_HEADERS "${ZLIB_INCLUDE}/crc32.h" "${ZLIB_INCLUDE}/deflate.h" "${ZLIB_INCLUDE}/gzguts.h" @@ -42,8 +45,8 @@ else() "${ZLIB_INCLUDE}/zutil.h" ) if(NOT TARGET zlib) - set(ZLIB_CFLAGS ) - if (ENABLE_PIC) + set(ZLIB_CFLAGS) + if(ENABLE_PIC) set(ZLIB_CFLAGS -fPIC) endif() @@ -51,25 +54,34 @@ else() if(NOT WIN32) if(BUILD_SHARED_LIBS) set(ZLIB_LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) - set(ZLIB_CONFIGURE_FLAGS ) + set(ZLIB_CONFIGURE_FLAGS) else() set(ZLIB_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) set(ZLIB_CONFIGURE_FLAGS "--static") endif() set(ZLIB_LIB "${ZLIB_SRC}/libz${ZLIB_LIB_SUFFIX}") - ExternalProject_Add(zlib + ExternalProject_Add( + zlib PREFIX "${PROJECT_BINARY_DIR}/zlib-prefix" URL "https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz" URL_HASH "SHA256=9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23" - CONFIGURE_COMMAND CFLAGS=${ZLIB_CFLAGS} ./configure --prefix=${ZLIB_SRC} ${ZLIB_CONFIGURE_FLAGS} + CONFIGURE_COMMAND CFLAGS=${ZLIB_CFLAGS} ./configure --prefix=${ZLIB_SRC} + ${ZLIB_CONFIGURE_FLAGS} BUILD_COMMAND make BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${ZLIB_LIB} - INSTALL_COMMAND "") - install(FILES "${ZLIB_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(FILES ${ZLIB_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/zlib" - COMPONENT "libs-deps") + INSTALL_COMMAND "" + ) + install( + FILES "${ZLIB_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + FILES ${ZLIB_HEADERS} + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/zlib" + COMPONENT "libs-deps" + ) else() if(BUILD_SHARED_LIBS) set(ZLIB_LIB_SUFFIX "${CMAKE_SHARED_LIBRARY_SUFFIX}") @@ -78,23 +90,30 @@ else() set(ZLIB_LIB_SUFFIX "${CMAKE_STATIC_LIBRARY_SUFFIX}") set(ZLIB_LIB "${ZLIB_SRC}/lib/zlibstatic$<$:d>${ZLIB_LIB_SUFFIX}") endif() - ExternalProject_Add(zlib + ExternalProject_Add( + zlib PREFIX "${PROJECT_BINARY_DIR}/zlib-prefix" URL "https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz" URL_HASH "SHA256=9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23" BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${ZLIB_LIB} - CMAKE_ARGS - -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW - -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} - -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} - -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} - -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} - -DCMAKE_INSTALL_PREFIX=${ZLIB_SRC}) - install(FILES "${ZLIB_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" - COMPONENT "libs-deps") - install(FILES ${ZLIB_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/zlib" - COMPONENT "libs-deps") + CMAKE_ARGS -DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW + -DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY} + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DCMAKE_POSITION_INDEPENDENT_CODE=${ENABLE_PIC} + -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} + -DCMAKE_INSTALL_PREFIX=${ZLIB_SRC} + ) + install( + FILES "${ZLIB_LIB}" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/${LIBS_PACKAGE_NAME}" + COMPONENT "libs-deps" + ) + install( + FILES ${ZLIB_HEADERS} + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${LIBS_PACKAGE_NAME}/zlib" + COMPONENT "libs-deps" + ) endif() endif() endif() diff --git a/driver/CMakeLists.txt b/driver/CMakeLists.txt index 80229cc034..94f37ee2ac 100644 --- a/driver/CMakeLists.txt +++ b/driver/CMakeLists.txt @@ -2,26 +2,31 @@ # # Copyright (C) 2023 The Falco Authors. # -# This file is dual licensed under either the MIT or GPL 2. See -# MIT.txt or GPL.txt for full copies of the license. +# This file is dual licensed under either the MIT or GPL 2. See MIT.txt or GPL.txt for full copies +# of the license. # cmake_minimum_required(VERSION 3.12) project(driver) set(TARGET_ARCH ${CMAKE_HOST_SYSTEM_PROCESSOR}) -if((NOT TARGET_ARCH STREQUAL "x86_64") AND - (NOT TARGET_ARCH STREQUAL "aarch64") AND - (NOT TARGET_ARCH STREQUAL "s390x") AND - (NOT TARGET_ARCH STREQUAL "riscv64") AND - (NOT TARGET_ARCH STREQUAL "ppc64le") AND - (NOT TARGET_ARCH STREQUAL "loongarch64")) +if((NOT TARGET_ARCH STREQUAL "x86_64") + AND (NOT TARGET_ARCH STREQUAL "aarch64") + AND (NOT TARGET_ARCH STREQUAL "s390x") + AND (NOT TARGET_ARCH STREQUAL "riscv64") + AND (NOT TARGET_ARCH STREQUAL "ppc64le") + AND (NOT TARGET_ARCH STREQUAL "loongarch64") +) message(WARNING "Target architecture not officially supported by our drivers!") else() # Load current kernel version - execute_process(COMMAND uname -r OUTPUT_VARIABLE UNAME_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE) + execute_process( + COMMAND uname -r + OUTPUT_VARIABLE UNAME_RESULT + OUTPUT_STRIP_TRAILING_WHITESPACE + ) string(REGEX MATCH "[0-9]+.[0-9]+" LINUX_KERNEL_VERSION ${UNAME_RESULT}) - message(STATUS "Kernel version: ${UNAME_RESULT}") + message(STATUS "Kernel version: ${UNAME_RESULT}") # Check minimum kernel version set(kmod_min_kver_map_x86_64 2.6) @@ -31,8 +36,11 @@ else() set(kmod_min_kver_map_ppc64le 2.6) set(kmod_min_kver_map_loongarch64 5.10) - if (LINUX_KERNEL_VERSION VERSION_LESS ${kmod_min_kver_map_${TARGET_ARCH}}) - message(WARNING "[KMOD] To run this driver you need a Linux kernel version >= ${kmod_min_kver_map_${TARGET_ARCH}} but actual kernel version is: ${UNAME_RESULT}") + if(LINUX_KERNEL_VERSION VERSION_LESS ${kmod_min_kver_map_${TARGET_ARCH}}) + message( + WARNING + "[KMOD] To run this driver you need a Linux kernel version >= ${kmod_min_kver_map_${TARGET_ARCH}} but actual kernel version is: ${UNAME_RESULT}" + ) endif() endif() @@ -40,8 +48,9 @@ option(BUILD_DRIVER "Build the driver on Linux" ON) option(ENABLE_DKMS "Enable DKMS on Linux" ON) if(NOT DEFINED DRIVER_VERSION) - message(FATAL_ERROR - "No DRIVER_VERSION set.\nPlease either explicitly set it or build the root project 'falcosecurity/libs' from a git working directory." + message( + FATAL_ERROR + "No DRIVER_VERSION set.\nPlease either explicitly set it or build the root project 'falcosecurity/libs' from a git working directory." ) endif() @@ -64,36 +73,30 @@ if(NOT DEFINED DRIVER_DEVICE_NAME) set(DRIVER_DEVICE_NAME "${DRIVER_NAME}") endif() -# The driver build process is somewhat involved because we use the same -# sources for building the driver locally and for shipping as a DKMS module. +# The driver build process is somewhat involved because we use the same sources for building the +# driver locally and for shipping as a DKMS module. # -# We need a single directory with the following files inside: -# - all the driver *.c/*.h sources -# - Makefile generated from Makefile.in -# - driver_config.h generated from driver_config.h.in +# We need a single directory with the following files inside: - all the driver *.c/*.h sources - +# Makefile generated from Makefile.in - driver_config.h generated from driver_config.h.in # -# The Makefile _must_ be called just Makefile (and not e.g. Makefile.dkms) -# because of the module build process, which looks like this: -# 1. The user (or some script) runs make in our driver directory -# 2. Our Makefile runs the Makefile from kernel sources/headers -# 3. The kernel Makefile calls our original Makefile again, with options that -# trigger the actual build. This step cannot know that our Makefile has -# a different name. +# The Makefile _must_ be called just Makefile (and not e.g. Makefile.dkms) because of the module +# build process, which looks like this: 1. The user (or some script) runs make in our driver +# directory 2. Our Makefile runs the Makefile from kernel sources/headers 3. The kernel Makefile +# calls our original Makefile again, with options that trigger the actual build. This step cannot +# know that our Makefile has a different name. # # (DKMS needs a Makefile called Makefile as well). # -# The files need to be in a single directory because we cannot know where -# the sources will be built (especially by DKMS) so we cannot put _any_ paths -# in the Makefile. +# The files need to be in a single directory because we cannot know where the sources will be built +# (especially by DKMS) so we cannot put _any_ paths in the Makefile. # -# The chosen directory must not be ${CMAKE_CURRENT_BINARY_DIR} because CMake -# puts its own generated Makefile in there, so we (arbitrarily) choose -# ${CMAKE_CURRENT_BINARY_DIR}/src. To maintain compatibility with older versions, -# after the build we copy the compiled module one directory up, +# The chosen directory must not be ${CMAKE_CURRENT_BINARY_DIR} because CMake puts its own generated +# Makefile in there, so we (arbitrarily) choose ${CMAKE_CURRENT_BINARY_DIR}/src. To maintain +# compatibility with older versions, after the build we copy the compiled module one directory up, # to ${CMAKE_CURRENT_BINARY_DIR}. include(compute_versions RESULT_VARIABLE RESULT) if(RESULT STREQUAL NOTFOUND) - message(FATAL_ERROR "problem with compute_versions.cmake in ${CMAKE_MODULE_PATH}") + message(FATAL_ERROR "problem with compute_versions.cmake in ${CMAKE_MODULE_PATH}") endif() compute_versions(API_VERSION SCHEMA_VERSION) @@ -108,23 +111,26 @@ file(GLOB configure_modules "${CMAKE_CURRENT_SOURCE_DIR}/configure/*") foreach(subdir ${configure_modules}) if(IS_DIRECTORY "${subdir}") file(RELATIVE_PATH CONFIGURE_MODULE "${CMAKE_CURRENT_SOURCE_DIR}/configure" "${subdir}") - configure_file(configure/${CONFIGURE_MODULE}/test.c src/configure/${CONFIGURE_MODULE}/test.c COPYONLY) + configure_file( + configure/${CONFIGURE_MODULE}/test.c src/configure/${CONFIGURE_MODULE}/test.c COPYONLY + ) configure_file(configure/Makefile src/configure/${CONFIGURE_MODULE}/Makefile COPYONLY) configure_file(configure/build.sh src/configure/${CONFIGURE_MODULE}/build.sh COPYONLY) configure_file(configure/Makefile.inc.in src/configure/${CONFIGURE_MODULE}/Makefile.inc) if(ENABLE_DKMS) - install(FILES - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/build.sh" - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/test.c" - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile" - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile.inc" - DESTINATION "src/${DRIVER_PACKAGE_NAME}-${DRIVER_VERSION}/configure/${CONFIGURE_MODULE}" - COMPONENT ${DRIVER_KMOD_COMPONENT_NAME}) + install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/build.sh" + "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/test.c" + "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile" + "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile.inc" + DESTINATION + "src/${DRIVER_PACKAGE_NAME}-${DRIVER_VERSION}/configure/${CONFIGURE_MODULE}" + COMPONENT ${DRIVER_KMOD_COMPONENT_NAME} + ) endif() endif() endforeach() - set(DRIVER_SOURCES dynamic_params_table.c event_table.c @@ -159,44 +165,51 @@ foreach(FILENAME IN LISTS DRIVER_SOURCES) configure_file(${FILENAME} src/${FILENAME} COPYONLY) endforeach() -# make can be self-referenced as $(MAKE) only from Makefiles but this -# triggers syntax errors with other generators such as Ninja +# make can be self-referenced as $(MAKE) only from Makefiles but this triggers syntax errors with +# other generators such as Ninja if(${CMAKE_GENERATOR} STREQUAL "Unix Makefiles") set(MAKE_COMMAND "$(MAKE)") else() set(MAKE_COMMAND "make") endif() -# This if/else is needed because you currently cannot manipulate dependencies -# of built-in targets like "all" in CMake: -# http://public.kitware.com/Bug/view.php?id=8438 +# This if/else is needed because you currently cannot manipulate dependencies of built-in targets +# like "all" in CMake: http://public.kitware.com/Bug/view.php?id=8438 if(BUILD_DRIVER) - add_custom_target(driver ALL + add_custom_target( + driver ALL COMMAND ${MAKE_COMMAND} - COMMAND "${CMAKE_COMMAND}" -E copy_if_different ${DRIVER_NAME}.ko "${CMAKE_CURRENT_BINARY_DIR}" + COMMAND "${CMAKE_COMMAND}" -E copy_if_different ${DRIVER_NAME}.ko + "${CMAKE_CURRENT_BINARY_DIR}" WORKING_DIRECTORY src - VERBATIM) + VERBATIM + ) else() - add_custom_target(driver + add_custom_target( + driver COMMAND ${MAKE_COMMAND} - COMMAND "${CMAKE_COMMAND}" -E copy_if_different ${DRIVER_NAME}.ko "${CMAKE_CURRENT_BINARY_DIR}" + COMMAND "${CMAKE_COMMAND}" -E copy_if_different ${DRIVER_NAME}.ko + "${CMAKE_CURRENT_BINARY_DIR}" WORKING_DIRECTORY src - VERBATIM) + VERBATIM + ) endif() -add_custom_target(install_driver +add_custom_target( + install_driver COMMAND ${MAKE_COMMAND} install DEPENDS driver WORKING_DIRECTORY src - VERBATIM) + VERBATIM +) if(ENABLE_DKMS) - install(FILES ${CMAKE_CURRENT_BINARY_DIR}/src/Makefile - ${CMAKE_CURRENT_BINARY_DIR}/src/dkms.conf - ${CMAKE_CURRENT_BINARY_DIR}/src/driver_config.h - ${DRIVER_SOURCES} + install( + FILES ${CMAKE_CURRENT_BINARY_DIR}/src/Makefile ${CMAKE_CURRENT_BINARY_DIR}/src/dkms.conf + ${CMAKE_CURRENT_BINARY_DIR}/src/driver_config.h ${DRIVER_SOURCES} DESTINATION "src/${DRIVER_PACKAGE_NAME}-${DRIVER_VERSION}" - COMPONENT ${DRIVER_KMOD_COMPONENT_NAME}) + COMPONENT ${DRIVER_KMOD_COMPONENT_NAME} + ) endif() add_subdirectory(bpf) diff --git a/driver/bpf/CMakeLists.txt b/driver/bpf/CMakeLists.txt index 8bf65b0dc6..af502b30e2 100644 --- a/driver/bpf/CMakeLists.txt +++ b/driver/bpf/CMakeLists.txt @@ -2,8 +2,8 @@ # # Copyright (C) 2023 The Falco Authors. # -# This file is dual licensed under either the MIT or GPL 2. See -# MIT.txt or GPL.txt for full copies of the license. +# This file is dual licensed under either the MIT or GPL 2. See MIT.txt or GPL.txt for full copies +# of the license. # configure_file(../driver_config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/../driver_config.h) @@ -16,15 +16,20 @@ if(BUILD_BPF) set(bpf_min_kver_map_aarch64 4.17) set(bpf_min_kver_map_s390x 5.5) set(bpf_min_kver_map_ppc64le 5.1) - if (LINUX_KERNEL_VERSION VERSION_LESS ${bpf_min_kver_map_${TARGET_ARCH}}) - message(WARNING "[BPF] To run this driver you need a Linux kernel version >= ${bpf_min_kver_map_${TARGET_ARCH}} but actual kernel version is: ${UNAME_RESULT}") + if(LINUX_KERNEL_VERSION VERSION_LESS ${bpf_min_kver_map_${TARGET_ARCH}}) + message( + WARNING + "[BPF] To run this driver you need a Linux kernel version >= ${bpf_min_kver_map_${TARGET_ARCH}} but actual kernel version is: ${UNAME_RESULT}" + ) endif() - add_custom_target(bpf ALL - COMMAND make - COMMAND "${CMAKE_COMMAND}" -E copy_if_different probe.o "${CMAKE_CURRENT_BINARY_DIR}" - WORKING_DIRECTORY src - VERBATIM) + add_custom_target( + bpf ALL + COMMAND make + COMMAND "${CMAKE_COMMAND}" -E copy_if_different probe.o "${CMAKE_CURRENT_BINARY_DIR}" + WORKING_DIRECTORY src + VERBATIM + ) endif() set(BPF_SOURCES @@ -51,16 +56,16 @@ file(GLOB DRIVER_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/../*.h) list(APPEND BPF_SOURCES ${DRIVER_HEADERS}) set(INSTALL_SET "") -# Copy all needed sources under src folder in current binary dir -# and add them to the set of installed files +# Copy all needed sources under src folder in current binary dir and add them to the set of +# installed files foreach(SOURCE IN LISTS BPF_SOURCES) get_filename_component(FILENAME ${SOURCE} NAME) configure_file(${SOURCE} src/${FILENAME} COPYONLY) list(APPEND INSTALL_SET ${CMAKE_CURRENT_BINARY_DIR}/src/${FILENAME}) endforeach() -install(FILES - ${INSTALL_SET} +install( + FILES ${INSTALL_SET} DESTINATION "src/${DRIVER_PACKAGE_NAME}-${DRIVER_VERSION}/bpf" COMPONENT ${DRIVER_BPF_COMPONENT_NAME} ) @@ -72,16 +77,20 @@ file(GLOB configure_modules "${CMAKE_CURRENT_SOURCE_DIR}/configure/*") foreach(subdir ${configure_modules}) if(IS_DIRECTORY "${subdir}") file(RELATIVE_PATH CONFIGURE_MODULE "${CMAKE_CURRENT_SOURCE_DIR}/configure" "${subdir}") - configure_file(configure/${CONFIGURE_MODULE}/test.c src/configure/${CONFIGURE_MODULE}/test.c COPYONLY) + configure_file( + configure/${CONFIGURE_MODULE}/test.c src/configure/${CONFIGURE_MODULE}/test.c COPYONLY + ) configure_file(configure/Makefile src/configure/${CONFIGURE_MODULE}/Makefile COPYONLY) configure_file(configure/build.sh src/configure/${CONFIGURE_MODULE}/build.sh COPYONLY) configure_file(configure/Makefile.inc.in src/configure/${CONFIGURE_MODULE}/Makefile.inc) - install(FILES - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/build.sh" - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/test.c" - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile" - "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile.inc" - DESTINATION "src/${DRIVER_PACKAGE_NAME}-${DRIVER_VERSION}/bpf/configure/${CONFIGURE_MODULE}" - COMPONENT ${DRIVER_BPF_COMPONENT_NAME}) + install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/build.sh" + "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/test.c" + "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile" + "${CMAKE_CURRENT_BINARY_DIR}/src/configure/${CONFIGURE_MODULE}/Makefile.inc" + DESTINATION + "src/${DRIVER_PACKAGE_NAME}-${DRIVER_VERSION}/bpf/configure/${CONFIGURE_MODULE}" + COMPONENT ${DRIVER_BPF_COMPONENT_NAME} + ) endif() -endforeach() \ No newline at end of file +endforeach() diff --git a/driver/bpf/bpf_helpers.h b/driver/bpf/bpf_helpers.h index 14ba02c5c0..38e6102df6 100644 --- a/driver/bpf/bpf_helpers.h +++ b/driver/bpf/bpf_helpers.h @@ -10,102 +10,99 @@ or GPL2.txt for full copies of the license. #ifndef __BPF_HELPERS_H #define __BPF_HELPERS_H -static void *(*bpf_map_lookup_elem)(void *map, void *key) = - (void *)BPF_FUNC_map_lookup_elem; -static int (*bpf_map_update_elem)(void *map, void *key, void *value, - unsigned long long flags) = - (void *)BPF_FUNC_map_update_elem; -static int (*bpf_map_delete_elem)(void *map, void *key) = - (void *)BPF_FUNC_map_delete_elem; -static int (*bpf_probe_read)(void *dst, int size, void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read; +static void *(*bpf_map_lookup_elem)(void *map, void *key) = (void *)BPF_FUNC_map_lookup_elem; +static int (*bpf_map_update_elem)(void *map, + void *key, + void *value, + unsigned long long flags) = (void *)BPF_FUNC_map_update_elem; +static int (*bpf_map_delete_elem)(void *map, void *key) = (void *)BPF_FUNC_map_delete_elem; +static int (*bpf_probe_read)(void *dst, int size, void *unsafe_ptr) = (void *)BPF_FUNC_probe_read; -/* Introduced in linux 5.8, see https://github.com/torvalds/linux/commit/71d19214776e61b33da48f7c1b46e522c7f78221 */ -#if LINUX_VERSION_CODE >= KERNEL_VERSION(5,8,0) -static unsigned long long (*bpf_ktime_get_boot_ns)(void) = - (void *)BPF_FUNC_ktime_get_boot_ns; +/* Introduced in linux 5.8, see + * https://github.com/torvalds/linux/commit/71d19214776e61b33da48f7c1b46e522c7f78221 */ +#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 8, 0) +static unsigned long long (*bpf_ktime_get_boot_ns)(void) = (void *)BPF_FUNC_ktime_get_boot_ns; #else /* fallback at using old, non suspend-time aware, helper */ -static unsigned long long (*bpf_ktime_get_boot_ns)(void) = - (void *)BPF_FUNC_ktime_get_ns; +static unsigned long long (*bpf_ktime_get_boot_ns)(void) = (void *)BPF_FUNC_ktime_get_ns; #endif -static int (*bpf_trace_printk)(const char *fmt, int fmt_size, ...) = - (void *)BPF_FUNC_trace_printk; -static void (*bpf_tail_call)(void *ctx, void *map, int index) = - (void *)BPF_FUNC_tail_call; -static unsigned long long (*bpf_get_smp_processor_id)(void) = - (void *)BPF_FUNC_get_smp_processor_id; -static unsigned long long (*bpf_get_current_pid_tgid)(void) = - (void *)BPF_FUNC_get_current_pid_tgid; -static unsigned long long (*bpf_get_current_uid_gid)(void) = - (void *)BPF_FUNC_get_current_uid_gid; -static int (*bpf_get_current_comm)(void *buf, int buf_size) = - (void *)BPF_FUNC_get_current_comm; -static int (*bpf_perf_event_read)(void *map, int index) = - (void *)BPF_FUNC_perf_event_read; -static int (*bpf_clone_redirect)(void *ctx, int ifindex, int flags) = - (void *)BPF_FUNC_clone_redirect; -static int (*bpf_redirect)(int ifindex, int flags) = - (void *)BPF_FUNC_redirect; -static int (*bpf_perf_event_output)(void *ctx, void *map, - unsigned long long flags, void *data, - int size) = - (void *)BPF_FUNC_perf_event_output; -static int (*bpf_get_stackid)(void *ctx, void *map, int flags) = - (void *)BPF_FUNC_get_stackid; -static int (*bpf_probe_write_user)(void *dst, void *src, int size) = - (void *)BPF_FUNC_probe_write_user; -static int (*bpf_current_task_under_cgroup)(void *map, int index) = - (void *)BPF_FUNC_current_task_under_cgroup; -static int (*bpf_skb_get_tunnel_key)(void *ctx, void *key, int size, int flags) = - (void *)BPF_FUNC_skb_get_tunnel_key; -static int (*bpf_skb_set_tunnel_key)(void *ctx, void *key, int size, int flags) = - (void *)BPF_FUNC_skb_set_tunnel_key; -static int (*bpf_skb_get_tunnel_opt)(void *ctx, void *md, int size) = - (void *)BPF_FUNC_skb_get_tunnel_opt; -static int (*bpf_skb_set_tunnel_opt)(void *ctx, void *md, int size) = - (void *)BPF_FUNC_skb_set_tunnel_opt; -static unsigned long long (*bpf_get_prandom_u32)(void) = - (void *)BPF_FUNC_get_prandom_u32; -static int (*bpf_xdp_adjust_head)(void *ctx, int offset) = - (void *)BPF_FUNC_xdp_adjust_head; -static int (*bpf_probe_read_str)(void *dst, uint64_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read_str; +static int (*bpf_trace_printk)(const char *fmt, int fmt_size, ...) = (void *)BPF_FUNC_trace_printk; +static void (*bpf_tail_call)(void *ctx, void *map, int index) = (void *)BPF_FUNC_tail_call; +static unsigned long long (*bpf_get_smp_processor_id)(void) = (void *)BPF_FUNC_get_smp_processor_id; +static unsigned long long (*bpf_get_current_pid_tgid)(void) = (void *)BPF_FUNC_get_current_pid_tgid; +static unsigned long long (*bpf_get_current_uid_gid)(void) = (void *)BPF_FUNC_get_current_uid_gid; +static int (*bpf_get_current_comm)(void *buf, int buf_size) = (void *)BPF_FUNC_get_current_comm; +static int (*bpf_perf_event_read)(void *map, int index) = (void *)BPF_FUNC_perf_event_read; +static int (*bpf_clone_redirect)(void *ctx, + int ifindex, + int flags) = (void *)BPF_FUNC_clone_redirect; +static int (*bpf_redirect)(int ifindex, int flags) = (void *)BPF_FUNC_redirect; +static int (*bpf_perf_event_output)(void *ctx, + void *map, + unsigned long long flags, + void *data, + int size) = (void *)BPF_FUNC_perf_event_output; +static int (*bpf_get_stackid)(void *ctx, void *map, int flags) = (void *)BPF_FUNC_get_stackid; +static int (*bpf_probe_write_user)(void *dst, + void *src, + int size) = (void *)BPF_FUNC_probe_write_user; +static int (*bpf_current_task_under_cgroup)(void *map, + int index) = (void *)BPF_FUNC_current_task_under_cgroup; +static int (*bpf_skb_get_tunnel_key)(void *ctx, void *key, int size, int flags) = (void *) + BPF_FUNC_skb_get_tunnel_key; +static int (*bpf_skb_set_tunnel_key)(void *ctx, void *key, int size, int flags) = (void *) + BPF_FUNC_skb_set_tunnel_key; +static int (*bpf_skb_get_tunnel_opt)(void *ctx, + void *md, + int size) = (void *)BPF_FUNC_skb_get_tunnel_opt; +static int (*bpf_skb_set_tunnel_opt)(void *ctx, + void *md, + int size) = (void *)BPF_FUNC_skb_set_tunnel_opt; +static unsigned long long (*bpf_get_prandom_u32)(void) = (void *)BPF_FUNC_get_prandom_u32; +static int (*bpf_xdp_adjust_head)(void *ctx, int offset) = (void *)BPF_FUNC_xdp_adjust_head; +static int (*bpf_probe_read_str)(void *dst, + uint64_t size, + const void *unsafe_ptr) = (void *)BPF_FUNC_probe_read_str; #if defined(USE_BPF_PROBE_KERNEL_USER_VARIANTS) -static int (*bpf_probe_read_user)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read_user; -static int (*bpf_probe_read_kernel)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read_kernel; -static int (*bpf_probe_read_user_str)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read_user_str; -static int (*bpf_probe_read_kernel_str)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read_kernel_str; +static int (*bpf_probe_read_user)(void *dst, + uint32_t size, + const void *unsafe_ptr) = (void *)BPF_FUNC_probe_read_user; +static int (*bpf_probe_read_kernel)(void *dst, + uint32_t size, + const void *unsafe_ptr) = (void *)BPF_FUNC_probe_read_kernel; +static int (*bpf_probe_read_user_str)(void *dst, uint32_t size, const void *unsafe_ptr) = (void *) + BPF_FUNC_probe_read_user_str; +static int (*bpf_probe_read_kernel_str)(void *dst, uint32_t size, const void *unsafe_ptr) = (void *) + BPF_FUNC_probe_read_kernel_str; #else -static int (*bpf_probe_read_user)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read; -static int (*bpf_probe_read_kernel)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read; -static int (*bpf_probe_read_user_str)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read_str; -static int (*bpf_probe_read_kernel_str)(void *dst, uint32_t size, const void *unsafe_ptr) = - (void *)BPF_FUNC_probe_read_str; +static int (*bpf_probe_read_user)(void *dst, + uint32_t size, + const void *unsafe_ptr) = (void *)BPF_FUNC_probe_read; +static int (*bpf_probe_read_kernel)(void *dst, + uint32_t size, + const void *unsafe_ptr) = (void *)BPF_FUNC_probe_read; +static int (*bpf_probe_read_user_str)(void *dst, + uint32_t size, + const void *unsafe_ptr) = (void *)BPF_FUNC_probe_read_str; +static int (*bpf_probe_read_kernel_str)(void *dst, + uint32_t size, + const void *unsafe_ptr) = (void *)BPF_FUNC_probe_read_str; #endif -static uint64_t (*bpf_get_current_task)(void) = - (void *)BPF_FUNC_get_current_task; -static int (*bpf_skb_load_bytes)(void *ctx, int off, void *to, int len) = - (void *)BPF_FUNC_skb_load_bytes; -static int (*bpf_skb_store_bytes)(void *ctx, int off, void *from, int len, int flags) = - (void *)BPF_FUNC_skb_store_bytes; -static int (*bpf_l3_csum_replace)(void *ctx, int off, int from, int to, int flags) = - (void *)BPF_FUNC_l3_csum_replace; -static int (*bpf_l4_csum_replace)(void *ctx, int off, int from, int to, int flags) = - (void *)BPF_FUNC_l4_csum_replace; -static int (*bpf_skb_under_cgroup)(void *ctx, void *map, int index) = - (void *)BPF_FUNC_skb_under_cgroup; -static int (*bpf_skb_change_head)(void *, int len, int flags) = - (void *)BPF_FUNC_skb_change_head; +static uint64_t (*bpf_get_current_task)(void) = (void *)BPF_FUNC_get_current_task; +static int (*bpf_skb_load_bytes)(void *ctx, int off, void *to, int len) = (void *) + BPF_FUNC_skb_load_bytes; +static int (*bpf_skb_store_bytes)(void *ctx, int off, void *from, int len, int flags) = (void *) + BPF_FUNC_skb_store_bytes; +static int (*bpf_l3_csum_replace)(void *ctx, int off, int from, int to, int flags) = (void *) + BPF_FUNC_l3_csum_replace; +static int (*bpf_l4_csum_replace)(void *ctx, int off, int from, int to, int flags) = (void *) + BPF_FUNC_l4_csum_replace; +static int (*bpf_skb_under_cgroup)(void *ctx, + void *map, + int index) = (void *)BPF_FUNC_skb_under_cgroup; +static int (*bpf_skb_change_head)(void *, int len, int flags) = (void *)BPF_FUNC_skb_change_head; #endif diff --git a/driver/bpf/builtins.h b/driver/bpf/builtins.h index 229a087a6e..ef08066b0e 100644 --- a/driver/bpf/builtins.h +++ b/driver/bpf/builtins.h @@ -28,4 +28,4 @@ or GPL2.txt for full copies of the license. #endif #define memcpy __builtin_memcpy -#endif // __BUILTINS_H +#endif // __BUILTINS_H diff --git a/driver/bpf/configure/RSS_STAT_ARRAY/test.c b/driver/bpf/configure/RSS_STAT_ARRAY/test.c index d102f7a132..96f4dac48b 100644 --- a/driver/bpf/configure/RSS_STAT_ARRAY/test.c +++ b/driver/bpf/configure/RSS_STAT_ARRAY/test.c @@ -10,7 +10,8 @@ or GPL2.txt for full copies of the license. /* * Check that mm_struct's field `rss_stat` is an array. - * See 6.2 kernel commit: https://github.com/torvalds/linux/commit/f1a7941243c102a44e8847e3b94ff4ff3ec56f25 + * See 6.2 kernel commit: + * https://github.com/torvalds/linux/commit/f1a7941243c102a44e8847e3b94ff4ff3ec56f25 */ #include "../../quirks.h" @@ -20,8 +21,7 @@ or GPL2.txt for full copies of the license. // struct mm_struct declaration #include -BPF_PROBE("signal/", signal_deliver, signal_deliver_args) -{ +BPF_PROBE("signal/", signal_deliver, signal_deliver_args) { long val; struct mm_struct *mm; val = mm->rss_stat[0].count; diff --git a/driver/bpf/filler_helpers.h b/driver/bpf/filler_helpers.h index 34a0b88a63..b12524dfd0 100644 --- a/driver/bpf/filler_helpers.h +++ b/driver/bpf/filler_helpers.h @@ -24,32 +24,28 @@ or GPL2.txt for full copies of the license. #include "missing_definitions.h" /* Helper used to please the verifier with operations on the number of arguments */ -#define SAFE_ARG_NUMBER(x) x & (PPM_MAX_EVENT_PARAMS - 1) +#define SAFE_ARG_NUMBER(x) x &(PPM_MAX_EVENT_PARAMS - 1) /* This enum is used to tell our helpers if they have to * read from kernel or user memory. */ -enum read_memory -{ +enum read_memory { USER = 0, KERNEL = 1, }; -static __always_inline struct inode *get_file_inode(struct file *file) -{ - if (file) { +static __always_inline struct inode *get_file_inode(struct file *file) { + if(file) { return _READ(file->f_inode); } return NULL; } -static __always_inline bool in_port_range(uint16_t port, uint16_t min, uint16_t max) -{ +static __always_inline bool in_port_range(uint16_t port, uint16_t min, uint16_t max) { return port >= min && port <= max; } -static __always_inline struct file *bpf_fget(int fd) -{ +static __always_inline struct file *bpf_fget(int fd) { struct task_struct *task; struct files_struct *files; struct fdtable *fdt; @@ -58,19 +54,19 @@ static __always_inline struct file *bpf_fget(int fd) struct file *fil; task = (struct task_struct *)bpf_get_current_task(); - if (!task) + if(!task) return NULL; files = _READ(task->files); - if (!files) + if(!files) return NULL; fdt = _READ(files->fdt); - if (!fdt) + if(!fdt) return NULL; max_fds = _READ(fdt->max_fds); - if (fd >= max_fds) + if(fd >= max_fds) return NULL; fds = _READ(fdt->fd); @@ -79,25 +75,22 @@ static __always_inline struct file *bpf_fget(int fd) return fil; } -static __always_inline uint32_t bpf_get_fd_fmode_created(int fd) -{ - if(fd < 0) - { - return 0; - } +static __always_inline uint32_t bpf_get_fd_fmode_created(int fd) { + if(fd < 0) { + return 0; + } /* FMODE_CREATED flag was introduced in kernel 4.19 and it's not present in earlier versions */ #if LINUX_VERSION_CODE > KERNEL_VERSION(4, 19, 0) - struct file *file; - file = bpf_fget(fd); - if(file) - { - fmode_t fmode = _READ(file->f_mode); - if (fmode & FMODE_CREATED) - return PPM_O_F_CREATED; - } + struct file *file; + file = bpf_fget(fd); + if(file) { + fmode_t fmode = _READ(file->f_mode); + if(fmode & FMODE_CREATED) + return PPM_O_F_CREATED; + } #endif - return 0; + return 0; } /* In this kernel version the instruction limit was bumped from 131072 to 1000000. @@ -146,8 +139,7 @@ static __always_inline uint32_t bpf_get_fd_fmode_created(int fd) * Take a look at the research that led to this implementation: * https://github.com/falcosecurity/libs/issues/1111 */ -static __always_inline char *bpf_d_path_approx(struct filler_data *data, struct path *path) -{ +static __always_inline char *bpf_d_path_approx(struct filler_data *data, struct path *path) { struct path f_path = {}; bpf_probe_read_kernel(&f_path, sizeof(struct path), path); struct dentry *dentry = f_path.dentry; @@ -170,21 +162,17 @@ static __always_inline char *bpf_d_path_approx(struct filler_data *data, struct char terminator = '\0'; #pragma unroll - for(int i = 0; i < MAX_NUM_COMPONENTS; i++) - { + for(int i = 0; i < MAX_NUM_COMPONENTS; i++) { bpf_probe_read_kernel(&d_parent, sizeof(struct dentry *), &(dentry->d_parent)); - if(dentry == d_parent && dentry != mnt_root_p) - { + if(dentry == d_parent && dentry != mnt_root_p) { /* We reached the root (dentry == d_parent) * but not the mount root...there is something weird, stop here. */ break; } - if(dentry == mnt_root_p) - { - if(mnt_p != mnt_parent_p) - { + if(dentry == mnt_root_p) { + if(mnt_p != mnt_parent_p) { /* We reached root, but not global root - continue with mount point path */ bpf_probe_read_kernel(&dentry, sizeof(struct dentry *), &mnt_p->mnt_mountpoint); bpf_probe_read_kernel(&mnt_p, sizeof(struct mount *), &mnt_p->mnt_parent); @@ -192,9 +180,7 @@ static __always_inline char *bpf_d_path_approx(struct filler_data *data, struct vfsmnt = &mnt_p->mnt; bpf_probe_read_kernel(&mnt_root_p, sizeof(struct dentry *), &(vfsmnt->mnt_root)); continue; - } - else - { + } else { /* We have the full path, stop here */ break; } @@ -209,17 +195,17 @@ static __always_inline char *bpf_d_path_approx(struct filler_data *data, struct */ current_off = max_buf_len - (d_name.len + 1); - effective_name_len = - bpf_probe_read_kernel_str(&(data->tmp_scratch[SAFE_TMP_SCRATCH_ACCESS(current_off)]), - MAX_COMPONENT_LEN, (void *)d_name.name); + effective_name_len = bpf_probe_read_kernel_str( + &(data->tmp_scratch[SAFE_TMP_SCRATCH_ACCESS(current_off)]), + MAX_COMPONENT_LEN, + (void *)d_name.name); /* This check shouldn't be necessary, right now we * keep it just to be extra safe. Unfortunately, it causes * verifier issues on s390x (5.15.0-75-generic Ubuntu s390x) */ #ifndef CONFIG_S390 - if(effective_name_len <= 1) - { + if(effective_name_len <= 1) { /* If effective_name_len is 0 or 1 we have an error * (path can't be null nor an empty string) */ @@ -232,14 +218,15 @@ static __always_inline char *bpf_d_path_approx(struct filler_data *data, struct * 3. Then we set `max_buf_len` to the last written char. */ max_buf_len -= 1; - bpf_probe_read_kernel(&(data->tmp_scratch[SAFE_TMP_SCRATCH_ACCESS(max_buf_len)]), 1, &slash); + bpf_probe_read_kernel(&(data->tmp_scratch[SAFE_TMP_SCRATCH_ACCESS(max_buf_len)]), + 1, + &slash); max_buf_len -= (effective_name_len - 1); dentry = d_parent; } - if(max_buf_len == MAX_TMP_SCRATCH_LEN) - { + if(max_buf_len == MAX_TMP_SCRATCH_LEN) { /* memfd files have no path in the filesystem so we never decremented the `max_buf_len` */ bpf_probe_read_kernel(&d_name, sizeof(struct qstr), &(dentry->d_name)); bpf_probe_read_kernel_str(&(data->tmp_scratch[0]), MAX_COMPONENT_LEN, (void *)d_name.name); @@ -253,119 +240,114 @@ static __always_inline char *bpf_d_path_approx(struct filler_data *data, struct /* Null terminate the path string. * Replace the first `/` we added in the loop with `\0` */ - bpf_probe_read_kernel(&(data->tmp_scratch[SAFE_TMP_SCRATCH_ACCESS(MAX_TMP_SCRATCH_LEN - 1)]), 1, &terminator); + bpf_probe_read_kernel(&(data->tmp_scratch[SAFE_TMP_SCRATCH_ACCESS(MAX_TMP_SCRATCH_LEN - 1)]), + 1, + &terminator); return &(data->tmp_scratch[SAFE_TMP_SCRATCH_ACCESS(max_buf_len)]); } -static __always_inline struct socket *bpf_sockfd_lookup(struct filler_data *data, - int fd) -{ +static __always_inline struct socket *bpf_sockfd_lookup(struct filler_data *data, int fd) { struct file *file; const struct file_operations *fop; struct socket *sock; - if (!data->settings->socket_file_ops) + if(!data->settings->socket_file_ops) return NULL; file = bpf_fget(fd); - if (!file) + if(!file) return NULL; fop = _READ(file->f_op); - if (fop != data->settings->socket_file_ops) + if(fop != data->settings->socket_file_ops) return NULL; sock = _READ(file->private_data); return sock; } -static __always_inline unsigned long bpf_encode_dev(dev_t dev) -{ +static __always_inline unsigned long bpf_encode_dev(dev_t dev) { unsigned int major = MAJOR(dev); unsigned int minor = MINOR(dev); return (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12); } -static __always_inline void bpf_get_ino_from_fd(int fd, unsigned long *ino) -{ +static __always_inline void bpf_get_ino_from_fd(int fd, unsigned long *ino) { struct super_block *sb; struct inode *inode; struct file *file; dev_t kdev; - if (fd < 0) + if(fd < 0) return; file = bpf_fget(fd); - if (!file) + if(!file) return; inode = _READ(file->f_inode); - if (!inode) + if(!inode) return; *ino = _READ(inode->i_ino); } -static __always_inline enum ppm_overlay get_overlay_layer(struct file *file) -{ - if (!file) - { +static __always_inline enum ppm_overlay get_overlay_layer(struct file *file) { + if(!file) { return PPM_NOT_OVERLAY_FS; } - struct dentry* dentry = NULL; + struct dentry *dentry = NULL; bpf_probe_read_kernel(&dentry, sizeof(dentry), &file->f_path.dentry); - struct super_block* sb = (struct super_block*)_READ(dentry->d_sb); + struct super_block *sb = (struct super_block *)_READ(dentry->d_sb); unsigned long sb_magic = _READ(sb->s_magic); - if(sb_magic != PPM_OVERLAYFS_SUPER_MAGIC) - { + if(sb_magic != PPM_OVERLAYFS_SUPER_MAGIC) { return PPM_NOT_OVERLAY_FS; } char *vfs_inode = (char *)_READ(dentry->d_inode); struct dentry *upper_dentry = NULL; - bpf_probe_read_kernel(&upper_dentry, sizeof(upper_dentry), (char *)vfs_inode + sizeof(struct inode)); - if(!upper_dentry) - { + bpf_probe_read_kernel(&upper_dentry, + sizeof(upper_dentry), + (char *)vfs_inode + sizeof(struct inode)); + if(!upper_dentry) { return PPM_OVERLAY_LOWER; } struct inode *upper_ino = _READ(upper_dentry->d_inode); - if(_READ(upper_ino->i_ino) != 0) - { + if(_READ(upper_ino->i_ino) != 0) { return PPM_OVERLAY_UPPER; - } - else - { + } else { return PPM_OVERLAY_LOWER; } } -static __always_inline void bpf_get_dev_ino_overlay_from_fd(int fd, unsigned long *dev, unsigned long *ino, enum ppm_overlay *ol) -{ +static __always_inline void bpf_get_dev_ino_overlay_from_fd(int fd, + unsigned long *dev, + unsigned long *ino, + enum ppm_overlay *ol) { struct super_block *sb; struct inode *inode; dev_t kdev; struct file *file; - if (fd < 0) + if(fd < 0) return; file = bpf_fget(fd); - if (!file) + if(!file) return; *ol = get_overlay_layer(file); inode = _READ(file->f_inode); - if (!inode) + if(!inode) return; sb = _READ(inode->i_sb); - if (!sb) + if(!sb) return; kdev = _READ(sb->s_dev); @@ -374,40 +356,37 @@ static __always_inline void bpf_get_dev_ino_overlay_from_fd(int fd, unsigned lon *ino = _READ(inode->i_ino); } -static __always_inline bool bpf_ipv6_addr_any(const struct in6_addr *a) -{ +static __always_inline bool bpf_ipv6_addr_any(const struct in6_addr *a) { const unsigned long *ul = (const unsigned long *)a; return (ul[0] | ul[1]) == 0UL; } static __always_inline bool bpf_getsockname(struct socket *sock, - struct sockaddr_storage *addr, - int peer) -{ + struct sockaddr_storage *addr, + int peer) { struct sock *sk; sa_family_t family; sk = _READ(sock->sk); - if (!sk) + if(!sk) return false; family = _READ(sk->sk_family); - switch (family) { - case AF_INET: - { - struct inet_sock *inet = (struct inet_sock *)sk; + switch(family) { + case AF_INET: { + struct inet_sock *inet = (struct inet_sock *)sk; struct sockaddr_in *sin = (struct sockaddr_in *)addr; sin->sin_family = AF_INET; - if (peer) { + if(peer) { sin->sin_port = _READ(inet->inet_dport); sin->sin_addr.s_addr = _READ(inet->inet_daddr); } else { uint32_t addr = _READ(inet->inet_rcv_saddr); - if (!addr) + if(!addr) addr = _READ(inet->inet_saddr); sin->sin_port = _READ(inet->inet_sport); sin->sin_addr.s_addr = addr; @@ -415,8 +394,7 @@ static __always_inline bool bpf_getsockname(struct socket *sock, break; } - case AF_INET6: - { + case AF_INET6: { struct sockaddr_in6 *sin = (struct sockaddr_in6 *)addr; struct inet_sock *inet = (struct inet_sock *)sk; struct ipv6_pinfo { @@ -425,40 +403,39 @@ static __always_inline bool bpf_getsockname(struct socket *sock, struct ipv6_pinfo *np = (struct ipv6_pinfo *)_READ(inet->pinet6); sin->sin6_family = AF_INET6; - if (peer) { + if(peer) { sin->sin6_port = _READ(inet->inet_dport); sin->sin6_addr = _READ(sk->sk_v6_daddr); } else { sin->sin6_addr = _READ(sk->sk_v6_rcv_saddr); - if (bpf_ipv6_addr_any(&sin->sin6_addr)) + if(bpf_ipv6_addr_any(&sin->sin6_addr)) sin->sin6_addr = _READ(np->saddr); sin->sin6_port = _READ(inet->inet_sport); } break; } - case AF_UNIX: - { + case AF_UNIX: { struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr; struct unix_sock *u; struct unix_address *addr; - if (peer) + if(peer) sk = _READ(((struct unix_sock *)sk)->peer); u = (struct unix_sock *)sk; addr = _READ(u->addr); - if (!addr) { + if(!addr) { sunaddr->sun_family = AF_UNIX; sunaddr->sun_path[0] = 0; } else { unsigned int len = _READ(addr->len); - if (len > sizeof(struct sockaddr_storage)) + if(len > sizeof(struct sockaddr_storage)) len = sizeof(struct sockaddr_storage); #ifdef BPF_FORBIDS_ZERO_ACCESS - if (len > 0) + if(len > 0) bpf_probe_read_kernel(sunaddr, ((len - 1) & 0xff) + 1, addr->name); #else bpf_probe_read_kernel(sunaddr, len, addr->name); @@ -474,20 +451,18 @@ static __always_inline bool bpf_getsockname(struct socket *sock, return true; } -static __always_inline int bpf_addr_to_kernel(void *uaddr, int ulen, - struct sockaddr *kaddr) -{ - int len = ulen & 0xfff; /* required by BPF verifier */ +static __always_inline int bpf_addr_to_kernel(void *uaddr, int ulen, struct sockaddr *kaddr) { + int len = ulen & 0xfff; /* required by BPF verifier */ - if (len < 0 || len > sizeof(struct sockaddr_storage)) + if(len < 0 || len > sizeof(struct sockaddr_storage)) return -EINVAL; - if (len == 0) + if(len == 0) return 0; #ifdef BPF_FORBIDS_ZERO_ACCESS - if (bpf_probe_read_user(kaddr, ((len - 1) & 0xff) + 1, uaddr)) + if(bpf_probe_read_user(kaddr, ((len - 1) & 0xff) + 1, uaddr)) #else - if (bpf_probe_read_user(kaddr, len & 0xff, uaddr)) + if(bpf_probe_read_user(kaddr, len & 0xff, uaddr)) #endif return -EFAULT; @@ -496,8 +471,8 @@ static __always_inline int bpf_addr_to_kernel(void *uaddr, int ulen, #define get_buf(x) data->buf[(data->state->tail_ctx.curoff + (x)) & SCRATCH_SIZE_HALF] -static __always_inline uint32_t bpf_compute_snaplen(struct filler_data *data, uint32_t lookahead_size) -{ +static __always_inline uint32_t bpf_compute_snaplen(struct filler_data *data, + uint32_t lookahead_size) { uint32_t res = data->settings->snaplen; if(!data->settings->do_dynamic_snaplen) @@ -519,8 +494,7 @@ static __always_inline uint32_t bpf_compute_snaplen(struct filler_data *data, ui uint16_t port_remote = 0; uint16_t socket_family = _READ(sk->sk_family); - if(socket_family == AF_INET || socket_family == AF_INET6) - { + if(socket_family == AF_INET || socket_family == AF_INET6) { struct inet_sock *inet = (struct inet_sock *)sk; port_local = _READ(inet->inet_sport); port_remote = _READ(sk->__sk_common.skc_dport); @@ -528,23 +502,19 @@ static __always_inline uint32_t bpf_compute_snaplen(struct filler_data *data, ui port_remote = ntohs(port_remote); struct sockaddr *sockaddr = NULL; - switch(data->state->tail_ctx.evt_type) - { + switch(data->state->tail_ctx.evt_type) { case PPME_SOCKET_SENDTO_X: case PPME_SOCKET_RECVFROM_X: sockaddr = (struct sockaddr *)bpf_syscall_get_argument(data, 4); break; case PPME_SOCKET_RECVMSG_X: - case PPME_SOCKET_SENDMSG_X: - { + case PPME_SOCKET_SENDMSG_X: { unsigned long mh_p = bpf_syscall_get_argument(data, 1); #ifdef CONFIG_COMPAT - if(bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { struct compat_msghdr compat_mh = {}; - if(likely(bpf_probe_read_user(&compat_mh, sizeof(compat_mh), (void *)mh_p) == 0)) - { + if(likely(bpf_probe_read_user(&compat_mh, sizeof(compat_mh), (void *)mh_p) == 0)) { sockaddr = (struct sockaddr *)(unsigned long)(compat_mh.msg_name); } // in any case we break the switch. @@ -552,27 +522,21 @@ static __always_inline uint32_t bpf_compute_snaplen(struct filler_data *data, ui } #endif struct user_msghdr mh = {}; - if(bpf_probe_read_user(&mh, sizeof(mh), (void *)mh_p) == 0) - { + if(bpf_probe_read_user(&mh, sizeof(mh), (void *)mh_p) == 0) { sockaddr = (struct sockaddr *)mh.msg_name; - } - } - break; + } + } break; default: break; } - if(port_remote == 0 && sockaddr != NULL) - { - if(socket_family == AF_INET) - { + if(port_remote == 0 && sockaddr != NULL) { + if(socket_family == AF_INET) { struct sockaddr_in sockaddr_in = {}; bpf_probe_read_user(&sockaddr_in, sizeof(sockaddr_in), sockaddr); port_remote = ntohs(sockaddr_in.sin_port); - } - else - { + } else { struct sockaddr_in6 sockaddr_in6 = {}; bpf_probe_read_user(&sockaddr_in6, sizeof(sockaddr_in6), sockaddr); port_remote = ntohs(sockaddr_in6.sin6_port); @@ -583,57 +547,48 @@ static __always_inline uint32_t bpf_compute_snaplen(struct filler_data *data, ui uint16_t min_port = data->settings->fullcapture_port_range_start; uint16_t max_port = data->settings->fullcapture_port_range_end; - if(max_port > 0 && (in_port_range(port_local, min_port, max_port) || in_port_range(port_remote, min_port, max_port))) - { + if(max_port > 0 && (in_port_range(port_local, min_port, max_port) || + in_port_range(port_remote, min_port, max_port))) { return res > SNAPLEN_FULLCAPTURE_PORT ? res : SNAPLEN_FULLCAPTURE_PORT; - } - else if(port_remote == data->settings->statsd_port) - { + } else if(port_remote == data->settings->statsd_port) { return res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; - } - else if(port_remote == PPM_PORT_DNS) - { + } else if(port_remote == PPM_PORT_DNS) { return res > SNAPLEN_DNS_UDP ? res : SNAPLEN_DNS_UDP; - } - else if((port_local == PPM_PORT_MYSQL || port_remote == PPM_PORT_MYSQL) && lookahead_size >= 5) - { - if((get_buf(0) == 3 || get_buf(1) == 3 || get_buf(2) == 3 || get_buf(3) == 3 || get_buf(4) == 3) || - (get_buf(2) == 0 && get_buf(3) == 0)) - { + } else if((port_local == PPM_PORT_MYSQL || port_remote == PPM_PORT_MYSQL) && + lookahead_size >= 5) { + if((get_buf(0) == 3 || get_buf(1) == 3 || get_buf(2) == 3 || get_buf(3) == 3 || + get_buf(4) == 3) || + (get_buf(2) == 0 && get_buf(3) == 0)) { return res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; } - } - else if((port_local == PPM_PORT_POSTGRES || port_remote == PPM_PORT_POSTGRES) && lookahead_size >= 7) - { - if((get_buf(0) == 'Q' && get_buf(1) == 0) || /* SimpleQuery command */ - (get_buf(0) == 'P' && get_buf(1) == 0) || /* Prepare statement command */ + } else if((port_local == PPM_PORT_POSTGRES || port_remote == PPM_PORT_POSTGRES) && + lookahead_size >= 7) { + if((get_buf(0) == 'Q' && get_buf(1) == 0) || /* SimpleQuery command */ + (get_buf(0) == 'P' && get_buf(1) == 0) || /* Prepare statement command */ (get_buf(4) == 0 && get_buf(5) == 3 && get_buf(6) == 0) || /* startup command */ - (get_buf(0) == 'E' && get_buf(1) == 0) /* error or execute command */ - ) - { + (get_buf(0) == 'E' && get_buf(1) == 0) /* error or execute command */ + ) { return res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; } - } - else if((port_local == PPM_PORT_MONGODB || port_remote == PPM_PORT_MONGODB) || - (lookahead_size >= 16 && (*(int32_t *)&get_buf(12) == 1 || /* matches header */ - *(int32_t *)&get_buf(12) == 2001 || *(int32_t *)&get_buf(12) == 2002 || - *(int32_t *)&get_buf(12) == 2003 || *(int32_t *)&get_buf(12) == 2004 || - *(int32_t *)&get_buf(12) == 2005 || *(int32_t *)&get_buf(12) == 2006 || - *(int32_t *)&get_buf(12) == 2007))) - { + } else if((port_local == PPM_PORT_MONGODB || port_remote == PPM_PORT_MONGODB) || + (lookahead_size >= 16 && + (*(int32_t *)&get_buf(12) == 1 || /* matches header */ + *(int32_t *)&get_buf(12) == 2001 || *(int32_t *)&get_buf(12) == 2002 || + *(int32_t *)&get_buf(12) == 2003 || *(int32_t *)&get_buf(12) == 2004 || + *(int32_t *)&get_buf(12) == 2005 || *(int32_t *)&get_buf(12) == 2006 || + *(int32_t *)&get_buf(12) == 2007))) { return res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; - } - else if(lookahead_size >= 5) - { + } else if(lookahead_size >= 5) { uint32_t buf = *(uint32_t *)&get_buf(0); #ifdef CONFIG_S390 buf = __builtin_bswap32(buf); #endif - if(buf == BPF_HTTP_GET || buf == BPF_HTTP_POST || buf == BPF_HTTP_PUT || buf == BPF_HTTP_DELETE || - buf == BPF_HTTP_TRACE || buf == BPF_HTTP_CONNECT || buf == BPF_HTTP_OPTIONS || - (buf == BPF_HTTP_PREFIX && data->buf[(data->state->tail_ctx.curoff + 4) & SCRATCH_SIZE_HALF] == '/')) - { // "HTTP/" + if(buf == BPF_HTTP_GET || buf == BPF_HTTP_POST || buf == BPF_HTTP_PUT || + buf == BPF_HTTP_DELETE || buf == BPF_HTTP_TRACE || buf == BPF_HTTP_CONNECT || + buf == BPF_HTTP_OPTIONS || + (buf == BPF_HTTP_PREFIX && + data->buf[(data->state->tail_ctx.curoff + 4) & SCRATCH_SIZE_HALF] == '/')) { // "HTTP/" return res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; } } @@ -641,31 +596,28 @@ static __always_inline uint32_t bpf_compute_snaplen(struct filler_data *data, ui } static __always_inline int unix_socket_path(char *dest, const char *user_ptr, size_t size) { - int res = bpf_probe_read_kernel_str(dest, - size, - user_ptr); + int res = bpf_probe_read_kernel_str(dest, size, user_ptr); /* - * Extract from: https://man7.org/linux/man-pages/man7/unix.7.html + * Extract from: https://man7.org/linux/man-pages/man7/unix.7.html * an abstract socket address is distinguished (from a * pathname socket) by the fact that sun_path[0] is a null byte * ('\0'). The socket's address in this namespace is given by * the additional bytes in sun_path that are covered by the * specified length of the address structure. */ - if (res == 1) { + if(res == 1) { dest[0] = '@'; res = bpf_probe_read_kernel_str(dest + 1, - size - 1, // account for '@' - user_ptr + 1); - res++; // account for '@' + size - 1, // account for '@' + user_ptr + 1); + res++; // account for '@' } return res; } static __always_inline uint16_t bpf_pack_addr(struct filler_data *data, - struct sockaddr *usrsockaddr, - int ulen) -{ + struct sockaddr *usrsockaddr, + int ulen) { uint32_t ip; uint16_t port; sa_family_t family = usrsockaddr->sa_family; @@ -676,7 +628,7 @@ static __always_inline uint16_t bpf_pack_addr(struct filler_data *data, char *dest; int res; - switch (family) { + switch(family) { case AF_INET: /* * Map the user-provided address to a sockaddr_in @@ -717,7 +669,8 @@ static __always_inline uint16_t bpf_pack_addr(struct filler_data *data, data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF] = socket_family_to_scap(family); memcpy(&data->buf[(data->state->tail_ctx.curoff + 1) & SCRATCH_SIZE_HALF], - usrsockaddr_in6->sin6_addr.s6_addr, 16); + usrsockaddr_in6->sin6_addr.s6_addr, + 16); memcpy(&data->buf[(data->state->tail_ctx.curoff + 17) & SCRATCH_SIZE_HALF], &port, 2); break; @@ -731,7 +684,7 @@ static __always_inline uint16_t bpf_pack_addr(struct filler_data *data, * Put a 0 at the end of struct sockaddr_un because * the user might not have considered it in the length */ - if (ulen == sizeof(struct sockaddr_storage)) + if(ulen == sizeof(struct sockaddr_storage)) ((char *)usrsockaddr_un)[(ulen - 1) & SCRATCH_SIZE_MAX] = 0; else ((char *)usrsockaddr_un)[ulen & SCRATCH_SIZE_MAX] = 0; @@ -744,8 +697,8 @@ static __always_inline uint16_t bpf_pack_addr(struct filler_data *data, data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF] = socket_family_to_scap(family); res = unix_socket_path(&data->buf[(data->state->tail_ctx.curoff + 1) & SCRATCH_SIZE_HALF], - usrsockaddr_un->sun_path, - UNIX_PATH_MAX); + usrsockaddr_un->sun_path, + UNIX_PATH_MAX); size += res; @@ -759,13 +712,12 @@ static __always_inline uint16_t bpf_pack_addr(struct filler_data *data, } static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, - int fd, - struct sockaddr *usrsockaddr, - int ulen, - bool use_userdata, - bool is_inbound, - char *tmp_area) -{ + int fd, + struct sockaddr *usrsockaddr, + int ulen, + bool use_userdata, + bool is_inbound, + char *tmp_area) { struct sockaddr_storage *sock_address; struct sockaddr_storage *peer_address; unsigned short family; @@ -775,32 +727,31 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, struct in6_addr in6 = {0}; sock = bpf_sockfd_lookup(data, fd); - if (!sock) + if(!sock) return 0; sock_address = (struct sockaddr_storage *)tmp_area; peer_address = (struct sockaddr_storage *)tmp_area + 1; - if (!bpf_getsockname(sock, sock_address, 0)) + if(!bpf_getsockname(sock, sock_address, 0)) return 0; sk = _READ(sock->sk); - if (!sk) + if(!sk) return 0; family = _READ(sk->sk_family); - switch (family) { - case AF_INET: - { + switch(family) { + case AF_INET: { uint32_t sip; uint32_t dip; uint16_t sport; uint16_t dport; - if (!use_userdata) { - if (bpf_getsockname(sock, peer_address, 1)) { - if (is_inbound) { + if(!use_userdata) { + if(bpf_getsockname(sock, peer_address, 1)) { + if(is_inbound) { sip = ((struct sockaddr_in *)peer_address)->sin_addr.s_addr; sport = ntohs(((struct sockaddr_in *)peer_address)->sin_port); dip = ((struct sockaddr_in *)sock_address)->sin_addr.s_addr; @@ -820,7 +771,7 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, } else { struct sockaddr_in *usrsockaddr_in = (struct sockaddr_in *)usrsockaddr; - if (is_inbound) { + if(is_inbound) { /* To take peer address info we try to use the kernel where possible. * TCP allows us to obtain the right information, while the kernel doesn't fill * `sk->__sk_common.skc_daddr` for UDP connection. @@ -829,14 +780,11 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, * structs. */ bpf_probe_read_kernel(&sport, sizeof(sport), &sk->__sk_common.skc_dport); - if(sport != 0) - { + if(sport != 0) { /* We can read from the kernel */ bpf_probe_read_kernel(&sip, sizeof(sip), &sk->__sk_common.skc_daddr); sport = ntohs(sport); - } - else - { + } else { /* Fallback to userspace struct */ sip = usrsockaddr_in->sin_addr.s_addr; sport = ntohs(usrsockaddr_in->sin_port); @@ -861,16 +809,15 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, break; } - case AF_INET6: - { + case AF_INET6: { uint8_t *sip6; uint8_t *dip6; uint16_t sport; uint16_t dport; - if (!use_userdata) { - if (bpf_getsockname(sock, peer_address, 1)) { - if (is_inbound) { + if(!use_userdata) { + if(bpf_getsockname(sock, peer_address, 1)) { + if(is_inbound) { sip6 = ((struct sockaddr_in6 *)peer_address)->sin6_addr.s6_addr; sport = ntohs(((struct sockaddr_in6 *)peer_address)->sin6_port); dip6 = ((struct sockaddr_in6 *)sock_address)->sin6_addr.s6_addr; @@ -894,17 +841,14 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, */ struct sockaddr_in6 *usrsockaddr_in6 = (struct sockaddr_in6 *)usrsockaddr; - if (is_inbound) { + if(is_inbound) { bpf_probe_read_kernel(&sport, sizeof(sport), &sk->__sk_common.skc_dport); - if(sport != 0) - { + if(sport != 0) { /* We can read from the kernel */ bpf_probe_read_kernel(&in6, sizeof(in6), &sk->__sk_common.skc_v6_daddr); sip6 = in6.in6_u.u6_addr8; sport = ntohs(sport); - } - else - { + } else { /* Fallback to userspace struct */ sip6 = usrsockaddr_in6->sin6_addr.s6_addr; sport = ntohs(usrsockaddr_in6->sin6_port); @@ -932,8 +876,7 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, break; } - case AF_UNIX: - { + case AF_UNIX: { /* * Retrieve the addresses */ @@ -943,9 +886,11 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF] = socket_family_to_scap(family); - if (is_inbound) { + if(is_inbound) { memcpy(&data->buf[(data->state->tail_ctx.curoff + 1) & SCRATCH_SIZE_HALF], &us, 8); - memcpy(&data->buf[(data->state->tail_ctx.curoff + 1 + 8) & SCRATCH_SIZE_HALF], &speer, 8); + memcpy(&data->buf[(data->state->tail_ctx.curoff + 1 + 8) & SCRATCH_SIZE_HALF], + &speer, + 8); } else { memcpy(&data->buf[(data->state->tail_ctx.curoff + 1) & SCRATCH_SIZE_HALF], &speer, 8); memcpy(&data->buf[(data->state->tail_ctx.curoff + 1 + 8) & SCRATCH_SIZE_HALF], &us, 8); @@ -956,8 +901,8 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, */ size = 1 + 8 + 8; - if (!use_userdata) { - if (is_inbound) { + if(!use_userdata) { + if(is_inbound) { us_name = ((struct sockaddr_un *)sock_address)->sun_path; } else { bpf_getsockname(sock, peer_address, 1); @@ -973,20 +918,21 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, * Put a 0 at the end of struct sockaddr_un because * the user might not have considered it in the length */ - if (ulen == sizeof(struct sockaddr_storage)) + if(ulen == sizeof(struct sockaddr_storage)) ((char *)usrsockaddr_un)[(ulen - 1) & SCRATCH_SIZE_MAX] = 0; else ((char *)usrsockaddr_un)[ulen & SCRATCH_SIZE_MAX] = 0; - if (is_inbound) + if(is_inbound) us_name = ((struct sockaddr_un *)sock_address)->sun_path; else us_name = usrsockaddr_un->sun_path; } - int res = unix_socket_path(&data->buf[(data->state->tail_ctx.curoff + 1 + 8 + 8) & SCRATCH_SIZE_HALF], - us_name, - UNIX_PATH_MAX); + int res = unix_socket_path( + &data->buf[(data->state->tail_ctx.curoff + 1 + 8 + 8) & SCRATCH_SIZE_HALF], + us_name, + UNIX_PATH_MAX); size += res; @@ -998,16 +944,15 @@ static __always_inline long bpf_fd_to_socktuple(struct filler_data *data, } static __always_inline int __bpf_read_val_into(struct filler_data *data, - unsigned long curoff_bounded, - unsigned long val, - volatile uint16_t read_size, - enum read_memory mem) -{ + unsigned long curoff_bounded, + unsigned long val, + volatile uint16_t read_size, + enum read_memory mem) { int rc; int read_size_bound; #ifdef BPF_FORBIDS_ZERO_ACCESS - if (read_size == 0) + if(read_size == 0) return -1; read_size_bound = ((read_size - 1) & SCRATCH_SIZE_HALF) + 1; @@ -1015,37 +960,31 @@ static __always_inline int __bpf_read_val_into(struct filler_data *data, read_size_bound = read_size & SCRATCH_SIZE_HALF; #endif - if (mem == KERNEL) - rc = bpf_probe_read_kernel(&data->buf[curoff_bounded], - read_size_bound, - (void *)val); + if(mem == KERNEL) + rc = bpf_probe_read_kernel(&data->buf[curoff_bounded], read_size_bound, (void *)val); else - rc = bpf_probe_read_user(&data->buf[curoff_bounded], - read_size_bound, - (void *)val); + rc = bpf_probe_read_user(&data->buf[curoff_bounded], read_size_bound, (void *)val); return rc; } static __always_inline int __bpf_val_to_ring(struct filler_data *data, - unsigned long val, - unsigned long val_len, - enum ppm_param_type type, - uint8_t dyn_idx, - bool enforce_snaplen, - enum read_memory mem) -{ + unsigned long val, + unsigned long val_len, + enum ppm_param_type type, + uint8_t dyn_idx, + bool enforce_snaplen, + enum read_memory mem) { unsigned int len_dyn = 0; unsigned int len = 0; unsigned long curoff_bounded = 0; curoff_bounded = data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF; - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } - if (dyn_idx != (uint8_t)-1) { + if(dyn_idx != (uint8_t)-1) { *((uint8_t *)&data->buf[curoff_bounded]) = dyn_idx; len_dyn = sizeof(uint8_t); data->state->tail_ctx.curoff += len_dyn; @@ -1053,71 +992,59 @@ static __always_inline int __bpf_val_to_ring(struct filler_data *data, } curoff_bounded = data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF; - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } - switch (type) { + switch(type) { case PT_CHARBUF: case PT_FSPATH: case PT_FSRELPATH: { - if (!data->curarg_already_on_frame) - { + if(!data->curarg_already_on_frame) { int res = -1; - if (val) + if(val) /* Return `res<0` only in case of error. */ res = (mem == KERNEL) ? bpf_probe_read_kernel_str(&data->buf[curoff_bounded], - PPM_MAX_ARG_SIZE, - (const void *)val) - : bpf_probe_read_user_str(&data->buf[curoff_bounded], - PPM_MAX_ARG_SIZE, - (const void *)val); - if(res >= 0) - { + PPM_MAX_ARG_SIZE, + (const void *)val) + : bpf_probe_read_user_str(&data->buf[curoff_bounded], + PPM_MAX_ARG_SIZE, + (const void *)val); + if(res >= 0) { len = res; - } - else - { + } else { /* This should be already `0`, but just to be future-proof. */ len = 0; } - } - else - { + } else { len = val_len; } break; } case PT_BYTEBUF: { - if(data->curarg_already_on_frame || (val && val_len)) - { + if(data->curarg_already_on_frame || (val && val_len)) { len = val_len; - if(enforce_snaplen) - { + if(enforce_snaplen) { uint32_t dpi_lookahead_size = DPI_LOOKAHEAD_SIZE; unsigned int sl; - if(dpi_lookahead_size > len) - { + if(dpi_lookahead_size > len) { dpi_lookahead_size = len; } - if(!data->curarg_already_on_frame) - { - /* We need to read the first `dpi_lookahead_size` bytes. - * If we are not able to read at least `dpi_lookahead_size` + if(!data->curarg_already_on_frame) { + /* We need to read the first `dpi_lookahead_size` bytes. + * If we are not able to read at least `dpi_lookahead_size` * we send an empty param `len=0`. */ volatile uint16_t read_size = dpi_lookahead_size; int rc = 0; rc = __bpf_read_val_into(data, curoff_bounded, val, read_size, mem); - if (rc) - { - len=0; + if(rc) { + len = 0; break; } } @@ -1126,36 +1053,30 @@ static __always_inline int __bpf_val_to_ring(struct filler_data *data, * so we can understand how many bytes of the `curarg` we have to consider. */ sl = bpf_compute_snaplen(data, dpi_lookahead_size); - if(len > sl) - { + if(len > sl) { len = sl; } } - if (len > PPM_MAX_ARG_SIZE) + if(len > PPM_MAX_ARG_SIZE) len = PPM_MAX_ARG_SIZE; - if(!data->curarg_already_on_frame) - { + if(!data->curarg_already_on_frame) { volatile uint16_t read_size = len; int rc = 0; curoff_bounded = data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF; - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } rc = __bpf_read_val_into(data, curoff_bounded, val, read_size, mem); - if (rc) - { - len=0; + if(rc) { + len = 0; break; } } - } - else - { + } else { /* Handle NULL pointers */ len = 0; } @@ -1164,22 +1085,21 @@ static __always_inline int __bpf_val_to_ring(struct filler_data *data, case PT_SOCKADDR: case PT_SOCKTUPLE: case PT_FDLIST: - if(data->curarg_already_on_frame) - { + if(data->curarg_already_on_frame) { len = val_len; break; } /* Cases in which we don't have the tuple and * we want to send an empty param. */ - else if(val==0) - { + else if(val == 0) { len = 0; break; } bpf_printk("expected arg already on frame: evt_type %d, curarg %d, type %d\n", - data->state->tail_ctx.evt_type, - data->state->tail_ctx.curarg, type); + data->state->tail_ctx.evt_type, + data->state->tail_ctx.curarg, + type); return PPM_FAILURE_BUG; case PT_FLAGS8: @@ -1233,13 +1153,13 @@ static __always_inline int __bpf_val_to_ring(struct filler_data *data, break; default: { bpf_printk("unhandled type in bpf_val_to_ring: evt_type %d, curarg %d, type %d\n", - data->state->tail_ctx.evt_type, - data->state->tail_ctx.curarg, type); + data->state->tail_ctx.evt_type, + data->state->tail_ctx.curarg, + type); return PPM_FAILURE_BUG; } } - if (len_dyn + len > PPM_MAX_ARG_SIZE) - { + if(len_dyn + len > PPM_MAX_ARG_SIZE) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -1252,8 +1172,7 @@ static __always_inline int __bpf_val_to_ring(struct filler_data *data, return PPM_SUCCESS; } -static __always_inline int bpf_push_empty_param(struct filler_data *data) -{ +static __always_inline int bpf_push_empty_param(struct filler_data *data) { /* We push 0 in the length array */ fixup_evt_arg_len(data->buf, data->state->tail_ctx.curarg, 0); data->curarg_already_on_frame = false; @@ -1263,15 +1182,13 @@ static __always_inline int bpf_push_empty_param(struct filler_data *data) return PPM_SUCCESS; } -static __always_inline enum read_memory param_type_to_mem(enum ppm_param_type type) -{ +static __always_inline enum read_memory param_type_to_mem(enum ppm_param_type type) { /* __bpf_val_to_ring() uses bpf_probe_read_* functions for particular types * only. Instead of changing all places, let's keep it simple and try to * spot the correct address space by type. */ - switch (type) - { + switch(type) { case PT_CHARBUF: case PT_FSPATH: case PT_FSRELPATH: @@ -1289,12 +1206,11 @@ static __always_inline enum read_memory param_type_to_mem(enum ppm_param_type ty } static __always_inline int bpf_val_to_ring_mem(struct filler_data *data, - unsigned long val, - enum read_memory mem) -{ + unsigned long val, + enum read_memory mem) { const struct ppm_param_info *param_info; - if (data->state->tail_ctx.curarg >= PPM_MAX_EVENT_PARAMS) { + if(data->state->tail_ctx.curarg >= PPM_MAX_EVENT_PARAMS) { bpf_printk("invalid curarg: %d\n", data->state->tail_ctx.curarg); return PPM_FAILURE_BUG; } @@ -1305,11 +1221,9 @@ static __always_inline int bpf_val_to_ring_mem(struct filler_data *data, } /// TODO: @Andreagit97 these functions should return void -static __always_inline int bpf_push_s64_to_ring(struct filler_data *data, int64_t val) -{ +static __always_inline int bpf_push_s64_to_ring(struct filler_data *data, int64_t val) { /// TODO: @Andreagit97 this could be removed in a second iteration. - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(int64_t); @@ -1324,10 +1238,8 @@ static __always_inline int bpf_push_s64_to_ring(struct filler_data *data, int64_ return PPM_SUCCESS; } -static __always_inline int bpf_push_u64_to_ring(struct filler_data *data, uint64_t val) -{ - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { +static __always_inline int bpf_push_u64_to_ring(struct filler_data *data, uint64_t val) { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(uint64_t); @@ -1341,10 +1253,8 @@ static __always_inline int bpf_push_u64_to_ring(struct filler_data *data, uint64 return PPM_SUCCESS; } -static __always_inline int bpf_push_u32_to_ring(struct filler_data *data, uint32_t val) -{ - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { +static __always_inline int bpf_push_u32_to_ring(struct filler_data *data, uint32_t val) { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(uint32_t); @@ -1358,10 +1268,8 @@ static __always_inline int bpf_push_u32_to_ring(struct filler_data *data, uint32 return PPM_SUCCESS; } -static __always_inline int bpf_push_s32_to_ring(struct filler_data *data, int32_t val) -{ - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { +static __always_inline int bpf_push_s32_to_ring(struct filler_data *data, int32_t val) { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(int32_t); @@ -1375,10 +1283,8 @@ static __always_inline int bpf_push_s32_to_ring(struct filler_data *data, int32_ return PPM_SUCCESS; } -static __always_inline int bpf_push_u16_to_ring(struct filler_data *data, uint16_t val) -{ - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { +static __always_inline int bpf_push_u16_to_ring(struct filler_data *data, uint16_t val) { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(uint16_t); @@ -1392,10 +1298,8 @@ static __always_inline int bpf_push_u16_to_ring(struct filler_data *data, uint16 return PPM_SUCCESS; } -static __always_inline int bpf_push_s16_to_ring(struct filler_data *data, int16_t val) -{ - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { +static __always_inline int bpf_push_s16_to_ring(struct filler_data *data, int16_t val) { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(int16_t); @@ -1409,10 +1313,8 @@ static __always_inline int bpf_push_s16_to_ring(struct filler_data *data, int16_ return PPM_SUCCESS; } -static __always_inline int bpf_push_u8_to_ring(struct filler_data *data, uint8_t val) -{ - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { +static __always_inline int bpf_push_u8_to_ring(struct filler_data *data, uint8_t val) { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(uint8_t); @@ -1426,10 +1328,8 @@ static __always_inline int bpf_push_u8_to_ring(struct filler_data *data, uint8_t return PPM_SUCCESS; } -static __always_inline int bpf_push_s8_to_ring(struct filler_data *data, int16_t val) -{ - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { +static __always_inline int bpf_push_s8_to_ring(struct filler_data *data, int16_t val) { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } const unsigned int len = sizeof(int8_t); @@ -1443,60 +1343,64 @@ static __always_inline int bpf_push_s8_to_ring(struct filler_data *data, int16_t return PPM_SUCCESS; } -static __always_inline int bpf_val_to_ring(struct filler_data *data, - unsigned long val) -{ +static __always_inline int bpf_val_to_ring(struct filler_data *data, unsigned long val) { const struct ppm_param_info *param_info; /// TODO this is something we want to enforce at test time, not runtime - if (data->state->tail_ctx.curarg >= PPM_MAX_EVENT_PARAMS) { + if(data->state->tail_ctx.curarg >= PPM_MAX_EVENT_PARAMS) { bpf_printk("invalid curarg: %d\n", data->state->tail_ctx.curarg); return PPM_FAILURE_BUG; } param_info = &data->evt->params[data->state->tail_ctx.curarg & (PPM_MAX_EVENT_PARAMS - 1)]; - return __bpf_val_to_ring(data, val, 0, param_info->type, -1, false, - param_type_to_mem(param_info->type)); + return __bpf_val_to_ring(data, + val, + 0, + param_info->type, + -1, + false, + param_type_to_mem(param_info->type)); } static __always_inline int bpf_val_to_ring_len(struct filler_data *data, - unsigned long val, - unsigned long val_len) -{ + unsigned long val, + unsigned long val_len) { const struct ppm_param_info *param_info; - if (data->state->tail_ctx.curarg >= PPM_MAX_EVENT_PARAMS) { + if(data->state->tail_ctx.curarg >= PPM_MAX_EVENT_PARAMS) { bpf_printk("invalid curarg: %d\n", data->state->tail_ctx.curarg); return PPM_FAILURE_BUG; } param_info = &data->evt->params[data->state->tail_ctx.curarg & (PPM_MAX_EVENT_PARAMS - 1)]; - return __bpf_val_to_ring(data, val, val_len, param_info->type, -1, false, - param_type_to_mem(param_info->type)); + return __bpf_val_to_ring(data, + val, + val_len, + param_info->type, + -1, + false, + param_type_to_mem(param_info->type)); } static __always_inline int bpf_val_to_ring_dyn(struct filler_data *data, - unsigned long val, - enum ppm_param_type type, - uint8_t dyn_idx) -{ + unsigned long val, + enum ppm_param_type type, + uint8_t dyn_idx) { return __bpf_val_to_ring(data, val, 0, type, dyn_idx, false, param_type_to_mem(type)); } static __always_inline int bpf_val_to_ring_type_mem(struct filler_data *data, - unsigned long val, - enum ppm_param_type type, - enum read_memory mem) -{ + unsigned long val, + enum ppm_param_type type, + enum read_memory mem) { return __bpf_val_to_ring(data, val, 0, type, -1, false, mem); } static __always_inline int bpf_val_to_ring_type(struct filler_data *data, - unsigned long val, - enum ppm_param_type type) -{ + unsigned long val, + enum ppm_param_type type) { return __bpf_val_to_ring(data, val, 0, type, -1, false, param_type_to_mem(type)); } diff --git a/driver/bpf/fillers.h b/driver/bpf/fillers.h index d6f56250d6..623c834940 100644 --- a/driver/bpf/fillers.h +++ b/driver/bpf/fillers.h @@ -19,10 +19,10 @@ or GPL2.txt for full copies of the license. #include #include - -/* Linux kernel 4.15 introduced the new const `UID_GID_MAP_MAX_BASE_EXTENTS` in place of - * the old `UID_GID_MAP_MAX_EXTENTS`, which instead has changed its meaning. - * For more info see https://github.com/torvalds/linux/commit/6397fac4915ab3002dc15aae751455da1a852f25 +/* Linux kernel 4.15 introduced the new const `UID_GID_MAP_MAX_BASE_EXTENTS` in place of + * the old `UID_GID_MAP_MAX_EXTENTS`, which instead has changed its meaning. + * For more info see + * https://github.com/torvalds/linux/commit/6397fac4915ab3002dc15aae751455da1a852f25 */ #ifndef UID_GID_MAP_MAX_BASE_EXTENTS #define UID_GID_MAP_MAX_BASE_EXTENTS 5 @@ -34,247 +34,243 @@ or GPL2.txt for full copies of the license. */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) #include - struct timespec { - int32_t tv_sec; - int32_t tv_nsec; - }; - - struct timeval { - int32_t tv_sec; - int32_t tv_usec; - }; - typedef struct old_timespec32 old_timespec32; +struct timespec { + int32_t tv_sec; + int32_t tv_nsec; +}; + +struct timeval { + int32_t tv_sec; + int32_t tv_usec; +}; +typedef struct old_timespec32 old_timespec32; +#else +#if __has_include() +#include #else - #if __has_include() - #include - #else - #include - #endif - #define timeval64 timeval - typedef struct compat_timespec old_timespec32; +#include +#endif +#define timeval64 timeval +typedef struct compat_timespec old_timespec32; #endif -#define FILLER_RAW(x) \ -static __always_inline int __bpf_##x(struct filler_data *data); \ - \ -__bpf_section(TP_NAME "filler/" #x) \ -static __always_inline int bpf_##x(void *ctx) \ - -#define FILLER(x, is_syscall) \ -static __always_inline int __bpf_##x(struct filler_data *data); \ - \ -__bpf_section(TP_NAME "filler/" #x) \ -static __always_inline int bpf_##x(void *ctx) \ -{ \ - struct filler_data data = {0}; \ - int res; \ - \ - res = init_filler_data(ctx, &data, is_syscall); \ - if (res == PPM_SUCCESS) { \ - if (!data.state->tail_ctx.len) \ - write_evt_hdr(&data); \ - res = __bpf_##x(&data); \ - } \ - \ - if (res == PPM_SUCCESS) \ - res = push_evt_frame(ctx, &data); \ - \ - if (data.state) \ - data.state->tail_ctx.prev_res = res; \ - \ - bpf_tail_call(ctx, &tail_map, PPM_FILLER_terminate_filler); \ - bpf_printk("Can't tail call terminate filler\n"); \ - return 0; \ -} \ - \ -static __always_inline int __bpf_##x(struct filler_data *data) \ - -FILLER_RAW(terminate_filler) -{ +#define FILLER_RAW(x) \ + static __always_inline int __bpf_##x(struct filler_data *data); \ + \ + __bpf_section(TP_NAME "filler/" #x) static __always_inline int bpf_##x(void *ctx) + +#define FILLER(x, is_syscall) \ + static __always_inline int __bpf_##x(struct filler_data *data); \ + \ + __bpf_section(TP_NAME "filler/" #x) static __always_inline int bpf_##x(void *ctx) { \ + struct filler_data data = {0}; \ + int res; \ + \ + res = init_filler_data(ctx, &data, is_syscall); \ + if(res == PPM_SUCCESS) { \ + if(!data.state->tail_ctx.len) \ + write_evt_hdr(&data); \ + res = __bpf_##x(&data); \ + } \ + \ + if(res == PPM_SUCCESS) \ + res = push_evt_frame(ctx, &data); \ + \ + if(data.state) \ + data.state->tail_ctx.prev_res = res; \ + \ + bpf_tail_call(ctx, &tail_map, PPM_FILLER_terminate_filler); \ + bpf_printk("Can't tail call terminate filler\n"); \ + return 0; \ + } \ + \ + static __always_inline int __bpf_##x(struct filler_data *data) + +FILLER_RAW(terminate_filler) { struct scap_bpf_per_cpu_state *state; state = get_local_state(bpf_get_smp_processor_id()); - if (!state) + if(!state) return 0; - switch (state->tail_ctx.prev_res) { + switch(state->tail_ctx.prev_res) { case PPM_SUCCESS: break; case PPM_FAILURE_BUFFER_FULL: bpf_printk("PPM_FAILURE_BUFFER_FULL event=%d curarg=%d\n", - state->tail_ctx.evt_type, - state->tail_ctx.curarg); - if (state->n_drops_buffer != ULLONG_MAX) { + state->tail_ctx.evt_type, + state->tail_ctx.curarg); + if(state->n_drops_buffer != ULLONG_MAX) { ++state->n_drops_buffer; } - switch (state->tail_ctx.evt_type) { - // enter - case PPME_SYSCALL_OPEN_E: - case PPME_SYSCALL_CREAT_E: - case PPME_SYSCALL_OPENAT_2_E: - case PPME_SYSCALL_OPENAT2_E: - case PPME_SYSCALL_OPEN_BY_HANDLE_AT_E: - if (state->n_drops_buffer_open_enter != ULLONG_MAX) { - ++state->n_drops_buffer_open_enter; - } - break; - case PPME_SYSCALL_DUP_E: - case PPME_SYSCALL_CHMOD_E: - case PPME_SYSCALL_FCHMOD_E: - case PPME_SYSCALL_FCHMODAT_E: - case PPME_SYSCALL_CHOWN_E: - case PPME_SYSCALL_LCHOWN_E: - case PPME_SYSCALL_FCHOWN_E: - case PPME_SYSCALL_FCHOWNAT_E: - case PPME_SYSCALL_LINK_2_E: - case PPME_SYSCALL_LINKAT_2_E: - case PPME_SYSCALL_MKDIR_2_E: - case PPME_SYSCALL_MKDIRAT_E: - case PPME_SYSCALL_MOUNT_E: - case PPME_SYSCALL_UMOUNT_1_E: - case PPME_SYSCALL_UMOUNT2_E: - case PPME_SYSCALL_RENAME_E: - case PPME_SYSCALL_RENAMEAT_E: - case PPME_SYSCALL_RENAMEAT2_E: - case PPME_SYSCALL_RMDIR_2_E: - case PPME_SYSCALL_SYMLINK_E: - case PPME_SYSCALL_SYMLINKAT_E: - case PPME_SYSCALL_UNLINK_2_E: - case PPME_SYSCALL_UNLINKAT_2_E: - if (state->n_drops_buffer_dir_file_enter != ULLONG_MAX) { - ++state->n_drops_buffer_dir_file_enter; - } - break; - case PPME_SYSCALL_CLONE_20_E: - case PPME_SYSCALL_CLONE3_E: - case PPME_SYSCALL_FORK_20_E: - case PPME_SYSCALL_VFORK_20_E: - if (state->n_drops_buffer_clone_fork_enter != ULLONG_MAX) { - ++state->n_drops_buffer_clone_fork_enter; - } - break; - case PPME_SYSCALL_EXECVE_19_E: - case PPME_SYSCALL_EXECVEAT_E: - if (state->n_drops_buffer_execve_enter != ULLONG_MAX) { - ++state->n_drops_buffer_execve_enter; - } - break; - case PPME_SOCKET_CONNECT_E: - if (state->n_drops_buffer_connect_enter != ULLONG_MAX) { - ++state->n_drops_buffer_connect_enter; - } - break; - case PPME_SYSCALL_BPF_2_E: - case PPME_SYSCALL_SETPGID_E: - case PPME_SYSCALL_PTRACE_E: - case PPME_SYSCALL_SECCOMP_E: - case PPME_SYSCALL_SETNS_E: - case PPME_SYSCALL_SETRESGID_E: - case PPME_SYSCALL_SETRESUID_E: - case PPME_SYSCALL_SETSID_E: - case PPME_SYSCALL_UNSHARE_E: - case PPME_SYSCALL_CAPSET_E: - if (state->n_drops_buffer_other_interest_enter != ULLONG_MAX) { - ++state->n_drops_buffer_other_interest_enter; - } - break; - case PPME_PROCEXIT_1_E: - if (state->n_drops_buffer_proc_exit != ULLONG_MAX) { - ++state->n_drops_buffer_proc_exit; - } - break; - // exit - case PPME_SYSCALL_OPEN_X: - case PPME_SYSCALL_CREAT_X: - case PPME_SYSCALL_OPENAT_2_X: - case PPME_SYSCALL_OPENAT2_X: - case PPME_SYSCALL_OPEN_BY_HANDLE_AT_X: - if (state->n_drops_buffer_open_exit != ULLONG_MAX) { - ++state->n_drops_buffer_open_exit; - } - break; - case PPME_SYSCALL_DUP_X: - case PPME_SYSCALL_CHMOD_X: - case PPME_SYSCALL_FCHMOD_X: - case PPME_SYSCALL_FCHMODAT_X: - case PPME_SYSCALL_CHOWN_X: - case PPME_SYSCALL_LCHOWN_X: - case PPME_SYSCALL_FCHOWN_X: - case PPME_SYSCALL_FCHOWNAT_X: - case PPME_SYSCALL_LINK_2_X: - case PPME_SYSCALL_LINKAT_2_X: - case PPME_SYSCALL_MKDIR_2_X: - case PPME_SYSCALL_MKDIRAT_X: - case PPME_SYSCALL_MOUNT_X: - case PPME_SYSCALL_UMOUNT_1_X: - case PPME_SYSCALL_UMOUNT2_X: - case PPME_SYSCALL_RENAME_X: - case PPME_SYSCALL_RENAMEAT_X: - case PPME_SYSCALL_RENAMEAT2_X: - case PPME_SYSCALL_RMDIR_2_X: - case PPME_SYSCALL_SYMLINK_X: - case PPME_SYSCALL_SYMLINKAT_X: - case PPME_SYSCALL_UNLINK_2_X: - case PPME_SYSCALL_UNLINKAT_2_X: - if (state->n_drops_buffer_dir_file_exit != ULLONG_MAX) { - ++state->n_drops_buffer_dir_file_exit; - } - break; - case PPME_SYSCALL_CLONE_20_X: - case PPME_SYSCALL_CLONE3_X: - case PPME_SYSCALL_FORK_20_X: - case PPME_SYSCALL_VFORK_20_X: - if (state->n_drops_buffer_clone_fork_exit != ULLONG_MAX) { - ++state->n_drops_buffer_clone_fork_exit; - } - break; - case PPME_SYSCALL_EXECVE_19_X: - case PPME_SYSCALL_EXECVEAT_X: - if (state->n_drops_buffer_execve_exit != ULLONG_MAX) { - ++state->n_drops_buffer_execve_exit; - } - break; - case PPME_SOCKET_CONNECT_X: - if (state->n_drops_buffer_connect_exit != ULLONG_MAX) { - ++state->n_drops_buffer_connect_exit; - } - break; - case PPME_SYSCALL_BPF_2_X: - case PPME_SYSCALL_SETPGID_X: - case PPME_SYSCALL_PTRACE_X: - case PPME_SYSCALL_SECCOMP_X: - case PPME_SYSCALL_SETNS_X: - case PPME_SYSCALL_SETRESGID_X: - case PPME_SYSCALL_SETRESUID_X: - case PPME_SYSCALL_SETSID_X: - case PPME_SYSCALL_UNSHARE_X: - case PPME_SYSCALL_CAPSET_X: - if (state->n_drops_buffer_other_interest_exit != ULLONG_MAX) { - ++state->n_drops_buffer_other_interest_exit; - } - break; - case PPME_SYSCALL_CLOSE_X: - if (state->n_drops_buffer_close_exit != ULLONG_MAX) { - ++state->n_drops_buffer_close_exit; - } - break; - default: - break; + switch(state->tail_ctx.evt_type) { + // enter + case PPME_SYSCALL_OPEN_E: + case PPME_SYSCALL_CREAT_E: + case PPME_SYSCALL_OPENAT_2_E: + case PPME_SYSCALL_OPENAT2_E: + case PPME_SYSCALL_OPEN_BY_HANDLE_AT_E: + if(state->n_drops_buffer_open_enter != ULLONG_MAX) { + ++state->n_drops_buffer_open_enter; + } + break; + case PPME_SYSCALL_DUP_E: + case PPME_SYSCALL_CHMOD_E: + case PPME_SYSCALL_FCHMOD_E: + case PPME_SYSCALL_FCHMODAT_E: + case PPME_SYSCALL_CHOWN_E: + case PPME_SYSCALL_LCHOWN_E: + case PPME_SYSCALL_FCHOWN_E: + case PPME_SYSCALL_FCHOWNAT_E: + case PPME_SYSCALL_LINK_2_E: + case PPME_SYSCALL_LINKAT_2_E: + case PPME_SYSCALL_MKDIR_2_E: + case PPME_SYSCALL_MKDIRAT_E: + case PPME_SYSCALL_MOUNT_E: + case PPME_SYSCALL_UMOUNT_1_E: + case PPME_SYSCALL_UMOUNT2_E: + case PPME_SYSCALL_RENAME_E: + case PPME_SYSCALL_RENAMEAT_E: + case PPME_SYSCALL_RENAMEAT2_E: + case PPME_SYSCALL_RMDIR_2_E: + case PPME_SYSCALL_SYMLINK_E: + case PPME_SYSCALL_SYMLINKAT_E: + case PPME_SYSCALL_UNLINK_2_E: + case PPME_SYSCALL_UNLINKAT_2_E: + if(state->n_drops_buffer_dir_file_enter != ULLONG_MAX) { + ++state->n_drops_buffer_dir_file_enter; + } + break; + case PPME_SYSCALL_CLONE_20_E: + case PPME_SYSCALL_CLONE3_E: + case PPME_SYSCALL_FORK_20_E: + case PPME_SYSCALL_VFORK_20_E: + if(state->n_drops_buffer_clone_fork_enter != ULLONG_MAX) { + ++state->n_drops_buffer_clone_fork_enter; + } + break; + case PPME_SYSCALL_EXECVE_19_E: + case PPME_SYSCALL_EXECVEAT_E: + if(state->n_drops_buffer_execve_enter != ULLONG_MAX) { + ++state->n_drops_buffer_execve_enter; + } + break; + case PPME_SOCKET_CONNECT_E: + if(state->n_drops_buffer_connect_enter != ULLONG_MAX) { + ++state->n_drops_buffer_connect_enter; + } + break; + case PPME_SYSCALL_BPF_2_E: + case PPME_SYSCALL_SETPGID_E: + case PPME_SYSCALL_PTRACE_E: + case PPME_SYSCALL_SECCOMP_E: + case PPME_SYSCALL_SETNS_E: + case PPME_SYSCALL_SETRESGID_E: + case PPME_SYSCALL_SETRESUID_E: + case PPME_SYSCALL_SETSID_E: + case PPME_SYSCALL_UNSHARE_E: + case PPME_SYSCALL_CAPSET_E: + if(state->n_drops_buffer_other_interest_enter != ULLONG_MAX) { + ++state->n_drops_buffer_other_interest_enter; + } + break; + case PPME_PROCEXIT_1_E: + if(state->n_drops_buffer_proc_exit != ULLONG_MAX) { + ++state->n_drops_buffer_proc_exit; + } + break; + // exit + case PPME_SYSCALL_OPEN_X: + case PPME_SYSCALL_CREAT_X: + case PPME_SYSCALL_OPENAT_2_X: + case PPME_SYSCALL_OPENAT2_X: + case PPME_SYSCALL_OPEN_BY_HANDLE_AT_X: + if(state->n_drops_buffer_open_exit != ULLONG_MAX) { + ++state->n_drops_buffer_open_exit; + } + break; + case PPME_SYSCALL_DUP_X: + case PPME_SYSCALL_CHMOD_X: + case PPME_SYSCALL_FCHMOD_X: + case PPME_SYSCALL_FCHMODAT_X: + case PPME_SYSCALL_CHOWN_X: + case PPME_SYSCALL_LCHOWN_X: + case PPME_SYSCALL_FCHOWN_X: + case PPME_SYSCALL_FCHOWNAT_X: + case PPME_SYSCALL_LINK_2_X: + case PPME_SYSCALL_LINKAT_2_X: + case PPME_SYSCALL_MKDIR_2_X: + case PPME_SYSCALL_MKDIRAT_X: + case PPME_SYSCALL_MOUNT_X: + case PPME_SYSCALL_UMOUNT_1_X: + case PPME_SYSCALL_UMOUNT2_X: + case PPME_SYSCALL_RENAME_X: + case PPME_SYSCALL_RENAMEAT_X: + case PPME_SYSCALL_RENAMEAT2_X: + case PPME_SYSCALL_RMDIR_2_X: + case PPME_SYSCALL_SYMLINK_X: + case PPME_SYSCALL_SYMLINKAT_X: + case PPME_SYSCALL_UNLINK_2_X: + case PPME_SYSCALL_UNLINKAT_2_X: + if(state->n_drops_buffer_dir_file_exit != ULLONG_MAX) { + ++state->n_drops_buffer_dir_file_exit; + } + break; + case PPME_SYSCALL_CLONE_20_X: + case PPME_SYSCALL_CLONE3_X: + case PPME_SYSCALL_FORK_20_X: + case PPME_SYSCALL_VFORK_20_X: + if(state->n_drops_buffer_clone_fork_exit != ULLONG_MAX) { + ++state->n_drops_buffer_clone_fork_exit; + } + break; + case PPME_SYSCALL_EXECVE_19_X: + case PPME_SYSCALL_EXECVEAT_X: + if(state->n_drops_buffer_execve_exit != ULLONG_MAX) { + ++state->n_drops_buffer_execve_exit; + } + break; + case PPME_SOCKET_CONNECT_X: + if(state->n_drops_buffer_connect_exit != ULLONG_MAX) { + ++state->n_drops_buffer_connect_exit; + } + break; + case PPME_SYSCALL_BPF_2_X: + case PPME_SYSCALL_SETPGID_X: + case PPME_SYSCALL_PTRACE_X: + case PPME_SYSCALL_SECCOMP_X: + case PPME_SYSCALL_SETNS_X: + case PPME_SYSCALL_SETRESGID_X: + case PPME_SYSCALL_SETRESUID_X: + case PPME_SYSCALL_SETSID_X: + case PPME_SYSCALL_UNSHARE_X: + case PPME_SYSCALL_CAPSET_X: + if(state->n_drops_buffer_other_interest_exit != ULLONG_MAX) { + ++state->n_drops_buffer_other_interest_exit; + } + break; + case PPME_SYSCALL_CLOSE_X: + if(state->n_drops_buffer_close_exit != ULLONG_MAX) { + ++state->n_drops_buffer_close_exit; + } + break; + default: + break; } break; case PPM_FAILURE_INVALID_USER_MEMORY: bpf_printk("PPM_FAILURE_INVALID_USER_MEMORY event=%d curarg=%d\n", - state->tail_ctx.evt_type, - state->tail_ctx.curarg); - if (state->n_drops_pf != ULLONG_MAX) { + state->tail_ctx.evt_type, + state->tail_ctx.curarg); + if(state->n_drops_pf != ULLONG_MAX) { ++state->n_drops_pf; } break; case PPM_FAILURE_BUG: bpf_printk("PPM_FAILURE_BUG event=%d curarg=%d\n", - state->tail_ctx.evt_type, - state->tail_ctx.curarg); - if (state->n_drops_bug != ULLONG_MAX) { + state->tail_ctx.evt_type, + state->tail_ctx.curarg); + if(state->n_drops_bug != ULLONG_MAX) { ++state->n_drops_bug; } break; @@ -282,17 +278,17 @@ FILLER_RAW(terminate_filler) break; case PPM_FAILURE_FRAME_SCRATCH_MAP_FULL: bpf_printk("PPM_FAILURE_FRAME_SCRATCH_MAP_FULL event=%d curarg=%d\n", - state->tail_ctx.evt_type, - state->tail_ctx.curarg); - if (state->n_drops_scratch_map != ULLONG_MAX) { + state->tail_ctx.evt_type, + state->tail_ctx.curarg); + if(state->n_drops_scratch_map != ULLONG_MAX) { ++state->n_drops_scratch_map; } break; default: bpf_printk("Unknown filler res=%d event=%d curarg=%d\n", - state->tail_ctx.prev_res, - state->tail_ctx.evt_type, - state->tail_ctx.curarg); + state->tail_ctx.prev_res, + state->tail_ctx.evt_type, + state->tail_ctx.curarg); break; } @@ -300,13 +296,11 @@ FILLER_RAW(terminate_filler) return 0; } -FILLER(sys_empty, true) -{ +FILLER(sys_empty, true) { return PPM_SUCCESS; } -FILLER(sys_single, true) -{ +FILLER(sys_single, true) { unsigned long val; int res; @@ -315,8 +309,7 @@ FILLER(sys_single, true) return bpf_val_to_ring(data, val); } -FILLER(sys_single_x, true) -{ +FILLER(sys_single_x, true) { int res; long retval; @@ -324,15 +317,13 @@ FILLER(sys_single_x, true) return bpf_push_s64_to_ring(data, (int64_t)retval); } -FILLER(sys_fstat_e, true) -{ +FILLER(sys_fstat_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)fd); } -FILLER(sys_open_e, true) -{ +FILLER(sys_open_e, true) { uint32_t flags; unsigned long val; uint32_t mode; @@ -355,8 +346,7 @@ FILLER(sys_open_e, true) return bpf_push_u32_to_ring(data, mode); } -FILLER(sys_open_x, true) -{ +FILLER(sys_open_x, true) { unsigned int flags; unsigned int mode; unsigned long val; @@ -381,14 +371,11 @@ FILLER(sys_open_x, true) /* Parameter 3: flags (type: PT_FLAGS32) */ val = bpf_syscall_get_argument(data, 1); flags = open_flags_to_scap(val); - /* update flags if file is created*/ + /* update flags if file is created*/ flags |= bpf_get_fd_fmode_created(retval); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } res = bpf_push_u32_to_ring(data, flags); @@ -408,8 +395,7 @@ FILLER(sys_open_x, true) return bpf_push_u64_to_ring(data, (uint64_t)ino); } -FILLER(sys_read_e, true) -{ +FILLER(sys_read_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -420,8 +406,7 @@ FILLER(sys_read_e, true) return bpf_push_u32_to_ring(data, size); } -FILLER(sys_read_x, true) -{ +FILLER(sys_read_x, true) { unsigned long bufsize; unsigned long val; long retval; @@ -432,8 +417,7 @@ FILLER(sys_read_x, true) res = bpf_push_s64_to_ring(data, (int64_t)retval); CHECK_RES(res); - if (retval < 0) - { + if(retval < 0) { /* Parameter 2: data (type: PT_BYTEBUF) */ return bpf_push_empty_param(data); } @@ -443,11 +427,11 @@ FILLER(sys_read_x, true) /* Parameter 2: data (type: PT_BYTEBUF) */ data->fd = bpf_syscall_get_argument(data, 0); - return __bpf_val_to_ring(data, val, bufsize, PT_BYTEBUF, -1, true, USER);; + return __bpf_val_to_ring(data, val, bufsize, PT_BYTEBUF, -1, true, USER); + ; } -FILLER(sys_write_e, true) -{ +FILLER(sys_write_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -458,8 +442,7 @@ FILLER(sys_write_e, true) return bpf_push_u32_to_ring(data, (uint32_t)size); } -FILLER(sys_write_x, true) -{ +FILLER(sys_write_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -477,9 +460,7 @@ FILLER(sys_write_x, true) #define POLL_MAXFDS 16 -static __always_inline int bpf_poll_parse_fds(struct filler_data *data, - bool enter_event) -{ +static __always_inline int bpf_poll_parse_fds(struct filler_data *data, bool enter_event) { unsigned long read_size; unsigned int fds_count; int res = PPM_SUCCESS; @@ -492,8 +473,7 @@ static __always_inline int bpf_poll_parse_fds(struct filler_data *data, nfds = bpf_syscall_get_argument(data, 1); fds = (struct pollfd *)data->tmp_scratch; read_size = nfds * sizeof(struct pollfd); - if (read_size > SCRATCH_SIZE_MAX) - { + if(read_size > SCRATCH_SIZE_MAX) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -503,17 +483,14 @@ static __always_inline int bpf_poll_parse_fds(struct filler_data *data, * in this case `0`. */ #ifdef BPF_FORBIDS_ZERO_ACCESS - if (read_size) - if (bpf_probe_read_user(fds, - ((read_size - 1) & SCRATCH_SIZE_MAX) + 1, - (void *)val)) + if(read_size) + if(bpf_probe_read_user(fds, ((read_size - 1) & SCRATCH_SIZE_MAX) + 1, (void *)val)) #else - if (bpf_probe_read_user(fds, read_size & SCRATCH_SIZE_MAX, (void *)val)) + if(bpf_probe_read_user(fds, read_size & SCRATCH_SIZE_MAX, (void *)val)) #endif - nfds = 0; + nfds = 0; - if (data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) - { + if(data->state->tail_ctx.curoff > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -523,18 +500,17 @@ static __always_inline int bpf_poll_parse_fds(struct filler_data *data, off = data->state->tail_ctx.curoff + sizeof(uint16_t); fds_count = 0; - #pragma unroll - for (j = 0; j < POLL_MAXFDS; ++j) { - if (off > SCRATCH_SIZE_HALF) - { +#pragma unroll + for(j = 0; j < POLL_MAXFDS; ++j) { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } - if (j == nfds) + if(j == nfds) break; uint16_t flags; - if (enter_event) { + if(enter_event) { flags = poll_events_to_scap(fds[j].events); } else { flags = poll_events_to_scap(fds[j].revents); @@ -542,8 +518,7 @@ static __always_inline int bpf_poll_parse_fds(struct filler_data *data, *(int64_t *)&data->buf[off & SCRATCH_SIZE_HALF] = (int64_t)fds[j].fd; off += sizeof(int64_t); - if (off > SCRATCH_SIZE_HALF) - { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -554,11 +529,16 @@ static __always_inline int bpf_poll_parse_fds(struct filler_data *data, *((uint16_t *)&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF]) = fds_count; data->curarg_already_on_frame = true; - return __bpf_val_to_ring(data, 0, off - data->state->tail_ctx.curoff, PT_FDLIST, -1, false, KERNEL); + return __bpf_val_to_ring(data, + 0, + off - data->state->tail_ctx.curoff, + PT_FDLIST, + -1, + false, + KERNEL); } -FILLER(sys_poll_e, true) -{ +FILLER(sys_poll_e, true) { /* Parameter 1: fds (type: PT_FDLIST) */ int res = bpf_poll_parse_fds(data, true); CHECK_RES(res); @@ -569,8 +549,7 @@ FILLER(sys_poll_e, true) return bpf_push_s64_to_ring(data, (int64_t)timeout_msecs); } -FILLER(sys_poll_x, true) -{ +FILLER(sys_poll_x, true) { /* Parameter 1: ret (type: PT_FD) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, (int64_t)retval); @@ -581,17 +560,16 @@ FILLER(sys_poll_x, true) } #ifdef CONFIG_COMPAT - #define MAX_IOVCNT 8 +#define MAX_IOVCNT 8 #else - #define MAX_IOVCNT 32 +#define MAX_IOVCNT 32 #endif static __always_inline int bpf_parse_readv_writev_bufs(struct filler_data *data, - const void __user *iovsrc, - unsigned long iovcnt, - long retval, - int flags) -{ + const void __user *iovsrc, + unsigned long iovcnt, + long retval, + int flags) { int res = PPM_SUCCESS; unsigned long copylen; long size = 0; @@ -602,8 +580,7 @@ static __always_inline int bpf_parse_readv_writev_bufs(struct filler_data *data, unsigned long ptr_size = sizeof(void *); #ifdef CONFIG_COMPAT - if (bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { iov_size = sizeof(struct compat_iovec); len_off = offsetof(struct compat_iovec, iov_len); base_off = offsetof(struct compat_iovec, iov_base); @@ -612,116 +589,103 @@ static __always_inline int bpf_parse_readv_writev_bufs(struct filler_data *data, #endif copylen = iovcnt * iov_size; - if (copylen > SCRATCH_SIZE_MAX) - { + if(copylen > SCRATCH_SIZE_MAX) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } #ifdef BPF_FORBIDS_ZERO_ACCESS - if (copylen) - if (bpf_probe_read_user(data->tmp_scratch, - ((copylen - 1) & SCRATCH_SIZE_MAX) + 1, - (void *)iovsrc)) + if(copylen) + if(bpf_probe_read_user(data->tmp_scratch, + ((copylen - 1) & SCRATCH_SIZE_MAX) + 1, + (void *)iovsrc)) #else - if (bpf_probe_read_user(data->tmp_scratch, - copylen & SCRATCH_SIZE_MAX, - (void *)iovsrc)) + if(bpf_probe_read_user(data->tmp_scratch, copylen & SCRATCH_SIZE_MAX, (void *)iovsrc)) #endif return PPM_FAILURE_INVALID_USER_MEMORY; - #pragma unroll - for (j = 0; j < MAX_IOVCNT; ++j) { - if (j == iovcnt) + for(j = 0; j < MAX_IOVCNT; ++j) { + if(j == iovcnt) break; // BPF seems to require a hard limit to avoid overflows - if (size == LONG_MAX) + if(size == LONG_MAX) break; volatile unsigned curr_shift = j * iov_size + len_off; unsigned long shift_bounded = curr_shift & SCRATCH_SIZE_HALF; - if (curr_shift > SCRATCH_SIZE_HALF) + if(curr_shift > SCRATCH_SIZE_HALF) break; long curr_len; - if (ptr_size == 4) - { + if(ptr_size == 4) { curr_len = *((int *)(data->tmp_scratch + shift_bounded)); - } - else - { + } else { curr_len = *((long *)(data->tmp_scratch + shift_bounded)); } size += curr_len; } - if ((flags & PRB_FLAG_IS_WRITE) == 0) - if (size > retval) + if((flags & PRB_FLAG_IS_WRITE) == 0) + if(size > retval) size = retval; - if (flags & PRB_FLAG_PUSH_SIZE) { + if(flags & PRB_FLAG_PUSH_SIZE) { res = bpf_push_u32_to_ring(data, (uint32_t)size); CHECK_RES(res); } - if (flags & PRB_FLAG_PUSH_DATA) { - if (size > 0) { + if(flags & PRB_FLAG_PUSH_DATA) { + if(size > 0) { unsigned long off = _READ(data->state->tail_ctx.curoff); unsigned long remaining = size; #pragma unroll - for (j = 0; j < MAX_IOVCNT; ++j) { + for(j = 0; j < MAX_IOVCNT; ++j) { volatile unsigned int to_read; - if (j == iovcnt) + if(j == iovcnt) break; unsigned long off_bounded = off & SCRATCH_SIZE_HALF; - if (off > SCRATCH_SIZE_HALF) + if(off > SCRATCH_SIZE_HALF) break; volatile unsigned len_curr_shift = j * iov_size + len_off; unsigned long len_shift_bounded = len_curr_shift & SCRATCH_SIZE_HALF; - if (len_curr_shift > SCRATCH_SIZE_HALF) + if(len_curr_shift > SCRATCH_SIZE_HALF) break; long curr_len; - if (ptr_size == 4) - { + if(ptr_size == 4) { curr_len = *((int *)(data->tmp_scratch + len_shift_bounded)); - } - else - { + } else { curr_len = *((long *)(data->tmp_scratch + len_shift_bounded)); } - if (curr_len <= remaining) + if(curr_len <= remaining) to_read = curr_len; else to_read = remaining; - if (to_read > SCRATCH_SIZE_HALF) + if(to_read > SCRATCH_SIZE_HALF) to_read = SCRATCH_SIZE_HALF; volatile unsigned base_curr_shift = j * iov_size + base_off; unsigned long base_shift_bounded = base_curr_shift & SCRATCH_SIZE_HALF; - if (base_curr_shift > SCRATCH_SIZE_HALF) + if(base_curr_shift > SCRATCH_SIZE_HALF) break; unsigned long curr_base; - if (ptr_size == 4) - { + if(ptr_size == 4) { curr_base = *((unsigned int *)(data->tmp_scratch + base_shift_bounded)); - } - else - { + } else { curr_base = *((unsigned long *)(data->tmp_scratch + base_shift_bounded)); } #ifdef BPF_FORBIDS_ZERO_ACCESS - if (to_read) - if (bpf_probe_read_user(&data->buf[off_bounded], - ((to_read - 1) & SCRATCH_SIZE_HALF) + 1, - (void *)curr_base)) + if(to_read) + if(bpf_probe_read_user(&data->buf[off_bounded], + ((to_read - 1) & SCRATCH_SIZE_HALF) + 1, + (void *)curr_base)) #else - if (bpf_probe_read_user(&data->buf[off_bounded], - to_read & SCRATCH_SIZE_HALF, - (void *)curr_base)) + if(bpf_probe_read_user(&data->buf[off_bounded], + to_read & SCRATCH_SIZE_HALF, + (void *)curr_base)) #endif return PPM_FAILURE_INVALID_USER_MEMORY; @@ -739,8 +703,7 @@ static __always_inline int bpf_parse_readv_writev_bufs(struct filler_data *data, return res; } -FILLER(sys_readv_e, true) -{ +FILLER(sys_readv_e, true) { int32_t fd; /* Parameter 1: fd (type: PT_FD) */ @@ -748,8 +711,7 @@ FILLER(sys_readv_e, true) return bpf_push_s64_to_ring(data, (int64_t)fd); } -FILLER(sys_preadv_e, true) -{ +FILLER(sys_preadv_e, true) { #ifndef CAPTURE_64BIT_ARGS_SINGLE_REGISTER #error Implement this #endif @@ -761,14 +723,13 @@ FILLER(sys_preadv_e, true) fd = (int32_t)bpf_syscall_get_argument(data, 0); res = bpf_push_s64_to_ring(data, (int64_t)fd); CHECK_RES(res); - + /* Parameter 2: pos (type: PT_UINT64) */ val = bpf_syscall_get_argument(data, 3); return bpf_push_u64_to_ring(data, (uint64_t)val); } -FILLER(sys_readv_preadv_x, true) -{ +FILLER(sys_readv_preadv_x, true) { const struct iovec __user *iov; unsigned long iovcnt; long retval; @@ -780,21 +741,14 @@ FILLER(sys_readv_preadv_x, true) CHECK_RES(res); /* - * data and size - */ - if (retval > 0) - { + * data and size + */ + if(retval > 0) { iov = (const struct iovec __user *)bpf_syscall_get_argument(data, 1); iovcnt = bpf_syscall_get_argument(data, 2); - res = bpf_parse_readv_writev_bufs(data, - iov, - iovcnt, - retval, - PRB_FLAG_PUSH_ALL); - } - else - { + res = bpf_parse_readv_writev_bufs(data, iov, iovcnt, retval, PRB_FLAG_PUSH_ALL); + } else { /* Parameter 2: size (type: PT_UINT32) */ res = bpf_push_u32_to_ring(data, 0); @@ -805,8 +759,7 @@ FILLER(sys_readv_preadv_x, true) return res; } -FILLER(sys_writev_e, true) -{ +FILLER(sys_writev_e, true) { #ifndef CAPTURE_64BIT_ARGS_SINGLE_REGISTER #error Implement this #endif @@ -820,23 +773,21 @@ FILLER(sys_writev_e, true) /* Parameter 2: size (type: PT_UINT32) */ res = bpf_parse_readv_writev_bufs(data, - (const struct iovec __user *)iov_pointer, - iov_cnt, - 0, - PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); + (const struct iovec __user *)iov_pointer, + iov_cnt, + 0, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); /* if there was an error we send a size equal to `0`. * we can improve this in the future but at least we don't lose the whole event. */ - if(res == PPM_FAILURE_INVALID_USER_MEMORY) - { + if(res == PPM_FAILURE_INVALID_USER_MEMORY) { res = bpf_push_u32_to_ring(data, (uint32_t)0); } return res; } -FILLER(sys_writev_pwritev_x, true) -{ +FILLER(sys_writev_pwritev_x, true) { unsigned long iovcnt; unsigned long val; long retval; @@ -853,45 +804,38 @@ FILLER(sys_writev_pwritev_x, true) val = bpf_syscall_get_argument(data, 1); iovcnt = bpf_syscall_get_argument(data, 2); res = bpf_parse_readv_writev_bufs(data, - (const struct iovec __user *)val, - iovcnt, - 0, - PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); + (const struct iovec __user *)val, + iovcnt, + 0, + PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); /* if there was an error we send an empty param. * we can improve this in the future but at least we don't lose the whole event. */ - if(res == PPM_FAILURE_INVALID_USER_MEMORY) - { + if(res == PPM_FAILURE_INVALID_USER_MEMORY) { res = bpf_push_empty_param(data); } return res; } -static __always_inline int timespec_parse(struct filler_data *data, - unsigned long val) -{ - if (!bpf_in_ia32_syscall()) - { - #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 18, 0) +static __always_inline int timespec_parse(struct filler_data *data, unsigned long val) { + if(!bpf_in_ia32_syscall()) { +#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 18, 0) struct __kernel_timespec ts = {}; - #else +#else struct timespec ts = {}; - #endif +#endif bpf_probe_read_user(&ts, sizeof(ts), (void *)val); return bpf_push_u64_to_ring(data, ((uint64_t)ts.tv_sec) * 1000000000 + ts.tv_nsec); - } - else - { + } else { old_timespec32 ts = {}; bpf_probe_read_user(&ts, sizeof(ts), (void *)val); return bpf_push_u64_to_ring(data, ((uint32_t)ts.tv_sec) * 1000000000 + ts.tv_nsec); } } -FILLER(sys_nanosleep_e, true) -{ +FILLER(sys_nanosleep_e, true) { unsigned long val; int res; @@ -901,8 +845,7 @@ FILLER(sys_nanosleep_e, true) return res; } -FILLER(sys_futex_e, true) -{ +FILLER(sys_futex_e, true) { unsigned long val; int res; @@ -921,9 +864,7 @@ FILLER(sys_futex_e, true) return bpf_push_u64_to_ring(data, (uint64_t)val); } -static __always_inline unsigned long bpf_get_mm_counter(struct mm_struct *mm, - int member) -{ +static __always_inline unsigned long bpf_get_mm_counter(struct mm_struct *mm, int member) { long val; #ifdef HAS_RSS_STAT_ARRAY @@ -931,26 +872,22 @@ static __always_inline unsigned long bpf_get_mm_counter(struct mm_struct *mm, #else bpf_probe_read_kernel(&val, sizeof(val), &mm->rss_stat.count[member]); #endif - if (val < 0) + if(val < 0) val = 0; return (unsigned long)val; } -static __always_inline unsigned long bpf_get_mm_rss(struct mm_struct *mm) -{ - return bpf_get_mm_counter(mm, MM_FILEPAGES) + - bpf_get_mm_counter(mm, MM_ANONPAGES) + - bpf_get_mm_counter(mm, MM_SHMEMPAGES); +static __always_inline unsigned long bpf_get_mm_rss(struct mm_struct *mm) { + return bpf_get_mm_counter(mm, MM_FILEPAGES) + bpf_get_mm_counter(mm, MM_ANONPAGES) + + bpf_get_mm_counter(mm, MM_SHMEMPAGES); } -static __always_inline unsigned long bpf_get_mm_swap(struct mm_struct *mm) -{ +static __always_inline unsigned long bpf_get_mm_swap(struct mm_struct *mm) { return bpf_get_mm_counter(mm, MM_SWAPENTS); } -FILLER(sys_brk_munmap_mmap_x, true) -{ +FILLER(sys_brk_munmap_mmap_x, true) { struct task_struct *task; unsigned long total_vm = 0; struct mm_struct *mm; @@ -968,7 +905,7 @@ FILLER(sys_brk_munmap_mmap_x, true) res = bpf_push_s64_to_ring(data, retval); CHECK_RES(res); - if (mm) { + if(mm) { total_vm = _READ(mm->total_vm); total_vm <<= (PAGE_SHIFT - 10); total_rss = bpf_get_mm_rss(mm) << (PAGE_SHIFT - 10); @@ -987,8 +924,7 @@ FILLER(sys_brk_munmap_mmap_x, true) return bpf_push_u32_to_ring(data, swap); } -FILLER(sys_mmap_e, true) -{ +FILLER(sys_mmap_e, true) { unsigned long val; int res; @@ -1034,8 +970,7 @@ FILLER(sys_mmap_e, true) return bpf_push_u64_to_ring(data, val); } -FILLER(sys_mprotect_e, true) -{ +FILLER(sys_mprotect_e, true) { unsigned long val; int res; @@ -1054,15 +989,13 @@ FILLER(sys_mprotect_e, true) return bpf_push_u32_to_ring(data, prot_flags_to_scap(val)); } -FILLER(sys_mprotect_x, true) -{ +FILLER(sys_mprotect_x, true) { /* Parameter 1: ret (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); return bpf_push_s64_to_ring(data, retval); } -FILLER(sys_fcntl_e, true) -{ +FILLER(sys_fcntl_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -1073,8 +1006,7 @@ FILLER(sys_fcntl_e, true) return bpf_push_u8_to_ring(data, fcntl_cmd_to_scap(cmd)); } -FILLER(sys_fcntl_x, true) -{ +FILLER(sys_fcntl_x, true) { long retval; /* Parameter 1: Return Value */ @@ -1092,22 +1024,19 @@ FILLER(sys_fcntl_x, true) return bpf_push_u8_to_ring(data, fcntl_cmd_to_scap(cmd)); } -FILLER(sys_access_e, true) -{ +FILLER(sys_access_e, true) { /* Parameter 1: mode (type: PT_UINT32) */ int mode = (int)bpf_syscall_get_argument(data, 1); return bpf_push_u32_to_ring(data, (uint32_t)access_flags_to_scap(mode)); } -FILLER(sys_getrlimit_setrlimit_e, true) -{ +FILLER(sys_getrlimit_setrlimit_e, true) { /* Parameter 1: resource (type: PT_ENUMFLAGS8) */ uint32_t resource = bpf_syscall_get_argument(data, 0); return bpf_push_u8_to_ring(data, rlimit_resource_to_scap(resource)); } -FILLER(sys_getrlimit_x, true) -{ +FILLER(sys_getrlimit_x, true) { unsigned long val; long retval; int64_t cur; @@ -1122,7 +1051,7 @@ FILLER(sys_getrlimit_x, true) /* * Copy the user structure and extract cur and max */ - if(retval == 0){ + if(retval == 0) { struct rlimit rl = {0}; val = bpf_syscall_get_argument(data, 1); bpf_probe_read_user(&rl, sizeof(rl), (void *)val); @@ -1141,8 +1070,7 @@ FILLER(sys_getrlimit_x, true) return bpf_push_s64_to_ring(data, max); } -FILLER(sys_setrlimit_x, true) -{ +FILLER(sys_setrlimit_x, true) { unsigned long val; long retval; int64_t cur; @@ -1157,7 +1085,7 @@ FILLER(sys_setrlimit_x, true) /* * Copy the user structure and extract cur and max */ - struct rlimit rl = {0}; + struct rlimit rl = {0}; val = bpf_syscall_get_argument(data, 1); bpf_probe_read_user(&rl, sizeof(rl), (void *)val); cur = rl.rlim_cur; @@ -1170,14 +1098,13 @@ FILLER(sys_setrlimit_x, true) /* Parameter 3: max (type: PT_INT64) */ res = bpf_push_s64_to_ring(data, max); CHECK_RES(res); - + /* Parameter 4: resource (type: PT_ENUMFLAGS8) */ uint32_t resource = bpf_syscall_get_argument(data, 0); return bpf_push_u8_to_ring(data, rlimit_resource_to_scap(resource)); } -FILLER(sys_connect_e, true) -{ +FILLER(sys_connect_e, true) { struct sockaddr *usrsockaddr; unsigned long val; long size = 0; @@ -1190,23 +1117,20 @@ FILLER(sys_connect_e, true) res = bpf_push_s64_to_ring(data, fd); CHECK_RES(res); - if (fd >= 0) { + if(fd >= 0) { usrsockaddr = (struct sockaddr *)bpf_syscall_get_argument(data, 1); val = bpf_syscall_get_argument(data, 2); - if (usrsockaddr && val != 0) { + if(usrsockaddr && val != 0) { /* * Copy the address */ - err = bpf_addr_to_kernel(usrsockaddr, val, - (struct sockaddr *)data->tmp_scratch); - if (err >= 0) { + err = bpf_addr_to_kernel(usrsockaddr, val, (struct sockaddr *)data->tmp_scratch); + if(err >= 0) { /* * Convert the fd into socket endpoint information */ - size = bpf_pack_addr(data, - (struct sockaddr *)data->tmp_scratch, - val); + size = bpf_pack_addr(data, (struct sockaddr *)data->tmp_scratch, val); } } } @@ -1220,8 +1144,7 @@ FILLER(sys_connect_e, true) return res; } -FILLER(sys_connect_x, true) -{ +FILLER(sys_connect_x, true) { struct sockaddr *usrsockaddr; unsigned long val; long size = 0; @@ -1243,27 +1166,26 @@ FILLER(sys_connect_x, true) * in the stack, and therefore we can consume them. */ fd = bpf_syscall_get_argument(data, 0); - if (fd >= 0) { + if(fd >= 0) { usrsockaddr = (struct sockaddr *)bpf_syscall_get_argument(data, 1); val = bpf_syscall_get_argument(data, 2); - if (usrsockaddr && val != 0) { + if(usrsockaddr && val != 0) { /* * Copy the address */ - err = bpf_addr_to_kernel(usrsockaddr, val, - (struct sockaddr *)data->tmp_scratch); - if (err >= 0) { + err = bpf_addr_to_kernel(usrsockaddr, val, (struct sockaddr *)data->tmp_scratch); + if(err >= 0) { /* * Convert the fd into socket endpoint information */ size = bpf_fd_to_socktuple(data, - fd, - (struct sockaddr *)data->tmp_scratch, - val, - true, - false, - data->tmp_scratch + sizeof(struct sockaddr_storage)); + fd, + (struct sockaddr *)data->tmp_scratch, + val, + true, + false, + data->tmp_scratch + sizeof(struct sockaddr_storage)); } } } @@ -1280,8 +1202,7 @@ FILLER(sys_connect_x, true) return res; } -FILLER(sys_socketpair_x, true) -{ +FILLER(sys_socketpair_x, true) { struct unix_sock *us = NULL; struct sock *speer = NULL; /* In case of failure we send invalid fd (-1) */ @@ -1295,14 +1216,14 @@ FILLER(sys_socketpair_x, true) res = bpf_push_s64_to_ring(data, retval); CHECK_RES(res); - if (retval == 0) { + if(retval == 0) { val = bpf_syscall_get_argument(data, 3); - if (bpf_probe_read_user(fds, 2 * sizeof(int), (void *)val)) + if(bpf_probe_read_user(fds, 2 * sizeof(int), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; struct socket *sock = bpf_sockfd_lookup(data, fds[0]); - if (sock) { + if(sock) { us = (struct unix_sock *)_READ(sock->sk); speer = _READ(us->peer); } @@ -1324,8 +1245,8 @@ FILLER(sys_socketpair_x, true) } // TODO bpf_val_to_ring_dyn? -static int __always_inline parse_sockopt(struct filler_data *data, int level, int optname, void *optval, int optlen) -{ +static int __always_inline +parse_sockopt(struct filler_data *data, int level, int optname, void *optval, int optlen) { /* We use a signed int because in some case we have to convert it to a negative value. */ int32_t val32 = 0; uint64_t val64 = 0; @@ -1334,184 +1255,201 @@ static int __always_inline parse_sockopt(struct filler_data *data, int level, in /* Levels different from `SOL_SOCKET` are not supported * right now. */ - if(level != SOL_SOCKET) - { - return __bpf_val_to_ring(data, (unsigned long)optval, optlen, PT_BYTEBUF, PPM_SOCKOPT_IDX_UNKNOWN, false, USER); + if(level != SOL_SOCKET) { + return __bpf_val_to_ring(data, + (unsigned long)optval, + optlen, + PT_BYTEBUF, + PPM_SOCKOPT_IDX_UNKNOWN, + false, + USER); } - switch (optname) { + switch(optname) { #ifdef SO_ERROR - case SO_ERROR: - /* If there is an error while reading `bpf_probe_read` performs - * a `memset` so no need to check return value. - */ - bpf_probe_read_user(&val32, sizeof(val32), optval); - return bpf_val_to_ring_dyn(data, (int64_t)-val32, PT_ERRNO, PPM_SOCKOPT_IDX_ERRNO); + case SO_ERROR: + /* If there is an error while reading `bpf_probe_read` performs + * a `memset` so no need to check return value. + */ + bpf_probe_read_user(&val32, sizeof(val32), optval); + return bpf_val_to_ring_dyn(data, (int64_t)-val32, PT_ERRNO, PPM_SOCKOPT_IDX_ERRNO); #endif #ifdef SO_RCVTIMEO - case SO_RCVTIMEO: + case SO_RCVTIMEO: +#endif +#if(defined(SO_RCVTIMEO_OLD) && !defined(SO_RCVTIMEO)) || \ + (defined(SO_RCVTIMEO_OLD) && (SO_RCVTIMEO_OLD != SO_RCVTIMEO)) + case SO_RCVTIMEO_OLD: #endif -#if (defined(SO_RCVTIMEO_OLD) && !defined(SO_RCVTIMEO)) || (defined(SO_RCVTIMEO_OLD) && (SO_RCVTIMEO_OLD != SO_RCVTIMEO)) - case SO_RCVTIMEO_OLD: -#endif -#if (defined(SO_RCVTIMEO_NEW) && !defined(SO_RCVTIMEO)) || (defined(SO_RCVTIMEO_NEW) && (SO_RCVTIMEO_NEW != SO_RCVTIMEO)) - case SO_RCVTIMEO_NEW: +#if(defined(SO_RCVTIMEO_NEW) && !defined(SO_RCVTIMEO)) || \ + (defined(SO_RCVTIMEO_NEW) && (SO_RCVTIMEO_NEW != SO_RCVTIMEO)) + case SO_RCVTIMEO_NEW: #endif #ifdef SO_SNDTIMEO - case SO_SNDTIMEO: + case SO_SNDTIMEO: #endif -#if (defined(SO_SNDTIMEO_OLD) && !defined(SO_SNDTIMEO)) || (defined(SO_SNDTIMEO_OLD) && (SO_SNDTIMEO_OLD != SO_SNDTIMEO)) - case SO_SNDTIMEO_OLD: +#if(defined(SO_SNDTIMEO_OLD) && !defined(SO_SNDTIMEO)) || \ + (defined(SO_SNDTIMEO_OLD) && (SO_SNDTIMEO_OLD != SO_SNDTIMEO)) + case SO_SNDTIMEO_OLD: #endif -#if (defined(SO_SNDTIMEO_NEW) && !defined(SO_SNDTIMEO)) || (defined(SO_SNDTIMEO_NEW) && (SO_SNDTIMEO_NEW != SO_SNDTIMEO)) - case SO_SNDTIMEO_NEW: +#if(defined(SO_SNDTIMEO_NEW) && !defined(SO_SNDTIMEO)) || \ + (defined(SO_SNDTIMEO_NEW) && (SO_SNDTIMEO_NEW != SO_SNDTIMEO)) + case SO_SNDTIMEO_NEW: #endif - bpf_probe_read_user(&tv, sizeof(tv), optval); - return bpf_val_to_ring_dyn(data, tv.tv_sec * SECOND_IN_NS + tv.tv_usec * USECOND_IN_NS, PT_RELTIME, PPM_SOCKOPT_IDX_TIMEVAL); + bpf_probe_read_user(&tv, sizeof(tv), optval); + return bpf_val_to_ring_dyn(data, + tv.tv_sec * SECOND_IN_NS + tv.tv_usec * USECOND_IN_NS, + PT_RELTIME, + PPM_SOCKOPT_IDX_TIMEVAL); #ifdef SO_COOKIE - case SO_COOKIE: - bpf_probe_read_user(&val64, sizeof(val64), optval); - return bpf_val_to_ring_dyn(data, val64, PT_UINT64, PPM_SOCKOPT_IDX_UINT64); + case SO_COOKIE: + bpf_probe_read_user(&val64, sizeof(val64), optval); + return bpf_val_to_ring_dyn(data, val64, PT_UINT64, PPM_SOCKOPT_IDX_UINT64); #endif #ifdef SO_DEBUG - case SO_DEBUG: + case SO_DEBUG: #endif #ifdef SO_REUSEADDR - case SO_REUSEADDR: + case SO_REUSEADDR: #endif #ifdef SO_TYPE - case SO_TYPE: + case SO_TYPE: #endif #ifdef SO_DONTROUTE - case SO_DONTROUTE: + case SO_DONTROUTE: #endif #ifdef SO_BROADCAST - case SO_BROADCAST: + case SO_BROADCAST: #endif #ifdef SO_SNDBUF - case SO_SNDBUF: + case SO_SNDBUF: #endif #ifdef SO_RCVBUF - case SO_RCVBUF: + case SO_RCVBUF: #endif #ifdef SO_SNDBUFFORCE - case SO_SNDBUFFORCE: + case SO_SNDBUFFORCE: #endif #ifdef SO_RCVBUFFORCE - case SO_RCVBUFFORCE: + case SO_RCVBUFFORCE: #endif #ifdef SO_KEEPALIVE - case SO_KEEPALIVE: + case SO_KEEPALIVE: #endif #ifdef SO_OOBINLINE - case SO_OOBINLINE: + case SO_OOBINLINE: #endif #ifdef SO_NO_CHECK - case SO_NO_CHECK: + case SO_NO_CHECK: #endif #ifdef SO_PRIORITY - case SO_PRIORITY: + case SO_PRIORITY: #endif #ifdef SO_BSDCOMPAT - case SO_BSDCOMPAT: + case SO_BSDCOMPAT: #endif #ifdef SO_REUSEPORT - case SO_REUSEPORT: + case SO_REUSEPORT: #endif #ifdef SO_PASSCRED - case SO_PASSCRED: + case SO_PASSCRED: #endif #ifdef SO_RCVLOWAT - case SO_RCVLOWAT: + case SO_RCVLOWAT: #endif #ifdef SO_SNDLOWAT - case SO_SNDLOWAT: + case SO_SNDLOWAT: #endif #ifdef SO_SECURITY_AUTHENTICATION - case SO_SECURITY_AUTHENTICATION: + case SO_SECURITY_AUTHENTICATION: #endif #ifdef SO_SECURITY_ENCRYPTION_TRANSPORT - case SO_SECURITY_ENCRYPTION_TRANSPORT: + case SO_SECURITY_ENCRYPTION_TRANSPORT: #endif #ifdef SO_SECURITY_ENCRYPTION_NETWORK - case SO_SECURITY_ENCRYPTION_NETWORK: + case SO_SECURITY_ENCRYPTION_NETWORK: #endif #ifdef SO_BINDTODEVICE - case SO_BINDTODEVICE: + case SO_BINDTODEVICE: #endif #ifdef SO_DETACH_FILTER - case SO_DETACH_FILTER: + case SO_DETACH_FILTER: #endif #ifdef SO_TIMESTAMP - case SO_TIMESTAMP: + case SO_TIMESTAMP: #endif #ifdef SO_ACCEPTCONN - case SO_ACCEPTCONN: + case SO_ACCEPTCONN: #endif #ifdef SO_PEERSEC - case SO_PEERSEC: + case SO_PEERSEC: #endif #ifdef SO_PASSSEC - case SO_PASSSEC: + case SO_PASSSEC: #endif #ifdef SO_TIMESTAMPNS - case SO_TIMESTAMPNS: + case SO_TIMESTAMPNS: #endif #ifdef SO_MARK - case SO_MARK: + case SO_MARK: #endif #ifdef SO_TIMESTAMPING - case SO_TIMESTAMPING: + case SO_TIMESTAMPING: #endif #ifdef SO_PROTOCOL - case SO_PROTOCOL: + case SO_PROTOCOL: #endif #ifdef SO_DOMAIN - case SO_DOMAIN: + case SO_DOMAIN: #endif #ifdef SO_RXQ_OVFL - case SO_RXQ_OVFL: + case SO_RXQ_OVFL: #endif #ifdef SO_WIFI_STATUS - case SO_WIFI_STATUS: + case SO_WIFI_STATUS: #endif #ifdef SO_PEEK_OFF - case SO_PEEK_OFF: + case SO_PEEK_OFF: #endif #ifdef SO_NOFCS - case SO_NOFCS: + case SO_NOFCS: #endif #ifdef SO_LOCK_FILTER - case SO_LOCK_FILTER: + case SO_LOCK_FILTER: #endif #ifdef SO_SELECT_ERR_QUEUE - case SO_SELECT_ERR_QUEUE: + case SO_SELECT_ERR_QUEUE: #endif #ifdef SO_BUSY_POLL - case SO_BUSY_POLL: + case SO_BUSY_POLL: #endif #ifdef SO_MAX_PACING_RATE - case SO_MAX_PACING_RATE: + case SO_MAX_PACING_RATE: #endif #ifdef SO_BPF_EXTENSIONS - case SO_BPF_EXTENSIONS: + case SO_BPF_EXTENSIONS: #endif #ifdef SO_INCOMING_CPU - case SO_INCOMING_CPU: + case SO_INCOMING_CPU: #endif - bpf_probe_read_user(&val32, sizeof(val32), optval); - return bpf_val_to_ring_dyn(data, val32, PT_UINT32, PPM_SOCKOPT_IDX_UINT32); + bpf_probe_read_user(&val32, sizeof(val32), optval); + return bpf_val_to_ring_dyn(data, val32, PT_UINT32, PPM_SOCKOPT_IDX_UINT32); - default: - return __bpf_val_to_ring(data, (unsigned long)optval, optlen, PT_BYTEBUF, PPM_SOCKOPT_IDX_UNKNOWN, false, USER); + default: + return __bpf_val_to_ring(data, + (unsigned long)optval, + optlen, + PT_BYTEBUF, + PPM_SOCKOPT_IDX_UNKNOWN, + false, + USER); } } -FILLER(sys_setsockopt_x, true) -{ +FILLER(sys_setsockopt_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, (int64_t)retval); @@ -1535,15 +1473,14 @@ FILLER(sys_setsockopt_x, true) /* Parameter 5: optval (type: PT_DYN) */ unsigned long optval = bpf_syscall_get_argument(data, 3); uint16_t optlen = (uint16_t)bpf_syscall_get_argument(data, 4); - res = parse_sockopt(data, level, optname, (void*)optval, optlen); + res = parse_sockopt(data, level, optname, (void *)optval, optlen); CHECK_RES(res); /* Parameter 6: optlen (type: PT_UINT32) */ return bpf_push_u32_to_ring(data, (uint32_t)optlen); } -FILLER(sys_getsockopt_x, true) -{ +FILLER(sys_getsockopt_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, (int64_t)retval); @@ -1573,16 +1510,15 @@ FILLER(sys_getsockopt_x, true) int optlen = 0; unsigned long optlen_pointer = bpf_syscall_get_argument(data, 4); /* if the read fails it internally calls memeset(0) so we are ok */ - bpf_probe_read_user(&optlen, sizeof(optlen), (void*)optlen_pointer); - res = parse_sockopt(data, level, optname, (void*)optval, optlen); + bpf_probe_read_user(&optlen, sizeof(optlen), (void *)optlen_pointer); + res = parse_sockopt(data, level, optname, (void *)optval, optlen); CHECK_RES(res); /* Parameter 6: optlen (type: PT_UINT32) */ return bpf_push_u32_to_ring(data, optlen); } -static __always_inline int f_sys_send_e_common(struct filler_data *data, int fd) -{ +static __always_inline int f_sys_send_e_common(struct filler_data *data, int fd) { unsigned long val; int res; @@ -1601,8 +1537,7 @@ static __always_inline int f_sys_send_e_common(struct filler_data *data, int fd) return res; } -FILLER(sys_send_e, true) -{ +FILLER(sys_send_e, true) { /* * Push the common params to the ring */ @@ -1610,8 +1545,7 @@ FILLER(sys_send_e, true) return f_sys_send_e_common(data, fd); } -FILLER(sys_sendto_e, true) -{ +FILLER(sys_sendto_e, true) { struct sockaddr __user *usrsockaddr; unsigned long val; long size = 0; @@ -1637,23 +1571,22 @@ FILLER(sys_sendto_e, true) */ val = bpf_syscall_get_argument(data, 5); - if (usrsockaddr && val != 0) { + if(usrsockaddr && val != 0) { /* * Copy the address */ - err = bpf_addr_to_kernel(usrsockaddr, val, - (struct sockaddr *)data->tmp_scratch); - if (err >= 0) { + err = bpf_addr_to_kernel(usrsockaddr, val, (struct sockaddr *)data->tmp_scratch); + if(err >= 0) { /* * Convert the fd into socket endpoint information */ size = bpf_fd_to_socktuple(data, - fd, - (struct sockaddr *)data->tmp_scratch, - val, - true, - false, - data->tmp_scratch + sizeof(struct sockaddr_storage)); + fd, + (struct sockaddr *)data->tmp_scratch, + val, + true, + false, + data->tmp_scratch + sizeof(struct sockaddr_storage)); } } @@ -1666,8 +1599,7 @@ FILLER(sys_sendto_e, true) return res; } -FILLER(sys_send_x, true) -{ +FILLER(sys_send_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -1683,15 +1615,13 @@ FILLER(sys_send_x, true) return __bpf_val_to_ring(data, sent_data_pointer, bytes_to_read, PT_BYTEBUF, -1, true, USER); } -FILLER(sys_execve_e, true) -{ +FILLER(sys_execve_e, true) { /* Parameter 1: filename (type: PT_FSPATH) */ unsigned long filename_pointer = bpf_syscall_get_argument(data, 0); return bpf_val_to_ring_mem(data, filename_pointer, USER); } -FILLER(sys_execveat_e, true) -{ +FILLER(sys_execveat_e, true) { unsigned long val; unsigned long flags; int32_t fd; @@ -1701,9 +1631,8 @@ FILLER(sys_execveat_e, true) * dirfd */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - - if (fd == AT_FDCWD) - { + + if(fd == AT_FDCWD) { fd = PPM_AT_FDCWD; } @@ -1725,8 +1654,7 @@ FILLER(sys_execveat_e, true) return bpf_push_u32_to_ring(data, flags); } -static __always_inline uint32_t bpf_ppm_get_tty(struct task_struct *task) -{ +static __always_inline uint32_t bpf_ppm_get_tty(struct task_struct *task) { struct signal_struct *sig; struct tty_struct *tty; struct tty_driver *driver; @@ -1735,15 +1663,15 @@ static __always_inline uint32_t bpf_ppm_get_tty(struct task_struct *task) int index = 0; sig = _READ(task->signal); - if (!sig) + if(!sig) return 0; tty = _READ(sig->tty); - if (!tty) + if(!tty) return 0; driver = _READ(tty->driver); - if (!driver) + if(!driver) return 0; index = _READ(tty->index); @@ -1753,9 +1681,8 @@ static __always_inline uint32_t bpf_ppm_get_tty(struct task_struct *task) return new_encode_dev(MKDEV(major, minor_start) + index); } -static __always_inline struct pid *bpf_task_pid(struct task_struct *task) -{ -#if (PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1)) +static __always_inline struct pid *bpf_task_pid(struct task_struct *task) { +#if(PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1)) return _READ(task->thread_pid); #elif LINUX_VERSION_CODE < KERNEL_VERSION(4, 19, 0) return _READ(task->pids[PIDTYPE_PID].pid); @@ -1764,60 +1691,52 @@ static __always_inline struct pid *bpf_task_pid(struct task_struct *task) #endif } -static __always_inline struct pid_namespace *bpf_ns_of_pid(struct pid *pid) -{ +static __always_inline struct pid_namespace *bpf_ns_of_pid(struct pid *pid) { struct pid_namespace *ns = NULL; - if (pid) + if(pid) ns = _READ(pid->numbers[_READ(pid->level)].ns); return ns; } -static __always_inline struct pid_namespace *bpf_task_active_pid_ns(struct task_struct *tsk) -{ +static __always_inline struct pid_namespace *bpf_task_active_pid_ns(struct task_struct *tsk) { return bpf_ns_of_pid(bpf_task_pid(tsk)); } -static __always_inline pid_t bpf_pid_nr_ns(struct pid *pid, - struct pid_namespace *ns) -{ +static __always_inline pid_t bpf_pid_nr_ns(struct pid *pid, struct pid_namespace *ns) { unsigned int ns_level; struct upid *upid; pid_t nr = 0; ns_level = _READ(ns->level); - if (pid && ns_level <= _READ(pid->level)) { + if(pid && ns_level <= _READ(pid->level)) { upid = &pid->numbers[ns_level]; - if (_READ(upid->ns) == ns) + if(_READ(upid->ns) == ns) nr = _READ(upid->nr); } return nr; } -#if ((PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1))) || LINUX_VERSION_CODE >= KERNEL_VERSION(4, 19, 0) -static __always_inline struct pid **bpf_task_pid_ptr(struct task_struct *task, - enum pid_type type) -{ - return (type == PIDTYPE_PID) ? - &task->thread_pid : - &_READ(task->signal)->pids[type]; +#if((PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1))) || \ + LINUX_VERSION_CODE >= KERNEL_VERSION(4, 19, 0) +static __always_inline struct pid **bpf_task_pid_ptr(struct task_struct *task, enum pid_type type) { + return (type == PIDTYPE_PID) ? &task->thread_pid : &_READ(task->signal)->pids[type]; } #endif static __always_inline pid_t bpf_task_pid_nr_ns(struct task_struct *task, - enum pid_type type, - struct pid_namespace *ns) -{ + enum pid_type type, + struct pid_namespace *ns) { pid_t nr = 0; - if (!ns) + if(!ns) ns = bpf_task_active_pid_ns(task); -#if (PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1)) +#if(PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1)) nr = bpf_pid_nr_ns(_READ(*bpf_task_pid_ptr(task, type)), ns); #elif LINUX_VERSION_CODE < KERNEL_VERSION(4, 19, 0) - if (type != PIDTYPE_PID) { - if (type == __PIDTYPE_TGID) + if(type != PIDTYPE_PID) { + if(type == __PIDTYPE_TGID) type = PIDTYPE_PID; task = _READ(task->group_leader); @@ -1831,14 +1750,12 @@ static __always_inline pid_t bpf_task_pid_nr_ns(struct task_struct *task, return nr; } -static __always_inline pid_t bpf_task_pid_vnr(struct task_struct *task) -{ +static __always_inline pid_t bpf_task_pid_vnr(struct task_struct *task) { return bpf_task_pid_nr_ns(task, PIDTYPE_PID, NULL); } -static __always_inline pid_t bpf_task_tgid_vnr(struct task_struct *task) -{ -#if (PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1)) +static __always_inline pid_t bpf_task_tgid_vnr(struct task_struct *task) { +#if(PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 1)) return bpf_task_pid_nr_ns(task, PIDTYPE_TGID, NULL); #elif LINUX_VERSION_CODE < KERNEL_VERSION(4, 19, 0) return bpf_task_pid_nr_ns(task, __PIDTYPE_TGID, NULL); @@ -1847,18 +1764,16 @@ static __always_inline pid_t bpf_task_tgid_vnr(struct task_struct *task) #endif } -static __always_inline pid_t bpf_task_pgrp_vnr(struct task_struct *task) -{ +static __always_inline pid_t bpf_task_pgrp_vnr(struct task_struct *task) { return bpf_task_pid_nr_ns(task, PIDTYPE_PGID, NULL); } #define MAX_CGROUP_PATHS 6 static __always_inline int __bpf_append_cgroup(struct css_set *cgroups, - int subsys_id, - char *buf, - int *len) -{ + int subsys_id, + char *buf, + int *len) { struct cgroup_subsys_state *css = _READ(cgroups->subsys[subsys_id]); struct cgroup_subsys *ss = _READ(css->ss); char *subsys_name = (char *)_READ(ss->name); @@ -1870,22 +1785,18 @@ static __always_inline int __bpf_append_cgroup(struct css_set *cgroups, unsigned int off_bounded; off_bounded = off & SCRATCH_SIZE_HALF; - if (off > SCRATCH_SIZE_HALF) - { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } - int res = bpf_probe_read_kernel_str(&buf[off_bounded], - SCRATCH_SIZE_HALF, - subsys_name); - if (res == -EFAULT) + int res = bpf_probe_read_kernel_str(&buf[off_bounded], SCRATCH_SIZE_HALF, subsys_name); + if(res == -EFAULT) return PPM_FAILURE_INVALID_USER_MEMORY; off += res - 1; off_bounded = off & SCRATCH_SIZE_HALF; - if (off > SCRATCH_SIZE_HALF) - { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -1893,9 +1804,9 @@ static __always_inline int __bpf_append_cgroup(struct css_set *cgroups, ++off; off_bounded = off & SCRATCH_SIZE_HALF; - #pragma unroll MAX_CGROUP_PATHS - for (int k = 0; k < MAX_CGROUP_PATHS; ++k) { - if (kn) { +#pragma unroll MAX_CGROUP_PATHS + for(int k = 0; k < MAX_CGROUP_PATHS; ++k) { + if(kn) { cgroup_path[k] = (char *)_READ(kn->name); kn = _READ(kn->parent); } else { @@ -1903,12 +1814,11 @@ static __always_inline int __bpf_append_cgroup(struct css_set *cgroups, } } - #pragma unroll MAX_CGROUP_PATHS - for (int k = MAX_CGROUP_PATHS - 1; k >= 0 ; --k) { - if (cgroup_path[k]) { - if (!prev_empty) { - if (off > SCRATCH_SIZE_HALF) - { +#pragma unroll MAX_CGROUP_PATHS + for(int k = MAX_CGROUP_PATHS - 1; k >= 0; --k) { + if(cgroup_path[k]) { + if(!prev_empty) { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -1919,28 +1829,22 @@ static __always_inline int __bpf_append_cgroup(struct css_set *cgroups, prev_empty = false; - if (off > SCRATCH_SIZE_HALF) - { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } - res = bpf_probe_read_kernel_str(&buf[off_bounded], - SCRATCH_SIZE_HALF, - cgroup_path[k]); - if (res > 1) - { + res = bpf_probe_read_kernel_str(&buf[off_bounded], SCRATCH_SIZE_HALF, cgroup_path[k]); + if(res > 1) { off += res - 1; off_bounded = off & SCRATCH_SIZE_HALF; - } - else if (res == 1) + } else if(res == 1) prev_empty = true; else return PPM_FAILURE_INVALID_USER_MEMORY; } } - if (off > SCRATCH_SIZE_HALF) - { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -1951,10 +1855,7 @@ static __always_inline int __bpf_append_cgroup(struct css_set *cgroups, return PPM_SUCCESS; } -static __always_inline int bpf_append_cgroup(struct task_struct *task, - char *buf, - int *len) -{ +static __always_inline int bpf_append_cgroup(struct task_struct *task, char *buf, int *len) { struct css_set *cgroups = _READ(task->cgroups); int res; @@ -1990,9 +1891,8 @@ static __always_inline int bpf_append_cgroup(struct task_struct *task, #define FAILED_ARGS_ENV_ITEMS_MAX 16 static __always_inline int bpf_accumulate_argv_or_env(struct filler_data *data, - char **argv, - long *args_len) -{ + char **argv, + long *args_len) { char *arg; int off; int len; @@ -2001,40 +1901,37 @@ static __always_inline int bpf_accumulate_argv_or_env(struct filler_data *data, *args_len = 0; off = data->state->tail_ctx.curoff; - if(argv == NULL) - { + if(argv == NULL) { // we need to put a `\0` otherwise we could read junk data data->buf[off & SCRATCH_SIZE_HALF] = '\0'; return PPM_SUCCESS; } - #pragma unroll - for (j = 0; j < FAILED_ARGS_ENV_ITEMS_MAX; ++j) { +#pragma unroll + for(j = 0; j < FAILED_ARGS_ENV_ITEMS_MAX; ++j) { arg = _READ_USER(argv[j]); - if (!arg) + if(!arg) break; - if (off > SCRATCH_SIZE_HALF) - { + if(off > SCRATCH_SIZE_HALF) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } len = bpf_probe_read_user_str(&data->buf[off & SCRATCH_SIZE_HALF], SCRATCH_SIZE_HALF, arg); // set trailing \0 if the arg is empty - if(len == 0) - { + if(len == 0) { data->buf[off & SCRATCH_SIZE_HALF] = 0; len = 1; } - - if (len == -EFAULT) + + if(len == -EFAULT) return PPM_FAILURE_INVALID_USER_MEMORY; *args_len += len; off += len; - if (*args_len > ARGS_ENV_SIZE_MAX) { + if(*args_len > ARGS_ENV_SIZE_MAX) { *args_len = ARGS_ENV_SIZE_MAX; data->buf[(data->state->tail_ctx.curoff + *args_len - 1) & SCRATCH_SIZE_MAX] = 0; break; @@ -2049,23 +1946,23 @@ static __always_inline int bpf_accumulate_argv_or_env(struct filler_data *data, static __always_inline bool bpf_groups_search(struct group_info *group_info, kgid_t grp) { unsigned int left, right; - if (!group_info) { + if(!group_info) { return 0; } left = 0; right = _READ(group_info->ngroups); - #pragma unroll MAX_GROUP_SEARCH_DEPTH - for (int j = 0; j < MAX_GROUP_SEARCH_DEPTH; j++) { - if (left >= right) { +#pragma unroll MAX_GROUP_SEARCH_DEPTH + for(int j = 0; j < MAX_GROUP_SEARCH_DEPTH; j++) { + if(left >= right) { break; } - - unsigned int mid = (left+right)/2; - if (gid_gt(grp, _READ(group_info->gid[mid]))) { + + unsigned int mid = (left + right) / 2; + if(gid_gt(grp, _READ(group_info->gid[mid]))) { left = mid + 1; - } else if (gid_lt(grp, _READ(group_info->gid[mid]))) { + } else if(gid_lt(grp, _READ(group_info->gid[mid]))) { right = mid; } else { return true; @@ -2078,45 +1975,45 @@ static __always_inline bool bpf_groups_search(struct group_info *group_info, kgi // log(UID_GID_MAP_MAX_EXTENTS) = log(340) #define MAX_EXTENT_SEARCH_DEPTH 9 -static __always_inline struct uid_gid_extent * -bpf_map_id_up_max(unsigned extents, struct uid_gid_map *map, uint32_t id) -{ +static __always_inline struct uid_gid_extent *bpf_map_id_up_max(unsigned extents, + struct uid_gid_map *map, + uint32_t id) { uint32_t left, right; left = 0; right = _READ(map->nr_extents); - - #pragma unroll MAX_EXTENT_SEARCH_DEPTH - for (int j = 0; j < MAX_EXTENT_SEARCH_DEPTH; j++) { - if (left >= right) { + +#pragma unroll MAX_EXTENT_SEARCH_DEPTH + for(int j = 0; j < MAX_EXTENT_SEARCH_DEPTH; j++) { + if(left >= right) { break; } - - unsigned int mid = (left+right)/2; + + unsigned int mid = (left + right) / 2; uint32_t mid_id = _READ(map->extent[mid].lower_first); - if (id > mid_id) { + if(id > mid_id) { left = mid + 1; - } else if (id < mid_id) { + } else if(id < mid_id) { right = mid; } else { return &map->extent[mid]; } } - + return NULL; } -static __always_inline struct uid_gid_extent * -bpf_map_id_up_base(unsigned extents, struct uid_gid_map *map, uint32_t id) -{ +static __always_inline struct uid_gid_extent *bpf_map_id_up_base(unsigned extents, + struct uid_gid_map *map, + uint32_t id) { unsigned idx; uint32_t first, last; - #pragma unroll UID_GID_MAP_MAX_BASE_EXTENTS - for (idx = 0; idx < UID_GID_MAP_MAX_BASE_EXTENTS; idx++) { - if (idx < extents) { +#pragma unroll UID_GID_MAP_MAX_BASE_EXTENTS + for(idx = 0; idx < UID_GID_MAP_MAX_BASE_EXTENTS; idx++) { + if(idx < extents) { first = _READ(map->extent[idx].lower_first); last = first + _READ(map->extent[idx].count) - 1; - if (id >= first && id <= last) + if(id >= first && id <= last) return &map->extent[idx]; } } @@ -2124,48 +2021,44 @@ bpf_map_id_up_base(unsigned extents, struct uid_gid_map *map, uint32_t id) } // UP means get NS id (uid/gid) from kuid/kgid -static __always_inline uint32_t bpf_map_id_up(struct uid_gid_map *map, uint32_t id) -{ +static __always_inline uint32_t bpf_map_id_up(struct uid_gid_map *map, uint32_t id) { struct uid_gid_extent *extent = NULL; unsigned extents = _READ(map->nr_extents); - if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS) { + if(extents <= UID_GID_MAP_MAX_BASE_EXTENTS) { extent = bpf_map_id_up_base(extents, map, id); } - /* Kernel 4.15 increased the number of extents to `340` while all the previous kernels have + /* Kernel 4.15 increased the number of extents to `340` while all the previous kernels have * the limit set to `5`. So the `if` case should be enough. */ -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 15, 0)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 15, 0)) else { extent = bpf_map_id_up_max(extents, map, id); } -#endif +#endif /* Map the id or note failure */ - if (extent) { + if(extent) { id = (id - _READ(extent->lower_first)) + _READ(extent->first); } else { - id = (uint32_t) - 1; + id = (uint32_t)-1; } return id; } -static __always_inline bool bpf_kuid_has_mapping(struct user_namespace *targ, kuid_t kuid) -{ +static __always_inline bool bpf_kuid_has_mapping(struct user_namespace *targ, kuid_t kuid) { /* Map the uid from a global kernel uid */ - return bpf_map_id_up(&targ->uid_map, __kuid_val(kuid)) != (uid_t) -1; + return bpf_map_id_up(&targ->uid_map, __kuid_val(kuid)) != (uid_t)-1; } -static __always_inline bool bpf_kgid_has_mapping(struct user_namespace *targ, kgid_t kgid) -{ - return bpf_map_id_up(&targ->gid_map, __kgid_val(kgid)) != (gid_t) -1; +static __always_inline bool bpf_kgid_has_mapping(struct user_namespace *targ, kgid_t kgid) { + return bpf_map_id_up(&targ->gid_map, __kgid_val(kgid)) != (gid_t)-1; } -static __always_inline struct file *get_exe_file(struct task_struct *task) -{ +static __always_inline struct file *get_exe_file(struct task_struct *task) { struct mm_struct *mm = NULL; - if (task && (mm = _READ(task->mm))) { + if(task && (mm = _READ(task->mm))) { return _READ(mm->exe_file); } return NULL; @@ -2178,30 +2071,25 @@ static __always_inline struct file *get_exe_file(struct task_struct *task) * inode object and other file attributes. * **/ -static __always_inline bool get_exe_from_memfd(struct file *file) -{ +static __always_inline bool get_exe_from_memfd(struct file *file) { struct dentry *dentry = _READ(file->f_path.dentry); - if(!dentry) - { + if(!dentry) { bpf_printk("get_exe_from_memfd(): failed to get dentry"); return false; } struct dentry *parent = _READ(dentry->d_parent); - if(!parent) - { + if(!parent) { bpf_printk("get_exe_from_memfd(): failed to get parent"); return false; } - if(parent != dentry) - { + if(parent != dentry) { return false; } const unsigned char *name = _READ(dentry->d_name.name); - if(!name) - { + if(!name) { bpf_printk("get_exe_from_memfd(): failed to get name"); return false; } @@ -2209,16 +2097,13 @@ static __always_inline bool get_exe_from_memfd(struct file *file) const char expected_prefix[] = "memfd:"; char memfd_name[sizeof(expected_prefix)] = {'\0'}; - if(bpf_probe_read_kernel_str(memfd_name, sizeof(memfd_name), name) != sizeof(expected_prefix)) - { + if(bpf_probe_read_kernel_str(memfd_name, sizeof(memfd_name), name) != sizeof(expected_prefix)) { return false; } #pragma unroll - for(int i = 0; i < sizeof(expected_prefix); i++) - { - if(expected_prefix[i] != memfd_name[i]) - { + for(int i = 0; i < sizeof(expected_prefix); i++) { + if(expected_prefix[i] != memfd_name[i]) { return false; } } @@ -2227,18 +2112,15 @@ static __always_inline bool get_exe_from_memfd(struct file *file) } /* `timespec64` was introduced in kernels >= 3.17 so it is ok here */ -static __always_inline unsigned long long bpf_epoch_ns_from_time(struct timespec64 time) -{ +static __always_inline unsigned long long bpf_epoch_ns_from_time(struct timespec64 time) { time64_t tv_sec = time.tv_sec; - if (tv_sec < 0) - { + if(tv_sec < 0) { return 0; } - return (tv_sec * (uint64_t) 1000000000 + time.tv_nsec); + return (tv_sec * (uint64_t)1000000000 + time.tv_nsec); } -static __always_inline bool get_exe_writable(struct inode *inode, struct cred *cred) -{ +static __always_inline bool get_exe_writable(struct inode *inode, struct cred *cred) { umode_t i_mode = _READ(inode->i_mode); unsigned i_flags = _READ(inode->i_flags); struct super_block *sb = _READ(inode->i_sb); @@ -2252,26 +2134,27 @@ static __always_inline bool get_exe_writable(struct inode *inode, struct cred *c // basic inode_permission() // check superblock permissions, i.e. if the FS is read only - if ((_READ(sb->s_flags) & SB_RDONLY) && (S_ISREG(i_mode) || S_ISDIR(i_mode) || S_ISLNK(i_mode))) { + if((_READ(sb->s_flags) & SB_RDONLY) && + (S_ISREG(i_mode) || S_ISDIR(i_mode) || S_ISLNK(i_mode))) { return false; } - if (i_flags & S_IMMUTABLE) { + if(i_flags & S_IMMUTABLE) { return false; } // HAS_UNMAPPED_ID() - if (!uid_valid(i_uid) || !gid_valid(i_gid)) { + if(!uid_valid(i_uid) || !gid_valid(i_gid)) { return false; } // inode_owner_or_capable check. If the owner matches the exe counts as writable - if (uid_eq(fsuid, i_uid)) { + if(uid_eq(fsuid, i_uid)) { return true; } - // Basic file permission check -- this may not work in all cases as kernel functions are more complex - // and take into account different types of ACLs which can use custom function pointers, + // Basic file permission check -- this may not work in all cases as kernel functions are more + // complex and take into account different types of ACLs which can use custom function pointers, // but I don't think we can inspect those in eBPF // basic acl_permission_check() @@ -2280,43 +2163,43 @@ static __always_inline bool get_exe_writable(struct inode *inode, struct cred *c umode_t mode = i_mode; - if (uid_eq(i_uid, fsuid)) { + if(uid_eq(i_uid, fsuid)) { mode >>= 6; } else { bool in_group = false; - if (gid_eq(i_gid, fsgid)) { + if(gid_eq(i_gid, fsgid)) { in_group = true; } else { in_group = bpf_groups_search(group_info, i_gid); } - if (in_group) { + if(in_group) { mode >>= 3; } } - if ((MAY_WRITE & ~mode) == 0) { + if((MAY_WRITE & ~mode) == 0) { return true; } struct user_namespace *ns = _READ(cred->user_ns); bool kuid_mapped = bpf_kuid_has_mapping(ns, i_uid); bool kgid_mapped = bpf_kgid_has_mapping(ns, i_gid); - if (cap_raised(_READ(cred->cap_effective), CAP_DAC_OVERRIDE) && kuid_mapped && kgid_mapped) { + if(cap_raised(_READ(cred->cap_effective), CAP_DAC_OVERRIDE) && kuid_mapped && kgid_mapped) { return true; } - // Check if the user is capable. Even if it doesn't own the file or the read bits are not set, root with CAP_FOWNER can do what it wants. - if (cap_raised(_READ(cred->cap_effective), CAP_FOWNER) && kuid_mapped) { + // Check if the user is capable. Even if it doesn't own the file or the read bits are not set, + // root with CAP_FOWNER can do what it wants. + if(cap_raised(_READ(cred->cap_effective), CAP_FOWNER) && kuid_mapped) { return true; } return false; } -FILLER(proc_startupdate, true) -{ +FILLER(proc_startupdate, true) { struct task_struct *real_parent; struct signal_struct *signal; struct task_struct *task; @@ -2343,10 +2226,10 @@ FILLER(proc_startupdate, true) task = (struct task_struct *)bpf_get_current_task(); mm = _READ(task->mm); - if (!mm) + if(!mm) return PPM_FAILURE_BUG; - if (retval >= 0) { + if(retval >= 0) { /* * The call succeeded. Get exe, args from the current * process; put one \0-separated exe-args string into @@ -2356,37 +2239,35 @@ FILLER(proc_startupdate, true) unsigned long arg_end; arg_end = _READ(mm->arg_end); - if (!arg_end) + if(!arg_end) return PPM_FAILURE_BUG; arg_start = _READ(mm->arg_start); args_len = arg_end - arg_start; - if (args_len > 0) { - if (args_len > ARGS_ENV_SIZE_MAX) + if(args_len > 0) { + if(args_len > ARGS_ENV_SIZE_MAX) args_len = ARGS_ENV_SIZE_MAX; #ifdef BPF_FORBIDS_ZERO_ACCESS - if (bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - ((args_len - 1) & SCRATCH_SIZE_HALF) + 1, - (void *)arg_start)) + if(bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + ((args_len - 1) & SCRATCH_SIZE_HALF) + 1, + (void *)arg_start)) #else - if (bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - args_len & SCRATCH_SIZE_HALF, - (void *)arg_start)) + if(bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + args_len & SCRATCH_SIZE_HALF, + (void *)arg_start)) #endif args_len = 0; else data->buf[(data->state->tail_ctx.curoff + args_len - 1) & SCRATCH_SIZE_MAX] = 0; } - } else if (data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVE_19_X || - data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVEAT_X ) { - + } else if(data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVE_19_X || + data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVEAT_X) { unsigned long val; char **argv; - switch (data->state->tail_ctx.evt_type) - { + switch(data->state->tail_ctx.evt_type) { case PPME_SYSCALL_EXECVE_19_X: val = bpf_syscall_get_argument(data, 1); break; @@ -2402,7 +2283,7 @@ FILLER(proc_startupdate, true) argv = (char **)val; res = bpf_accumulate_argv_or_env(data, argv, &args_len); - if (res != PPM_SUCCESS) + if(res != PPM_SUCCESS) args_len = 0; } else { args_len = 0; @@ -2410,24 +2291,21 @@ FILLER(proc_startupdate, true) int exe_len; - exe_len = bpf_probe_read_kernel_str(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - SCRATCH_SIZE_HALF, - &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF]); + exe_len = + bpf_probe_read_kernel_str(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + SCRATCH_SIZE_HALF, + &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF]); - if (exe_len < 0) - { + if(exe_len < 0) { return PPM_FAILURE_INVALID_USER_MEMORY; } /* * exe */ - if (exe_len == 0) - { + if(exe_len == 0) { res = bpf_push_empty_param(data); - } - else - { + } else { data->curarg_already_on_frame = true; res = __bpf_val_to_ring(data, 0, exe_len, PT_CHARBUF, -1, false, KERNEL); } @@ -2438,13 +2316,10 @@ FILLER(proc_startupdate, true) /* * Args */ - if(args_len <= 0) - { + if(args_len <= 0) { res = bpf_push_empty_param(data); CHECK_RES(res); - } - else - { + } else { data->curarg_already_on_frame = true; res = __bpf_val_to_ring(data, 0, args_len, PT_BYTEBUF, -1, false, KERNEL); CHECK_RES(res); @@ -2509,7 +2384,7 @@ FILLER(proc_startupdate, true) total_rss = 0; swap = 0; - if (mm) { + if(mm) { total_vm = _READ(mm->total_vm); total_vm <<= (PAGE_SHIFT - 10); total_rss = bpf_get_mm_rss(mm) << (PAGE_SHIFT - 10); @@ -2545,8 +2420,7 @@ FILLER(proc_startupdate, true) return PPM_FAILURE_BUG; } -FILLER(proc_startupdate_2, true) -{ +FILLER(proc_startupdate_2, true) { struct task_struct *task; int cgroups_len = 0; int res; @@ -2559,7 +2433,13 @@ FILLER(proc_startupdate_2, true) res = bpf_append_cgroup(task, data->tmp_scratch, &cgroups_len); CHECK_RES(res); - res = __bpf_val_to_ring(data, (unsigned long)data->tmp_scratch, cgroups_len, PT_BYTEBUF, -1, false, KERNEL); + res = __bpf_val_to_ring(data, + (unsigned long)data->tmp_scratch, + cgroups_len, + PT_BYTEBUF, + -1, + false, + KERNEL); CHECK_RES(res); bpf_tail_call(data->ctx, &tail_map, PPM_FILLER_proc_startupdate_3); @@ -2567,8 +2447,7 @@ FILLER(proc_startupdate_2, true) return PPM_FAILURE_BUG; } -FILLER(proc_startupdate_3, true) -{ +FILLER(proc_startupdate_3, true) { struct task_struct *task; struct mm_struct *mm; long retval; @@ -2582,14 +2461,13 @@ FILLER(proc_startupdate_3, true) task = (struct task_struct *)bpf_get_current_task(); mm = _READ(task->mm); - if (!mm) + if(!mm) return PPM_FAILURE_BUG; - if (data->state->tail_ctx.evt_type == PPME_SYSCALL_CLONE_20_X || - data->state->tail_ctx.evt_type == PPME_SYSCALL_FORK_20_X || - data->state->tail_ctx.evt_type == PPME_SYSCALL_VFORK_20_X || - data->state->tail_ctx.evt_type == PPME_SYSCALL_CLONE3_X) - { + if(data->state->tail_ctx.evt_type == PPME_SYSCALL_CLONE_20_X || + data->state->tail_ctx.evt_type == PPME_SYSCALL_FORK_20_X || + data->state->tail_ctx.evt_type == PPME_SYSCALL_VFORK_20_X || + data->state->tail_ctx.evt_type == PPME_SYSCALL_CLONE3_X) { /* * clone-only parameters */ @@ -2605,8 +2483,7 @@ FILLER(proc_startupdate_3, true) /* * flags */ - switch (data->state->tail_ctx.evt_type) - { + switch(data->state->tail_ctx.evt_type) { case PPME_SYSCALL_CLONE_20_X: #ifdef CONFIG_S390 flags = bpf_syscall_get_argument(data, 1); @@ -2614,20 +2491,17 @@ FILLER(proc_startupdate_3, true) flags = bpf_syscall_get_argument(data, 0); #endif break; - + case PPME_SYSCALL_CLONE3_X: #ifdef __NR_clone3 flags = bpf_syscall_get_argument(data, 0); - if (bpf_probe_read_user(&cl_args, sizeof(struct clone_args), (void *)flags)) - { + if(bpf_probe_read_user(&cl_args, sizeof(struct clone_args), (void *)flags)) { flags = 0; - } - else - { + } else { flags = cl_args.flags; } #else - flags = 0; + flags = 0; #endif break; @@ -2636,7 +2510,7 @@ FILLER(proc_startupdate_3, true) break; } - flags = clone_flags_to_scap((int) flags); + flags = clone_flags_to_scap((int)flags); if(pidns_level != 0) { flags |= PPM_CL_CHILD_IN_PIDNS; @@ -2691,19 +2565,19 @@ FILLER(proc_startupdate_3, true) res = bpf_push_s64_to_ring(data, vpid); CHECK_RES(res); - /* Parameter 21: pid_namespace init task start_time monotonic time in ns (type: PT_UINT64) */ + /* Parameter 21: pid_namespace init task start_time monotonic time in ns (type: PT_UINT64) + */ // only perform lookup when clone/vfork/fork returns 0 (child process / childtid) uint64_t pidns_init_start_time = 0; - if(retval == 0 && pidns) - { + if(retval == 0 && pidns) { struct task_struct *child_reaper = (struct task_struct *)_READ(pidns->child_reaper); pidns_init_start_time = _READ(child_reaper->start_time); } res = bpf_push_u64_to_ring(data, pidns_init_start_time); CHECK_RES(res); - } else if (data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVE_19_X || - data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVEAT_X) { + } else if(data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVE_19_X || + data->state->tail_ctx.evt_type == PPME_SYSCALL_EXECVEAT_X) { /* * execve family parameters. */ @@ -2715,7 +2589,7 @@ FILLER(proc_startupdate_3, true) /* * environ */ - if (retval >= 0) { + if(retval >= 0) { /* * Already checked for mm validity */ @@ -2724,18 +2598,18 @@ FILLER(proc_startupdate_3, true) env_len = env_end - env_start; - if (env_len) { - if (env_len > ARGS_ENV_SIZE_MAX) + if(env_len) { + if(env_len > ARGS_ENV_SIZE_MAX) env_len = ARGS_ENV_SIZE_MAX; #ifdef BPF_FORBIDS_ZERO_ACCESS - if (bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - ((env_len - 1) & SCRATCH_SIZE_HALF) + 1, - (void *)env_start)) + if(bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + ((env_len - 1) & SCRATCH_SIZE_HALF) + 1, + (void *)env_start)) #else - if (bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - env_len & SCRATCH_SIZE_HALF, - (void *)env_start)) + if(bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + env_len & SCRATCH_SIZE_HALF, + (void *)env_start)) #endif env_len = 0; else @@ -2745,16 +2619,15 @@ FILLER(proc_startupdate_3, true) unsigned long val; char **envp; - switch (data->state->tail_ctx.evt_type) - { + switch(data->state->tail_ctx.evt_type) { case PPME_SYSCALL_EXECVE_19_X: val = bpf_syscall_get_argument(data, 2); break; case PPME_SYSCALL_EXECVEAT_X: val = bpf_syscall_get_argument(data, 3); - break; - + break; + default: val = 0; break; @@ -2763,7 +2636,7 @@ FILLER(proc_startupdate_3, true) envp = (char **)val; res = bpf_accumulate_argv_or_env(data, envp, &env_len); - if (res != PPM_SUCCESS) + if(res != PPM_SUCCESS) env_len = 0; } @@ -2789,11 +2662,12 @@ FILLER(proc_startupdate_3, true) * loginuid */ /* TODO: implement user namespace support */ -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0) && CONFIG_AUDIT) || (LINUX_VERSION_CODE < KERNEL_VERSION(5, 1, 0) && CONFIG_AUDITSYSCALL) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0) && CONFIG_AUDIT) || \ + (LINUX_VERSION_CODE < KERNEL_VERSION(5, 1, 0) && CONFIG_AUDITSYSCALL) #ifdef COS_73_WORKAROUND { - struct audit_task_info* audit = _READ(task->audit); - if (audit) { + struct audit_task_info *audit = _READ(task->audit); + if(audit) { loginuid = _READ(audit->loginuid); } else { loginuid = INVALID_UID; @@ -2811,15 +2685,14 @@ FILLER(proc_startupdate_3, true) bpf_tail_call(data->ctx, &tail_map, PPM_FILLER_execve_extra_tail_1); bpf_printk("Can't tail call 'execve_extra_tail_1' filler\n"); - return PPM_FAILURE_BUG; + return PPM_FAILURE_BUG; } return res; } /* This filler avoids a bpf stack overflow on old kernels (like 4.14). */ -FILLER(execve_extra_tail_1, true) -{ +FILLER(execve_extra_tail_1, true) { struct task_struct *task = (struct task_struct *)bpf_get_current_task(); struct cred *cred = (struct cred *)_READ(task->cred); struct file *exe_file = get_exe_file(task); @@ -2827,14 +2700,12 @@ FILLER(execve_extra_tail_1, true) uint32_t flags = 0; kuid_t euid = {0}; - if(inode) - { + if(inode) { /* * exe_writable */ bool exe_writable = get_exe_writable(inode, cred); - if (exe_writable) - { + if(exe_writable) { flags |= PPM_EXE_WRITABLE; } } @@ -2842,20 +2713,15 @@ FILLER(execve_extra_tail_1, true) /* * exe_upper_layer/exe_lower_layer and exe_from_memfd */ - if(exe_file) - { + if(exe_file) { enum ppm_overlay exe_layer = get_overlay_layer(exe_file); - if (exe_layer == PPM_OVERLAY_UPPER) - { + if(exe_layer == PPM_OVERLAY_UPPER) { flags |= PPM_EXE_UPPER_LAYER; - } - else if (exe_layer == PPM_OVERLAY_LOWER) - { + } else if(exe_layer == PPM_OVERLAY_LOWER) { flags |= PPM_EXE_LOWER_LAYER; } - if(get_exe_from_memfd(exe_file)) - { + if(get_exe_from_memfd(exe_file)) { flags |= PPM_EXE_FROM_MEMFD; } } @@ -2867,7 +2733,9 @@ FILLER(execve_extra_tail_1, true) /* Parameter 21: cap_inheritable (type: PT_UINT64) */ kernel_cap_t cap = _READ(cred->cap_inheritable); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) - res = bpf_push_u64_to_ring(data, capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); + res = bpf_push_u64_to_ring( + data, + capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); #else res = bpf_push_u64_to_ring(data, capabilities_to_scap((unsigned long)cap.val)); #endif @@ -2876,7 +2744,9 @@ FILLER(execve_extra_tail_1, true) /* Parameter 22: cap_permitted (type: PT_UINT64) */ cap = _READ(cred->cap_permitted); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) - res = bpf_push_u64_to_ring(data, capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); + res = bpf_push_u64_to_ring( + data, + capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); #else res = bpf_push_u64_to_ring(data, capabilities_to_scap((unsigned long)cap.val)); #endif @@ -2885,7 +2755,9 @@ FILLER(execve_extra_tail_1, true) /* Parameter 23: cap_effective (type: PT_UINT64) */ cap = _READ(cred->cap_effective); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) - res = bpf_push_u64_to_ring(data, capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); + res = bpf_push_u64_to_ring( + data, + capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); #else res = bpf_push_u64_to_ring(data, capabilities_to_scap((unsigned long)cap.val)); #endif @@ -2898,7 +2770,8 @@ FILLER(execve_extra_tail_1, true) struct timespec64 time = {0}; - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0) time.tv_sec = _READ(inode->i_ctime_sec); time.tv_nsec = _READ(inode->i_ctime_nsec); @@ -2910,7 +2783,8 @@ FILLER(execve_extra_tail_1, true) res = bpf_push_u64_to_ring(data, bpf_epoch_ns_from_time(time)); CHECK_RES(res); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0) time.tv_sec = _READ(inode->i_mtime_sec); time.tv_nsec = _READ(inode->i_mtime_nsec); @@ -2929,31 +2803,26 @@ FILLER(execve_extra_tail_1, true) bpf_tail_call(data->ctx, &tail_map, PPM_FILLER_execve_extra_tail_2); bpf_printk("Can't tail call 'execve_extra_tail_2' filler\n"); - return PPM_FAILURE_BUG; + return PPM_FAILURE_BUG; } -FILLER(execve_extra_tail_2, true) -{ +FILLER(execve_extra_tail_2, true) { int res = 0; /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ struct task_struct *task = (struct task_struct *)bpf_get_current_task(); struct file *exe_file = get_exe_file(task); - if(exe_file != NULL) - { - char* filepath = bpf_d_path_approx(data, &(exe_file->f_path)); - res = bpf_val_to_ring_mem(data,(unsigned long)filepath, KERNEL); - } - else - { + if(exe_file != NULL) { + char *filepath = bpf_d_path_approx(data, &(exe_file->f_path)); + res = bpf_val_to_ring_mem(data, (unsigned long)filepath, KERNEL); + } else { res = bpf_push_empty_param(data); } return res; } -FILLER(sys_accept4_e, true) -{ +FILLER(sys_accept4_e, true) { /* * push the flags into the ring. * XXX we don't support flags yet and so we just return zero @@ -2962,8 +2831,7 @@ FILLER(sys_accept4_e, true) return bpf_push_s32_to_ring(data, 0); } -FILLER(sys_accept_x, true) -{ +FILLER(sys_accept_x, true) { /* Parameter 1: fd (type: PT_FD) */ /* Retrieve the fd and push it to the ring. * Note that, even if we are in the exit callback, the arguments are still @@ -2977,8 +2845,7 @@ FILLER(sys_accept_x, true) uint32_t queuemax = 0; uint8_t queuepct = 0; - if (fd >= 0) - { + if(fd >= 0) { /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ long size = bpf_fd_to_socktuple(data, fd, NULL, 0, false, true, data->tmp_scratch); data->curarg_already_on_frame = true; @@ -2987,17 +2854,14 @@ FILLER(sys_accept_x, true) /* Get the listening socket (first syscall parameter) */ int32_t listening_fd = (int32_t)bpf_syscall_get_argument(data, 0); - struct socket * sock = bpf_sockfd_lookup(data, listening_fd); + struct socket *sock = bpf_sockfd_lookup(data, listening_fd); struct sock *sk = _READ(sock->sk); queuelen = _READ(sk->sk_ack_backlog); queuemax = _READ(sk->sk_max_ack_backlog); - if(queuelen && queuemax) - { + if(queuelen && queuemax) { queuepct = (uint8_t)((uint64_t)queuelen * 100 / queuemax); } - } - else - { + } else { res = bpf_push_empty_param(data); CHECK_RES(res); } @@ -3014,36 +2878,31 @@ FILLER(sys_accept_x, true) return bpf_push_u32_to_ring(data, queuemax); } -FILLER(sys_close_e, true) -{ +FILLER(sys_close_e, true) { /* Parameter 1: fd (type: PT_FD)*/ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)fd); } -FILLER(sys_close_x, true) -{ +FILLER(sys_close_x, true) { /* Parameter 1: res (type: PT_ERRNO)*/ long retval = bpf_syscall_get_retval(data->ctx); return bpf_push_s64_to_ring(data, retval); } -FILLER(sys_fchdir_e, true) -{ +FILLER(sys_fchdir_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)fd); } -FILLER(sys_fchdir_x, true) -{ +FILLER(sys_fchdir_x, true) { /* Parameter 1: res (type: PT_ERRNO)*/ long retval = bpf_syscall_get_retval(data->ctx); return bpf_push_s64_to_ring(data, retval); } -FILLER(sys_setns_e, true) -{ +FILLER(sys_setns_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -3051,11 +2910,10 @@ FILLER(sys_setns_e, true) /* Parameter 2: nstype (type: PT_FLAGS32) */ unsigned long nstype = bpf_syscall_get_argument(data, 1); - return bpf_push_u32_to_ring(data, clone_flags_to_scap((int) nstype)); + return bpf_push_u32_to_ring(data, clone_flags_to_scap((int)nstype)); } -FILLER(sys_setpgid_e, true) -{ +FILLER(sys_setpgid_e, true) { /* Parameter 1: pid (type: PT_PID) */ pid_t pid = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)pid); @@ -3066,18 +2924,16 @@ FILLER(sys_setpgid_e, true) return bpf_push_s64_to_ring(data, (int64_t)pgid); } -FILLER(sys_unshare_e, true) -{ +FILLER(sys_unshare_e, true) { unsigned long val; uint32_t flags; val = bpf_syscall_get_argument(data, 0); - flags = clone_flags_to_scap((int) val); + flags = clone_flags_to_scap((int)val); return bpf_push_u32_to_ring(data, flags); } -FILLER(sys_generic, true) -{ +FILLER(sys_generic, true) { int scap_id; int native_id; int res; @@ -3089,19 +2945,18 @@ FILLER(sys_generic, true) // if we are in ia32 syscall sys_{enter,exit} already // validated the converted 32bit->64bit syscall ID for us, // otherwise the event would've been discarded. - if (bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { native_id = convert_ia32_to_64(native_id); } sc_evt = get_syscall_info(native_id); - if (!sc_evt) { + if(!sc_evt) { bpf_printk("no routing for syscall %d\n", native_id); return PPM_FAILURE_BUG; } scap_id = sc_evt->ppm_sc; - if (scap_id == PPM_SC_UNKNOWN) + if(scap_id == PPM_SC_UNKNOWN) bpf_printk("no syscall for id %d\n", native_id); /* @@ -3110,7 +2965,7 @@ FILLER(sys_generic, true) res = bpf_push_u16_to_ring(data, scap_id); CHECK_RES(res); - if (data->state->tail_ctx.evt_type == PPME_GENERIC_E) { + if(data->state->tail_ctx.evt_type == PPME_GENERIC_E) { /* * native id */ @@ -3120,8 +2975,7 @@ FILLER(sys_generic, true) return res; } -FILLER(sys_openat_e, true) -{ +FILLER(sys_openat_e, true) { unsigned long flags; unsigned long val; unsigned long mode; @@ -3132,7 +2986,7 @@ FILLER(sys_openat_e, true) * dirfd */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -3147,7 +3001,8 @@ FILLER(sys_openat_e, true) /* * Flags - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ val = bpf_syscall_get_argument(data, 2); flags = open_flags_to_scap(val); @@ -3162,8 +3017,7 @@ FILLER(sys_openat_e, true) return bpf_push_u32_to_ring(data, mode); } -FILLER(sys_openat_x, true) -{ +FILLER(sys_openat_x, true) { unsigned long dev = 0; unsigned long ino = 0; unsigned long flags; @@ -3182,7 +3036,7 @@ FILLER(sys_openat_x, true) * dirfd */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -3199,18 +3053,16 @@ FILLER(sys_openat_x, true) /* * Flags - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ val = bpf_syscall_get_argument(data, 2); flags = open_flags_to_scap(val); - /* update flags if file is created*/ + /* update flags if file is created*/ flags |= bpf_get_fd_fmode_created(retval); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } res = bpf_push_u32_to_ring(data, flags); @@ -3236,8 +3088,7 @@ FILLER(sys_openat_x, true) return bpf_push_u64_to_ring(data, ino); } -FILLER(sys_openat2_e, true) -{ +FILLER(sys_openat2_e, true) { uint32_t resolve; uint32_t flags; unsigned long val; @@ -3251,7 +3102,7 @@ FILLER(sys_openat2_e, true) * dirfd */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -3269,7 +3120,7 @@ FILLER(sys_openat2_e, true) * how: we get the data structure, and put its fields in the buffer one by one */ val = bpf_syscall_get_argument(data, 2); - if (bpf_probe_read_user(&how, sizeof(struct open_how), (void *)val)) { + if(bpf_probe_read_user(&how, sizeof(struct open_how), (void *)val)) { return PPM_FAILURE_INVALID_USER_MEMORY; } flags = open_flags_to_scap(how.flags); @@ -3283,28 +3134,29 @@ FILLER(sys_openat2_e, true) /* * flags (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = bpf_push_u32_to_ring(data, flags); CHECK_RES(res); /* * mode (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = bpf_push_u32_to_ring(data, mode); CHECK_RES(res); /* * resolve (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ return bpf_push_u32_to_ring(data, resolve); } - -FILLER(sys_openat2_x, true) -{ +FILLER(sys_openat2_x, true) { uint32_t resolve; uint32_t flags; unsigned long val; @@ -3327,7 +3179,7 @@ FILLER(sys_openat2_x, true) * dirfd */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -3345,7 +3197,7 @@ FILLER(sys_openat2_x, true) * how: we get the data structure, and put its fields in the buffer one by one */ val = bpf_syscall_get_argument(data, 2); - if (bpf_probe_read_user(&how, sizeof(struct open_how), (void *)val)) { + if(bpf_probe_read_user(&how, sizeof(struct open_how), (void *)val)) { return PPM_FAILURE_INVALID_USER_MEMORY; } flags = open_flags_to_scap(how.flags); @@ -3361,16 +3213,14 @@ FILLER(sys_openat2_x, true) /* * flags (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ - /* update flags if file is created*/ + /* update flags if file is created*/ flags |= bpf_get_fd_fmode_created(retval); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } res = bpf_push_u32_to_ring(data, flags); @@ -3378,14 +3228,16 @@ FILLER(sys_openat2_x, true) /* * mode (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = bpf_push_u32_to_ring(data, mode); CHECK_RES(res); /* * resolve (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = bpf_push_u32_to_ring(data, resolve); CHECK_RES(res); @@ -3402,8 +3254,7 @@ FILLER(sys_openat2_x, true) return bpf_push_u64_to_ring(data, ino); } -FILLER(sys_open_by_handle_at_x, true) -{ +FILLER(sys_open_by_handle_at_x, true) { long retval = bpf_syscall_get_retval(data->ctx); /* Parameter 1: ret (type: PT_FD) */ @@ -3412,28 +3263,26 @@ FILLER(sys_open_by_handle_at_x, true) /* Parameter 2: mountfd (type: PT_FD) */ int32_t mountfd = (int32_t)bpf_syscall_get_argument(data, 0); - if(mountfd == AT_FDCWD) - { + if(mountfd == AT_FDCWD) { mountfd = PPM_AT_FDCWD; } res = bpf_push_s64_to_ring(data, (int64_t)mountfd); CHECK_RES(res); - if(retval >= 0) - { + if(retval >= 0) { bpf_tail_call(data->ctx, &tail_map, PPM_FILLER_open_by_handle_at_x_extra_tail_1); bpf_printk("Can't tail call 'open_by_handle_at_x_extra_tail_1' filler\n"); return PPM_FAILURE_BUG; } /* Parameter 3: flags (type: PT_FLAGS32) */ - // If `retval < 0` we cannot retrieve the `struct file` and + // If `retval < 0` we cannot retrieve the `struct file` and // so we cannot retrieve the `OVERLAY` and the `O_F_CREATED` flags uint32_t flags = (uint32_t)bpf_syscall_get_argument(data, 2); flags = (uint32_t)open_flags_to_scap(flags); res = bpf_val_to_ring(data, flags); CHECK_RES(res); - + /* Parameter 4: path (type: PT_FSPATH) */ res = bpf_push_empty_param(data); CHECK_RES(res); @@ -3446,26 +3295,24 @@ FILLER(sys_open_by_handle_at_x, true) return bpf_push_u64_to_ring(data, 0); } -FILLER(open_by_handle_at_x_extra_tail_1, true) -{ +FILLER(open_by_handle_at_x_extra_tail_1, true) { long retval = bpf_syscall_get_retval(data->ctx); struct file *f = bpf_fget(retval); unsigned long dev = 0; unsigned long ino = 0; enum ppm_overlay ol = PPM_NOT_OVERLAY_FS; - if(f == NULL) - { + if(f == NULL) { /* In theory here we should send an empty param but we are experimenting some issues * with the verifier on debian10 (4.19.0-25-amd64). Sending an empty param exceeds * the complexity limit of the verifier for this reason we simply return an error code. - * Returning an error code means that we drop the entire event, but please note that this should - * never happen since we previosuly check `retval > 0`. The kernel should always have an entry for - * this fd in the fd table. + * Returning an error code means that we drop the entire event, but please note that this + * should never happen since we previosuly check `retval > 0`. The kernel should always have + * an entry for this fd in the fd table. */ return PPM_FAILURE_BUG; } - + bpf_get_dev_ino_overlay_from_fd(retval, &dev, &ino, &ol); /* Parameter 3: flags (type: PT_FLAGS32) */ @@ -3474,22 +3321,19 @@ FILLER(open_by_handle_at_x_extra_tail_1, true) */ uint32_t flags = (uint32_t)bpf_syscall_get_argument(data, 2); flags = (uint32_t)open_flags_to_scap(flags); - /* update flags if file is created*/ + /* update flags if file is created*/ flags |= bpf_get_fd_fmode_created(retval); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } int res = bpf_val_to_ring(data, flags); CHECK_RES(res); - + /* Parameter 4: path (type: PT_FSPATH) */ - char* filepath = bpf_d_path_approx(data, &(f->f_path)); - res = bpf_val_to_ring_mem(data,(unsigned long)filepath, KERNEL); + char *filepath = bpf_d_path_approx(data, &(f->f_path)); + res = bpf_val_to_ring_mem(data, (unsigned long)filepath, KERNEL); /* Parameter 5: dev (type: PT_UINT32) */ res = bpf_push_u32_to_ring(data, dev); @@ -3499,8 +3343,7 @@ FILLER(open_by_handle_at_x_extra_tail_1, true) return bpf_push_u64_to_ring(data, ino); } -FILLER(sys_io_uring_setup_x, true) -{ +FILLER(sys_io_uring_setup_x, true) { /* All these params are sent equal to `0` if `__NR_io_uring_setup` * syscall is not defined. */ @@ -3525,12 +3368,12 @@ FILLER(sys_io_uring_setup_x, true) flags = io_uring_setup_flags_to_scap(params.flags); sq_thread_cpu = params.sq_thread_cpu; sq_thread_idle = params.sq_thread_idle; - - /* We need this ifdef because `features` field is defined into the + + /* We need this ifdef because `features` field is defined into the * `struct io_uring_params` only if the `IORING_FEAT_SINGLE_MMAP` is * defined. */ -#ifdef IORING_FEAT_SINGLE_MMAP +#ifdef IORING_FEAT_SINGLE_MMAP features = io_uring_setup_feats_to_scap(params.features); #endif #endif /* __NR_io_uring_setup */ @@ -3569,8 +3412,7 @@ FILLER(sys_io_uring_setup_x, true) return bpf_push_u32_to_ring(data, features); } -FILLER(sys_io_uring_enter_x, true) -{ +FILLER(sys_io_uring_enter_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -3604,8 +3446,7 @@ FILLER(sys_io_uring_enter_x, true) /// we need to implement it in all our drivers } -FILLER(sys_io_uring_register_x, true) -{ +FILLER(sys_io_uring_register_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -3631,8 +3472,7 @@ FILLER(sys_io_uring_register_x, true) return bpf_push_u32_to_ring(data, nr_args); } -FILLER(sys_inotify_init_e, true) -{ +FILLER(sys_inotify_init_e, true) { /* Parameter 1: flags (type: PT_UINT8) */ /* We have nothing to extract from the kernel here so we send `0`. * This is done to preserve the `PPME_SYSCALL_INOTIFY_INIT_E` event with 1 param. @@ -3640,8 +3480,7 @@ FILLER(sys_inotify_init_e, true) return bpf_push_u8_to_ring(data, 0); } -FILLER(sys_inotify_init1_x, true) -{ +FILLER(sys_inotify_init1_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -3652,8 +3491,7 @@ FILLER(sys_inotify_init1_x, true) return bpf_push_u16_to_ring(data, inotify_init1_flags_to_scap(flags)); } -FILLER(sys_mlock_x, true) -{ +FILLER(sys_mlock_x, true) { unsigned long val; unsigned long retval; unsigned long res; @@ -3674,8 +3512,7 @@ FILLER(sys_mlock_x, true) return bpf_push_u64_to_ring(data, val); } -FILLER(sys_mlock2_x, true) -{ +FILLER(sys_mlock2_x, true) { unsigned long val; unsigned long retval; unsigned long res; @@ -3704,8 +3541,7 @@ FILLER(sys_mlock2_x, true) return bpf_push_u32_to_ring(data, flags); } -FILLER(sys_munlock_x, true) -{ +FILLER(sys_munlock_x, true) { unsigned long val; unsigned long retval; unsigned long res; @@ -3726,8 +3562,7 @@ FILLER(sys_munlock_x, true) return bpf_push_u64_to_ring(data, val); } -FILLER(sys_mlockall_x, true) -{ +FILLER(sys_mlockall_x, true) { unsigned long val; unsigned long retval; unsigned long res; @@ -3742,14 +3577,12 @@ FILLER(sys_mlockall_x, true) return bpf_push_u32_to_ring(data, mlockall_flags_to_scap(val)); } -FILLER(sys_munlockall_x, true) -{ +FILLER(sys_munlockall_x, true) { unsigned long retval = bpf_syscall_get_retval(data->ctx); return bpf_push_s64_to_ring(data, retval); } -FILLER(sys_fsconfig_x, true) -{ +FILLER(sys_fsconfig_x, true) { unsigned long res = 0; /* Parameter 1: ret (type: PT_ERRNO) */ @@ -3776,8 +3609,7 @@ FILLER(sys_fsconfig_x, true) int aux = bpf_syscall_get_argument(data, 4); - if(ret < 0) - { + if(ret < 0) { /* This differs from the implementation of the other 2 drivers (modern bpf, kmod) * because we hit the max instruction size for a program. So to avoid it we use this * workaround to fall into the `default` case of the switch, since we need to send @@ -3790,8 +3622,7 @@ FILLER(sys_fsconfig_x, true) /* According to the command we need to understand what value we have to push to userspace. */ /* see https://elixir.bootlin.com/linux/latest/source/fs/fsopen.c#L271 */ - switch(scap_cmd) - { + switch(scap_cmd) { case PPM_FSCONFIG_SET_FLAG: case PPM_FSCONFIG_SET_FD: case PPM_FSCONFIG_CMD_CREATE: @@ -3853,8 +3684,7 @@ FILLER(sys_fsconfig_x, true) return bpf_push_s32_to_ring(data, aux); } -FILLER(sys_signalfd_e, true) -{ +FILLER(sys_signalfd_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -3872,8 +3702,7 @@ FILLER(sys_signalfd_e, true) return bpf_push_u8_to_ring(data, 0); } -FILLER(sys_signalfd4_e, true) -{ +FILLER(sys_signalfd4_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -3884,8 +3713,7 @@ FILLER(sys_signalfd4_e, true) return bpf_push_u32_to_ring(data, 0); } -FILLER(sys_signalfd4_x, true) -{ +FILLER(sys_signalfd4_x, true) { /* Parameter 1: res (type: PT_FD) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -3896,36 +3724,31 @@ FILLER(sys_signalfd4_x, true) return bpf_push_u16_to_ring(data, signalfd4_flags_to_scap(flags)); } -FILLER(sys_epoll_create_e, true) -{ - /* Parameter 1: size (type: PT_INT32) */ +FILLER(sys_epoll_create_e, true) { + /* Parameter 1: size (type: PT_INT32) */ int32_t size = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s32_to_ring(data, size); } -FILLER(sys_epoll_create_x, true) -{ - /* Parameter 1: res (type: PT_ERRNO)*/ +FILLER(sys_epoll_create_x, true) { + /* Parameter 1: res (type: PT_ERRNO)*/ unsigned long retval = bpf_syscall_get_retval(data->ctx); return bpf_push_s64_to_ring(data, retval); } -FILLER(sys_epoll_create1_e, true) -{ +FILLER(sys_epoll_create1_e, true) { /* Parameter 1: flags (type: PT_FLAGS32) */ int32_t flags = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_u32_to_ring(data, epoll_create1_flags_to_scap(flags)); } -FILLER(sys_epoll_create1_x, true) -{ - /* Parameter 1: res (type: PT_ERRNO)*/ +FILLER(sys_epoll_create1_x, true) { + /* Parameter 1: res (type: PT_ERRNO)*/ unsigned long retval = bpf_syscall_get_retval(data->ctx); return bpf_push_s64_to_ring(data, retval); } -FILLER(sys_sendfile_e, true) -{ +FILLER(sys_sendfile_e, true) { /* Parameter 1: out_fd (type: PT_FD) */ int32_t out_fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)out_fd); @@ -3948,8 +3771,7 @@ FILLER(sys_sendfile_e, true) return bpf_push_u64_to_ring(data, size); } -FILLER(sys_sendfile_x, true) -{ +FILLER(sys_sendfile_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -3962,8 +3784,7 @@ FILLER(sys_sendfile_x, true) return bpf_push_u64_to_ring(data, offset); } -FILLER(sys_prlimit_e, true) -{ +FILLER(sys_prlimit_e, true) { /* Parameter 1: pid (type: PT_PID) */ pid_t pid = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)pid); @@ -3974,8 +3795,7 @@ FILLER(sys_prlimit_e, true) return bpf_push_u8_to_ring(data, rlimit_resource_to_scap(resource)); } -FILLER(sys_prlimit_x, true) -{ +FILLER(sys_prlimit_x, true) { unsigned long val; /* Parameter 1: res (type: PT_ERRNO) */ @@ -3999,8 +3819,7 @@ FILLER(sys_prlimit_x, true) CHECK_RES(res); struct rlimit old_rlimit = {0}; - if(retval == 0) - { + if(retval == 0) { val = bpf_syscall_get_argument(data, 3); bpf_probe_read_user(&old_rlimit, sizeof(old_rlimit), (void *)val); @@ -4010,17 +3829,15 @@ FILLER(sys_prlimit_x, true) /* Parameter 5: oldmax (type: PT_INT64) */ res = bpf_push_s64_to_ring(data, old_rlimit.rlim_max); - CHECK_RES(res); - } - else - { + CHECK_RES(res); + } else { /* Parameter 4: oldcur (type: PT_INT64) */ res = bpf_push_s64_to_ring(data, -1); CHECK_RES(res); /* Parameter 5: oldmax (type: PT_INT64) */ res = bpf_push_s64_to_ring(data, -1); - CHECK_RES(res); + CHECK_RES(res); } /* Parameter 6: pid (type: PT_PID) */ @@ -4033,8 +3850,7 @@ FILLER(sys_prlimit_x, true) return bpf_push_u8_to_ring(data, rlimit_resource_to_scap(resource)); } -FILLER(sys_pwritev_e, true) -{ +FILLER(sys_pwritev_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -4045,16 +3861,15 @@ FILLER(sys_pwritev_e, true) /* Parameter 2: size (type: PT_UINT32) */ res = bpf_parse_readv_writev_bufs(data, - (const struct iovec __user *)iov_pointer, - iov_cnt, - 0, - PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); + (const struct iovec __user *)iov_pointer, + iov_cnt, + 0, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); /* if there was an error we send a size equal to `0`. * we can improve this in the future but at least we don't lose the whole event. */ - if(res == PPM_FAILURE_INVALID_USER_MEMORY) - { + if(res == PPM_FAILURE_INVALID_USER_MEMORY) { res = bpf_push_u32_to_ring(data, 0); } CHECK_RES(res); @@ -4064,8 +3879,7 @@ FILLER(sys_pwritev_e, true) return bpf_push_u64_to_ring(data, pos); } -FILLER(sys_getresuid_and_gid_x, true) -{ +FILLER(sys_getresuid_and_gid_x, true) { long retval; uint32_t *idp; int res; @@ -4105,15 +3919,13 @@ FILLER(sys_getresuid_and_gid_x, true) return bpf_push_u32_to_ring(data, id); } -FILLER(sys_socket_bind_e, true) -{ +FILLER(sys_socket_bind_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)fd); } -FILLER(sys_socket_bind_x, true) -{ +FILLER(sys_socket_bind_x, true) { struct sockaddr *usrsockaddr; unsigned long val; uint16_t size = 0; @@ -4134,19 +3946,16 @@ FILLER(sys_socket_bind_x, true) usrsockaddr = (struct sockaddr __user *)bpf_syscall_get_argument(data, 1); val = bpf_syscall_get_argument(data, 2); - if (usrsockaddr && val != 0) { + if(usrsockaddr && val != 0) { /* * Copy the address */ - err = bpf_addr_to_kernel(usrsockaddr, val, - (struct sockaddr *)data->tmp_scratch); - if (err >= 0) { + err = bpf_addr_to_kernel(usrsockaddr, val, (struct sockaddr *)data->tmp_scratch); + if(err >= 0) { /* * Convert the fd into socket endpoint information */ - size = bpf_pack_addr(data, - (struct sockaddr *)data->tmp_scratch, - val); + size = bpf_pack_addr(data, (struct sockaddr *)data->tmp_scratch, val); } } @@ -4159,8 +3968,7 @@ FILLER(sys_socket_bind_x, true) return res; } -static __always_inline int f_sys_recv_x_common(struct filler_data *data, long retval) -{ +static __always_inline int f_sys_recv_x_common(struct filler_data *data, long retval) { unsigned long bufsize; unsigned long val; int res; @@ -4174,7 +3982,7 @@ static __always_inline int f_sys_recv_x_common(struct filler_data *data, long re /* * data */ - if (retval < 0) { + if(retval < 0) { /* * The operation failed, return an empty buffer */ @@ -4196,8 +4004,7 @@ static __always_inline int f_sys_recv_x_common(struct filler_data *data, long re return res; } -FILLER(sys_recv_x, true) -{ +FILLER(sys_recv_x, true) { long retval; int res; @@ -4207,8 +4014,7 @@ FILLER(sys_recv_x, true) return res; } -FILLER(sys_recvfrom_e, true) -{ +FILLER(sys_recvfrom_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -4219,8 +4025,7 @@ FILLER(sys_recvfrom_e, true) return bpf_push_u32_to_ring(data, size); } -FILLER(sys_recvfrom_x, true) -{ +FILLER(sys_recvfrom_x, true) { struct sockaddr *usrsockaddr; unsigned long val; uint16_t size = 0; @@ -4239,8 +4044,7 @@ FILLER(sys_recvfrom_x, true) res = f_sys_recv_x_common(data, retval); CHECK_RES(res); - - if (retval >= 0) { + if(retval >= 0) { /* * Get the fd */ @@ -4256,36 +4060,35 @@ FILLER(sys_recvfrom_x, true) */ val = bpf_syscall_get_argument(data, 5); - if (usrsockaddr && val != 0) { - if (bpf_probe_read_user(&addrlen, sizeof(addrlen), - (void *)val)) + if(usrsockaddr && val != 0) { + if(bpf_probe_read_user(&addrlen, sizeof(addrlen), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; /* * Copy the address */ - err = bpf_addr_to_kernel(usrsockaddr, addrlen, - (struct sockaddr *)data->tmp_scratch); - if (err >= 0) - { + err = bpf_addr_to_kernel(usrsockaddr, addrlen, (struct sockaddr *)data->tmp_scratch); + if(err >= 0) { /* - * Convert the fd into socket endpoint information + * Convert the fd into socket endpoint information */ from_usr = true; - } - else - { + } else { // Do not send any socket endpoint info. push = false; } } - if (push) - { + if(push) { /* - * Get socket endpoint information from fd if the user-provided *sockaddr is NULL + * Get socket endpoint information from fd if the user-provided *sockaddr is NULL */ - size = bpf_fd_to_socktuple(data, fd, (struct sockaddr *)data->tmp_scratch, addrlen, from_usr, - true, data->tmp_scratch + sizeof(struct sockaddr_storage)); + size = bpf_fd_to_socktuple(data, + fd, + (struct sockaddr *)data->tmp_scratch, + addrlen, + from_usr, + true, + data->tmp_scratch + sizeof(struct sockaddr_storage)); } } @@ -4298,8 +4101,7 @@ FILLER(sys_recvfrom_x, true) return res; } -FILLER(sys_shutdown_e, true) -{ +FILLER(sys_shutdown_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -4310,8 +4112,7 @@ FILLER(sys_shutdown_e, true) return bpf_push_u8_to_ring(data, (uint8_t)shutdown_how_to_scap(how)); } -FILLER(sys_listen_e, true) -{ +FILLER(sys_listen_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -4322,15 +4123,13 @@ FILLER(sys_listen_e, true) return bpf_push_s32_to_ring(data, (int32_t)backlog); } -FILLER(sys_recvmsg_e, true) -{ +FILLER(sys_recvmsg_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)fd); } -FILLER(sys_recvmsg_x, true) -{ +FILLER(sys_recvmsg_x, true) { const struct iovec *iov; struct user_msghdr mh; unsigned long iovcnt; @@ -4344,8 +4143,7 @@ FILLER(sys_recvmsg_x, true) /* If the syscall fails we are not able to collect reliable params * so we return empty ones. */ - if(retval < 0) - { + if(retval < 0) { /* Parameter 2: size (type: PT_UINT32) */ res = bpf_push_u32_to_ring(data, 0); CHECK_RES(res); @@ -4366,7 +4164,7 @@ FILLER(sys_recvmsg_x, true) * Retrieve the message header */ val = bpf_syscall_get_argument(data, 1); - if (bpf_probe_read_user(&mh, sizeof(mh), (void *)val)) + if(bpf_probe_read_user(&mh, sizeof(mh), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; /* @@ -4383,8 +4181,7 @@ FILLER(sys_recvmsg_x, true) return PPM_FAILURE_BUG; } -FILLER(sys_recvmsg_x_2, true) -{ +FILLER(sys_recvmsg_x_2, true) { struct sockaddr *usrsockaddr; struct user_msghdr mh; unsigned long val; @@ -4401,39 +4198,37 @@ FILLER(sys_recvmsg_x_2, true) */ /* - * Retrieve the message header - */ + * Retrieve the message header + */ val = bpf_syscall_get_argument(data, 1); - if (bpf_probe_read_user(&mh, sizeof(mh), (void *)val)) + if(bpf_probe_read_user(&mh, sizeof(mh), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; /* - * Get the address - */ + * Get the address + */ usrsockaddr = (struct sockaddr *)mh.msg_name; addrlen = mh.msg_namelen; - if (usrsockaddr && addrlen != 0) { + if(usrsockaddr && addrlen != 0) { /* - * Copy the address - */ - res = bpf_addr_to_kernel(usrsockaddr, - addrlen, - (struct sockaddr *)data->tmp_scratch); + * Copy the address + */ + res = bpf_addr_to_kernel(usrsockaddr, addrlen, (struct sockaddr *)data->tmp_scratch); - if (res >= 0) { + if(res >= 0) { fd = bpf_syscall_get_argument(data, 0); /* - * Convert the fd into socket endpoint information - */ + * Convert the fd into socket endpoint information + */ size = bpf_fd_to_socktuple(data, - fd, - (struct sockaddr *)data->tmp_scratch, - addrlen, - true, - true, - data->tmp_scratch + sizeof(struct sockaddr_storage)); + fd, + (struct sockaddr *)data->tmp_scratch, + addrlen, + true, + true, + data->tmp_scratch + sizeof(struct sockaddr_storage)); } } @@ -4441,19 +4236,22 @@ FILLER(sys_recvmsg_x_2, true) res = __bpf_val_to_ring(data, 0, size, PT_SOCKTUPLE, -1, false, KERNEL); CHECK_RES(res); - if(mh.msg_control != NULL) - { - res = __bpf_val_to_ring(data, (unsigned long)mh.msg_control, mh.msg_controllen, PT_BYTEBUF, -1, false, USER); - } else - { + if(mh.msg_control != NULL) { + res = __bpf_val_to_ring(data, + (unsigned long)mh.msg_control, + mh.msg_controllen, + PT_BYTEBUF, + -1, + false, + USER); + } else { res = bpf_push_empty_param(data); } return res; } -FILLER(sys_sendmsg_e, true) -{ +FILLER(sys_sendmsg_e, true) { struct sockaddr *usrsockaddr; const struct iovec *iov; struct user_msghdr mh; @@ -4476,7 +4274,7 @@ FILLER(sys_sendmsg_e, true) * Retrieve the message header */ val = bpf_syscall_get_argument(data, 1); - if (bpf_probe_read_user(&mh, sizeof(mh), (void *)val)) + if(bpf_probe_read_user(&mh, sizeof(mh), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; /* @@ -4485,8 +4283,7 @@ FILLER(sys_sendmsg_e, true) iov = (const struct iovec *)mh.msg_iov; iovcnt = mh.msg_iovlen; - res = bpf_parse_readv_writev_bufs(data, iov, iovcnt, 0, - PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); + res = bpf_parse_readv_writev_bufs(data, iov, iovcnt, 0, PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); CHECK_RES(res); /* @@ -4495,25 +4292,23 @@ FILLER(sys_sendmsg_e, true) usrsockaddr = (struct sockaddr *)mh.msg_name; addrlen = mh.msg_namelen; - if (usrsockaddr && addrlen != 0) { + if(usrsockaddr && addrlen != 0) { /* * Copy the address */ - err = bpf_addr_to_kernel(usrsockaddr, - addrlen, - (struct sockaddr *)data->tmp_scratch); + err = bpf_addr_to_kernel(usrsockaddr, addrlen, (struct sockaddr *)data->tmp_scratch); - if (err >= 0) { + if(err >= 0) { /* * Convert the fd into socket endpoint information */ size = bpf_fd_to_socktuple(data, - fd, - (struct sockaddr *)data->tmp_scratch, - addrlen, - true, - false, - data->tmp_scratch + sizeof(struct sockaddr_storage)); + fd, + (struct sockaddr *)data->tmp_scratch, + addrlen, + true, + false, + data->tmp_scratch + sizeof(struct sockaddr_storage)); } } @@ -4523,8 +4318,7 @@ FILLER(sys_sendmsg_e, true) return res; } -FILLER(sys_sendmsg_x, true) -{ +FILLER(sys_sendmsg_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -4533,23 +4327,24 @@ FILLER(sys_sendmsg_x, true) /* Parameter 2: data (type: PT_BYTEBUF) */ struct user_msghdr mh = {0}; unsigned long msghdr_pointer = bpf_syscall_get_argument(data, 1); - if (bpf_probe_read_user(&mh, sizeof(mh), (void *)msghdr_pointer)) - { + if(bpf_probe_read_user(&mh, sizeof(mh), (void *)msghdr_pointer)) { /* in case of NULL msghdr we return an empty param */ return bpf_push_empty_param(data); } const struct iovec *iov = (const struct iovec *)mh.msg_iov; - unsigned long iovcnt = mh.msg_iovlen; + unsigned long iovcnt = mh.msg_iovlen; - res = bpf_parse_readv_writev_bufs(data, iov, iovcnt, retval, - PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); + res = bpf_parse_readv_writev_bufs(data, + iov, + iovcnt, + retval, + PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); return res; } -FILLER(sys_creat_e, true) -{ +FILLER(sys_creat_e, true) { unsigned long val; unsigned long mode; int res; @@ -4569,8 +4364,7 @@ FILLER(sys_creat_e, true) return bpf_push_u32_to_ring(data, mode); } -FILLER(sys_creat_x, true) -{ +FILLER(sys_creat_x, true) { unsigned long dev = 0; unsigned long ino = 0; unsigned long val; @@ -4616,19 +4410,15 @@ FILLER(sys_creat_x, true) /* * creat_flags */ - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { creat_flags |= PPM_FD_UPPER_LAYER_CREAT; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { creat_flags |= PPM_FD_LOWER_LAYER_CREAT; } return bpf_push_u16_to_ring(data, (uint16_t)creat_flags); } -FILLER(sys_pipe_x, true) -{ +FILLER(sys_pipe_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -4637,8 +4427,7 @@ FILLER(sys_pipe_x, true) int32_t pipefd[2] = {-1, -1}; /* This is a pointer to the vector with the 2 file descriptors. */ unsigned long fd_vector_pointer = bpf_syscall_get_argument(data, 0); - if(bpf_probe_read_user(pipefd, sizeof(pipefd), (void *)fd_vector_pointer)) - { + if(bpf_probe_read_user(pipefd, sizeof(pipefd), (void *)fd_vector_pointer)) { pipefd[0] = -1; pipefd[1] = -1; } @@ -4653,8 +4442,7 @@ FILLER(sys_pipe_x, true) unsigned long ino = 0; /* On success, pipe returns `0` */ - if(retval == 0) - { + if(retval == 0) { bpf_get_ino_from_fd(pipefd[0], &ino); } @@ -4662,8 +4450,7 @@ FILLER(sys_pipe_x, true) return bpf_push_u64_to_ring(data, ino); } -FILLER(sys_pipe2_x, true) -{ +FILLER(sys_pipe2_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -4672,8 +4459,7 @@ FILLER(sys_pipe2_x, true) int32_t pipefd[2] = {-1, -1}; /* This is a pointer to the vector with the 2 file descriptors. */ unsigned long fd_vector_pointer = bpf_syscall_get_argument(data, 0); - if(bpf_probe_read_user(pipefd, sizeof(pipefd), (void *)fd_vector_pointer)) - { + if(bpf_probe_read_user(pipefd, sizeof(pipefd), (void *)fd_vector_pointer)) { pipefd[0] = -1; pipefd[1] = -1; } @@ -4688,8 +4474,7 @@ FILLER(sys_pipe2_x, true) unsigned long ino = 0; /* On success, pipe returns `0` */ - if(retval == 0) - { + if(retval == 0) { bpf_get_ino_from_fd(pipefd[0], &ino); } @@ -4702,8 +4487,7 @@ FILLER(sys_pipe2_x, true) return bpf_push_u32_to_ring(data, pipe2_flags_to_scap(flags)); } -FILLER(sys_lseek_e, true) -{ +FILLER(sys_lseek_e, true) { unsigned long flags; unsigned long val; int32_t fd; @@ -4732,8 +4516,7 @@ FILLER(sys_lseek_e, true) return bpf_push_u8_to_ring(data, flags); } -FILLER(sys_llseek_e, true) -{ +FILLER(sys_llseek_e, true) { unsigned long flags; unsigned long val; unsigned long oh; @@ -4769,8 +4552,7 @@ FILLER(sys_llseek_e, true) return bpf_push_u8_to_ring(data, flags); } -FILLER(sys_eventfd_e, true) -{ +FILLER(sys_eventfd_e, true) { /* Parameter 1: initval (type: PT_UINT64) */ unsigned long val = bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, val); @@ -4783,15 +4565,13 @@ FILLER(sys_eventfd_e, true) return bpf_push_u32_to_ring(data, 0); } -FILLER(sys_eventfd2_e, true) -{ +FILLER(sys_eventfd2_e, true) { /* Parameter 1: initval (type: PT_UINT64) */ unsigned long val = bpf_syscall_get_argument(data, 0); return bpf_push_u64_to_ring(data, val); } -FILLER(sys_eventfd2_x, true) -{ +FILLER(sys_eventfd2_x, true) { /* Parameter 1: res (type: PT_FD) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -4802,21 +4582,19 @@ FILLER(sys_eventfd2_x, true) return bpf_push_u16_to_ring(data, eventfd2_flags_to_scap(flags)); } -FILLER(sys_mount_e, true) -{ +FILLER(sys_mount_e, true) { /* * Fix mount flags in arg 3. * See http://lxr.free-electrons.com/source/fs/namespace.c?v=4.2#L2650 */ unsigned long val = bpf_syscall_get_argument(data, 3); - if ((val & PPM_MS_MGC_MSK) == PPM_MS_MGC_VAL) + if((val & PPM_MS_MGC_MSK) == PPM_MS_MGC_VAL) val &= ~PPM_MS_MGC_MSK; return bpf_push_u32_to_ring(data, val); } -FILLER(sys_ppoll_e, true) -{ +FILLER(sys_ppoll_e, true) { unsigned long val; int res; @@ -4836,8 +4614,7 @@ FILLER(sys_ppoll_e, true) return bpf_push_u32_to_ring(data, sigmask[0]); } -FILLER(sys_semop_x, true) -{ +FILLER(sys_semop_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -4852,21 +4629,16 @@ FILLER(sys_semop_x, true) struct sembuf sops[2] = {0}; unsigned long sops_pointer = bpf_syscall_get_argument(data, 1); - if(retval != 0 || sops_pointer == 0 || nsops == 0) - { + if(retval != 0 || sops_pointer == 0 || nsops == 0) { /* We send all 0 when one of these is true: * - the syscall fails (retval != 0) * - `sops_pointer` is NULL * - `nsops` is 0 */ - } - else if(nsops == 1) - { + } else if(nsops == 1) { /* If we have just one entry the second will be empty, we don't fill it */ bpf_probe_read_user((void *)sops, sizeof(struct sembuf), (void *)sops_pointer); - } - else - { + } else { /* If `nsops>1` we read just the first 2 entries. */ bpf_probe_read_user((void *)sops, sizeof(struct sembuf) * 2, (void *)sops_pointer); } @@ -4895,8 +4667,7 @@ FILLER(sys_semop_x, true) return bpf_push_u16_to_ring(data, semop_flags_to_scap(sops[1].sem_flg)); } -FILLER(sys_socket_x, true) -{ +FILLER(sys_socket_x, true) { long retval; int res; @@ -4904,11 +4675,10 @@ FILLER(sys_socket_x, true) res = bpf_push_s64_to_ring(data, retval); CHECK_RES(res); - if (retval >= 0 && - !data->settings->socket_file_ops) { + if(retval >= 0 && !data->settings->socket_file_ops) { struct file *file = bpf_fget(retval); - if (file) { + if(file) { const struct file_operations *f_op = _READ(file->f_op); data->settings->socket_file_ops = (void *)f_op; @@ -4918,8 +4688,7 @@ FILLER(sys_socket_x, true) return res; } -FILLER(sys_flock_e, true) -{ +FILLER(sys_flock_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -4930,8 +4699,7 @@ FILLER(sys_flock_e, true) return bpf_push_u32_to_ring(data, flock_flags_to_scap(operation)); } -FILLER(sys_ioctl_e, true) -{ +FILLER(sys_ioctl_e, true) { /* Parameter 1: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -4947,15 +4715,13 @@ FILLER(sys_ioctl_e, true) return bpf_push_u64_to_ring(data, argument); } -FILLER(sys_mkdir_e, true) -{ +FILLER(sys_mkdir_e, true) { /* Parameter 1: mode (type: PT_UINT32) */ uint32_t mode = (uint32_t)bpf_syscall_get_argument(data, 1); return bpf_push_u32_to_ring(data, mode); } -FILLER(sys_pread64_e, true) -{ +FILLER(sys_pread64_e, true) { #ifndef CAPTURE_64BIT_ARGS_SINGLE_REGISTER #error Implement this #endif @@ -4985,8 +4751,7 @@ FILLER(sys_pread64_e, true) return bpf_push_u64_to_ring(data, val); } -FILLER(sys_pwrite64_e, true) -{ +FILLER(sys_pwrite64_e, true) { #ifndef CAPTURE_64BIT_ARGS_SINGLE_REGISTER #error Implement this #endif @@ -4995,7 +4760,7 @@ FILLER(sys_pwrite64_e, true) int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); int res = bpf_push_s64_to_ring(data, (int64_t)fd); CHECK_RES(res); - + /* Parameter 2: size (type: PT_UINT32) */ size_t size = bpf_syscall_get_argument(data, 2); res = bpf_push_u32_to_ring(data, size); @@ -5006,8 +4771,7 @@ FILLER(sys_pwrite64_e, true) return bpf_push_u64_to_ring(data, pos); } -FILLER(sys_renameat_x, true) -{ +FILLER(sys_renameat_x, true) { unsigned long val; long retval; int32_t fd; @@ -5022,7 +4786,7 @@ FILLER(sys_renameat_x, true) */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -5040,7 +4804,7 @@ FILLER(sys_renameat_x, true) */ fd = (int32_t)bpf_syscall_get_argument(data, 2); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -5055,8 +4819,7 @@ FILLER(sys_renameat_x, true) return res; } -FILLER(sys_renameat2_x, true) -{ +FILLER(sys_renameat2_x, true) { unsigned long val; long retval; int32_t fd; @@ -5071,7 +4834,7 @@ FILLER(sys_renameat2_x, true) */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -5089,7 +4852,7 @@ FILLER(sys_renameat2_x, true) */ fd = (int32_t)bpf_syscall_get_argument(data, 2); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -5110,8 +4873,7 @@ FILLER(sys_renameat2_x, true) return res; } -FILLER(sys_symlinkat_x, true) -{ +FILLER(sys_symlinkat_x, true) { unsigned long val; long retval; int32_t fd; @@ -5133,7 +4895,7 @@ FILLER(sys_symlinkat_x, true) */ fd = (int32_t)bpf_syscall_get_argument(data, 1); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); @@ -5148,14 +4910,12 @@ FILLER(sys_symlinkat_x, true) return res; } -FILLER(sys_scapevent_e, false) -{ +FILLER(sys_scapevent_e, false) { bpf_printk("f_sys_scapevent_e should never be called\n"); return PPM_FAILURE_BUG; } -FILLER(cpu_hotplug_e, false) -{ +FILLER(cpu_hotplug_e, false) { int res; res = bpf_push_u32_to_ring(data, data->state->hotplug_cpu); @@ -5169,8 +4929,7 @@ FILLER(cpu_hotplug_e, false) return res; } -FILLER(sched_drop, false) -{ +FILLER(sched_drop, false) { /* * ratio */ @@ -5181,7 +4940,7 @@ FILLER(sched_drop, false) * We use these 2 values because they are the minimum required to run our eBPF probe * on some GKE environments. See https://github.com/falcosecurity/libs/issues/1639 */ -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 2, 0)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(5, 2, 0)) #define MAX_THREADS_GROUPS 25 #define MAX_HIERARCHY_TRAVERSE 35 #else @@ -5193,12 +4952,13 @@ FILLER(sched_drop, false) #endif /* 3 possible cases: - * - Looping between all threads of the current thread group we don't find a valid reaper. -> return 0 - * - We cannot loop over all threads of the group due to BPF verifier limits (MAX_THREADS_GROUPS) -> return -1 + * - Looping between all threads of the current thread group we don't find a valid reaper. -> return + * 0 + * - We cannot loop over all threads of the group due to BPF verifier limits (MAX_THREADS_GROUPS) -> + * return -1 * - We find a reaper -> return its `pid` */ -static __always_inline pid_t find_alive_thread(struct task_struct *father) -{ +static __always_inline pid_t find_alive_thread(struct task_struct *father) { struct signal_struct *signal = (struct signal_struct *)_READ(father->signal); struct list_head *head = &(signal->thread_head); struct list_head *next_thread = (struct list_head *)_READ(head->next); @@ -5209,12 +4969,10 @@ static __always_inline pid_t find_alive_thread(struct task_struct *father) #pragma unroll MAX_THREADS_GROUPS for(struct task_struct *t = container_of(next_thread, typeof(struct task_struct), thread_node); next_thread != (head) && cnt < MAX_THREADS_GROUPS; - t = container_of(next_thread, typeof(struct task_struct), thread_node)) - { + t = container_of(next_thread, typeof(struct task_struct), thread_node)) { cnt++; bpf_probe_read_kernel(&flags, sizeof(flags), &t->flags); - if(!(flags & PF_EXITING)) - { + if(!(flags & PF_EXITING)) { /* Found it */ return _READ(t->pid); } @@ -5222,8 +4980,7 @@ static __always_inline pid_t find_alive_thread(struct task_struct *father) } /* If we cannot loop over all threads, we cannot know the right reaper */ - if(cnt == MAX_THREADS_GROUPS) - { + if(cnt == MAX_THREADS_GROUPS) { return -1; } @@ -5237,19 +4994,18 @@ static __always_inline pid_t find_alive_thread(struct task_struct *father) * child_subreaper for its children (like a service manager) * 3. give it to the init process (PID 1) in our pid namespace */ -static __always_inline pid_t find_new_reaper_pid(struct filler_data *data, struct task_struct *father) -{ +static __always_inline pid_t find_new_reaper_pid(struct filler_data *data, + struct task_struct *father) { pid_t reaper_pid = find_alive_thread(father); - + /* - If we are not able to find the reaper due to BPF * verifier limits we return `-1` immediately in this * way the userspace can handle the reparenting logic * without complexity limits. - * + * * - If reaper_pid > 0 we find a valid reaper, we can return. */ - if(reaper_pid != 0) - { + if(reaper_pid != 0) { return reaper_pid; } @@ -5257,13 +5013,12 @@ static __always_inline pid_t find_new_reaper_pid(struct filler_data *data, struc /* This is the reaper of that namespace */ struct task_struct *child_ns_reaper = (struct task_struct *)_READ(pid_ns->child_reaper); - /* There could be a strange case in which the actual thread is the init one + /* There could be a strange case in which the actual thread is the init one * and we have no other threads in the same thread group, so the whole init group is dying. * The kernel will destroy all the processes in that namespace. We send a reaper equal to * `0` in userspace. */ - if(child_ns_reaper == father) - { + if(child_ns_reaper == father) { return 0; } @@ -5278,8 +5033,7 @@ static __always_inline pid_t find_new_reaper_pid(struct filler_data *data, struc signal = (struct signal_struct *)data->tmp_scratch; /* If there are no sub reapers the reaper is the init process of that namespace */ - if(!signal->has_child_subreaper) - { + if(!signal->has_child_subreaper) { return child_reaper_pid; } @@ -5301,47 +5055,43 @@ static __always_inline pid_t find_new_reaper_pid(struct filler_data *data, struc pid_t sub_reaper_pid = 0; #pragma unroll MAX_HIERARCHY_TRAVERSE - for(struct task_struct *possible_reaper = (struct task_struct *)_READ(father->real_parent); cnt < MAX_HIERARCHY_TRAVERSE; - possible_reaper = (struct task_struct *)_READ(possible_reaper->real_parent)) - { + for(struct task_struct *possible_reaper = (struct task_struct *)_READ(father->real_parent); + cnt < MAX_HIERARCHY_TRAVERSE; + possible_reaper = (struct task_struct *)_READ(possible_reaper->real_parent)) { cnt++; thread_pid = bpf_task_pid(possible_reaper); current_ns_level = _READ(thread_pid->level); /* We are crossing the namespace or we are the child_ns_reaper */ - if(father_ns_level != current_ns_level || - possible_reaper == child_ns_reaper) - { + if(father_ns_level != current_ns_level || possible_reaper == child_ns_reaper) { return child_reaper_pid; } signal = (struct signal_struct *)_READ(possible_reaper->signal); - bpf_probe_read_kernel(data->tmp_scratch, sizeof(struct signal_struct), (const void *)signal); + bpf_probe_read_kernel(data->tmp_scratch, + sizeof(struct signal_struct), + (const void *)signal); signal = (struct signal_struct *)data->tmp_scratch; - if(!signal->is_child_subreaper) - { + if(!signal->is_child_subreaper) { continue; } /* Here again we can return -1 in case we have verifier limits issues */ reaper_pid = find_alive_thread(possible_reaper); - if(reaper_pid != 0) - { + if(reaper_pid != 0) { return reaper_pid; } } /* We cannot traverse all the hierarchy, we cannot know the right reaper */ - if(cnt == MAX_HIERARCHY_TRAVERSE) - { + if(cnt == MAX_HIERARCHY_TRAVERSE) { return -1; } return child_reaper_pid; } -FILLER(sys_procexit_e, false) -{ +FILLER(sys_procexit_e, false) { struct task_struct *task; unsigned int flags; int exit_code; @@ -5361,8 +5111,7 @@ FILLER(sys_procexit_e, false) /* Parameter 3: sig (type: PT_SIGTYPE) */ /* If signaled -> signum, else 0 */ - if (__WIFSIGNALED(exit_code)) - { + if(__WIFSIGNALED(exit_code)) { res = bpf_push_u8_to_ring(data, __WTERMSIG(exit_code)); } else { res = bpf_push_u8_to_ring(data, 0); @@ -5378,12 +5127,11 @@ FILLER(sys_procexit_e, false) * we don't need a reaper and we can save some precious cycles. * We send `reaper_pid==0` if the userspace still has some children * it will manage them with its userspace logic. - */ + */ pid_t reaper_pid = 0; struct list_head *head = &(task->children); struct list_head *next_child = (struct list_head *)_READ(head->next); - if(next_child != head) - { + if(next_child != head) { /* We have at least one child, so we need a reaper for it */ reaper_pid = find_new_reaper_pid(data, task); } @@ -5399,8 +5147,7 @@ FILLER(sys_procexit_e, false) return res; } -FILLER(sched_switch_e, false) -{ +FILLER(sched_switch_e, false) { struct sched_switch_args *ctx; struct task_struct *task; unsigned long total_vm; @@ -5448,7 +5195,7 @@ FILLER(sched_switch_e, false) swap = 0; mm = _READ(task->mm); - if (mm) { + if(mm) { total_vm = _READ(mm->total_vm); total_vm <<= (PAGE_SHIFT - 10); total_rss = bpf_get_mm_rss(mm) << (PAGE_SHIFT - 10); @@ -5474,8 +5221,7 @@ FILLER(sched_switch_e, false) } #ifdef CAPTURE_PAGE_FAULTS -FILLER(sys_pagefault_e, false) -{ +FILLER(sys_pagefault_e, false) { struct page_fault_args *ctx; unsigned long error_code; unsigned long address; @@ -5507,17 +5253,15 @@ FILLER(sys_pagefault_e, false) } #endif -static __always_inline int siginfo_not_a_pointer(struct siginfo* info) -{ +static __always_inline int siginfo_not_a_pointer(struct siginfo *info) { #ifdef SEND_SIG_FORCED return info == SEND_SIG_NOINFO || info == SEND_SIG_PRIV || SEND_SIG_FORCED; #else - return info == (struct siginfo*)SEND_SIG_NOINFO || info == (struct siginfo*)SEND_SIG_PRIV; + return info == (struct siginfo *)SEND_SIG_NOINFO || info == (struct siginfo *)SEND_SIG_PRIV; #endif } -FILLER(sys_signaldeliver_e, false) -{ +FILLER(sys_signaldeliver_e, false) { struct signal_deliver_args *ctx; pid_t spid = 0; int sig; @@ -5528,23 +5272,21 @@ FILLER(sys_signaldeliver_e, false) struct siginfo *info = (struct siginfo *)ctx->info; sig = ctx->sig; - if (siginfo_not_a_pointer(info)) { + if(siginfo_not_a_pointer(info)) { info = NULL; spid = 0; - } else if (sig == SIGKILL) { + } else if(sig == SIGKILL) { spid = _READ(info->_sifields._kill._pid); - } else if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT || - sig == SIGTSTP || sig == SIGQUIT) { + } else if(sig == SIGTERM || sig == SIGHUP || sig == SIGINT || sig == SIGTSTP || + sig == SIGQUIT) { int si_code = _READ(info->si_code); - if (si_code == SI_USER || - si_code == SI_QUEUE || - si_code <= 0) { + if(si_code == SI_USER || si_code == SI_QUEUE || si_code <= 0) { spid = _READ(info->si_pid); } - } else if (sig == SIGCHLD) { + } else if(sig == SIGCHLD) { spid = _READ(info->_sifields._sigchld._pid); - } else if (sig >= SIGRTMIN && sig <= SIGRTMAX) { + } else if(sig >= SIGRTMIN && sig <= SIGRTMAX) { spid = _READ(info->_sifields._rt._pid); } #else @@ -5569,8 +5311,7 @@ FILLER(sys_signaldeliver_e, false) return bpf_push_u8_to_ring(data, sig); } -FILLER(sys_quotactl_e, true) -{ +FILLER(sys_quotactl_e, true) { /* Parameter 1: cmd (type: PT_FLAGS16) */ uint32_t cmd = (uint32_t)bpf_syscall_get_argument(data, 0); uint16_t scap_cmd = quotactl_cmd_to_scap(cmd); @@ -5583,30 +5324,23 @@ FILLER(sys_quotactl_e, true) /* Parameter 3: id (type: PT_UINT32) */ uint32_t id = (uint32_t)bpf_syscall_get_argument(data, 2); - if(scap_cmd != PPM_Q_GETQUOTA && - scap_cmd != PPM_Q_SETQUOTA && - scap_cmd != PPM_Q_XGETQUOTA && - scap_cmd != PPM_Q_XSETQLIM) - { + if(scap_cmd != PPM_Q_GETQUOTA && scap_cmd != PPM_Q_SETQUOTA && scap_cmd != PPM_Q_XGETQUOTA && + scap_cmd != PPM_Q_XSETQLIM) { /* In this case `id` don't represent a `userid` or a `groupid` */ res = bpf_push_u32_to_ring(data, 0); - } - else - { + } else { res = bpf_push_u32_to_ring(data, id); } /* Parameter 4: quota_fmt (type: PT_FLAGS8) */ uint8_t quota_fmt = PPM_QFMT_NOT_USED; - if(scap_cmd == PPM_Q_QUOTAON) - { + if(scap_cmd == PPM_Q_QUOTAON) { quota_fmt = quotactl_fmt_to_scap(id); } return bpf_push_u8_to_ring(data, quota_fmt); } -FILLER(sys_quotactl_x, true) -{ +FILLER(sys_quotactl_x, true) { struct if_dqinfo dqinfo = {0}; struct if_dqblk dqblk = {0}; uint32_t quota_fmt_out; @@ -5643,7 +5377,7 @@ FILLER(sys_quotactl_x, true) /* * get quotafilepath only for QUOTAON */ - if (cmd == PPM_Q_QUOTAON) { + if(cmd == PPM_Q_QUOTAON) { res = bpf_val_to_ring_type_mem(data, val, PT_CHARBUF, USER); CHECK_RES(res); } else { @@ -5654,12 +5388,11 @@ FILLER(sys_quotactl_x, true) /* * dqblk fields if present */ - if (cmd == PPM_Q_GETQUOTA || cmd == PPM_Q_SETQUOTA) { - if (bpf_probe_read_user(&dqblk, sizeof(dqblk), - (void *)val)) + if(cmd == PPM_Q_GETQUOTA || cmd == PPM_Q_SETQUOTA) { + if(bpf_probe_read_user(&dqblk, sizeof(dqblk), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; } - if (dqblk.dqb_valid & QIF_BLIMITS) { + if(dqblk.dqb_valid & QIF_BLIMITS) { res = bpf_push_u64_to_ring(data, dqblk.dqb_bhardlimit); CHECK_RES(res); @@ -5673,7 +5406,7 @@ FILLER(sys_quotactl_x, true) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_SPACE) { + if(dqblk.dqb_valid & QIF_SPACE) { res = bpf_push_u64_to_ring(data, dqblk.dqb_curspace); CHECK_RES(res); } else { @@ -5681,7 +5414,7 @@ FILLER(sys_quotactl_x, true) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_ILIMITS) { + if(dqblk.dqb_valid & QIF_ILIMITS) { res = bpf_push_u64_to_ring(data, dqblk.dqb_ihardlimit); CHECK_RES(res); res = bpf_push_u64_to_ring(data, dqblk.dqb_isoftlimit); @@ -5693,7 +5426,7 @@ FILLER(sys_quotactl_x, true) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_BTIME) { + if(dqblk.dqb_valid & QIF_BTIME) { res = bpf_push_u64_to_ring(data, dqblk.dqb_btime); CHECK_RES(res); } else { @@ -5701,7 +5434,7 @@ FILLER(sys_quotactl_x, true) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_ITIME) { + if(dqblk.dqb_valid & QIF_ITIME) { res = bpf_push_u64_to_ring(data, dqblk.dqb_itime); CHECK_RES(res); } else { @@ -5712,13 +5445,12 @@ FILLER(sys_quotactl_x, true) /* * dqinfo fields if present */ - if (cmd == PPM_Q_GETINFO || cmd == PPM_Q_SETINFO) { - if (bpf_probe_read_user(&dqinfo, sizeof(dqinfo), - (void *)val)) + if(cmd == PPM_Q_GETINFO || cmd == PPM_Q_SETINFO) { + if(bpf_probe_read_user(&dqinfo, sizeof(dqinfo), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; } - if (dqinfo.dqi_valid & IIF_BGRACE) { + if(dqinfo.dqi_valid & IIF_BGRACE) { res = bpf_push_u64_to_ring(data, dqinfo.dqi_bgrace); CHECK_RES(res); } else { @@ -5726,7 +5458,7 @@ FILLER(sys_quotactl_x, true) CHECK_RES(res); } - if (dqinfo.dqi_valid & IIF_IGRACE) { + if(dqinfo.dqi_valid & IIF_IGRACE) { res = bpf_push_u64_to_ring(data, dqinfo.dqi_igrace); CHECK_RES(res); } else { @@ -5734,7 +5466,7 @@ FILLER(sys_quotactl_x, true) CHECK_RES(res); } - if (dqinfo.dqi_valid & IIF_FLAGS) { + if(dqinfo.dqi_valid & IIF_FLAGS) { res = bpf_push_u8_to_ring(data, dqinfo.dqi_flags); CHECK_RES(res); } else { @@ -5743,10 +5475,10 @@ FILLER(sys_quotactl_x, true) } quota_fmt_out = PPM_QFMT_NOT_USED; - if (cmd == PPM_Q_GETFMT) { + if(cmd == PPM_Q_GETFMT) { uint32_t tmp; - if (bpf_probe_read_user(&tmp, sizeof(tmp), (void *)val)) + if(bpf_probe_read_user(&tmp, sizeof(tmp), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; quota_fmt_out = quotactl_fmt_to_scap(tmp); } @@ -5754,8 +5486,7 @@ FILLER(sys_quotactl_x, true) return bpf_push_u8_to_ring(data, quota_fmt_out); } -FILLER(sys_semget_e, true) -{ +FILLER(sys_semget_e, true) { unsigned long val; int res; @@ -5780,8 +5511,7 @@ FILLER(sys_semget_e, true) return bpf_push_u32_to_ring(data, semget_flags_to_scap(val)); } -FILLER(sys_semctl_e, true) -{ +FILLER(sys_semctl_e, true) { unsigned long val; int res; @@ -5809,7 +5539,7 @@ FILLER(sys_semctl_e, true) /* * optional argument semun/val */ - if (val == SETVAL) + if(val == SETVAL) val = bpf_syscall_get_argument(data, 3); else val = 0; @@ -5817,27 +5547,24 @@ FILLER(sys_semctl_e, true) return bpf_push_s32_to_ring(data, val); } -FILLER(sys_ptrace_e, true) -{ - +FILLER(sys_ptrace_e, true) { /* Parameter 1: request (type: PT_FLAGS16) */ unsigned long request = bpf_syscall_get_argument(data, 0); int res = bpf_push_u16_to_ring(data, ptrace_requests_to_scap(request)); CHECK_RES(res); /* Parameter 2: pid (type: PT_PID) */ - pid_t pid = (int32_t) bpf_syscall_get_argument(data, 1); + pid_t pid = (int32_t)bpf_syscall_get_argument(data, 1); return bpf_push_s64_to_ring(data, (int64_t)pid); } -static __always_inline int bpf_parse_ptrace_addr(struct filler_data *data, uint16_t request) -{ +static __always_inline int bpf_parse_ptrace_addr(struct filler_data *data, uint16_t request) { enum ppm_param_type type; unsigned long val; uint8_t idx; val = bpf_syscall_get_argument(data, 2); - switch (request) { + switch(request) { default: idx = PPM_PTRACE_IDX_UINT64; type = PT_UINT64; @@ -5846,21 +5573,20 @@ static __always_inline int bpf_parse_ptrace_addr(struct filler_data *data, uint1 return bpf_val_to_ring_dyn(data, val, type, idx); } -static __always_inline int bpf_parse_ptrace_data(struct filler_data *data, uint16_t request) -{ +static __always_inline int bpf_parse_ptrace_data(struct filler_data *data, uint16_t request) { enum ppm_param_type type; unsigned long val; uint64_t dst; uint8_t idx; val = bpf_syscall_get_argument(data, 3); - switch (request) { + switch(request) { case PPM_PTRACE_PEEKTEXT: case PPM_PTRACE_PEEKDATA: case PPM_PTRACE_PEEKUSR: idx = PPM_PTRACE_IDX_UINT64; type = PT_UINT64; - if (bpf_probe_read_user(&dst, sizeof(long), (void *)val)) + if(bpf_probe_read_user(&dst, sizeof(long), (void *)val)) return PPM_FAILURE_INVALID_USER_MEMORY; break; @@ -5887,8 +5613,7 @@ static __always_inline int bpf_parse_ptrace_data(struct filler_data *data, uint1 return bpf_val_to_ring_dyn(data, dst, type, idx); } -FILLER(sys_ptrace_x, true) -{ +FILLER(sys_ptrace_x, true) { unsigned long val; uint16_t request; long retval; @@ -5901,7 +5626,7 @@ FILLER(sys_ptrace_x, true) res = bpf_push_s64_to_ring(data, retval); CHECK_RES(res); - if (retval < 0) { + if(retval < 0) { res = bpf_val_to_ring_dyn(data, 0, PT_UINT64, 0); CHECK_RES(res); @@ -5921,15 +5646,13 @@ FILLER(sys_ptrace_x, true) return res; } -FILLER(sys_bpf_e, true) -{ +FILLER(sys_bpf_e, true) { /* Parameter 1: cmd (type: PT_INT64) */ int32_t cmd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)cmd); } -FILLER(sys_bpf_x, true) -{ +FILLER(sys_bpf_x, true) { /* Parameter 1: fd (type: PT_DEC) */ long fd = bpf_syscall_get_retval(data->ctx); bpf_push_s64_to_ring(data, fd); @@ -5939,8 +5662,7 @@ FILLER(sys_bpf_x, true) return bpf_push_s32_to_ring(data, (int32_t)bpf_cmd_to_scap(cmd)); } -FILLER(sys_unlinkat_x, true) -{ +FILLER(sys_unlinkat_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -5948,8 +5670,7 @@ FILLER(sys_unlinkat_x, true) /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)bpf_syscall_get_argument(data, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } res = bpf_push_s64_to_ring(data, (int64_t)dirfd); @@ -5962,11 +5683,10 @@ FILLER(sys_unlinkat_x, true) /* Parameter 4: flags (type: PT_FLAGS32) */ unsigned long flags = bpf_syscall_get_argument(data, 2); - return bpf_push_u32_to_ring(data, unlinkat_flags_to_scap((int32_t) flags)); + return bpf_push_u32_to_ring(data, unlinkat_flags_to_scap((int32_t)flags)); } -FILLER(sys_mkdirat_x, true) -{ +FILLER(sys_mkdirat_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -5974,15 +5694,14 @@ FILLER(sys_mkdirat_x, true) /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)bpf_syscall_get_argument(data, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } res = bpf_push_s64_to_ring(data, (int64_t)dirfd); CHECK_RES(res); /* Parameter 3: path (type: PT_FSRELPATH) */ - unsigned long path_pointer = bpf_syscall_get_argument(data, 1); + unsigned long path_pointer = bpf_syscall_get_argument(data, 1); res = bpf_val_to_ring(data, path_pointer); CHECK_RES(res); @@ -5991,8 +5710,7 @@ FILLER(sys_mkdirat_x, true) return bpf_push_u32_to_ring(data, mode); } -FILLER(sys_linkat_x, true) -{ +FILLER(sys_linkat_x, true) { unsigned long val; long retval; int res; @@ -6005,7 +5723,7 @@ FILLER(sys_linkat_x, true) * olddir */ val = bpf_syscall_get_argument(data, 0); - if ((int)val == AT_FDCWD) + if((int)val == AT_FDCWD) val = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, val); @@ -6022,7 +5740,7 @@ FILLER(sys_linkat_x, true) * newdir */ val = bpf_syscall_get_argument(data, 2); - if ((int)val == AT_FDCWD) + if((int)val == AT_FDCWD) val = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, val); @@ -6039,11 +5757,10 @@ FILLER(sys_linkat_x, true) * flags */ val = bpf_syscall_get_argument(data, 4); - return bpf_push_u32_to_ring(data, linkat_flags_to_scap((int32_t) val)); + return bpf_push_u32_to_ring(data, linkat_flags_to_scap((int32_t)val)); } -FILLER(sys_autofill, true) -{ +FILLER(sys_autofill, true) { const struct ppm_event_entry *evinfo; int res; int j; @@ -6056,25 +5773,24 @@ FILLER(sys_autofill, true) * We are interested in the return value only inside the exit events. * Remember that all exit events have an odd `PPM`code. */ - if(data->state->tail_ctx.evt_type % 2 != 0) - { + if(data->state->tail_ctx.evt_type % 2 != 0) { ret = bpf_syscall_get_retval(data->ctx); } evinfo = data->filler_info; - #pragma unroll - for (j = 0; j < PPM_MAX_AUTOFILL_ARGS; j++) { +#pragma unroll + for(j = 0; j < PPM_MAX_AUTOFILL_ARGS; j++) { struct ppm_autofill_arg arg = evinfo->autofill_args[j]; - if (j == evinfo->n_autofill_args) + if(j == evinfo->n_autofill_args) break; - if (arg.id >= 0) + if(arg.id >= 0) val = bpf_syscall_get_argument(data, arg.id); - else if (arg.id == AF_ID_RETVAL) + else if(arg.id == AF_ID_RETVAL) val = ret; - else if (arg.id == AF_ID_USEDEFAULT) + else if(arg.id == AF_ID_USEDEFAULT) val = arg.default_val; // TODO HOW TO avoid using bpf_val_to_ring? @@ -6085,8 +5801,7 @@ FILLER(sys_autofill, true) return res; } -FILLER(sys_fchmodat_x, true) -{ +FILLER(sys_fchmodat_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6094,8 +5809,7 @@ FILLER(sys_fchmodat_x, true) /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)bpf_syscall_get_argument(data, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } res = bpf_push_s64_to_ring(data, (int64_t)dirfd); @@ -6111,8 +5825,7 @@ FILLER(sys_fchmodat_x, true) return bpf_push_u32_to_ring(data, chmod_mode_to_scap(mode)); } -FILLER(sys_chmod_x, true) -{ +FILLER(sys_chmod_x, true) { unsigned long val; int res; long retval; @@ -6133,8 +5846,7 @@ FILLER(sys_chmod_x, true) return bpf_push_u32_to_ring(data, val); } -FILLER(sys_fchmod_x, true) -{ +FILLER(sys_fchmod_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6150,8 +5862,7 @@ FILLER(sys_fchmod_x, true) return bpf_push_u32_to_ring(data, chmod_mode_to_scap(mode)); } -FILLER(sys_chown_x, true) -{ +FILLER(sys_chown_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6172,8 +5883,7 @@ FILLER(sys_chown_x, true) return bpf_push_u32_to_ring(data, gid); } -FILLER(sys_lchown_x, true) -{ +FILLER(sys_lchown_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6194,8 +5904,7 @@ FILLER(sys_lchown_x, true) return bpf_push_u32_to_ring(data, gid); } -FILLER(sys_fchown_x, true) -{ +FILLER(sys_fchown_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6216,8 +5925,7 @@ FILLER(sys_fchown_x, true) return bpf_push_u32_to_ring(data, gid); } -FILLER(sys_fchownat_x, true) -{ +FILLER(sys_fchownat_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6225,8 +5933,7 @@ FILLER(sys_fchownat_x, true) /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)bpf_syscall_get_argument(data, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } res = bpf_push_s64_to_ring(data, (int64_t)dirfd); @@ -6252,8 +5959,7 @@ FILLER(sys_fchownat_x, true) return bpf_push_u32_to_ring(data, fchownat_flags_to_scap(flags)); } -FILLER(sys_copy_file_range_e, true) -{ +FILLER(sys_copy_file_range_e, true) { int res = 0; /* Parameter 1: fdin (type: PT_FD) */ @@ -6271,8 +5977,7 @@ FILLER(sys_copy_file_range_e, true) return bpf_push_u64_to_ring(data, len); } -FILLER(sys_copy_file_range_x, true) -{ +FILLER(sys_copy_file_range_x, true) { int fdout; unsigned long offout; long retval; @@ -6280,37 +5985,36 @@ FILLER(sys_copy_file_range_x, true) retval = bpf_syscall_get_retval(data->ctx); res = bpf_push_s64_to_ring(data, retval); - + /* - * fdout - */ + * fdout + */ fdout = bpf_syscall_get_argument(data, 2); res = bpf_push_s64_to_ring(data, fdout); CHECK_RES(res); /* - * offout - */ + * offout + */ offout = bpf_syscall_get_argument(data, 3); res = bpf_push_u64_to_ring(data, offout); CHECK_RES(res); - + return res; } -FILLER(sys_capset_x, true) -{ +FILLER(sys_capset_x, true) { unsigned long val; int res; long retval; kernel_cap_t cap; - + retval = bpf_syscall_get_retval(data->ctx); res = bpf_push_s64_to_ring(data, retval); CHECK_RES(res); - struct task_struct *task = (struct task_struct *) bpf_get_current_task(); - struct cred *cred = (struct cred*) _READ(task->cred); + struct task_struct *task = (struct task_struct *)bpf_get_current_task(); + struct cred *cred = (struct cred *)_READ(task->cred); cap = _READ(cred->cap_inheritable); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) @@ -6339,8 +6043,7 @@ FILLER(sys_capset_x, true) return bpf_push_u64_to_ring(data, capabilities_to_scap(val)); } -FILLER(sys_splice_e, true) -{ +FILLER(sys_splice_e, true) { unsigned long val; int32_t fd; int res; @@ -6365,15 +6068,13 @@ FILLER(sys_splice_e, true) return bpf_push_u32_to_ring(data, splice_flags_to_scap(val)); } -FILLER(sys_dup_e, true) -{ +FILLER(sys_dup_e, true) { /* Parameter 1: oldfd (type: PT_FD) */ int32_t oldfd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)oldfd); } -FILLER(sys_dup_x, true) -{ +FILLER(sys_dup_x, true) { unsigned long val; unsigned long retval; unsigned long res; @@ -6388,15 +6089,13 @@ FILLER(sys_dup_x, true) return bpf_push_s64_to_ring(data, val); } -FILLER(sys_dup2_e, true) -{ +FILLER(sys_dup2_e, true) { /* Parameter 1: oldfd (type: PT_FD) */ int32_t oldfd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)oldfd); } -FILLER(sys_dup2_x, true) -{ +FILLER(sys_dup2_x, true) { unsigned long val; unsigned long retval; unsigned long res; @@ -6418,15 +6117,13 @@ FILLER(sys_dup2_x, true) return bpf_push_s64_to_ring(data, val); } -FILLER(sys_dup3_e, true) -{ +FILLER(sys_dup3_e, true) { /* Parameter 1: oldfd (type: PT_FD) */ int32_t oldfd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)oldfd); } -FILLER(sys_dup3_x, true) -{ +FILLER(sys_dup3_x, true) { unsigned long val; unsigned long retval; unsigned long res; @@ -6455,8 +6152,7 @@ FILLER(sys_dup3_x, true) return bpf_push_u32_to_ring(data, dup3_flags_to_scap(flags)); } -FILLER(sys_umount_x, true) -{ +FILLER(sys_umount_x, true) { /* Parameter 1: ret (type: PT_FD) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6464,18 +6160,16 @@ FILLER(sys_umount_x, true) /* Parameter 2: name (type: PT_FSPATH) */ unsigned long target_pointer = bpf_syscall_get_argument(data, 0); - return bpf_val_to_ring(data, target_pointer); + return bpf_val_to_ring(data, target_pointer); } -FILLER(sys_umount2_e, true) -{ +FILLER(sys_umount2_e, true) { /* Parameter 1: flags (type: PT_FLAGS32) */ int flags = (int)bpf_syscall_get_argument(data, 1); return bpf_push_u32_to_ring(data, umount2_flags_to_scap(flags)); } -FILLER(sys_umount2_x, true) -{ +FILLER(sys_umount2_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -6483,40 +6177,35 @@ FILLER(sys_umount2_x, true) /* Parameter 2: name (type: PT_FSPATH) */ unsigned long target_pointer = bpf_syscall_get_argument(data, 0); - return bpf_val_to_ring(data, target_pointer); + return bpf_val_to_ring(data, target_pointer); } -FILLER(sys_getcwd_x, true) -{ +FILLER(sys_getcwd_x, true) { /* Parameter 1: res (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); CHECK_RES(res); - /* we get the path only in case of success, in case of failure we would read only userspace junk */ - if(retval >= 0) - { + /* we get the path only in case of success, in case of failure we would read only userspace junk + */ + if(retval >= 0) { /* Parameter 2: path (type: PT_CHARBUF) */ unsigned long path_pointer = bpf_syscall_get_argument(data, 0); res = bpf_val_to_ring(data, path_pointer); - } - else - { + } else { /* Parameter 2: path (type: PT_CHARBUF) */ res = bpf_push_empty_param(data); } return res; } -FILLER(sys_getdents_e, true) -{ +FILLER(sys_getdents_e, true) { /* Parameter 1: fd (type: PT_FD)*/ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)fd); } -FILLER(sys_getdents64_e, true) -{ +FILLER(sys_getdents64_e, true) { /* Parameter 1: fd (type: PT_FD)*/ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); return bpf_push_s64_to_ring(data, (int64_t)fd); @@ -6526,12 +6215,11 @@ FILLER(sys_getdents64_e, true) /* We set `is_syscall` flag to `false` since this is not * a real syscall, we only send the same event from another * tracepoint. - * - * These `sched_proc_exec` fillers will generate a + * + * These `sched_proc_exec` fillers will generate a * `PPME_SYSCALL_EXECVE_19_X` event. */ -FILLER(sched_prog_exec, false) -{ +FILLER(sched_prog_exec, false) { int res = 0; /* Parameter 1: res (type: PT_ERRNO) */ @@ -6543,8 +6231,7 @@ FILLER(sched_prog_exec, false) struct task_struct *task = (struct task_struct *)bpf_get_current_task(); struct mm_struct *mm = _READ(task->mm); - if(!mm) - { + if(!mm) { return PPM_FAILURE_BUG; } @@ -6559,36 +6246,36 @@ FILLER(sched_prog_exec, false) unsigned long args_len = arg_end - arg_start; - if(args_len > ARGS_ENV_SIZE_MAX) - { + if(args_len > ARGS_ENV_SIZE_MAX) { args_len = ARGS_ENV_SIZE_MAX; } /* `bpf_probe_read()` returns 0 in case of success. */ #ifdef BPF_FORBIDS_ZERO_ACCESS - int correctly_read = bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - ((args_len - 1) & SCRATCH_SIZE_HALF) + 1, - (void *)arg_start); -#else - int correctly_read = bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - args_len & SCRATCH_SIZE_HALF, - (void *)arg_start); + int correctly_read = + bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + ((args_len - 1) & SCRATCH_SIZE_HALF) + 1, + (void *)arg_start); +#else + int correctly_read = + bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + args_len & SCRATCH_SIZE_HALF, + (void *)arg_start); #endif /* BPF_FORBIDS_ZERO_ACCESS */ /* If there was something to read and we read it correctly, update all * the offsets, otherwise push empty params to userspace. */ - if(args_len && correctly_read == 0) - { + if(args_len && correctly_read == 0) { data->buf[(data->state->tail_ctx.curoff + args_len - 1) & SCRATCH_SIZE_MAX] = 0; /* We need the len of the second param `exe`. */ - int exe_len = bpf_probe_read_kernel_str(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - SCRATCH_SIZE_HALF, - &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF]); + int exe_len = bpf_probe_read_kernel_str( + &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + SCRATCH_SIZE_HALF, + &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF]); - if(exe_len == -EFAULT) - { + if(exe_len == -EFAULT) { return PPM_FAILURE_INVALID_USER_MEMORY; } @@ -6601,9 +6288,7 @@ FILLER(sched_prog_exec, false) data->curarg_already_on_frame = true; res = __bpf_val_to_ring(data, 0, args_len - exe_len, PT_BYTEBUF, -1, false, KERNEL); CHECK_RES(res); - } - else - { + } else { /* Parameter 2: exe (type: PT_CHARBUF) */ res = bpf_push_empty_param(data); CHECK_RES(res); @@ -6656,8 +6341,7 @@ FILLER(sched_prog_exec, false) unsigned long total_rss = 0; unsigned long swap = 0; - if(mm) - { + if(mm) { total_vm = _READ(mm->total_vm); total_vm <<= (PAGE_SHIFT - 10); total_rss = bpf_get_mm_rss(mm) << (PAGE_SHIFT - 10); @@ -6685,8 +6369,7 @@ FILLER(sched_prog_exec, false) return PPM_FAILURE_BUG; } -FILLER(sched_prog_exec_2, false) -{ +FILLER(sched_prog_exec_2, false) { int cgroups_len = 0; int res = 0; struct task_struct *task = (struct task_struct *)bpf_get_current_task(); @@ -6695,7 +6378,13 @@ FILLER(sched_prog_exec_2, false) CHECK_RES(res); /* Parameter 15: cgroups (type: PT_CHARBUFARRAY) */ - res = __bpf_val_to_ring(data, (unsigned long)data->tmp_scratch, cgroups_len, PT_BYTEBUF, -1, false, KERNEL); + res = __bpf_val_to_ring(data, + (unsigned long)data->tmp_scratch, + cgroups_len, + PT_BYTEBUF, + -1, + false, + KERNEL); CHECK_RES(res); bpf_tail_call(data->ctx, &tail_map, PPM_FILLER_sched_prog_exec_3); @@ -6703,14 +6392,12 @@ FILLER(sched_prog_exec_2, false) return PPM_FAILURE_BUG; } -FILLER(sched_prog_exec_3, false) -{ +FILLER(sched_prog_exec_3, false) { int res = 0; struct task_struct *task = (struct task_struct *)bpf_get_current_task(); struct mm_struct *mm = _READ(task->mm); - if(!mm) - { + if(!mm) { return PPM_FAILURE_BUG; } @@ -6718,27 +6405,23 @@ FILLER(sched_prog_exec_3, false) unsigned long env_end = _READ(mm->env_end); long env_len = env_end - env_start; - if(env_len) - { - if(env_len > ARGS_ENV_SIZE_MAX) - { + if(env_len) { + if(env_len > ARGS_ENV_SIZE_MAX) { env_len = ARGS_ENV_SIZE_MAX; } #ifdef BPF_FORBIDS_ZERO_ACCESS if(bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - ((env_len - 1) & SCRATCH_SIZE_HALF) + 1, - (void *)env_start)) + ((env_len - 1) & SCRATCH_SIZE_HALF) + 1, + (void *)env_start)) #else if(bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - env_len & SCRATCH_SIZE_HALF, - (void *)env_start)) + env_len & SCRATCH_SIZE_HALF, + (void *)env_start)) #endif /* BPF_FORBIDS_ZERO_ACCESS */ { env_len = 0; - } - else - { + } else { data->buf[(data->state->tail_ctx.curoff + env_len - 1) & SCRATCH_SIZE_MAX] = 0; } } @@ -6759,16 +6442,14 @@ FILLER(sched_prog_exec_3, false) /* TODO: implement user namespace support */ kuid_t loginuid; -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0) && CONFIG_AUDIT) || (LINUX_VERSION_CODE < KERNEL_VERSION(5, 1, 0) && CONFIG_AUDITSYSCALL) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0) && CONFIG_AUDIT) || \ + (LINUX_VERSION_CODE < KERNEL_VERSION(5, 1, 0) && CONFIG_AUDITSYSCALL) #ifdef COS_73_WORKAROUND { struct audit_task_info *audit = _READ(task->audit); - if(audit) - { + if(audit) { loginuid = _READ(audit->loginuid); - } - else - { + } else { loginuid = INVALID_UID; } } @@ -6788,8 +6469,7 @@ FILLER(sched_prog_exec_3, false) return PPM_FAILURE_BUG; } -FILLER(sched_prog_exec_4, false) -{ +FILLER(sched_prog_exec_4, false) { struct task_struct *task = (struct task_struct *)bpf_get_current_task(); struct cred *cred = (struct cred *)_READ(task->cred); struct file *exe_file = get_exe_file(task); @@ -6797,14 +6477,12 @@ FILLER(sched_prog_exec_4, false) uint32_t flags = 0; kuid_t euid = {0}; - if(inode) - { + if(inode) { /* * exe_writable */ bool exe_writable = get_exe_writable(inode, cred); - if (exe_writable) - { + if(exe_writable) { flags |= PPM_EXE_WRITABLE; } } @@ -6812,20 +6490,15 @@ FILLER(sched_prog_exec_4, false) /* * exe_upper_layer/exe_lower_layer and exe_from_memfd */ - if(exe_file) - { + if(exe_file) { enum ppm_overlay exe_layer = get_overlay_layer(exe_file); - if (exe_layer == PPM_OVERLAY_UPPER) - { + if(exe_layer == PPM_OVERLAY_UPPER) { flags |= PPM_EXE_UPPER_LAYER; - } - else if (exe_layer == PPM_OVERLAY_LOWER) - { + } else if(exe_layer == PPM_OVERLAY_LOWER) { flags |= PPM_EXE_LOWER_LAYER; } - if(get_exe_from_memfd(exe_file)) - { + if(get_exe_from_memfd(exe_file)) { flags |= PPM_EXE_FROM_MEMFD; } } @@ -6837,7 +6510,9 @@ FILLER(sched_prog_exec_4, false) /* Parameter 21: cap_inheritable (type: PT_UINT64) */ kernel_cap_t cap = _READ(cred->cap_inheritable); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) - res = bpf_push_u64_to_ring(data, capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); + res = bpf_push_u64_to_ring( + data, + capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); #else res = bpf_push_u64_to_ring(data, capabilities_to_scap((unsigned long)cap.val)); #endif @@ -6846,7 +6521,9 @@ FILLER(sched_prog_exec_4, false) /* Parameter 22: cap_permitted (type: PT_UINT64) */ cap = _READ(cred->cap_permitted); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) - res = bpf_push_u64_to_ring(data, capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); + res = bpf_push_u64_to_ring( + data, + capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); #else res = bpf_push_u64_to_ring(data, capabilities_to_scap((unsigned long)cap.val)); #endif @@ -6855,7 +6532,9 @@ FILLER(sched_prog_exec_4, false) /* Parameter 23: cap_effective (type: PT_UINT64) */ cap = _READ(cred->cap_effective); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) - res = bpf_push_u64_to_ring(data, capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); + res = bpf_push_u64_to_ring( + data, + capabilities_to_scap(((unsigned long)cap.cap[1] << 32) | cap.cap[0])); #else res = bpf_push_u64_to_ring(data, capabilities_to_scap((unsigned long)cap.val)); #endif @@ -6868,7 +6547,8 @@ FILLER(sched_prog_exec_4, false) struct timespec64 time = {0}; - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0) time.tv_sec = _READ(inode->i_ctime_sec); time.tv_nsec = _READ((inode->i_ctime_nsec); @@ -6880,7 +6560,8 @@ FILLER(sched_prog_exec_4, false) res = bpf_push_u64_to_ring(data, bpf_epoch_ns_from_time(time)); CHECK_RES(res); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0) time.tv_sec = _READ(inode->i_mtime_sec); time.tv_nsec = _READ(inode->i_mtime_nsec); @@ -6902,20 +6583,16 @@ FILLER(sched_prog_exec_4, false) return PPM_FAILURE_BUG; } -FILLER(sched_prog_exec_5, false) -{ +FILLER(sched_prog_exec_5, false) { int res = 0; /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ struct task_struct *task = (struct task_struct *)bpf_get_current_task(); struct file *exe_file = get_exe_file(task); - if(exe_file != NULL) - { - char* filepath = bpf_d_path_approx(data, &(exe_file->f_path)); - res = bpf_val_to_ring_mem(data,(unsigned long)filepath, KERNEL); - } - else - { + if(exe_file != NULL) { + char *filepath = bpf_d_path_approx(data, &(exe_file->f_path)); + res = bpf_val_to_ring_mem(data, (unsigned long)filepath, KERNEL); + } else { res = bpf_push_empty_param(data); } @@ -6925,14 +6602,13 @@ FILLER(sched_prog_exec_5, false) #endif #ifdef CAPTURE_SCHED_PROC_FORK -/* These `sched_proc_fork` fillers will generate a +/* These `sched_proc_fork` fillers will generate a * `PPME_SYSCALL_CLONE_20_X` event. - * + * * Please note: `is_syscall` is used only if `BPF_RAW_TRACEPOINT` * are not defined. */ -FILLER(sched_prog_fork, false) -{ +FILLER(sched_prog_fork, false) { int res = 0; /* First of all we need to update the event header with the child tid. @@ -6940,7 +6616,8 @@ FILLER(sched_prog_fork, false) * we are sending this event, we are still the parent so we have to * modify the event header to simulate it. */ - struct sched_process_fork_raw_args* original_ctx = (struct sched_process_fork_raw_args*)data->ctx; + struct sched_process_fork_raw_args *original_ctx = + (struct sched_process_fork_raw_args *)data->ctx; struct task_struct *child = (struct task_struct *)original_ctx->child; pid_t child_pid = _READ(child->pid); @@ -6955,16 +6632,15 @@ FILLER(sched_prog_fork, false) CHECK_RES(res); struct mm_struct *mm = _READ(child->mm); - if(!mm) - { + if(!mm) { return PPM_FAILURE_BUG; } /* - * The call always succeed so get `exe`, `args` from the current - * process; put one \0-separated exe-args string into - * str_storage - */ + * The call always succeed so get `exe`, `args` from the current + * process; put one \0-separated exe-args string into + * str_storage + */ unsigned long arg_start = 0; unsigned long arg_end = 0; @@ -6973,30 +6649,29 @@ FILLER(sched_prog_fork, false) unsigned long args_len = arg_end - arg_start; - if(args_len > ARGS_ENV_SIZE_MAX) - { + if(args_len > ARGS_ENV_SIZE_MAX) { args_len = ARGS_ENV_SIZE_MAX; } /* `bpf_probe_read()` returns 0 in case of success. */ - int correctly_read = bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - args_len & SCRATCH_SIZE_HALF, - (void *)arg_start); + int correctly_read = + bpf_probe_read_user(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + args_len & SCRATCH_SIZE_HALF, + (void *)arg_start); /* If there was something to read and we read it correctly, update all * the offsets, otherwise push empty params to userspace. */ - if(args_len && correctly_read == 0) - { + if(args_len && correctly_read == 0) { data->buf[(data->state->tail_ctx.curoff + args_len - 1) & SCRATCH_SIZE_MAX] = 0; /* We need the len of the second param `exe`. */ - int exe_len = bpf_probe_read_kernel_str(&data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], - SCRATCH_SIZE_HALF, - &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF]); + int exe_len = bpf_probe_read_kernel_str( + &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF], + SCRATCH_SIZE_HALF, + &data->buf[data->state->tail_ctx.curoff & SCRATCH_SIZE_HALF]); - if(exe_len == -EFAULT) - { + if(exe_len == -EFAULT) { return PPM_FAILURE_INVALID_USER_MEMORY; } @@ -7009,9 +6684,7 @@ FILLER(sched_prog_fork, false) data->curarg_already_on_frame = true; res = __bpf_val_to_ring(data, 0, args_len - exe_len, PT_BYTEBUF, -1, false, KERNEL); CHECK_RES(res); - } - else - { + } else { /* Parameter 2: exe (type: PT_CHARBUF) */ res = bpf_push_empty_param(data); CHECK_RES(res); @@ -7064,8 +6737,7 @@ FILLER(sched_prog_fork, false) unsigned long total_rss = 0; unsigned long swap = 0; - if(mm) - { + if(mm) { total_vm = _READ(mm->total_vm); total_vm <<= (PAGE_SHIFT - 10); total_rss = bpf_get_mm_rss(mm) << (PAGE_SHIFT - 10); @@ -7093,18 +6765,24 @@ FILLER(sched_prog_fork, false) return PPM_FAILURE_BUG; } -FILLER(sched_prog_fork_2, false) -{ +FILLER(sched_prog_fork_2, false) { int res = 0; int cgroups_len = 0; - struct sched_process_fork_raw_args* original_ctx = (struct sched_process_fork_raw_args*)data->ctx; + struct sched_process_fork_raw_args *original_ctx = + (struct sched_process_fork_raw_args *)data->ctx; struct task_struct *child = (struct task_struct *)original_ctx->child; res = bpf_append_cgroup(child, data->tmp_scratch, &cgroups_len); CHECK_RES(res); /* Parameter 15: cgroups (type: PT_CHARBUFARRAY) */ - res = __bpf_val_to_ring(data, (unsigned long)data->tmp_scratch, cgroups_len, PT_BYTEBUF, -1, false, KERNEL); + res = __bpf_val_to_ring(data, + (unsigned long)data->tmp_scratch, + cgroups_len, + PT_BYTEBUF, + -1, + false, + KERNEL); CHECK_RES(res); bpf_tail_call(data->ctx, &tail_map, PPM_FILLER_sched_prog_fork_3); @@ -7112,10 +6790,10 @@ FILLER(sched_prog_fork_2, false) return PPM_FAILURE_BUG; } -FILLER(sched_prog_fork_3, false) -{ +FILLER(sched_prog_fork_3, false) { int res = 0; - struct sched_process_fork_raw_args* original_ctx = (struct sched_process_fork_raw_args*)data->ctx; + struct sched_process_fork_raw_args *original_ctx = + (struct sched_process_fork_raw_args *)data->ctx; struct task_struct *child = (struct task_struct *)original_ctx->child; struct task_struct *parent = (struct task_struct *)original_ctx->parent; uint32_t flags = 0; @@ -7123,37 +6801,34 @@ FILLER(sched_prog_fork_3, false) /* Since Linux 2.5.35, the flags mask must also include * CLONE_SIGHAND if CLONE_THREAD is specified (and note that, * since Linux 2.6.0, CLONE_SIGHAND also requires CLONE_VM to - * be included). + * be included). * Taken from https://man7.org/linux/man-pages/man2/clone.2.html */ pid_t tid = _READ(child->pid); pid_t tgid = _READ(child->tgid); - if(tid != tgid) - { + if(tid != tgid) { flags |= PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM; } - + /* If CLONE_FILES is set, the calling process and the child * process share the same file descriptor table. * Taken from https://man7.org/linux/man-pages/man2/clone.2.html */ - struct files_struct * file_struct = NULL; - struct files_struct * parent_file_struct = NULL; + struct files_struct *file_struct = NULL; + struct files_struct *parent_file_struct = NULL; file_struct = _READ(child->files); parent_file_struct = _READ(parent->files); - if(parent_file_struct == file_struct) - { + if(parent_file_struct == file_struct) { flags |= PPM_CL_CLONE_FILES; } - /* It's possible to have a process in a PID namespace that + /* It's possible to have a process in a PID namespace that * nevertheless has tid == vtid, so we need to generate this * custom flag `PPM_CL_CHILD_IN_PIDNS`. */ struct pid_namespace *pidns = bpf_task_active_pid_ns(child); int pidns_level = _READ(pidns->level); - if(pidns_level != 0) - { + if(pidns_level != 0) { flags |= PPM_CL_CHILD_IN_PIDNS; } @@ -7185,8 +6860,7 @@ FILLER(sched_prog_fork_3, false) /* Parameter 21: pid_namespace init task start_time monotonic time in ns (type: PT_UINT64) */ uint64_t pidns_init_start_time = 0; - if (pidns) - { + if(pidns) { struct task_struct *child_reaper = (struct task_struct *)_READ(pidns->child_reaper); pidns_init_start_time = _READ(child_reaper->start_time); } @@ -7194,8 +6868,7 @@ FILLER(sched_prog_fork_3, false) } #endif -FILLER(sys_prctl_x, true) -{ +FILLER(sys_prctl_x, true) { unsigned long option; unsigned long arg2; unsigned long arg2_int; @@ -7216,54 +6889,53 @@ FILLER(sys_prctl_x, true) arg2 = bpf_syscall_get_argument(data, 1); - switch(option){ - case PPM_PR_GET_NAME: - case PPM_PR_SET_NAME: - /* - * arg2_str - */ - res = bpf_val_to_ring(data, arg2); - CHECK_RES(res); - /* - * arg2_int - */ - res = bpf_push_s64_to_ring(data, 0); - CHECK_RES(res); - break; - case PPM_PR_GET_CHILD_SUBREAPER: - /* - * arg2_str - */ - res = bpf_push_empty_param(data); - CHECK_RES(res); - /* - * arg2_int - */ - reaper_attr = 0; - bpf_probe_read_user(&reaper_attr, sizeof(reaper_attr), (void*)arg2); - res = bpf_push_s64_to_ring(data, (int64_t)reaper_attr); - CHECK_RES(res); - break; - case PPM_PR_SET_CHILD_SUBREAPER: - default: - /* - * arg2_str - */ - res = bpf_push_empty_param(data); - CHECK_RES(res); - /* - * arg2_int - */ - res = bpf_push_s64_to_ring(data, arg2); - CHECK_RES(res); - break; + switch(option) { + case PPM_PR_GET_NAME: + case PPM_PR_SET_NAME: + /* + * arg2_str + */ + res = bpf_val_to_ring(data, arg2); + CHECK_RES(res); + /* + * arg2_int + */ + res = bpf_push_s64_to_ring(data, 0); + CHECK_RES(res); + break; + case PPM_PR_GET_CHILD_SUBREAPER: + /* + * arg2_str + */ + res = bpf_push_empty_param(data); + CHECK_RES(res); + /* + * arg2_int + */ + reaper_attr = 0; + bpf_probe_read_user(&reaper_attr, sizeof(reaper_attr), (void *)arg2); + res = bpf_push_s64_to_ring(data, (int64_t)reaper_attr); + CHECK_RES(res); + break; + case PPM_PR_SET_CHILD_SUBREAPER: + default: + /* + * arg2_str + */ + res = bpf_push_empty_param(data); + CHECK_RES(res); + /* + * arg2_int + */ + res = bpf_push_s64_to_ring(data, arg2); + CHECK_RES(res); + break; } return res; } -FILLER(sys_memfd_create_x,true) -{ +FILLER(sys_memfd_create_x, true) { /* Parameter 1: ret (type: PT_FD) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -7279,8 +6951,7 @@ FILLER(sys_memfd_create_x,true) return bpf_push_u32_to_ring(data, memfd_create_flags_to_scap(flags)); } -FILLER(sys_pidfd_getfd_x, true) -{ +FILLER(sys_pidfd_getfd_x, true) { /* Parameter 1: ret (type: PT_FD) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -7295,19 +6966,17 @@ FILLER(sys_pidfd_getfd_x, true) int32_t targetfd = bpf_syscall_get_argument(data, 1); res = bpf_push_s64_to_ring(data, (int64_t)targetfd); CHECK_RES(res); - + /* Parameter 4: flags (type: PT_UINT32) */ - uint32_t flags = bpf_syscall_get_argument(data,2); - /* - The flags argument is reserved for future use. Currently, it must be specified as 0. - See https://elixir.bootlin.com/linux/latest/source/kernel/pid.c#L709 - */ + uint32_t flags = bpf_syscall_get_argument(data, 2); + /* + The flags argument is reserved for future use. Currently, it must be specified as 0. + See https://elixir.bootlin.com/linux/latest/source/kernel/pid.c#L709 + */ return bpf_push_u32_to_ring(data, flags); } -FILLER(sys_pidfd_open_x, true) -{ - +FILLER(sys_pidfd_open_x, true) { /* Parameter 1: ret (type: PT_FD) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -7321,12 +6990,9 @@ FILLER(sys_pidfd_open_x, true) /* Parameter 3: flags (type: PT_FLAGS32)*/ uint32_t flags = bpf_syscall_get_argument(data, 1); return bpf_push_u32_to_ring(data, pidfd_open_flags_to_scap(flags)); - } -FILLER(sys_init_module_x, true) -{ - +FILLER(sys_init_module_x, true) { /* Parameter 1: ret (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -7348,9 +7014,7 @@ FILLER(sys_init_module_x, true) return bpf_val_to_ring(data, uargs); } -FILLER(sys_finit_module_x, true) -{ - +FILLER(sys_finit_module_x, true) { /* Parameter 1: ret (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -7371,9 +7035,7 @@ FILLER(sys_finit_module_x, true) return bpf_push_u32_to_ring(data, finit_module_flags_to_scap(flags)); } -FILLER(sys_mknod_x, true) -{ - +FILLER(sys_mknod_x, true) { /* Parameter 1: ret (type: PT_ERRNO) */ long retval = bpf_syscall_get_retval(data->ctx); int res = bpf_push_s64_to_ring(data, retval); @@ -7394,8 +7056,7 @@ FILLER(sys_mknod_x, true) return bpf_push_u32_to_ring(data, bpf_encode_dev(dev)); } -FILLER(sys_mknodat_x, true) -{ +FILLER(sys_mknodat_x, true) { unsigned long val; int32_t fd; @@ -7406,7 +7067,7 @@ FILLER(sys_mknodat_x, true) /* Parameter 2: fd (type: PT_FD) */ fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); CHECK_RES(res); @@ -7426,8 +7087,7 @@ FILLER(sys_mknodat_x, true) return bpf_push_u32_to_ring(data, bpf_encode_dev(dev)); } -FILLER(sys_newfstatat_x, true) -{ +FILLER(sys_newfstatat_x, true) { unsigned long val; /* Parameter 1: ret (type: PT_ERRNO) */ @@ -7437,7 +7097,7 @@ FILLER(sys_newfstatat_x, true) /* Parameter 2: fd (type: PT_FD) */ int32_t fd = (int32_t)bpf_syscall_get_argument(data, 0); - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = bpf_push_s64_to_ring(data, (int64_t)fd); CHECK_RES(res); @@ -7452,9 +7112,7 @@ FILLER(sys_newfstatat_x, true) return bpf_push_u32_to_ring(data, newfstatat_flags_to_scap(flags)); } - -FILLER(sys_process_vm_readv_x, true) -{ +FILLER(sys_process_vm_readv_x, true) { const struct iovec __user *iov; unsigned long iovcnt; @@ -7469,27 +7127,19 @@ FILLER(sys_process_vm_readv_x, true) CHECK_RES(res); /* Parameter 3: data (type: PT_BYTEBUF) */ - if (retval > 0) - { + if(retval > 0) { iov = (const struct iovec __user *)bpf_syscall_get_argument(data, 1); iovcnt = bpf_syscall_get_argument(data, 2); - res = bpf_parse_readv_writev_bufs(data, - iov, - iovcnt, - retval, - PRB_FLAG_PUSH_DATA); - } - else - { + res = bpf_parse_readv_writev_bufs(data, iov, iovcnt, retval, PRB_FLAG_PUSH_DATA); + } else { res = bpf_push_empty_param(data); } return res; } -FILLER(sys_process_vm_writev_x, true) -{ +FILLER(sys_process_vm_writev_x, true) { const struct iovec __user *iov; unsigned long iovcnt; @@ -7504,27 +7154,19 @@ FILLER(sys_process_vm_writev_x, true) CHECK_RES(res); /* Parameter 3: data (type: PT_BYTEBUF) */ - if (retval > 0) - { + if(retval > 0) { iov = (const struct iovec __user *)bpf_syscall_get_argument(data, 1); iovcnt = bpf_syscall_get_argument(data, 2); - res = bpf_parse_readv_writev_bufs(data, - iov, - iovcnt, - retval, - PRB_FLAG_PUSH_DATA); - } - else - { + res = bpf_parse_readv_writev_bufs(data, iov, iovcnt, retval, PRB_FLAG_PUSH_DATA); + } else { res = bpf_push_empty_param(data); } return res; } -FILLER(sys_delete_module_x, true) -{ +FILLER(sys_delete_module_x, true) { long retval; int res; diff --git a/driver/bpf/maps.h b/driver/bpf/maps.h index b9601f7f6a..1a17658a55 100644 --- a/driver/bpf/maps.h +++ b/driver/bpf/maps.h @@ -22,92 +22,92 @@ struct bpf_map_def { #ifdef __KERNEL__ struct bpf_map_def __bpf_section("maps") perf_map = { - .type = BPF_MAP_TYPE_PERF_EVENT_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(uint32_t), - .max_entries = 0, + .type = BPF_MAP_TYPE_PERF_EVENT_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(uint32_t), + .max_entries = 0, }; struct bpf_map_def __bpf_section("maps") tail_map = { - .type = BPF_MAP_TYPE_PROG_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(uint32_t), - .max_entries = PPM_FILLER_MAX, + .type = BPF_MAP_TYPE_PROG_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(uint32_t), + .max_entries = PPM_FILLER_MAX, }; struct bpf_map_def __bpf_section("maps") syscall_table = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(struct syscall_evt_pair), - .max_entries = SYSCALL_TABLE_SIZE, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(struct syscall_evt_pair), + .max_entries = SYSCALL_TABLE_SIZE, }; struct bpf_map_def __bpf_section("maps") event_info_table = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(struct ppm_event_info), - .max_entries = PPM_EVENT_MAX, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(struct ppm_event_info), + .max_entries = PPM_EVENT_MAX, }; struct bpf_map_def __bpf_section("maps") fillers_table = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(struct ppm_event_entry), - .max_entries = PPM_EVENT_MAX, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(struct ppm_event_entry), + .max_entries = PPM_EVENT_MAX, }; struct bpf_map_def __bpf_section("maps") frame_scratch_map = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = SCRATCH_SIZE, - .max_entries = 0, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = SCRATCH_SIZE, + .max_entries = 0, }; struct bpf_map_def __bpf_section("maps") tmp_scratch_map = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = SCRATCH_SIZE, - .max_entries = 0, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = SCRATCH_SIZE, + .max_entries = 0, }; struct bpf_map_def __bpf_section("maps") settings_map = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(struct scap_bpf_settings), - .max_entries = 1, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(struct scap_bpf_settings), + .max_entries = 1, }; struct bpf_map_def __bpf_section("maps") local_state_map = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(struct scap_bpf_per_cpu_state), - .max_entries = 0, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(struct scap_bpf_per_cpu_state), + .max_entries = 0, }; struct bpf_map_def __bpf_section("maps") interesting_syscalls_table = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(bool), - .max_entries = SYSCALL_TABLE_SIZE, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(bool), + .max_entries = SYSCALL_TABLE_SIZE, }; // The key is the 32-bit syscall code while the value is 64-bit one struct bpf_map_def __bpf_section("maps") ia32_64_map = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(uint32_t), - .value_size = sizeof(uint32_t), - .max_entries = SYSCALL_TABLE_SIZE, + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(uint32_t), + .value_size = sizeof(uint32_t), + .max_entries = SYSCALL_TABLE_SIZE, }; #ifndef BPF_SUPPORTS_RAW_TRACEPOINTS struct bpf_map_def __bpf_section("maps") stash_map = { - .type = BPF_MAP_TYPE_HASH, - .key_size = sizeof(uint64_t), - .value_size = sizeof(struct sys_stash_args), - .max_entries = 65535, + .type = BPF_MAP_TYPE_HASH, + .key_size = sizeof(uint64_t), + .value_size = sizeof(struct sys_stash_args), + .max_entries = 65535, }; #endif -#endif // __KERNEL__ +#endif // __KERNEL__ #endif diff --git a/driver/bpf/missing_definitions.h b/driver/bpf/missing_definitions.h index e4c21f86ef..d76154ae8a 100644 --- a/driver/bpf/missing_definitions.h +++ b/driver/bpf/missing_definitions.h @@ -13,11 +13,11 @@ or GPL2.txt for full copies of the license. #include /* This require the inlclude `linux/mount.h` for `vfsmount` definition */ struct mount { - struct hlist_node mnt_hash; - struct mount *mnt_parent; - struct dentry *mnt_mountpoint; - struct vfsmount mnt; - // ... + struct hlist_node mnt_hash; + struct mount *mnt_parent; + struct dentry *mnt_mountpoint; + struct vfsmount mnt; + // ... }; #endif /*__BPF_MISSING_DEFINITIONS_H__*/ diff --git a/driver/bpf/plumbing_helpers.h b/driver/bpf/plumbing_helpers.h index 06a6032f4b..0fa1ae876e 100644 --- a/driver/bpf/plumbing_helpers.h +++ b/driver/bpf/plumbing_helpers.h @@ -18,65 +18,63 @@ or GPL2.txt for full copies of the license. #include "builtins.h" #include "socketcall_to_syscall.h" -#define _READ(P) ({ typeof(P) _val; \ - bpf_probe_read_kernel(&_val, sizeof(_val), &P); \ - _val; \ - }) +#define _READ(P) \ + ({ \ + typeof(P) _val; \ + bpf_probe_read_kernel(&_val, sizeof(_val), &P); \ + _val; \ + }) #define _READ_KERNEL(P) _READ(P) -#define _READ_USER(P) ({ typeof(P) _val; \ - bpf_probe_read_user(&_val, sizeof(_val), &P); \ - _val; \ - }) +#define _READ_USER(P) \ + ({ \ + typeof(P) _val; \ + bpf_probe_read_user(&_val, sizeof(_val), &P); \ + _val; \ + }) #ifdef BPF_DEBUG -#define bpf_printk(fmt, ...) \ - do { \ - char s[] = fmt; \ - bpf_trace_printk(s, sizeof(s), ##__VA_ARGS__); \ - } while (0) +#define bpf_printk(fmt, ...) \ + do { \ + char s[] = fmt; \ + bpf_trace_printk(s, sizeof(s), ##__VA_ARGS__); \ + } while(0) #else #define bpf_printk(fmt, ...) #endif #ifndef BPF_SUPPORTS_RAW_TRACEPOINTS -static __always_inline int __stash_args(unsigned long long id, - unsigned long *args) -{ +static __always_inline int __stash_args(unsigned long long id, unsigned long *args) { int ret = bpf_map_update_elem(&stash_map, &id, args, BPF_ANY); - if (ret) + if(ret) bpf_printk("error stashing arguments for %d:%d\n", id, ret); return ret; } -static __always_inline int stash_args(unsigned long *args) -{ +static __always_inline int stash_args(unsigned long *args) { unsigned long long id = bpf_get_current_pid_tgid() & 0xffffffff; return __stash_args(id, args); } -static __always_inline unsigned long *__unstash_args(unsigned long long id) -{ +static __always_inline unsigned long *__unstash_args(unsigned long long id) { struct sys_stash_args *args; args = bpf_map_lookup_elem(&stash_map, &id); - if (!args) + if(!args) return NULL; return args->args; } -static __always_inline unsigned long *unstash_args(void) -{ +static __always_inline unsigned long *unstash_args(void) { unsigned long long id = bpf_get_current_pid_tgid() & 0xffffffff; return __unstash_args(id); } -static __always_inline void delete_args(void) -{ +static __always_inline void delete_args(void) { unsigned long long id = bpf_get_current_pid_tgid() & 0xffffffff; bpf_map_delete_elem(&stash_map, &id); @@ -85,15 +83,13 @@ static __always_inline void delete_args(void) /* Can be called just from an exit event */ -static __always_inline long bpf_syscall_get_retval(void *ctx) -{ +static __always_inline long bpf_syscall_get_retval(void *ctx) { struct sys_exit_args *args = (struct sys_exit_args *)ctx; return args->ret; } -static __always_inline bool bpf_in_ia32_syscall() -{ +static __always_inline bool bpf_in_ia32_syscall() { struct task_struct *task = (struct task_struct *)bpf_get_current_task(); uint32_t status = 0; @@ -160,8 +156,7 @@ static __always_inline bool bpf_in_ia32_syscall() /* Can be called from both enter and exit event, id is at the same * offset in both struct sys_enter_args and struct sys_exit_args */ -static __always_inline long bpf_syscall_get_nr(void *ctx) -{ +static __always_inline long bpf_syscall_get_nr(void *ctx) { struct sys_enter_args *args = (struct sys_enter_args *)ctx; long id = 0; @@ -173,14 +168,14 @@ static __always_inline long bpf_syscall_get_nr(void *ctx) /* See here for the definition: * https://github.com/torvalds/linux/blob/69cb6c6556ad89620547318439d6be8bb1629a5a/arch/x86/include/asm/syscall.h#L40 - */ + */ id = _READ(regs->orig_ax); #elif CONFIG_ARM64 /* See here for the definition: * https://github.com/torvalds/linux/blob/69cb6c6556ad89620547318439d6be8bb1629a5a/arch/arm64/include/asm/syscall.h#L23 - */ + */ id = _READ(regs->syscallno); #elif CONFIG_S390 @@ -211,12 +206,10 @@ static __always_inline long bpf_syscall_get_nr(void *ctx) #ifndef BPF_SUPPORTS_RAW_TRACEPOINTS static __always_inline unsigned long bpf_syscall_get_argument_from_args(unsigned long *args, - int idx) -{ + int idx) { unsigned long arg = 0; - if(idx <= 5) - { + if(idx <= 5) { arg = args[idx]; } @@ -224,9 +217,7 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_args(unsigned } #endif -static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx, - int idx) -{ +static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx, int idx) { unsigned long arg = 0; #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS @@ -235,9 +226,8 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx struct pt_regs *regs = (struct pt_regs *)args->regs; #ifdef CONFIG_X86_64 - if (bpf_in_ia32_syscall()) - { - switch (idx) { + if(bpf_in_ia32_syscall()) { + switch(idx) { case 0: arg = _READ(regs->bx); break; @@ -265,7 +255,7 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx /* See here for the definition: * https://github.com/libbpf/libbpf/blob/master/src/bpf_tracing.h#L75-L87 */ - switch (idx) { + switch(idx) { case 0: arg = _READ(regs->di); break; @@ -291,10 +281,10 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx #elif CONFIG_ARM64 /* See here for the definition: - * https://github.com/libbpf/libbpf/blob/master/src/bpf_tracing.h#L166-L178 + * https://github.com/libbpf/libbpf/blob/master/src/bpf_tracing.h#L166-L178 */ struct user_pt_regs *user_regs = (struct user_pt_regs *)args->regs; - switch (idx) { + switch(idx) { case 0: arg = _READ(regs->orig_x0); break; @@ -310,12 +300,12 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx } #elif CONFIG_S390 - + /* See here for the definition: * https://github.com/libbpf/libbpf/blob/master/src/bpf_tracing.h#L132-L144 */ user_pt_regs *user_regs = (user_pt_regs *)args->regs; - switch (idx) { + switch(idx) { case 0: arg = _READ(regs->orig_gpr2); break; @@ -324,7 +314,7 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx case 3: case 4: case 5: - arg = _READ(user_regs->gprs[idx+2]); + arg = _READ(user_regs->gprs[idx + 2]); break; default: arg = 0; @@ -335,7 +325,7 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx /* See here for the definition: * https://github.com/libbpf/libbpf/blob/master/src/bpf_tracing.h#L290-L306 */ - switch (idx) { + switch(idx) { case 0: arg = _READ(regs->orig_gpr3); break; @@ -344,7 +334,7 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx case 3: case 4: case 5: - arg = _READ(regs->gpr[idx+3]); + arg = _READ(regs->gpr[idx + 3]); break; default: arg = 0; @@ -355,41 +345,40 @@ static __always_inline unsigned long bpf_syscall_get_argument_from_ctx(void *ctx #else unsigned long *args = unstash_args(); - if (args) + if(args) arg = bpf_syscall_get_argument_from_args(args, idx); else arg = 0; - + #endif /* BPF_SUPPORTS_RAW_TRACEPOINTS */ return arg; } -static __always_inline unsigned long bpf_syscall_get_socketcall_arg(void *ctx, int idx) -{ +static __always_inline unsigned long bpf_syscall_get_socketcall_arg(void *ctx, int idx) { unsigned long arg = 0; unsigned long args_pointer = 0; args_pointer = bpf_syscall_get_argument_from_ctx(ctx, 1); - if (bpf_in_ia32_syscall()) - { - bpf_probe_read_user(&arg, sizeof(uint32_t), (void*)(args_pointer + (idx * sizeof(uint32_t)))); - } - else - { - bpf_probe_read_user(&arg, sizeof(unsigned long), (void*)(args_pointer + (idx * sizeof(unsigned long)))); + if(bpf_in_ia32_syscall()) { + bpf_probe_read_user(&arg, + sizeof(uint32_t), + (void *)(args_pointer + (idx * sizeof(uint32_t)))); + } else { + bpf_probe_read_user(&arg, + sizeof(unsigned long), + (void *)(args_pointer + (idx * sizeof(unsigned long)))); } return arg; } -static __always_inline unsigned long bpf_syscall_get_argument(struct filler_data *data, - int idx) -{ +static __always_inline unsigned long bpf_syscall_get_argument(struct filler_data *data, int idx) { #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS - // We define it here because we support socket calls only on kernels with BPF_SUPPORTS_RAW_TRACEPOINTS - // `data->state->tail_ctx.socketcall_syscall_id != -1` just to improve perf - if(data->state->tail_ctx.socketcall_syscall_id != -1 && bpf_syscall_get_nr(data->ctx) == data->state->tail_ctx.socketcall_syscall_id) - { + // We define it here because we support socket calls only on kernels with + // BPF_SUPPORTS_RAW_TRACEPOINTS `data->state->tail_ctx.socketcall_syscall_id != -1` just to + // improve perf + if(data->state->tail_ctx.socketcall_syscall_id != -1 && + bpf_syscall_get_nr(data->ctx) == data->state->tail_ctx.socketcall_syscall_id) { return bpf_syscall_get_socketcall_arg(data->ctx, idx); } return bpf_syscall_get_argument_from_ctx(data->ctx, idx); @@ -398,45 +387,39 @@ static __always_inline unsigned long bpf_syscall_get_argument(struct filler_data #endif } -static __always_inline char *get_frame_scratch_area(unsigned int cpu) -{ +static __always_inline char *get_frame_scratch_area(unsigned int cpu) { char *scratchp; scratchp = bpf_map_lookup_elem(&frame_scratch_map, &cpu); - if (!scratchp) + if(!scratchp) bpf_printk("frame scratch NULL\n"); return scratchp; } -static __always_inline char *get_tmp_scratch_area(unsigned int cpu) -{ +static __always_inline char *get_tmp_scratch_area(unsigned int cpu) { char *scratchp; scratchp = bpf_map_lookup_elem(&tmp_scratch_map, &cpu); - if (!scratchp) + if(!scratchp) bpf_printk("tmp scratch NULL\n"); return scratchp; } -static __always_inline const struct syscall_evt_pair *get_syscall_info(int id) -{ - const struct syscall_evt_pair *p = - bpf_map_lookup_elem(&syscall_table, &id); +static __always_inline const struct syscall_evt_pair *get_syscall_info(int id) { + const struct syscall_evt_pair *p = bpf_map_lookup_elem(&syscall_table, &id); - if (!p) + if(!p) bpf_printk("no syscall_info for %d\n", id); return p; } -static __always_inline bool is_syscall_interesting(int id) -{ +static __always_inline bool is_syscall_interesting(int id) { bool *enabled = bpf_map_lookup_elem(&interesting_syscalls_table, &id); - if (!enabled) - { + if(!enabled) { bpf_printk("no syscall_info for %d\n", id); return false; } @@ -444,12 +427,10 @@ static __always_inline bool is_syscall_interesting(int id) return *enabled; } -static __always_inline int convert_ia32_to_64(int id) -{ +static __always_inline int convert_ia32_to_64(int id) { int *x64_id = bpf_map_lookup_elem(&ia32_64_map, &id); - if (!x64_id) - { + if(!x64_id) { bpf_printk("no 64bit mapped value for %d\n", id); return -1; } @@ -457,54 +438,49 @@ static __always_inline int convert_ia32_to_64(int id) return *x64_id; } -static __always_inline const struct ppm_event_info *get_event_info(ppm_event_code event_type) -{ - const struct ppm_event_info *e = - bpf_map_lookup_elem(&event_info_table, &event_type); +static __always_inline const struct ppm_event_info *get_event_info(ppm_event_code event_type) { + const struct ppm_event_info *e = bpf_map_lookup_elem(&event_info_table, &event_type); - if (!e) + if(!e) bpf_printk("no event info for %d\n", event_type); return e; } -static __always_inline const struct ppm_event_entry *get_event_filler_info(ppm_event_code event_type) -{ +static __always_inline const struct ppm_event_entry *get_event_filler_info( + ppm_event_code event_type) { const struct ppm_event_entry *e; e = bpf_map_lookup_elem(&fillers_table, &event_type); - if (!e) + if(!e) bpf_printk("no filler info for %d\n", event_type); return e; } -static __always_inline struct scap_bpf_settings *get_bpf_settings(void) -{ +static __always_inline struct scap_bpf_settings *get_bpf_settings(void) { struct scap_bpf_settings *settings; int id = 0; settings = bpf_map_lookup_elem(&settings_map, &id); - if (!settings) + if(!settings) bpf_printk("settings NULL\n"); return settings; } -static __always_inline struct scap_bpf_per_cpu_state *get_local_state(unsigned int cpu) -{ +static __always_inline struct scap_bpf_per_cpu_state *get_local_state(unsigned int cpu) { struct scap_bpf_per_cpu_state *state; state = bpf_map_lookup_elem(&local_state_map, &cpu); - if (!state) + if(!state) bpf_printk("state NULL\n"); return state; } -static __always_inline bool acquire_local_state(struct scap_bpf_per_cpu_state *state) -{ - if (state->in_use) { +static __always_inline bool acquire_local_state(struct scap_bpf_per_cpu_state *state) { + if(state->in_use) { bpf_printk("acquire_local_state: already in use\n"); return false; } @@ -513,9 +489,8 @@ static __always_inline bool acquire_local_state(struct scap_bpf_per_cpu_state *s return true; } -static __always_inline bool release_local_state(struct scap_bpf_per_cpu_state *state) -{ - if (!state->in_use) { +static __always_inline bool release_local_state(struct scap_bpf_per_cpu_state *state) { + if(!state->in_use) { bpf_printk("release_local_state: already not in use\n"); return false; } @@ -524,44 +499,41 @@ static __always_inline bool release_local_state(struct scap_bpf_per_cpu_state *s return true; } -static __always_inline int init_filler_data(void *ctx, - struct filler_data *data, - bool is_syscall) -{ +static __always_inline int init_filler_data(void *ctx, struct filler_data *data, bool is_syscall) { unsigned int cpu; data->ctx = ctx; data->settings = get_bpf_settings(); - if (!data->settings) + if(!data->settings) return PPM_FAILURE_BUG; cpu = bpf_get_smp_processor_id(); data->buf = get_frame_scratch_area(cpu); - if (!data->buf) + if(!data->buf) return PPM_FAILURE_BUG; data->state = get_local_state(cpu); - if (!data->state) + if(!data->state) return PPM_FAILURE_BUG; data->tmp_scratch = get_tmp_scratch_area(cpu); - if (!data->tmp_scratch) + if(!data->tmp_scratch) return PPM_FAILURE_BUG; data->evt = get_event_info(data->state->tail_ctx.evt_type); - if (!data->evt) + if(!data->evt) return PPM_FAILURE_BUG; data->filler_info = get_event_filler_info(data->state->tail_ctx.evt_type); - if (!data->filler_info) + if(!data->filler_info) return PPM_FAILURE_BUG; #ifndef BPF_SUPPORTS_RAW_TRACEPOINTS - if (is_syscall) { + if(is_syscall) { data->args = unstash_args(); - if (!data->args) + if(!data->args) return PPM_SKIP_EVENT; } #endif @@ -572,17 +544,14 @@ static __always_inline int init_filler_data(void *ctx, return PPM_SUCCESS; } -static __always_inline int bpf_test_bit(int nr, unsigned long *addr) -{ +static __always_inline int bpf_test_bit(int nr, unsigned long *addr) { return 1UL & (_READ(addr[BIT_WORD(nr)]) >> (nr & (BITS_PER_LONG - 1))); } #if defined(CAPTURE_SCHED_PROC_FORK) || defined(CAPTURE_SCHED_PROC_EXEC) -static __always_inline bool bpf_drop_syscall_exit_events(void *ctx, ppm_event_code evt_type) -{ +static __always_inline bool bpf_drop_syscall_exit_events(void *ctx, ppm_event_code evt_type) { long ret = 0; - switch (evt_type) - { + switch(evt_type) { /* On s390x, clone and fork child events will be generated but * due to page faults, no args/envp information will be collected. * Also no child events appear for clone3 syscall. @@ -591,48 +560,47 @@ static __always_inline bool bpf_drop_syscall_exit_events(void *ctx, ppm_event_co * let proactively ignore them. */ #ifdef CAPTURE_SCHED_PROC_FORK - case PPME_SYSCALL_CLONE_20_X: - case PPME_SYSCALL_FORK_20_X: - case PPME_SYSCALL_VFORK_20_X: - case PPME_SYSCALL_CLONE3_X: - ret = bpf_syscall_get_retval(ctx); - /* We ignore only child events, so ret == 0! */ - return ret == 0; + case PPME_SYSCALL_CLONE_20_X: + case PPME_SYSCALL_FORK_20_X: + case PPME_SYSCALL_VFORK_20_X: + case PPME_SYSCALL_CLONE3_X: + ret = bpf_syscall_get_retval(ctx); + /* We ignore only child events, so ret == 0! */ + return ret == 0; #endif /* If `CAPTURE_SCHED_PROC_EXEC` logic is enabled we collect execve-family * exit events through a dedicated tracepoint so we can ignore them here. */ #ifdef CAPTURE_SCHED_PROC_EXEC - case PPME_SYSCALL_EXECVE_19_X: - case PPME_SYSCALL_EXECVEAT_X: - ret = bpf_syscall_get_retval(ctx); - /* We ignore only successful events, so ret == 0! */ - return ret == 0; + case PPME_SYSCALL_EXECVE_19_X: + case PPME_SYSCALL_EXECVEAT_X: + ret = bpf_syscall_get_retval(ctx); + /* We ignore only successful events, so ret == 0! */ + return ret == 0; #endif - default: - break; + default: + break; } return false; } #endif static __always_inline bool drop_event(void *ctx, - struct scap_bpf_per_cpu_state *state, - ppm_event_code evt_type, - struct scap_bpf_settings *settings, - enum syscall_flags drop_flags) -{ - if (!settings->dropping_mode) + struct scap_bpf_per_cpu_state *state, + ppm_event_code evt_type, + struct scap_bpf_settings *settings, + enum syscall_flags drop_flags) { + if(!settings->dropping_mode) return false; - switch (evt_type) { + switch(evt_type) { case PPME_SYSCALL_CLOSE_X: case PPME_SOCKET_BIND_X: { long ret = bpf_syscall_get_retval(ctx); - if (ret < 0) + if(ret < 0) return true; break; @@ -647,30 +615,30 @@ static __always_inline bool drop_event(void *ctx, int max_fds; close_fd = bpf_syscall_get_argument_from_ctx(ctx, 0); - if (close_fd < 0) + if(close_fd < 0) return true; task = (struct task_struct *)bpf_get_current_task(); - if (!task) + if(!task) break; files = _READ(task->files); - if (!files) + if(!files) break; fdt = _READ(files->fdt); - if (!fdt) + if(!fdt) break; max_fds = _READ(fdt->max_fds); - if (close_fd >= max_fds) + if(close_fd >= max_fds) return true; open_fds = _READ(fdt->open_fds); - if (!open_fds) + if(!open_fds) break; - if (!bpf_test_bit(close_fd, open_fds)) + if(!bpf_test_bit(close_fd, open_fds)) return true; break; @@ -679,7 +647,7 @@ static __always_inline bool drop_event(void *ctx, case PPME_SYSCALL_FCNTL_X: { long cmd = bpf_syscall_get_argument_from_ctx(ctx, 1); - if (cmd != F_DUPFD && cmd != F_DUPFD_CLOEXEC) + if(cmd != F_DUPFD && cmd != F_DUPFD_CLOEXEC) return true; break; @@ -688,15 +656,14 @@ static __always_inline bool drop_event(void *ctx, break; } - if (drop_flags & UF_NEVER_DROP) + if(drop_flags & UF_NEVER_DROP) return false; - if (drop_flags & UF_ALWAYS_DROP) + if(drop_flags & UF_ALWAYS_DROP) return true; - if (state->tail_ctx.ts % 1000000000 >= 1000000000 / - settings->sampling_ratio) { - if (!settings->is_dropping) { + if(state->tail_ctx.ts % 1000000000 >= 1000000000 / settings->sampling_ratio) { + if(!settings->is_dropping) { settings->is_dropping = true; state->tail_ctx.evt_type = PPME_DROP_E; return false; @@ -705,7 +672,7 @@ static __always_inline bool drop_event(void *ctx, return true; } - if (settings->is_dropping) { + if(settings->is_dropping) { settings->is_dropping = false; state->tail_ctx.evt_type = PPME_DROP_X; return false; @@ -715,9 +682,8 @@ static __always_inline bool drop_event(void *ctx, } static __always_inline void reset_tail_ctx(struct scap_bpf_per_cpu_state *state, - ppm_event_code evt_type, - unsigned long long ts) -{ + ppm_event_code evt_type, + unsigned long long ts) { state->tail_ctx.evt_type = evt_type; state->tail_ctx.ts = ts; state->tail_ctx.curarg = 0; @@ -727,11 +693,10 @@ static __always_inline void reset_tail_ctx(struct scap_bpf_per_cpu_state *state, } static __always_inline void call_filler(void *ctx, - void *stack_ctx, - ppm_event_code evt_type, - enum syscall_flags drop_flags, - int socketcall_syscall_id) -{ + void *stack_ctx, + ppm_event_code evt_type, + enum syscall_flags drop_flags, + int socketcall_syscall_id) { struct scap_bpf_settings *settings; const struct ppm_event_entry *filler_info; struct scap_bpf_per_cpu_state *state; @@ -742,17 +707,17 @@ static __always_inline void call_filler(void *ctx, cpu = bpf_get_smp_processor_id(); state = get_local_state(cpu); - if (!state) + if(!state) return; settings = get_bpf_settings(); - if (!settings) + if(!settings) return; - if (!acquire_local_state(state)) + if(!acquire_local_state(state)) return; - if (cpu == 0 && state->hotplug_cpu != 0) { + if(cpu == 0 && state->hotplug_cpu != 0) { evt_type = PPME_CPU_HOTPLUG_E; drop_flags = UF_NEVER_DROP; } @@ -761,7 +726,7 @@ static __always_inline void call_filler(void *ctx, reset_tail_ctx(state, evt_type, ts); /* drop_event can change state->tail_ctx.evt_type */ - if (drop_event(stack_ctx, state, evt_type, settings, drop_flags)) + if(drop_event(stack_ctx, state, evt_type, settings, drop_flags)) goto cleanup; ++state->n_evts; @@ -769,21 +734,20 @@ static __always_inline void call_filler(void *ctx, state->tail_ctx.socketcall_syscall_id = socketcall_syscall_id; filler_info = get_event_filler_info(state->tail_ctx.evt_type); - if (!filler_info) + if(!filler_info) goto cleanup; bpf_tail_call(ctx, &tail_map, filler_info->filler_id); bpf_printk("Can't tail call filler evt=%d, filler=%d\n", - state->tail_ctx.evt_type, - filler_info->filler_id); + state->tail_ctx.evt_type, + filler_info->filler_id); cleanup: release_local_state(state); } #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS -static __always_inline long convert_network_syscalls(void *ctx, bool *is_syscall) -{ +static __always_inline long convert_network_syscalls(void *ctx, bool *is_syscall) { int socketcall_id = (int)bpf_syscall_get_argument_from_ctx(ctx, 0); return socketcall_code_to_syscall_code(socketcall_id, is_syscall); } diff --git a/driver/bpf/probe.c b/driver/bpf/probe.c index bb9e570f3f..66d6fd1487 100644 --- a/driver/bpf/probe.c +++ b/driver/bpf/probe.c @@ -29,8 +29,7 @@ or GPL2.txt for full copies of the license. #define __NR_ia32_socketcall 102 -BPF_PROBE("raw_syscalls/", sys_enter, sys_enter_args) -{ +BPF_PROBE("raw_syscalls/", sys_enter, sys_enter_args) { const struct syscall_evt_pair *sc_evt = NULL; ppm_event_code evt_type = -1; int drop_flags = 0; @@ -39,59 +38,47 @@ BPF_PROBE("raw_syscalls/", sys_enter, sys_enter_args) int socketcall_syscall_id = -1; id = bpf_syscall_get_nr(ctx); - if (id < 0 || id >= SYSCALL_TABLE_SIZE) + if(id < 0 || id >= SYSCALL_TABLE_SIZE) return 0; - if (bpf_in_ia32_syscall()) - { - // Right now we support 32-bit emulation only on x86. - // We try to convert the 32-bit id into the 64-bit one. + if(bpf_in_ia32_syscall()) { + // Right now we support 32-bit emulation only on x86. + // We try to convert the 32-bit id into the 64-bit one. #if defined(CONFIG_X86_64) && defined(CONFIG_IA32_EMULATION) - if (id == __NR_ia32_socketcall) - { + if(id == __NR_ia32_socketcall) { socketcall_syscall_id = __NR_ia32_socketcall; - } - else - { + } else { id = convert_ia32_to_64(id); // syscalls defined only on 32 bits are dropped here. - if(id == -1) - { + if(id == -1) { return 0; } } #else // Unsupported arch return 0; -#endif - } - else - { - // Right now only s390x supports it +#endif + } else { + // Right now only s390x supports it #ifdef __NR_socketcall socketcall_syscall_id = __NR_socketcall; #endif } - + // Now all syscalls on 32-bit should be converted to 64-bit apart from `socketcall`. // This one deserves a special treatment - if(id == socketcall_syscall_id) - { + if(id == socketcall_syscall_id) { #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS bool is_syscall_return = false; int return_code = convert_network_syscalls(ctx, &is_syscall_return); - if (return_code == -1) - { + if(return_code == -1) { // Wrong SYS_ argument passed. Drop the syscall. return 0; } - if(!is_syscall_return) - { + if(!is_syscall_return) { evt_type = return_code; drop_flags = UF_USED; - } - else - { + } else { id = return_code; } #else @@ -105,11 +92,9 @@ BPF_PROBE("raw_syscalls/", sys_enter, sys_enter_args) // There could be cases in which we have a `PPME_SOCKET_SEND_E` event // and`id=__NR_ia32_socketcall`...We resolved the correct event type but we cannot // update the `id`. - if (evt_type == -1) - { + if(evt_type == -1) { enabled = is_syscall_interesting(id); - if(!enabled) - { + if(!enabled) { return 0; } @@ -117,19 +102,15 @@ BPF_PROBE("raw_syscalls/", sys_enter, sys_enter_args) if(!sc_evt) return 0; - if(sc_evt->flags & UF_USED) - { + if(sc_evt->flags & UF_USED) { evt_type = sc_evt->enter_event_type; drop_flags = sc_evt->flags; - } - else - { + } else { evt_type = PPME_GENERIC_E; drop_flags = UF_ALWAYS_DROP; } } - #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS call_filler(ctx, ctx, evt_type, drop_flags, socketcall_syscall_id); #else @@ -137,7 +118,7 @@ BPF_PROBE("raw_syscalls/", sys_enter, sys_enter_args) struct sys_enter_args stack_ctx; memcpy(stack_ctx.args, ctx->args, sizeof(ctx->args)); - if (stash_args(stack_ctx.args)) + if(stash_args(stack_ctx.args)) return 0; call_filler(ctx, &stack_ctx, evt_type, drop_flags, socketcall_syscall_id); @@ -145,30 +126,25 @@ BPF_PROBE("raw_syscalls/", sys_enter, sys_enter_args) return 0; } -BPF_PROBE("raw_syscalls/", sys_exit, sys_exit_args) -{ +BPF_PROBE("raw_syscalls/", sys_exit, sys_exit_args) { const struct syscall_evt_pair *sc_evt = NULL; ppm_event_code evt_type = -1; int drop_flags = 0; long id = 0; bool enabled = false; - struct scap_bpf_settings *settings = 0; + struct scap_bpf_settings *settings = 0; long retval = 0; int socketcall_syscall_id = -1; id = bpf_syscall_get_nr(ctx); - if (id < 0 || id >= SYSCALL_TABLE_SIZE) + if(id < 0 || id >= SYSCALL_TABLE_SIZE) return 0; - if (bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { #if defined(CONFIG_X86_64) && defined(CONFIG_IA32_EMULATION) - if (id == __NR_ia32_socketcall) - { + if(id == __NR_ia32_socketcall) { socketcall_syscall_id = __NR_ia32_socketcall; - } - else - { + } else { /* * When a process does execve from 64bit to 32bit, TS_COMPAT is marked true * but the id of the syscall is __NR_execve, so to correctly parse it we need to @@ -182,8 +158,7 @@ BPF_PROBE("raw_syscalls/", sys_exit, sys_exit_args) #endif { id = convert_ia32_to_64(id); - if(id == -1) - { + if(id == -1) { return 0; } } @@ -192,31 +167,24 @@ BPF_PROBE("raw_syscalls/", sys_exit, sys_exit_args) // Unsupported arch return 0; #endif - } - else - { + } else { #ifdef __NR_socketcall socketcall_syscall_id = __NR_socketcall; #endif } - if(id == socketcall_syscall_id) - { + if(id == socketcall_syscall_id) { #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS bool is_syscall_return = false; int return_code = convert_network_syscalls(ctx, &is_syscall_return); - if (return_code == -1) - { + if(return_code == -1) { // Wrong SYS_ argument passed. Drop the syscall. return 0; } - if(!is_syscall_return) - { - evt_type = return_code + 1; // we are in sys_exit! + if(!is_syscall_return) { + evt_type = return_code + 1; // we are in sys_exit! drop_flags = UF_USED; - } - else - { + } else { id = return_code; } #else @@ -225,39 +193,32 @@ BPF_PROBE("raw_syscalls/", sys_exit, sys_exit_args) #endif } - if(evt_type == -1) - { + if(evt_type == -1) { enabled = is_syscall_interesting(id); - if(!enabled) - { + if(!enabled) { return 0; } sc_evt = get_syscall_info(id); if(!sc_evt) return 0; - if(sc_evt->flags & UF_USED) - { + if(sc_evt->flags & UF_USED) { evt_type = sc_evt->exit_event_type; drop_flags = sc_evt->flags; - } - else - { + } else { evt_type = PPME_GENERIC_X; drop_flags = UF_ALWAYS_DROP; } } settings = get_bpf_settings(); - if (!settings) + if(!settings) return 0; // Drop failed syscalls if necessary - if (settings->drop_failed) - { + if(settings->drop_failed) { retval = bpf_syscall_get_retval(ctx); - if (retval < 0) - { + if(retval < 0) { return 0; } } @@ -271,8 +232,7 @@ BPF_PROBE("raw_syscalls/", sys_exit, sys_exit_args) return 0; } -BPF_PROBE("sched/", sched_process_exit, sched_process_exit_args) -{ +BPF_PROBE("sched/", sched_process_exit, sched_process_exit_args) { ppm_event_code evt_type; struct task_struct *task; unsigned int flags; @@ -280,7 +240,7 @@ BPF_PROBE("sched/", sched_process_exit, sched_process_exit_args) task = (struct task_struct *)bpf_get_current_task(); flags = _READ(task->flags); - if (flags & PF_KTHREAD) + if(flags & PF_KTHREAD) return 0; evt_type = PPME_PROCEXIT_1_E; @@ -289,8 +249,7 @@ BPF_PROBE("sched/", sched_process_exit, sched_process_exit_args) return 0; } -BPF_PROBE("sched/", sched_switch, sched_switch_args) -{ +BPF_PROBE("sched/", sched_switch, sched_switch_args) { ppm_event_code evt_type; evt_type = PPME_SCHEDSWITCH_6_E; @@ -300,8 +259,7 @@ BPF_PROBE("sched/", sched_switch, sched_switch_args) } #ifdef CAPTURE_PAGE_FAULTS -static __always_inline int bpf_page_fault(struct page_fault_args *ctx) -{ +static __always_inline int bpf_page_fault(struct page_fault_args *ctx) { ppm_event_code evt_type; evt_type = PPME_PAGE_FAULT_E; @@ -310,19 +268,16 @@ static __always_inline int bpf_page_fault(struct page_fault_args *ctx) return 0; } -BPF_PROBE("exceptions/", page_fault_user, page_fault_args) -{ +BPF_PROBE("exceptions/", page_fault_user, page_fault_args) { return bpf_page_fault(ctx); } -BPF_PROBE("exceptions/", page_fault_kernel, page_fault_args) -{ +BPF_PROBE("exceptions/", page_fault_kernel, page_fault_args) { return bpf_page_fault(ctx); } #endif -BPF_PROBE("signal/", signal_deliver, signal_deliver_args) -{ +BPF_PROBE("signal/", signal_deliver, signal_deliver_args) { ppm_event_code evt_type; evt_type = PPME_SIGNALDELIVER_E; @@ -332,15 +287,14 @@ BPF_PROBE("signal/", signal_deliver, signal_deliver_args) } #ifndef BPF_SUPPORTS_RAW_TRACEPOINTS -__bpf_section(TP_NAME "sched/sched_process_fork&1") -int bpf_sched_process_fork(struct sched_process_fork_args *ctx) -{ +__bpf_section(TP_NAME "sched/sched_process_fork&1") int bpf_sched_process_fork( + struct sched_process_fork_args *ctx) { ppm_event_code evt_type; struct sys_stash_args args; unsigned long *argsp; argsp = __unstash_args(ctx->parent_pid); - if (!argsp) + if(!argsp) return 0; memcpy(&args, argsp, sizeof(args)); @@ -352,8 +306,7 @@ int bpf_sched_process_fork(struct sched_process_fork_args *ctx) #endif #ifdef CAPTURE_SCHED_PROC_EXEC -BPF_PROBE("sched/", sched_process_exec, sched_process_exec_args) -{ +BPF_PROBE("sched/", sched_process_exec, sched_process_exec_args) { struct scap_bpf_settings *settings; /* We will always send an execve exit event. */ ppm_event_code event_type = PPME_SYSCALL_EXECVE_19_X; @@ -361,42 +314,37 @@ BPF_PROBE("sched/", sched_process_exec, sched_process_exec_args) /* We are not interested in kernel threads. */ struct task_struct *task = (struct task_struct *)bpf_get_current_task(); unsigned int flags = _READ(task->flags); - if(flags & PF_KTHREAD) - { + if(flags & PF_KTHREAD) { return 0; } /* Reset the tail context in the CPU state map. */ uint32_t cpu = bpf_get_smp_processor_id(); - struct scap_bpf_per_cpu_state * state = get_local_state(cpu); - if(!state) - { + struct scap_bpf_per_cpu_state *state = get_local_state(cpu); + if(!state) { return 0; } settings = get_bpf_settings(); - if(!settings) - { + if(!settings) { return 0; } uint64_t ts = settings->boot_time + bpf_ktime_get_boot_ns(); reset_tail_ctx(state, event_type, ts); ++state->n_evts; - int filler_code = PPM_FILLER_sched_prog_exec; bpf_tail_call(ctx, &tail_map, filler_code); bpf_printk("Can't tail call filler 'sched_proc_exec' evt=%d, filler=%d\n", - event_type, - filler_code); + event_type, + filler_code); return 0; } #endif /* CAPTURE_SCHED_PROC_EXEC */ #ifdef CAPTURE_SCHED_PROC_FORK -__bpf_section("raw_tracepoint/sched_process_fork&2") -int bpf_sched_process_fork(struct sched_process_fork_raw_args *ctx) -{ +__bpf_section("raw_tracepoint/sched_process_fork&2") int bpf_sched_process_fork( + struct sched_process_fork_raw_args *ctx) { struct scap_bpf_settings *settings; /* We will always send a clone exit event. */ ppm_event_code event_type = PPME_SYSCALL_CLONE_20_X; @@ -404,22 +352,19 @@ int bpf_sched_process_fork(struct sched_process_fork_raw_args *ctx) /* We are not interested in kernel threads. */ struct task_struct *task = (struct task_struct *)bpf_get_current_task(); unsigned int flags = _READ(task->flags); - if(flags & PF_KTHREAD) - { + if(flags & PF_KTHREAD) { return 0; } /* Reset the tail context in the CPU state map. */ uint32_t cpu = bpf_get_smp_processor_id(); - struct scap_bpf_per_cpu_state * state = get_local_state(cpu); - if(!state) - { + struct scap_bpf_per_cpu_state *state = get_local_state(cpu); + if(!state) { return 0; } settings = get_bpf_settings(); - if(!settings) - { + if(!settings) { return 0; } uint64_t ts = settings->boot_time + bpf_ktime_get_boot_ns(); @@ -429,8 +374,8 @@ int bpf_sched_process_fork(struct sched_process_fork_raw_args *ctx) int filler_code = PPM_FILLER_sched_prog_fork; bpf_tail_call(ctx, &tail_map, filler_code); bpf_printk("Can't tail call filler 'sched_proc_fork' evt=%d, filler=%d\n", - event_type, - filler_code); + event_type, + filler_code); return 0; } #endif /* CAPTURE_SCHED_PROC_FORK */ diff --git a/driver/bpf/quirks.h b/driver/bpf/quirks.h index e9a4847349..693fff259e 100644 --- a/driver/bpf/quirks.h +++ b/driver/bpf/quirks.h @@ -17,20 +17,24 @@ or GPL2.txt for full copies of the license. #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 13, 0) && LINUX_VERSION_CODE < KERNEL_VERSION(4, 14, 4) -#define randomized_struct_fields_start struct { -#define randomized_struct_fields_end }; +#define randomized_struct_fields_start struct { +#define randomized_struct_fields_end \ + } \ + ; #endif #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 15, 0) #define BPF_FORBIDS_ZERO_ACCESS #endif -#if (defined(CONFIG_X86_64) || defined(CONFIG_ARM64) || defined(CONFIG_S390) || defined(CONFIG_PPC64)) && LINUX_VERSION_CODE >= KERNEL_VERSION(4, 17, 0) - #define BPF_SUPPORTS_RAW_TRACEPOINTS +#if(defined(CONFIG_X86_64) || defined(CONFIG_ARM64) || defined(CONFIG_S390) || \ + defined(CONFIG_PPC64)) && \ + LINUX_VERSION_CODE >= KERNEL_VERSION(4, 17, 0) +#define BPF_SUPPORTS_RAW_TRACEPOINTS #endif #if CAPTURE_SCHED_PROC_FORK && !defined(BPF_SUPPORTS_RAW_TRACEPOINTS) - #error The CAPTURE_SCHED_PROC_FORK support requires 'raw_tracepoints' so kernel versions greater or equal than '4.17'. +#error The CAPTURE_SCHED_PROC_FORK support requires 'raw_tracepoints' so kernel versions greater or equal than '4.17'. #endif /* Redefine asm_volatile_goto to work around clang not supporting it diff --git a/driver/bpf/ring_helpers.h b/driver/bpf/ring_helpers.h index 4ef5b968a8..3a6c6f1b8e 100644 --- a/driver/bpf/ring_helpers.h +++ b/driver/bpf/ring_helpers.h @@ -10,8 +10,7 @@ or GPL2.txt for full copies of the license. #ifndef __RING_HELPERS_H #define __RING_HELPERS_H -static __always_inline void write_evt_hdr(struct filler_data *data) -{ +static __always_inline void write_evt_hdr(struct filler_data *data) { struct ppm_evt_hdr *evt_hdr = (struct ppm_evt_hdr *)data->buf; evt_hdr->ts = data->state->tail_ctx.ts; @@ -19,43 +18,35 @@ static __always_inline void write_evt_hdr(struct filler_data *data) evt_hdr->type = data->state->tail_ctx.evt_type; evt_hdr->nparams = data->evt->nparams; - data->state->tail_ctx.curoff = sizeof(struct ppm_evt_hdr) + - sizeof(uint16_t) * data->evt->nparams; + data->state->tail_ctx.curoff = + sizeof(struct ppm_evt_hdr) + sizeof(uint16_t) * data->evt->nparams; data->state->tail_ctx.len = data->state->tail_ctx.curoff; } -static __always_inline void fixup_evt_len(char *p, unsigned long len) -{ +static __always_inline void fixup_evt_len(char *p, unsigned long len) { struct ppm_evt_hdr *evt_hdr = (struct ppm_evt_hdr *)p; evt_hdr->len = len; } -static __always_inline void fixup_evt_arg_len(char *p, - unsigned int argnum, - unsigned int arglen) -{ - if (argnum > PPM_MAX_EVENT_PARAMS) - { +static __always_inline void fixup_evt_arg_len(char *p, unsigned int argnum, unsigned int arglen) { + if(argnum > PPM_MAX_EVENT_PARAMS) { return; } volatile unsigned int argnumv = argnum; *((uint16_t *)&p[sizeof(struct ppm_evt_hdr)] + (argnumv & (PPM_MAX_EVENT_PARAMS - 1))) = arglen; } -static __always_inline int push_evt_frame(void *ctx, - struct filler_data *data) -{ - if (data->state->tail_ctx.curarg != data->evt->nparams) { +static __always_inline int push_evt_frame(void *ctx, struct filler_data *data) { + if(data->state->tail_ctx.curarg != data->evt->nparams) { bpf_printk("corrupted filler for event type %d (added %u args, should have added %u)\n", - data->state->tail_ctx.evt_type, - data->state->tail_ctx.curarg, - data->evt->nparams); + data->state->tail_ctx.evt_type, + data->state->tail_ctx.curarg, + data->evt->nparams); return PPM_FAILURE_BUG; } - if (data->state->tail_ctx.len > PERF_EVENT_MAX_SIZE) - { + if(data->state->tail_ctx.len > PERF_EVENT_MAX_SIZE) { return PPM_FAILURE_FRAME_SCRATCH_MAP_FULL; } @@ -63,18 +54,18 @@ static __always_inline int push_evt_frame(void *ctx, #ifdef BPF_FORBIDS_ZERO_ACCESS int res = bpf_perf_event_output(ctx, - &perf_map, - BPF_F_CURRENT_CPU, - data->buf, - ((data->state->tail_ctx.len - 1) & SCRATCH_SIZE_MAX) + 1); + &perf_map, + BPF_F_CURRENT_CPU, + data->buf, + ((data->state->tail_ctx.len - 1) & SCRATCH_SIZE_MAX) + 1); #else int res = bpf_perf_event_output(ctx, - &perf_map, - BPF_F_CURRENT_CPU, - data->buf, - data->state->tail_ctx.len & SCRATCH_SIZE_MAX); + &perf_map, + BPF_F_CURRENT_CPU, + data->buf, + data->state->tail_ctx.len & SCRATCH_SIZE_MAX); #endif - if (res == -ENOENT || res == -EOPNOTSUPP) { + if(res == -ENOENT || res == -EOPNOTSUPP) { /* * ENOENT = likely a new CPU is online that wasn't * opened in userspace @@ -86,15 +77,15 @@ static __always_inline int push_evt_frame(void *ctx, */ struct scap_bpf_per_cpu_state *state = get_local_state(0); - if (!state) + if(!state) return PPM_FAILURE_BUG; state->hotplug_cpu = bpf_get_smp_processor_id(); bpf_printk("detected hotplug event, cpu=%d\n", state->hotplug_cpu); - } else if (res == -ENOSPC) { + } else if(res == -ENOSPC) { bpf_printk("bpf_perf_buffer full\n"); return PPM_FAILURE_BUFFER_FULL; - } else if (res) { + } else if(res) { bpf_printk("bpf_perf_event_output failed, res=%d\n", res); return PPM_FAILURE_BUG; } diff --git a/driver/bpf/types.h b/driver/bpf/types.h index 9af3eedcc8..2f859f0da1 100644 --- a/driver/bpf/types.h +++ b/driver/bpf/types.h @@ -25,13 +25,11 @@ or GPL2.txt for full copies of the license. #endif #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS -#define BPF_PROBE(prefix, event, type) \ -__bpf_section(TP_NAME #event) \ -int bpf_##event(struct type *ctx) +#define BPF_PROBE(prefix, event, type) \ + __bpf_section(TP_NAME #event) int bpf_##event(struct type *ctx) #else -#define BPF_PROBE(prefix, event, type) \ -__bpf_section(TP_NAME prefix #event) \ -int bpf_##event(struct type *ctx) +#define BPF_PROBE(prefix, event, type) \ + __bpf_section(TP_NAME prefix #event) int bpf_##event(struct type *ctx) #endif #ifdef BPF_SUPPORTS_RAW_TRACEPOINTS @@ -146,15 +144,13 @@ struct sys_stash_args { /* TP_PROTO(struct task_struct *p, pid_t old_pid, struct linux_binprm *bprm) * Taken from `/include/trace/events/sched.h` */ -struct sched_process_exec_args -{ +struct sched_process_exec_args { struct task_struct *p; pid_t old_pid; struct linux_binprm *bprm; }; #else -struct sched_process_exec_args -{ +struct sched_process_exec_args { unsigned short common_type; unsigned char common_flags; unsigned char common_preempt_count; @@ -171,10 +167,9 @@ struct sched_process_exec_args /* TP_PROTO(struct task_struct *parent, struct task_struct *child) * Taken from `/include/trace/events/sched.h` */ -struct sched_process_fork_raw_args -{ +struct sched_process_fork_raw_args { struct task_struct *parent; - struct task_struct *child; + struct task_struct *child; }; #endif @@ -220,7 +215,6 @@ struct perf_event_sample { #endif /* __KERNEL__ */ - /* WARNING: This enum must follow the order in which BPF maps are defined in * `driver/bpf/maps.h`. */ @@ -267,9 +261,13 @@ struct tail_context { struct scap_bpf_per_cpu_state { struct tail_context tail_ctx; - unsigned long long n_evts; /* Total number of kernel side events actively traced (not including events discarded due to simple consumer mode). */ - unsigned long long n_drops_buffer; /* Total number of kernel side drops due to full buffer, includes all categories below, likely higher than sum of syscall categories. */ - /* Kernel side drops due to full buffer for categories of system calls. Not all system calls of interest are mapped into one of the categories. */ + unsigned long long n_evts; /* Total number of kernel side events actively traced (not including + events discarded due to simple consumer mode). */ + unsigned long long + n_drops_buffer; /* Total number of kernel side drops due to full buffer, includes all + categories below, likely higher than sum of syscall categories. */ + /* Kernel side drops due to full buffer for categories of system calls. Not all system calls of + * interest are mapped into one of the categories. */ unsigned long long n_drops_buffer_clone_fork_enter; unsigned long long n_drops_buffer_clone_fork_exit; unsigned long long n_drops_buffer_execve_enter; @@ -280,13 +278,18 @@ struct scap_bpf_per_cpu_state { unsigned long long n_drops_buffer_open_exit; unsigned long long n_drops_buffer_dir_file_enter; unsigned long long n_drops_buffer_dir_file_exit; - unsigned long long n_drops_buffer_other_interest_enter; /* Category of other system calls of interest, not all other system calls that did not match a category from above. */ + unsigned long long + n_drops_buffer_other_interest_enter; /* Category of other system calls of interest, not + all other system calls that did not match a + category from above. */ unsigned long long n_drops_buffer_other_interest_exit; unsigned long long n_drops_buffer_close_exit; unsigned long long n_drops_buffer_proc_exit; - unsigned long long n_drops_scratch_map; /* Number of kernel side scratch map drops. */ - unsigned long long n_drops_pf; /* Number of kernel side page faults drops (invalid memory access). */ - unsigned long long n_drops_bug; /* Number of kernel side bug drops (invalid condition in the kernel instrumentation). */ + unsigned long long n_drops_scratch_map; /* Number of kernel side scratch map drops. */ + unsigned long long + n_drops_pf; /* Number of kernel side page faults drops (invalid memory access). */ + unsigned long long n_drops_bug; /* Number of kernel side bug drops (invalid condition in the + kernel instrumentation). */ unsigned int hotplug_cpu; bool in_use; } __attribute__((packed)); diff --git a/driver/capture_macro.h b/driver/capture_macro.h index d3bd3bed50..f8df651708 100644 --- a/driver/capture_macro.h +++ b/driver/capture_macro.h @@ -37,5 +37,5 @@ or GPL2.txt for full copies of the license. #define SECOND_TO_NS 1000000000ULL #ifdef PAGE_SIZE - #define STR_STORAGE_SIZE PAGE_SIZE +#define STR_STORAGE_SIZE PAGE_SIZE #endif diff --git a/driver/configure/ACCESS_OK_2/test.c b/driver/configure/ACCESS_OK_2/test.c index 512deb894a..baf908ed92 100644 --- a/driver/configure/ACCESS_OK_2/test.c +++ b/driver/configure/ACCESS_OK_2/test.c @@ -18,15 +18,12 @@ or GPL2.txt for full copies of the license. MODULE_LICENSE("GPL"); MODULE_AUTHOR("the Falco authors"); -static int access_ok_init(void) -{ +static int access_ok_init(void) { access_ok(0, 0); return 0; } -static void access_ok_exit(void) -{ -} +static void access_ok_exit(void) {} module_init(access_ok_init); module_exit(access_ok_exit); diff --git a/driver/configure/CLASS_CREATE_1/test.c b/driver/configure/CLASS_CREATE_1/test.c index 675113bc5e..fdf3344462 100644 --- a/driver/configure/CLASS_CREATE_1/test.c +++ b/driver/configure/CLASS_CREATE_1/test.c @@ -9,7 +9,8 @@ or GPL2.txt for full copies of the license. /* * Check that `class_create` builds with only a single parameter - * See https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1aaba11da9aa7d7d6b52a74d45b31cac118295a1 + * See + * https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1aaba11da9aa7d7d6b52a74d45b31cac118295a1 */ #include @@ -18,15 +19,12 @@ or GPL2.txt for full copies of the license. MODULE_LICENSE("GPL"); MODULE_AUTHOR("the Falco authors"); -static int class_create_test_init(void) -{ +static int class_create_test_init(void) { struct class *g_ppm_class = class_create("test"); return 0; } -static void class_create_test_exit(void) -{ -} +static void class_create_test_exit(void) {} module_init(class_create_test_init); module_exit(class_create_test_exit); diff --git a/driver/configure/DEVNODE_ARG1_CONST/test.c b/driver/configure/DEVNODE_ARG1_CONST/test.c index c697f9bc2f..59c1c60f26 100644 --- a/driver/configure/DEVNODE_ARG1_CONST/test.c +++ b/driver/configure/DEVNODE_ARG1_CONST/test.c @@ -18,24 +18,18 @@ or GPL2.txt for full copies of the license. MODULE_LICENSE("GPL"); MODULE_AUTHOR("the Falco authors"); -static char *ppm_devnode(const struct device *dev, umode_t *mode) -{ +static char *ppm_devnode(const struct device *dev, umode_t *mode) { return NULL; } -static int devnode_dev_const_init(void) -{ - struct class g_ppm_class = { - .devnode = ppm_devnode - }; +static int devnode_dev_const_init(void) { + struct class g_ppm_class = {.devnode = ppm_devnode}; /* suppress unused variable warning by casting to void */ (void)g_ppm_class; return 0; } -static void devnode_dev_const_exit(void) -{ -} +static void devnode_dev_const_exit(void) {} module_init(devnode_dev_const_init); module_exit(devnode_dev_const_exit); diff --git a/driver/dynamic_params_table.c b/driver/dynamic_params_table.c index 91b7da7f3b..c55e7d0f0d 100644 --- a/driver/dynamic_params_table.c +++ b/driver/dynamic_params_table.c @@ -11,19 +11,19 @@ or GPL2.txt for full copies of the license. #include "ppm_events_public.h" const struct ppm_param_info sockopt_dynamic_param[PPM_SOCKOPT_IDX_MAX] = { - [PPM_SOCKOPT_IDX_UNKNOWN] = {{0}, PT_BYTEBUF, PF_HEX, 0, 0}, - [PPM_SOCKOPT_IDX_ERRNO] = {{0}, PT_ERRNO, PF_DEC, 0, 0}, - [PPM_SOCKOPT_IDX_UINT32] = {{0}, PT_UINT32, PF_DEC, 0, 0}, - [PPM_SOCKOPT_IDX_UINT64] = {{0}, PT_UINT64, PF_DEC, 0, 0}, - [PPM_SOCKOPT_IDX_TIMEVAL] = {{0}, PT_RELTIME, PF_DEC, 0, 0}, + [PPM_SOCKOPT_IDX_UNKNOWN] = {{0}, PT_BYTEBUF, PF_HEX, 0, 0}, + [PPM_SOCKOPT_IDX_ERRNO] = {{0}, PT_ERRNO, PF_DEC, 0, 0}, + [PPM_SOCKOPT_IDX_UINT32] = {{0}, PT_UINT32, PF_DEC, 0, 0}, + [PPM_SOCKOPT_IDX_UINT64] = {{0}, PT_UINT64, PF_DEC, 0, 0}, + [PPM_SOCKOPT_IDX_TIMEVAL] = {{0}, PT_RELTIME, PF_DEC, 0, 0}, }; const struct ppm_param_info ptrace_dynamic_param[PPM_PTRACE_IDX_MAX] = { - [PPM_PTRACE_IDX_UINT64] = {{0}, PT_UINT64, PF_HEX, 0, 0}, - [PPM_PTRACE_IDX_SIGTYPE] = {{0}, PT_SIGTYPE, PF_DEC, 0, 0}, + [PPM_PTRACE_IDX_UINT64] = {{0}, PT_UINT64, PF_HEX, 0, 0}, + [PPM_PTRACE_IDX_SIGTYPE] = {{0}, PT_SIGTYPE, PF_DEC, 0, 0}, }; const struct ppm_param_info bpf_dynamic_param[PPM_BPF_IDX_MAX] = { - [PPM_BPF_IDX_FD] = {{0}, PT_FD, PF_DEC, 0, 0}, - [PPM_BPF_IDX_RES] = {{0}, PT_ERRNO, PF_DEC, 0, 0}, + [PPM_BPF_IDX_FD] = {{0}, PT_FD, PF_DEC, 0, 0}, + [PPM_BPF_IDX_RES] = {{0}, PT_ERRNO, PF_DEC, 0, 0}, }; diff --git a/driver/event_table.c b/driver/event_table.c index 99cb18becd..077721baee 100644 --- a/driver/event_table.c +++ b/driver/event_table.c @@ -28,470 +28,2384 @@ or GPL2.txt for full copies of the license. * * - Events marked with `EC_UNKNOWN` must have a name equal to `NA`. * - * - All events that have the "EF_USES_FD" flag should return as one of the parameters a file descriptor. - * "libsinsp" will try to access the parameter and use it as a file descriptor. If the event has - * 0 parameters but has the "EF_USES_FD" flag then a runtime error will occur shutting down the process. - * Furthermore if an exit event has the "EF_USES_FD" then also the related enter event must have - * it (following the logic described above). Otherwise the exit event will not trigger "libsinsp" code - * in order to properly manage the file descriptor returned by the exit event. + * - All events that have the "EF_USES_FD" flag should return as one of the parameters a file + *descriptor. "libsinsp" will try to access the parameter and use it as a file descriptor. If the + *event has 0 parameters but has the "EF_USES_FD" flag then a runtime error will occur shutting down + *the process. Furthermore if an exit event has the "EF_USES_FD" then also the related enter event + *must have it (following the logic described above). Otherwise the exit event will not trigger + *"libsinsp" code in order to properly manage the file descriptor returned by the exit event. * - * - The only kind of change permitted for pre-existent events is adding parameters. If you need to modify or - * remove some existing parameters you must create a new event pair. The new enum name should be equal to the previous one - * but with the version bumped by 1. - * Consider the `PPME_SYSCALL_EXECVE_19_E` event as an example, if you want to create a new version for it, the new enum - * will be called `PPME_SYSCALL_EXECVE_20_E`. + * - The only kind of change permitted for pre-existent events is adding parameters. If you need to + *modify or remove some existing parameters you must create a new event pair. The new enum name + *should be equal to the previous one but with the version bumped by 1. Consider the + *`PPME_SYSCALL_EXECVE_19_E` event as an example, if you want to create a new version for it, the + *new enum will be called `PPME_SYSCALL_EXECVE_20_E`. * * - All the versions of the same event must have the same name */ - #include "ppm_events_public.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-field-initializers" const struct ppm_event_info g_event_info[] = { - [PPME_GENERIC_E] = {"syscall", EC_OTHER | EC_SYSCALL, EF_NONE, 2, {{"ID", PT_SYSCALLID, PF_DEC}, {"nativeID", PT_UINT16, PF_DEC} } }, - [PPME_GENERIC_X] = {"syscall", EC_OTHER | EC_SYSCALL, EF_NONE, 1, {{"ID", PT_SYSCALLID, PF_DEC} } }, - [PPME_SYSCALL_OPEN_E] = {"open", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 3, {{"name", PT_FSPATH, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"mode", PT_UINT32, PF_OCT} } }, - [PPME_SYSCALL_OPEN_X] = {"open", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 6, {{"fd", PT_FD, PF_DEC}, {"name", PT_FSPATH, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"mode", PT_UINT32, PF_OCT}, {"dev", PT_UINT32, PF_HEX}, {"ino", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_CLOSE_E] = {"close", EC_IO_OTHER | EC_SYSCALL, EF_DESTROYS_FD | EF_USES_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_CLOSE_X] = {"close", EC_IO_OTHER | EC_SYSCALL, EF_DESTROYS_FD | EF_USES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_READ_E] = {"read", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 2, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_READ_X] = {"read", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_WRITE_E] = {"write", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_WRITE_X] = {"write", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_BRK_1_E] = {"brk", EC_MEMORY | EC_SYSCALL, EF_OLD_VERSION, 1, {{"size", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_BRK_1_X] = {"brk", EC_MEMORY | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_UINT64, PF_HEX} } }, - [PPME_SYSCALL_EXECVE_8_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_EXECVE_8_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 8, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_CLONE_11_E] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_CLONE_11_X] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 11, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_PROCEXIT_E] = {"procexit", EC_PROCESS | EC_TRACEPOINT, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_PROCEXIT_X] = {"NA", EC_UNKNOWN, EF_UNUSED | EF_OLD_VERSION, 0}, - [PPME_SOCKET_SOCKET_E] = {"socket", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 3, {{"domain", PT_ENUMFLAGS32, PF_DEC, socket_families}, {"type", PT_UINT32, PF_DEC}, {"proto", PT_UINT32, PF_DEC} } }, - [PPME_SOCKET_SOCKET_X] = {"socket", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SOCKET_BIND_E] = {"bind", EC_NET | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SOCKET_BIND_X] = {"bind", EC_NET | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"addr", PT_SOCKADDR, PF_NA} } }, - [PPME_SOCKET_CONNECT_E] = {"connect", EC_NET | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 2, {{"fd", PT_FD, PF_DEC}, {"addr", PT_SOCKADDR, PF_NA} } }, - [PPME_SOCKET_CONNECT_X] = {"connect", EC_NET | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 3, {{"res", PT_ERRNO, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA}, {"fd", PT_FD, PF_DEC } } }, - [PPME_SOCKET_LISTEN_E] = {"listen", EC_NET | EC_SYSCALL, EF_USES_FD, 2, {{"fd", PT_FD, PF_DEC}, {"backlog", PT_INT32, PF_DEC} } }, - [PPME_SOCKET_LISTEN_X] = {"listen", EC_NET | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SOCKET_ACCEPT_E] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SOCKET_ACCEPT_X] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 3, {{"fd", PT_FD, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA}, {"queuepct", PT_UINT8, PF_DEC} } }, - [PPME_SOCKET_SEND_E] = {"send", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC} } }, - [PPME_SOCKET_SEND_X] = {"send", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SOCKET_SENDTO_E] = {"sendto", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, 3, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA} } }, - [PPME_SOCKET_SENDTO_X] = {"sendto", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SOCKET_RECV_E] = {"recv", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 2, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC} } }, - [PPME_SOCKET_RECV_X] = {"recv", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SOCKET_RECVFROM_E] = {"recvfrom", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, 2, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC} } }, - [PPME_SOCKET_RECVFROM_X] = {"recvfrom", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, 3, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}, {"tuple", PT_SOCKTUPLE, PF_NA} } }, - [PPME_SOCKET_SHUTDOWN_E] = {"shutdown", EC_NET | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 2, {{"fd", PT_FD, PF_DEC}, {"how", PT_ENUMFLAGS8, PF_HEX, shutdown_how} } }, - [PPME_SOCKET_SHUTDOWN_X] = {"shutdown", EC_NET | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SOCKET_GETSOCKNAME_E] = {"getsockname", EC_NET | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_GETSOCKNAME_X] = {"getsockname", EC_NET | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_GETPEERNAME_E] = {"getpeername", EC_NET | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_GETPEERNAME_X] = {"getpeername", EC_NET | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_SOCKETPAIR_E] = {"socketpair", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 3, {{"domain", PT_ENUMFLAGS32, PF_DEC, socket_families}, {"type", PT_UINT32, PF_DEC}, {"proto", PT_UINT32, PF_DEC} } }, - [PPME_SOCKET_SOCKETPAIR_X] = {"socketpair", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 5, {{"res", PT_ERRNO, PF_DEC}, {"fd1", PT_FD, PF_DEC}, {"fd2", PT_FD, PF_DEC}, {"source", PT_UINT64, PF_HEX}, {"peer", PT_UINT64, PF_HEX} } }, - [PPME_SOCKET_SETSOCKOPT_E] = {"setsockopt", EC_NET | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SOCKET_SETSOCKOPT_X] = {"setsockopt", EC_NET | EC_SYSCALL, EF_USES_FD, 6, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"level", PT_ENUMFLAGS8, PF_DEC, sockopt_levels}, {"optname", PT_ENUMFLAGS8, PF_DEC, sockopt_options}, {"val", PT_DYN, PF_DEC, sockopt_dynamic_param, PPM_SOCKOPT_IDX_MAX}, {"optlen", PT_UINT32, PF_DEC}}}, - [PPME_SOCKET_GETSOCKOPT_E] = {"getsockopt", EC_NET | EC_SYSCALL, EF_MODIFIES_STATE, 0 }, - [PPME_SOCKET_GETSOCKOPT_X] = {"getsockopt", EC_NET | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 6, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"level", PT_ENUMFLAGS8, PF_DEC, sockopt_levels}, {"optname", PT_ENUMFLAGS8, PF_DEC, sockopt_options}, {"val", PT_DYN, PF_DEC, sockopt_dynamic_param, PPM_SOCKOPT_IDX_MAX}, {"optlen", PT_UINT32, PF_DEC}}}, - [PPME_SOCKET_SENDMSG_E] = {"sendmsg", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, 3, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA} } }, - [PPME_SOCKET_SENDMSG_X] = {"sendmsg", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SOCKET_SENDMMSG_E] = {"sendmmsg", EC_IO_WRITE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_SENDMMSG_X] = {"sendmmsg", EC_IO_WRITE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_RECVMSG_E] = {"recvmsg", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SOCKET_RECVMSG_X] = {"recvmsg", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, 5, {{"res", PT_ERRNO, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}, {"tuple", PT_SOCKTUPLE, PF_NA}, {"msgcontrol", PT_BYTEBUF, PF_NA} } }, - [PPME_SOCKET_RECVMMSG_E] = {"recvmmsg", EC_IO_READ | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_RECVMMSG_X] = {"recvmmsg", EC_IO_READ | EC_SYSCALL, EF_NONE, 0}, - [PPME_SOCKET_ACCEPT4_E] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"flags", PT_INT32, PF_HEX} } }, - [PPME_SOCKET_ACCEPT4_X] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 3, {{"fd", PT_FD, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA}, {"queuepct", PT_UINT8, PF_DEC} } }, - [PPME_SYSCALL_CREAT_E] = {"creat", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"name", PT_FSPATH, PF_NA}, {"mode", PT_UINT32, PF_OCT} } }, - [PPME_SYSCALL_CREAT_X] = {"creat", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 6, {{"fd", PT_FD, PF_DEC}, {"name", PT_FSPATH, PF_NA}, {"mode", PT_UINT32, PF_OCT}, {"dev", PT_UINT32, PF_HEX}, {"ino", PT_UINT64, PF_DEC}, {"creat_flags", PT_FLAGS16, PF_HEX, creat_flags} } }, - [PPME_SYSCALL_PIPE_E] = {"pipe", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_PIPE_X] = {"pipe", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 4, {{"res", PT_ERRNO, PF_DEC}, {"fd1", PT_FD, PF_DEC}, {"fd2", PT_FD, PF_DEC}, {"ino", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_EVENTFD_E] = {"eventfd", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"initval", PT_UINT64, PF_DEC}, {"flags", PT_UINT32, PF_HEX} } }, - [PPME_SYSCALL_EVENTFD_X] = {"eventfd", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_FUTEX_E] = {"futex", EC_IPC | EC_SYSCALL, EF_NONE, 3, {{"addr", PT_UINT64, PF_HEX}, {"op", PT_FLAGS16, PF_HEX, futex_operations}, {"val", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_FUTEX_X] = {"futex", EC_IPC | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_STAT_E] = {"stat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_STAT_X] = {"stat", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_LSTAT_E] = {"lstat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_LSTAT_X] = {"lstat", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_FSTAT_E] = {"fstat", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA} } }, - [PPME_SYSCALL_FSTAT_X] = {"fstat", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_STAT64_E] = {"stat64", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_STAT64_X] = {"stat64", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_LSTAT64_E] = {"lstat64", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_LSTAT64_X] = {"lstat64", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_FSTAT64_E] = {"fstat64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA} } }, - [PPME_SYSCALL_FSTAT64_X] = {"fstat64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_EPOLLWAIT_E] = {"epoll_wait", EC_WAIT | EC_SYSCALL, EF_WAITS, 1, {{"maxevents", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_EPOLLWAIT_X] = {"epoll_wait", EC_WAIT | EC_SYSCALL, EF_WAITS, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_POLL_E] = {"poll", EC_WAIT | EC_SYSCALL, EF_WAITS, 2, {{"fds", PT_FDLIST, PF_DEC}, {"timeout", PT_INT64, PF_DEC} } }, - [PPME_SYSCALL_POLL_X] = {"poll", EC_WAIT | EC_SYSCALL, EF_WAITS, 2, {{"res", PT_ERRNO, PF_DEC}, {"fds", PT_FDLIST, PF_DEC} } }, - [PPME_SYSCALL_SELECT_E] = {"select", EC_WAIT | EC_SYSCALL, EF_WAITS, 0}, - [PPME_SYSCALL_SELECT_X] = {"select", EC_WAIT | EC_SYSCALL, EF_WAITS, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_NEWSELECT_E] = {"select", EC_WAIT | EC_SYSCALL, EF_WAITS | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_NEWSELECT_X] = {"select", EC_WAIT | EC_SYSCALL, EF_WAITS | EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_LSEEK_E] = {"lseek", EC_FILE | EC_SYSCALL, EF_USES_FD, 3, {{"fd", PT_FD, PF_DEC}, {"offset", PT_UINT64, PF_DEC}, {"whence", PT_ENUMFLAGS8, PF_DEC, lseek_whence} } }, - [PPME_SYSCALL_LSEEK_X] = {"lseek", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_LLSEEK_E] = {"llseek", EC_FILE | EC_SYSCALL, EF_USES_FD, 3, {{"fd", PT_FD, PF_DEC}, {"offset", PT_UINT64, PF_DEC}, {"whence", PT_ENUMFLAGS8, PF_DEC, lseek_whence} } }, - [PPME_SYSCALL_LLSEEK_X] = {"llseek", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_IOCTL_2_E] = {"ioctl", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD | EF_OLD_VERSION, 2, {{"fd", PT_FD, PF_DEC}, {"request", PT_UINT64, PF_HEX} } }, - [PPME_SYSCALL_IOCTL_2_X] = {"ioctl", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD | EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_GETCWD_E] = {"getcwd", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - /* Note: path is PT_CHARBUF and not PT_FSPATH because we assume it's absolute and will never need resolution */ - [PPME_SYSCALL_GETCWD_X] = {"getcwd", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_CHARBUF, PF_NA} } }, - /* Note: path is PT_CHARBUF and not PT_FSPATH because we don't want it to be resolved, since the event handler already changes it */ - [PPME_SYSCALL_CHDIR_E] = {"chdir", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_CHDIR_X] = {"chdir", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_CHARBUF, PF_NA} } }, - [PPME_SYSCALL_FCHDIR_E] = {"fchdir", EC_FILE | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_NA} } }, - [PPME_SYSCALL_FCHDIR_X] = {"fchdir", EC_FILE | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_MKDIR_E] = {"mkdir", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 2, {{"path", PT_FSPATH, PF_NA}, {"mode", PT_UINT32, PF_HEX} } }, - [PPME_SYSCALL_MKDIR_X] = {"mkdir", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_RMDIR_E] = {"rmdir", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_RMDIR_X] = {"rmdir", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_OPENAT_E] = {"openat", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 4, {{"dirfd", PT_FD, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"mode", PT_UINT32, PF_OCT} } }, - [PPME_SYSCALL_OPENAT_X] = {"openat", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_LINK_E] = {"link", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 2, {{"oldpath", PT_FSPATH, PF_NA}, {"newpath", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_LINK_X] = {"link", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_LINKAT_E] = {"linkat", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 4, {{"olddir", PT_FD, PF_DEC}, {"oldpath", PT_CHARBUF, PF_NA}, {"newdir", PT_FD, PF_DEC}, {"newpath", PT_CHARBUF, PF_NA} } }, - [PPME_SYSCALL_LINKAT_X] = {"linkat", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_UNLINK_E] = {"unlink", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_UNLINK_X] = {"unlink", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_UNLINKAT_E] = {"unlinkat", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 2, {{"dirfd", PT_FD, PF_DEC}, {"name", PT_CHARBUF, PF_NA} } }, - [PPME_SYSCALL_UNLINKAT_X] = {"unlinkat", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_PREAD_E] = {"pread", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 3, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"pos", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_PREAD_X] = {"pread", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_PWRITE_E] = {"pwrite", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 3, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"pos", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_PWRITE_X] = {"pwrite", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_READV_E] = {"readv", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_READV_X] = {"readv", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 3, {{"res", PT_ERRNO, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_WRITEV_E] = {"writev", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_WRITEV_X] = {"writev", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_PREADV_E] = {"preadv", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 2, {{"fd", PT_FD, PF_DEC}, {"pos", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_PREADV_X] = {"preadv", EC_IO_READ | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 3, {{"res", PT_ERRNO, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_PWRITEV_E] = {"pwritev", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 3, {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}, {"pos", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_PWRITEV_X] = {"pwritev", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD | EF_WRITES_TO_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_DUP_E] = {"dup", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_DUP_X] = {"dup", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"res", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_SIGNALFD_E] = {"signalfd", EC_SIGNAL | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 3, {{"fd", PT_FD, PF_DEC}, {"mask", PT_UINT32, PF_HEX}, {"flags", PT_UINT8, PF_HEX} } }, - [PPME_SYSCALL_SIGNALFD_X] = {"signalfd", EC_SIGNAL | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_KILL_E] = {"kill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 2, {{"pid", PT_PID, PF_DEC}, {"sig", PT_SIGTYPE, PF_DEC} } }, - [PPME_SYSCALL_KILL_X] = {"kill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_TKILL_E] = {"tkill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 2, {{"tid", PT_PID, PF_DEC}, {"sig", PT_SIGTYPE, PF_DEC} } }, - [PPME_SYSCALL_TKILL_X] = {"tkill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_TGKILL_E] = {"tgkill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 3, {{"pid", PT_PID, PF_DEC}, {"tid", PT_PID, PF_DEC}, {"sig", PT_SIGTYPE, PF_DEC} } }, - [PPME_SYSCALL_TGKILL_X] = {"tgkill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_NANOSLEEP_E] = {"nanosleep", EC_SLEEP | EC_SYSCALL, EF_WAITS, 1, {{"interval", PT_RELTIME, PF_DEC} } }, - [PPME_SYSCALL_NANOSLEEP_X] = {"nanosleep", EC_SLEEP | EC_SYSCALL, EF_WAITS, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_TIMERFD_CREATE_E] = {"timerfd_create", EC_TIME | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"clockid", PT_UINT8, PF_DEC}, {"flags", PT_UINT8, PF_HEX} } }, - [PPME_SYSCALL_TIMERFD_CREATE_X] = {"timerfd_create", EC_TIME | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_INOTIFY_INIT_E] = {"inotify_init", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"flags", PT_UINT8, PF_HEX} } }, - [PPME_SYSCALL_INOTIFY_INIT_X] = {"inotify_init", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_GETRLIMIT_E] = {"getrlimit", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources} } }, - [PPME_SYSCALL_GETRLIMIT_X] = {"getrlimit", EC_PROCESS | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"cur", PT_INT64, PF_DEC}, {"max", PT_INT64, PF_DEC} } }, - [PPME_SYSCALL_SETRLIMIT_E] = {"setrlimit", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources} } }, - [PPME_SYSCALL_SETRLIMIT_X] = {"setrlimit", EC_PROCESS | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC},{"cur", PT_INT64, PF_DEC}, {"max", PT_INT64, PF_DEC}, {"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources} } }, - [PPME_SYSCALL_PRLIMIT_E] = {"prlimit", EC_PROCESS | EC_SYSCALL, EF_NONE, 2, {{"pid", PT_PID, PF_DEC}, {"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources} } }, - [PPME_SYSCALL_PRLIMIT_X] = {"prlimit", EC_PROCESS | EC_SYSCALL, EF_NONE, 7, {{"res", PT_ERRNO, PF_DEC}, {"newcur", PT_INT64, PF_DEC}, {"newmax", PT_INT64, PF_DEC}, {"oldcur", PT_INT64, PF_DEC}, {"oldmax", PT_INT64, PF_DEC}, {"pid", PT_INT64, PF_DEC}, {"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources} } }, - [PPME_SCHEDSWITCH_1_E] = {"switch", EC_SCHEDULER | EC_TRACEPOINT, EF_SKIPPARSERESET | EF_OLD_VERSION, 1, {{"next", PT_PID, PF_DEC} } }, - [PPME_SCHEDSWITCH_1_X] = {"NA", EC_UNKNOWN, EF_SKIPPARSERESET | EF_UNUSED | EF_OLD_VERSION, 0}, - [PPME_DROP_E] = {"drop", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET, 1, {{"ratio", PT_UINT32, PF_DEC} } }, - [PPME_DROP_X] = {"drop", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET, 1, {{"ratio", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_FCNTL_E] = {"fcntl", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 2, {{"fd", PT_FD, PF_DEC}, {"cmd", PT_ENUMFLAGS8, PF_DEC, fcntl_commands} } }, - [PPME_SYSCALL_FCNTL_X] = {"fcntl", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD | EF_MODIFIES_STATE, 3, {{"res", PT_FD, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"cmd", PT_ENUMFLAGS8, PF_DEC, fcntl_commands} } }, - [PPME_SCHEDSWITCH_6_E] = {"switch", EC_SCHEDULER | EC_TRACEPOINT, EF_NONE, 6, {{"next", PT_PID, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC} } }, /// TODO: do we need SKIPPARSERESET flag? - [PPME_SCHEDSWITCH_6_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_EXECVE_13_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_EXECVE_13_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 13, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_CLONE_16_E] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_CLONE_16_X] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 16, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_BRK_4_E] = {"brk", EC_MEMORY | EC_SYSCALL, EF_NONE, 1, {{"addr", PT_UINT64, PF_HEX} } }, - [PPME_SYSCALL_BRK_4_X] = {"brk", EC_MEMORY | EC_SYSCALL, EF_NONE, 4, {{"res", PT_UINT64, PF_HEX}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_MMAP_E] = {"mmap", EC_MEMORY | EC_SYSCALL, EF_USES_FD, 6, {{"addr", PT_UINT64, PF_HEX}, {"length", PT_UINT64, PF_DEC}, {"prot", PT_FLAGS32, PF_HEX, prot_flags}, {"flags", PT_FLAGS32, PF_HEX, mmap_flags}, {"fd", PT_FD, PF_DEC}, {"offset", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_MMAP_X] = {"mmap", EC_MEMORY | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_HEX}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_MMAP2_E] = {"mmap2", EC_MEMORY | EC_SYSCALL, EF_USES_FD, 6, {{"addr", PT_UINT64, PF_HEX}, {"length", PT_UINT64, PF_DEC}, {"prot", PT_FLAGS32, PF_HEX, prot_flags}, {"flags", PT_FLAGS32, PF_HEX, mmap_flags}, {"fd", PT_FD, PF_DEC}, {"pgoffset", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_MMAP2_X] = {"mmap2", EC_MEMORY | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_HEX}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_MUNMAP_E] = {"munmap", EC_MEMORY | EC_SYSCALL, EF_NONE, 2, {{"addr", PT_UINT64, PF_HEX}, {"length", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_MUNMAP_X] = {"munmap", EC_MEMORY | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_SPLICE_E] = {"splice", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 4, {{"fd_in", PT_FD, PF_DEC}, {"fd_out", PT_FD, PF_DEC}, {"size", PT_UINT64, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, splice_flags} } }, - [PPME_SYSCALL_SPLICE_X] = {"splice", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_PTRACE_E] = {"ptrace", EC_PROCESS | EC_SYSCALL, EF_NONE, 2, {{"request", PT_ENUMFLAGS16, PF_DEC, ptrace_requests}, {"pid", PT_PID, PF_DEC} } }, - [PPME_SYSCALL_PTRACE_X] = {"ptrace", EC_PROCESS | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"addr", PT_DYN, PF_HEX, ptrace_dynamic_param, PPM_PTRACE_IDX_MAX}, {"data", PT_DYN, PF_HEX, ptrace_dynamic_param, PPM_PTRACE_IDX_MAX} } }, - [PPME_SYSCALL_IOCTL_3_E] = {"ioctl", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 3, {{"fd", PT_FD, PF_DEC}, {"request", PT_UINT64, PF_HEX}, {"argument", PT_UINT64, PF_HEX} } }, - [PPME_SYSCALL_IOCTL_3_X] = {"ioctl", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_EXECVE_14_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_EXECVE_14_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 14, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"env", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_RENAME_E] = {"rename", EC_FILE | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_RENAME_X] = {"rename", EC_FILE | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"oldpath", PT_FSPATH, PF_NA}, {"newpath", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_RENAMEAT_E] = {"renameat", EC_FILE | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_RENAMEAT_X] = {"renameat", EC_FILE | EC_SYSCALL, EF_NONE, 5, {{"res", PT_ERRNO, PF_DEC}, {"olddirfd", PT_FD, PF_DEC}, {"oldpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"newdirfd", PT_FD, PF_DEC}, {"newpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(3)} } }, - [PPME_SYSCALL_SYMLINK_E] = {"symlink", EC_FILE | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_SYMLINK_X] = {"symlink", EC_FILE | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"target", PT_CHARBUF, PF_NA}, {"linkpath", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_SYMLINKAT_E] = {"symlinkat", EC_FILE | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_SYMLINKAT_X] = {"symlinkat", EC_FILE | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"target", PT_CHARBUF, PF_NA}, {"linkdirfd", PT_FD, PF_DEC}, {"linkpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(2)} } }, - [PPME_SYSCALL_FORK_E] = {"fork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_FORK_X] = {"fork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 16, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_VFORK_E] = {"vfork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_VFORK_X] = {"vfork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 16, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_PROCEXIT_1_E] = {"procexit", EC_PROCESS | EC_TRACEPOINT, EF_MODIFIES_STATE, 5, {{"status", PT_ERRNO, PF_DEC}, {"ret", PT_ERRNO, PF_DEC}, {"sig", PT_SIGTYPE, PF_DEC}, {"core", PT_UINT8, PF_DEC}, {"reaper_tid", PT_PID, PF_DEC} } }, - [PPME_PROCEXIT_1_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_SENDFILE_E] = {"sendfile", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD, 4, {{"out_fd", PT_FD, PF_DEC}, {"in_fd", PT_FD, PF_DEC}, {"offset", PT_UINT64, PF_DEC}, {"size", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_SENDFILE_X] = {"sendfile", EC_IO_WRITE | EC_SYSCALL, EF_USES_FD, 2, {{"res", PT_ERRNO, PF_DEC}, {"offset", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_QUOTACTL_E] = {"quotactl", EC_USER | EC_SYSCALL, EF_NONE, 4, {{"cmd", PT_FLAGS16, PF_DEC, quotactl_cmds }, {"type", PT_FLAGS8, PF_DEC, quotactl_types}, {"id", PT_UINT32, PF_DEC}, {"quota_fmt", PT_FLAGS8, PF_DEC, quotactl_quota_fmts } } }, - [PPME_SYSCALL_QUOTACTL_X] = {"quotactl", EC_USER | EC_SYSCALL, EF_NONE, 14, {{"res", PT_ERRNO, PF_DEC}, {"special", PT_CHARBUF, PF_NA }, {"quotafilepath", PT_CHARBUF, PF_NA}, {"dqb_bhardlimit", PT_UINT64, PF_DEC }, {"dqb_bsoftlimit", PT_UINT64, PF_DEC }, {"dqb_curspace", PT_UINT64, PF_DEC }, {"dqb_ihardlimit", PT_UINT64, PF_DEC }, {"dqb_isoftlimit", PT_UINT64, PF_DEC }, {"dqb_btime", PT_RELTIME, PF_DEC }, {"dqb_itime", PT_RELTIME, PF_DEC }, {"dqi_bgrace", PT_RELTIME, PF_DEC }, {"dqi_igrace", PT_RELTIME, PF_DEC }, {"dqi_flags", PT_FLAGS8, PF_DEC, quotactl_dqi_flags }, {"quota_fmt_out", PT_FLAGS8, PF_DEC, quotactl_quota_fmts } } }, - [PPME_SYSCALL_SETRESUID_E] = {"setresuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 3, {{"ruid", PT_UID, PF_DEC }, {"euid", PT_UID, PF_DEC }, {"suid", PT_UID, PF_DEC } } }, - [PPME_SYSCALL_SETRESUID_X] = {"setresuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_SETRESGID_E] = {"setresgid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 3, {{"rgid", PT_GID, PF_DEC }, {"egid", PT_GID, PF_DEC }, {"sgid", PT_GID, PF_DEC } } }, - [PPME_SYSCALL_SETRESGID_X] = {"setresgid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SCAPEVENT_E] = {"scapevent", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET, 2, {{"event_type", PT_UINT32, PF_DEC}, {"event_data", PT_UINT64, PF_DEC} } }, - [PPME_SCAPEVENT_X] = {"scapevent", EC_INTERNAL | EC_METAEVENT, EF_UNUSED, 0}, - [PPME_SYSCALL_SETUID_E] = {"setuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"uid", PT_UID, PF_DEC} } }, - [PPME_SYSCALL_SETUID_X] = {"setuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_SETGID_E] = {"setgid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"gid", PT_GID, PF_DEC} } }, - [PPME_SYSCALL_SETGID_X] = {"setgid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_GETUID_E] = {"getuid", EC_USER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_GETUID_X] = {"getuid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"uid", PT_UID, PF_DEC} } }, - [PPME_SYSCALL_GETEUID_E] = {"geteuid", EC_USER | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_GETEUID_X] = {"geteuid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"euid", PT_UID, PF_DEC} } }, - [PPME_SYSCALL_GETGID_E] = {"getgid", EC_USER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_GETGID_X] = {"getgid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"gid", PT_GID, PF_DEC} } }, - [PPME_SYSCALL_GETEGID_E] = {"getegid", EC_USER | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_GETEGID_X] = {"getegid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"egid", PT_GID, PF_DEC} } }, - [PPME_SYSCALL_GETRESUID_E] = {"getresuid", EC_USER | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_GETRESUID_X] = {"getresuid", EC_USER | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"ruid", PT_UID, PF_DEC }, {"euid", PT_UID, PF_DEC }, {"suid", PT_UID, PF_DEC } } }, - [PPME_SYSCALL_GETRESGID_E] = {"getresgid", EC_USER | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_GETRESGID_X] = {"getresgid", EC_USER | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"rgid", PT_GID, PF_DEC }, {"egid", PT_GID, PF_DEC }, {"sgid", PT_GID, PF_DEC } } }, - [PPME_SYSCALL_EXECVE_15_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_EXECVE_15_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 15, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"env", PT_BYTEBUF, PF_NA} } }, - [PPME_SYSCALL_CLONE_17_E] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_CLONE_17_X] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 17, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_FORK_17_E] = {"fork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_FORK_17_X] = {"fork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 17, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_VFORK_17_E] = {"vfork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_VFORK_17_X] = {"vfork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 17, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_CLONE_20_E] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_CLONE_20_X] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 21, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC}, {"vtid", PT_PID, PF_DEC}, {"vpid", PT_PID, PF_DEC}, {"pidns_init_start_ts", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_FORK_20_E] = {"fork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_FORK_20_X] = {"fork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 21, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC}, {"vtid", PT_PID, PF_DEC}, {"vpid", PT_PID, PF_DEC}, {"pidns_init_start_ts", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_VFORK_20_E] = {"vfork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_VFORK_20_X] = {"vfork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 21, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC}, {"vtid", PT_PID, PF_DEC}, {"vpid", PT_PID, PF_DEC}, {"pidns_init_start_ts", PT_UINT64, PF_DEC} } }, - [PPME_CONTAINER_E] = {"container", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET | EF_MODIFIES_STATE | EF_OLD_VERSION, 4, {{"id", PT_CHARBUF, PF_NA}, {"type", PT_UINT32, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"image", PT_CHARBUF, PF_NA} } }, - [PPME_CONTAINER_X] = {"NA", EC_UNKNOWN, EF_UNUSED | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_EXECVE_16_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_EXECVE_16_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 16, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"env", PT_BYTEBUF, PF_NA} } }, - [PPME_SIGNALDELIVER_E] = {"signaldeliver", EC_SIGNAL | EC_TRACEPOINT, EF_NONE, 3, {{"spid", PT_PID, PF_DEC}, {"dpid", PT_PID, PF_DEC}, {"sig", PT_SIGTYPE, PF_DEC} } }, - [PPME_SIGNALDELIVER_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0 }, - [PPME_PROCINFO_E] = {"procinfo", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET, 2, {{"cpu_usr", PT_UINT64, PF_DEC}, {"cpu_sys", PT_UINT64, PF_DEC} } }, - [PPME_PROCINFO_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_GETDENTS_E] = {"getdents", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA} } }, - [PPME_SYSCALL_GETDENTS_X] = {"getdents", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_GETDENTS64_E] = {"getdents64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA} } }, - [PPME_SYSCALL_GETDENTS64_X] = {"getdents64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_SETNS_E] = {"setns", EC_PROCESS | EC_SYSCALL, EF_USES_FD, 2, {{"fd", PT_FD, PF_NA}, {"nstype", PT_FLAGS32, PF_HEX, clone_flags} } }, - [PPME_SYSCALL_SETNS_X] = {"setns", EC_PROCESS | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_FLOCK_E] = {"flock", EC_FILE | EC_SYSCALL, EF_USES_FD, 2, {{"fd", PT_FD, PF_NA}, {"operation", PT_FLAGS32, PF_HEX, flock_flags} } }, - [PPME_SYSCALL_FLOCK_X] = {"flock", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_CPU_HOTPLUG_E] = {"cpu_hotplug", EC_SYSTEM | EC_METAEVENT, EF_SKIPPARSERESET | EF_MODIFIES_STATE, 2, {{"cpu", PT_UINT32, PF_DEC}, {"action", PT_UINT32, PF_DEC} } }, - [PPME_CPU_HOTPLUG_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SOCKET_ACCEPT_5_E] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SOCKET_ACCEPT_5_X] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 5, {{"fd", PT_FD, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA}, {"queuepct", PT_UINT8, PF_DEC}, {"queuelen", PT_UINT32, PF_DEC}, {"queuemax", PT_UINT32, PF_DEC} } }, - [PPME_SOCKET_ACCEPT4_5_E] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"flags", PT_INT32, PF_HEX} } }, - [PPME_SOCKET_ACCEPT4_5_X] = {"accept", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, 5, {{"fd", PT_FD, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA}, {"queuepct", PT_UINT8, PF_DEC}, {"queuelen", PT_UINT32, PF_DEC}, {"queuemax", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_SEMOP_E] = {"semop", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"semid", PT_INT32, PF_DEC} } }, - [PPME_SYSCALL_SEMOP_X] = {"semop", EC_PROCESS | EC_SYSCALL, EF_NONE, 8, {{"res", PT_ERRNO, PF_DEC}, {"nsops", PT_UINT32, PF_DEC}, {"sem_num_0", PT_UINT16, PF_DEC}, {"sem_op_0", PT_INT16, PF_DEC}, {"sem_flg_0", PT_FLAGS16, PF_HEX, semop_flags}, {"sem_num_1", PT_UINT16, PF_DEC}, {"sem_op_1", PT_INT16, PF_DEC}, {"sem_flg_1", PT_FLAGS16, PF_HEX, semop_flags} } }, - [PPME_SYSCALL_SEMCTL_E] = {"semctl", EC_PROCESS | EC_SYSCALL, EF_NONE, 4, {{"semid", PT_INT32, PF_DEC}, {"semnum", PT_INT32, PF_DEC}, {"cmd", PT_FLAGS16, PF_HEX, semctl_commands}, {"val", PT_INT32, PF_DEC} } }, - [PPME_SYSCALL_SEMCTL_X] = {"semctl", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_PPOLL_E] = {"ppoll", EC_WAIT | EC_SYSCALL, EF_WAITS, 3, {{"fds", PT_FDLIST, PF_DEC}, {"timeout", PT_RELTIME, PF_DEC}, {"sigmask", PT_SIGSET, PF_DEC} } }, - [PPME_SYSCALL_PPOLL_X] = {"ppoll", EC_WAIT | EC_SYSCALL, EF_WAITS, 2, {{"res", PT_ERRNO, PF_DEC}, {"fds", PT_FDLIST, PF_DEC} } }, - [PPME_SYSCALL_MOUNT_E] = {"mount", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"flags", PT_FLAGS32, PF_HEX, mount_flags} } }, - [PPME_SYSCALL_MOUNT_X] = {"mount", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 4, {{"res", PT_ERRNO, PF_DEC}, {"dev", PT_CHARBUF, PF_NA}, {"dir", PT_FSPATH, PF_NA}, {"type", PT_CHARBUF, PF_NA} } }, - [PPME_SYSCALL_UMOUNT_E] = {"umount", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"flags", PT_FLAGS32, PF_HEX, umount_flags} } }, - [PPME_SYSCALL_UMOUNT_X] = {"umount", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 2, {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA} } }, - [PPME_K8S_E] = {"k8s", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET | EF_MODIFIES_STATE, 1, {{"json", PT_CHARBUF, PF_NA} } }, - [PPME_K8S_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_SEMGET_E] = {"semget", EC_PROCESS | EC_SYSCALL, EF_NONE, 3, {{"key", PT_INT32, PF_HEX}, {"nsems", PT_INT32, PF_DEC}, {"semflg", PT_FLAGS32, PF_HEX, semget_flags} } }, - [PPME_SYSCALL_SEMGET_X] = {"semget", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_ACCESS_E] = {"access", EC_FILE | EC_SYSCALL, EF_NONE, 1, {{"mode", PT_FLAGS32, PF_HEX, access_flags} } }, - [PPME_SYSCALL_ACCESS_X] = {"access", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_CHROOT_E] = {"chroot", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_CHROOT_X] = {"chroot", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_TRACER_E] = {"tracer", EC_OTHER | EC_METAEVENT, EF_NONE, 3, {{"id", PT_INT64, PF_DEC}, {"tags", PT_CHARBUFARRAY, PF_NA}, {"args", PT_CHARBUF_PAIR_ARRAY, PF_NA} } }, - [PPME_TRACER_X] = { "tracer", EC_OTHER | EC_METAEVENT, EF_NONE, 3, { { "id", PT_INT64, PF_DEC }, { "tags", PT_CHARBUFARRAY, PF_NA }, { "args", PT_CHARBUF_PAIR_ARRAY, PF_NA } } }, - [PPME_MESOS_E] = {"mesos", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET | EF_MODIFIES_STATE, 1, {{"json", PT_CHARBUF, PF_NA} } }, - [PPME_MESOS_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_CONTAINER_JSON_E] = {"container", EC_PROCESS | EC_METAEVENT, EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"json", PT_CHARBUF, PF_NA} } }, /// TODO: do we need SKIPPARSERESET flag? - [PPME_CONTAINER_JSON_X] = {"NA", EC_UNKNOWN, EF_UNUSED | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_SETSID_E] = {"setsid", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_SETSID_X] = {"setsid", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_PID, PF_DEC} } }, - [PPME_SYSCALL_MKDIR_2_E] = {"mkdir", EC_FILE | EC_SYSCALL, EF_NONE, 1, {{"mode", PT_UINT32, PF_HEX} } }, - [PPME_SYSCALL_MKDIR_2_X] = {"mkdir", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_RMDIR_2_E] = {"rmdir", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_RMDIR_2_X] = {"rmdir", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_NOTIFICATION_E] = {"notification", EC_OTHER | EC_METAEVENT, EF_SKIPPARSERESET, 2, {{"id", PT_CHARBUF, PF_DEC}, {"desc", PT_CHARBUF, PF_NA}, } }, - [PPME_NOTIFICATION_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_EXECVE_17_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 0}, - [PPME_SYSCALL_EXECVE_17_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 17, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"env", PT_BYTEBUF, PF_NA}, {"tty", PT_INT32, PF_DEC} } }, - [PPME_SYSCALL_UNSHARE_E] = {"unshare", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"flags", PT_FLAGS32, PF_HEX, clone_flags} } }, - [PPME_SYSCALL_UNSHARE_X] = {"unshare", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_INFRASTRUCTURE_EVENT_E] = {"infra", EC_INTERNAL | EC_METAEVENT, EF_SKIPPARSERESET, 4, {{"source", PT_CHARBUF, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"description", PT_CHARBUF, PF_NA}, {"scope", PT_CHARBUF, PF_NA} } }, - [PPME_INFRASTRUCTURE_EVENT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_EXECVE_18_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 1, {{"filename", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_EXECVE_18_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE | EF_OLD_VERSION, 17, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"env", PT_BYTEBUF, PF_NA}, {"tty", PT_INT32, PF_DEC} } }, - [PPME_PAGE_FAULT_E] = {"page_fault", EC_OTHER | EC_TRACEPOINT, EF_SKIPPARSERESET, 3, {{"addr", PT_UINT64, PF_HEX}, {"ip", PT_UINT64, PF_HEX}, {"error", PT_FLAGS32, PF_HEX, pf_flags} } }, - [PPME_PAGE_FAULT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_EXECVE_19_E] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"filename", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_EXECVE_19_X] = {"execve", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 28, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"env", PT_BYTEBUF, PF_NA}, {"tty", PT_UINT32, PF_DEC}, {"pgid", PT_PID, PF_DEC}, {"loginuid", PT_UID, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, execve_flags}, {"cap_inheritable", PT_UINT64, PF_HEX}, {"cap_permitted", PT_UINT64, PF_HEX}, {"cap_effective", PT_UINT64, PF_HEX}, {"exe_ino", PT_UINT64, PF_DEC}, {"exe_ino_ctime", PT_ABSTIME, PF_DEC}, {"exe_ino_mtime", PT_ABSTIME, PF_DEC}, {"uid", PT_UID, PF_DEC}, {"trusted_exepath", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_SETPGID_E] = {"setpgid", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 2, {{"pid", PT_PID, PF_DEC}, {"pgid", PT_PID, PF_DEC} } }, - [PPME_SYSCALL_SETPGID_X] = {"setpgid", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_PID, PF_DEC} } }, - [PPME_SYSCALL_BPF_E] = {"bpf", EC_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_OLD_VERSION, 1, {{"cmd", PT_INT64, PF_DEC} } }, - [PPME_SYSCALL_BPF_X] = {"bpf", EC_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_OLD_VERSION, 1, {{"res_or_fd", PT_DYN, PF_DEC, bpf_dynamic_param, PPM_BPF_IDX_MAX}} }, - [PPME_SYSCALL_SECCOMP_E] = {"seccomp", EC_OTHER | EC_SYSCALL, EF_NONE, 2, {{"op", PT_UINT64, PF_DEC}, {"flags", PT_UINT64, PF_HEX} } }, - [PPME_SYSCALL_SECCOMP_X] = {"seccomp", EC_OTHER | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_UNLINK_2_E] = {"unlink", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_UNLINK_2_X] = {"unlink", EC_FILE | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_UNLINKAT_2_E] = {"unlinkat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_UNLINKAT_2_X] = {"unlinkat", EC_FILE | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"flags", PT_FLAGS32, PF_HEX, unlinkat_flags} } }, - [PPME_SYSCALL_MKDIRAT_E] = {"mkdirat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MKDIRAT_X] = {"mkdirat", EC_FILE | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"path", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"mode", PT_UINT32, PF_HEX} } }, - [PPME_SYSCALL_OPENAT_2_E] = {"openat", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 4, {{"dirfd", PT_FD, PF_DEC}, {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(0)}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"mode", PT_UINT32, PF_OCT} } }, - [PPME_SYSCALL_OPENAT_2_X] = {"openat", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 7, {{"fd", PT_FD, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"mode", PT_UINT32, PF_OCT}, {"dev", PT_UINT32, PF_HEX}, {"ino", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_LINK_2_E] = {"link", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_LINK_2_X] = {"link", EC_FILE | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"oldpath", PT_FSPATH, PF_NA}, {"newpath", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_LINKAT_2_E] = {"linkat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_LINKAT_2_X] = {"linkat", EC_FILE | EC_SYSCALL, EF_NONE, 6, {{"res", PT_ERRNO, PF_DEC}, {"olddir", PT_FD, PF_DEC}, {"oldpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"newdir", PT_FD, PF_DEC}, {"newpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(3)}, {"flags", PT_FLAGS32, PF_HEX, linkat_flags} } }, - [PPME_SYSCALL_FCHMODAT_E] = {"fchmodat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_FCHMODAT_X] = {"fchmodat", EC_FILE | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"filename", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"mode", PT_MODE, PF_OCT, chmod_mode} } }, - [PPME_SYSCALL_CHMOD_E] = {"chmod", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_CHMOD_X] = {"chmod", EC_FILE | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"filename", PT_FSPATH, PF_NA}, {"mode", PT_MODE, PF_OCT, chmod_mode} } }, - [PPME_SYSCALL_FCHMOD_E] = {"fchmod", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_FCHMOD_X] = {"fchmod", EC_FILE | EC_SYSCALL, EF_USES_FD, 3, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"mode", PT_MODE, PF_OCT, chmod_mode} } }, - [PPME_SYSCALL_RENAMEAT2_E] = {"renameat2", EC_FILE | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_RENAMEAT2_X] = {"renameat2", EC_FILE | EC_SYSCALL, EF_NONE, 6, {{"res", PT_ERRNO, PF_DEC}, {"olddirfd", PT_FD, PF_DEC}, {"oldpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"newdirfd", PT_FD, PF_DEC}, {"newpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(3)}, {"flags", PT_FLAGS32, PF_HEX, renameat2_flags} } }, - [PPME_SYSCALL_USERFAULTFD_E] = {"userfaultfd", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_USERFAULTFD_X] = {"userfaultfd", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, file_flags} } }, - [PPME_PLUGINEVENT_E] = {"pluginevent", EC_OTHER | EC_PLUGIN, EF_LARGE_PAYLOAD, 2, {{"plugin_id", PT_UINT32, PF_DEC}, {"event_data", PT_BYTEBUF, PF_NA} } }, - [PPME_PLUGINEVENT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_CONTAINER_JSON_2_E] = {"container", EC_PROCESS | EC_METAEVENT, EF_MODIFIES_STATE | EF_LARGE_PAYLOAD, 1, {{"json", PT_CHARBUF, PF_NA} } }, /// TODO: do we need SKIPPARSERESET flag? - [PPME_CONTAINER_JSON_2_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_OPENAT2_E] = {"openat2", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 5, {{"dirfd", PT_FD, PF_DEC}, {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"mode", PT_UINT32, PF_OCT}, {"resolve", PT_FLAGS32, PF_HEX, openat2_flags} } }, - [PPME_SYSCALL_OPENAT2_X] = {"openat2", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 8, {{"fd", PT_FD, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"mode", PT_UINT32, PF_OCT}, {"resolve", PT_FLAGS32, PF_HEX, openat2_flags}, {"dev", PT_UINT32, PF_HEX}, {"ino", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_MPROTECT_E] = {"mprotect", EC_MEMORY | EC_SYSCALL, EF_NONE, 3, {{"addr", PT_UINT64, PF_HEX}, {"length", PT_UINT64, PF_DEC}, {"prot", PT_FLAGS32, PF_HEX, prot_flags} } }, - [PPME_SYSCALL_MPROTECT_X] = {"mprotect", EC_MEMORY | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_EXECVEAT_E] = {"execveat", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 3, {{"dirfd", PT_FD, PF_DEC}, {"pathname", PT_FSRELPATH, PF_NA, DIRFD_PARAM(0)}, {"flags", PT_FLAGS32, PF_HEX, execveat_flags} } }, - [PPME_SYSCALL_EXECVEAT_X] = {"execveat", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 28, {{"res", PT_ERRNO, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_UINT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"env", PT_BYTEBUF, PF_NA}, {"tty", PT_UINT32, PF_DEC}, {"pgid", PT_PID, PF_DEC}, {"loginuid", PT_UID, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, execve_flags}, {"cap_inheritable", PT_UINT64, PF_HEX}, {"cap_permitted", PT_UINT64, PF_HEX}, {"cap_effective", PT_UINT64, PF_HEX}, {"exe_ino", PT_UINT64, PF_DEC}, {"exe_ino_ctime", PT_ABSTIME, PF_DEC}, {"exe_ino_mtime", PT_ABSTIME, PF_DEC}, {"uid", PT_UID, PF_DEC}, {"trusted_exepath", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_COPY_FILE_RANGE_E] = {"copy_file_range", EC_FILE | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD | EF_WRITES_TO_FD, 3, {{"fdin", PT_FD, PF_DEC}, {"offin", PT_UINT64, PF_DEC}, {"len", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_COPY_FILE_RANGE_X] = {"copy_file_range", EC_FILE | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD | EF_WRITES_TO_FD, 3, {{"res", PT_ERRNO, PF_DEC}, {"fdout", PT_FD, PF_DEC}, {"offout", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_CLONE3_E] = {"clone3", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_CLONE3_X] = {"clone3", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 21, {{"res", PT_PID, PF_DEC}, {"exe", PT_CHARBUF, PF_NA}, {"args", PT_BYTEBUF, PF_NA}, {"tid", PT_PID, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"ptid", PT_PID, PF_DEC}, {"cwd", PT_CHARBUF, PF_NA}, {"fdlimit", PT_INT64, PF_DEC}, {"pgft_maj", PT_UINT64, PF_DEC}, {"pgft_min", PT_UINT64, PF_DEC}, {"vm_size", PT_UINT32, PF_DEC}, {"vm_rss", PT_UINT32, PF_DEC}, {"vm_swap", PT_UINT32, PF_DEC}, {"comm", PT_CHARBUF, PF_NA}, {"cgroups", PT_BYTEBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, clone_flags}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC}, {"vtid", PT_PID, PF_DEC}, {"vpid", PT_PID, PF_DEC}, {"pidns_init_start_ts", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = {"open_by_handle_at", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = {"open_by_handle_at", EC_FILE | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 6, {{"fd", PT_FD, PF_DEC}, {"mountfd", PT_FD, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, file_flags}, {"path", PT_FSPATH, PF_NA}, {"dev", PT_UINT32, PF_HEX}, {"ino", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_IO_URING_SETUP_E] = {"io_uring_setup", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_IO_URING_SETUP_X] = {"io_uring_setup", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 8, {{"res", PT_ERRNO, PF_DEC}, {"entries", PT_UINT32, PF_DEC}, {"sq_entries", PT_UINT32, PF_DEC},{"cq_entries", PT_UINT32, PF_DEC},{"flags", PT_FLAGS32, PF_HEX, io_uring_setup_flags},{"sq_thread_cpu", PT_UINT32, PF_DEC}, {"sq_thread_idle", PT_UINT32, PF_DEC},{"features", PT_FLAGS32, PF_HEX, io_uring_setup_feats}}}, - [PPME_SYSCALL_IO_URING_ENTER_E] = {"io_uring_enter", EC_IO_OTHER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_IO_URING_ENTER_X] = {"io_uring_enter", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 6, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"to_submit", PT_UINT32, PF_DEC}, {"min_complete", PT_UINT32, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, io_uring_enter_flags}, {"sig", PT_SIGSET, PF_DEC}}}, - [PPME_SYSCALL_IO_URING_REGISTER_E] = {"io_uring_register", EC_IO_OTHER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_IO_URING_REGISTER_X] = {"io_uring_register", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 5, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC }, {"opcode", PT_ENUMFLAGS16, PF_DEC, io_uring_register_opcodes}, {"arg", PT_UINT64, PF_HEX}, {"nr_args", PT_UINT32, PF_DEC}}}, - [PPME_SYSCALL_MLOCK_E] = {"mlock", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MLOCK_X] = {"mlock", EC_MEMORY | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"addr", PT_UINT64, PF_HEX}, {"len", PT_UINT64, PF_DEC}}}, - [PPME_SYSCALL_MUNLOCK_E] = {"munlock", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MUNLOCK_X] = {"munlock", EC_MEMORY | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"addr", PT_UINT64, PF_HEX}, {"len", PT_UINT64, PF_DEC}}}, - [PPME_SYSCALL_MLOCKALL_E] = {"mlockall", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MLOCKALL_X] = {"mlockall", EC_MEMORY | EC_SYSCALL, EF_NONE, 2, {{"res", PT_ERRNO, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, mlockall_flags}}}, - [PPME_SYSCALL_MUNLOCKALL_E] = {"munlockall", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MUNLOCKALL_X] = {"munlockall", EC_MEMORY | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, - [PPME_SYSCALL_CAPSET_E] = {"capset", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_CAPSET_X] = {"capset", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 4, {{"res", PT_ERRNO, PF_DEC}, {"cap_inheritable", PT_UINT64, PF_HEX}, {"cap_permitted", PT_UINT64, PF_HEX}, {"cap_effective", PT_UINT64, PF_HEX} } }, - [PPME_USER_ADDED_E] = {"useradded", EC_PROCESS | EC_METAEVENT, EF_MODIFIES_STATE, 6, {{"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"home", PT_CHARBUF, PF_NA}, {"shell", PT_CHARBUF, PF_NA}, {"container_id", PT_CHARBUF, PF_NA} } }, - [PPME_USER_ADDED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_USER_DELETED_E] = {"userdeleted", EC_PROCESS | EC_METAEVENT, EF_MODIFIES_STATE, 6, {{"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"home", PT_CHARBUF, PF_NA}, {"shell", PT_CHARBUF, PF_NA}, {"container_id", PT_CHARBUF, PF_NA} } }, - [PPME_USER_DELETED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_GROUP_ADDED_E] = {"groupadded", EC_PROCESS | EC_METAEVENT, EF_MODIFIES_STATE, 3, {{"gid", PT_UINT32, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"container_id", PT_CHARBUF, PF_NA} } }, - [PPME_GROUP_ADDED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_GROUP_DELETED_E] = {"groupdeleted", EC_PROCESS | EC_METAEVENT, EF_MODIFIES_STATE, 3, {{"gid", PT_UINT32, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"container_id", PT_CHARBUF, PF_NA} } }, - [PPME_GROUP_DELETED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_DUP2_E] = {"dup2", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_DUP2_X] = {"dup2", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, 3, {{"res", PT_FD, PF_DEC}, {"oldfd", PT_FD, PF_DEC}, {"newfd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_DUP3_E] = {"dup3", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_DUP3_X] = {"dup3", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, 4, {{"res", PT_FD, PF_DEC}, {"oldfd", PT_FD, PF_DEC}, {"newfd", PT_FD, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, file_flags} } }, - [PPME_SYSCALL_DUP_1_E] = {"dup", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, 1, {{"fd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_DUP_1_X] = {"dup", EC_IO_OTHER | EC_SYSCALL, EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, 2, {{"res", PT_FD, PF_DEC}, {"oldfd", PT_FD, PF_DEC} } }, - [PPME_SYSCALL_BPF_2_E] = {"bpf", EC_OTHER | EC_SYSCALL, EF_CREATES_FD, 1, {{"cmd", PT_INT64, PF_DEC} } }, - [PPME_SYSCALL_BPF_2_X] = {"bpf", EC_OTHER | EC_SYSCALL, EF_CREATES_FD, 2, { {"fd", PT_FD, PF_DEC}, {"cmd", PT_ENUMFLAGS32, PF_DEC, bpf_commands} } }, - [PPME_SYSCALL_MLOCK2_E] = {"mlock2", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MLOCK2_X] = {"mlock2", EC_MEMORY | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"addr", PT_UINT64, PF_HEX}, {"len", PT_UINT64, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, mlock2_flags}}}, - [PPME_SYSCALL_FSCONFIG_E] = {"fsconfig", EC_SYSTEM | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_FSCONFIG_X] = {"fsconfig", EC_SYSTEM | EC_SYSCALL, EF_USES_FD, 7, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"cmd", PT_ENUMFLAGS32, PF_DEC, fsconfig_cmds}, {"key", PT_CHARBUF, PF_NA}, {"value_bytebuf", PT_BYTEBUF, PF_NA}, {"value_charbuf", PT_CHARBUF, PF_NA}, {"aux", PT_INT32, PF_DEC}}}, - [PPME_SYSCALL_EPOLL_CREATE_E] = {"epoll_create", EC_WAIT | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, { {"size", PT_INT32, PF_DEC} } }, - [PPME_SYSCALL_EPOLL_CREATE_X] = {"epoll_create", EC_WAIT | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, { {"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_EPOLL_CREATE1_E] = {"epoll_create1", EC_WAIT | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"flags", PT_FLAGS32, PF_HEX, epoll_create1_flags} } }, - [PPME_SYSCALL_EPOLL_CREATE1_X] = {"epoll_create1", EC_WAIT | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC} } }, - [PPME_SYSCALL_CHOWN_E] = {"chown", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_CHOWN_X] = {"chown", EC_FILE | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_LCHOWN_E] = {"lchown", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_LCHOWN_X] = {"lchown", EC_FILE | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_FCHOWN_E] = {"fchown", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_FCHOWN_X] = {"fchown", EC_FILE | EC_SYSCALL, EF_USES_FD, 4, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_FCHOWNAT_E] = {"fchownat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_FCHOWNAT_X] = {"fchownat", EC_FILE | EC_SYSCALL, EF_NONE, 6, {{"res", PT_ERRNO, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"pathname", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"uid", PT_UINT32, PF_DEC}, {"gid", PT_UINT32, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, fchownat_flags}} }, - [PPME_SYSCALL_UMOUNT_1_E] = {"umount", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_UMOUNT_1_X] = {"umount", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA} } }, - [PPME_SOCKET_ACCEPT4_6_E] = {"accept4", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"flags", PT_INT32, PF_HEX} } }, - [PPME_SOCKET_ACCEPT4_6_X] = {"accept4", EC_NET | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 5, {{"fd", PT_FD, PF_DEC}, {"tuple", PT_SOCKTUPLE, PF_NA}, {"queuepct", PT_UINT8, PF_DEC}, {"queuelen", PT_UINT32, PF_DEC}, {"queuemax", PT_UINT32, PF_DEC} } }, - [PPME_SYSCALL_UMOUNT2_E] = {"umount2", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"flags", PT_FLAGS32, PF_HEX, umount_flags} } }, - [PPME_SYSCALL_UMOUNT2_X] = {"umount2", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 2, {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA} } }, - [PPME_SYSCALL_PIPE2_E] = {"pipe2", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_PIPE2_X] = {"pipe2", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 5, {{"res", PT_ERRNO, PF_DEC}, {"fd1", PT_FD, PF_DEC}, {"fd2", PT_FD, PF_DEC}, {"ino", PT_UINT64, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, file_flags}} }, - [PPME_SYSCALL_INOTIFY_INIT1_E] = {"inotify_init1", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_INOTIFY_INIT1_X] = {"inotify_init1", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"res", PT_FD, PF_DEC}, {"flags", PT_FLAGS16, PF_HEX, file_flags}}}, - [PPME_SYSCALL_EVENTFD2_E] = {"eventfd2", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 1, {{"initval", PT_UINT64, PF_DEC} } }, - [PPME_SYSCALL_EVENTFD2_X] = {"eventfd2", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"res", PT_FD, PF_DEC}, {"flags", PT_FLAGS16, PF_HEX, file_flags} } }, - [PPME_SYSCALL_SIGNALFD4_E] = {"signalfd4", EC_SIGNAL | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"fd", PT_FD, PF_DEC}, {"mask", PT_UINT32, PF_HEX}}}, - [PPME_SYSCALL_SIGNALFD4_X] = {"signalfd4", EC_SIGNAL | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 2, {{"res", PT_FD, PF_DEC}, {"flags", PT_FLAGS16, PF_HEX, file_flags}}}, - [PPME_SYSCALL_PRCTL_E] = {"prctl", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0 }, - [PPME_SYSCALL_PRCTL_X] = {"prctl", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 4, {{"res", PT_ERRNO, PF_DEC}, {"option", PT_ENUMFLAGS32, PF_DEC, prctl_options}, {"arg2_str", PT_CHARBUF, PF_NA}, {"arg2_int", PT_INT64, PF_DEC} } }, - [PPME_ASYNCEVENT_E] = {"asyncevent", EC_OTHER | EC_METAEVENT, EF_LARGE_PAYLOAD, 3, {{"plugin_id", PT_UINT32, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"data", PT_BYTEBUF, PF_NA} } }, - [PPME_ASYNCEVENT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, - [PPME_SYSCALL_MEMFD_CREATE_E] = {"memfd_create", EC_MEMORY | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_MEMFD_CREATE_X] = {"memfd_create", EC_MEMORY | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 3, {{"fd", PT_FD, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, memfd_create_flags} } }, - [PPME_SYSCALL_PIDFD_GETFD_E] = {"pidfd_getfd", EC_PROCESS | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_PIDFD_GETFD_X] = {"pidfd_getfd", EC_PROCESS | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 4, {{"fd", PT_FD, PF_DEC}, {"pid_fd", PT_FD, PF_DEC}, {"target_fd", PT_FD, PF_DEC}, {"flags", PT_UINT32, PF_HEX}}}, - [PPME_SYSCALL_PIDFD_OPEN_E] = {"pidfd_open", EC_PROCESS | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, - [PPME_SYSCALL_PIDFD_OPEN_X] = {"pidfd_open", EC_PROCESS | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 3, {{"fd", PT_FD, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"flags", PT_FLAGS32, PF_HEX, pidfd_open_flags}}}, - [PPME_SYSCALL_INIT_MODULE_E] = {"init_module", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_INIT_MODULE_X] = {"init_module", EC_OTHER | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"img", PT_BYTEBUF, PF_NA}, {"length", PT_UINT64, PF_DEC}, {"uargs", PT_CHARBUF, PF_NA}}}, - [PPME_SYSCALL_FINIT_MODULE_E] = {"finit_module", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_FINIT_MODULE_X] = {"finit_module", EC_OTHER | EC_SYSCALL, EF_USES_FD | EF_READS_FROM_FD, 4, {{"res", PT_ERRNO, PF_DEC}, {"fd", PT_FD, PF_DEC}, {"uargs", PT_CHARBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, finit_module_flags}}}, - [PPME_SYSCALL_MKNOD_E] = {"mknod", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MKNOD_X] = {"mknod", EC_OTHER | EC_SYSCALL, EF_NONE, 4, {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA},{"mode", PT_MODE, PF_OCT, mknod_mode},{"dev", PT_UINT32, PF_DEC}}}, - [PPME_SYSCALL_MKNODAT_E] = {"mknodat", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_MKNODAT_X] = {"mknodat", EC_OTHER | EC_SYSCALL, EF_USES_FD, 5, {{"res", PT_ERRNO, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"path", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)},{"mode", PT_MODE, PF_OCT, mknod_mode},{"dev", PT_UINT32, PF_DEC}}}, - [PPME_SYSCALL_NEWFSTATAT_E] = {"newfstatat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_NEWFSTATAT_X] = {"newfstatat", EC_FILE | EC_SYSCALL, EF_USES_FD, 4, {{"res", PT_ERRNO, PF_DEC}, {"dirfd", PT_FD, PF_DEC}, {"path", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, {"flags", PT_FLAGS32, PF_HEX, newfstatat_flags}}}, - [PPME_SYSCALL_PROCESS_VM_READV_E] = {"process_vm_readv", EC_SYSCALL | EC_IPC, EF_NONE, 0}, - [PPME_SYSCALL_PROCESS_VM_READV_X] = {"process_vm_readv", EC_SYSCALL | EC_IPC, EF_NONE, 3, {{"res", PT_INT64, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, - [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = {"process_vm_writev", EC_SYSCALL | EC_IPC, EF_NONE, 0}, - [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = {"process_vm_writev", EC_SYSCALL | EC_IPC, EF_NONE, 3, {{"res", PT_INT64, PF_DEC}, {"pid", PT_PID, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, - [PPME_SYSCALL_DELETE_MODULE_E] = {"delete_module", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, - [PPME_SYSCALL_DELETE_MODULE_X] = {"delete_module", EC_OTHER | EC_SYSCALL, EF_NONE, 3, {{"res", PT_ERRNO, PF_DEC}, {"name", PT_CHARBUF, PF_NA}, {"flags", PT_FLAGS32, PF_HEX, delete_module_flags}}}, - [PPME_SYSCALL_SETREUID_E] = {"setreuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 0 }, - [PPME_SYSCALL_SETREUID_X] = {"setreuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 3, {{"res", PT_ERRNO, PF_DEC}, {"ruid", PT_UID, PF_DEC}, {"euid", PT_UID, PF_DEC}} }, - [PPME_SYSCALL_SETREGID_E] = {"setregid", EC_USER | EC_SYSCALL, EF_NONE, 0 }, - [PPME_SYSCALL_SETREGID_X] = {"setregid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 3, {{"res", PT_ERRNO, PF_DEC}, {"rgid", PT_UID, PF_DEC}, {"egid", PT_UID, PF_DEC}} }, + [PPME_GENERIC_E] = {"syscall", + EC_OTHER | EC_SYSCALL, + EF_NONE, + 2, + {{"ID", PT_SYSCALLID, PF_DEC}, {"nativeID", PT_UINT16, PF_DEC}}}, + [PPME_GENERIC_X] = + {"syscall", EC_OTHER | EC_SYSCALL, EF_NONE, 1, {{"ID", PT_SYSCALLID, PF_DEC}}}, + [PPME_SYSCALL_OPEN_E] = {"open", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 3, + {{"name", PT_FSPATH, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"mode", PT_UINT32, PF_OCT}}}, + [PPME_SYSCALL_OPEN_X] = {"open", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 6, + {{"fd", PT_FD, PF_DEC}, + {"name", PT_FSPATH, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"mode", PT_UINT32, PF_OCT}, + {"dev", PT_UINT32, PF_HEX}, + {"ino", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_CLOSE_E] = {"close", + EC_IO_OTHER | EC_SYSCALL, + EF_DESTROYS_FD | EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_CLOSE_X] = {"close", + EC_IO_OTHER | EC_SYSCALL, + EF_DESTROYS_FD | EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_READ_E] = {"read", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 2, + {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_READ_X] = {"read", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_WRITE_E] = {"write", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_WRITE_X] = {"write", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_BRK_1_E] = + {"brk", EC_MEMORY | EC_SYSCALL, EF_OLD_VERSION, 1, {{"size", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_BRK_1_X] = + {"brk", EC_MEMORY | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_UINT64, PF_HEX}}}, + [PPME_SYSCALL_EXECVE_8_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_EXECVE_8_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 8, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_CLONE_11_E] = {"clone", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_CLONE_11_X] = {"clone", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 11, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_PROCEXIT_E] = {"procexit", + EC_PROCESS | EC_TRACEPOINT, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_PROCEXIT_X] = {"NA", EC_UNKNOWN, EF_UNUSED | EF_OLD_VERSION, 0}, + [PPME_SOCKET_SOCKET_E] = {"socket", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 3, + {{"domain", PT_ENUMFLAGS32, PF_DEC, socket_families}, + {"type", PT_UINT32, PF_DEC}, + {"proto", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_SOCKET_X] = {"socket", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SOCKET_BIND_E] = {"bind", + EC_NET | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SOCKET_BIND_X] = {"bind", + EC_NET | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"addr", PT_SOCKADDR, PF_NA}}}, + [PPME_SOCKET_CONNECT_E] = {"connect", + EC_NET | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 2, + {{"fd", PT_FD, PF_DEC}, {"addr", PT_SOCKADDR, PF_NA}}}, + [PPME_SOCKET_CONNECT_X] = {"connect", + EC_NET | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}, + {"fd", PT_FD, PF_DEC}}}, + [PPME_SOCKET_LISTEN_E] = {"listen", + EC_NET | EC_SYSCALL, + EF_USES_FD, + 2, + {{"fd", PT_FD, PF_DEC}, {"backlog", PT_INT32, PF_DEC}}}, + [PPME_SOCKET_LISTEN_X] = + {"listen", EC_NET | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SOCKET_ACCEPT_E] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SOCKET_ACCEPT_X] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 3, + {{"fd", PT_FD, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}, + {"queuepct", PT_UINT8, PF_DEC}}}, + [PPME_SOCKET_SEND_E] = {"send", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_SEND_X] = {"send", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SOCKET_SENDTO_E] = {"sendto", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, + 3, + {{"fd", PT_FD, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}}}, + [PPME_SOCKET_SENDTO_X] = {"sendto", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SOCKET_RECV_E] = {"recv", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 2, + {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_RECV_X] = {"recv", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SOCKET_RECVFROM_E] = {"recvfrom", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, + 2, + {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_RECVFROM_X] = {"recvfrom", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"data", PT_BYTEBUF, PF_NA}, + {"tuple", PT_SOCKTUPLE, PF_NA}}}, + [PPME_SOCKET_SHUTDOWN_E] = {"shutdown", + EC_NET | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 2, + {{"fd", PT_FD, PF_DEC}, + {"how", PT_ENUMFLAGS8, PF_HEX, shutdown_how}}}, + [PPME_SOCKET_SHUTDOWN_X] = {"shutdown", + EC_NET | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SOCKET_GETSOCKNAME_E] = {"getsockname", EC_NET | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_GETSOCKNAME_X] = {"getsockname", EC_NET | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_GETPEERNAME_E] = {"getpeername", EC_NET | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_GETPEERNAME_X] = {"getpeername", EC_NET | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_SOCKETPAIR_E] = {"socketpair", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 3, + {{"domain", PT_ENUMFLAGS32, PF_DEC, socket_families}, + {"type", PT_UINT32, PF_DEC}, + {"proto", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_SOCKETPAIR_X] = {"socketpair", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 5, + {{"res", PT_ERRNO, PF_DEC}, + {"fd1", PT_FD, PF_DEC}, + {"fd2", PT_FD, PF_DEC}, + {"source", PT_UINT64, PF_HEX}, + {"peer", PT_UINT64, PF_HEX}}}, + [PPME_SOCKET_SETSOCKOPT_E] = {"setsockopt", EC_NET | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_SETSOCKOPT_X] = + {"setsockopt", + EC_NET | EC_SYSCALL, + EF_USES_FD, + 6, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"level", PT_ENUMFLAGS8, PF_DEC, sockopt_levels}, + {"optname", PT_ENUMFLAGS8, PF_DEC, sockopt_options}, + {"val", PT_DYN, PF_DEC, sockopt_dynamic_param, PPM_SOCKOPT_IDX_MAX}, + {"optlen", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_GETSOCKOPT_E] = {"getsockopt", EC_NET | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SOCKET_GETSOCKOPT_X] = + {"getsockopt", + EC_NET | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 6, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"level", PT_ENUMFLAGS8, PF_DEC, sockopt_levels}, + {"optname", PT_ENUMFLAGS8, PF_DEC, sockopt_options}, + {"val", PT_DYN, PF_DEC, sockopt_dynamic_param, PPM_SOCKOPT_IDX_MAX}, + {"optlen", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_SENDMSG_E] = {"sendmsg", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, + 3, + {{"fd", PT_FD, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}}}, + [PPME_SOCKET_SENDMSG_X] = {"sendmsg", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SOCKET_SENDMMSG_E] = {"sendmmsg", EC_IO_WRITE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_SENDMMSG_X] = {"sendmmsg", EC_IO_WRITE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_RECVMSG_E] = {"recvmsg", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SOCKET_RECVMSG_X] = {"recvmsg", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD | EF_MODIFIES_STATE, + 5, + {{"res", PT_ERRNO, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"data", PT_BYTEBUF, PF_NA}, + {"tuple", PT_SOCKTUPLE, PF_NA}, + {"msgcontrol", PT_BYTEBUF, PF_NA}}}, + [PPME_SOCKET_RECVMMSG_E] = {"recvmmsg", EC_IO_READ | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_RECVMMSG_X] = {"recvmmsg", EC_IO_READ | EC_SYSCALL, EF_NONE, 0}, + [PPME_SOCKET_ACCEPT4_E] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"flags", PT_INT32, PF_HEX}}}, + [PPME_SOCKET_ACCEPT4_X] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 3, + {{"fd", PT_FD, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}, + {"queuepct", PT_UINT8, PF_DEC}}}, + [PPME_SYSCALL_CREAT_E] = {"creat", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"name", PT_FSPATH, PF_NA}, {"mode", PT_UINT32, PF_OCT}}}, + [PPME_SYSCALL_CREAT_X] = {"creat", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 6, + {{"fd", PT_FD, PF_DEC}, + {"name", PT_FSPATH, PF_NA}, + {"mode", PT_UINT32, PF_OCT}, + {"dev", PT_UINT32, PF_HEX}, + {"ino", PT_UINT64, PF_DEC}, + {"creat_flags", PT_FLAGS16, PF_HEX, creat_flags}}}, + [PPME_SYSCALL_PIPE_E] = {"pipe", EC_IPC | EC_SYSCALL, EF_CREATES_FD | EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_PIPE_X] = {"pipe", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"fd1", PT_FD, PF_DEC}, + {"fd2", PT_FD, PF_DEC}, + {"ino", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_EVENTFD_E] = {"eventfd", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"initval", PT_UINT64, PF_DEC}, {"flags", PT_UINT32, PF_HEX}}}, + [PPME_SYSCALL_EVENTFD_X] = {"eventfd", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_FUTEX_E] = {"futex", + EC_IPC | EC_SYSCALL, + EF_NONE, + 3, + {{"addr", PT_UINT64, PF_HEX}, + {"op", PT_FLAGS16, PF_HEX, futex_operations}, + {"val", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_FUTEX_X] = + {"futex", EC_IPC | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_STAT_E] = {"stat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_STAT_X] = {"stat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_LSTAT_E] = {"lstat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_LSTAT_X] = {"lstat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_FSTAT_E] = + {"fstat", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA}}}, + [PPME_SYSCALL_FSTAT_X] = + {"fstat", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_STAT64_E] = {"stat64", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_STAT64_X] = {"stat64", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_LSTAT64_E] = {"lstat64", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_LSTAT64_X] = {"lstat64", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_FSTAT64_E] = + {"fstat64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA}}}, + [PPME_SYSCALL_FSTAT64_X] = + {"fstat64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_EPOLLWAIT_E] = {"epoll_wait", + EC_WAIT | EC_SYSCALL, + EF_WAITS, + 1, + {{"maxevents", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_EPOLLWAIT_X] = + {"epoll_wait", EC_WAIT | EC_SYSCALL, EF_WAITS, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_POLL_E] = {"poll", + EC_WAIT | EC_SYSCALL, + EF_WAITS, + 2, + {{"fds", PT_FDLIST, PF_DEC}, {"timeout", PT_INT64, PF_DEC}}}, + [PPME_SYSCALL_POLL_X] = {"poll", + EC_WAIT | EC_SYSCALL, + EF_WAITS, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"fds", PT_FDLIST, PF_DEC}}}, + [PPME_SYSCALL_SELECT_E] = {"select", EC_WAIT | EC_SYSCALL, EF_WAITS, 0}, + [PPME_SYSCALL_SELECT_X] = + {"select", EC_WAIT | EC_SYSCALL, EF_WAITS, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_NEWSELECT_E] = {"select", EC_WAIT | EC_SYSCALL, EF_WAITS | EF_OLD_VERSION, 0}, + [PPME_SYSCALL_NEWSELECT_X] = {"select", + EC_WAIT | EC_SYSCALL, + EF_WAITS | EF_OLD_VERSION, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_LSEEK_E] = {"lseek", + EC_FILE | EC_SYSCALL, + EF_USES_FD, + 3, + {{"fd", PT_FD, PF_DEC}, + {"offset", PT_UINT64, PF_DEC}, + {"whence", PT_ENUMFLAGS8, PF_DEC, lseek_whence}}}, + [PPME_SYSCALL_LSEEK_X] = + {"lseek", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_LLSEEK_E] = {"llseek", + EC_FILE | EC_SYSCALL, + EF_USES_FD, + 3, + {{"fd", PT_FD, PF_DEC}, + {"offset", PT_UINT64, PF_DEC}, + {"whence", PT_ENUMFLAGS8, PF_DEC, lseek_whence}}}, + [PPME_SYSCALL_LLSEEK_X] = + {"llseek", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_IOCTL_2_E] = {"ioctl", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD | EF_OLD_VERSION, + 2, + {{"fd", PT_FD, PF_DEC}, {"request", PT_UINT64, PF_HEX}}}, + [PPME_SYSCALL_IOCTL_2_X] = {"ioctl", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD | EF_OLD_VERSION, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_GETCWD_E] = {"getcwd", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + /* Note: path is PT_CHARBUF and not PT_FSPATH because we assume it's absolute and will never + need resolution */ + [PPME_SYSCALL_GETCWD_X] = {"getcwd", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_CHARBUF, PF_NA}}}, + /* Note: path is PT_CHARBUF and not PT_FSPATH because we don't want it to be resolved, since + the event handler already changes it */ + [PPME_SYSCALL_CHDIR_E] = {"chdir", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_CHDIR_X] = {"chdir", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_CHARBUF, PF_NA}}}, + [PPME_SYSCALL_FCHDIR_E] = {"fchdir", + EC_FILE | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_NA}}}, + [PPME_SYSCALL_FCHDIR_X] = {"fchdir", + EC_FILE | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_MKDIR_E] = {"mkdir", + EC_FILE | EC_SYSCALL, + EF_OLD_VERSION, + 2, + {{"path", PT_FSPATH, PF_NA}, {"mode", PT_UINT32, PF_HEX}}}, + [PPME_SYSCALL_MKDIR_X] = + {"mkdir", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_RMDIR_E] = + {"rmdir", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_RMDIR_X] = + {"rmdir", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_OPENAT_E] = {"openat", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 4, + {{"dirfd", PT_FD, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"mode", PT_UINT32, PF_OCT}}}, + [PPME_SYSCALL_OPENAT_X] = {"openat", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_LINK_E] = {"link", + EC_FILE | EC_SYSCALL, + EF_OLD_VERSION, + 2, + {{"oldpath", PT_FSPATH, PF_NA}, {"newpath", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_LINK_X] = + {"link", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_LINKAT_E] = {"linkat", + EC_FILE | EC_SYSCALL, + EF_OLD_VERSION, + 4, + {{"olddir", PT_FD, PF_DEC}, + {"oldpath", PT_CHARBUF, PF_NA}, + {"newdir", PT_FD, PF_DEC}, + {"newpath", PT_CHARBUF, PF_NA}}}, + [PPME_SYSCALL_LINKAT_X] = + {"linkat", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_UNLINK_E] = + {"unlink", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_UNLINK_X] = + {"unlink", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_UNLINKAT_E] = {"unlinkat", + EC_FILE | EC_SYSCALL, + EF_OLD_VERSION, + 2, + {{"dirfd", PT_FD, PF_DEC}, {"name", PT_CHARBUF, PF_NA}}}, + [PPME_SYSCALL_UNLINKAT_X] = + {"unlinkat", EC_FILE | EC_SYSCALL, EF_OLD_VERSION, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_PREAD_E] = {"pread", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 3, + {{"fd", PT_FD, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"pos", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_PREAD_X] = {"pread", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_PWRITE_E] = {"pwrite", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 3, + {{"fd", PT_FD, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"pos", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_PWRITE_X] = {"pwrite", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_READV_E] = {"readv", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_READV_X] = {"readv", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_WRITEV_E] = {"writev", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"fd", PT_FD, PF_DEC}, {"size", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_WRITEV_X] = {"writev", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_PREADV_E] = {"preadv", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 2, + {{"fd", PT_FD, PF_DEC}, {"pos", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_PREADV_X] = {"preadv", + EC_IO_READ | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_PWRITEV_E] = {"pwritev", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 3, + {{"fd", PT_FD, PF_DEC}, + {"size", PT_UINT32, PF_DEC}, + {"pos", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_PWRITEV_X] = {"pwritev", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD | EF_WRITES_TO_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_DUP_E] = {"dup", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_DUP_X] = {"dup", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"res", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_SIGNALFD_E] = {"signalfd", + EC_SIGNAL | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 3, + {{"fd", PT_FD, PF_DEC}, + {"mask", PT_UINT32, PF_HEX}, + {"flags", PT_UINT8, PF_HEX}}}, + [PPME_SYSCALL_SIGNALFD_X] = {"signalfd", + EC_SIGNAL | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_KILL_E] = {"kill", + EC_SIGNAL | EC_SYSCALL, + EF_NONE, + 2, + {{"pid", PT_PID, PF_DEC}, {"sig", PT_SIGTYPE, PF_DEC}}}, + [PPME_SYSCALL_KILL_X] = + {"kill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_TKILL_E] = {"tkill", + EC_SIGNAL | EC_SYSCALL, + EF_NONE, + 2, + {{"tid", PT_PID, PF_DEC}, {"sig", PT_SIGTYPE, PF_DEC}}}, + [PPME_SYSCALL_TKILL_X] = + {"tkill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_TGKILL_E] = {"tgkill", + EC_SIGNAL | EC_SYSCALL, + EF_NONE, + 3, + {{"pid", PT_PID, PF_DEC}, + {"tid", PT_PID, PF_DEC}, + {"sig", PT_SIGTYPE, PF_DEC}}}, + [PPME_SYSCALL_TGKILL_X] = + {"tgkill", EC_SIGNAL | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_NANOSLEEP_E] = {"nanosleep", + EC_SLEEP | EC_SYSCALL, + EF_WAITS, + 1, + {{"interval", PT_RELTIME, PF_DEC}}}, + [PPME_SYSCALL_NANOSLEEP_X] = + {"nanosleep", EC_SLEEP | EC_SYSCALL, EF_WAITS, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_TIMERFD_CREATE_E] = {"timerfd_create", + EC_TIME | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"clockid", PT_UINT8, PF_DEC}, + {"flags", PT_UINT8, PF_HEX}}}, + [PPME_SYSCALL_TIMERFD_CREATE_X] = {"timerfd_create", + EC_TIME | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_INOTIFY_INIT_E] = {"inotify_init", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"flags", PT_UINT8, PF_HEX}}}, + [PPME_SYSCALL_INOTIFY_INIT_X] = {"inotify_init", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_GETRLIMIT_E] = {"getrlimit", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 1, + {{"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources}}}, + [PPME_SYSCALL_GETRLIMIT_X] = {"getrlimit", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"cur", PT_INT64, PF_DEC}, + {"max", PT_INT64, PF_DEC}}}, + [PPME_SYSCALL_SETRLIMIT_E] = {"setrlimit", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 1, + {{"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources}}}, + [PPME_SYSCALL_SETRLIMIT_X] = {"setrlimit", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"cur", PT_INT64, PF_DEC}, + {"max", PT_INT64, PF_DEC}, + {"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources}}}, + [PPME_SYSCALL_PRLIMIT_E] = {"prlimit", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 2, + {{"pid", PT_PID, PF_DEC}, + {"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources}}}, + [PPME_SYSCALL_PRLIMIT_X] = {"prlimit", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 7, + {{"res", PT_ERRNO, PF_DEC}, + {"newcur", PT_INT64, PF_DEC}, + {"newmax", PT_INT64, PF_DEC}, + {"oldcur", PT_INT64, PF_DEC}, + {"oldmax", PT_INT64, PF_DEC}, + {"pid", PT_INT64, PF_DEC}, + {"resource", PT_ENUMFLAGS8, PF_DEC, rlimit_resources}}}, + [PPME_SCHEDSWITCH_1_E] = {"switch", + EC_SCHEDULER | EC_TRACEPOINT, + EF_SKIPPARSERESET | EF_OLD_VERSION, + 1, + {{"next", PT_PID, PF_DEC}}}, + [PPME_SCHEDSWITCH_1_X] = {"NA", + EC_UNKNOWN, + EF_SKIPPARSERESET | EF_UNUSED | EF_OLD_VERSION, + 0}, + [PPME_DROP_E] = {"drop", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET, + 1, + {{"ratio", PT_UINT32, PF_DEC}}}, + [PPME_DROP_X] = {"drop", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET, + 1, + {{"ratio", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_FCNTL_E] = {"fcntl", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 2, + {{"fd", PT_FD, PF_DEC}, + {"cmd", PT_ENUMFLAGS8, PF_DEC, fcntl_commands}}}, + [PPME_SYSCALL_FCNTL_X] = {"fcntl", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD | EF_MODIFIES_STATE, + 3, + {{"res", PT_FD, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"cmd", PT_ENUMFLAGS8, PF_DEC, fcntl_commands}}}, + [PPME_SCHEDSWITCH_6_E] = + {"switch", + EC_SCHEDULER | EC_TRACEPOINT, + EF_NONE, + 6, + {{"next", PT_PID, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}}}, /// TODO: do we need SKIPPARSERESET flag? + [PPME_SCHEDSWITCH_6_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_EXECVE_13_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_EXECVE_13_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 13, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_CLONE_16_E] = {"clone", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_CLONE_16_X] = {"clone", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 16, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_BRK_4_E] = + {"brk", EC_MEMORY | EC_SYSCALL, EF_NONE, 1, {{"addr", PT_UINT64, PF_HEX}}}, + [PPME_SYSCALL_BRK_4_X] = {"brk", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_UINT64, PF_HEX}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_MMAP_E] = {"mmap", + EC_MEMORY | EC_SYSCALL, + EF_USES_FD, + 6, + {{"addr", PT_UINT64, PF_HEX}, + {"length", PT_UINT64, PF_DEC}, + {"prot", PT_FLAGS32, PF_HEX, prot_flags}, + {"flags", PT_FLAGS32, PF_HEX, mmap_flags}, + {"fd", PT_FD, PF_DEC}, + {"offset", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_MMAP_X] = {"mmap", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_HEX}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_MMAP2_E] = {"mmap2", + EC_MEMORY | EC_SYSCALL, + EF_USES_FD, + 6, + {{"addr", PT_UINT64, PF_HEX}, + {"length", PT_UINT64, PF_DEC}, + {"prot", PT_FLAGS32, PF_HEX, prot_flags}, + {"flags", PT_FLAGS32, PF_HEX, mmap_flags}, + {"fd", PT_FD, PF_DEC}, + {"pgoffset", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_MMAP2_X] = {"mmap2", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_HEX}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_MUNMAP_E] = {"munmap", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 2, + {{"addr", PT_UINT64, PF_HEX}, {"length", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_MUNMAP_X] = {"munmap", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_SPLICE_E] = {"splice", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD, + 4, + {{"fd_in", PT_FD, PF_DEC}, + {"fd_out", PT_FD, PF_DEC}, + {"size", PT_UINT64, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, splice_flags}}}, + [PPME_SYSCALL_SPLICE_X] = + {"splice", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_PTRACE_E] = {"ptrace", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 2, + {{"request", PT_ENUMFLAGS16, PF_DEC, ptrace_requests}, + {"pid", PT_PID, PF_DEC}}}, + [PPME_SYSCALL_PTRACE_X] = + {"ptrace", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"addr", PT_DYN, PF_HEX, ptrace_dynamic_param, PPM_PTRACE_IDX_MAX}, + {"data", PT_DYN, PF_HEX, ptrace_dynamic_param, PPM_PTRACE_IDX_MAX}}}, + [PPME_SYSCALL_IOCTL_3_E] = {"ioctl", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD, + 3, + {{"fd", PT_FD, PF_DEC}, + {"request", PT_UINT64, PF_HEX}, + {"argument", PT_UINT64, PF_HEX}}}, + [PPME_SYSCALL_IOCTL_3_X] = + {"ioctl", EC_IO_OTHER | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_EXECVE_14_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_EXECVE_14_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 14, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"env", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_RENAME_E] = {"rename", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_RENAME_X] = {"rename", + EC_FILE | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"oldpath", PT_FSPATH, PF_NA}, + {"newpath", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_RENAMEAT_E] = {"renameat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_RENAMEAT_X] = {"renameat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 5, + {{"res", PT_ERRNO, PF_DEC}, + {"olddirfd", PT_FD, PF_DEC}, + {"oldpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"newdirfd", PT_FD, PF_DEC}, + {"newpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(3)}}}, + [PPME_SYSCALL_SYMLINK_E] = {"symlink", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_SYMLINK_X] = {"symlink", + EC_FILE | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"target", PT_CHARBUF, PF_NA}, + {"linkpath", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_SYMLINKAT_E] = {"symlinkat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_SYMLINKAT_X] = {"symlinkat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"target", PT_CHARBUF, PF_NA}, + {"linkdirfd", PT_FD, PF_DEC}, + {"linkpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(2)}}}, + [PPME_SYSCALL_FORK_E] = {"fork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_FORK_X] = {"fork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 16, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_VFORK_E] = {"vfork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_VFORK_X] = {"vfork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 16, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_PROCEXIT_1_E] = {"procexit", + EC_PROCESS | EC_TRACEPOINT, + EF_MODIFIES_STATE, + 5, + {{"status", PT_ERRNO, PF_DEC}, + {"ret", PT_ERRNO, PF_DEC}, + {"sig", PT_SIGTYPE, PF_DEC}, + {"core", PT_UINT8, PF_DEC}, + {"reaper_tid", PT_PID, PF_DEC}}}, + [PPME_PROCEXIT_1_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_SENDFILE_E] = {"sendfile", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD, + 4, + {{"out_fd", PT_FD, PF_DEC}, + {"in_fd", PT_FD, PF_DEC}, + {"offset", PT_UINT64, PF_DEC}, + {"size", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_SENDFILE_X] = {"sendfile", + EC_IO_WRITE | EC_SYSCALL, + EF_USES_FD, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"offset", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_QUOTACTL_E] = {"quotactl", + EC_USER | EC_SYSCALL, + EF_NONE, + 4, + {{"cmd", PT_FLAGS16, PF_DEC, quotactl_cmds}, + {"type", PT_FLAGS8, PF_DEC, quotactl_types}, + {"id", PT_UINT32, PF_DEC}, + {"quota_fmt", PT_FLAGS8, PF_DEC, quotactl_quota_fmts}}}, + [PPME_SYSCALL_QUOTACTL_X] = {"quotactl", + EC_USER | EC_SYSCALL, + EF_NONE, + 14, + {{"res", PT_ERRNO, PF_DEC}, + {"special", PT_CHARBUF, PF_NA}, + {"quotafilepath", PT_CHARBUF, PF_NA}, + {"dqb_bhardlimit", PT_UINT64, PF_DEC}, + {"dqb_bsoftlimit", PT_UINT64, PF_DEC}, + {"dqb_curspace", PT_UINT64, PF_DEC}, + {"dqb_ihardlimit", PT_UINT64, PF_DEC}, + {"dqb_isoftlimit", PT_UINT64, PF_DEC}, + {"dqb_btime", PT_RELTIME, PF_DEC}, + {"dqb_itime", PT_RELTIME, PF_DEC}, + {"dqi_bgrace", PT_RELTIME, PF_DEC}, + {"dqi_igrace", PT_RELTIME, PF_DEC}, + {"dqi_flags", PT_FLAGS8, PF_DEC, quotactl_dqi_flags}, + {"quota_fmt_out", PT_FLAGS8, PF_DEC, quotactl_quota_fmts}}}, + [PPME_SYSCALL_SETRESUID_E] = {"setresuid", + EC_USER | EC_SYSCALL, + EF_MODIFIES_STATE, + 3, + {{"ruid", PT_UID, PF_DEC}, + {"euid", PT_UID, PF_DEC}, + {"suid", PT_UID, PF_DEC}}}, + [PPME_SYSCALL_SETRESUID_X] = {"setresuid", + EC_USER | EC_SYSCALL, + EF_MODIFIES_STATE, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_SETRESGID_E] = {"setresgid", + EC_USER | EC_SYSCALL, + EF_MODIFIES_STATE, + 3, + {{"rgid", PT_GID, PF_DEC}, + {"egid", PT_GID, PF_DEC}, + {"sgid", PT_GID, PF_DEC}}}, + [PPME_SYSCALL_SETRESGID_X] = {"setresgid", + EC_USER | EC_SYSCALL, + EF_MODIFIES_STATE, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SCAPEVENT_E] = {"scapevent", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET, + 2, + {{"event_type", PT_UINT32, PF_DEC}, + {"event_data", PT_UINT64, PF_DEC}}}, + [PPME_SCAPEVENT_X] = {"scapevent", EC_INTERNAL | EC_METAEVENT, EF_UNUSED, 0}, + [PPME_SYSCALL_SETUID_E] = + {"setuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"uid", PT_UID, PF_DEC}}}, + [PPME_SYSCALL_SETUID_X] = + {"setuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_SETGID_E] = + {"setgid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"gid", PT_GID, PF_DEC}}}, + [PPME_SYSCALL_SETGID_X] = + {"setgid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_GETUID_E] = {"getuid", EC_USER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_GETUID_X] = + {"getuid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"uid", PT_UID, PF_DEC}}}, + [PPME_SYSCALL_GETEUID_E] = {"geteuid", EC_USER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_GETEUID_X] = + {"geteuid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"euid", PT_UID, PF_DEC}}}, + [PPME_SYSCALL_GETGID_E] = {"getgid", EC_USER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_GETGID_X] = + {"getgid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"gid", PT_GID, PF_DEC}}}, + [PPME_SYSCALL_GETEGID_E] = {"getegid", EC_USER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_GETEGID_X] = + {"getegid", EC_USER | EC_SYSCALL, EF_NONE, 1, {{"egid", PT_GID, PF_DEC}}}, + [PPME_SYSCALL_GETRESUID_E] = {"getresuid", EC_USER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_GETRESUID_X] = {"getresuid", + EC_USER | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"ruid", PT_UID, PF_DEC}, + {"euid", PT_UID, PF_DEC}, + {"suid", PT_UID, PF_DEC}}}, + [PPME_SYSCALL_GETRESGID_E] = {"getresgid", EC_USER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_GETRESGID_X] = {"getresgid", + EC_USER | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"rgid", PT_GID, PF_DEC}, + {"egid", PT_GID, PF_DEC}, + {"sgid", PT_GID, PF_DEC}}}, + [PPME_SYSCALL_EXECVE_15_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_EXECVE_15_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 15, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"env", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_CLONE_17_E] = {"clone", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_CLONE_17_X] = {"clone", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 17, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_FORK_17_E] = {"fork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_FORK_17_X] = {"fork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 17, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_VFORK_17_E] = {"vfork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_VFORK_17_X] = {"vfork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 17, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_CLONE_20_E] = {"clone", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_CLONE_20_X] = {"clone", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 21, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}, + {"vtid", PT_PID, PF_DEC}, + {"vpid", PT_PID, PF_DEC}, + {"pidns_init_start_ts", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_FORK_20_E] = {"fork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_FORK_20_X] = {"fork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 21, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}, + {"vtid", PT_PID, PF_DEC}, + {"vpid", PT_PID, PF_DEC}, + {"pidns_init_start_ts", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_VFORK_20_E] = {"vfork", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_VFORK_20_X] = {"vfork", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 21, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}, + {"vtid", PT_PID, PF_DEC}, + {"vpid", PT_PID, PF_DEC}, + {"pidns_init_start_ts", PT_UINT64, PF_DEC}}}, + [PPME_CONTAINER_E] = {"container", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET | EF_MODIFIES_STATE | EF_OLD_VERSION, + 4, + {{"id", PT_CHARBUF, PF_NA}, + {"type", PT_UINT32, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"image", PT_CHARBUF, PF_NA}}}, + [PPME_CONTAINER_X] = {"NA", EC_UNKNOWN, EF_UNUSED | EF_OLD_VERSION, 0}, + [PPME_SYSCALL_EXECVE_16_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_EXECVE_16_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 16, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"env", PT_BYTEBUF, PF_NA}}}, + [PPME_SIGNALDELIVER_E] = {"signaldeliver", + EC_SIGNAL | EC_TRACEPOINT, + EF_NONE, + 3, + {{"spid", PT_PID, PF_DEC}, + {"dpid", PT_PID, PF_DEC}, + {"sig", PT_SIGTYPE, PF_DEC}}}, + [PPME_SIGNALDELIVER_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_PROCINFO_E] = {"procinfo", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET, + 2, + {{"cpu_usr", PT_UINT64, PF_DEC}, {"cpu_sys", PT_UINT64, PF_DEC}}}, + [PPME_PROCINFO_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_GETDENTS_E] = + {"getdents", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA}}}, + [PPME_SYSCALL_GETDENTS_X] = + {"getdents", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_GETDENTS64_E] = + {"getdents64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"fd", PT_FD, PF_NA}}}, + [PPME_SYSCALL_GETDENTS64_X] = + {"getdents64", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_SETNS_E] = {"setns", + EC_PROCESS | EC_SYSCALL, + EF_USES_FD, + 2, + {{"fd", PT_FD, PF_NA}, + {"nstype", PT_FLAGS32, PF_HEX, clone_flags}}}, + [PPME_SYSCALL_SETNS_X] = + {"setns", EC_PROCESS | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_FLOCK_E] = {"flock", + EC_FILE | EC_SYSCALL, + EF_USES_FD, + 2, + {{"fd", PT_FD, PF_NA}, + {"operation", PT_FLAGS32, PF_HEX, flock_flags}}}, + [PPME_SYSCALL_FLOCK_X] = + {"flock", EC_FILE | EC_SYSCALL, EF_USES_FD, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_CPU_HOTPLUG_E] = {"cpu_hotplug", + EC_SYSTEM | EC_METAEVENT, + EF_SKIPPARSERESET | EF_MODIFIES_STATE, + 2, + {{"cpu", PT_UINT32, PF_DEC}, {"action", PT_UINT32, PF_DEC}}}, + [PPME_CPU_HOTPLUG_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SOCKET_ACCEPT_5_E] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SOCKET_ACCEPT_5_X] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 5, + {{"fd", PT_FD, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}, + {"queuepct", PT_UINT8, PF_DEC}, + {"queuelen", PT_UINT32, PF_DEC}, + {"queuemax", PT_UINT32, PF_DEC}}}, + [PPME_SOCKET_ACCEPT4_5_E] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"flags", PT_INT32, PF_HEX}}}, + [PPME_SOCKET_ACCEPT4_5_X] = {"accept", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE | EF_OLD_VERSION, + 5, + {{"fd", PT_FD, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}, + {"queuepct", PT_UINT8, PF_DEC}, + {"queuelen", PT_UINT32, PF_DEC}, + {"queuemax", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_SEMOP_E] = + {"semop", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"semid", PT_INT32, PF_DEC}}}, + [PPME_SYSCALL_SEMOP_X] = {"semop", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 8, + {{"res", PT_ERRNO, PF_DEC}, + {"nsops", PT_UINT32, PF_DEC}, + {"sem_num_0", PT_UINT16, PF_DEC}, + {"sem_op_0", PT_INT16, PF_DEC}, + {"sem_flg_0", PT_FLAGS16, PF_HEX, semop_flags}, + {"sem_num_1", PT_UINT16, PF_DEC}, + {"sem_op_1", PT_INT16, PF_DEC}, + {"sem_flg_1", PT_FLAGS16, PF_HEX, semop_flags}}}, + [PPME_SYSCALL_SEMCTL_E] = {"semctl", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 4, + {{"semid", PT_INT32, PF_DEC}, + {"semnum", PT_INT32, PF_DEC}, + {"cmd", PT_FLAGS16, PF_HEX, semctl_commands}, + {"val", PT_INT32, PF_DEC}}}, + [PPME_SYSCALL_SEMCTL_X] = + {"semctl", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_PPOLL_E] = {"ppoll", + EC_WAIT | EC_SYSCALL, + EF_WAITS, + 3, + {{"fds", PT_FDLIST, PF_DEC}, + {"timeout", PT_RELTIME, PF_DEC}, + {"sigmask", PT_SIGSET, PF_DEC}}}, + [PPME_SYSCALL_PPOLL_X] = {"ppoll", + EC_WAIT | EC_SYSCALL, + EF_WAITS, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"fds", PT_FDLIST, PF_DEC}}}, + [PPME_SYSCALL_MOUNT_E] = {"mount", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE, + 1, + {{"flags", PT_FLAGS32, PF_HEX, mount_flags}}}, + [PPME_SYSCALL_MOUNT_X] = {"mount", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"dev", PT_CHARBUF, PF_NA}, + {"dir", PT_FSPATH, PF_NA}, + {"type", PT_CHARBUF, PF_NA}}}, + [PPME_SYSCALL_UMOUNT_E] = {"umount", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"flags", PT_FLAGS32, PF_HEX, umount_flags}}}, + [PPME_SYSCALL_UMOUNT_X] = {"umount", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA}}}, + [PPME_K8S_E] = {"k8s", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET | EF_MODIFIES_STATE, + 1, + {{"json", PT_CHARBUF, PF_NA}}}, + [PPME_K8S_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_SEMGET_E] = {"semget", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 3, + {{"key", PT_INT32, PF_HEX}, + {"nsems", PT_INT32, PF_DEC}, + {"semflg", PT_FLAGS32, PF_HEX, semget_flags}}}, + [PPME_SYSCALL_SEMGET_X] = + {"semget", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_ACCESS_E] = {"access", + EC_FILE | EC_SYSCALL, + EF_NONE, + 1, + {{"mode", PT_FLAGS32, PF_HEX, access_flags}}}, + [PPME_SYSCALL_ACCESS_X] = {"access", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_CHROOT_E] = {"chroot", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_CHROOT_X] = {"chroot", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_TRACER_E] = {"tracer", + EC_OTHER | EC_METAEVENT, + EF_NONE, + 3, + {{"id", PT_INT64, PF_DEC}, + {"tags", PT_CHARBUFARRAY, PF_NA}, + {"args", PT_CHARBUF_PAIR_ARRAY, PF_NA}}}, + [PPME_TRACER_X] = {"tracer", + EC_OTHER | EC_METAEVENT, + EF_NONE, + 3, + {{"id", PT_INT64, PF_DEC}, + {"tags", PT_CHARBUFARRAY, PF_NA}, + {"args", PT_CHARBUF_PAIR_ARRAY, PF_NA}}}, + [PPME_MESOS_E] = {"mesos", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET | EF_MODIFIES_STATE, + 1, + {{"json", PT_CHARBUF, PF_NA}}}, + [PPME_MESOS_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_CONTAINER_JSON_E] = + {"container", + EC_PROCESS | EC_METAEVENT, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"json", PT_CHARBUF, PF_NA}}}, /// TODO: do we need SKIPPARSERESET flag? + [PPME_CONTAINER_JSON_X] = {"NA", EC_UNKNOWN, EF_UNUSED | EF_OLD_VERSION, 0}, + [PPME_SYSCALL_SETSID_E] = {"setsid", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_SETSID_X] = {"setsid", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 1, + {{"res", PT_PID, PF_DEC}}}, + [PPME_SYSCALL_MKDIR_2_E] = + {"mkdir", EC_FILE | EC_SYSCALL, EF_NONE, 1, {{"mode", PT_UINT32, PF_HEX}}}, + [PPME_SYSCALL_MKDIR_2_X] = {"mkdir", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_RMDIR_2_E] = {"rmdir", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_RMDIR_2_X] = {"rmdir", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_NOTIFICATION_E] = {"notification", + EC_OTHER | EC_METAEVENT, + EF_SKIPPARSERESET, + 2, + { + {"id", PT_CHARBUF, PF_DEC}, + {"desc", PT_CHARBUF, PF_NA}, + }}, + [PPME_NOTIFICATION_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_EXECVE_17_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 0}, + [PPME_SYSCALL_EXECVE_17_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 17, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"env", PT_BYTEBUF, PF_NA}, + {"tty", PT_INT32, PF_DEC}}}, + [PPME_SYSCALL_UNSHARE_E] = {"unshare", + EC_PROCESS | EC_SYSCALL, + EF_NONE, + 1, + {{"flags", PT_FLAGS32, PF_HEX, clone_flags}}}, + [PPME_SYSCALL_UNSHARE_X] = + {"unshare", EC_PROCESS | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_INFRASTRUCTURE_EVENT_E] = {"infra", + EC_INTERNAL | EC_METAEVENT, + EF_SKIPPARSERESET, + 4, + {{"source", PT_CHARBUF, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"description", PT_CHARBUF, PF_NA}, + {"scope", PT_CHARBUF, PF_NA}}}, + [PPME_INFRASTRUCTURE_EVENT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_EXECVE_18_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 1, + {{"filename", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_EXECVE_18_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE | EF_OLD_VERSION, + 17, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"env", PT_BYTEBUF, PF_NA}, + {"tty", PT_INT32, PF_DEC}}}, + [PPME_PAGE_FAULT_E] = {"page_fault", + EC_OTHER | EC_TRACEPOINT, + EF_SKIPPARSERESET, + 3, + {{"addr", PT_UINT64, PF_HEX}, + {"ip", PT_UINT64, PF_HEX}, + {"error", PT_FLAGS32, PF_HEX, pf_flags}}}, + [PPME_PAGE_FAULT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_EXECVE_19_E] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 1, + {{"filename", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_EXECVE_19_X] = {"execve", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 28, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"env", PT_BYTEBUF, PF_NA}, + {"tty", PT_UINT32, PF_DEC}, + {"pgid", PT_PID, PF_DEC}, + {"loginuid", PT_UID, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, execve_flags}, + {"cap_inheritable", PT_UINT64, PF_HEX}, + {"cap_permitted", PT_UINT64, PF_HEX}, + {"cap_effective", PT_UINT64, PF_HEX}, + {"exe_ino", PT_UINT64, PF_DEC}, + {"exe_ino_ctime", PT_ABSTIME, PF_DEC}, + {"exe_ino_mtime", PT_ABSTIME, PF_DEC}, + {"uid", PT_UID, PF_DEC}, + {"trusted_exepath", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_SETPGID_E] = {"setpgid", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 2, + {{"pid", PT_PID, PF_DEC}, {"pgid", PT_PID, PF_DEC}}}, + [PPME_SYSCALL_SETPGID_X] = {"setpgid", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 1, + {{"res", PT_PID, PF_DEC}}}, + [PPME_SYSCALL_BPF_E] = {"bpf", + EC_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_OLD_VERSION, + 1, + {{"cmd", PT_INT64, PF_DEC}}}, + [PPME_SYSCALL_BPF_X] = + {"bpf", + EC_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_OLD_VERSION, + 1, + {{"res_or_fd", PT_DYN, PF_DEC, bpf_dynamic_param, PPM_BPF_IDX_MAX}}}, + [PPME_SYSCALL_SECCOMP_E] = {"seccomp", + EC_OTHER | EC_SYSCALL, + EF_NONE, + 2, + {{"op", PT_UINT64, PF_DEC}, {"flags", PT_UINT64, PF_HEX}}}, + [PPME_SYSCALL_SECCOMP_X] = + {"seccomp", EC_OTHER | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_UNLINK_2_E] = {"unlink", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_UNLINK_2_X] = {"unlink", + EC_FILE | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"path", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_UNLINKAT_2_E] = {"unlinkat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_UNLINKAT_2_X] = {"unlinkat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"flags", PT_FLAGS32, PF_HEX, unlinkat_flags}}}, + [PPME_SYSCALL_MKDIRAT_E] = {"mkdirat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MKDIRAT_X] = {"mkdirat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"path", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"mode", PT_UINT32, PF_HEX}}}, + [PPME_SYSCALL_OPENAT_2_E] = {"openat", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 4, + {{"dirfd", PT_FD, PF_DEC}, + {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(0)}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"mode", PT_UINT32, PF_OCT}}}, + [PPME_SYSCALL_OPENAT_2_X] = {"openat", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 7, + {{"fd", PT_FD, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"mode", PT_UINT32, PF_OCT}, + {"dev", PT_UINT32, PF_HEX}, + {"ino", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_LINK_2_E] = {"link", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_LINK_2_X] = {"link", + EC_FILE | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"oldpath", PT_FSPATH, PF_NA}, + {"newpath", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_LINKAT_2_E] = {"linkat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_LINKAT_2_X] = {"linkat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 6, + {{"res", PT_ERRNO, PF_DEC}, + {"olddir", PT_FD, PF_DEC}, + {"oldpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"newdir", PT_FD, PF_DEC}, + {"newpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(3)}, + {"flags", PT_FLAGS32, PF_HEX, linkat_flags}}}, + [PPME_SYSCALL_FCHMODAT_E] = {"fchmodat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_FCHMODAT_X] = {"fchmodat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"filename", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"mode", PT_MODE, PF_OCT, chmod_mode}}}, + [PPME_SYSCALL_CHMOD_E] = {"chmod", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_CHMOD_X] = {"chmod", + EC_FILE | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"filename", PT_FSPATH, PF_NA}, + {"mode", PT_MODE, PF_OCT, chmod_mode}}}, + [PPME_SYSCALL_FCHMOD_E] = {"fchmod", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_FCHMOD_X] = {"fchmod", + EC_FILE | EC_SYSCALL, + EF_USES_FD, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"mode", PT_MODE, PF_OCT, chmod_mode}}}, + [PPME_SYSCALL_RENAMEAT2_E] = {"renameat2", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_RENAMEAT2_X] = {"renameat2", + EC_FILE | EC_SYSCALL, + EF_NONE, + 6, + {{"res", PT_ERRNO, PF_DEC}, + {"olddirfd", PT_FD, PF_DEC}, + {"oldpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"newdirfd", PT_FD, PF_DEC}, + {"newpath", PT_FSRELPATH, PF_NA, DIRFD_PARAM(3)}, + {"flags", PT_FLAGS32, PF_HEX, renameat2_flags}}}, + [PPME_SYSCALL_USERFAULTFD_E] = {"userfaultfd", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_USERFAULTFD_X] = {"userfaultfd", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}}}, + [PPME_PLUGINEVENT_E] = {"pluginevent", + EC_OTHER | EC_PLUGIN, + EF_LARGE_PAYLOAD, + 2, + {{"plugin_id", PT_UINT32, PF_DEC}, + {"event_data", PT_BYTEBUF, PF_NA}}}, + [PPME_PLUGINEVENT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_CONTAINER_JSON_2_E] = + {"container", + EC_PROCESS | EC_METAEVENT, + EF_MODIFIES_STATE | EF_LARGE_PAYLOAD, + 1, + {{"json", PT_CHARBUF, PF_NA}}}, /// TODO: do we need SKIPPARSERESET flag? + [PPME_CONTAINER_JSON_2_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_OPENAT2_E] = {"openat2", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 5, + {{"dirfd", PT_FD, PF_DEC}, + {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"mode", PT_UINT32, PF_OCT}, + {"resolve", PT_FLAGS32, PF_HEX, openat2_flags}}}, + [PPME_SYSCALL_OPENAT2_X] = {"openat2", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 8, + {{"fd", PT_FD, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"name", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"mode", PT_UINT32, PF_OCT}, + {"resolve", PT_FLAGS32, PF_HEX, openat2_flags}, + {"dev", PT_UINT32, PF_HEX}, + {"ino", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_MPROTECT_E] = {"mprotect", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 3, + {{"addr", PT_UINT64, PF_HEX}, + {"length", PT_UINT64, PF_DEC}, + {"prot", PT_FLAGS32, PF_HEX, prot_flags}}}, + [PPME_SYSCALL_MPROTECT_X] = + {"mprotect", EC_MEMORY | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_EXECVEAT_E] = {"execveat", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 3, + {{"dirfd", PT_FD, PF_DEC}, + {"pathname", PT_FSRELPATH, PF_NA, DIRFD_PARAM(0)}, + {"flags", PT_FLAGS32, PF_HEX, execveat_flags}}}, + [PPME_SYSCALL_EXECVEAT_X] = {"execveat", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 28, + {{"res", PT_ERRNO, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_UINT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"env", PT_BYTEBUF, PF_NA}, + {"tty", PT_UINT32, PF_DEC}, + {"pgid", PT_PID, PF_DEC}, + {"loginuid", PT_UID, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, execve_flags}, + {"cap_inheritable", PT_UINT64, PF_HEX}, + {"cap_permitted", PT_UINT64, PF_HEX}, + {"cap_effective", PT_UINT64, PF_HEX}, + {"exe_ino", PT_UINT64, PF_DEC}, + {"exe_ino_ctime", PT_ABSTIME, PF_DEC}, + {"exe_ino_mtime", PT_ABSTIME, PF_DEC}, + {"uid", PT_UID, PF_DEC}, + {"trusted_exepath", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_COPY_FILE_RANGE_E] = {"copy_file_range", + EC_FILE | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD | EF_WRITES_TO_FD, + 3, + {{"fdin", PT_FD, PF_DEC}, + {"offin", PT_UINT64, PF_DEC}, + {"len", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_COPY_FILE_RANGE_X] = {"copy_file_range", + EC_FILE | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD | EF_WRITES_TO_FD, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"fdout", PT_FD, PF_DEC}, + {"offout", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_CLONE3_E] = {"clone3", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_CLONE3_X] = {"clone3", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 21, + {{"res", PT_PID, PF_DEC}, + {"exe", PT_CHARBUF, PF_NA}, + {"args", PT_BYTEBUF, PF_NA}, + {"tid", PT_PID, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"ptid", PT_PID, PF_DEC}, + {"cwd", PT_CHARBUF, PF_NA}, + {"fdlimit", PT_INT64, PF_DEC}, + {"pgft_maj", PT_UINT64, PF_DEC}, + {"pgft_min", PT_UINT64, PF_DEC}, + {"vm_size", PT_UINT32, PF_DEC}, + {"vm_rss", PT_UINT32, PF_DEC}, + {"vm_swap", PT_UINT32, PF_DEC}, + {"comm", PT_CHARBUF, PF_NA}, + {"cgroups", PT_BYTEBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, clone_flags}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}, + {"vtid", PT_PID, PF_DEC}, + {"vpid", PT_PID, PF_DEC}, + {"pidns_init_start_ts", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = {"open_by_handle_at", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = {"open_by_handle_at", + EC_FILE | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 6, + {{"fd", PT_FD, PF_DEC}, + {"mountfd", PT_FD, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}, + {"path", PT_FSPATH, PF_NA}, + {"dev", PT_UINT32, PF_HEX}, + {"ino", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_IO_URING_SETUP_E] = {"io_uring_setup", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_IO_URING_SETUP_X] = + {"io_uring_setup", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 8, + {{"res", PT_ERRNO, PF_DEC}, + {"entries", PT_UINT32, PF_DEC}, + {"sq_entries", PT_UINT32, PF_DEC}, + {"cq_entries", PT_UINT32, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, io_uring_setup_flags}, + {"sq_thread_cpu", PT_UINT32, PF_DEC}, + {"sq_thread_idle", PT_UINT32, PF_DEC}, + {"features", PT_FLAGS32, PF_HEX, io_uring_setup_feats}}}, + [PPME_SYSCALL_IO_URING_ENTER_E] = {"io_uring_enter", EC_IO_OTHER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_IO_URING_ENTER_X] = {"io_uring_enter", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD, + 6, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"to_submit", PT_UINT32, PF_DEC}, + {"min_complete", PT_UINT32, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, io_uring_enter_flags}, + {"sig", PT_SIGSET, PF_DEC}}}, + [PPME_SYSCALL_IO_URING_REGISTER_E] = {"io_uring_register", + EC_IO_OTHER | EC_SYSCALL, + EF_NONE, + 0}, + [PPME_SYSCALL_IO_URING_REGISTER_X] = + {"io_uring_register", + EC_IO_OTHER | EC_SYSCALL, + EF_USES_FD, + 5, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"opcode", PT_ENUMFLAGS16, PF_DEC, io_uring_register_opcodes}, + {"arg", PT_UINT64, PF_HEX}, + {"nr_args", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_MLOCK_E] = {"mlock", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MLOCK_X] = {"mlock", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"addr", PT_UINT64, PF_HEX}, + {"len", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_MUNLOCK_E] = {"munlock", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MUNLOCK_X] = {"munlock", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"addr", PT_UINT64, PF_HEX}, + {"len", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_MLOCKALL_E] = {"mlockall", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MLOCKALL_X] = {"mlockall", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 2, + {{"res", PT_ERRNO, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, mlockall_flags}}}, + [PPME_SYSCALL_MUNLOCKALL_E] = {"munlockall", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MUNLOCKALL_X] = + {"munlockall", EC_MEMORY | EC_SYSCALL, EF_NONE, 1, {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_CAPSET_E] = {"capset", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_CAPSET_X] = {"capset", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"cap_inheritable", PT_UINT64, PF_HEX}, + {"cap_permitted", PT_UINT64, PF_HEX}, + {"cap_effective", PT_UINT64, PF_HEX}}}, + [PPME_USER_ADDED_E] = {"useradded", + EC_PROCESS | EC_METAEVENT, + EF_MODIFIES_STATE, + 6, + {{"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"home", PT_CHARBUF, PF_NA}, + {"shell", PT_CHARBUF, PF_NA}, + {"container_id", PT_CHARBUF, PF_NA}}}, + [PPME_USER_ADDED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_USER_DELETED_E] = {"userdeleted", + EC_PROCESS | EC_METAEVENT, + EF_MODIFIES_STATE, + 6, + {{"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"home", PT_CHARBUF, PF_NA}, + {"shell", PT_CHARBUF, PF_NA}, + {"container_id", PT_CHARBUF, PF_NA}}}, + [PPME_USER_DELETED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_GROUP_ADDED_E] = {"groupadded", + EC_PROCESS | EC_METAEVENT, + EF_MODIFIES_STATE, + 3, + {{"gid", PT_UINT32, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"container_id", PT_CHARBUF, PF_NA}}}, + [PPME_GROUP_ADDED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_GROUP_DELETED_E] = {"groupdeleted", + EC_PROCESS | EC_METAEVENT, + EF_MODIFIES_STATE, + 3, + {{"gid", PT_UINT32, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"container_id", PT_CHARBUF, PF_NA}}}, + [PPME_GROUP_DELETED_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_DUP2_E] = {"dup2", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_DUP2_X] = {"dup2", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, + 3, + {{"res", PT_FD, PF_DEC}, + {"oldfd", PT_FD, PF_DEC}, + {"newfd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_DUP3_E] = {"dup3", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_DUP3_X] = {"dup3", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, + 4, + {{"res", PT_FD, PF_DEC}, + {"oldfd", PT_FD, PF_DEC}, + {"newfd", PT_FD, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}}}, + [PPME_SYSCALL_DUP_1_E] = {"dup", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, + 1, + {{"fd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_DUP_1_X] = {"dup", + EC_IO_OTHER | EC_SYSCALL, + EF_CREATES_FD | EF_USES_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_FD, PF_DEC}, {"oldfd", PT_FD, PF_DEC}}}, + [PPME_SYSCALL_BPF_2_E] = + {"bpf", EC_OTHER | EC_SYSCALL, EF_CREATES_FD, 1, {{"cmd", PT_INT64, PF_DEC}}}, + [PPME_SYSCALL_BPF_2_X] = {"bpf", + EC_OTHER | EC_SYSCALL, + EF_CREATES_FD, + 2, + {{"fd", PT_FD, PF_DEC}, + {"cmd", PT_ENUMFLAGS32, PF_DEC, bpf_commands}}}, + [PPME_SYSCALL_MLOCK2_E] = {"mlock2", EC_MEMORY | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MLOCK2_X] = {"mlock2", + EC_MEMORY | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"addr", PT_UINT64, PF_HEX}, + {"len", PT_UINT64, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, mlock2_flags}}}, + [PPME_SYSCALL_FSCONFIG_E] = {"fsconfig", EC_SYSTEM | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_FSCONFIG_X] = {"fsconfig", + EC_SYSTEM | EC_SYSCALL, + EF_USES_FD, + 7, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"cmd", PT_ENUMFLAGS32, PF_DEC, fsconfig_cmds}, + {"key", PT_CHARBUF, PF_NA}, + {"value_bytebuf", PT_BYTEBUF, PF_NA}, + {"value_charbuf", PT_CHARBUF, PF_NA}, + {"aux", PT_INT32, PF_DEC}}}, + [PPME_SYSCALL_EPOLL_CREATE_E] = {"epoll_create", + EC_WAIT | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"size", PT_INT32, PF_DEC}}}, + [PPME_SYSCALL_EPOLL_CREATE_X] = {"epoll_create", + EC_WAIT | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_EPOLL_CREATE1_E] = {"epoll_create1", + EC_WAIT | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"flags", PT_FLAGS32, PF_HEX, epoll_create1_flags}}}, + [PPME_SYSCALL_EPOLL_CREATE1_X] = {"epoll_create1", + EC_WAIT | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"res", PT_ERRNO, PF_DEC}}}, + [PPME_SYSCALL_CHOWN_E] = {"chown", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_CHOWN_X] = {"chown", + EC_FILE | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"path", PT_FSPATH, PF_NA}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_LCHOWN_E] = {"lchown", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_LCHOWN_X] = {"lchown", + EC_FILE | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"path", PT_FSPATH, PF_NA}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_FCHOWN_E] = {"fchown", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_FCHOWN_X] = {"fchown", + EC_FILE | EC_SYSCALL, + EF_USES_FD, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_FCHOWNAT_E] = {"fchownat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_FCHOWNAT_X] = {"fchownat", + EC_FILE | EC_SYSCALL, + EF_NONE, + 6, + {{"res", PT_ERRNO, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"pathname", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"uid", PT_UINT32, PF_DEC}, + {"gid", PT_UINT32, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, fchownat_flags}}}, + [PPME_SYSCALL_UMOUNT_1_E] = {"umount", EC_FILE | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_UMOUNT_1_X] = {"umount", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA}}}, + [PPME_SOCKET_ACCEPT4_6_E] = {"accept4", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"flags", PT_INT32, PF_HEX}}}, + [PPME_SOCKET_ACCEPT4_6_X] = {"accept4", + EC_NET | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 5, + {{"fd", PT_FD, PF_DEC}, + {"tuple", PT_SOCKTUPLE, PF_NA}, + {"queuepct", PT_UINT8, PF_DEC}, + {"queuelen", PT_UINT32, PF_DEC}, + {"queuemax", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_UMOUNT2_E] = {"umount2", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE, + 1, + {{"flags", PT_FLAGS32, PF_HEX, umount_flags}}}, + [PPME_SYSCALL_UMOUNT2_X] = {"umount2", + EC_FILE | EC_SYSCALL, + EF_MODIFIES_STATE, + 2, + {{"res", PT_ERRNO, PF_DEC}, {"name", PT_FSPATH, PF_NA}}}, + [PPME_SYSCALL_PIPE2_E] = {"pipe2", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_PIPE2_X] = {"pipe2", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 5, + {{"res", PT_ERRNO, PF_DEC}, + {"fd1", PT_FD, PF_DEC}, + {"fd2", PT_FD, PF_DEC}, + {"ino", PT_UINT64, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, file_flags}}}, + [PPME_SYSCALL_INOTIFY_INIT1_E] = {"inotify_init1", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_INOTIFY_INIT1_X] = {"inotify_init1", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_FD, PF_DEC}, + {"flags", PT_FLAGS16, PF_HEX, file_flags}}}, + [PPME_SYSCALL_EVENTFD2_E] = {"eventfd2", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 1, + {{"initval", PT_UINT64, PF_DEC}}}, + [PPME_SYSCALL_EVENTFD2_X] = {"eventfd2", + EC_IPC | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_FD, PF_DEC}, + {"flags", PT_FLAGS16, PF_HEX, file_flags}}}, + [PPME_SYSCALL_SIGNALFD4_E] = {"signalfd4", + EC_SIGNAL | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"fd", PT_FD, PF_DEC}, {"mask", PT_UINT32, PF_HEX}}}, + [PPME_SYSCALL_SIGNALFD4_X] = {"signalfd4", + EC_SIGNAL | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 2, + {{"res", PT_FD, PF_DEC}, + {"flags", PT_FLAGS16, PF_HEX, file_flags}}}, + [PPME_SYSCALL_PRCTL_E] = {"prctl", EC_PROCESS | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_PRCTL_X] = {"prctl", + EC_PROCESS | EC_SYSCALL, + EF_MODIFIES_STATE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"option", PT_ENUMFLAGS32, PF_DEC, prctl_options}, + {"arg2_str", PT_CHARBUF, PF_NA}, + {"arg2_int", PT_INT64, PF_DEC}}}, + [PPME_ASYNCEVENT_E] = {"asyncevent", + EC_OTHER | EC_METAEVENT, + EF_LARGE_PAYLOAD, + 3, + {{"plugin_id", PT_UINT32, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_ASYNCEVENT_X] = {"NA", EC_UNKNOWN, EF_UNUSED, 0}, + [PPME_SYSCALL_MEMFD_CREATE_E] = {"memfd_create", + EC_MEMORY | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_MEMFD_CREATE_X] = {"memfd_create", + EC_MEMORY | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 3, + {{"fd", PT_FD, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, memfd_create_flags}}}, + [PPME_SYSCALL_PIDFD_GETFD_E] = {"pidfd_getfd", + EC_PROCESS | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_PIDFD_GETFD_X] = {"pidfd_getfd", + EC_PROCESS | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 4, + {{"fd", PT_FD, PF_DEC}, + {"pid_fd", PT_FD, PF_DEC}, + {"target_fd", PT_FD, PF_DEC}, + {"flags", PT_UINT32, PF_HEX}}}, + [PPME_SYSCALL_PIDFD_OPEN_E] = {"pidfd_open", + EC_PROCESS | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 0}, + [PPME_SYSCALL_PIDFD_OPEN_X] = {"pidfd_open", + EC_PROCESS | EC_SYSCALL, + EF_CREATES_FD | EF_MODIFIES_STATE, + 3, + {{"fd", PT_FD, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"flags", PT_FLAGS32, PF_HEX, pidfd_open_flags}}}, + [PPME_SYSCALL_INIT_MODULE_E] = {"init_module", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_INIT_MODULE_X] = {"init_module", + EC_OTHER | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"img", PT_BYTEBUF, PF_NA}, + {"length", PT_UINT64, PF_DEC}, + {"uargs", PT_CHARBUF, PF_NA}}}, + [PPME_SYSCALL_FINIT_MODULE_E] = {"finit_module", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_FINIT_MODULE_X] = {"finit_module", + EC_OTHER | EC_SYSCALL, + EF_USES_FD | EF_READS_FROM_FD, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"fd", PT_FD, PF_DEC}, + {"uargs", PT_CHARBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, finit_module_flags}}}, + [PPME_SYSCALL_MKNOD_E] = {"mknod", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MKNOD_X] = {"mknod", + EC_OTHER | EC_SYSCALL, + EF_NONE, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"path", PT_FSPATH, PF_NA}, + {"mode", PT_MODE, PF_OCT, mknod_mode}, + {"dev", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_MKNODAT_E] = {"mknodat", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_MKNODAT_X] = {"mknodat", + EC_OTHER | EC_SYSCALL, + EF_USES_FD, + 5, + {{"res", PT_ERRNO, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"path", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"mode", PT_MODE, PF_OCT, mknod_mode}, + {"dev", PT_UINT32, PF_DEC}}}, + [PPME_SYSCALL_NEWFSTATAT_E] = {"newfstatat", EC_FILE | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_NEWFSTATAT_X] = {"newfstatat", + EC_FILE | EC_SYSCALL, + EF_USES_FD, + 4, + {{"res", PT_ERRNO, PF_DEC}, + {"dirfd", PT_FD, PF_DEC}, + {"path", PT_FSRELPATH, PF_NA, DIRFD_PARAM(1)}, + {"flags", PT_FLAGS32, PF_HEX, newfstatat_flags}}}, + [PPME_SYSCALL_PROCESS_VM_READV_E] = {"process_vm_readv", EC_SYSCALL | EC_IPC, EF_NONE, 0}, + [PPME_SYSCALL_PROCESS_VM_READV_X] = {"process_vm_readv", + EC_SYSCALL | EC_IPC, + EF_NONE, + 3, + {{"res", PT_INT64, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = {"process_vm_writev", EC_SYSCALL | EC_IPC, EF_NONE, 0}, + [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = {"process_vm_writev", + EC_SYSCALL | EC_IPC, + EF_NONE, + 3, + {{"res", PT_INT64, PF_DEC}, + {"pid", PT_PID, PF_DEC}, + {"data", PT_BYTEBUF, PF_NA}}}, + [PPME_SYSCALL_DELETE_MODULE_E] = {"delete_module", EC_OTHER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_DELETE_MODULE_X] = {"delete_module", + EC_OTHER | EC_SYSCALL, + EF_NONE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"name", PT_CHARBUF, PF_NA}, + {"flags", PT_FLAGS32, PF_HEX, delete_module_flags}}}, + [PPME_SYSCALL_SETREUID_E] = {"setreuid", EC_USER | EC_SYSCALL, EF_MODIFIES_STATE, 0}, + [PPME_SYSCALL_SETREUID_X] = {"setreuid", + EC_USER | EC_SYSCALL, + EF_MODIFIES_STATE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"ruid", PT_UID, PF_DEC}, + {"euid", PT_UID, PF_DEC}}}, + [PPME_SYSCALL_SETREGID_E] = {"setregid", EC_USER | EC_SYSCALL, EF_NONE, 0}, + [PPME_SYSCALL_SETREGID_X] = {"setregid", + EC_USER | EC_SYSCALL, + EF_MODIFIES_STATE, + 3, + {{"res", PT_ERRNO, PF_DEC}, + {"rgid", PT_UID, PF_DEC}, + {"egid", PT_UID, PF_DEC}}}, }; #pragma GCC diagnostic pop // We don't need this check in kmod (this source file is included during kmod compilation!) -// This also avoids weird situation where the _Static_assert is not available in some very old compilers, -// thus breaking the kmod build. +// This also avoids weird situation where the _Static_assert is not available in some very old +// compilers, thus breaking the kmod build. #ifndef __KERNEL__ // This code is compiled on windows and osx too! // Make sure to be on gcc or that the c standard is >= c11 #if defined __GNUC__ || __STDC_VERSION__ >= 201112L -_Static_assert(sizeof(g_event_info) / sizeof(*g_event_info) == PPM_EVENT_MAX, "Missing event entries in event table."); +_Static_assert(sizeof(g_event_info) / sizeof(*g_event_info) == PPM_EVENT_MAX, + "Missing event entries in event table."); #endif #endif diff --git a/driver/feature_gates.h b/driver/feature_gates.h index e3a6fc842d..2f1a1dfd06 100644 --- a/driver/feature_gates.h +++ b/driver/feature_gates.h @@ -12,92 +12,92 @@ or GPL2.txt for full copies of the license. #define FEATURE_GATES_H /* FEATURE GATES: - * - * These feature gates are used by: + * + * These feature gates are used by: * - kernel module * - BPF probe * - userspace * - modern BPF probe - * to compile out some features. The userspace is in charge of + * to compile out some features. The userspace is in charge of * filling the BPF maps that's why it also needs these macros. - * - * This file is included by the 2 drivers and the userspace so + * + * This file is included by the 2 drivers and the userspace so * it could be the right place to define these feature gates. */ - #ifdef __KERNEL__ /* Kernel module - BPF probe */ #include "ppm_version.h" /////////////////////////////// -// CAPTURE_SCHED_PROC_FORK +// CAPTURE_SCHED_PROC_FORK /////////////////////////////// /* In some architectures we are not able to catch the `clone exit child - * event` from the `sys_exit` tracepoint. This is because there is no - * default behavior among different architectures... you can find more - * info here: + * event` from the `sys_exit` tracepoint. This is because there is no + * default behavior among different architectures... you can find more + * info here: * https://www.spinics.net/lists/linux-trace/msg01001.html - * + * * Anyway, to not lose this event, we need to instrument a new kernel tracepoint: - * + * * - `sched_process_fork`: allows us to catch every new process that is spawned. - * + * * In this way we can detect when a child is spawned and we can send to userspace * a `PPME_SYSCALL_CLONE_X` event as we do with the `sys_exit` tracepoint. - * + * * Please note: in BPF we need to use raw_tracepoint programs to access * the raw tracepoint arguments! This is essential for `sched_process_fork` - * tracepoint since the only way we have to access the child task struct - * is through its raw arguments. All the architectures that need this - * patch can use our BPF probe only with kernel versions greater or equal - * than `4.17`, since `BPF_PROG_TYPE_RAW_TRACEPOINT` programs have been + * tracepoint since the only way we have to access the child task struct + * is through its raw arguments. All the architectures that need this + * patch can use our BPF probe only with kernel versions greater or equal + * than `4.17`, since `BPF_PROG_TYPE_RAW_TRACEPOINT` programs have been * introduced in this kernel release: * https://github.com/torvalds/linux/commit/c4f6699dfcb8558d138fe838f741b2c10f416cf9 - * - * If you run old kernels, you can use the kernel module which requires + * + * If you run old kernels, you can use the kernel module which requires * kernel versions greater or equal than `2.6`, since this tracepoint has * been introduced in the following kernel release: * https://github.com/torvalds/linux/commit/0a16b6075843325dc402edf80c1662838b929aff */ -#if defined(CONFIG_ARM64) || defined(CONFIG_S390) || defined(CONFIG_RISCV) || defined(CONFIG_LOONGARCH) - #define CAPTURE_SCHED_PROC_FORK +#if defined(CONFIG_ARM64) || defined(CONFIG_S390) || defined(CONFIG_RISCV) || \ + defined(CONFIG_LOONGARCH) +#define CAPTURE_SCHED_PROC_FORK #endif /////////////////////////////// -// CAPTURE_SCHED_PROC_EXEC +// CAPTURE_SCHED_PROC_EXEC /////////////////////////////// -/* In some architectures we are not able to catch the `execve exit event` - * from the `sys_exit` tracepoint. This is because there is no - * default behavior among different architectures... you can find more - * info here: +/* In some architectures we are not able to catch the `execve exit event` + * from the `sys_exit` tracepoint. This is because there is no + * default behavior among different architectures... you can find more + * info here: * https://www.spinics.net/lists/linux-trace/msg01001.html - * + * * Anyway, to not lose this event, we need to instrument a new kernel tracepoint: - * + * * - `sched_process_exec`: allows us to catch every process that correctly performs * an `execve` call. - * + * * In this way we can send to userspace a `PPME_SYSCALL_EXECVE_X` event * as we do with the `sys_exit` tracepoint. - * - * All the architectures that need this patch can use our BPF probe with all + * + * All the architectures that need this patch can use our BPF probe with all * supported kernel versions (so >= `4.14`), since `BPF_PROG_TYPE_RAW_TRACEPOINT` are * not required in this case. - * - * If you run old kernels, you can use the kernel module which requires + * + * If you run old kernels, you can use the kernel module which requires * kernel versions greater or equal than `3.4`, since this tracepoint has * been introduced in the following kernel release: * https://github.com/torvalds/linux/commit/4ff16c25e2cc48cbe6956e356c38a25ac063a64d */ #if defined(CONFIG_ARM64) - #define CAPTURE_SCHED_PROC_EXEC +#define CAPTURE_SCHED_PROC_EXEC #endif /////////////////////////////// -// CAPTURE_64BIT_ARGS_SINGLE_REGISTER +// CAPTURE_64BIT_ARGS_SINGLE_REGISTER /////////////////////////////// /* This is described in syscall(2). Some syscalls take 64-bit arguments. On @@ -108,56 +108,57 @@ or GPL2.txt for full copies of the license. * we can handle the rest when we port those. */ #ifdef CONFIG_64BIT - #define CAPTURE_64BIT_ARGS_SINGLE_REGISTER +#define CAPTURE_64BIT_ARGS_SINGLE_REGISTER #endif /* CONFIG_64BIT */ /////////////////////////////// -// CAPTURE_CONTEXT_SWITCHES +// CAPTURE_CONTEXT_SWITCHES /////////////////////////////// #define CAPTURE_CONTEXT_SWITCHES /////////////////////////////// -// CAPTURE_SIGNAL_DELIVERIES +// CAPTURE_SIGNAL_DELIVERIES /////////////////////////////// -#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 32)) - #define CAPTURE_SIGNAL_DELIVERIES +#if(LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 32)) +#define CAPTURE_SIGNAL_DELIVERIES #endif /////////////////////////////// -// CAPTURE_PAGE_FAULTS +// CAPTURE_PAGE_FAULTS /////////////////////////////// -#if (LINUX_VERSION_CODE > KERNEL_VERSION(3, 12, 0)) && defined(CONFIG_X86) - #define CAPTURE_PAGE_FAULTS +#if(LINUX_VERSION_CODE > KERNEL_VERSION(3, 12, 0)) && defined(CONFIG_X86) +#define CAPTURE_PAGE_FAULTS #endif /////////////////////////////// // USE_BPF_PROBE_KERNEL_USER_VARIANTS /////////////////////////////// -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(5,5,0)) || \ - ((PPM_RHEL_RELEASE_CODE > 0) && (PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 5))) - #define USE_BPF_PROBE_KERNEL_USER_VARIANTS +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(5, 5, 0)) || \ + ((PPM_RHEL_RELEASE_CODE > 0) && (PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(8, 5))) +#define USE_BPF_PROBE_KERNEL_USER_VARIANTS #endif #elif defined(__USE_VMLINUX__) /* modern BPF probe */ /////////////////////////////// -// CAPTURE_SCHED_PROC_EXEC +// CAPTURE_SCHED_PROC_EXEC /////////////////////////////// #if defined(__TARGET_ARCH_arm64) - #define CAPTURE_SCHED_PROC_EXEC +#define CAPTURE_SCHED_PROC_EXEC #endif /////////////////////////////// -// CAPTURE_SCHED_PROC_FORK +// CAPTURE_SCHED_PROC_FORK /////////////////////////////// -#if defined(__TARGET_ARCH_arm64) || defined(__TARGET_ARCH_s390) || defined(__TARGET_ARCH_riscv) || defined(__TARGET_ARCH_loongarch64) - #define CAPTURE_SCHED_PROC_FORK +#if defined(__TARGET_ARCH_arm64) || defined(__TARGET_ARCH_s390) || defined(__TARGET_ARCH_riscv) || \ + defined(__TARGET_ARCH_loongarch64) +#define CAPTURE_SCHED_PROC_FORK #endif /////////////////////////////// @@ -165,7 +166,7 @@ or GPL2.txt for full copies of the license. /////////////////////////////// #if defined(__TARGET_ARCH_x86) - #define CAPTURE_PAGE_FAULTS +#define CAPTURE_PAGE_FAULTS #endif #else /* Userspace */ @@ -175,47 +176,47 @@ or GPL2.txt for full copies of the license. */ /////////////////////////////// -// CAPTURE_64BIT_ARGS_SINGLE_REGISTER +// CAPTURE_64BIT_ARGS_SINGLE_REGISTER /////////////////////////////// #if defined(__x86_64__) || defined(__aarch64__) || defined(__loongarch64) - #define CAPTURE_64BIT_ARGS_SINGLE_REGISTER -#endif +#define CAPTURE_64BIT_ARGS_SINGLE_REGISTER +#endif /////////////////////////////// -// CAPTURE_CONTEXT_SWITCHES +// CAPTURE_CONTEXT_SWITCHES /////////////////////////////// #define CAPTURE_CONTEXT_SWITCHES /////////////////////////////// -// CAPTURE_SIGNAL_DELIVERIES +// CAPTURE_SIGNAL_DELIVERIES /////////////////////////////// #define CAPTURE_SIGNAL_DELIVERIES /////////////////////////////// -// CAPTURE_PAGE_FAULTS +// CAPTURE_PAGE_FAULTS /////////////////////////////// #ifdef __x86_64__ - #define CAPTURE_PAGE_FAULTS +#define CAPTURE_PAGE_FAULTS #endif /* __x86_64__ */ /////////////////////////////// -// CAPTURE_SCHED_PROC_FORK +// CAPTURE_SCHED_PROC_FORK /////////////////////////////// #if defined(__aarch64__) || defined(__s390x__) || defined(__riscv) || defined(__loongarch64) - #define CAPTURE_SCHED_PROC_FORK +#define CAPTURE_SCHED_PROC_FORK #endif /////////////////////////////// -// CAPTURE_SCHED_PROC_EXEC +// CAPTURE_SCHED_PROC_EXEC /////////////////////////////// #if defined(__aarch64__) - #define CAPTURE_SCHED_PROC_EXEC +#define CAPTURE_SCHED_PROC_EXEC #endif #endif /* __KERNEL__ */ diff --git a/driver/fillers_table.c b/driver/fillers_table.c index af39dae9ea..65b0d90926 100644 --- a/driver/fillers_table.c +++ b/driver/fillers_table.c @@ -25,346 +25,370 @@ or GPL2.txt for full copies of the license. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-field-initializers" const struct ppm_event_entry g_ppm_events[PPM_EVENT_MAX] = { - [PPME_GENERIC_E] = {FILLER_REF(sys_generic)}, - [PPME_GENERIC_X] = {FILLER_REF(sys_generic)}, - [PPME_SYSCALL_OPEN_E] = {FILLER_REF(sys_open_e)}, - [PPME_SYSCALL_OPEN_X] = {FILLER_REF(sys_open_x)}, - [PPME_SYSCALL_CLOSE_E] = {FILLER_REF(sys_close_e)}, - [PPME_SYSCALL_CLOSE_X] = {FILLER_REF(sys_close_x)}, - [PPME_SYSCALL_READ_E] = {FILLER_REF(sys_read_e)}, - [PPME_SYSCALL_READ_X] = {FILLER_REF(sys_read_x)}, - [PPME_SYSCALL_WRITE_E] = {FILLER_REF(sys_write_e)}, - [PPME_SYSCALL_WRITE_X] = {FILLER_REF(sys_write_x)}, - [PPME_PROCEXIT_1_E] = {FILLER_REF(sys_procexit_e)}, - [PPME_SOCKET_SOCKET_E] = {FILLER_REF(sys_autofill), 3, APT_SOCK, {{0}, {1}, {2} } }, - [PPME_SOCKET_SOCKET_X] = {FILLER_REF(sys_socket_x)}, - [PPME_SOCKET_BIND_E] = {FILLER_REF(sys_socket_bind_e)}, - [PPME_SOCKET_BIND_X] = {FILLER_REF(sys_socket_bind_x)}, - [PPME_SOCKET_CONNECT_E] = {FILLER_REF(sys_connect_e)}, - [PPME_SOCKET_CONNECT_X] = {FILLER_REF(sys_connect_x)}, - [PPME_SOCKET_LISTEN_E] = {FILLER_REF(sys_listen_e)}, - [PPME_SOCKET_LISTEN_X] = {FILLER_REF(sys_single_x)}, - [PPME_SOCKET_SEND_E] = {FILLER_REF(sys_send_e)}, - [PPME_SOCKET_SEND_X] = {FILLER_REF(sys_send_x)}, - [PPME_SOCKET_SENDTO_E] = {FILLER_REF(sys_sendto_e)}, - [PPME_SOCKET_SENDTO_X] = {FILLER_REF(sys_send_x)}, - [PPME_SOCKET_RECV_E] = {FILLER_REF(sys_autofill), 2, APT_SOCK, {{0}, {2} } }, - [PPME_SOCKET_RECV_X] = {FILLER_REF(sys_recv_x)}, - [PPME_SOCKET_RECVFROM_E] = {FILLER_REF(sys_recvfrom_e)}, - [PPME_SOCKET_RECVFROM_X] = {FILLER_REF(sys_recvfrom_x)}, - [PPME_SOCKET_SHUTDOWN_E] = {FILLER_REF(sys_shutdown_e)}, - [PPME_SOCKET_SHUTDOWN_X] = {FILLER_REF(sys_single_x)}, - [PPME_SOCKET_GETSOCKNAME_E] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_GETSOCKNAME_X] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_GETPEERNAME_E] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_GETPEERNAME_X] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_SOCKETPAIR_E] = {FILLER_REF(sys_autofill), 3, APT_SOCK, {{0}, {1}, {2} } }, - [PPME_SOCKET_SOCKETPAIR_X] = {FILLER_REF(sys_socketpair_x)}, - [PPME_SOCKET_SETSOCKOPT_E] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_SETSOCKOPT_X] = {FILLER_REF(sys_setsockopt_x)}, - [PPME_SOCKET_GETSOCKOPT_E] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_GETSOCKOPT_X] = {FILLER_REF(sys_getsockopt_x)}, - [PPME_SOCKET_SENDMSG_E] = {FILLER_REF(sys_sendmsg_e)}, - [PPME_SOCKET_SENDMSG_X] = {FILLER_REF(sys_sendmsg_x)}, - [PPME_SOCKET_SENDMMSG_E] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_SENDMMSG_X] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_RECVMSG_E] = {FILLER_REF(sys_recvmsg_e)}, - [PPME_SOCKET_RECVMSG_X] = {FILLER_REF(sys_recvmsg_x)}, - [PPME_SOCKET_RECVMMSG_E] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_RECVMMSG_X] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CREAT_E] = {FILLER_REF(sys_creat_e)}, - [PPME_SYSCALL_CREAT_X] = {FILLER_REF(sys_creat_x)}, - [PPME_SYSCALL_PIPE_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_PIPE_X] = {FILLER_REF(sys_pipe_x)}, - [PPME_SYSCALL_EVENTFD_E] = {FILLER_REF(sys_eventfd_e)}, - [PPME_SYSCALL_EVENTFD_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_FUTEX_E] = {FILLER_REF(sys_futex_e)}, - [PPME_SYSCALL_FUTEX_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_STAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_STAT_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_LSTAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_LSTAT_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_FSTAT_E] = {FILLER_REF(sys_fstat_e)}, - [PPME_SYSCALL_FSTAT_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_STAT64_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_STAT64_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_LSTAT64_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_LSTAT64_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_FSTAT64_E] = {FILLER_REF(sys_single)}, - [PPME_SYSCALL_FSTAT64_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_EPOLLWAIT_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{2} } }, - [PPME_SYSCALL_EPOLLWAIT_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_POLL_E] = {FILLER_REF(sys_poll_e)}, - [PPME_SYSCALL_POLL_X] = {FILLER_REF(sys_poll_x)}, - [PPME_SYSCALL_SELECT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_SELECT_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_NEWSELECT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_NEWSELECT_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_LSEEK_E] = {FILLER_REF(sys_lseek_e)}, - [PPME_SYSCALL_LSEEK_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_LLSEEK_E] = {FILLER_REF(sys_llseek_e)}, - [PPME_SYSCALL_LLSEEK_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_GETCWD_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_GETCWD_X] = {FILLER_REF(sys_getcwd_x)}, - [PPME_SYSCALL_CHDIR_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CHDIR_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_FCHDIR_E] = {FILLER_REF(sys_fchdir_e)}, - [PPME_SYSCALL_FCHDIR_X] = {FILLER_REF(sys_fchdir_x)}, - [PPME_SYSCALL_UNLINK_E] = {FILLER_REF(sys_single)}, - [PPME_SYSCALL_UNLINK_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_UNLINKAT_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1} } }, - [PPME_SYSCALL_UNLINKAT_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_PREAD_E] = {FILLER_REF(sys_pread64_e)}, - [PPME_SYSCALL_PREAD_X] = {FILLER_REF(sys_read_x)}, - [PPME_SYSCALL_PWRITE_E] = {FILLER_REF(sys_pwrite64_e)}, - [PPME_SYSCALL_PWRITE_X] = {FILLER_REF(sys_write_x)}, - [PPME_SYSCALL_READV_E] = {FILLER_REF(sys_readv_e)}, - [PPME_SYSCALL_READV_X] = {FILLER_REF(sys_readv_preadv_x)}, - [PPME_SYSCALL_WRITEV_E] = {FILLER_REF(sys_writev_e)}, - [PPME_SYSCALL_WRITEV_X] = {FILLER_REF(sys_writev_pwritev_x)}, - [PPME_SYSCALL_PREADV_E] = {FILLER_REF(sys_preadv_e)}, - [PPME_SYSCALL_PREADV_X] = {FILLER_REF(sys_readv_preadv_x)}, - [PPME_SYSCALL_PWRITEV_E] = {FILLER_REF(sys_pwritev_e)}, - [PPME_SYSCALL_PWRITEV_X] = {FILLER_REF(sys_writev_pwritev_x)}, - [PPME_SYSCALL_DUP_1_E] = {FILLER_REF(sys_dup_e)}, - [PPME_SYSCALL_DUP_1_X] = {FILLER_REF(sys_dup_x)}, - [PPME_SYSCALL_DUP2_E] = {FILLER_REF(sys_dup2_e)}, - [PPME_SYSCALL_DUP2_X] = {FILLER_REF(sys_dup2_x)}, - [PPME_SYSCALL_DUP3_E] = {FILLER_REF(sys_dup3_e)}, - [PPME_SYSCALL_DUP3_X] = {FILLER_REF(sys_dup3_x)}, - [PPME_SYSCALL_SIGNALFD_E] = {FILLER_REF(sys_signalfd_e)}, - [PPME_SYSCALL_SIGNALFD_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_KILL_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1} } }, - [PPME_SYSCALL_KILL_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_TKILL_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1} } }, - [PPME_SYSCALL_TKILL_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_TGKILL_E] = {FILLER_REF(sys_autofill), 3, APT_REG, {{0}, {1}, {2} } }, - [PPME_SYSCALL_TGKILL_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_NANOSLEEP_E] = {FILLER_REF(sys_nanosleep_e)}, - [PPME_SYSCALL_NANOSLEEP_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_TIMERFD_CREATE_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_USEDEFAULT, 0}, {AF_ID_USEDEFAULT, 0} } }, - [PPME_SYSCALL_TIMERFD_CREATE_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_INOTIFY_INIT_E] = {FILLER_REF(sys_inotify_init_e)}, - [PPME_SYSCALL_INOTIFY_INIT_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_GETRLIMIT_E] = {FILLER_REF(sys_getrlimit_setrlimit_e)}, - [PPME_SYSCALL_GETRLIMIT_X] = {FILLER_REF(sys_getrlimit_x)}, - [PPME_SYSCALL_SETRLIMIT_E] = {FILLER_REF(sys_getrlimit_setrlimit_e)}, - [PPME_SYSCALL_SETRLIMIT_X] = {FILLER_REF(sys_setrlimit_x)}, - [PPME_SYSCALL_PRLIMIT_E] = {FILLER_REF(sys_prlimit_e)}, - [PPME_SYSCALL_PRLIMIT_X] = {FILLER_REF(sys_prlimit_x)}, - [PPME_DROP_E] = {FILLER_REF(sched_drop)}, - [PPME_DROP_X] = {FILLER_REF(sched_drop)}, - [PPME_SYSCALL_FCNTL_E] = {FILLER_REF(sys_fcntl_e)}, - [PPME_SYSCALL_FCNTL_X] = {FILLER_REF(sys_fcntl_x)}, + [PPME_GENERIC_E] = {FILLER_REF(sys_generic)}, + [PPME_GENERIC_X] = {FILLER_REF(sys_generic)}, + [PPME_SYSCALL_OPEN_E] = {FILLER_REF(sys_open_e)}, + [PPME_SYSCALL_OPEN_X] = {FILLER_REF(sys_open_x)}, + [PPME_SYSCALL_CLOSE_E] = {FILLER_REF(sys_close_e)}, + [PPME_SYSCALL_CLOSE_X] = {FILLER_REF(sys_close_x)}, + [PPME_SYSCALL_READ_E] = {FILLER_REF(sys_read_e)}, + [PPME_SYSCALL_READ_X] = {FILLER_REF(sys_read_x)}, + [PPME_SYSCALL_WRITE_E] = {FILLER_REF(sys_write_e)}, + [PPME_SYSCALL_WRITE_X] = {FILLER_REF(sys_write_x)}, + [PPME_PROCEXIT_1_E] = {FILLER_REF(sys_procexit_e)}, + [PPME_SOCKET_SOCKET_E] = {FILLER_REF(sys_autofill), 3, APT_SOCK, {{0}, {1}, {2}}}, + [PPME_SOCKET_SOCKET_X] = {FILLER_REF(sys_socket_x)}, + [PPME_SOCKET_BIND_E] = {FILLER_REF(sys_socket_bind_e)}, + [PPME_SOCKET_BIND_X] = {FILLER_REF(sys_socket_bind_x)}, + [PPME_SOCKET_CONNECT_E] = {FILLER_REF(sys_connect_e)}, + [PPME_SOCKET_CONNECT_X] = {FILLER_REF(sys_connect_x)}, + [PPME_SOCKET_LISTEN_E] = {FILLER_REF(sys_listen_e)}, + [PPME_SOCKET_LISTEN_X] = {FILLER_REF(sys_single_x)}, + [PPME_SOCKET_SEND_E] = {FILLER_REF(sys_send_e)}, + [PPME_SOCKET_SEND_X] = {FILLER_REF(sys_send_x)}, + [PPME_SOCKET_SENDTO_E] = {FILLER_REF(sys_sendto_e)}, + [PPME_SOCKET_SENDTO_X] = {FILLER_REF(sys_send_x)}, + [PPME_SOCKET_RECV_E] = {FILLER_REF(sys_autofill), 2, APT_SOCK, {{0}, {2}}}, + [PPME_SOCKET_RECV_X] = {FILLER_REF(sys_recv_x)}, + [PPME_SOCKET_RECVFROM_E] = {FILLER_REF(sys_recvfrom_e)}, + [PPME_SOCKET_RECVFROM_X] = {FILLER_REF(sys_recvfrom_x)}, + [PPME_SOCKET_SHUTDOWN_E] = {FILLER_REF(sys_shutdown_e)}, + [PPME_SOCKET_SHUTDOWN_X] = {FILLER_REF(sys_single_x)}, + [PPME_SOCKET_GETSOCKNAME_E] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_GETSOCKNAME_X] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_GETPEERNAME_E] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_GETPEERNAME_X] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_SOCKETPAIR_E] = {FILLER_REF(sys_autofill), 3, APT_SOCK, {{0}, {1}, {2}}}, + [PPME_SOCKET_SOCKETPAIR_X] = {FILLER_REF(sys_socketpair_x)}, + [PPME_SOCKET_SETSOCKOPT_E] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_SETSOCKOPT_X] = {FILLER_REF(sys_setsockopt_x)}, + [PPME_SOCKET_GETSOCKOPT_E] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_GETSOCKOPT_X] = {FILLER_REF(sys_getsockopt_x)}, + [PPME_SOCKET_SENDMSG_E] = {FILLER_REF(sys_sendmsg_e)}, + [PPME_SOCKET_SENDMSG_X] = {FILLER_REF(sys_sendmsg_x)}, + [PPME_SOCKET_SENDMMSG_E] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_SENDMMSG_X] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_RECVMSG_E] = {FILLER_REF(sys_recvmsg_e)}, + [PPME_SOCKET_RECVMSG_X] = {FILLER_REF(sys_recvmsg_x)}, + [PPME_SOCKET_RECVMMSG_E] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_RECVMMSG_X] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CREAT_E] = {FILLER_REF(sys_creat_e)}, + [PPME_SYSCALL_CREAT_X] = {FILLER_REF(sys_creat_x)}, + [PPME_SYSCALL_PIPE_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_PIPE_X] = {FILLER_REF(sys_pipe_x)}, + [PPME_SYSCALL_EVENTFD_E] = {FILLER_REF(sys_eventfd_e)}, + [PPME_SYSCALL_EVENTFD_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_FUTEX_E] = {FILLER_REF(sys_futex_e)}, + [PPME_SYSCALL_FUTEX_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_STAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_STAT_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_LSTAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_LSTAT_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_FSTAT_E] = {FILLER_REF(sys_fstat_e)}, + [PPME_SYSCALL_FSTAT_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_STAT64_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_STAT64_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_LSTAT64_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_LSTAT64_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_FSTAT64_E] = {FILLER_REF(sys_single)}, + [PPME_SYSCALL_FSTAT64_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_EPOLLWAIT_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{2}}}, + [PPME_SYSCALL_EPOLLWAIT_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_POLL_E] = {FILLER_REF(sys_poll_e)}, + [PPME_SYSCALL_POLL_X] = {FILLER_REF(sys_poll_x)}, + [PPME_SYSCALL_SELECT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_SELECT_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_NEWSELECT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_NEWSELECT_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_LSEEK_E] = {FILLER_REF(sys_lseek_e)}, + [PPME_SYSCALL_LSEEK_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_LLSEEK_E] = {FILLER_REF(sys_llseek_e)}, + [PPME_SYSCALL_LLSEEK_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_GETCWD_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_GETCWD_X] = {FILLER_REF(sys_getcwd_x)}, + [PPME_SYSCALL_CHDIR_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CHDIR_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_FCHDIR_E] = {FILLER_REF(sys_fchdir_e)}, + [PPME_SYSCALL_FCHDIR_X] = {FILLER_REF(sys_fchdir_x)}, + [PPME_SYSCALL_UNLINK_E] = {FILLER_REF(sys_single)}, + [PPME_SYSCALL_UNLINK_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_UNLINKAT_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1}}}, + [PPME_SYSCALL_UNLINKAT_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_PREAD_E] = {FILLER_REF(sys_pread64_e)}, + [PPME_SYSCALL_PREAD_X] = {FILLER_REF(sys_read_x)}, + [PPME_SYSCALL_PWRITE_E] = {FILLER_REF(sys_pwrite64_e)}, + [PPME_SYSCALL_PWRITE_X] = {FILLER_REF(sys_write_x)}, + [PPME_SYSCALL_READV_E] = {FILLER_REF(sys_readv_e)}, + [PPME_SYSCALL_READV_X] = {FILLER_REF(sys_readv_preadv_x)}, + [PPME_SYSCALL_WRITEV_E] = {FILLER_REF(sys_writev_e)}, + [PPME_SYSCALL_WRITEV_X] = {FILLER_REF(sys_writev_pwritev_x)}, + [PPME_SYSCALL_PREADV_E] = {FILLER_REF(sys_preadv_e)}, + [PPME_SYSCALL_PREADV_X] = {FILLER_REF(sys_readv_preadv_x)}, + [PPME_SYSCALL_PWRITEV_E] = {FILLER_REF(sys_pwritev_e)}, + [PPME_SYSCALL_PWRITEV_X] = {FILLER_REF(sys_writev_pwritev_x)}, + [PPME_SYSCALL_DUP_1_E] = {FILLER_REF(sys_dup_e)}, + [PPME_SYSCALL_DUP_1_X] = {FILLER_REF(sys_dup_x)}, + [PPME_SYSCALL_DUP2_E] = {FILLER_REF(sys_dup2_e)}, + [PPME_SYSCALL_DUP2_X] = {FILLER_REF(sys_dup2_x)}, + [PPME_SYSCALL_DUP3_E] = {FILLER_REF(sys_dup3_e)}, + [PPME_SYSCALL_DUP3_X] = {FILLER_REF(sys_dup3_x)}, + [PPME_SYSCALL_SIGNALFD_E] = {FILLER_REF(sys_signalfd_e)}, + [PPME_SYSCALL_SIGNALFD_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_KILL_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1}}}, + [PPME_SYSCALL_KILL_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_TKILL_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1}}}, + [PPME_SYSCALL_TKILL_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_TGKILL_E] = {FILLER_REF(sys_autofill), 3, APT_REG, {{0}, {1}, {2}}}, + [PPME_SYSCALL_TGKILL_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_NANOSLEEP_E] = {FILLER_REF(sys_nanosleep_e)}, + [PPME_SYSCALL_NANOSLEEP_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_TIMERFD_CREATE_E] = {FILLER_REF(sys_autofill), + 2, + APT_REG, + {{AF_ID_USEDEFAULT, 0}, {AF_ID_USEDEFAULT, 0}}}, + [PPME_SYSCALL_TIMERFD_CREATE_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_INOTIFY_INIT_E] = {FILLER_REF(sys_inotify_init_e)}, + [PPME_SYSCALL_INOTIFY_INIT_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_GETRLIMIT_E] = {FILLER_REF(sys_getrlimit_setrlimit_e)}, + [PPME_SYSCALL_GETRLIMIT_X] = {FILLER_REF(sys_getrlimit_x)}, + [PPME_SYSCALL_SETRLIMIT_E] = {FILLER_REF(sys_getrlimit_setrlimit_e)}, + [PPME_SYSCALL_SETRLIMIT_X] = {FILLER_REF(sys_setrlimit_x)}, + [PPME_SYSCALL_PRLIMIT_E] = {FILLER_REF(sys_prlimit_e)}, + [PPME_SYSCALL_PRLIMIT_X] = {FILLER_REF(sys_prlimit_x)}, + [PPME_DROP_E] = {FILLER_REF(sched_drop)}, + [PPME_DROP_X] = {FILLER_REF(sched_drop)}, + [PPME_SYSCALL_FCNTL_E] = {FILLER_REF(sys_fcntl_e)}, + [PPME_SYSCALL_FCNTL_X] = {FILLER_REF(sys_fcntl_x)}, #ifdef CAPTURE_CONTEXT_SWITCHES - [PPME_SCHEDSWITCH_6_E] = {FILLER_REF(sched_switch_e)}, + [PPME_SCHEDSWITCH_6_E] = {FILLER_REF(sched_switch_e)}, #endif - [PPME_SYSCALL_BRK_4_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{0} } }, - [PPME_SYSCALL_BRK_4_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, - [PPME_SYSCALL_MMAP_E] = {FILLER_REF(sys_mmap_e)}, - [PPME_SYSCALL_MMAP_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, - [PPME_SYSCALL_MMAP2_E] = {FILLER_REF(sys_mmap_e)}, - [PPME_SYSCALL_MMAP2_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, - [PPME_SYSCALL_MUNMAP_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1} } }, - [PPME_SYSCALL_MUNMAP_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, - [PPME_SYSCALL_SPLICE_E] = {FILLER_REF(sys_splice_e)}, - [PPME_SYSCALL_SPLICE_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_PTRACE_E] = {FILLER_REF(sys_ptrace_e)}, - [PPME_SYSCALL_PTRACE_X] = {FILLER_REF(sys_ptrace_x)}, - [PPME_SYSCALL_IOCTL_3_E] = {FILLER_REF(sys_ioctl_e)}, - [PPME_SYSCALL_IOCTL_3_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_RENAME_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_RENAME_X] = {FILLER_REF(sys_autofill), 3, APT_REG, {{AF_ID_RETVAL}, {0}, {1} } }, - [PPME_SYSCALL_RENAMEAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_RENAMEAT_X] = {FILLER_REF(sys_renameat_x)}, - [PPME_SYSCALL_SYMLINK_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_SYMLINK_X] = {FILLER_REF(sys_autofill), 3, APT_REG, {{AF_ID_RETVAL}, {0}, {1} } }, - [PPME_SYSCALL_SYMLINKAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_SYMLINKAT_X] = {FILLER_REF(sys_symlinkat_x)}, - [PPME_SYSCALL_SENDFILE_E] = {FILLER_REF(sys_sendfile_e)}, - [PPME_SYSCALL_SENDFILE_X] = {FILLER_REF(sys_sendfile_x)}, - [PPME_SYSCALL_QUOTACTL_E] = {FILLER_REF(sys_quotactl_e)}, - [PPME_SYSCALL_QUOTACTL_X] = {FILLER_REF(sys_quotactl_x)}, - [PPME_SYSCALL_SETRESUID_E] = {FILLER_REF(sys_autofill), 3, APT_REG, {{0}, {1}, {2} } }, - [PPME_SYSCALL_SETRESUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_SETRESGID_E] = {FILLER_REF(sys_autofill), 3, APT_REG, {{0}, {1}, {2} } }, - [PPME_SYSCALL_SETRESGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SCAPEVENT_E] = {FILLER_REF(sys_scapevent_e)}, - [PPME_SYSCALL_SETUID_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{0} } }, - [PPME_SYSCALL_SETUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_SETGID_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{0} } }, - [PPME_SYSCALL_SETGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_GETUID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_GETUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_GETEUID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_GETEUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_GETGID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_GETGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_GETEGID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_GETEGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_GETRESUID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_GETRESUID_X] = {FILLER_REF(sys_getresuid_and_gid_x)}, - [PPME_SYSCALL_GETRESGID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_GETRESGID_X] = {FILLER_REF(sys_getresuid_and_gid_x)}, - [PPME_SYSCALL_CLONE_20_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CLONE_20_X] = {FILLER_REF(proc_startupdate)}, - [PPME_SYSCALL_FORK_20_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_FORK_20_X] = {FILLER_REF(proc_startupdate)}, - [PPME_SYSCALL_VFORK_20_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_VFORK_20_X] = {FILLER_REF(proc_startupdate)}, + [PPME_SYSCALL_BRK_4_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{0}}}, + [PPME_SYSCALL_BRK_4_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, + [PPME_SYSCALL_MMAP_E] = {FILLER_REF(sys_mmap_e)}, + [PPME_SYSCALL_MMAP_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, + [PPME_SYSCALL_MMAP2_E] = {FILLER_REF(sys_mmap_e)}, + [PPME_SYSCALL_MMAP2_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, + [PPME_SYSCALL_MUNMAP_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1}}}, + [PPME_SYSCALL_MUNMAP_X] = {FILLER_REF(sys_brk_munmap_mmap_x)}, + [PPME_SYSCALL_SPLICE_E] = {FILLER_REF(sys_splice_e)}, + [PPME_SYSCALL_SPLICE_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_PTRACE_E] = {FILLER_REF(sys_ptrace_e)}, + [PPME_SYSCALL_PTRACE_X] = {FILLER_REF(sys_ptrace_x)}, + [PPME_SYSCALL_IOCTL_3_E] = {FILLER_REF(sys_ioctl_e)}, + [PPME_SYSCALL_IOCTL_3_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_RENAME_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_RENAME_X] = {FILLER_REF(sys_autofill), + 3, + APT_REG, + {{AF_ID_RETVAL}, {0}, {1}}}, + [PPME_SYSCALL_RENAMEAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_RENAMEAT_X] = {FILLER_REF(sys_renameat_x)}, + [PPME_SYSCALL_SYMLINK_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_SYMLINK_X] = {FILLER_REF(sys_autofill), + 3, + APT_REG, + {{AF_ID_RETVAL}, {0}, {1}}}, + [PPME_SYSCALL_SYMLINKAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_SYMLINKAT_X] = {FILLER_REF(sys_symlinkat_x)}, + [PPME_SYSCALL_SENDFILE_E] = {FILLER_REF(sys_sendfile_e)}, + [PPME_SYSCALL_SENDFILE_X] = {FILLER_REF(sys_sendfile_x)}, + [PPME_SYSCALL_QUOTACTL_E] = {FILLER_REF(sys_quotactl_e)}, + [PPME_SYSCALL_QUOTACTL_X] = {FILLER_REF(sys_quotactl_x)}, + [PPME_SYSCALL_SETRESUID_E] = {FILLER_REF(sys_autofill), 3, APT_REG, {{0}, {1}, {2}}}, + [PPME_SYSCALL_SETRESUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_SETRESGID_E] = {FILLER_REF(sys_autofill), 3, APT_REG, {{0}, {1}, {2}}}, + [PPME_SYSCALL_SETRESGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SCAPEVENT_E] = {FILLER_REF(sys_scapevent_e)}, + [PPME_SYSCALL_SETUID_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{0}}}, + [PPME_SYSCALL_SETUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_SETGID_E] = {FILLER_REF(sys_autofill), 1, APT_REG, {{0}}}, + [PPME_SYSCALL_SETGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_GETUID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_GETUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_GETEUID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_GETEUID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_GETGID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_GETGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_GETEGID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_GETEGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_GETRESUID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_GETRESUID_X] = {FILLER_REF(sys_getresuid_and_gid_x)}, + [PPME_SYSCALL_GETRESGID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_GETRESGID_X] = {FILLER_REF(sys_getresuid_and_gid_x)}, + [PPME_SYSCALL_CLONE_20_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CLONE_20_X] = {FILLER_REF(proc_startupdate)}, + [PPME_SYSCALL_FORK_20_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_FORK_20_X] = {FILLER_REF(proc_startupdate)}, + [PPME_SYSCALL_VFORK_20_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_VFORK_20_X] = {FILLER_REF(proc_startupdate)}, #ifdef CAPTURE_SIGNAL_DELIVERIES - [PPME_SIGNALDELIVER_E] = {FILLER_REF(sys_signaldeliver_e)}, + [PPME_SIGNALDELIVER_E] = {FILLER_REF(sys_signaldeliver_e)}, #endif - [PPME_SYSCALL_GETDENTS_E] = {FILLER_REF(sys_getdents_e)}, - [PPME_SYSCALL_GETDENTS_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_GETDENTS64_E] = {FILLER_REF(sys_getdents64_e)}, - [PPME_SYSCALL_GETDENTS64_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_SETNS_E] = {FILLER_REF(sys_setns_e)}, - [PPME_SYSCALL_SETNS_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_FLOCK_E] = {FILLER_REF(sys_flock_e)}, - [PPME_SYSCALL_FLOCK_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_CPU_HOTPLUG_E] = {FILLER_REF(cpu_hotplug_e)}, - [PPME_SOCKET_ACCEPT_5_E] = {FILLER_REF(sys_empty)}, - [PPME_SOCKET_ACCEPT_5_X] = {FILLER_REF(sys_accept_x)}, - [PPME_SYSCALL_SEMOP_E] = {FILLER_REF(sys_single)}, - [PPME_SYSCALL_SEMOP_X] = {FILLER_REF(sys_semop_x)}, - [PPME_SYSCALL_SEMCTL_E] = {FILLER_REF(sys_semctl_e)}, - [PPME_SYSCALL_SEMCTL_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_PPOLL_E] = {FILLER_REF(sys_ppoll_e)}, - [PPME_SYSCALL_PPOLL_X] = {FILLER_REF(sys_poll_x)}, /* exit same for poll() and ppoll() */ - [PPME_SYSCALL_MOUNT_E] = {FILLER_REF(sys_mount_e)}, - [PPME_SYSCALL_MOUNT_X] = {FILLER_REF(sys_autofill), 4, APT_REG, {{AF_ID_RETVAL}, {0}, {1}, {2} } }, - [PPME_SYSCALL_SEMGET_E] = {FILLER_REF(sys_semget_e)}, - [PPME_SYSCALL_SEMGET_X] = {FILLER_REF(sys_single_x)}, - [PPME_SYSCALL_ACCESS_E] = {FILLER_REF(sys_access_e)}, - [PPME_SYSCALL_ACCESS_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_CHROOT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CHROOT_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_SETSID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_SETSID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_SETPGID_E] = {FILLER_REF(sys_setpgid_e)}, - [PPME_SYSCALL_SETPGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_MKDIR_2_E] = {FILLER_REF(sys_mkdir_e)}, - [PPME_SYSCALL_MKDIR_2_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_RMDIR_2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_RMDIR_2_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_UNSHARE_E] = {FILLER_REF(sys_unshare_e)}, - [PPME_SYSCALL_UNSHARE_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_EXECVE_19_E] = {FILLER_REF(sys_execve_e)}, - [PPME_SYSCALL_EXECVE_19_X] = {FILLER_REF(proc_startupdate)}, + [PPME_SYSCALL_GETDENTS_E] = {FILLER_REF(sys_getdents_e)}, + [PPME_SYSCALL_GETDENTS_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_GETDENTS64_E] = {FILLER_REF(sys_getdents64_e)}, + [PPME_SYSCALL_GETDENTS64_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_SETNS_E] = {FILLER_REF(sys_setns_e)}, + [PPME_SYSCALL_SETNS_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_FLOCK_E] = {FILLER_REF(sys_flock_e)}, + [PPME_SYSCALL_FLOCK_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_CPU_HOTPLUG_E] = {FILLER_REF(cpu_hotplug_e)}, + [PPME_SOCKET_ACCEPT_5_E] = {FILLER_REF(sys_empty)}, + [PPME_SOCKET_ACCEPT_5_X] = {FILLER_REF(sys_accept_x)}, + [PPME_SYSCALL_SEMOP_E] = {FILLER_REF(sys_single)}, + [PPME_SYSCALL_SEMOP_X] = {FILLER_REF(sys_semop_x)}, + [PPME_SYSCALL_SEMCTL_E] = {FILLER_REF(sys_semctl_e)}, + [PPME_SYSCALL_SEMCTL_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_PPOLL_E] = {FILLER_REF(sys_ppoll_e)}, + [PPME_SYSCALL_PPOLL_X] = {FILLER_REF(sys_poll_x)}, /* exit same for poll() and ppoll() */ + [PPME_SYSCALL_MOUNT_E] = {FILLER_REF(sys_mount_e)}, + [PPME_SYSCALL_MOUNT_X] = {FILLER_REF(sys_autofill), + 4, + APT_REG, + {{AF_ID_RETVAL}, {0}, {1}, {2}}}, + [PPME_SYSCALL_SEMGET_E] = {FILLER_REF(sys_semget_e)}, + [PPME_SYSCALL_SEMGET_X] = {FILLER_REF(sys_single_x)}, + [PPME_SYSCALL_ACCESS_E] = {FILLER_REF(sys_access_e)}, + [PPME_SYSCALL_ACCESS_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_CHROOT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CHROOT_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_SETSID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_SETSID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_SETPGID_E] = {FILLER_REF(sys_setpgid_e)}, + [PPME_SYSCALL_SETPGID_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_MKDIR_2_E] = {FILLER_REF(sys_mkdir_e)}, + [PPME_SYSCALL_MKDIR_2_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_RMDIR_2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_RMDIR_2_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_UNSHARE_E] = {FILLER_REF(sys_unshare_e)}, + [PPME_SYSCALL_UNSHARE_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_EXECVE_19_E] = {FILLER_REF(sys_execve_e)}, + [PPME_SYSCALL_EXECVE_19_X] = {FILLER_REF(proc_startupdate)}, #ifdef CAPTURE_PAGE_FAULTS - [PPME_PAGE_FAULT_E] = {FILLER_REF(sys_pagefault_e)}, + [PPME_PAGE_FAULT_E] = {FILLER_REF(sys_pagefault_e)}, #endif - [PPME_SYSCALL_BPF_2_E] = {FILLER_REF(sys_bpf_e)}, - [PPME_SYSCALL_BPF_2_X] = {FILLER_REF(sys_bpf_x)}, - [PPME_SYSCALL_SECCOMP_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1} } }, - [PPME_SYSCALL_SECCOMP_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL} } }, - [PPME_SYSCALL_UNLINK_2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_UNLINK_2_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_UNLINKAT_2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_UNLINKAT_2_X] = {FILLER_REF(sys_unlinkat_x)}, - [PPME_SYSCALL_MKDIRAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MKDIRAT_X] = {FILLER_REF(sys_mkdirat_x)}, - [PPME_SYSCALL_OPENAT_2_E] = {FILLER_REF(sys_openat_e)}, - [PPME_SYSCALL_OPENAT_2_X] = {FILLER_REF(sys_openat_x)}, - [PPME_SYSCALL_LINK_2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_LINK_2_X] = {FILLER_REF(sys_autofill), 3, APT_REG, {{AF_ID_RETVAL}, {0}, {1} } }, - [PPME_SYSCALL_LINKAT_2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_LINKAT_2_X] = {FILLER_REF(sys_linkat_x)}, - [PPME_SYSCALL_FCHMODAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_FCHMODAT_X] = {FILLER_REF(sys_fchmodat_x)}, - [PPME_SYSCALL_CHMOD_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CHMOD_X] = {FILLER_REF(sys_chmod_x)}, - [PPME_SYSCALL_FCHMOD_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_FCHMOD_X] = {FILLER_REF(sys_fchmod_x)}, - [PPME_SYSCALL_RENAMEAT2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_RENAMEAT2_X] = {FILLER_REF(sys_renameat2_x)}, - [PPME_SYSCALL_USERFAULTFD_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_USERFAULTFD_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0} } }, - [PPME_SYSCALL_OPENAT2_E] = {FILLER_REF(sys_openat2_e)}, - [PPME_SYSCALL_OPENAT2_X] = {FILLER_REF(sys_openat2_x)}, - [PPME_SYSCALL_MPROTECT_E] = {FILLER_REF(sys_mprotect_e)}, - [PPME_SYSCALL_MPROTECT_X] = {FILLER_REF(sys_mprotect_x)}, - [PPME_SYSCALL_EXECVEAT_E] = {FILLER_REF(sys_execveat_e)}, - [PPME_SYSCALL_EXECVEAT_X] = {FILLER_REF(proc_startupdate)}, - [PPME_SYSCALL_COPY_FILE_RANGE_E] = {FILLER_REF(sys_copy_file_range_e)}, - [PPME_SYSCALL_COPY_FILE_RANGE_X] = {FILLER_REF(sys_copy_file_range_x)}, - [PPME_SYSCALL_CLONE3_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CLONE3_X] = {FILLER_REF(proc_startupdate)}, - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = {FILLER_REF(sys_open_by_handle_at_x)}, - [PPME_SYSCALL_IO_URING_SETUP_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_IO_URING_SETUP_X] = {FILLER_REF(sys_io_uring_setup_x)}, - [PPME_SYSCALL_IO_URING_ENTER_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_IO_URING_ENTER_X] = {FILLER_REF(sys_io_uring_enter_x)}, - [PPME_SYSCALL_IO_URING_REGISTER_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_IO_URING_REGISTER_X] = {FILLER_REF(sys_io_uring_register_x)}, - [PPME_SYSCALL_MLOCK_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MLOCK_X] = {FILLER_REF(sys_mlock_x)}, - [PPME_SYSCALL_MUNLOCK_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MUNLOCK_X] = {FILLER_REF(sys_munlock_x)}, - [PPME_SYSCALL_MLOCKALL_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MLOCKALL_X] = {FILLER_REF(sys_mlockall_x)}, - [PPME_SYSCALL_MUNLOCKALL_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MUNLOCKALL_X] = {FILLER_REF(sys_munlockall_x)}, - [PPME_SYSCALL_CAPSET_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CAPSET_X] = {FILLER_REF(sys_capset_x)}, - [PPME_SYSCALL_MLOCK2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MLOCK2_X] = {FILLER_REF(sys_mlock2_x)}, - [PPME_SYSCALL_FSCONFIG_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_FSCONFIG_X] = {FILLER_REF(sys_fsconfig_x)}, - [PPME_SYSCALL_EPOLL_CREATE_E] = {FILLER_REF(sys_epoll_create_e)}, - [PPME_SYSCALL_EPOLL_CREATE_X] = {FILLER_REF(sys_epoll_create_x)}, - [PPME_SYSCALL_EPOLL_CREATE1_E] = {FILLER_REF(sys_epoll_create1_e)}, - [PPME_SYSCALL_EPOLL_CREATE1_X] = {FILLER_REF(sys_epoll_create1_x)}, - [PPME_SYSCALL_CHOWN_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_CHOWN_X] = {FILLER_REF(sys_chown_x)}, - [PPME_SYSCALL_LCHOWN_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_LCHOWN_X] = {FILLER_REF(sys_lchown_x)}, - [PPME_SYSCALL_FCHOWN_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_FCHOWN_X] = {FILLER_REF(sys_fchown_x)}, - [PPME_SYSCALL_FCHOWNAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_FCHOWNAT_X] = {FILLER_REF(sys_fchownat_x)}, - [PPME_SYSCALL_UMOUNT_1_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_UMOUNT_1_X] = {FILLER_REF(sys_umount_x)}, - [PPME_SOCKET_ACCEPT4_6_E] = {FILLER_REF(sys_accept4_e)}, - [PPME_SOCKET_ACCEPT4_6_X] = {FILLER_REF(sys_accept_x)}, - [PPME_SYSCALL_UMOUNT2_E] = {FILLER_REF(sys_umount2_e)}, - [PPME_SYSCALL_UMOUNT2_X] = {FILLER_REF(sys_umount2_x)}, - [PPME_SYSCALL_PIPE2_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_PIPE2_X] = {FILLER_REF(sys_pipe2_x)}, - [PPME_SYSCALL_INOTIFY_INIT1_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_INOTIFY_INIT1_X] = {FILLER_REF(sys_inotify_init1_x)}, - [PPME_SYSCALL_EVENTFD2_E] = {FILLER_REF(sys_eventfd2_e)}, - [PPME_SYSCALL_EVENTFD2_X] = {FILLER_REF(sys_eventfd2_x)}, - [PPME_SYSCALL_SIGNALFD4_E] = {FILLER_REF(sys_signalfd4_e)}, - [PPME_SYSCALL_SIGNALFD4_X] = {FILLER_REF(sys_signalfd4_x)}, - [PPME_SYSCALL_PRCTL_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_PRCTL_X] = {FILLER_REF(sys_prctl_x)}, - [PPME_SYSCALL_MEMFD_CREATE_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MEMFD_CREATE_X] = {FILLER_REF(sys_memfd_create_x)}, - [PPME_SYSCALL_PIDFD_GETFD_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_PIDFD_GETFD_X] = {FILLER_REF(sys_pidfd_getfd_x)}, - [PPME_SYSCALL_PIDFD_OPEN_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_PIDFD_OPEN_X] = {FILLER_REF(sys_pidfd_open_x)}, - [PPME_SYSCALL_INIT_MODULE_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_INIT_MODULE_X] = {FILLER_REF(sys_init_module_x)}, - [PPME_SYSCALL_FINIT_MODULE_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_FINIT_MODULE_X] = {FILLER_REF(sys_finit_module_x)}, - [PPME_SYSCALL_MKNOD_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MKNOD_X] = {FILLER_REF(sys_mknod_x)}, - [PPME_SYSCALL_MKNODAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_MKNODAT_X] = {FILLER_REF(sys_mknodat_x)}, - [PPME_SYSCALL_NEWFSTATAT_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_NEWFSTATAT_X] = {FILLER_REF(sys_newfstatat_x)}, - [PPME_SYSCALL_PROCESS_VM_READV_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_PROCESS_VM_READV_X] = {FILLER_REF(sys_process_vm_readv_x)}, - [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = {FILLER_REF(sys_process_vm_writev_x)}, - [PPME_SYSCALL_DELETE_MODULE_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_DELETE_MODULE_X] = {FILLER_REF(sys_delete_module_x)}, - [PPME_SYSCALL_SETREUID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_SETREUID_X] = {FILLER_REF(sys_autofill), 3, APT_REG, {{AF_ID_RETVAL}, {0}, {1} } }, - [PPME_SYSCALL_SETREGID_E] = {FILLER_REF(sys_empty)}, - [PPME_SYSCALL_SETREGID_X] = {FILLER_REF(sys_autofill), 3, APT_REG, {{AF_ID_RETVAL}, {0}, {1} } }, + [PPME_SYSCALL_BPF_2_E] = {FILLER_REF(sys_bpf_e)}, + [PPME_SYSCALL_BPF_2_X] = {FILLER_REF(sys_bpf_x)}, + [PPME_SYSCALL_SECCOMP_E] = {FILLER_REF(sys_autofill), 2, APT_REG, {{0}, {1}}}, + [PPME_SYSCALL_SECCOMP_X] = {FILLER_REF(sys_autofill), 1, APT_REG, {{AF_ID_RETVAL}}}, + [PPME_SYSCALL_UNLINK_2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_UNLINK_2_X] = {FILLER_REF(sys_autofill), 2, APT_REG, {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_UNLINKAT_2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_UNLINKAT_2_X] = {FILLER_REF(sys_unlinkat_x)}, + [PPME_SYSCALL_MKDIRAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MKDIRAT_X] = {FILLER_REF(sys_mkdirat_x)}, + [PPME_SYSCALL_OPENAT_2_E] = {FILLER_REF(sys_openat_e)}, + [PPME_SYSCALL_OPENAT_2_X] = {FILLER_REF(sys_openat_x)}, + [PPME_SYSCALL_LINK_2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_LINK_2_X] = {FILLER_REF(sys_autofill), + 3, + APT_REG, + {{AF_ID_RETVAL}, {0}, {1}}}, + [PPME_SYSCALL_LINKAT_2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_LINKAT_2_X] = {FILLER_REF(sys_linkat_x)}, + [PPME_SYSCALL_FCHMODAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_FCHMODAT_X] = {FILLER_REF(sys_fchmodat_x)}, + [PPME_SYSCALL_CHMOD_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CHMOD_X] = {FILLER_REF(sys_chmod_x)}, + [PPME_SYSCALL_FCHMOD_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_FCHMOD_X] = {FILLER_REF(sys_fchmod_x)}, + [PPME_SYSCALL_RENAMEAT2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_RENAMEAT2_X] = {FILLER_REF(sys_renameat2_x)}, + [PPME_SYSCALL_USERFAULTFD_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_USERFAULTFD_X] = {FILLER_REF(sys_autofill), + 2, + APT_REG, + {{AF_ID_RETVAL}, {0}}}, + [PPME_SYSCALL_OPENAT2_E] = {FILLER_REF(sys_openat2_e)}, + [PPME_SYSCALL_OPENAT2_X] = {FILLER_REF(sys_openat2_x)}, + [PPME_SYSCALL_MPROTECT_E] = {FILLER_REF(sys_mprotect_e)}, + [PPME_SYSCALL_MPROTECT_X] = {FILLER_REF(sys_mprotect_x)}, + [PPME_SYSCALL_EXECVEAT_E] = {FILLER_REF(sys_execveat_e)}, + [PPME_SYSCALL_EXECVEAT_X] = {FILLER_REF(proc_startupdate)}, + [PPME_SYSCALL_COPY_FILE_RANGE_E] = {FILLER_REF(sys_copy_file_range_e)}, + [PPME_SYSCALL_COPY_FILE_RANGE_X] = {FILLER_REF(sys_copy_file_range_x)}, + [PPME_SYSCALL_CLONE3_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CLONE3_X] = {FILLER_REF(proc_startupdate)}, + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = {FILLER_REF(sys_open_by_handle_at_x)}, + [PPME_SYSCALL_IO_URING_SETUP_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_IO_URING_SETUP_X] = {FILLER_REF(sys_io_uring_setup_x)}, + [PPME_SYSCALL_IO_URING_ENTER_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_IO_URING_ENTER_X] = {FILLER_REF(sys_io_uring_enter_x)}, + [PPME_SYSCALL_IO_URING_REGISTER_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_IO_URING_REGISTER_X] = {FILLER_REF(sys_io_uring_register_x)}, + [PPME_SYSCALL_MLOCK_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MLOCK_X] = {FILLER_REF(sys_mlock_x)}, + [PPME_SYSCALL_MUNLOCK_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MUNLOCK_X] = {FILLER_REF(sys_munlock_x)}, + [PPME_SYSCALL_MLOCKALL_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MLOCKALL_X] = {FILLER_REF(sys_mlockall_x)}, + [PPME_SYSCALL_MUNLOCKALL_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MUNLOCKALL_X] = {FILLER_REF(sys_munlockall_x)}, + [PPME_SYSCALL_CAPSET_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CAPSET_X] = {FILLER_REF(sys_capset_x)}, + [PPME_SYSCALL_MLOCK2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MLOCK2_X] = {FILLER_REF(sys_mlock2_x)}, + [PPME_SYSCALL_FSCONFIG_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_FSCONFIG_X] = {FILLER_REF(sys_fsconfig_x)}, + [PPME_SYSCALL_EPOLL_CREATE_E] = {FILLER_REF(sys_epoll_create_e)}, + [PPME_SYSCALL_EPOLL_CREATE_X] = {FILLER_REF(sys_epoll_create_x)}, + [PPME_SYSCALL_EPOLL_CREATE1_E] = {FILLER_REF(sys_epoll_create1_e)}, + [PPME_SYSCALL_EPOLL_CREATE1_X] = {FILLER_REF(sys_epoll_create1_x)}, + [PPME_SYSCALL_CHOWN_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_CHOWN_X] = {FILLER_REF(sys_chown_x)}, + [PPME_SYSCALL_LCHOWN_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_LCHOWN_X] = {FILLER_REF(sys_lchown_x)}, + [PPME_SYSCALL_FCHOWN_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_FCHOWN_X] = {FILLER_REF(sys_fchown_x)}, + [PPME_SYSCALL_FCHOWNAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_FCHOWNAT_X] = {FILLER_REF(sys_fchownat_x)}, + [PPME_SYSCALL_UMOUNT_1_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_UMOUNT_1_X] = {FILLER_REF(sys_umount_x)}, + [PPME_SOCKET_ACCEPT4_6_E] = {FILLER_REF(sys_accept4_e)}, + [PPME_SOCKET_ACCEPT4_6_X] = {FILLER_REF(sys_accept_x)}, + [PPME_SYSCALL_UMOUNT2_E] = {FILLER_REF(sys_umount2_e)}, + [PPME_SYSCALL_UMOUNT2_X] = {FILLER_REF(sys_umount2_x)}, + [PPME_SYSCALL_PIPE2_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_PIPE2_X] = {FILLER_REF(sys_pipe2_x)}, + [PPME_SYSCALL_INOTIFY_INIT1_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_INOTIFY_INIT1_X] = {FILLER_REF(sys_inotify_init1_x)}, + [PPME_SYSCALL_EVENTFD2_E] = {FILLER_REF(sys_eventfd2_e)}, + [PPME_SYSCALL_EVENTFD2_X] = {FILLER_REF(sys_eventfd2_x)}, + [PPME_SYSCALL_SIGNALFD4_E] = {FILLER_REF(sys_signalfd4_e)}, + [PPME_SYSCALL_SIGNALFD4_X] = {FILLER_REF(sys_signalfd4_x)}, + [PPME_SYSCALL_PRCTL_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_PRCTL_X] = {FILLER_REF(sys_prctl_x)}, + [PPME_SYSCALL_MEMFD_CREATE_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MEMFD_CREATE_X] = {FILLER_REF(sys_memfd_create_x)}, + [PPME_SYSCALL_PIDFD_GETFD_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_PIDFD_GETFD_X] = {FILLER_REF(sys_pidfd_getfd_x)}, + [PPME_SYSCALL_PIDFD_OPEN_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_PIDFD_OPEN_X] = {FILLER_REF(sys_pidfd_open_x)}, + [PPME_SYSCALL_INIT_MODULE_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_INIT_MODULE_X] = {FILLER_REF(sys_init_module_x)}, + [PPME_SYSCALL_FINIT_MODULE_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_FINIT_MODULE_X] = {FILLER_REF(sys_finit_module_x)}, + [PPME_SYSCALL_MKNOD_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MKNOD_X] = {FILLER_REF(sys_mknod_x)}, + [PPME_SYSCALL_MKNODAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_MKNODAT_X] = {FILLER_REF(sys_mknodat_x)}, + [PPME_SYSCALL_NEWFSTATAT_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_NEWFSTATAT_X] = {FILLER_REF(sys_newfstatat_x)}, + [PPME_SYSCALL_PROCESS_VM_READV_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_PROCESS_VM_READV_X] = {FILLER_REF(sys_process_vm_readv_x)}, + [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = {FILLER_REF(sys_process_vm_writev_x)}, + [PPME_SYSCALL_DELETE_MODULE_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_DELETE_MODULE_X] = {FILLER_REF(sys_delete_module_x)}, + [PPME_SYSCALL_SETREUID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_SETREUID_X] = {FILLER_REF(sys_autofill), + 3, + APT_REG, + {{AF_ID_RETVAL}, {0}, {1}}}, + [PPME_SYSCALL_SETREGID_E] = {FILLER_REF(sys_empty)}, + [PPME_SYSCALL_SETREGID_X] = {FILLER_REF(sys_autofill), + 3, + APT_REG, + {{AF_ID_RETVAL}, {0}, {1}}}, }; diff --git a/driver/flags_table.c b/driver/flags_table.c index a187059f24..3b1bede169 100644 --- a/driver/flags_table.c +++ b/driver/flags_table.c @@ -11,771 +11,770 @@ or GPL2.txt for full copies of the license. #include "ppm_events_public.h" const struct ppm_name_value socket_families[] = { - {"AF_NFC", PPM_AF_NFC}, - {"AF_ALG", PPM_AF_ALG}, - {"AF_CAIF", PPM_AF_CAIF}, - {"AF_IEEE802154", PPM_AF_IEEE802154}, - {"AF_PHONET", PPM_AF_PHONET}, - {"AF_ISDN", PPM_AF_ISDN}, - {"AF_RXRPC", PPM_AF_RXRPC}, - {"AF_IUCV", PPM_AF_IUCV}, - {"AF_BLUETOOTH", PPM_AF_BLUETOOTH}, - {"AF_TIPC", PPM_AF_TIPC}, - {"AF_CAN", PPM_AF_CAN}, - {"AF_LLC", PPM_AF_LLC}, - {"AF_WANPIPE", PPM_AF_WANPIPE}, - {"AF_PPPOX", PPM_AF_PPPOX}, - {"AF_IRDA", PPM_AF_IRDA}, - {"AF_SNA", PPM_AF_SNA}, - {"AF_RDS", PPM_AF_RDS}, - {"AF_ATMSVC", PPM_AF_ATMSVC}, - {"AF_ECONET", PPM_AF_ECONET}, - {"AF_ASH", PPM_AF_ASH}, - {"AF_PACKET", PPM_AF_PACKET}, - {"AF_ROUTE", PPM_AF_ROUTE}, - {"AF_NETLINK", PPM_AF_NETLINK}, - {"AF_KEY", PPM_AF_KEY}, - {"AF_SECURITY", PPM_AF_SECURITY}, - {"AF_NETBEUI", PPM_AF_NETBEUI}, - {"AF_DECnet", PPM_AF_DECnet}, - {"AF_ROSE", PPM_AF_ROSE}, - {"AF_INET6", PPM_AF_INET6}, - {"AF_X25", PPM_AF_X25}, - {"AF_ATMPVC", PPM_AF_ATMPVC}, - {"AF_BRIDGE", PPM_AF_BRIDGE}, - {"AF_NETROM", PPM_AF_NETROM}, - {"AF_APPLETALK", PPM_AF_APPLETALK}, - {"AF_IPX", PPM_AF_IPX}, - {"AF_AX25", PPM_AF_AX25}, - {"AF_INET", PPM_AF_INET}, - {"AF_LOCAL", PPM_AF_LOCAL}, - {"AF_UNIX", PPM_AF_UNIX}, - {"AF_UNSPEC", PPM_AF_UNSPEC}, - {0, 0}, + {"AF_NFC", PPM_AF_NFC}, + {"AF_ALG", PPM_AF_ALG}, + {"AF_CAIF", PPM_AF_CAIF}, + {"AF_IEEE802154", PPM_AF_IEEE802154}, + {"AF_PHONET", PPM_AF_PHONET}, + {"AF_ISDN", PPM_AF_ISDN}, + {"AF_RXRPC", PPM_AF_RXRPC}, + {"AF_IUCV", PPM_AF_IUCV}, + {"AF_BLUETOOTH", PPM_AF_BLUETOOTH}, + {"AF_TIPC", PPM_AF_TIPC}, + {"AF_CAN", PPM_AF_CAN}, + {"AF_LLC", PPM_AF_LLC}, + {"AF_WANPIPE", PPM_AF_WANPIPE}, + {"AF_PPPOX", PPM_AF_PPPOX}, + {"AF_IRDA", PPM_AF_IRDA}, + {"AF_SNA", PPM_AF_SNA}, + {"AF_RDS", PPM_AF_RDS}, + {"AF_ATMSVC", PPM_AF_ATMSVC}, + {"AF_ECONET", PPM_AF_ECONET}, + {"AF_ASH", PPM_AF_ASH}, + {"AF_PACKET", PPM_AF_PACKET}, + {"AF_ROUTE", PPM_AF_ROUTE}, + {"AF_NETLINK", PPM_AF_NETLINK}, + {"AF_KEY", PPM_AF_KEY}, + {"AF_SECURITY", PPM_AF_SECURITY}, + {"AF_NETBEUI", PPM_AF_NETBEUI}, + {"AF_DECnet", PPM_AF_DECnet}, + {"AF_ROSE", PPM_AF_ROSE}, + {"AF_INET6", PPM_AF_INET6}, + {"AF_X25", PPM_AF_X25}, + {"AF_ATMPVC", PPM_AF_ATMPVC}, + {"AF_BRIDGE", PPM_AF_BRIDGE}, + {"AF_NETROM", PPM_AF_NETROM}, + {"AF_APPLETALK", PPM_AF_APPLETALK}, + {"AF_IPX", PPM_AF_IPX}, + {"AF_AX25", PPM_AF_AX25}, + {"AF_INET", PPM_AF_INET}, + {"AF_LOCAL", PPM_AF_LOCAL}, + {"AF_UNIX", PPM_AF_UNIX}, + {"AF_UNSPEC", PPM_AF_UNSPEC}, + {0, 0}, }; const struct ppm_name_value file_flags[] = { - {"O_LARGEFILE", PPM_O_LARGEFILE}, - {"O_DIRECTORY", PPM_O_DIRECTORY}, - {"O_DIRECT", PPM_O_DIRECT}, - {"O_TRUNC", PPM_O_TRUNC}, - {"O_SYNC", PPM_O_SYNC}, - {"O_NONBLOCK", PPM_O_NONBLOCK}, - {"O_EXCL", PPM_O_EXCL}, - {"O_DSYNC", PPM_O_DSYNC}, - {"O_APPEND", PPM_O_APPEND}, - {"O_CREAT", PPM_O_CREAT}, - {"O_RDWR", PPM_O_RDWR}, - {"O_WRONLY", PPM_O_WRONLY}, - {"O_RDONLY", PPM_O_RDONLY}, - {"O_CLOEXEC", PPM_O_CLOEXEC}, - {"O_NONE", PPM_O_NONE}, - {"O_TMPFILE", PPM_O_TMPFILE}, - {"O_F_CREATED", PPM_O_F_CREATED}, - {"FD_UPPER_LAYER", PPM_FD_UPPER_LAYER}, - {"FD_LOWER_LAYER", PPM_FD_LOWER_LAYER}, - {0, 0}, + {"O_LARGEFILE", PPM_O_LARGEFILE}, + {"O_DIRECTORY", PPM_O_DIRECTORY}, + {"O_DIRECT", PPM_O_DIRECT}, + {"O_TRUNC", PPM_O_TRUNC}, + {"O_SYNC", PPM_O_SYNC}, + {"O_NONBLOCK", PPM_O_NONBLOCK}, + {"O_EXCL", PPM_O_EXCL}, + {"O_DSYNC", PPM_O_DSYNC}, + {"O_APPEND", PPM_O_APPEND}, + {"O_CREAT", PPM_O_CREAT}, + {"O_RDWR", PPM_O_RDWR}, + {"O_WRONLY", PPM_O_WRONLY}, + {"O_RDONLY", PPM_O_RDONLY}, + {"O_CLOEXEC", PPM_O_CLOEXEC}, + {"O_NONE", PPM_O_NONE}, + {"O_TMPFILE", PPM_O_TMPFILE}, + {"O_F_CREATED", PPM_O_F_CREATED}, + {"FD_UPPER_LAYER", PPM_FD_UPPER_LAYER}, + {"FD_LOWER_LAYER", PPM_FD_LOWER_LAYER}, + {0, 0}, }; const struct ppm_name_value creat_flags[] = { - {"FD_UPPER_LAYER_CREAT", PPM_FD_UPPER_LAYER_CREAT}, - {"FD_LOWER_LAYER_CREAT", PPM_FD_LOWER_LAYER_CREAT}, - {0, 0}, + {"FD_UPPER_LAYER_CREAT", PPM_FD_UPPER_LAYER_CREAT}, + {"FD_LOWER_LAYER_CREAT", PPM_FD_LOWER_LAYER_CREAT}, + {0, 0}, }; const struct ppm_name_value flock_flags[] = { - {"LOCK_SH", PPM_LOCK_SH}, - {"LOCK_EX", PPM_LOCK_EX}, - {"LOCK_NB", PPM_LOCK_NB}, - {"LOCK_UN", PPM_LOCK_UN}, - {"LOCK_NONE", PPM_LOCK_NONE}, - {0, 0}, + {"LOCK_SH", PPM_LOCK_SH}, + {"LOCK_EX", PPM_LOCK_EX}, + {"LOCK_NB", PPM_LOCK_NB}, + {"LOCK_UN", PPM_LOCK_UN}, + {"LOCK_NONE", PPM_LOCK_NONE}, + {0, 0}, }; const struct ppm_name_value clone_flags[] = { - {"CLONE_FILES", PPM_CL_CLONE_FILES}, - {"CLONE_FS", PPM_CL_CLONE_FS}, - {"CLONE_IO", PPM_CL_CLONE_IO}, - {"CLONE_NEWIPC", PPM_CL_CLONE_NEWIPC}, - {"CLONE_NEWNET", PPM_CL_CLONE_NEWNET}, - {"CLONE_NEWNS", PPM_CL_CLONE_NEWNS}, - {"CLONE_NEWPID", PPM_CL_CLONE_NEWPID}, - {"CLONE_NEWUTS", PPM_CL_CLONE_NEWUTS}, - {"CLONE_PARENT", PPM_CL_CLONE_PARENT}, - {"CLONE_PARENT_SETTID", PPM_CL_CLONE_PARENT_SETTID}, - {"CLONE_PTRACE", PPM_CL_CLONE_PTRACE}, - {"CLONE_SIGHAND", PPM_CL_CLONE_SIGHAND}, - {"CLONE_SYSVSEM", PPM_CL_CLONE_SYSVSEM}, - {"CLONE_THREAD", PPM_CL_CLONE_THREAD}, - {"CLONE_UNTRACED", PPM_CL_CLONE_UNTRACED}, - {"CLONE_VM", PPM_CL_CLONE_VM}, - {"CLONE_INVERTED", PPM_CL_CLONE_INVERTED}, - {"NAME_CHANGED", PPM_CL_NAME_CHANGED}, - {"CLOSED", PPM_CL_CLOSED}, - {"CLONE_NEWUSER", PPM_CL_CLONE_NEWUSER}, - {"CLONE_CHILD_CLEARTID", PPM_CL_CLONE_CHILD_CLEARTID}, - {"CLONE_CHILD_SETTID", PPM_CL_CLONE_CHILD_SETTID}, - {"CLONE_SETTLS", PPM_CL_CLONE_SETTLS}, - {"CLONE_STOPPED", PPM_CL_CLONE_STOPPED}, - {"CLONE_VFORK", PPM_CL_CLONE_VFORK}, - {"CLONE_NEWCGROUP", PPM_CL_CLONE_NEWCGROUP}, - {0, 0}, + {"CLONE_FILES", PPM_CL_CLONE_FILES}, + {"CLONE_FS", PPM_CL_CLONE_FS}, + {"CLONE_IO", PPM_CL_CLONE_IO}, + {"CLONE_NEWIPC", PPM_CL_CLONE_NEWIPC}, + {"CLONE_NEWNET", PPM_CL_CLONE_NEWNET}, + {"CLONE_NEWNS", PPM_CL_CLONE_NEWNS}, + {"CLONE_NEWPID", PPM_CL_CLONE_NEWPID}, + {"CLONE_NEWUTS", PPM_CL_CLONE_NEWUTS}, + {"CLONE_PARENT", PPM_CL_CLONE_PARENT}, + {"CLONE_PARENT_SETTID", PPM_CL_CLONE_PARENT_SETTID}, + {"CLONE_PTRACE", PPM_CL_CLONE_PTRACE}, + {"CLONE_SIGHAND", PPM_CL_CLONE_SIGHAND}, + {"CLONE_SYSVSEM", PPM_CL_CLONE_SYSVSEM}, + {"CLONE_THREAD", PPM_CL_CLONE_THREAD}, + {"CLONE_UNTRACED", PPM_CL_CLONE_UNTRACED}, + {"CLONE_VM", PPM_CL_CLONE_VM}, + {"CLONE_INVERTED", PPM_CL_CLONE_INVERTED}, + {"NAME_CHANGED", PPM_CL_NAME_CHANGED}, + {"CLOSED", PPM_CL_CLOSED}, + {"CLONE_NEWUSER", PPM_CL_CLONE_NEWUSER}, + {"CLONE_CHILD_CLEARTID", PPM_CL_CLONE_CHILD_CLEARTID}, + {"CLONE_CHILD_SETTID", PPM_CL_CLONE_CHILD_SETTID}, + {"CLONE_SETTLS", PPM_CL_CLONE_SETTLS}, + {"CLONE_STOPPED", PPM_CL_CLONE_STOPPED}, + {"CLONE_VFORK", PPM_CL_CLONE_VFORK}, + {"CLONE_NEWCGROUP", PPM_CL_CLONE_NEWCGROUP}, + {0, 0}, }; const struct ppm_name_value futex_operations[] = { - {"FUTEX_CLOCK_REALTIME", PPM_FU_FUTEX_CLOCK_REALTIME}, - {"FUTEX_PRIVATE_FLAG", PPM_FU_FUTEX_PRIVATE_FLAG}, - {"FUTEX_CMP_REQUEUE_PI", PPM_FU_FUTEX_CMP_REQUEUE_PI}, - {"FUTEX_WAIT_REQUEUE_PI", PPM_FU_FUTEX_WAIT_REQUEUE_PI}, - {"FUTEX_WAKE_BITSET", PPM_FU_FUTEX_WAKE_BITSET}, - {"FUTEX_WAIT_BITSET", PPM_FU_FUTEX_WAIT_BITSET}, - {"FUTEX_TRYLOCK_PI", PPM_FU_FUTEX_TRYLOCK_PI}, - {"FUTEX_UNLOCK_PI", PPM_FU_FUTEX_UNLOCK_PI}, - {"FUTEX_LOCK_PI", PPM_FU_FUTEX_LOCK_PI}, - {"FUTEX_WAKE_OP", PPM_FU_FUTEX_WAKE_OP}, - {"FUTEX_CMP_REQUEUE", PPM_FU_FUTEX_CMP_REQUEUE}, - {"FUTEX_REQUEUE", PPM_FU_FUTEX_REQUEUE}, - {"FUTEX_FD", PPM_FU_FUTEX_FD}, - {"FUTEX_WAKE", PPM_FU_FUTEX_WAKE}, - {"FUTEX_WAIT", PPM_FU_FUTEX_WAIT}, - {0, 0}, + {"FUTEX_CLOCK_REALTIME", PPM_FU_FUTEX_CLOCK_REALTIME}, + {"FUTEX_PRIVATE_FLAG", PPM_FU_FUTEX_PRIVATE_FLAG}, + {"FUTEX_CMP_REQUEUE_PI", PPM_FU_FUTEX_CMP_REQUEUE_PI}, + {"FUTEX_WAIT_REQUEUE_PI", PPM_FU_FUTEX_WAIT_REQUEUE_PI}, + {"FUTEX_WAKE_BITSET", PPM_FU_FUTEX_WAKE_BITSET}, + {"FUTEX_WAIT_BITSET", PPM_FU_FUTEX_WAIT_BITSET}, + {"FUTEX_TRYLOCK_PI", PPM_FU_FUTEX_TRYLOCK_PI}, + {"FUTEX_UNLOCK_PI", PPM_FU_FUTEX_UNLOCK_PI}, + {"FUTEX_LOCK_PI", PPM_FU_FUTEX_LOCK_PI}, + {"FUTEX_WAKE_OP", PPM_FU_FUTEX_WAKE_OP}, + {"FUTEX_CMP_REQUEUE", PPM_FU_FUTEX_CMP_REQUEUE}, + {"FUTEX_REQUEUE", PPM_FU_FUTEX_REQUEUE}, + {"FUTEX_FD", PPM_FU_FUTEX_FD}, + {"FUTEX_WAKE", PPM_FU_FUTEX_WAKE}, + {"FUTEX_WAIT", PPM_FU_FUTEX_WAIT}, + {0, 0}, }; const struct ppm_name_value poll_flags[] = { - {"POLLIN", PPM_POLLIN}, - {"POLLPRI", PPM_POLLPRI}, - {"POLLOUT", PPM_POLLOUT}, - {"POLLRDHUP", PPM_POLLRDHUP}, - {"POLLERR", PPM_POLLERR}, - {"POLLHUP", PPM_POLLHUP}, - {"POLLNVAL", PPM_POLLNVAL}, - {"POLLRDNORM", PPM_POLLRDNORM}, - {"POLLRDBAND", PPM_POLLRDBAND}, - {"POLLWRNORM", PPM_POLLWRNORM}, - {"POLLWRBAND", PPM_POLLWRBAND}, - {0, 0}, + {"POLLIN", PPM_POLLIN}, + {"POLLPRI", PPM_POLLPRI}, + {"POLLOUT", PPM_POLLOUT}, + {"POLLRDHUP", PPM_POLLRDHUP}, + {"POLLERR", PPM_POLLERR}, + {"POLLHUP", PPM_POLLHUP}, + {"POLLNVAL", PPM_POLLNVAL}, + {"POLLRDNORM", PPM_POLLRDNORM}, + {"POLLRDBAND", PPM_POLLRDBAND}, + {"POLLWRNORM", PPM_POLLWRNORM}, + {"POLLWRBAND", PPM_POLLWRBAND}, + {0, 0}, }; /* http://lxr.free-electrons.com/source/include/uapi/linux/fs.h?v=4.2#L65 */ const struct ppm_name_value mount_flags[] = { - {"RDONLY", PPM_MS_RDONLY}, - {"NOSUID", PPM_MS_NOSUID}, - {"NODEV", PPM_MS_NODEV}, - {"NOEXEC", PPM_MS_NOEXEC}, - {"SYNCHRONOUS", PPM_MS_SYNCHRONOUS}, - {"REMOUNT", PPM_MS_REMOUNT}, - {"MANDLOCK", PPM_MS_MANDLOCK}, - {"DIRSYNC", PPM_MS_DIRSYNC}, - {"NOATIME", PPM_MS_NOATIME}, - {"NODIRATIME", PPM_MS_NODIRATIME}, - {"BIND", PPM_MS_BIND}, - {"MOVE", PPM_MS_MOVE}, - {"REC", PPM_MS_REC}, - {"SILENT", PPM_MS_SILENT}, - {"POSIXACL", PPM_MS_POSIXACL}, - {"UNBINDABLE", PPM_MS_UNBINDABLE}, - {"PRIVATE", PPM_MS_PRIVATE}, - {"SLAVE", PPM_MS_SLAVE}, - {"SHARED", PPM_MS_SHARED}, - {"RELATIME", PPM_MS_RELATIME}, - {"KERNMOUNT", PPM_MS_KERNMOUNT}, - {"I_VERSION", PPM_MS_I_VERSION}, - {"STRICTATIME", PPM_MS_STRICTATIME}, - {"LAZYTIME", PPM_MS_LAZYTIME}, - {"NOSEC", PPM_MS_NOSEC}, - {"BORN", PPM_MS_BORN}, - {"ACTIVE", PPM_MS_ACTIVE}, - {"NOUSER", PPM_MS_NOUSER}, // NOTE: we are at 1 << 31 -> and we have an uint32_t value. - {0, 0}, + {"RDONLY", PPM_MS_RDONLY}, + {"NOSUID", PPM_MS_NOSUID}, + {"NODEV", PPM_MS_NODEV}, + {"NOEXEC", PPM_MS_NOEXEC}, + {"SYNCHRONOUS", PPM_MS_SYNCHRONOUS}, + {"REMOUNT", PPM_MS_REMOUNT}, + {"MANDLOCK", PPM_MS_MANDLOCK}, + {"DIRSYNC", PPM_MS_DIRSYNC}, + {"NOATIME", PPM_MS_NOATIME}, + {"NODIRATIME", PPM_MS_NODIRATIME}, + {"BIND", PPM_MS_BIND}, + {"MOVE", PPM_MS_MOVE}, + {"REC", PPM_MS_REC}, + {"SILENT", PPM_MS_SILENT}, + {"POSIXACL", PPM_MS_POSIXACL}, + {"UNBINDABLE", PPM_MS_UNBINDABLE}, + {"PRIVATE", PPM_MS_PRIVATE}, + {"SLAVE", PPM_MS_SLAVE}, + {"SHARED", PPM_MS_SHARED}, + {"RELATIME", PPM_MS_RELATIME}, + {"KERNMOUNT", PPM_MS_KERNMOUNT}, + {"I_VERSION", PPM_MS_I_VERSION}, + {"STRICTATIME", PPM_MS_STRICTATIME}, + {"LAZYTIME", PPM_MS_LAZYTIME}, + {"NOSEC", PPM_MS_NOSEC}, + {"BORN", PPM_MS_BORN}, + {"ACTIVE", PPM_MS_ACTIVE}, + {"NOUSER", PPM_MS_NOUSER}, // NOTE: we are at 1 << 31 -> and we have an uint32_t value. + {0, 0}, }; /* There is a 1:1 mapping between `umount2` flags and our `PPM` notation, so we don't * need a dedicated helper for the conversion. */ const struct ppm_name_value umount_flags[] = { - {"FORCE", PPM_MNT_FORCE}, - {"DETACH", PPM_MNT_DETACH}, - {"EXPIRE", PPM_MNT_EXPIRE}, - {"NOFOLLOW", PPM_UMOUNT_NOFOLLOW}, - {0, 0}, + {"FORCE", PPM_MNT_FORCE}, + {"DETACH", PPM_MNT_DETACH}, + {"EXPIRE", PPM_MNT_EXPIRE}, + {"NOFOLLOW", PPM_UMOUNT_NOFOLLOW}, + {0, 0}, }; const struct ppm_name_value lseek_whence[] = { - {"SEEK_END", PPM_SEEK_END}, - {"SEEK_CUR", PPM_SEEK_CUR}, - {"SEEK_SET", PPM_SEEK_SET}, - {0, 0}, + {"SEEK_END", PPM_SEEK_END}, + {"SEEK_CUR", PPM_SEEK_CUR}, + {"SEEK_SET", PPM_SEEK_SET}, + {0, 0}, }; const struct ppm_name_value shutdown_how[] = { - {"SHUT_UNKNOWN", PPM_SHUT_UNKNOWN}, - {"SHUT_RDWR", PPM_SHUT_RDWR}, - {"SHUT_WR", PPM_SHUT_WR}, - {"SHUT_RD", PPM_SHUT_RD}, - {0, 0}, + {"SHUT_UNKNOWN", PPM_SHUT_UNKNOWN}, + {"SHUT_RDWR", PPM_SHUT_RDWR}, + {"SHUT_WR", PPM_SHUT_WR}, + {"SHUT_RD", PPM_SHUT_RD}, + {0, 0}, }; const struct ppm_name_value rlimit_resources[] = { - {"RLIMIT_UNKNOWN", PPM_RLIMIT_UNKNOWN}, - {"RLIMIT_RTTIME", PPM_RLIMIT_RTTIME}, - {"RLIMIT_RTPRIO", PPM_RLIMIT_RTPRIO}, - {"RLIMIT_NICE", PPM_RLIMIT_NICE}, - {"RLIMIT_MSGQUEUE", PPM_RLIMIT_MSGQUEUE}, - {"RLIMIT_SIGPENDING", PPM_RLIMIT_SIGPENDING}, - {"RLIMIT_LOCKS", PPM_RLIMIT_LOCKS}, - {"RLIMIT_AS", PPM_RLIMIT_AS}, - {"RLIMIT_MEMLOCK", PPM_RLIMIT_MEMLOCK}, - {"RLIMIT_NOFILE", PPM_RLIMIT_NOFILE}, - {"RLIMIT_NPROC", PPM_RLIMIT_NPROC}, - {"RLIMIT_RSS", PPM_RLIMIT_RSS}, - {"RLIMIT_CORE", PPM_RLIMIT_CORE}, - {"RLIMIT_STACK", PPM_RLIMIT_STACK}, - {"RLIMIT_DATA", PPM_RLIMIT_DATA}, - {"RLIMIT_FSIZE", PPM_RLIMIT_FSIZE}, - {"RLIMIT_CPU", PPM_RLIMIT_CPU}, - {0, 0}, + {"RLIMIT_UNKNOWN", PPM_RLIMIT_UNKNOWN}, + {"RLIMIT_RTTIME", PPM_RLIMIT_RTTIME}, + {"RLIMIT_RTPRIO", PPM_RLIMIT_RTPRIO}, + {"RLIMIT_NICE", PPM_RLIMIT_NICE}, + {"RLIMIT_MSGQUEUE", PPM_RLIMIT_MSGQUEUE}, + {"RLIMIT_SIGPENDING", PPM_RLIMIT_SIGPENDING}, + {"RLIMIT_LOCKS", PPM_RLIMIT_LOCKS}, + {"RLIMIT_AS", PPM_RLIMIT_AS}, + {"RLIMIT_MEMLOCK", PPM_RLIMIT_MEMLOCK}, + {"RLIMIT_NOFILE", PPM_RLIMIT_NOFILE}, + {"RLIMIT_NPROC", PPM_RLIMIT_NPROC}, + {"RLIMIT_RSS", PPM_RLIMIT_RSS}, + {"RLIMIT_CORE", PPM_RLIMIT_CORE}, + {"RLIMIT_STACK", PPM_RLIMIT_STACK}, + {"RLIMIT_DATA", PPM_RLIMIT_DATA}, + {"RLIMIT_FSIZE", PPM_RLIMIT_FSIZE}, + {"RLIMIT_CPU", PPM_RLIMIT_CPU}, + {0, 0}, }; const struct ppm_name_value fcntl_commands[] = { - {"F_GETPIPE_SZ", PPM_FCNTL_F_GETPIPE_SZ}, - {"F_SETPIPE_SZ", PPM_FCNTL_F_SETPIPE_SZ}, - {"F_NOTIFY", PPM_FCNTL_F_NOTIFY}, - {"F_DUPFD_CLOEXEC", PPM_FCNTL_F_DUPFD_CLOEXEC}, - {"F_CANCELLK", PPM_FCNTL_F_CANCELLK}, - {"F_GETLEASE", PPM_FCNTL_F_GETLEASE}, - {"F_SETLEASE", PPM_FCNTL_F_SETLEASE}, - {"F_GETOWN_EX", PPM_FCNTL_F_GETOWN_EX}, - {"F_SETOWN_EX", PPM_FCNTL_F_SETOWN_EX}, + {"F_GETPIPE_SZ", PPM_FCNTL_F_GETPIPE_SZ}, + {"F_SETPIPE_SZ", PPM_FCNTL_F_SETPIPE_SZ}, + {"F_NOTIFY", PPM_FCNTL_F_NOTIFY}, + {"F_DUPFD_CLOEXEC", PPM_FCNTL_F_DUPFD_CLOEXEC}, + {"F_CANCELLK", PPM_FCNTL_F_CANCELLK}, + {"F_GETLEASE", PPM_FCNTL_F_GETLEASE}, + {"F_SETLEASE", PPM_FCNTL_F_SETLEASE}, + {"F_GETOWN_EX", PPM_FCNTL_F_GETOWN_EX}, + {"F_SETOWN_EX", PPM_FCNTL_F_SETOWN_EX}, #ifndef CONFIG_64BIT - {"F_SETLKW64", PPM_FCNTL_F_SETLKW64}, - {"F_SETLK64", PPM_FCNTL_F_SETLK64}, - {"F_GETLK64", PPM_FCNTL_F_GETLK64}, + {"F_SETLKW64", PPM_FCNTL_F_SETLKW64}, + {"F_SETLK64", PPM_FCNTL_F_SETLK64}, + {"F_GETLK64", PPM_FCNTL_F_GETLK64}, #endif - {"F_GETSIG", PPM_FCNTL_F_GETSIG}, - {"F_SETSIG", PPM_FCNTL_F_SETSIG}, - {"F_GETOWN", PPM_FCNTL_F_GETOWN}, - {"F_SETOWN", PPM_FCNTL_F_SETOWN}, - {"F_SETLKW", PPM_FCNTL_F_SETLKW}, - {"F_SETLK", PPM_FCNTL_F_SETLK}, - {"F_GETLK", PPM_FCNTL_F_GETLK}, - {"F_SETFL", PPM_FCNTL_F_SETFL}, - {"F_GETFL", PPM_FCNTL_F_GETFL}, - {"F_SETFD", PPM_FCNTL_F_SETFD}, - {"F_GETFD", PPM_FCNTL_F_GETFD}, - {"F_DUPFD", PPM_FCNTL_F_DUPFD}, - {"F_OFD_GETLK", PPM_FCNTL_F_OFD_GETLK}, - {"F_OFD_SETLK", PPM_FCNTL_F_OFD_SETLK}, - {"F_OFD_SETLKW", PPM_FCNTL_F_OFD_SETLKW}, - {"UNKNOWN", PPM_FCNTL_UNKNOWN}, - {0, 0}, + {"F_GETSIG", PPM_FCNTL_F_GETSIG}, + {"F_SETSIG", PPM_FCNTL_F_SETSIG}, + {"F_GETOWN", PPM_FCNTL_F_GETOWN}, + {"F_SETOWN", PPM_FCNTL_F_SETOWN}, + {"F_SETLKW", PPM_FCNTL_F_SETLKW}, + {"F_SETLK", PPM_FCNTL_F_SETLK}, + {"F_GETLK", PPM_FCNTL_F_GETLK}, + {"F_SETFL", PPM_FCNTL_F_SETFL}, + {"F_GETFL", PPM_FCNTL_F_GETFL}, + {"F_SETFD", PPM_FCNTL_F_SETFD}, + {"F_GETFD", PPM_FCNTL_F_GETFD}, + {"F_DUPFD", PPM_FCNTL_F_DUPFD}, + {"F_OFD_GETLK", PPM_FCNTL_F_OFD_GETLK}, + {"F_OFD_SETLK", PPM_FCNTL_F_OFD_SETLK}, + {"F_OFD_SETLKW", PPM_FCNTL_F_OFD_SETLKW}, + {"UNKNOWN", PPM_FCNTL_UNKNOWN}, + {0, 0}, }; const struct ppm_name_value sockopt_levels[] = { - {"SOL_SOCKET", PPM_SOCKOPT_LEVEL_SOL_SOCKET}, - {"SOL_TCP", PPM_SOCKOPT_LEVEL_SOL_TCP}, - {"UNKNOWN", PPM_SOCKOPT_LEVEL_UNKNOWN}, - {0, 0}, + {"SOL_SOCKET", PPM_SOCKOPT_LEVEL_SOL_SOCKET}, + {"SOL_TCP", PPM_SOCKOPT_LEVEL_SOL_TCP}, + {"UNKNOWN", PPM_SOCKOPT_LEVEL_UNKNOWN}, + {0, 0}, }; const struct ppm_name_value sockopt_options[] = { - {"SO_COOKIE", PPM_SOCKOPT_SO_COOKIE}, - {"SO_MEMINFO", PPM_SOCKOPT_SO_MEMINFO}, - {"SO_PEERGROUPS", PPM_SOCKOPT_SO_PEERGROUPS}, - {"SO_ATTACH_BPF", PPM_SOCKOPT_SO_ATTACH_BPF}, - {"SO_INCOMING_CPU", PPM_SOCKOPT_SO_INCOMING_CPU}, - {"SO_BPF_EXTENSIONS", PPM_SOCKOPT_SO_BPF_EXTENSIONS}, - {"SO_MAX_PACING_RATE", PPM_SOCKOPT_SO_MAX_PACING_RATE}, - {"SO_BUSY_POLL", PPM_SOCKOPT_SO_BUSY_POLL}, - {"SO_SELECT_ERR_QUEUE", PPM_SOCKOPT_SO_SELECT_ERR_QUEUE}, - {"SO_LOCK_FILTER", PPM_SOCKOPT_SO_LOCK_FILTER}, - {"SO_NOFCS", PPM_SOCKOPT_SO_NOFCS}, - {"SO_PEEK_OFF", PPM_SOCKOPT_SO_PEEK_OFF}, - {"SO_WIFI_STATUS", PPM_SOCKOPT_SO_WIFI_STATUS}, - {"SO_RXQ_OVFL", PPM_SOCKOPT_SO_RXQ_OVFL}, - {"SO_DOMAIN", PPM_SOCKOPT_SO_DOMAIN}, - {"SO_PROTOCOL", PPM_SOCKOPT_SO_PROTOCOL}, - {"SO_TIMESTAMPING", PPM_SOCKOPT_SO_TIMESTAMPING}, - {"SO_MARK", PPM_SOCKOPT_SO_MARK}, - {"SO_TIMESTAMPNS", PPM_SOCKOPT_SO_TIMESTAMPNS}, - {"SO_PASSSEC", PPM_SOCKOPT_SO_PASSSEC}, - {"SO_PEERSEC", PPM_SOCKOPT_SO_PEERSEC}, - {"SO_ACCEPTCONN", PPM_SOCKOPT_SO_ACCEPTCONN}, - {"SO_TIMESTAMP", PPM_SOCKOPT_SO_TIMESTAMP}, - {"SO_PEERNAME", PPM_SOCKOPT_SO_PEERNAME}, - {"SO_DETACH_FILTER", PPM_SOCKOPT_SO_DETACH_FILTER}, - {"SO_ATTACH_FILTER", PPM_SOCKOPT_SO_ATTACH_FILTER}, - {"SO_BINDTODEVICE", PPM_SOCKOPT_SO_BINDTODEVICE}, - {"SO_SECURITY_ENCRYPTION_NETWORK", PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_NETWORK}, - {"SO_SECURITY_ENCRYPTION_TRANSPORT", PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_TRANSPORT}, - {"SO_SECURITY_AUTHENTICATION", PPM_SOCKOPT_SO_SECURITY_AUTHENTICATION}, - {"SO_SNDTIMEO", PPM_SOCKOPT_SO_SNDTIMEO}, - {"SO_RCVTIMEO", PPM_SOCKOPT_SO_RCVTIMEO}, - {"SO_SNDLOWAT", PPM_SOCKOPT_SO_SNDLOWAT}, - {"SO_RCVLOWAT", PPM_SOCKOPT_SO_RCVLOWAT}, - {"SO_PEERCRED", PPM_SOCKOPT_SO_PEERCRED}, - {"SO_PASSCRED", PPM_SOCKOPT_SO_PASSCRED}, - {"SO_REUSEPORT", PPM_SOCKOPT_SO_REUSEPORT}, - {"SO_BSDCOMPAT", PPM_SOCKOPT_SO_BSDCOMPAT}, - {"SO_LINGER", PPM_SOCKOPT_SO_LINGER}, - {"SO_PRIORITY", PPM_SOCKOPT_SO_PRIORITY}, - {"SO_NO_CHECK", PPM_SOCKOPT_SO_NO_CHECK}, - {"SO_OOBINLINE", PPM_SOCKOPT_SO_OOBINLINE}, - {"SO_KEEPALIVE", PPM_SOCKOPT_SO_KEEPALIVE}, - {"SO_RCVBUFFORCE", PPM_SOCKOPT_SO_RCVBUFFORCE}, - {"SO_SNDBUFFORCE", PPM_SOCKOPT_SO_SNDBUFFORCE}, - {"SO_RCVBUF", PPM_SOCKOPT_SO_RCVBUF}, - {"SO_SNDBUF", PPM_SOCKOPT_SO_SNDBUF}, - {"SO_BROADCAST", PPM_SOCKOPT_SO_BROADCAST}, - {"SO_DONTROUTE", PPM_SOCKOPT_SO_DONTROUTE}, - {"SO_ERROR", PPM_SOCKOPT_SO_ERROR}, - {"SO_TYPE", PPM_SOCKOPT_SO_TYPE}, - {"SO_REUSEADDR", PPM_SOCKOPT_SO_REUSEADDR}, - {"SO_DEBUG", PPM_SOCKOPT_SO_DEBUG}, - {"UNKNOWN", PPM_SOCKOPT_UNKNOWN}, - {0, 0}, + {"SO_COOKIE", PPM_SOCKOPT_SO_COOKIE}, + {"SO_MEMINFO", PPM_SOCKOPT_SO_MEMINFO}, + {"SO_PEERGROUPS", PPM_SOCKOPT_SO_PEERGROUPS}, + {"SO_ATTACH_BPF", PPM_SOCKOPT_SO_ATTACH_BPF}, + {"SO_INCOMING_CPU", PPM_SOCKOPT_SO_INCOMING_CPU}, + {"SO_BPF_EXTENSIONS", PPM_SOCKOPT_SO_BPF_EXTENSIONS}, + {"SO_MAX_PACING_RATE", PPM_SOCKOPT_SO_MAX_PACING_RATE}, + {"SO_BUSY_POLL", PPM_SOCKOPT_SO_BUSY_POLL}, + {"SO_SELECT_ERR_QUEUE", PPM_SOCKOPT_SO_SELECT_ERR_QUEUE}, + {"SO_LOCK_FILTER", PPM_SOCKOPT_SO_LOCK_FILTER}, + {"SO_NOFCS", PPM_SOCKOPT_SO_NOFCS}, + {"SO_PEEK_OFF", PPM_SOCKOPT_SO_PEEK_OFF}, + {"SO_WIFI_STATUS", PPM_SOCKOPT_SO_WIFI_STATUS}, + {"SO_RXQ_OVFL", PPM_SOCKOPT_SO_RXQ_OVFL}, + {"SO_DOMAIN", PPM_SOCKOPT_SO_DOMAIN}, + {"SO_PROTOCOL", PPM_SOCKOPT_SO_PROTOCOL}, + {"SO_TIMESTAMPING", PPM_SOCKOPT_SO_TIMESTAMPING}, + {"SO_MARK", PPM_SOCKOPT_SO_MARK}, + {"SO_TIMESTAMPNS", PPM_SOCKOPT_SO_TIMESTAMPNS}, + {"SO_PASSSEC", PPM_SOCKOPT_SO_PASSSEC}, + {"SO_PEERSEC", PPM_SOCKOPT_SO_PEERSEC}, + {"SO_ACCEPTCONN", PPM_SOCKOPT_SO_ACCEPTCONN}, + {"SO_TIMESTAMP", PPM_SOCKOPT_SO_TIMESTAMP}, + {"SO_PEERNAME", PPM_SOCKOPT_SO_PEERNAME}, + {"SO_DETACH_FILTER", PPM_SOCKOPT_SO_DETACH_FILTER}, + {"SO_ATTACH_FILTER", PPM_SOCKOPT_SO_ATTACH_FILTER}, + {"SO_BINDTODEVICE", PPM_SOCKOPT_SO_BINDTODEVICE}, + {"SO_SECURITY_ENCRYPTION_NETWORK", PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_NETWORK}, + {"SO_SECURITY_ENCRYPTION_TRANSPORT", PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_TRANSPORT}, + {"SO_SECURITY_AUTHENTICATION", PPM_SOCKOPT_SO_SECURITY_AUTHENTICATION}, + {"SO_SNDTIMEO", PPM_SOCKOPT_SO_SNDTIMEO}, + {"SO_RCVTIMEO", PPM_SOCKOPT_SO_RCVTIMEO}, + {"SO_SNDLOWAT", PPM_SOCKOPT_SO_SNDLOWAT}, + {"SO_RCVLOWAT", PPM_SOCKOPT_SO_RCVLOWAT}, + {"SO_PEERCRED", PPM_SOCKOPT_SO_PEERCRED}, + {"SO_PASSCRED", PPM_SOCKOPT_SO_PASSCRED}, + {"SO_REUSEPORT", PPM_SOCKOPT_SO_REUSEPORT}, + {"SO_BSDCOMPAT", PPM_SOCKOPT_SO_BSDCOMPAT}, + {"SO_LINGER", PPM_SOCKOPT_SO_LINGER}, + {"SO_PRIORITY", PPM_SOCKOPT_SO_PRIORITY}, + {"SO_NO_CHECK", PPM_SOCKOPT_SO_NO_CHECK}, + {"SO_OOBINLINE", PPM_SOCKOPT_SO_OOBINLINE}, + {"SO_KEEPALIVE", PPM_SOCKOPT_SO_KEEPALIVE}, + {"SO_RCVBUFFORCE", PPM_SOCKOPT_SO_RCVBUFFORCE}, + {"SO_SNDBUFFORCE", PPM_SOCKOPT_SO_SNDBUFFORCE}, + {"SO_RCVBUF", PPM_SOCKOPT_SO_RCVBUF}, + {"SO_SNDBUF", PPM_SOCKOPT_SO_SNDBUF}, + {"SO_BROADCAST", PPM_SOCKOPT_SO_BROADCAST}, + {"SO_DONTROUTE", PPM_SOCKOPT_SO_DONTROUTE}, + {"SO_ERROR", PPM_SOCKOPT_SO_ERROR}, + {"SO_TYPE", PPM_SOCKOPT_SO_TYPE}, + {"SO_REUSEADDR", PPM_SOCKOPT_SO_REUSEADDR}, + {"SO_DEBUG", PPM_SOCKOPT_SO_DEBUG}, + {"UNKNOWN", PPM_SOCKOPT_UNKNOWN}, + {0, 0}, }; const struct ppm_name_value ptrace_requests[] = { - {"PTRACE_SINGLEBLOCK", PPM_PTRACE_SINGLEBLOCK}, - {"PTRACE_SYSEMU_SINGLESTEP", PPM_PTRACE_SYSEMU_SINGLESTEP}, - {"PTRACE_SYSEMU", PPM_PTRACE_SYSEMU}, - {"PTRACE_ARCH_PRCTL", PPM_PTRACE_ARCH_PRCTL}, - {"PTRACE_SET_THREAD_AREA", PPM_PTRACE_SET_THREAD_AREA}, - {"PTRACE_GET_THREAD_AREA", PPM_PTRACE_GET_THREAD_AREA}, - {"PTRACE_OLDSETOPTIONS", PPM_PTRACE_OLDSETOPTIONS}, - {"PTRACE_SETFPXREGS", PPM_PTRACE_SETFPXREGS}, - {"PTRACE_GETFPXREGS", PPM_PTRACE_GETFPXREGS}, - {"PTRACE_SETFPREGS", PPM_PTRACE_SETFPREGS}, - {"PTRACE_GETFPREGS", PPM_PTRACE_GETFPREGS}, - {"PTRACE_SETREGS", PPM_PTRACE_SETREGS}, - {"PTRACE_GETREGS", PPM_PTRACE_GETREGS}, - {"PTRACE_SETSIGMASK", PPM_PTRACE_SETSIGMASK}, - {"PTRACE_GETSIGMASK", PPM_PTRACE_GETSIGMASK}, - {"PTRACE_PEEKSIGINFO", PPM_PTRACE_PEEKSIGINFO}, - {"PTRACE_LISTEN", PPM_PTRACE_LISTEN}, - {"PTRACE_INTERRUPT", PPM_PTRACE_INTERRUPT}, - {"PTRACE_SEIZE", PPM_PTRACE_SEIZE}, - {"PTRACE_SETREGSET", PPM_PTRACE_SETREGSET}, - {"PTRACE_GETREGSET", PPM_PTRACE_GETREGSET}, - {"PTRACE_SETSIGINFO", PPM_PTRACE_SETSIGINFO}, - {"PTRACE_GETSIGINFO", PPM_PTRACE_GETSIGINFO}, - {"PTRACE_GETEVENTMSG", PPM_PTRACE_GETEVENTMSG}, - {"PTRACE_SETOPTIONS", PPM_PTRACE_SETOPTIONS}, - {"PTRACE_SYSCALL", PPM_PTRACE_SYSCALL}, - {"PTRACE_DETACH", PPM_PTRACE_DETACH}, - {"PTRACE_ATTACH", PPM_PTRACE_ATTACH}, - {"PTRACE_SINGLESTEP", PPM_PTRACE_SINGLESTEP}, - {"PTRACE_KILL", PPM_PTRACE_KILL}, - {"PTRACE_CONT", PPM_PTRACE_CONT}, - {"PTRACE_POKEUSR", PPM_PTRACE_POKEUSR}, - {"PTRACE_POKEDATA", PPM_PTRACE_POKEDATA}, - {"PTRACE_POKETEXT", PPM_PTRACE_POKETEXT}, - {"PTRACE_PEEKUSR", PPM_PTRACE_PEEKUSR}, - {"PTRACE_PEEKDATA", PPM_PTRACE_PEEKDATA}, - {"PTRACE_PEEKTEXT", PPM_PTRACE_PEEKTEXT}, - {"PTRACE_TRACEME", PPM_PTRACE_TRACEME}, - {"PTRACE_UNKNOWN", PPM_PTRACE_UNKNOWN}, - {0, 0}, + {"PTRACE_SINGLEBLOCK", PPM_PTRACE_SINGLEBLOCK}, + {"PTRACE_SYSEMU_SINGLESTEP", PPM_PTRACE_SYSEMU_SINGLESTEP}, + {"PTRACE_SYSEMU", PPM_PTRACE_SYSEMU}, + {"PTRACE_ARCH_PRCTL", PPM_PTRACE_ARCH_PRCTL}, + {"PTRACE_SET_THREAD_AREA", PPM_PTRACE_SET_THREAD_AREA}, + {"PTRACE_GET_THREAD_AREA", PPM_PTRACE_GET_THREAD_AREA}, + {"PTRACE_OLDSETOPTIONS", PPM_PTRACE_OLDSETOPTIONS}, + {"PTRACE_SETFPXREGS", PPM_PTRACE_SETFPXREGS}, + {"PTRACE_GETFPXREGS", PPM_PTRACE_GETFPXREGS}, + {"PTRACE_SETFPREGS", PPM_PTRACE_SETFPREGS}, + {"PTRACE_GETFPREGS", PPM_PTRACE_GETFPREGS}, + {"PTRACE_SETREGS", PPM_PTRACE_SETREGS}, + {"PTRACE_GETREGS", PPM_PTRACE_GETREGS}, + {"PTRACE_SETSIGMASK", PPM_PTRACE_SETSIGMASK}, + {"PTRACE_GETSIGMASK", PPM_PTRACE_GETSIGMASK}, + {"PTRACE_PEEKSIGINFO", PPM_PTRACE_PEEKSIGINFO}, + {"PTRACE_LISTEN", PPM_PTRACE_LISTEN}, + {"PTRACE_INTERRUPT", PPM_PTRACE_INTERRUPT}, + {"PTRACE_SEIZE", PPM_PTRACE_SEIZE}, + {"PTRACE_SETREGSET", PPM_PTRACE_SETREGSET}, + {"PTRACE_GETREGSET", PPM_PTRACE_GETREGSET}, + {"PTRACE_SETSIGINFO", PPM_PTRACE_SETSIGINFO}, + {"PTRACE_GETSIGINFO", PPM_PTRACE_GETSIGINFO}, + {"PTRACE_GETEVENTMSG", PPM_PTRACE_GETEVENTMSG}, + {"PTRACE_SETOPTIONS", PPM_PTRACE_SETOPTIONS}, + {"PTRACE_SYSCALL", PPM_PTRACE_SYSCALL}, + {"PTRACE_DETACH", PPM_PTRACE_DETACH}, + {"PTRACE_ATTACH", PPM_PTRACE_ATTACH}, + {"PTRACE_SINGLESTEP", PPM_PTRACE_SINGLESTEP}, + {"PTRACE_KILL", PPM_PTRACE_KILL}, + {"PTRACE_CONT", PPM_PTRACE_CONT}, + {"PTRACE_POKEUSR", PPM_PTRACE_POKEUSR}, + {"PTRACE_POKEDATA", PPM_PTRACE_POKEDATA}, + {"PTRACE_POKETEXT", PPM_PTRACE_POKETEXT}, + {"PTRACE_PEEKUSR", PPM_PTRACE_PEEKUSR}, + {"PTRACE_PEEKDATA", PPM_PTRACE_PEEKDATA}, + {"PTRACE_PEEKTEXT", PPM_PTRACE_PEEKTEXT}, + {"PTRACE_TRACEME", PPM_PTRACE_TRACEME}, + {"PTRACE_UNKNOWN", PPM_PTRACE_UNKNOWN}, + {0, 0}, }; const struct ppm_name_value prot_flags[] = { - {"PROT_READ", PPM_PROT_READ}, - {"PROT_WRITE", PPM_PROT_WRITE}, - {"PROT_EXEC", PPM_PROT_EXEC}, - {"PROT_SEM", PPM_PROT_SEM}, - {"PROT_GROWSDOWN", PPM_PROT_GROWSDOWN}, - {"PROT_GROWSUP", PPM_PROT_GROWSUP}, - {"PROT_SAO", PPM_PROT_SAO}, - {"PROT_NONE", PPM_PROT_NONE}, - {0, 0}, + {"PROT_READ", PPM_PROT_READ}, + {"PROT_WRITE", PPM_PROT_WRITE}, + {"PROT_EXEC", PPM_PROT_EXEC}, + {"PROT_SEM", PPM_PROT_SEM}, + {"PROT_GROWSDOWN", PPM_PROT_GROWSDOWN}, + {"PROT_GROWSUP", PPM_PROT_GROWSUP}, + {"PROT_SAO", PPM_PROT_SAO}, + {"PROT_NONE", PPM_PROT_NONE}, + {0, 0}, }; const struct ppm_name_value mmap_flags[] = { - {"MAP_SHARED", PPM_MAP_SHARED}, - {"MAP_PRIVATE", PPM_MAP_PRIVATE}, - {"MAP_FIXED", PPM_MAP_FIXED}, - {"MAP_ANONYMOUS", PPM_MAP_ANONYMOUS}, - {"MAP_32BIT", PPM_MAP_32BIT}, - {"MAP_RENAME", PPM_MAP_RENAME}, - {"MAP_NORESERVE", PPM_MAP_NORESERVE}, - {"MAP_POPULATE", PPM_MAP_POPULATE}, - {"MAP_NONBLOCK", PPM_MAP_NONBLOCK}, - {"MAP_GROWSDOWN", PPM_MAP_GROWSDOWN}, - {"MAP_DENYWRITE", PPM_MAP_DENYWRITE}, - {"MAP_EXECUTABLE", PPM_MAP_EXECUTABLE}, - {"MAP_INHERIT", PPM_MAP_INHERIT}, - {"MAP_FILE", PPM_MAP_FILE}, - {"MAP_LOCKED", PPM_MAP_LOCKED}, - {0, 0}, + {"MAP_SHARED", PPM_MAP_SHARED}, + {"MAP_PRIVATE", PPM_MAP_PRIVATE}, + {"MAP_FIXED", PPM_MAP_FIXED}, + {"MAP_ANONYMOUS", PPM_MAP_ANONYMOUS}, + {"MAP_32BIT", PPM_MAP_32BIT}, + {"MAP_RENAME", PPM_MAP_RENAME}, + {"MAP_NORESERVE", PPM_MAP_NORESERVE}, + {"MAP_POPULATE", PPM_MAP_POPULATE}, + {"MAP_NONBLOCK", PPM_MAP_NONBLOCK}, + {"MAP_GROWSDOWN", PPM_MAP_GROWSDOWN}, + {"MAP_DENYWRITE", PPM_MAP_DENYWRITE}, + {"MAP_EXECUTABLE", PPM_MAP_EXECUTABLE}, + {"MAP_INHERIT", PPM_MAP_INHERIT}, + {"MAP_FILE", PPM_MAP_FILE}, + {"MAP_LOCKED", PPM_MAP_LOCKED}, + {0, 0}, }; const struct ppm_name_value splice_flags[] = { - {"SPLICE_F_MOVE", PPM_SPLICE_F_MOVE}, - {"SPLICE_F_NONBLOCK", PPM_SPLICE_F_NONBLOCK}, - {"SPLICE_F_MORE", PPM_SPLICE_F_MORE}, - {"SPLICE_F_GIFT", PPM_SPLICE_F_GIFT}, - {0, 0}, + {"SPLICE_F_MOVE", PPM_SPLICE_F_MOVE}, + {"SPLICE_F_NONBLOCK", PPM_SPLICE_F_NONBLOCK}, + {"SPLICE_F_MORE", PPM_SPLICE_F_MORE}, + {"SPLICE_F_GIFT", PPM_SPLICE_F_GIFT}, + {0, 0}, }; const struct ppm_name_value quotactl_dqi_flags[] = { - {"DQF_NONE", PPM_DQF_NONE}, - {"V1_DQF_RSQUASH", PPM_V1_DQF_RSQUASH}, - {0, 0}, + {"DQF_NONE", PPM_DQF_NONE}, + {"V1_DQF_RSQUASH", PPM_V1_DQF_RSQUASH}, + {0, 0}, }; const struct ppm_name_value quotactl_cmds[] = { - {"Q_QUOTAON", PPM_Q_QUOTAON}, - {"Q_QUOTAOFF", PPM_Q_QUOTAOFF}, - {"Q_GETFMT", PPM_Q_GETFMT}, - {"Q_GETINFO", PPM_Q_GETINFO}, - {"Q_SETINFO", PPM_Q_SETINFO}, - {"Q_GETQUOTA", PPM_Q_GETQUOTA}, - {"Q_SETQUOTA", PPM_Q_SETQUOTA}, - {"Q_SYNC", PPM_Q_SYNC}, - {"Q_XQUOTAON", PPM_Q_XQUOTAON}, - {"Q_XQUOTAOFF", PPM_Q_XQUOTAOFF}, - {"Q_XGETQUOTA", PPM_Q_XGETQUOTA}, - {"Q_XSETQLIM", PPM_Q_XSETQLIM}, - {"Q_XGETQSTAT", PPM_Q_XGETQSTAT}, - {"Q_XQUOTARM", PPM_Q_XQUOTARM}, - {"Q_XQUOTASYNC", PPM_Q_XQUOTASYNC}, - {0, 0}, + {"Q_QUOTAON", PPM_Q_QUOTAON}, + {"Q_QUOTAOFF", PPM_Q_QUOTAOFF}, + {"Q_GETFMT", PPM_Q_GETFMT}, + {"Q_GETINFO", PPM_Q_GETINFO}, + {"Q_SETINFO", PPM_Q_SETINFO}, + {"Q_GETQUOTA", PPM_Q_GETQUOTA}, + {"Q_SETQUOTA", PPM_Q_SETQUOTA}, + {"Q_SYNC", PPM_Q_SYNC}, + {"Q_XQUOTAON", PPM_Q_XQUOTAON}, + {"Q_XQUOTAOFF", PPM_Q_XQUOTAOFF}, + {"Q_XGETQUOTA", PPM_Q_XGETQUOTA}, + {"Q_XSETQLIM", PPM_Q_XSETQLIM}, + {"Q_XGETQSTAT", PPM_Q_XGETQSTAT}, + {"Q_XQUOTARM", PPM_Q_XQUOTARM}, + {"Q_XQUOTASYNC", PPM_Q_XQUOTASYNC}, + {0, 0}, }; const struct ppm_name_value quotactl_types[] = { - {"USRQUOTA", PPM_USRQUOTA}, - {"GRPQUOTA", PPM_GRPQUOTA}, - {0, 0}, + {"USRQUOTA", PPM_USRQUOTA}, + {"GRPQUOTA", PPM_GRPQUOTA}, + {0, 0}, }; const struct ppm_name_value quotactl_quota_fmts[] = { - {"QFMT_NOT_USED", PPM_QFMT_NOT_USED}, - {"QFMT_VFS_OLD", PPM_QFMT_VFS_OLD}, - {"QFMT_VFS_V0", PPM_QFMT_VFS_V0}, - {"QFMT_VFS_V1", PPM_QFMT_VFS_V1}, - {0, 0}, + {"QFMT_NOT_USED", PPM_QFMT_NOT_USED}, + {"QFMT_VFS_OLD", PPM_QFMT_VFS_OLD}, + {"QFMT_VFS_V0", PPM_QFMT_VFS_V0}, + {"QFMT_VFS_V1", PPM_QFMT_VFS_V1}, + {0, 0}, }; const struct ppm_name_value semop_flags[] = { - {"IPC_NOWAIT", PPM_IPC_NOWAIT}, - {"SEM_UNDO", PPM_SEM_UNDO}, - {0, 0}, + {"IPC_NOWAIT", PPM_IPC_NOWAIT}, + {"SEM_UNDO", PPM_SEM_UNDO}, + {0, 0}, }; const struct ppm_name_value semget_flags[] = { - {"IPC_EXCL", PPM_IPC_EXCL}, - {"IPC_CREAT", PPM_IPC_CREAT}, - {0, 0}, + {"IPC_EXCL", PPM_IPC_EXCL}, + {"IPC_CREAT", PPM_IPC_CREAT}, + {0, 0}, }; const struct ppm_name_value semctl_commands[] = { - {"IPC_STAT", PPM_IPC_STAT}, - {"IPC_SET", PPM_IPC_SET}, - {"IPC_RMID", PPM_IPC_RMID}, - {"IPC_INFO", PPM_IPC_INFO}, - {"SEM_INFO", PPM_SEM_INFO}, - {"SEM_STAT", PPM_SEM_STAT}, - {"GETALL", PPM_GETALL}, - {"GETNCNT", PPM_GETNCNT}, - {"GETPID", PPM_GETPID}, - {"GETVAL", PPM_GETVAL}, - {"GETZCNT", PPM_GETZCNT}, - {"SETALL", PPM_SETALL}, - {"SETVAL", PPM_SETVAL}, - {0, 0}, + {"IPC_STAT", PPM_IPC_STAT}, + {"IPC_SET", PPM_IPC_SET}, + {"IPC_RMID", PPM_IPC_RMID}, + {"IPC_INFO", PPM_IPC_INFO}, + {"SEM_INFO", PPM_SEM_INFO}, + {"SEM_STAT", PPM_SEM_STAT}, + {"GETALL", PPM_GETALL}, + {"GETNCNT", PPM_GETNCNT}, + {"GETPID", PPM_GETPID}, + {"GETVAL", PPM_GETVAL}, + {"GETZCNT", PPM_GETZCNT}, + {"SETALL", PPM_SETALL}, + {"SETVAL", PPM_SETVAL}, + {0, 0}, }; const struct ppm_name_value access_flags[] = { - {"F_OK", PPM_F_OK}, - {"R_OK", PPM_R_OK}, - {"W_OK", PPM_W_OK}, - {"X_OK", PPM_X_OK}, - {0, 0}, + {"F_OK", PPM_F_OK}, + {"R_OK", PPM_R_OK}, + {"W_OK", PPM_W_OK}, + {"X_OK", PPM_X_OK}, + {0, 0}, }; const struct ppm_name_value pf_flags[] = { - {"PROTECTION_VIOLATION", PPM_PF_PROTECTION_VIOLATION}, - {"PAGE_NOT_PRESENT", PPM_PF_PAGE_NOT_PRESENT}, - {"WRITE_ACCESS", PPM_PF_WRITE_ACCESS}, - {"READ_ACCESS", PPM_PF_READ_ACCESS}, - {"USER_FAULT", PPM_PF_USER_FAULT}, - {"SUPERVISOR_FAULT", PPM_PF_SUPERVISOR_FAULT}, - {"RESERVED_PAGE", PPM_PF_RESERVED_PAGE}, - {"INSTRUCTION_FETCH", PPM_PF_INSTRUCTION_FETCH}, - {0, 0}, + {"PROTECTION_VIOLATION", PPM_PF_PROTECTION_VIOLATION}, + {"PAGE_NOT_PRESENT", PPM_PF_PAGE_NOT_PRESENT}, + {"WRITE_ACCESS", PPM_PF_WRITE_ACCESS}, + {"READ_ACCESS", PPM_PF_READ_ACCESS}, + {"USER_FAULT", PPM_PF_USER_FAULT}, + {"SUPERVISOR_FAULT", PPM_PF_SUPERVISOR_FAULT}, + {"RESERVED_PAGE", PPM_PF_RESERVED_PAGE}, + {"INSTRUCTION_FETCH", PPM_PF_INSTRUCTION_FETCH}, + {0, 0}, }; const struct ppm_name_value unlinkat_flags[] = { - {"AT_REMOVEDIR", PPM_AT_REMOVEDIR}, - {0, 0}, + {"AT_REMOVEDIR", PPM_AT_REMOVEDIR}, + {0, 0}, }; const struct ppm_name_value linkat_flags[] = { - {"AT_SYMLINK_FOLLOW", PPM_AT_SYMLINK_FOLLOW}, - {"AT_EMPTY_PATH", PPM_AT_EMPTY_PATH}, - {0, 0}, + {"AT_SYMLINK_FOLLOW", PPM_AT_SYMLINK_FOLLOW}, + {"AT_EMPTY_PATH", PPM_AT_EMPTY_PATH}, + {0, 0}, }; const struct ppm_name_value newfstatat_flags[] = { - {"AT_EMPTY_PATH", PPM_AT_EMPTY_PATH}, - {"AT_NO_AUTOMOUNT", PPM_AT_NO_AUTOMOUNT}, - {"AT_SYMLINK_NOFOLLOW", PPM_AT_SYMLINK_NOFOLLOW}, - {0, 0}, + {"AT_EMPTY_PATH", PPM_AT_EMPTY_PATH}, + {"AT_NO_AUTOMOUNT", PPM_AT_NO_AUTOMOUNT}, + {"AT_SYMLINK_NOFOLLOW", PPM_AT_SYMLINK_NOFOLLOW}, + {0, 0}, }; const struct ppm_name_value chmod_mode[] = { - {"S_IXOTH", PPM_S_IXOTH}, - {"S_IWOTH", PPM_S_IWOTH}, - {"S_IROTH", PPM_S_IROTH}, - {"S_IXGRP", PPM_S_IXGRP}, - {"S_IWGRP", PPM_S_IWGRP}, - {"S_IRGRP", PPM_S_IRGRP}, - {"S_IXUSR", PPM_S_IXUSR}, - {"S_IWUSR", PPM_S_IWUSR}, - {"S_IRUSR", PPM_S_IRUSR}, - {"S_ISVTX", PPM_S_ISVTX}, - {"S_ISGID", PPM_S_ISGID}, - {"S_ISUID", PPM_S_ISUID}, - {0, 0}, + {"S_IXOTH", PPM_S_IXOTH}, + {"S_IWOTH", PPM_S_IWOTH}, + {"S_IROTH", PPM_S_IROTH}, + {"S_IXGRP", PPM_S_IXGRP}, + {"S_IWGRP", PPM_S_IWGRP}, + {"S_IRGRP", PPM_S_IRGRP}, + {"S_IXUSR", PPM_S_IXUSR}, + {"S_IWUSR", PPM_S_IWUSR}, + {"S_IRUSR", PPM_S_IRUSR}, + {"S_ISVTX", PPM_S_ISVTX}, + {"S_ISGID", PPM_S_ISGID}, + {"S_ISUID", PPM_S_ISUID}, + {0, 0}, }; const struct ppm_name_value fchownat_flags[] = { - {"AT_SYMLINK_NOFOLLOW", PPM_AT_SYMLINK_FOLLOW}, - {"AT_EMPTY_PATH", PPM_AT_EMPTY_PATH}, - {0, 0}, + {"AT_SYMLINK_NOFOLLOW", PPM_AT_SYMLINK_FOLLOW}, + {"AT_EMPTY_PATH", PPM_AT_EMPTY_PATH}, + {0, 0}, }; const struct ppm_name_value renameat2_flags[] = { - {"RENAME_NOREPLACE", PPM_RENAME_NOREPLACE}, - {"RENAME_EXCHANGE", PPM_RENAME_EXCHANGE}, - {"RENAME_WHITEOUT", PPM_RENAME_WHITEOUT}, - {0, 0}, + {"RENAME_NOREPLACE", PPM_RENAME_NOREPLACE}, + {"RENAME_EXCHANGE", PPM_RENAME_EXCHANGE}, + {"RENAME_WHITEOUT", PPM_RENAME_WHITEOUT}, + {0, 0}, }; const struct ppm_name_value openat2_flags[] = { - {"RESOLVE_BENEATH", PPM_RESOLVE_BENEATH}, - {"RESOLVE_IN_ROOT", PPM_RESOLVE_IN_ROOT}, - {"RESOLVE_NO_MAGICLINKS", PPM_RESOLVE_NO_MAGICLINKS}, - {"RESOLVE_NO_SYMLINKS", PPM_RESOLVE_NO_SYMLINKS}, - {"RESOLVE_NO_XDEV", PPM_RESOLVE_NO_XDEV}, - {"RESOLVE_CACHED", PPM_RESOLVE_CACHED}, - {0, 0}, + {"RESOLVE_BENEATH", PPM_RESOLVE_BENEATH}, + {"RESOLVE_IN_ROOT", PPM_RESOLVE_IN_ROOT}, + {"RESOLVE_NO_MAGICLINKS", PPM_RESOLVE_NO_MAGICLINKS}, + {"RESOLVE_NO_SYMLINKS", PPM_RESOLVE_NO_SYMLINKS}, + {"RESOLVE_NO_XDEV", PPM_RESOLVE_NO_XDEV}, + {"RESOLVE_CACHED", PPM_RESOLVE_CACHED}, + {0, 0}, }; const struct ppm_name_value execve_flags[] = { - {"EXE_WRITABLE", PPM_EXE_WRITABLE}, - {"EXE_UPPER_LAYER", PPM_EXE_UPPER_LAYER}, - {"EXE_FROM_MEMFD", PPM_EXE_FROM_MEMFD}, - {"EXE_LOWER_LAYER", PPM_EXE_LOWER_LAYER}, - {0, 0}, + {"EXE_WRITABLE", PPM_EXE_WRITABLE}, + {"EXE_UPPER_LAYER", PPM_EXE_UPPER_LAYER}, + {"EXE_FROM_MEMFD", PPM_EXE_FROM_MEMFD}, + {"EXE_LOWER_LAYER", PPM_EXE_LOWER_LAYER}, + {0, 0}, }; const struct ppm_name_value execveat_flags[] = { - {"AT_EMPTY_PATH", PPM_EXVAT_AT_EMPTY_PATH}, - {"AT_SYMLINK_NOFOLLOW", PPM_EXVAT_AT_SYMLINK_NOFOLLOW}, - {0, 0}, + {"AT_EMPTY_PATH", PPM_EXVAT_AT_EMPTY_PATH}, + {"AT_SYMLINK_NOFOLLOW", PPM_EXVAT_AT_SYMLINK_NOFOLLOW}, + {0, 0}, }; const struct ppm_name_value io_uring_setup_flags[] = { - {"IORING_SETUP_IOPOLL", PPM_IORING_SETUP_IOPOLL}, - {"IORING_SETUP_SQPOLL", PPM_IORING_SETUP_SQPOLL}, - {"IORING_SQ_NEED_WAKEUP", PPM_IORING_SQ_NEED_WAKEUP}, - {"IORING_SETUP_SQ_AFF", PPM_IORING_SETUP_SQ_AFF}, - {"IORING_SETUP_CQSIZE", PPM_IORING_SETUP_CQSIZE}, - {"IORING_SETUP_CLAMP", PPM_IORING_SETUP_CLAMP}, - {"IORING_SETUP_ATTACH_RW", PPM_IORING_SETUP_ATTACH_WQ}, - {"IORING_SETUP_R_DISABLED", PPM_IORING_SETUP_R_DISABLED}, - {0,0}, + {"IORING_SETUP_IOPOLL", PPM_IORING_SETUP_IOPOLL}, + {"IORING_SETUP_SQPOLL", PPM_IORING_SETUP_SQPOLL}, + {"IORING_SQ_NEED_WAKEUP", PPM_IORING_SQ_NEED_WAKEUP}, + {"IORING_SETUP_SQ_AFF", PPM_IORING_SETUP_SQ_AFF}, + {"IORING_SETUP_CQSIZE", PPM_IORING_SETUP_CQSIZE}, + {"IORING_SETUP_CLAMP", PPM_IORING_SETUP_CLAMP}, + {"IORING_SETUP_ATTACH_RW", PPM_IORING_SETUP_ATTACH_WQ}, + {"IORING_SETUP_R_DISABLED", PPM_IORING_SETUP_R_DISABLED}, + {0, 0}, }; const struct ppm_name_value io_uring_setup_feats[] = { - {"IORING_FEAT_SINGLE_MMAP",PPM_IORING_FEAT_SINGLE_MMAP}, - {"IORING_FEAT_NODROP", PPM_IORING_FEAT_NODROP}, - {"IORING_FEAT_SUBMIT_STABLE", PPM_IORING_FEAT_SUBMIT_STABLE}, - {"IORING_FEAT_RW_CUR_POS", PPM_IORING_FEAT_RW_CUR_POS}, - {"IORING_FEAT_CUR_PERSONALITY", PPM_IORING_FEAT_CUR_PERSONALITY}, - {"IORING_FEAT_FAST_POLL", PPM_IORING_FEAT_FAST_POLL}, - {"IORING_FEAT_POLL_32BITS", PPM_IORING_FEAT_POLL_32BITS}, - {"IORING_FEAT_SQPOLL_NONFIXED", PPM_IORING_FEAT_SQPOLL_NONFIXED}, - {"IORING_FEAT_ENTER_EXT_ARG", PPM_IORING_FEAT_ENTER_EXT_ARG}, - {"IORING_FEAT_NATIVE_WORKERS", PPM_IORING_FEAT_NATIVE_WORKERS}, - {"IORING_FEAT_RSRC_TAGS", PPM_IORING_FEAT_RSRC_TAGS}, - {0,0}, + {"IORING_FEAT_SINGLE_MMAP", PPM_IORING_FEAT_SINGLE_MMAP}, + {"IORING_FEAT_NODROP", PPM_IORING_FEAT_NODROP}, + {"IORING_FEAT_SUBMIT_STABLE", PPM_IORING_FEAT_SUBMIT_STABLE}, + {"IORING_FEAT_RW_CUR_POS", PPM_IORING_FEAT_RW_CUR_POS}, + {"IORING_FEAT_CUR_PERSONALITY", PPM_IORING_FEAT_CUR_PERSONALITY}, + {"IORING_FEAT_FAST_POLL", PPM_IORING_FEAT_FAST_POLL}, + {"IORING_FEAT_POLL_32BITS", PPM_IORING_FEAT_POLL_32BITS}, + {"IORING_FEAT_SQPOLL_NONFIXED", PPM_IORING_FEAT_SQPOLL_NONFIXED}, + {"IORING_FEAT_ENTER_EXT_ARG", PPM_IORING_FEAT_ENTER_EXT_ARG}, + {"IORING_FEAT_NATIVE_WORKERS", PPM_IORING_FEAT_NATIVE_WORKERS}, + {"IORING_FEAT_RSRC_TAGS", PPM_IORING_FEAT_RSRC_TAGS}, + {0, 0}, }; const struct ppm_name_value io_uring_enter_flags[] = { - {"IORING_ENTER_GETEVENTS", PPM_IORING_ENTER_GETEVENTS}, - {"IORING_ENTER_SQ_WAKEUP", PPM_IORING_ENTER_SQ_WAKEUP}, - {"IORING_ENTER_SQ_WAIT", PPM_IORING_ENTER_SQ_WAIT}, - {"IORING_ENTER_EXT_ARG", PPM_IORING_ENTER_EXT_ARG}, - {0,0}, + {"IORING_ENTER_GETEVENTS", PPM_IORING_ENTER_GETEVENTS}, + {"IORING_ENTER_SQ_WAKEUP", PPM_IORING_ENTER_SQ_WAKEUP}, + {"IORING_ENTER_SQ_WAIT", PPM_IORING_ENTER_SQ_WAIT}, + {"IORING_ENTER_EXT_ARG", PPM_IORING_ENTER_EXT_ARG}, + {0, 0}, }; const struct ppm_name_value io_uring_register_opcodes[] = { - {"IORING_REGISTER_BUFFERS", PPM_IORING_REGISTER_BUFFERS}, - {"IORING_UNREGISTER_BUFFERS",PPM_IORING_UNREGISTER_BUFFERS}, - {"IORING_REGISTER_FILES",PPM_IORING_REGISTER_FILES}, - {"IORING_UNREGISTER_FILES", PPM_IORING_UNREGISTER_FILES}, - {"IORING_REGISTER_EVENTFD", PPM_IORING_REGISTER_EVENTFD}, - {"IORING_UNREGISTER_EVENTFD", PPM_IORING_UNREGISTER_EVENTFD}, - {"IORING_REGISTER_FILES_UPDATE", PPM_IORING_REGISTER_FILES_UPDATE}, - {"IORING_REGISTER_EVENTFD_ASYNC", PPM_IORING_REGISTER_EVENTFD_ASYNC}, - {"IORING_REGISTER_PROBE", PPM_IORING_REGISTER_PROBE}, - {"IORING_REGISTER_PERSONALITY", PPM_IORING_REGISTER_PERSONALITY}, - {"IORING_UNREGISTER_PERSONALITY", PPM_IORING_UNREGISTER_PERSONALITY}, - {"IORING_REGISTER_RESTRICTIONS", PPM_IORING_REGISTER_RESTRICTIONS}, - {"IORING_REGISTER_ENABLE_RINGS", PPM_IORING_REGISTER_ENABLE_RINGS}, - {"IORING_REGISTER_FILES2", PPM_IORING_REGISTER_FILES2}, - {"IORING_REGISTER_FILES_UPDATE2", PPM_IORING_REGISTER_FILES_UPDATE2}, - {"IORING_REGISTER_BUFFERS2", PPM_IORING_REGISTER_BUFFERS2}, - {"IORING_REGISTER_BUFFERS_UPDATE", PPM_IORING_REGISTER_BUFFERS_UPDATE}, - {"IORING_REGISTER_IOWQ_AFF", PPM_IORING_REGISTER_IOWQ_AFF}, - {"IORING_UNREGISTER_IOWQ_AFF", PPM_IORING_UNREGISTER_IOWQ_AFF}, - {"IORING_REGISTER_IOWQ_MAX_WORKERS", PPM_IORING_REGISTER_IOWQ_MAX_WORKERS}, - {"IORING_REGISTER_RING_FDS", PPM_IORING_REGISTER_RING_FDS}, - {"IORING_UNREGISTER_RING_FDS", PPM_IORING_UNREGISTER_RING_FDS}, - {0, 0} -}; + {"IORING_REGISTER_BUFFERS", PPM_IORING_REGISTER_BUFFERS}, + {"IORING_UNREGISTER_BUFFERS", PPM_IORING_UNREGISTER_BUFFERS}, + {"IORING_REGISTER_FILES", PPM_IORING_REGISTER_FILES}, + {"IORING_UNREGISTER_FILES", PPM_IORING_UNREGISTER_FILES}, + {"IORING_REGISTER_EVENTFD", PPM_IORING_REGISTER_EVENTFD}, + {"IORING_UNREGISTER_EVENTFD", PPM_IORING_UNREGISTER_EVENTFD}, + {"IORING_REGISTER_FILES_UPDATE", PPM_IORING_REGISTER_FILES_UPDATE}, + {"IORING_REGISTER_EVENTFD_ASYNC", PPM_IORING_REGISTER_EVENTFD_ASYNC}, + {"IORING_REGISTER_PROBE", PPM_IORING_REGISTER_PROBE}, + {"IORING_REGISTER_PERSONALITY", PPM_IORING_REGISTER_PERSONALITY}, + {"IORING_UNREGISTER_PERSONALITY", PPM_IORING_UNREGISTER_PERSONALITY}, + {"IORING_REGISTER_RESTRICTIONS", PPM_IORING_REGISTER_RESTRICTIONS}, + {"IORING_REGISTER_ENABLE_RINGS", PPM_IORING_REGISTER_ENABLE_RINGS}, + {"IORING_REGISTER_FILES2", PPM_IORING_REGISTER_FILES2}, + {"IORING_REGISTER_FILES_UPDATE2", PPM_IORING_REGISTER_FILES_UPDATE2}, + {"IORING_REGISTER_BUFFERS2", PPM_IORING_REGISTER_BUFFERS2}, + {"IORING_REGISTER_BUFFERS_UPDATE", PPM_IORING_REGISTER_BUFFERS_UPDATE}, + {"IORING_REGISTER_IOWQ_AFF", PPM_IORING_REGISTER_IOWQ_AFF}, + {"IORING_UNREGISTER_IOWQ_AFF", PPM_IORING_UNREGISTER_IOWQ_AFF}, + {"IORING_REGISTER_IOWQ_MAX_WORKERS", PPM_IORING_REGISTER_IOWQ_MAX_WORKERS}, + {"IORING_REGISTER_RING_FDS", PPM_IORING_REGISTER_RING_FDS}, + {"IORING_UNREGISTER_RING_FDS", PPM_IORING_UNREGISTER_RING_FDS}, + {0, 0}}; const struct ppm_name_value mlockall_flags[] = { - {"MCL_CURRENT", PPM_MLOCKALL_MCL_CURRENT}, - {"MCL_FUTURE", PPM_MLOCKALL_MCL_FUTURE}, - {"MCL_ONFAULT", PPM_MLOCKALL_MCL_ONFAULT}, - {0,0}, + {"MCL_CURRENT", PPM_MLOCKALL_MCL_CURRENT}, + {"MCL_FUTURE", PPM_MLOCKALL_MCL_FUTURE}, + {"MCL_ONFAULT", PPM_MLOCKALL_MCL_ONFAULT}, + {0, 0}, }; const struct ppm_name_value mlock2_flags[] = { - {"MLOCK_ONFAULT", PPM_MLOCK_ONFAULT}, - {0,0}, + {"MLOCK_ONFAULT", PPM_MLOCK_ONFAULT}, + {0, 0}, }; const struct ppm_name_value fsconfig_cmds[] = { - {"FSCONFIG_SET_FLAG", PPM_FSCONFIG_SET_FLAG}, - {"FSCONFIG_SET_STRING", PPM_FSCONFIG_SET_STRING}, - {"FSCONFIG_SET_BINARY", PPM_FSCONFIG_SET_BINARY}, - {"FSCONFIG_SET_PATH", PPM_FSCONFIG_SET_PATH}, - {"FSCONFIG_SET_PATH_EMPTY", PPM_FSCONFIG_SET_PATH_EMPTY}, - {"FSCONFIG_SET_FD", PPM_FSCONFIG_SET_FD}, - {"FSCONFIG_CMD_CREATE", PPM_FSCONFIG_CMD_CREATE}, - {"FSCONFIG_CMD_RECONFIGURE", PPM_FSCONFIG_CMD_RECONFIGURE}, - {0, 0}, + {"FSCONFIG_SET_FLAG", PPM_FSCONFIG_SET_FLAG}, + {"FSCONFIG_SET_STRING", PPM_FSCONFIG_SET_STRING}, + {"FSCONFIG_SET_BINARY", PPM_FSCONFIG_SET_BINARY}, + {"FSCONFIG_SET_PATH", PPM_FSCONFIG_SET_PATH}, + {"FSCONFIG_SET_PATH_EMPTY", PPM_FSCONFIG_SET_PATH_EMPTY}, + {"FSCONFIG_SET_FD", PPM_FSCONFIG_SET_FD}, + {"FSCONFIG_CMD_CREATE", PPM_FSCONFIG_CMD_CREATE}, + {"FSCONFIG_CMD_RECONFIGURE", PPM_FSCONFIG_CMD_RECONFIGURE}, + {0, 0}, }; const struct ppm_name_value epoll_create1_flags[] = { - {"EPOLL_CLOEXEC", PPM_EPOLL_CLOEXEC}, - {0, 0}, + {"EPOLL_CLOEXEC", PPM_EPOLL_CLOEXEC}, + {0, 0}, }; const struct ppm_name_value prctl_options[] = { - {"PR_GET_DUMPABLE",PPM_PR_GET_DUMPABLE}, - {"PR_SET_DUMPABLE",PPM_PR_SET_DUMPABLE}, - {"PR_GET_KEEPCAPS",PPM_PR_GET_KEEPCAPS}, - {"PR_SET_KEEPCAPS",PPM_PR_SET_KEEPCAPS}, - {"PR_SET_NAME",PPM_PR_SET_NAME}, - {"PR_GET_NAME",PPM_PR_GET_NAME}, - {"PR_GET_SECCOMP",PPM_PR_GET_SECCOMP}, - {"PR_SET_SECCOMP",PPM_PR_SET_SECCOMP}, - {"PR_CAPBSET_READ",PPM_PR_CAPBSET_READ}, - {"PR_CAPBSET_DROP",PPM_PR_CAPBSET_DROP}, - {"PR_GET_SECUREBITS",PPM_PR_GET_SECUREBITS}, - {"PR_SET_SECUREBITS",PPM_PR_SET_SECUREBITS}, - {"PR_MCE_KILL",PPM_PR_MCE_KILL}, - {"PR_MCE_KILL",PPM_PR_MCE_KILL}, - {"PR_SET_MM",PPM_PR_SET_MM}, - {"PR_SET_CHILD_SUBREAPER",PPM_PR_SET_CHILD_SUBREAPER}, - {"PR_GET_CHILD_SUBREAPER",PPM_PR_GET_CHILD_SUBREAPER}, - {"PR_SET_NO_NEW_PRIVS",PPM_PR_SET_NO_NEW_PRIVS}, - {"PR_GET_NO_NEW_PRIVS",PPM_PR_GET_NO_NEW_PRIVS}, - {"PR_GET_TID_ADDRESS",PPM_PR_GET_TID_ADDRESS}, - {"PR_SET_THP_DISABLE",PPM_PR_SET_THP_DISABLE}, - {"PR_GET_THP_DISABLE",PPM_PR_GET_THP_DISABLE}, - {"PR_CAP_AMBIENT",PPM_PR_CAP_AMBIENT}, - {0, 0}, + {"PR_GET_DUMPABLE", PPM_PR_GET_DUMPABLE}, + {"PR_SET_DUMPABLE", PPM_PR_SET_DUMPABLE}, + {"PR_GET_KEEPCAPS", PPM_PR_GET_KEEPCAPS}, + {"PR_SET_KEEPCAPS", PPM_PR_SET_KEEPCAPS}, + {"PR_SET_NAME", PPM_PR_SET_NAME}, + {"PR_GET_NAME", PPM_PR_GET_NAME}, + {"PR_GET_SECCOMP", PPM_PR_GET_SECCOMP}, + {"PR_SET_SECCOMP", PPM_PR_SET_SECCOMP}, + {"PR_CAPBSET_READ", PPM_PR_CAPBSET_READ}, + {"PR_CAPBSET_DROP", PPM_PR_CAPBSET_DROP}, + {"PR_GET_SECUREBITS", PPM_PR_GET_SECUREBITS}, + {"PR_SET_SECUREBITS", PPM_PR_SET_SECUREBITS}, + {"PR_MCE_KILL", PPM_PR_MCE_KILL}, + {"PR_MCE_KILL", PPM_PR_MCE_KILL}, + {"PR_SET_MM", PPM_PR_SET_MM}, + {"PR_SET_CHILD_SUBREAPER", PPM_PR_SET_CHILD_SUBREAPER}, + {"PR_GET_CHILD_SUBREAPER", PPM_PR_GET_CHILD_SUBREAPER}, + {"PR_SET_NO_NEW_PRIVS", PPM_PR_SET_NO_NEW_PRIVS}, + {"PR_GET_NO_NEW_PRIVS", PPM_PR_GET_NO_NEW_PRIVS}, + {"PR_GET_TID_ADDRESS", PPM_PR_GET_TID_ADDRESS}, + {"PR_SET_THP_DISABLE", PPM_PR_SET_THP_DISABLE}, + {"PR_GET_THP_DISABLE", PPM_PR_GET_THP_DISABLE}, + {"PR_CAP_AMBIENT", PPM_PR_CAP_AMBIENT}, + {0, 0}, }; const struct ppm_name_value memfd_create_flags[] = { - {"MFD_CLOEXEC",PPM_MFD_CLOEXEC}, - {"MFD_ALLOW_SEALING",PPM_MFD_ALLOW_SEALING}, - {"MFD_HUGETLB",PPM_MFD_HUGETLB}, - {0,0}, + {"MFD_CLOEXEC", PPM_MFD_CLOEXEC}, + {"MFD_ALLOW_SEALING", PPM_MFD_ALLOW_SEALING}, + {"MFD_HUGETLB", PPM_MFD_HUGETLB}, + {0, 0}, }; const struct ppm_name_value pidfd_open_flags[] = { - {"PIDFD_NONBLOCK", PPM_PIDFD_NONBLOCK}, - {0,0}, + {"PIDFD_NONBLOCK", PPM_PIDFD_NONBLOCK}, + {0, 0}, }; const struct ppm_name_value mknod_mode[] = { - {"S_IXOTH", PPM_S_IXOTH}, - {"S_IWOTH", PPM_S_IWOTH}, - {"S_IROTH", PPM_S_IROTH}, - {"S_IXGRP", PPM_S_IXGRP}, - {"S_IWGRP", PPM_S_IWGRP}, - {"S_IRGRP", PPM_S_IRGRP}, - {"S_IXUSR", PPM_S_IXUSR}, - {"S_IWUSR", PPM_S_IWUSR}, - {"S_IRUSR", PPM_S_IRUSR}, - {"S_ISVTX", PPM_S_ISVTX}, - {"S_ISGID", PPM_S_ISGID}, - {"S_ISUID", PPM_S_ISUID}, - {"S_IFREG", PPM_S_IFREG}, - {"S_IFCHR", PPM_S_IFCHR}, - {"S_IFBLK", PPM_S_IFBLK}, - {"S_IFIFO", PPM_S_IFIFO}, - {"S_IFSOCK", PPM_S_IFSOCK}, - {0, 0}, + {"S_IXOTH", PPM_S_IXOTH}, + {"S_IWOTH", PPM_S_IWOTH}, + {"S_IROTH", PPM_S_IROTH}, + {"S_IXGRP", PPM_S_IXGRP}, + {"S_IWGRP", PPM_S_IWGRP}, + {"S_IRGRP", PPM_S_IRGRP}, + {"S_IXUSR", PPM_S_IXUSR}, + {"S_IWUSR", PPM_S_IWUSR}, + {"S_IRUSR", PPM_S_IRUSR}, + {"S_ISVTX", PPM_S_ISVTX}, + {"S_ISGID", PPM_S_ISGID}, + {"S_ISUID", PPM_S_ISUID}, + {"S_IFREG", PPM_S_IFREG}, + {"S_IFCHR", PPM_S_IFCHR}, + {"S_IFBLK", PPM_S_IFBLK}, + {"S_IFIFO", PPM_S_IFIFO}, + {"S_IFSOCK", PPM_S_IFSOCK}, + {0, 0}, }; const struct ppm_name_value bpf_commands[] = { - {"BPF_MAP_CREATE", PPM_BPF_MAP_CREATE}, - {"BPF_MAP_LOOKUP_ELEM", PPM_BPF_MAP_LOOKUP_ELEM}, - {"BPF_MAP_UPDATE_ELEM", PPM_BPF_MAP_UPDATE_ELEM}, - {"BPF_MAP_DELETE_ELEM", PPM_BPF_MAP_DELETE_ELEM}, - {"BPF_MAP_GET_NEXT_KEY", PPM_BPF_MAP_GET_NEXT_KEY}, - {"BPF_PROG_LOAD", PPM_BPF_PROG_LOAD}, - {"BPF_OBJ_PIN", PPM_BPF_OBJ_PIN}, - {"BPF_OBJ_GET", PPM_BPF_OBJ_GET}, - {"BPF_PROG_ATTACH", PPM_BPF_PROG_ATTACH}, - {"BPF_PROG_DETACH", PPM_BPF_PROG_DETACH}, - {"BPF_PROG_TEST_RUN", PPM_BPF_PROG_TEST_RUN}, - {"BPF_PROG_RUN", PPM_BPF_PROG_RUN}, - {"BPF_PROG_GET_NEXT_ID", PPM_BPF_PROG_GET_NEXT_ID}, - {"BPF_MAP_GET_NEXT_ID", PPM_BPF_MAP_GET_NEXT_ID}, - {"BPF_PROG_GET_FD_BY_ID", PPM_BPF_PROG_GET_FD_BY_ID}, - {"BPF_MAP_GET_FD_BY_ID", PPM_BPF_MAP_GET_FD_BY_ID}, - {"BPF_OBJ_GET_INFO_BY_FD", PPM_BPF_OBJ_GET_INFO_BY_FD}, - {"BPF_PROG_QUERY", PPM_BPF_PROG_QUERY}, - {"BPF_RAW_TRACEPOINT_OPEN", PPM_BPF_RAW_TRACEPOINT_OPEN}, - {"BPF_BTF_LOAD", PPM_BPF_BTF_LOAD}, - {"BPF_BTF_GET_FD_BY_ID", PPM_BPF_BTF_GET_FD_BY_ID}, - {"BPF_TASK_FD_QUERY", PPM_BPF_TASK_FD_QUERY}, - {"BPF_MAP_LOOKUP_AND_DELETE_ELEM", PPM_BPF_MAP_LOOKUP_AND_DELETE_ELEM}, - {"BPF_MAP_FREEZE", PPM_BPF_MAP_FREEZE}, - {"BPF_BTF_GET_NEXT_ID", PPM_BPF_BTF_GET_NEXT_ID}, - {"BPF_MAP_LOOKUP_BATCH", PPM_BPF_MAP_LOOKUP_BATCH}, - {"BPF_MAP_LOOKUP_AND_DELETE_BATCH", PPM_BPF_MAP_LOOKUP_AND_DELETE_BATCH}, - {"BPF_MAP_UPDATE_BATCH", PPM_BPF_MAP_UPDATE_BATCH}, - {"BPF_MAP_DELETE_BATCH", PPM_BPF_MAP_DELETE_BATCH}, - {"BPF_LINK_CREATE", PPM_BPF_LINK_CREATE}, - {"BPF_LINK_UPDATE", PPM_BPF_LINK_UPDATE}, - {"BPF_LINK_GET_FD_BY_ID", PPM_BPF_LINK_GET_FD_BY_ID}, - {"BPF_LINK_GET_NEXT_ID", PPM_BPF_LINK_GET_NEXT_ID}, - {"BPF_ENABLE_STATS", PPM_BPF_ENABLE_STATS}, - {"BPF_ITER_CREATE", PPM_BPF_ITER_CREATE}, - {"BPF_LINK_DETACH", PPM_BPF_LINK_DETACH}, - {"BPF_PROG_BIND_MAP", PPM_BPF_PROG_BIND_MAP}, - {0,0}, + {"BPF_MAP_CREATE", PPM_BPF_MAP_CREATE}, + {"BPF_MAP_LOOKUP_ELEM", PPM_BPF_MAP_LOOKUP_ELEM}, + {"BPF_MAP_UPDATE_ELEM", PPM_BPF_MAP_UPDATE_ELEM}, + {"BPF_MAP_DELETE_ELEM", PPM_BPF_MAP_DELETE_ELEM}, + {"BPF_MAP_GET_NEXT_KEY", PPM_BPF_MAP_GET_NEXT_KEY}, + {"BPF_PROG_LOAD", PPM_BPF_PROG_LOAD}, + {"BPF_OBJ_PIN", PPM_BPF_OBJ_PIN}, + {"BPF_OBJ_GET", PPM_BPF_OBJ_GET}, + {"BPF_PROG_ATTACH", PPM_BPF_PROG_ATTACH}, + {"BPF_PROG_DETACH", PPM_BPF_PROG_DETACH}, + {"BPF_PROG_TEST_RUN", PPM_BPF_PROG_TEST_RUN}, + {"BPF_PROG_RUN", PPM_BPF_PROG_RUN}, + {"BPF_PROG_GET_NEXT_ID", PPM_BPF_PROG_GET_NEXT_ID}, + {"BPF_MAP_GET_NEXT_ID", PPM_BPF_MAP_GET_NEXT_ID}, + {"BPF_PROG_GET_FD_BY_ID", PPM_BPF_PROG_GET_FD_BY_ID}, + {"BPF_MAP_GET_FD_BY_ID", PPM_BPF_MAP_GET_FD_BY_ID}, + {"BPF_OBJ_GET_INFO_BY_FD", PPM_BPF_OBJ_GET_INFO_BY_FD}, + {"BPF_PROG_QUERY", PPM_BPF_PROG_QUERY}, + {"BPF_RAW_TRACEPOINT_OPEN", PPM_BPF_RAW_TRACEPOINT_OPEN}, + {"BPF_BTF_LOAD", PPM_BPF_BTF_LOAD}, + {"BPF_BTF_GET_FD_BY_ID", PPM_BPF_BTF_GET_FD_BY_ID}, + {"BPF_TASK_FD_QUERY", PPM_BPF_TASK_FD_QUERY}, + {"BPF_MAP_LOOKUP_AND_DELETE_ELEM", PPM_BPF_MAP_LOOKUP_AND_DELETE_ELEM}, + {"BPF_MAP_FREEZE", PPM_BPF_MAP_FREEZE}, + {"BPF_BTF_GET_NEXT_ID", PPM_BPF_BTF_GET_NEXT_ID}, + {"BPF_MAP_LOOKUP_BATCH", PPM_BPF_MAP_LOOKUP_BATCH}, + {"BPF_MAP_LOOKUP_AND_DELETE_BATCH", PPM_BPF_MAP_LOOKUP_AND_DELETE_BATCH}, + {"BPF_MAP_UPDATE_BATCH", PPM_BPF_MAP_UPDATE_BATCH}, + {"BPF_MAP_DELETE_BATCH", PPM_BPF_MAP_DELETE_BATCH}, + {"BPF_LINK_CREATE", PPM_BPF_LINK_CREATE}, + {"BPF_LINK_UPDATE", PPM_BPF_LINK_UPDATE}, + {"BPF_LINK_GET_FD_BY_ID", PPM_BPF_LINK_GET_FD_BY_ID}, + {"BPF_LINK_GET_NEXT_ID", PPM_BPF_LINK_GET_NEXT_ID}, + {"BPF_ENABLE_STATS", PPM_BPF_ENABLE_STATS}, + {"BPF_ITER_CREATE", PPM_BPF_ITER_CREATE}, + {"BPF_LINK_DETACH", PPM_BPF_LINK_DETACH}, + {"BPF_PROG_BIND_MAP", PPM_BPF_PROG_BIND_MAP}, + {0, 0}, }; const struct ppm_name_value delete_module_flags[] = { - {"O_NONBLOCK", PPM_DELETE_MODULE_O_NONBLOCK}, - {"O_TRUNC", PPM_DELETE_MODULE_O_TRUNC}, - {0, 0}, + {"O_NONBLOCK", PPM_DELETE_MODULE_O_NONBLOCK}, + {"O_TRUNC", PPM_DELETE_MODULE_O_TRUNC}, + {0, 0}, }; const struct ppm_name_value finit_module_flags[] = { - {"MODULE_INIT_IGNORE_MODVERSIONS", PPM_MODULE_INIT_IGNORE_MODVERSIONS}, - {"MODULE_INIT_IGNORE_VERMAGIC", PPM_MODULE_INIT_IGNORE_VERMAGIC}, - {"MODULE_INIT_COMPRESSED_FILE", PPM_MODULE_INIT_COMPRESSED_FILE}, - {0, 0}, + {"MODULE_INIT_IGNORE_MODVERSIONS", PPM_MODULE_INIT_IGNORE_MODVERSIONS}, + {"MODULE_INIT_IGNORE_VERMAGIC", PPM_MODULE_INIT_IGNORE_VERMAGIC}, + {"MODULE_INIT_COMPRESSED_FILE", PPM_MODULE_INIT_COMPRESSED_FILE}, + {0, 0}, }; diff --git a/driver/kernel_hacks.h b/driver/kernel_hacks.h index faacb52904..a0a1e0ebf4 100644 --- a/driver/kernel_hacks.h +++ b/driver/kernel_hacks.h @@ -17,8 +17,7 @@ /* probe_kernel_read() only added in kernel 2.6.26, name changed in 5.8.0 */ #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26) -static inline long copy_from_kernel_nofault(void *dst, const void *src, size_t size) -{ +static inline long copy_from_kernel_nofault(void *dst, const void *src, size_t size) { long ret; mm_segment_t old_fs = get_fs(); @@ -34,7 +33,6 @@ static inline long copy_from_kernel_nofault(void *dst, const void *src, size_t s #define copy_from_kernel_nofault probe_kernel_read #endif - /* * Linux 5.6 kernels no longer include the old 32-bit timeval * structures. But the syscalls (might) still use them. @@ -60,13 +58,12 @@ struct timeval { #endif #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 9, 0) -static inline struct inode *file_inode(struct file *f) -{ +static inline struct inode *file_inode(struct file *f) { return f->f_path.dentry->d_inode; } #endif -#define syscall_get_arguments_deprecated(_args, _start, _len, _out) \ - do { \ - memcpy(_out, &_args->args[_start], _len * sizeof(unsigned long)); \ +#define syscall_get_arguments_deprecated(_args, _start, _len, _out) \ + do { \ + memcpy(_out, &_args->args[_start], _len * sizeof(unsigned long)); \ } while(0) diff --git a/driver/main.c b/driver/main.c index 258fb8348d..9d4cea6381 100644 --- a/driver/main.c +++ b/driver/main.c @@ -8,13 +8,13 @@ or GPL2.txt for full copies of the license. */ -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include #include #include -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 37)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 37)) #include #else #include @@ -25,7 +25,7 @@ or GPL2.txt for full copies of the license. #include #include #include -#if (LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0)) #include #else #include @@ -36,7 +36,7 @@ or GPL2.txt for full copies of the license. #include #include #include -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)) #include #else #include @@ -60,21 +60,21 @@ MODULE_LICENSE("Dual MIT/GPL"); MODULE_AUTHOR("the Falco authors"); #if defined(CAPTURE_SCHED_PROC_EXEC) && (LINUX_VERSION_CODE < KERNEL_VERSION(3, 4, 0)) - #error The kernel module CAPTURE_SCHED_PROC_EXEC support requires kernel versions greater or equal than '3.4'. +#error The kernel module CAPTURE_SCHED_PROC_EXEC support requires kernel versions greater or equal than '3.4'. #endif #if defined(CAPTURE_SCHED_PROC_FORK) && (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 0)) - #error The kernel module CAPTURE_SCHED_PROC_FORK support requires kernel versions greater or equal than '2.6'. +#error The kernel module CAPTURE_SCHED_PROC_FORK support requires kernel versions greater or equal than '2.6'. #endif -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 35)) - #define TRACEPOINT_PROBE_REGISTER(p1, p2) tracepoint_probe_register(p1, p2) - #define TRACEPOINT_PROBE_UNREGISTER(p1, p2) tracepoint_probe_unregister(p1, p2) - #define TRACEPOINT_PROBE(probe, args...) static void probe(args) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 35)) +#define TRACEPOINT_PROBE_REGISTER(p1, p2) tracepoint_probe_register(p1, p2) +#define TRACEPOINT_PROBE_UNREGISTER(p1, p2) tracepoint_probe_unregister(p1, p2) +#define TRACEPOINT_PROBE(probe, args...) static void probe(args) #else - #define TRACEPOINT_PROBE_REGISTER(p1, p2) tracepoint_probe_register(p1, p2, NULL) - #define TRACEPOINT_PROBE_UNREGISTER(p1, p2) tracepoint_probe_unregister(p1, p2, NULL) - #define TRACEPOINT_PROBE(probe, args...) static void probe(void *__data, args) +#define TRACEPOINT_PROBE_REGISTER(p1, p2) tracepoint_probe_register(p1, p2, NULL) +#define TRACEPOINT_PROBE_UNREGISTER(p1, p2) tracepoint_probe_unregister(p1, p2, NULL) +#define TRACEPOINT_PROBE(probe, args...) static void probe(void *__data, args) #endif // Allow build even on arch where PAGE_ENC is not implemented @@ -99,7 +99,8 @@ struct event_data_t { /* We need this when we preload syscall params */ bool extract_socketcall_params; // notify record_event_consumer that it must skip syscalls of interest check. - // used when we were not able to extract a syscall_id from socketcall; instead we extracted a PPME event as a fallback. + // used when we were not able to extract a syscall_id from socketcall; instead we extracted a + // PPME event as a fallback. bool deny_syscalls_filtering; union { struct { @@ -147,32 +148,38 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, enum syscall_flags drop_flags, nanoseconds ns, struct event_data_t *event_datap, - kmod_prog_codes tp_type); + kmod_prog_codes tp_type); static void record_event_all_consumers(ppm_event_code event_type, enum syscall_flags drop_flags, struct event_data_t *event_datap, - kmod_prog_codes tp_type); + kmod_prog_codes tp_type); static int init_ring_buffer(struct ppm_ring_buffer_context *ring, unsigned long buffer_bytes_dim); static void free_ring_buffer(struct ppm_ring_buffer_context *ring); static void reset_ring_buffer(struct ppm_ring_buffer_context *ring); -#if (LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st); #endif #ifndef CONFIG_HAVE_SYSCALL_TRACEPOINTS - #error The kernel must have HAVE_SYSCALL_TRACEPOINTS in order to work +#error The kernel must have HAVE_SYSCALL_TRACEPOINTS in order to work #endif TRACEPOINT_PROBE(syscall_enter_probe, struct pt_regs *regs, long id); TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret); TRACEPOINT_PROBE(syscall_procexit_probe, struct task_struct *p); #ifdef CAPTURE_CONTEXT_SWITCHES -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 35)) -TRACEPOINT_PROBE(sched_switch_probe, struct rq *rq, struct task_struct *prev, struct task_struct *next); -#elif (LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 35)) +TRACEPOINT_PROBE(sched_switch_probe, + struct rq *rq, + struct task_struct *prev, + struct task_struct *next); +#elif(LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) TRACEPOINT_PROBE(sched_switch_probe, struct task_struct *prev, struct task_struct *next); #else -TRACEPOINT_PROBE(sched_switch_probe, bool preempt, struct task_struct *prev, struct task_struct *next); +TRACEPOINT_PROBE(sched_switch_probe, + bool preempt, + struct task_struct *prev, + struct task_struct *next); #endif /* (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35)) */ #endif /* CAPTURE_CONTEXT_SWITCHES */ @@ -182,8 +189,14 @@ TRACEPOINT_PROBE(signal_deliver_probe, int sig, struct siginfo *info, struct k_s /* tracepoints `page_fault_user/kernel` don't exist on some architectures.*/ #ifdef CAPTURE_PAGE_FAULTS -TRACEPOINT_PROBE(page_fault_user_probe, unsigned long address, struct pt_regs *regs, unsigned long error_code); -TRACEPOINT_PROBE(page_fault_kern_probe, unsigned long address, struct pt_regs *regs, unsigned long error_code); +TRACEPOINT_PROBE(page_fault_user_probe, + unsigned long address, + struct pt_regs *regs, + unsigned long error_code); +TRACEPOINT_PROBE(page_fault_kern_probe, + unsigned long address, + struct pt_regs *regs, + unsigned long error_code); #endif #ifdef CAPTURE_SCHED_PROC_FORK @@ -191,7 +204,10 @@ TRACEPOINT_PROBE(sched_proc_fork_probe, struct task_struct *parent, struct task_ #endif #ifdef CAPTURE_SCHED_PROC_EXEC -TRACEPOINT_PROBE(sched_proc_exec_probe, struct task_struct *p, pid_t old_pid, struct linux_binprm *bprm); +TRACEPOINT_PROBE(sched_proc_exec_probe, + struct task_struct *p, + pid_t old_pid, + struct linux_binprm *bprm); #endif extern const int g_ia32_64_map[]; @@ -202,11 +218,11 @@ static unsigned int g_ppm_numdevs; static int g_ppm_major; static DEFINE_PER_CPU(long, g_n_tracepoint_hit); static const struct file_operations g_ppm_fops = { - .open = ppm_open, - .release = ppm_release, - .mmap = ppm_mmap, - .unlocked_ioctl = ppm_ioctl, - .owner = THIS_MODULE, + .open = ppm_open, + .release = ppm_release, + .mmap = ppm_mmap, + .unlocked_ioctl = ppm_ioctl, + .owner = THIS_MODULE, }; /* @@ -216,9 +232,11 @@ static const struct file_operations g_ppm_fops = { LIST_HEAD(g_consumer_list); static DEFINE_MUTEX(g_consumer_mutex); -static uint32_t g_tracepoints_attached; // list of attached tracepoints; bitmask using ppm_tp.h enum +static uint32_t + g_tracepoints_attached; // list of attached tracepoints; bitmask using ppm_tp.h enum static uint32_t g_tracepoints_refs[KMOD_PROG_ATTACHED_MAX]; -static unsigned long g_buffer_bytes_dim = DEFAULT_BUFFER_BYTES_DIM; // dimension of a single per-CPU buffer in bytes. +static unsigned long g_buffer_bytes_dim = + DEFAULT_BUFFER_BYTES_DIM; // dimension of a single per-CPU buffer in bytes. #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) static struct tracepoint *tp_sys_enter; static struct tracepoint *tp_sys_exit; @@ -255,19 +273,18 @@ static bool verbose = 0; static unsigned int max_consumers = 5; -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) static enum cpuhp_state hp_state = 0; #endif -#define vpr_info(fmt, ...) \ -do { \ - if (verbose) \ - pr_info(fmt, ##__VA_ARGS__); \ -} while (0) +#define vpr_info(fmt, ...) \ + do { \ + if(verbose) \ + pr_info(fmt, ##__VA_ARGS__); \ + } while(0) -static inline nanoseconds ppm_nsecs(void) -{ -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 17, 0)) +static inline nanoseconds ppm_nsecs(void) { +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(3, 17, 0)) return ktime_get_real_ns(); #else /* Don't have ktime_get_real functions */ @@ -278,62 +295,57 @@ static inline nanoseconds ppm_nsecs(void) } /* Fetches 6 arguments of the system call */ -inline void ppm_syscall_get_arguments(struct task_struct *task, struct pt_regs *regs, unsigned long *args) -{ -#if (LINUX_VERSION_CODE < KERNEL_VERSION(5, 1, 0)) - syscall_get_arguments(task, regs, 0, 6, args); +inline void ppm_syscall_get_arguments(struct task_struct *task, + struct pt_regs *regs, + unsigned long *args) { +#if(LINUX_VERSION_CODE < KERNEL_VERSION(5, 1, 0)) + syscall_get_arguments(task, regs, 0, 6, args); #else - syscall_get_arguments(task, regs, args); + syscall_get_arguments(task, regs, args); #endif } /* compat tracepoint functions */ -static int compat_register_trace(void *func, const char *probename, struct tracepoint *tp) -{ -#if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0)) +static int compat_register_trace(void *func, const char *probename, struct tracepoint *tp) { +#if(LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0)) return TRACEPOINT_PROBE_REGISTER(probename, func); #else return tracepoint_probe_register(tp, func, NULL); #endif } -static void compat_unregister_trace(void *func, const char *probename, struct tracepoint *tp) -{ -#if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0)) +static void compat_unregister_trace(void *func, const char *probename, struct tracepoint *tp) { +#if(LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0)) TRACEPOINT_PROBE_UNREGISTER(probename, func); #else tracepoint_probe_unregister(tp, func, NULL); #endif } -static void set_consumer_tracepoints(struct ppm_consumer_t *consumer, uint32_t tp_set) -{ +static void set_consumer_tracepoints(struct ppm_consumer_t *consumer, uint32_t tp_set) { int i; int bits_processed; vpr_info("consumer %p | requested tp set: %d\n", consumer->consumer_id, tp_set); bits_processed = force_tp_set(consumer, tp_set); - for(i = 0; i < bits_processed; i++) - { - if (tp_set & (1 << i)) - { + for(i = 0; i < bits_processed; i++) { + if(tp_set & (1 << i)) { consumer->tracepoints_attached |= 1 << i; - } - else - { + } else { consumer->tracepoints_attached &= ~(1 << i); } } - vpr_info("consumer %p | set tp set: %d\n", consumer->consumer_id, consumer->tracepoints_attached); + vpr_info("consumer %p | set tp set: %d\n", + consumer->consumer_id, + consumer->tracepoints_attached); } -static struct ppm_consumer_t *ppm_find_consumer(struct task_struct *consumer_id) -{ +static struct ppm_consumer_t *ppm_find_consumer(struct task_struct *consumer_id) { struct ppm_consumer_t *el = NULL; rcu_read_lock(); list_for_each_entry_rcu(el, &g_consumer_list, node) { - if (el->consumer_id == consumer_id) { + if(el->consumer_id == consumer_id) { rcu_read_unlock(); return el; } @@ -343,25 +355,24 @@ static struct ppm_consumer_t *ppm_find_consumer(struct task_struct *consumer_id) return NULL; } -static void check_remove_consumer(struct ppm_consumer_t *consumer, int remove_from_list) -{ +static void check_remove_consumer(struct ppm_consumer_t *consumer, int remove_from_list) { int cpu; int open_rings = 0; for_each_possible_cpu(cpu) { struct ppm_ring_buffer_context *ring = per_cpu_ptr(consumer->ring_buffers, cpu); - if (ring && ring->open) + if(ring && ring->open) ++open_rings; } - if (open_rings == 0) { + if(open_rings == 0) { pr_info("deallocating consumer %p\n", consumer->consumer_id); // Clean up tracepoints references for this consumer set_consumer_tracepoints(consumer, 0); - if (remove_from_list) { + if(remove_from_list) { list_del_rcu(&consumer->node); synchronize_rcu(); } @@ -380,8 +391,7 @@ static void check_remove_consumer(struct ppm_consumer_t *consumer, int remove_fr /* * user I/O functions */ -static int ppm_open(struct inode *inode, struct file *filp) -{ +static int ppm_open(struct inode *inode, struct file *filp) { int ret; int in_list = false; #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) @@ -402,7 +412,7 @@ static int ppm_open(struct inode *inode, struct file *filp) mutex_lock(&g_consumer_mutex); consumer = ppm_find_consumer(consumer_id); - if (!consumer) { + if(!consumer) { unsigned int cpu; unsigned int num_consumers = 0; struct ppm_consumer_t *el = NULL; @@ -413,7 +423,7 @@ static int ppm_open(struct inode *inode, struct file *filp) } rcu_read_unlock(); - if (num_consumers >= max_consumers) { + if(num_consumers >= max_consumers) { pr_err("maximum number of consumers reached\n"); ret = -EBUSY; goto cleanup_open; @@ -422,7 +432,7 @@ static int ppm_open(struct inode *inode, struct file *filp) pr_info("adding new consumer %p\n", consumer_id); consumer = vmalloc(sizeof(struct ppm_consumer_t)); - if (!consumer) { + if(!consumer) { pr_err("can't allocate consumer\n"); ret = -ENOMEM; goto cleanup_open; @@ -437,7 +447,7 @@ static int ppm_open(struct inode *inode, struct file *filp) * Initialize the ring buffers array */ consumer->ring_buffers = alloc_percpu(struct ppm_ring_buffer_context); - if (consumer->ring_buffers == NULL) { + if(consumer->ring_buffers == NULL) { pr_err("can't allocate the ring buffer array\n"); vfree(consumer); @@ -475,7 +485,7 @@ static int ppm_open(struct inode *inode, struct file *filp) pr_info("initializing ring buffer for CPU %u\n", cpu); - if (!init_ring_buffer(ring, consumer->buffer_bytes_dim)) { + if(!init_ring_buffer(ring, consumer->buffer_bytes_dim)) { pr_err("can't initialize the ring buffer for CPU %u\n", cpu); ret = -ENOMEM; goto err_init_ring_buffer; @@ -498,13 +508,15 @@ static int ppm_open(struct inode *inode, struct file *filp) * online hotplug callback between the first open on this consumer and the open * for this particular device. */ - if (ring->cpu_online == false || ring->buffer == NULL) { + if(ring->cpu_online == false || ring->buffer == NULL) { ret = -ENODEV; goto cleanup_open; } - if (ring->open) { - pr_err("invalid operation: attempting to open device %d multiple times for consumer %p\n", ring_no, consumer->consumer_id); + if(ring->open) { + pr_err("invalid operation: attempting to open device %d multiple times for consumer %p\n", + ring_no, + consumer->consumer_id); ret = -EBUSY; goto cleanup_open; } @@ -513,10 +525,11 @@ static int ppm_open(struct inode *inode, struct file *filp) /* * ring->preempt_count is not reset to 0 on purpose, to prevent a race condition: - * if the same device is quickly closed and then reopened, record_event() might still be executing - * (with ring->preempt_count to 1) while ppm_open() resets ring->preempt_count to 0. + * if the same device is quickly closed and then reopened, record_event() might still be + * executing (with ring->preempt_count to 1) while ppm_open() resets ring->preempt_count to 0. * When record_event() will exit, it will decrease - * ring->preempt_count which will become < 0, leading to the complete loss of all the events for that CPU. + * ring->preempt_count which will become < 0, leading to the complete loss of all the events for + * that CPU. */ consumer->dropping_mode = 0; consumer->snaplen = SNAPLEN; @@ -546,8 +559,7 @@ static int ppm_open(struct inode *inode, struct file *filp) return ret; } -static int ppm_release(struct inode *inode, struct file *filp) -{ +static int ppm_release(struct inode *inode, struct file *filp) { int ret; struct ppm_ring_buffer_context *ring; #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) @@ -561,47 +573,53 @@ static int ppm_release(struct inode *inode, struct file *filp) mutex_lock(&g_consumer_mutex); consumer = ppm_find_consumer(consumer_id); - if (!consumer) { + if(!consumer) { pr_err("release: unknown consumer %p\n", consumer_id); ret = -EBUSY; goto cleanup_release; } ring = per_cpu_ptr(consumer->ring_buffers, ring_no); - if (!ring) { + if(!ring) { ASSERT(false); ret = -ENODEV; goto cleanup_release; } - if (!ring->open) { + if(!ring->open) { pr_err("attempting to close unopened device %d for consumer %p\n", ring_no, consumer_id); ret = -EBUSY; goto cleanup_release; } - vpr_info("closing ring %d, consumer:%p evt:%llu, dr_buf:%llu, dr_buf_clone_fork_e:%llu, dr_buf_clone_fork_x:%llu, dr_buf_execve_e:%llu, dr_buf_execve_x:%llu, dr_buf_connect_e:%llu, dr_buf_connect_x:%llu, dr_buf_open_e:%llu, dr_buf_open_x:%llu, dr_buf_dir_file_e:%llu, dr_buf_dir_file_x:%llu, dr_buf_other_e:%llu, dr_buf_other_x:%llu, dr_buf_close_exit:%llu, dr_buf_proc_exit:%llu, dr_pf:%llu, pr:%llu, cs:%llu\n", - ring_no, - consumer_id, - ring->info->n_evts, - ring->info->n_drops_buffer, - ring->info->n_drops_buffer_clone_fork_enter, - ring->info->n_drops_buffer_clone_fork_exit, - ring->info->n_drops_buffer_execve_enter, - ring->info->n_drops_buffer_execve_exit, - ring->info->n_drops_buffer_connect_enter, - ring->info->n_drops_buffer_connect_exit, - ring->info->n_drops_buffer_open_enter, - ring->info->n_drops_buffer_open_exit, - ring->info->n_drops_buffer_dir_file_enter, - ring->info->n_drops_buffer_dir_file_exit, - ring->info->n_drops_buffer_other_interest_enter, - ring->info->n_drops_buffer_other_interest_exit, - ring->info->n_drops_buffer_close_exit, - ring->info->n_drops_buffer_proc_exit, - ring->info->n_drops_pf, - ring->info->n_preemptions, - ring->info->n_context_switches); + vpr_info( + "closing ring %d, consumer:%p evt:%llu, dr_buf:%llu, dr_buf_clone_fork_e:%llu, " + "dr_buf_clone_fork_x:%llu, dr_buf_execve_e:%llu, dr_buf_execve_x:%llu, " + "dr_buf_connect_e:%llu, dr_buf_connect_x:%llu, dr_buf_open_e:%llu, dr_buf_open_x:%llu, " + "dr_buf_dir_file_e:%llu, dr_buf_dir_file_x:%llu, dr_buf_other_e:%llu, " + "dr_buf_other_x:%llu, dr_buf_close_exit:%llu, dr_buf_proc_exit:%llu, dr_pf:%llu, " + "pr:%llu, cs:%llu\n", + ring_no, + consumer_id, + ring->info->n_evts, + ring->info->n_drops_buffer, + ring->info->n_drops_buffer_clone_fork_enter, + ring->info->n_drops_buffer_clone_fork_exit, + ring->info->n_drops_buffer_execve_enter, + ring->info->n_drops_buffer_execve_exit, + ring->info->n_drops_buffer_connect_enter, + ring->info->n_drops_buffer_connect_exit, + ring->info->n_drops_buffer_open_enter, + ring->info->n_drops_buffer_open_exit, + ring->info->n_drops_buffer_dir_file_enter, + ring->info->n_drops_buffer_dir_file_exit, + ring->info->n_drops_buffer_other_interest_enter, + ring->info->n_drops_buffer_other_interest_exit, + ring->info->n_drops_buffer_close_exit, + ring->info->n_drops_buffer_proc_exit, + ring->info->n_drops_pf, + ring->info->n_preemptions, + ring->info->n_context_switches); ring->open = false; @@ -615,22 +633,20 @@ static int ppm_release(struct inode *inode, struct file *filp) return ret; } -static int compat_set_tracepoint(void *func, const char *probename, struct tracepoint *tp, bool enabled) -{ +static int compat_set_tracepoint(void *func, + const char *probename, + struct tracepoint *tp, + bool enabled) { int ret = 0; - if (enabled) - { + if(enabled) { ret = compat_register_trace(func, probename, tp); - } - else - { + } else { compat_unregister_trace(func, probename, tp); } return ret; } -static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) -{ +static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) { uint32_t idx; uint32_t new_val; uint32_t curr_val; @@ -638,20 +654,15 @@ static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) int ret; ret = 0; - for(idx = 0; idx < KMOD_PROG_ATTACHED_MAX && ret == 0; idx++) - { + for(idx = 0; idx < KMOD_PROG_ATTACHED_MAX && ret == 0; idx++) { new_val = new_tp_set & (1 << idx); curr_val = g_tracepoints_attached & (1 << idx); - if(new_val == curr_val) - { - if (new_val) - { + if(new_val == curr_val) { + if(new_val) { // If enable is requested, set ref bit g_tracepoints_refs[idx] |= 1 << consumer->id; - } - else - { + } else { // If disable is requested, unset ref bit g_tracepoints_refs[idx] &= ~(1 << consumer->id); } @@ -659,35 +670,31 @@ static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) continue; } - if (new_val && g_tracepoints_refs[idx] != 0) - { + if(new_val && g_tracepoints_refs[idx] != 0) { // we are not the first to request this tp; // set ref bit and continue g_tracepoints_refs[idx] |= 1 << consumer->id; continue; } - if (!new_val && g_tracepoints_refs[idx] != (1 << consumer->id)) - { + if(!new_val && g_tracepoints_refs[idx] != (1 << consumer->id)) { // we are not the last to unrequest this tp; // unset ref bit and continue g_tracepoints_refs[idx] &= ~(1 << consumer->id); continue; } - switch(idx) - { + switch(idx) { case KMOD_PROG_SYS_ENTER: - if(new_val) - { + if(new_val) { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) - ret = compat_register_trace(syscall_enter_probe, kmod_prog_names[idx], tp_sys_enter); + ret = compat_register_trace(syscall_enter_probe, + kmod_prog_names[idx], + tp_sys_enter); #else ret = register_trace_syscall_enter(syscall_enter_probe); #endif - } - else - { + } else { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) compat_unregister_trace(syscall_enter_probe, kmod_prog_names[idx], tp_sys_enter); #else @@ -696,16 +703,13 @@ static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) } break; case KMOD_PROG_SYS_EXIT: - if(new_val) - { + if(new_val) { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) ret = compat_register_trace(syscall_exit_probe, kmod_prog_names[idx], tp_sys_exit); #else ret = register_trace_syscall_exit(syscall_exit_probe); #endif - } - else - { + } else { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) compat_unregister_trace(syscall_exit_probe, kmod_prog_names[idx], tp_sys_exit); #else @@ -714,40 +718,59 @@ static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) } break; case KMOD_PROG_SCHED_PROC_EXIT: - ret = compat_set_tracepoint(syscall_procexit_probe, kmod_prog_names[idx], tp_sched_process_exit, new_val); + ret = compat_set_tracepoint(syscall_procexit_probe, + kmod_prog_names[idx], + tp_sched_process_exit, + new_val); break; #ifdef CAPTURE_CONTEXT_SWITCHES case KMOD_PROG_SCHED_SWITCH: - ret = compat_set_tracepoint(sched_switch_probe, kmod_prog_names[idx], tp_sched_switch, new_val); + ret = compat_set_tracepoint(sched_switch_probe, + kmod_prog_names[idx], + tp_sched_switch, + new_val); break; #endif #ifdef CAPTURE_PAGE_FAULTS case KMOD_PROG_PAGE_FAULT_USER: - if (!g_fault_tracepoint_disabled) - { - ret = compat_set_tracepoint(page_fault_user_probe, kmod_prog_names[idx], tp_page_fault_user, new_val); + if(!g_fault_tracepoint_disabled) { + ret = compat_set_tracepoint(page_fault_user_probe, + kmod_prog_names[idx], + tp_page_fault_user, + new_val); } break; case KMOD_PROG_PAGE_FAULT_KERNEL: - if (!g_fault_tracepoint_disabled) - { - ret = compat_set_tracepoint(page_fault_kern_probe, kmod_prog_names[idx], tp_page_fault_kernel, new_val); + if(!g_fault_tracepoint_disabled) { + ret = compat_set_tracepoint(page_fault_kern_probe, + kmod_prog_names[idx], + tp_page_fault_kernel, + new_val); } break; #endif #ifdef CAPTURE_SIGNAL_DELIVERIES case KMOD_PROG_SIGNAL_DELIVER: - ret = compat_set_tracepoint(signal_deliver_probe, kmod_prog_names[idx], tp_signal_deliver, new_val); + ret = compat_set_tracepoint(signal_deliver_probe, + kmod_prog_names[idx], + tp_signal_deliver, + new_val); break; #endif #ifdef CAPTURE_SCHED_PROC_FORK case KMOD_PROG_SCHED_PROC_FORK: - ret = compat_set_tracepoint(sched_proc_fork_probe, kmod_prog_names[idx], tp_sched_proc_fork, new_val); + ret = compat_set_tracepoint(sched_proc_fork_probe, + kmod_prog_names[idx], + tp_sched_proc_fork, + new_val); break; #endif #ifdef CAPTURE_SCHED_PROC_EXEC case KMOD_PROG_SCHED_PROC_EXEC: - ret = compat_set_tracepoint(sched_proc_exec_probe, kmod_prog_names[idx], tp_sched_proc_exec, new_val); + ret = compat_set_tracepoint(sched_proc_exec_probe, + kmod_prog_names[idx], + tp_sched_proc_exec, + new_val); break; #endif default: @@ -755,19 +778,17 @@ static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) break; } - if (ret == 0) - { + if(ret == 0) { g_tracepoints_attached ^= (1 << idx); g_tracepoints_refs[idx] ^= (1 << consumer->id); - } - else - { - pr_err("can't %s the %s tracepoint\n", new_val ? "attach" : "detach", kmod_prog_names[idx]); + } else { + pr_err("can't %s the %s tracepoint\n", + new_val ? "attach" : "detach", + kmod_prog_names[idx]); } } - if (g_tracepoints_attached == 0) - { + if(g_tracepoints_attached == 0) { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) tracepoint_synchronize_unregister(); #endif @@ -775,35 +796,32 @@ static int force_tp_set(struct ppm_consumer_t *consumer, uint32_t new_tp_set) /* * Reset tracepoint counter */ - for_each_possible_cpu(cpu) - { + for_each_possible_cpu(cpu) { per_cpu(g_n_tracepoint_hit, cpu) = 0; } } return idx; } -static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) -{ +static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { int cpu; int ret; struct task_struct *consumer_id = filp->private_data; struct ppm_consumer_t *consumer = NULL; - if (cmd == PPM_IOCTL_GET_PROCLIST) { + if(cmd == PPM_IOCTL_GET_PROCLIST) { struct ppm_proclist_info *proclist_info = NULL; struct task_struct *p, *t; uint64_t nentries = 0; struct ppm_proclist_info pli; uint32_t memsize; - if (copy_from_user(&pli, (void *)arg, sizeof(pli))) { + if(copy_from_user(&pli, (void *)arg, sizeof(pli))) { ret = -EINVAL; goto cleanup_ioctl_nolock; } - if(pli.max_entries < 0 || pli.max_entries > 1000000) - { + if(pli.max_entries < 0 || pli.max_entries > 1000000) { vpr_info("PPM_IOCTL_GET_PROCLIST: invalid max_entries %llu\n", pli.max_entries); ret = -EINVAL; goto cleanup_ioctl_procinfo; @@ -813,7 +831,7 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) memsize = sizeof(struct ppm_proclist_info) + sizeof(struct ppm_proc_info) * pli.max_entries; proclist_info = vmalloc(memsize); - if (!proclist_info) { + if(!proclist_info) { ret = -EINVAL; goto cleanup_ioctl_nolock; } @@ -834,38 +852,40 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) do { task_lock(p); #endif - if (nentries < pli.max_entries) { -#if (LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0)) - cputime_t utime, stime; + if(nentries < pli.max_entries) { +#if(LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0)) + cputime_t utime, stime; #else uint64_t utime, stime; #endif -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 4, 0)) - task_cputime_adjusted(t, &utime, &stime); +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 4, 0)) + task_cputime_adjusted(t, &utime, &stime); #else ppm_task_cputime_adjusted(t, &utime, &stime); #endif - proclist_info->entries[nentries].pid = t->pid; -#if (LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0)) - proclist_info->entries[nentries].utime = cputime_to_clock_t(utime); - proclist_info->entries[nentries].stime = cputime_to_clock_t(stime); + proclist_info->entries[nentries].pid = t->pid; +#if(LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0)) + proclist_info->entries[nentries].utime = cputime_to_clock_t(utime); + proclist_info->entries[nentries].stime = cputime_to_clock_t(stime); #else proclist_info->entries[nentries].utime = nsec_to_clock_t(utime); proclist_info->entries[nentries].stime = nsec_to_clock_t(stime); #endif - } + } - nentries++; + nentries++; #ifdef for_each_process_thread } #else task_unlock(p); #ifdef while_each_thread_all - } while_each_thread_all(p, t); + } + while_each_thread_all(p, t); } #else - } while_each_thread(p, t); + } + while_each_thread(p, t); } #endif #endif @@ -874,12 +894,12 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) proclist_info->n_entries = nentries; - if (nentries >= pli.max_entries) { + if(nentries >= pli.max_entries) { vpr_info("PPM_IOCTL_GET_PROCLIST: not enough space (%d avail, %d required)\n", - (int)pli.max_entries, - (int)nentries); + (int)pli.max_entries, + (int)nentries); - if (copy_to_user((void *)arg, proclist_info, sizeof(struct ppm_proclist_info))) { + if(copy_to_user((void *)arg, proclist_info, sizeof(struct ppm_proclist_info))) { ret = -EINVAL; goto cleanup_ioctl_procinfo; } @@ -889,44 +909,44 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) } else { memsize = sizeof(struct ppm_proclist_info) + sizeof(struct ppm_proc_info) * nentries; - if (copy_to_user((void *)arg, proclist_info, memsize)) { + if(copy_to_user((void *)arg, proclist_info, memsize)) { ret = -EINVAL; goto cleanup_ioctl_procinfo; } } ret = 0; -cleanup_ioctl_procinfo: + cleanup_ioctl_procinfo: vfree((void *)proclist_info); goto cleanup_ioctl_nolock; } - if (cmd == PPM_IOCTL_GET_N_TRACEPOINT_HIT) { - long __user *counters = (long __user *) arg; + if(cmd == PPM_IOCTL_GET_N_TRACEPOINT_HIT) { + long __user *counters = (long __user *)arg; for_each_possible_cpu(cpu) { - if (put_user(per_cpu(g_n_tracepoint_hit, cpu), &counters[cpu])) { + if(put_user(per_cpu(g_n_tracepoint_hit, cpu), &counters[cpu])) { ret = -EINVAL; goto cleanup_ioctl_nolock; } } ret = 0; goto cleanup_ioctl_nolock; - } else if (cmd == PPM_IOCTL_GET_DRIVER_VERSION) { - if (copy_to_user((void *)arg, DRIVER_VERSION, sizeof(DRIVER_VERSION))) { + } else if(cmd == PPM_IOCTL_GET_DRIVER_VERSION) { + if(copy_to_user((void *)arg, DRIVER_VERSION, sizeof(DRIVER_VERSION))) { ret = -EINVAL; goto cleanup_ioctl_nolock; } ret = 0; goto cleanup_ioctl_nolock; - } else if (cmd == PPM_IOCTL_GET_API_VERSION) { - unsigned long long __user *out = (unsigned long long __user *) arg; + } else if(cmd == PPM_IOCTL_GET_API_VERSION) { + unsigned long long __user *out = (unsigned long long __user *)arg; ret = 0; if(put_user(PPM_API_CURRENT_VERSION, out)) ret = -EINVAL; goto cleanup_ioctl_nolock; - } else if (cmd == PPM_IOCTL_GET_SCHEMA_VERSION) { - unsigned long long __user *out = (unsigned long long __user *) arg; + } else if(cmd == PPM_IOCTL_GET_SCHEMA_VERSION) { + unsigned long long __user *out = (unsigned long long __user *)arg; ret = 0; if(put_user(PPM_SCHEMA_CURRENT_VERSION, out)) ret = -EINVAL; @@ -936,15 +956,14 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) mutex_lock(&g_consumer_mutex); consumer = ppm_find_consumer(consumer_id); - if (!consumer) { + if(!consumer) { pr_err("ioctl: unknown consumer %p\n", consumer_id); ret = -EBUSY; goto cleanup_ioctl; } - switch (cmd) { - case PPM_IOCTL_DISABLE_DROPPING_MODE: - { + switch(cmd) { + case PPM_IOCTL_DISABLE_DROPPING_MODE: { vpr_info("PPM_IOCTL_DISABLE_DROPPING_MODE, consumer %p\n", consumer_id); consumer->dropping_mode = 0; @@ -954,8 +973,7 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_ENABLE_DROPPING_MODE: - { + case PPM_IOCTL_ENABLE_DROPPING_MODE: { uint32_t new_sampling_ratio; consumer->dropping_mode = 1; @@ -963,14 +981,9 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) new_sampling_ratio = (uint32_t)arg; - if (new_sampling_ratio != 1 && - new_sampling_ratio != 2 && - new_sampling_ratio != 4 && - new_sampling_ratio != 8 && - new_sampling_ratio != 16 && - new_sampling_ratio != 32 && - new_sampling_ratio != 64 && - new_sampling_ratio != 128) { + if(new_sampling_ratio != 1 && new_sampling_ratio != 2 && new_sampling_ratio != 4 && + new_sampling_ratio != 8 && new_sampling_ratio != 16 && new_sampling_ratio != 32 && + new_sampling_ratio != 64 && new_sampling_ratio != 128) { pr_err("invalid sampling ratio %u\n", new_sampling_ratio); ret = -EINVAL; goto cleanup_ioctl; @@ -984,14 +997,13 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_SET_SNAPLEN: - { + case PPM_IOCTL_SET_SNAPLEN: { uint32_t new_snaplen; vpr_info("PPM_IOCTL_SET_SNAPLEN, consumer %p\n", consumer_id); new_snaplen = (uint32_t)arg; - if (new_snaplen > SNAPLEN_MAX) { + if(new_snaplen > SNAPLEN_MAX) { pr_err("invalid snaplen %u\n", new_snaplen); ret = -EINVAL; goto cleanup_ioctl; @@ -1004,8 +1016,7 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_SET_FULLCAPTURE_PORT_RANGE: - { + case PPM_IOCTL_SET_FULLCAPTURE_PORT_RANGE: { uint32_t encoded_port_range; vpr_info("PPM_IOCTL_SET_FULLCAPTURE_PORT_RANGE, consumer %p\n", consumer_id); @@ -1014,14 +1025,14 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) consumer->fullcapture_port_range_start = encoded_port_range & 0xFFFF; consumer->fullcapture_port_range_end = encoded_port_range >> 16; - pr_info("new fullcapture_port_range_start: %d\n", (int)consumer->fullcapture_port_range_start); + pr_info("new fullcapture_port_range_start: %d\n", + (int)consumer->fullcapture_port_range_start); pr_info("new fullcapture_port_range_end: %d\n", (int)consumer->fullcapture_port_range_end); ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_SET_STATSD_PORT: - { + case PPM_IOCTL_SET_STATSD_PORT: { consumer->statsd_port = (uint16_t)arg; pr_info("new statsd_port: %d\n", (int)consumer->statsd_port); @@ -1029,13 +1040,12 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_ENABLE_SYSCALL: - { + case PPM_IOCTL_ENABLE_SYSCALL: { uint32_t syscall_to_set = (uint32_t)arg - SYSCALL_TABLE_ID0; vpr_info("PPM_IOCTL_ENABLE_SYSCALL (%u), consumer %p\n", syscall_to_set, consumer_id); - if (syscall_to_set >= SYSCALL_TABLE_SIZE) { + if(syscall_to_set >= SYSCALL_TABLE_SIZE) { pr_err("invalid syscall %u\n", syscall_to_set); ret = -EINVAL; goto cleanup_ioctl; @@ -1046,13 +1056,12 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_DISABLE_SYSCALL: - { + case PPM_IOCTL_DISABLE_SYSCALL: { uint32_t syscall_to_unset = (uint32_t)arg - SYSCALL_TABLE_ID0; vpr_info("PPM_IOCTL_DISABLE_SYSCALL (%u), consumer %p\n", syscall_to_unset, consumer_id); - if (syscall_to_unset >= SYSCALL_TABLE_SIZE) { + if(syscall_to_unset >= SYSCALL_TABLE_SIZE) { pr_err("invalid syscall %u\n", syscall_to_unset); ret = -EINVAL; goto cleanup_ioctl; @@ -1063,15 +1072,13 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_DISABLE_DYNAMIC_SNAPLEN: - { + case PPM_IOCTL_DISABLE_DYNAMIC_SNAPLEN: { consumer->do_dynamic_snaplen = false; ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_ENABLE_DYNAMIC_SNAPLEN: - { + case PPM_IOCTL_ENABLE_DYNAMIC_SNAPLEN: { consumer->do_dynamic_snaplen = true; ret = 0; @@ -1079,8 +1086,7 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) } #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) case PPM_IOCTL_GET_VTID: - case PPM_IOCTL_GET_VPID: - { + case PPM_IOCTL_GET_VPID: { pid_t vid; struct pid *pid; struct task_struct *task; @@ -1088,27 +1094,27 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) rcu_read_lock(); pid = find_pid_ns(arg, &init_pid_ns); - if (!pid) { + if(!pid) { rcu_read_unlock(); ret = -EINVAL; goto cleanup_ioctl; } task = pid_task(pid, PIDTYPE_PID); - if (!task) { + if(!task) { rcu_read_unlock(); ret = -EINVAL; goto cleanup_ioctl; } ns = ns_of_pid(pid); - if (!pid) { + if(!pid) { rcu_read_unlock(); ret = -EINVAL; goto cleanup_ioctl; } - if (cmd == PPM_IOCTL_GET_VTID) + if(cmd == PPM_IOCTL_GET_VTID) vid = task_pid_nr_ns(task, ns); else vid = task_tgid_nr_ns(task, ns); @@ -1126,10 +1132,9 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = task_tgid_nr(current); goto cleanup_ioctl; #endif /* LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) */ - case PPM_IOCTL_ENABLE_TP: - { + case PPM_IOCTL_ENABLE_TP: { uint32_t new_tp_set; - if ((uint32_t)arg >= KMOD_PROG_ATTACHED_MAX) { + if((uint32_t)arg >= KMOD_PROG_ATTACHED_MAX) { pr_err("invalid tp %u\n", (uint32_t)arg); ret = -EINVAL; goto cleanup_ioctl; @@ -1140,10 +1145,9 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_DISABLE_TP: - { + case PPM_IOCTL_DISABLE_TP: { uint32_t new_tp_set; - if ((uint32_t)arg >= KMOD_PROG_ATTACHED_MAX) { + if((uint32_t)arg >= KMOD_PROG_ATTACHED_MAX) { pr_err("invalid tp %u\n", (uint32_t)arg); ret = -EINVAL; goto cleanup_ioctl; @@ -1154,15 +1158,13 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_DISABLE_DROPFAILED: - { + case PPM_IOCTL_DISABLE_DROPFAILED: { consumer->drop_failed = false; ret = 0; goto cleanup_ioctl; } - case PPM_IOCTL_ENABLE_DROPFAILED: - { + case PPM_IOCTL_ENABLE_DROPFAILED: { consumer->drop_failed = true; ret = 0; @@ -1179,8 +1181,7 @@ static long ppm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) return ret; } -static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) -{ +static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) { int ret; struct task_struct *consumer_id = filp->private_data; struct ppm_consumer_t *consumer = NULL; @@ -1188,13 +1189,13 @@ static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) mutex_lock(&g_consumer_mutex); consumer = ppm_find_consumer(consumer_id); - if (!consumer) { + if(!consumer) { pr_err("mmap: unknown consumer %p\n", consumer_id); ret = -EIO; goto cleanup_mmap; } - if (vma->vm_pgoff == 0) { + if(vma->vm_pgoff == 0) { long length = vma->vm_end - vma->vm_start; unsigned long useraddr = vma->vm_start; unsigned long pfn; @@ -1208,23 +1209,23 @@ static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) struct ppm_ring_buffer_context *ring; vpr_info("mmap for consumer %p, CPU %d, start=%lu len=%ld page_size=%lu\n", - consumer_id, - ring_no, - useraddr, - length, - PAGE_SIZE); + consumer_id, + ring_no, + useraddr, + length, + PAGE_SIZE); /* * Retrieve the ring structure for this CPU */ ring = per_cpu_ptr(consumer->ring_buffers, ring_no); - if (!ring) { + if(!ring) { ASSERT(false); ret = -ENODEV; goto cleanup_mmap; } - if (length <= PAGE_SIZE) { + if(length <= PAGE_SIZE) { /* * When the size requested by the user is smaller than a page, we assume * she's mapping the ring info structure @@ -1237,18 +1238,15 @@ static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) pfn = vmalloc_to_pfn(vmalloc_area_ptr); pgprot_val(vma->vm_page_prot) = pgprot_val(PAGE_SHARED) | _PAGE_ENC; - ret = remap_pfn_range(vma, useraddr, pfn, - PAGE_SIZE, vma->vm_page_prot); - if (ret < 0) { + ret = remap_pfn_range(vma, useraddr, pfn, PAGE_SIZE, vma->vm_page_prot); + if(ret < 0) { pr_err("remap_pfn_range failed (1)\n"); goto cleanup_mmap; } ret = 0; goto cleanup_mmap; - } - else if(length == consumer->buffer_bytes_dim * 2) - { + } else if(length == consumer->buffer_bytes_dim * 2) { long mlength; /* @@ -1263,7 +1261,7 @@ static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) /* * Validate that the buffer access is read only */ - if (vma->vm_flags & VM_WRITE) { + if(vma->vm_flags & VM_WRITE) { pr_err("invalid mmap flags 0x%lx\n", vma->vm_flags); ret = -EIO; goto cleanup_mmap; @@ -1274,13 +1272,12 @@ static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) */ mlength = length / 2; - while (mlength > 0) { + while(mlength > 0) { pfn = vmalloc_to_pfn(vmalloc_area_ptr); pgprot_val(vma->vm_page_prot) = pgprot_val(PAGE_SHARED) | _PAGE_ENC; - ret = remap_pfn_range(vma, useraddr, pfn, - PAGE_SIZE, vma->vm_page_prot); - if (ret < 0) { + ret = remap_pfn_range(vma, useraddr, pfn, PAGE_SIZE, vma->vm_page_prot); + if(ret < 0) { pr_err("remap_pfn_range failed (1)\n"); goto cleanup_mmap; } @@ -1292,18 +1289,18 @@ static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) /* * Remap a second copy of the buffer pages at the end of the buffer. - * This effectively mirrors the buffer at its end and helps simplify buffer management in userland. + * This effectively mirrors the buffer at its end and helps simplify buffer management + * in userland. */ vmalloc_area_ptr = orig_vmalloc_area_ptr; mlength = length / 2; - while (mlength > 0) { + while(mlength > 0) { pfn = vmalloc_to_pfn(vmalloc_area_ptr); pgprot_val(vma->vm_page_prot) = pgprot_val(PAGE_SHARED) | _PAGE_ENC; - ret = remap_pfn_range(vma, useraddr, pfn, - PAGE_SIZE, vma->vm_page_prot); - if (ret < 0) { + ret = remap_pfn_range(vma, useraddr, pfn, PAGE_SIZE, vma->vm_page_prot); + if(ret < 0) { pr_err("remap_pfn_range failed (1)\n"); goto cleanup_mmap; } @@ -1333,30 +1330,22 @@ static int ppm_mmap(struct file *filp, struct vm_area_struct *vma) /* Argument list sizes for sys_socketcall */ #define AL(x) ((x) * sizeof(unsigned long)) -static const unsigned char nas[21] = { - AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), - AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), - AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), - AL(4), AL(5), AL(4) -}; +static const unsigned char nas[21] = {AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), + AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), + AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4)}; #undef AL #ifdef CONFIG_COMPAT #define AL(x) ((x) * sizeof(compat_ulong_t)) -static const unsigned char compat_nas[21] = { - AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), - AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), - AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), - AL(4), AL(5), AL(4) -}; +static const unsigned char compat_nas[21] = {AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), + AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), + AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4)}; #undef AL #endif - /* This method is just a pass-through to avoid exporting * `ppm_syscall_get_arguments` outside of `main.c` */ -static long convert_network_syscalls(struct pt_regs *regs, bool* is_syscall_return) -{ +static long convert_network_syscalls(struct pt_regs *regs, bool *is_syscall_return) { /* Here we extract just the first parameter of the socket call */ unsigned long __user args[6] = {}; ppm_syscall_get_arguments(current, regs, args); @@ -1365,8 +1354,7 @@ static long convert_network_syscalls(struct pt_regs *regs, bool* is_syscall_retu return socketcall_code_to_syscall_code(args[0], is_syscall_return); } -static int load_socketcall_params(struct event_filler_arguments *filler_args) -{ +static int load_socketcall_params(struct event_filler_arguments *filler_args) { unsigned long __user original_socketcall_args[6] = {}; unsigned long __user pointer_real_args = 0; int socketcall_id; @@ -1375,20 +1363,21 @@ static int load_socketcall_params(struct event_filler_arguments *filler_args) pointer_real_args = original_socketcall_args[1]; #ifdef CONFIG_COMPAT - if (unlikely(filler_args->compat)) - { + if(unlikely(filler_args->compat)) { compat_ulong_t socketcall_args32[6]; int j; - if (unlikely(ppm_copy_from_user(socketcall_args32, compat_ptr((compat_uptr_t)pointer_real_args), compat_nas[socketcall_id]))) + if(unlikely(ppm_copy_from_user(socketcall_args32, + compat_ptr((compat_uptr_t)pointer_real_args), + compat_nas[socketcall_id]))) return -1; - for (j = 0; j < 6; ++j) + for(j = 0; j < 6; ++j) filler_args->args[j] = (unsigned long)socketcall_args32[j]; - } - else - { + } else { #endif - if (unlikely(ppm_copy_from_user(filler_args->args, (unsigned long __user*)pointer_real_args, nas[socketcall_id]))) + if(unlikely(ppm_copy_from_user(filler_args->args, + (unsigned long __user *)pointer_real_args, + nas[socketcall_id]))) return -1; #ifdef CONFIG_COMPAT } @@ -1396,25 +1385,24 @@ static int load_socketcall_params(struct event_filler_arguments *filler_args) return 0; } -static inline struct event_data_t *manage_socketcall(struct event_data_t *event_data, int socketcall_syscall_id, bool is_exit) -{ +static inline struct event_data_t *manage_socketcall(struct event_data_t *event_data, + int socketcall_syscall_id, + bool is_exit) { bool is_syscall_return; - int return_code = convert_network_syscalls(event_data->event_info.syscall_data.regs, &is_syscall_return); - if (return_code == -1) - { + int return_code = + convert_network_syscalls(event_data->event_info.syscall_data.regs, &is_syscall_return); + if(return_code == -1) { // Wrong SYS_ argument passed. Drop the syscall. return NULL; } - /* If the return code is not the generic event we will need to extract parameters * with the socket call mechanism. */ event_data->extract_socketcall_params = true; /* If we return an event code, it means we need to call directly `record_event_all_consumers` */ - if(!is_syscall_return) - { + if(!is_syscall_return) { // We need to skip the syscall filtering logic because // the actual `id` is no longer representative for this event. // There could be cases in which we have a `PPME_SOCKET_SEND_E` event @@ -1424,9 +1412,11 @@ static inline struct event_data_t *manage_socketcall(struct event_data_t *event_ /* we need to use `return_code + 1` because return_code * is the enter event. */ - record_event_all_consumers(return_code + is_exit, UF_USED, - event_data, is_exit ? KMOD_PROG_SYS_EXIT : KMOD_PROG_SYS_ENTER); - return NULL; // managed + record_event_all_consumers(return_code + is_exit, + UF_USED, + event_data, + is_exit ? KMOD_PROG_SYS_EXIT : KMOD_PROG_SYS_ENTER); + return NULL; // managed } /* If we return a syscall id we just set it */ @@ -1434,10 +1424,9 @@ static inline struct event_data_t *manage_socketcall(struct event_data_t *event_ return event_data; } -static int preload_params(struct event_filler_arguments *filler_args, bool extract_socketcall_params) -{ - if (extract_socketcall_params) - { +static int preload_params(struct event_filler_arguments *filler_args, + bool extract_socketcall_params) { + if(extract_socketcall_params) { return load_socketcall_params(filler_args); } ppm_syscall_get_arguments(current, filler_args->regs, filler_args->args); @@ -1446,15 +1435,19 @@ static int preload_params(struct event_filler_arguments *filler_args, bool extra static inline void record_drop_e(struct ppm_consumer_t *consumer, nanoseconds ns, - enum syscall_flags drop_flags) -{ + enum syscall_flags drop_flags) { struct event_data_t event_data = {0}; - if (record_event_consumer(consumer, PPME_DROP_E, UF_NEVER_DROP, ns, &event_data, INTERNAL_EVENTS) == 0) { + if(record_event_consumer(consumer, + PPME_DROP_E, + UF_NEVER_DROP, + ns, + &event_data, + INTERNAL_EVENTS) == 0) { consumer->need_to_insert_drop_e = 1; } else { - if (consumer->need_to_insert_drop_e == 1 && !(drop_flags & UF_ATOMIC)) { - if (verbose) { + if(consumer->need_to_insert_drop_e == 1 && !(drop_flags & UF_ATOMIC)) { + if(verbose) { pr_err("consumer:%p drop enter event delayed insert\n", consumer->consumer_id); } } @@ -1463,10 +1456,10 @@ static inline void record_drop_e(struct ppm_consumer_t *consumer, } } -static inline void drops_buffer_syscall_categories_counters(ppm_event_code event_type, - struct ppm_ring_buffer_info *ring_info) -{ - switch (event_type) { +static inline void drops_buffer_syscall_categories_counters( + ppm_event_code event_type, + struct ppm_ring_buffer_info *ring_info) { + switch(event_type) { // enter case PPME_SYSCALL_OPEN_E: case PPME_SYSCALL_CREAT_E: @@ -1596,15 +1589,19 @@ static inline void drops_buffer_syscall_categories_counters(ppm_event_code event static inline void record_drop_x(struct ppm_consumer_t *consumer, nanoseconds ns, - enum syscall_flags drop_flags) -{ + enum syscall_flags drop_flags) { struct event_data_t event_data = {0}; - if (record_event_consumer(consumer, PPME_DROP_X, UF_NEVER_DROP, ns, &event_data, INTERNAL_EVENTS) == 0) { + if(record_event_consumer(consumer, + PPME_DROP_X, + UF_NEVER_DROP, + ns, + &event_data, + INTERNAL_EVENTS) == 0) { consumer->need_to_insert_drop_x = 1; } else { - if (consumer->need_to_insert_drop_x == 1 && !(drop_flags & UF_ATOMIC)) { - if (verbose) { + if(consumer->need_to_insert_drop_x == 1 && !(drop_flags & UF_ATOMIC)) { + if(verbose) { pr_err("consumer:%p drop exit event delayed insert\n", consumer->consumer_id); } } @@ -1614,9 +1611,7 @@ static inline void record_drop_x(struct ppm_consumer_t *consumer, } // Return 1 if the event should be dropped, else 0 -static inline int drop_nostate_event(ppm_event_code event_type, - struct pt_regs *regs) -{ +static inline int drop_nostate_event(ppm_event_code event_type, struct pt_regs *regs) { unsigned long args[6] = {}; unsigned long arg = 0; int close_fd = -1; @@ -1624,10 +1619,10 @@ static inline int drop_nostate_event(ppm_event_code event_type, struct fdtable *fdt; bool drop = false; - switch (event_type) { + switch(event_type) { case PPME_SYSCALL_CLOSE_X: case PPME_SOCKET_BIND_X: - if (syscall_get_return_value(current, regs) < 0) + if(syscall_get_return_value(current, regs) < 0) drop = true; break; case PPME_SYSCALL_CLOSE_E: @@ -1646,17 +1641,17 @@ static inline int drop_nostate_event(ppm_event_code event_type, files = current->files; spin_lock(&files->file_lock); fdt = files_fdtable(files); - if (close_fd < 0 || close_fd >= fdt->max_fds || -#if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 4, 0)) - !FD_ISSET(close_fd, fdt->open_fds) -#elif (LINUX_VERSION_CODE < KERNEL_VERSION(6, 10, 0)) - !fd_is_open(close_fd, fdt) + if(close_fd < 0 || close_fd >= fdt->max_fds || +#if(LINUX_VERSION_CODE < KERNEL_VERSION(3, 4, 0)) + !FD_ISSET(close_fd, fdt->open_fds) +#elif(LINUX_VERSION_CODE < KERNEL_VERSION(6, 10, 0)) + !fd_is_open(close_fd, fdt) #else - // fd_is_open() was made file-local: - // https://github.com/torvalds/linux/commit/c4aab26253cd1f302279b8d6b5b66ccf1b120520 - !test_bit(close_fd, fdt->open_fds) + // fd_is_open() was made file-local: + // https://github.com/torvalds/linux/commit/c4aab26253cd1f302279b8d6b5b66ccf1b120520 + !test_bit(close_fd, fdt->open_fds) #endif - ) { + ) { drop = true; } spin_unlock(&files->file_lock); @@ -1666,14 +1661,14 @@ static inline int drop_nostate_event(ppm_event_code event_type, // cmd arg ppm_syscall_get_arguments(current, regs, args); arg = args[1]; - if (arg != F_DUPFD && arg != F_DUPFD_CLOEXEC) + if(arg != F_DUPFD && arg != F_DUPFD_CLOEXEC) drop = true; break; default: break; } - if (drop) + if(drop) return 1; else return 0; @@ -1681,35 +1676,34 @@ static inline int drop_nostate_event(ppm_event_code event_type, // Return 1 if the event should be dropped, else 0 static inline int drop_event(struct ppm_consumer_t *consumer, - ppm_event_code event_type, - enum syscall_flags drop_flags, - nanoseconds ns, - struct pt_regs *regs) -{ + ppm_event_code event_type, + enum syscall_flags drop_flags, + nanoseconds ns, + struct pt_regs *regs) { int maybe_ret = 0; - if (consumer->dropping_mode) { + if(consumer->dropping_mode) { maybe_ret = drop_nostate_event(event_type, regs); - if (maybe_ret > 0) + if(maybe_ret > 0) return maybe_ret; } - if (drop_flags & UF_NEVER_DROP) { + if(drop_flags & UF_NEVER_DROP) { ASSERT((drop_flags & UF_ALWAYS_DROP) == 0); return 0; } - if (consumer->dropping_mode) { + if(consumer->dropping_mode) { nanoseconds ns2 = ns; - if (drop_flags & UF_ALWAYS_DROP) { + if(drop_flags & UF_ALWAYS_DROP) { ASSERT((drop_flags & UF_NEVER_DROP) == 0); return 1; } - if (consumer->sampling_interval < SECOND_IN_NS && - /* do_div replaces ns2 with the quotient and returns the remainder */ - do_div(ns2, SECOND_IN_NS) >= consumer->sampling_interval) { - if (consumer->is_dropping == 0) { + if(consumer->sampling_interval < SECOND_IN_NS && + /* do_div replaces ns2 with the quotient and returns the remainder */ + do_div(ns2, SECOND_IN_NS) >= consumer->sampling_interval) { + if(consumer->is_dropping == 0) { consumer->is_dropping = 1; record_drop_e(consumer, ns, drop_flags); } @@ -1717,7 +1711,7 @@ static inline int drop_event(struct ppm_consumer_t *consumer, return 1; } - if (consumer->is_dropping == 1) { + if(consumer->is_dropping == 1) { consumer->is_dropping = 0; record_drop_x(consumer, ns, drop_flags); } @@ -1727,10 +1721,9 @@ static inline int drop_event(struct ppm_consumer_t *consumer, } static void record_event_all_consumers(ppm_event_code event_type, - enum syscall_flags drop_flags, - struct event_data_t *event_datap, - kmod_prog_codes tp_type) -{ + enum syscall_flags drop_flags, + struct event_data_t *event_datap, + kmod_prog_codes tp_type) { struct ppm_consumer_t *consumer; nanoseconds ns = ppm_nsecs(); @@ -1745,12 +1738,11 @@ static void record_event_all_consumers(ppm_event_code event_type, * Returns 0 if the event is dropped */ static int record_event_consumer(struct ppm_consumer_t *consumer, - ppm_event_code event_type, - enum syscall_flags drop_flags, - nanoseconds ns, - struct event_data_t *event_datap, - kmod_prog_codes tp_type) -{ + ppm_event_code event_type, + enum syscall_flags drop_flags, + nanoseconds ns, + struct event_data_t *event_datap, + kmod_prog_codes tp_type) { int res = 0; size_t event_size = 0; int next; @@ -1768,28 +1760,23 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, long table_index; int64_t retval; - if (tp_type < INTERNAL_EVENTS && !(consumer->tracepoints_attached & (1 << tp_type))) - { + if(tp_type < INTERNAL_EVENTS && !(consumer->tracepoints_attached & (1 << tp_type))) { return res; } // Check if syscall is interesting for the consumer - if (event_datap->category == PPMC_SYSCALL) - { - if (!event_datap->deny_syscalls_filtering) - { + if(event_datap->category == PPMC_SYSCALL) { + if(!event_datap->deny_syscalls_filtering) { table_index = event_datap->event_info.syscall_data.id - SYSCALL_TABLE_ID0; - if(!test_bit(table_index, consumer->syscalls_mask)) - { + if(!test_bit(table_index, consumer->syscalls_mask)) { return res; } } - if (tp_type == KMOD_PROG_SYS_EXIT && consumer->drop_failed) - { - retval = (int64_t)syscall_get_return_value(current, event_datap->event_info.syscall_data.regs); - if (retval < 0) - { + if(tp_type == KMOD_PROG_SYS_EXIT && consumer->drop_failed) { + retval = (int64_t)syscall_get_return_value(current, + event_datap->event_info.syscall_data.regs); + if(retval < 0) { return res; } } @@ -1798,23 +1785,22 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, args.syscall_id = event_datap->event_info.syscall_data.id; args.compat = event_datap->compat; /* If the syscall is interesting we need to preload params */ - if(unlikely(preload_params(&args, event_datap->extract_socketcall_params) == -1)) - { + if(unlikely(preload_params(&args, event_datap->extract_socketcall_params) == -1)) { return res; } } - if (event_type != PPME_DROP_E && event_type != PPME_DROP_X) { - if (consumer->need_to_insert_drop_e == 1) + if(event_type != PPME_DROP_E && event_type != PPME_DROP_X) { + if(consumer->need_to_insert_drop_e == 1) record_drop_e(consumer, ns, drop_flags); - else if (consumer->need_to_insert_drop_x == 1) + else if(consumer->need_to_insert_drop_x == 1) record_drop_x(consumer, ns, drop_flags); - if (drop_event(consumer, - event_type, - drop_flags, - ns, - event_datap->event_info.syscall_data.regs)) + if(drop_event(consumer, + event_type, + drop_flags, + ns, + event_datap->event_info.syscall_data.regs)) return res; } @@ -1826,8 +1812,9 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, ASSERT(ring); ring_info = ring->info; - if (event_datap->category == PPMC_CONTEXT_SWITCH && event_datap->event_info.context_data.sched_prev != NULL) { - if (event_type != PPME_SCAPEVENT_E && event_type != PPME_CPU_HOTPLUG_E) { + if(event_datap->category == PPMC_CONTEXT_SWITCH && + event_datap->event_info.context_data.sched_prev != NULL) { + if(event_type != PPME_SCAPEVENT_E && event_type != PPME_CPU_HOTPLUG_E) { ASSERT(event_datap->event_info.context_data.sched_prev != NULL); ASSERT(event_datap->event_info.context_data.sched_next != NULL); ring_info->n_context_switches++; @@ -1837,7 +1824,7 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, /* * Preemption gate */ - if (unlikely(atomic_inc_return(&ring->preempt_count) != 1)) { + if(unlikely(atomic_inc_return(&ring->preempt_count) != 1)) { /* When this driver executing a filler calls ppm_copy_from_user(), * even if the page fault is disabled, the page fault tracepoint gets * called very early in the page fault handler, way before the kernel @@ -1849,7 +1836,7 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, * generated on this side, so let's see if someone complains. * This means that effectively those events would be lost. */ - if (event_type != PPME_PAGE_FAULT_E) { + if(event_type != PPME_PAGE_FAULT_E) { ASSERT(false); } ring_info->n_preemptions++; @@ -1865,7 +1852,7 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, head = ring_info->head; ttail = ring_info->tail; - if (ttail > head) + if(ttail > head) freespace = ttail - head - 1; else freespace = consumer->buffer_bytes_dim + ttail - head - 1; @@ -1891,7 +1878,7 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, * Make sure we have enough space for the event header. * We need at least space for the header plus 16 bit per parameter for the lengths. */ - if (likely(freespace >= sizeof(struct ppm_evt_hdr) + args.arg_data_offset)) { + if(likely(freespace >= sizeof(struct ppm_evt_hdr) + args.arg_data_offset)) { /* * Populate the header */ @@ -1913,17 +1900,18 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, #ifdef PPM_ENABLE_SENTINEL args.sentinel = ring->nevents; #endif - args.buffer_size = min(freespace, delta_from_end) - sizeof(struct ppm_evt_hdr); /* freespace is guaranteed to be bigger than sizeof(struct ppm_evt_hdr) */ + args.buffer_size = min(freespace, delta_from_end) - + sizeof(struct ppm_evt_hdr); /* freespace is guaranteed to be bigger than + sizeof(struct ppm_evt_hdr) */ args.event_type = event_type; - if(event_datap->category != PPMC_SYSCALL) - { + if(event_datap->category != PPMC_SYSCALL) { args.regs = NULL; args.syscall_id = -1; args.compat = false; } - if (event_datap->category == PPMC_CONTEXT_SWITCH) { + if(event_datap->category == PPMC_CONTEXT_SWITCH) { args.sched_prev = event_datap->event_info.context_data.sched_prev; args.sched_next = event_datap->event_info.context_data.sched_next; } else { @@ -1931,33 +1919,33 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, args.sched_next = NULL; } - if (event_datap->category == PPMC_SIGNAL) { + if(event_datap->category == PPMC_SIGNAL) { args.signo = event_datap->event_info.signal_data.sig; - if (event_datap->event_info.signal_data.info == NULL) { - args.spid = (__kernel_pid_t) 0; - } else if (args.signo == SIGKILL) { + if(event_datap->event_info.signal_data.info == NULL) { + args.spid = (__kernel_pid_t)0; + } else if(args.signo == SIGKILL) { args.spid = event_datap->event_info.signal_data.info->_sifields._kill._pid; - } else if (args.signo == SIGTERM || args.signo == SIGHUP || args.signo == SIGINT || - args.signo == SIGTSTP || args.signo == SIGQUIT) { - if (event_datap->event_info.signal_data.info->si_code == SI_USER || - event_datap->event_info.signal_data.info->si_code == SI_QUEUE || - event_datap->event_info.signal_data.info->si_code <= 0) { + } else if(args.signo == SIGTERM || args.signo == SIGHUP || args.signo == SIGINT || + args.signo == SIGTSTP || args.signo == SIGQUIT) { + if(event_datap->event_info.signal_data.info->si_code == SI_USER || + event_datap->event_info.signal_data.info->si_code == SI_QUEUE || + event_datap->event_info.signal_data.info->si_code <= 0) { args.spid = event_datap->event_info.signal_data.info->si_pid; } - } else if (args.signo == SIGCHLD) { + } else if(args.signo == SIGCHLD) { args.spid = event_datap->event_info.signal_data.info->_sifields._sigchld._pid; - } else if (args.signo >= SIGRTMIN && args.signo <= SIGRTMAX) { + } else if(args.signo >= SIGRTMIN && args.signo <= SIGRTMAX) { args.spid = event_datap->event_info.signal_data.info->_sifields._rt._pid; } else { - args.spid = (__kernel_pid_t) 0; + args.spid = (__kernel_pid_t)0; } } else { args.signo = 0; - args.spid = (__kernel_pid_t) 0; + args.spid = (__kernel_pid_t)0; } args.dpid = current->pid; - if (event_datap->category == PPMC_PAGE_FAULT) + if(event_datap->category == PPMC_PAGE_FAULT) args.fault_data = event_datap->event_info.fault_data; args.curarg = 0; @@ -1973,8 +1961,7 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, /* For events with category `PPMC_SCHED_PROC_EXEC` or `PPMC_SCHED_PROC_FORK` * we need to call dedicated fillers that are not in our `g_ppm_events` table. */ - switch (event_datap->category) - { + switch(event_datap->category) { #ifdef CAPTURE_SCHED_PROC_EXEC case PPMC_SCHED_PROC_EXEC: cbres = f_sched_prog_exec(&args); @@ -1991,23 +1978,20 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, #endif default: - if (likely(g_ppm_events[event_type].filler_callback)) - { + if(likely(g_ppm_events[event_type].filler_callback)) { cbres = g_ppm_events[event_type].filler_callback(&args); - } - else - { + } else { pr_err("corrupted filler for event type %d: NULL callback\n", event_type); ASSERT(0); } break; } - if (likely(cbres == PPM_SUCCESS)) { + if(likely(cbres == PPM_SUCCESS)) { /* * Validate that the filler added the right number of parameters */ - if (likely(args.curarg == args.nargs)) { + if(likely(args.curarg == args.nargs)) { /* * The event was successfully inserted in the buffer */ @@ -2024,22 +2008,22 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, } } - if (likely(!drop)) { + if(likely(!drop)) { res = 1; next = head + event_size; - if (unlikely(next >= consumer->buffer_bytes_dim)) { + if(unlikely(next >= consumer->buffer_bytes_dim)) { /* * If something has been written in the cushion space at the end of * the buffer, copy it to the beginning and wrap the head around. * Note, we don't check that the copy fits because we assume that * filler_callback failed if the space was not enough. */ - if (next > consumer->buffer_bytes_dim) { + if(next > consumer->buffer_bytes_dim) { memcpy(ring->buffer, - ring->buffer + consumer->buffer_bytes_dim, - next - consumer->buffer_bytes_dim); + ring->buffer + consumer->buffer_bytes_dim, + next - consumer->buffer_bytes_dim); } next -= consumer->buffer_bytes_dim; @@ -2056,15 +2040,15 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, ++ring->nevents; } else { - if (cbres == PPM_SUCCESS) { + if(cbres == PPM_SUCCESS) { ASSERT(freespace < sizeof(struct ppm_evt_hdr) + args.arg_data_offset); ring_info->n_drops_buffer++; - } else if (cbres == PPM_FAILURE_INVALID_USER_MEMORY) { + } else if(cbres == PPM_FAILURE_INVALID_USER_MEMORY) { #ifdef _DEBUG pr_err("Invalid read from user for event %d\n", event_type); #endif ring_info->n_drops_pf++; - } else if (cbres == PPM_FAILURE_BUFFER_FULL) { + } else if(cbres == PPM_FAILURE_BUFFER_FULL) { ring_info->n_drops_buffer++; drops_buffer_syscall_categories_counters(event_type, ring_info); } else { @@ -2073,30 +2057,36 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, } } - if (MORE_THAN_ONE_SECOND_AHEAD(ns, ring->last_print_time + 1) && !(drop_flags & UF_ATOMIC)) { - vpr_info("consumer:%p CPU:%d, use:%lu%%, ev:%llu, dr_buf:%llu, dr_buf_clone_fork_e:%llu, dr_buf_clone_fork_x:%llu, dr_buf_execve_e:%llu, dr_buf_execve_x:%llu, dr_buf_connect_e:%llu, dr_buf_connect_x:%llu, dr_buf_open_e:%llu, dr_buf_open_x:%llu, dr_buf_dir_file_e:%llu, dr_buf_dir_file_x:%llu, dr_buf_other_e:%llu, dr_buf_other_x:%llu, dr_buf_close_exit:%llu, dr_buf_proc_exit:%llu, dr_pf:%llu, pr:%llu, cs:%llu\n", - consumer->consumer_id, - smp_processor_id(), - (usedspace * 100) / consumer->buffer_bytes_dim, - ring_info->n_evts, - ring_info->n_drops_buffer, - ring_info->n_drops_buffer_clone_fork_enter, - ring_info->n_drops_buffer_clone_fork_exit, - ring_info->n_drops_buffer_execve_enter, - ring_info->n_drops_buffer_execve_exit, - ring_info->n_drops_buffer_connect_enter, - ring_info->n_drops_buffer_connect_exit, - ring_info->n_drops_buffer_open_enter, - ring_info->n_drops_buffer_open_exit, - ring_info->n_drops_buffer_dir_file_enter, - ring_info->n_drops_buffer_dir_file_exit, - ring_info->n_drops_buffer_other_interest_enter, - ring_info->n_drops_buffer_other_interest_exit, - ring->info->n_drops_buffer_close_exit, - ring->info->n_drops_buffer_proc_exit, - ring_info->n_drops_pf, - ring_info->n_preemptions, - ring->info->n_context_switches); + if(MORE_THAN_ONE_SECOND_AHEAD(ns, ring->last_print_time + 1) && !(drop_flags & UF_ATOMIC)) { + vpr_info( + "consumer:%p CPU:%d, use:%lu%%, ev:%llu, dr_buf:%llu, dr_buf_clone_fork_e:%llu, " + "dr_buf_clone_fork_x:%llu, dr_buf_execve_e:%llu, dr_buf_execve_x:%llu, " + "dr_buf_connect_e:%llu, dr_buf_connect_x:%llu, dr_buf_open_e:%llu, " + "dr_buf_open_x:%llu, dr_buf_dir_file_e:%llu, dr_buf_dir_file_x:%llu, " + "dr_buf_other_e:%llu, dr_buf_other_x:%llu, dr_buf_close_exit:%llu, " + "dr_buf_proc_exit:%llu, dr_pf:%llu, pr:%llu, cs:%llu\n", + consumer->consumer_id, + smp_processor_id(), + (usedspace * 100) / consumer->buffer_bytes_dim, + ring_info->n_evts, + ring_info->n_drops_buffer, + ring_info->n_drops_buffer_clone_fork_enter, + ring_info->n_drops_buffer_clone_fork_exit, + ring_info->n_drops_buffer_execve_enter, + ring_info->n_drops_buffer_execve_exit, + ring_info->n_drops_buffer_connect_enter, + ring_info->n_drops_buffer_connect_exit, + ring_info->n_drops_buffer_open_enter, + ring_info->n_drops_buffer_open_exit, + ring_info->n_drops_buffer_dir_file_enter, + ring_info->n_drops_buffer_dir_file_exit, + ring_info->n_drops_buffer_other_interest_enter, + ring_info->n_drops_buffer_other_interest_exit, + ring->info->n_drops_buffer_close_exit, + ring->info->n_drops_buffer_proc_exit, + ring_info->n_drops_pf, + ring_info->n_preemptions, + ring->info->n_context_switches); ring->last_print_time = ns; } @@ -2107,8 +2097,7 @@ static int record_event_consumer(struct ppm_consumer_t *consumer, return res; } -static inline void g_n_tracepoint_hit_inc(void) -{ +static inline void g_n_tracepoint_hit_inc(void) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 34) this_cpu_inc(g_n_tracepoint_hit); #elif defined(this_cpu_inc) @@ -2123,38 +2112,35 @@ static inline void g_n_tracepoint_hit_inc(void) #endif } -static inline bool kmod_in_ia32_syscall(void) -{ +static inline bool kmod_in_ia32_syscall(void) { #if defined(CONFIG_X86_64) && defined(CONFIG_IA32_EMULATION) #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 9, 0) - if (in_ia32_syscall()) + if(in_ia32_syscall()) #else - if (unlikely(task_thread_info(current)->status & TS_COMPAT)) + if(unlikely(task_thread_info(current)->status & TS_COMPAT)) #endif return true; #elif defined(CONFIG_ARM64) - if (unlikely(task_thread_info(current)->flags & _TIF_32BIT)) + if(unlikely(task_thread_info(current)->flags & _TIF_32BIT)) return true; #elif defined(CONFIG_S390) - if (unlikely(task_thread_info(current)->flags & _TIF_31BIT)) + if(unlikely(task_thread_info(current)->flags & _TIF_31BIT)) return true; #elif defined(CONFIG_PPC64) - if (unlikely(task_thread_info(current)->flags & _TIF_32BIT)) + if(unlikely(task_thread_info(current)->flags & _TIF_32BIT)) return true; #endif /* CONFIG_X86_64 */ return false; } -TRACEPOINT_PROBE(syscall_enter_probe, struct pt_regs *regs, long id) -{ +TRACEPOINT_PROBE(syscall_enter_probe, struct pt_regs *regs, long id) { struct event_data_t event_data = {}; const struct syscall_evt_pair *event_pair = NULL; long table_index = 0; int socketcall_syscall_id = -1; /* Just to be extra-safe */ - if(id < 0) - { + if(id < 0) { return; } @@ -2166,22 +2152,17 @@ TRACEPOINT_PROBE(syscall_enter_probe, struct pt_regs *regs, long id) event_data.event_info.syscall_data.id = id; event_data.compat = false; - if(kmod_in_ia32_syscall()) - { - // Right now we support 32-bit emulation only on x86. - // We try to convert the 32-bit id into the 64-bit one. + if(kmod_in_ia32_syscall()) { + // Right now we support 32-bit emulation only on x86. + // We try to convert the 32-bit id into the 64-bit one. #if defined(CONFIG_X86_64) && defined(CONFIG_IA32_EMULATION) event_data.compat = true; - if (id == __NR_ia32_socketcall) - { + if(id == __NR_ia32_socketcall) { socketcall_syscall_id = __NR_ia32_socketcall; - } - else - { + } else { event_data.event_info.syscall_data.id = g_ia32_64_map[id]; // syscalls defined only on 32 bits are dropped here. - if(event_data.event_info.syscall_data.id == -1) - { + if(event_data.event_info.syscall_data.id == -1) { return; } } @@ -2189,9 +2170,7 @@ TRACEPOINT_PROBE(syscall_enter_probe, struct pt_regs *regs, long id) // Unsupported arch return; #endif - } - else - { + } else { #ifdef __NR_socketcall socketcall_syscall_id = __NR_socketcall; #endif @@ -2201,32 +2180,33 @@ TRACEPOINT_PROBE(syscall_enter_probe, struct pt_regs *regs, long id) // Now all syscalls on 32-bit should be converted to 64-bit apart from `socketcall`. // This one deserves special treatment. - if(event_data.event_info.syscall_data.id == socketcall_syscall_id) - { - if(manage_socketcall(&event_data, socketcall_syscall_id, false) == NULL) - { + if(event_data.event_info.syscall_data.id == socketcall_syscall_id) { + if(manage_socketcall(&event_data, socketcall_syscall_id, false) == NULL) { return; } } /* We need to set here the `syscall_id` because it could change in case of socketcalls */ table_index = event_data.event_info.syscall_data.id - SYSCALL_TABLE_ID0; - if (unlikely(table_index < 0 || table_index >= SYSCALL_TABLE_SIZE)) - { + if(unlikely(table_index < 0 || table_index >= SYSCALL_TABLE_SIZE)) { return; } event_pair = &g_syscall_table[table_index]; - if (event_pair->flags & UF_USED) - record_event_all_consumers(event_pair->enter_event_type, event_pair->flags, &event_data, KMOD_PROG_SYS_ENTER); + if(event_pair->flags & UF_USED) + record_event_all_consumers(event_pair->enter_event_type, + event_pair->flags, + &event_data, + KMOD_PROG_SYS_ENTER); else - record_event_all_consumers(PPME_GENERIC_E, UF_ALWAYS_DROP, &event_data, KMOD_PROG_SYS_ENTER); + record_event_all_consumers(PPME_GENERIC_E, + UF_ALWAYS_DROP, + &event_data, + KMOD_PROG_SYS_ENTER); } -static __always_inline bool kmod_drop_syscall_exit_events(long ret, ppm_event_code evt_type) -{ - switch (evt_type) - { +static __always_inline bool kmod_drop_syscall_exit_events(long ret, ppm_event_code evt_type) { + switch(evt_type) { /* On s390x, clone and fork child events will be generated but * due to page faults, no args/envp information will be collected. * Also no child events appear for clone3 syscall. @@ -2235,46 +2215,44 @@ static __always_inline bool kmod_drop_syscall_exit_events(long ret, ppm_event_co * let proactively ignore them. */ #ifdef CAPTURE_SCHED_PROC_FORK - case PPME_SYSCALL_CLONE_20_X: - case PPME_SYSCALL_FORK_20_X: - case PPME_SYSCALL_VFORK_20_X: - case PPME_SYSCALL_CLONE3_X: - /* We ignore only child events, so ret == 0! */ - return ret == 0; + case PPME_SYSCALL_CLONE_20_X: + case PPME_SYSCALL_FORK_20_X: + case PPME_SYSCALL_VFORK_20_X: + case PPME_SYSCALL_CLONE3_X: + /* We ignore only child events, so ret == 0! */ + return ret == 0; #endif /* If `CAPTURE_SCHED_PROC_EXEC` logic is enabled we collect execve-family * exit events through a dedicated tracepoint so we can ignore them here. */ #ifdef CAPTURE_SCHED_PROC_EXEC - case PPME_SYSCALL_EXECVE_19_X: - case PPME_SYSCALL_EXECVEAT_X: - /* We ignore only successful events, so ret == 0! */ - return ret == 0; + case PPME_SYSCALL_EXECVE_19_X: + case PPME_SYSCALL_EXECVEAT_X: + /* We ignore only successful events, so ret == 0! */ + return ret == 0; #endif - default: - break; + default: + break; } return false; } -TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret) -{ +TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret) { struct event_data_t event_data = {}; const struct syscall_evt_pair *event_pair = NULL; long table_index = 0; int socketcall_syscall_id = -1; /* If @task is executing a system call or is at system call - * tracing about to attempt one, returns the system call number. - * If @task is not executing a system call, i.e. it's blocked - * inside the kernel for a fault or signal, returns -1. + * tracing about to attempt one, returns the system call number. + * If @task is not executing a system call, i.e. it's blocked + * inside the kernel for a fault or signal, returns -1. * * The syscall id could be overwritten if we are in a socket call. */ event_data.event_info.syscall_data.id = syscall_get_nr(current, regs); - if(event_data.event_info.syscall_data.id < 0) - { + if(event_data.event_info.syscall_data.id < 0) { return; } @@ -2283,16 +2261,12 @@ TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret) event_data.extract_socketcall_params = false; event_data.compat = false; - if (kmod_in_ia32_syscall()) - { + if(kmod_in_ia32_syscall()) { #if defined(CONFIG_X86_64) && defined(CONFIG_IA32_EMULATION) event_data.compat = true; - if (event_data.event_info.syscall_data.id == __NR_ia32_socketcall) - { + if(event_data.event_info.syscall_data.id == __NR_ia32_socketcall) { socketcall_syscall_id = __NR_ia32_socketcall; - } - else - { + } else { /* * When a process does execve from 64bit to 32bit, TS_COMPAT is marked true * but the id of the syscall is __NR_execve, so to correctly parse it we need to @@ -2300,15 +2274,15 @@ TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret) * which is a very old syscall, not used anymore by most applications */ #ifdef __NR_execveat - if (event_data.event_info.syscall_data.id != __NR_execve && event_data.event_info.syscall_data.id != __NR_execveat) + if(event_data.event_info.syscall_data.id != __NR_execve && + event_data.event_info.syscall_data.id != __NR_execveat) #else - if (event_data.event_info.syscall_data.id != __NR_execve) + if(event_data.event_info.syscall_data.id != __NR_execve) #endif { event_data.event_info.syscall_data.id = - g_ia32_64_map[event_data.event_info.syscall_data.id]; - if(event_data.event_info.syscall_data.id == -1) - { + g_ia32_64_map[event_data.event_info.syscall_data.id]; + if(event_data.event_info.syscall_data.id == -1) { return; } } @@ -2317,9 +2291,7 @@ TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret) // Unsupported arch return; #endif - } - else - { + } else { #ifdef __NR_socketcall socketcall_syscall_id = __NR_socketcall; #endif @@ -2327,17 +2299,14 @@ TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret) g_n_tracepoint_hit_inc(); - if(event_data.event_info.syscall_data.id == socketcall_syscall_id) - { - if (manage_socketcall(&event_data, socketcall_syscall_id, true) == NULL) - { + if(event_data.event_info.syscall_data.id == socketcall_syscall_id) { + if(manage_socketcall(&event_data, socketcall_syscall_id, true) == NULL) { return; } } table_index = event_data.event_info.syscall_data.id - SYSCALL_TABLE_ID0; - if (unlikely(table_index < 0 || table_index >= SYSCALL_TABLE_SIZE)) - { + if(unlikely(table_index < 0 || table_index >= SYSCALL_TABLE_SIZE)) { return; } @@ -2348,27 +2317,33 @@ TRACEPOINT_PROBE(syscall_exit_probe, struct pt_regs *regs, long ret) return; #endif - if (event_pair->flags & UF_USED) - record_event_all_consumers(event_pair->exit_event_type, event_pair->flags, &event_data, KMOD_PROG_SYS_EXIT); + if(event_pair->flags & UF_USED) + record_event_all_consumers(event_pair->exit_event_type, + event_pair->flags, + &event_data, + KMOD_PROG_SYS_EXIT); else record_event_all_consumers(PPME_GENERIC_X, UF_ALWAYS_DROP, &event_data, KMOD_PROG_SYS_EXIT); } #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 9, 1) -int __access_remote_vm(struct task_struct *t, struct mm_struct *mm, unsigned long addr, - void *buf, int len, int write); +int __access_remote_vm(struct task_struct *t, + struct mm_struct *mm, + unsigned long addr, + void *buf, + int len, + int write); #endif -TRACEPOINT_PROBE(syscall_procexit_probe, struct task_struct *p) -{ +TRACEPOINT_PROBE(syscall_procexit_probe, struct task_struct *p) { struct event_data_t event_data; g_n_tracepoint_hit_inc(); #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) - if (unlikely(current->flags & PF_KTHREAD)) { + if(unlikely(current->flags & PF_KTHREAD)) { #else - if (unlikely(current->flags & PF_BORROWED_MM)) { + if(unlikely(current->flags & PF_BORROWED_MM)) { #endif /* * We are not interested in kernel threads @@ -2380,7 +2355,10 @@ TRACEPOINT_PROBE(syscall_procexit_probe, struct task_struct *p) event_data.event_info.context_data.sched_prev = p; event_data.event_info.context_data.sched_next = p; - record_event_all_consumers(PPME_PROCEXIT_1_E, UF_NEVER_DROP, &event_data, KMOD_PROG_SCHED_PROC_EXIT); + record_event_all_consumers(PPME_PROCEXIT_1_E, + UF_NEVER_DROP, + &event_data, + KMOD_PROG_SCHED_PROC_EXIT); } #include @@ -2388,12 +2366,18 @@ TRACEPOINT_PROBE(syscall_procexit_probe, struct task_struct *p) #include #ifdef CAPTURE_CONTEXT_SWITCHES -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 35)) -TRACEPOINT_PROBE(sched_switch_probe, struct rq *rq, struct task_struct *prev, struct task_struct *next) -#elif (LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 35)) +TRACEPOINT_PROBE(sched_switch_probe, + struct rq *rq, + struct task_struct *prev, + struct task_struct *next) +#elif(LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) TRACEPOINT_PROBE(sched_switch_probe, struct task_struct *prev, struct task_struct *next) #else -TRACEPOINT_PROBE(sched_switch_probe, bool preempt, struct task_struct *prev, struct task_struct *next) +TRACEPOINT_PROBE(sched_switch_probe, + bool preempt, + struct task_struct *prev, + struct task_struct *next) #endif { struct event_data_t event_data; @@ -2408,42 +2392,48 @@ TRACEPOINT_PROBE(sched_switch_probe, bool preempt, struct task_struct *prev, str * Need to indicate ATOMIC (i.e. interrupt) context to avoid the event * handler calling printk() and potentially deadlocking the system. */ - record_event_all_consumers(PPME_SCHEDSWITCH_6_E, UF_USED | UF_ATOMIC, &event_data, KMOD_PROG_SCHED_SWITCH); + record_event_all_consumers(PPME_SCHEDSWITCH_6_E, + UF_USED | UF_ATOMIC, + &event_data, + KMOD_PROG_SCHED_SWITCH); } #endif #ifdef CAPTURE_SIGNAL_DELIVERIES -static __always_inline int siginfo_not_a_pointer(struct siginfo* info) -{ +static __always_inline int siginfo_not_a_pointer(struct siginfo *info) { #ifdef SEND_SIG_FORCED return info == SEND_SIG_NOINFO || info == SEND_SIG_PRIV || SEND_SIG_FORCED; #else - return info == (struct siginfo*)SEND_SIG_NOINFO || info == (struct siginfo*)SEND_SIG_PRIV; + return info == (struct siginfo *)SEND_SIG_NOINFO || info == (struct siginfo *)SEND_SIG_PRIV; #endif } -TRACEPOINT_PROBE(signal_deliver_probe, int sig, struct siginfo *info, struct k_sigaction *ka) -{ +TRACEPOINT_PROBE(signal_deliver_probe, int sig, struct siginfo *info, struct k_sigaction *ka) { struct event_data_t event_data; g_n_tracepoint_hit_inc(); event_data.category = PPMC_SIGNAL; event_data.event_info.signal_data.sig = sig; - if (siginfo_not_a_pointer(info)) + if(siginfo_not_a_pointer(info)) event_data.event_info.signal_data.info = NULL; else event_data.event_info.signal_data.info = info; event_data.event_info.signal_data.ka = ka; - record_event_all_consumers(PPME_SIGNALDELIVER_E, UF_USED | UF_ALWAYS_DROP, &event_data, KMOD_PROG_SIGNAL_DELIVER); + record_event_all_consumers(PPME_SIGNALDELIVER_E, + UF_USED | UF_ALWAYS_DROP, + &event_data, + KMOD_PROG_SIGNAL_DELIVER); } #endif #ifdef CAPTURE_PAGE_FAULTS -static void page_fault_probe(unsigned long address, struct pt_regs *regs, unsigned long error_code, kmod_prog_codes tp_type) -{ +static void page_fault_probe(unsigned long address, + struct pt_regs *regs, + unsigned long error_code, + kmod_prog_codes tp_type) { struct event_data_t event_data; /* We register both tracepoints under the same probe and @@ -2466,38 +2456,45 @@ static void page_fault_probe(unsigned long address, struct pt_regs *regs, unsign record_event_all_consumers(PPME_PAGE_FAULT_E, UF_ALWAYS_DROP, &event_data, tp_type); } -TRACEPOINT_PROBE(page_fault_user_probe, unsigned long address, struct pt_regs *regs, unsigned long error_code) -{ +TRACEPOINT_PROBE(page_fault_user_probe, + unsigned long address, + struct pt_regs *regs, + unsigned long error_code) { return page_fault_probe(address, regs, error_code, KMOD_PROG_PAGE_FAULT_USER); } -TRACEPOINT_PROBE(page_fault_kern_probe, unsigned long address, struct pt_regs *regs, unsigned long error_code) -{ +TRACEPOINT_PROBE(page_fault_kern_probe, + unsigned long address, + struct pt_regs *regs, + unsigned long error_code) { return page_fault_probe(address, regs, error_code, KMOD_PROG_PAGE_FAULT_KERNEL); } #endif #ifdef CAPTURE_SCHED_PROC_EXEC -TRACEPOINT_PROBE(sched_proc_exec_probe, struct task_struct *p, pid_t old_pid, struct linux_binprm *bprm) -{ +TRACEPOINT_PROBE(sched_proc_exec_probe, + struct task_struct *p, + pid_t old_pid, + struct linux_binprm *bprm) { struct event_data_t event_data; g_n_tracepoint_hit_inc(); /* We are not interested in kernel threads. */ - if(unlikely(current->flags & PF_KTHREAD)) - { + if(unlikely(current->flags & PF_KTHREAD)) { return; } event_data.category = PPMC_SCHED_PROC_EXEC; - record_event_all_consumers(PPME_SYSCALL_EXECVE_19_X, UF_NEVER_DROP, &event_data, KMOD_PROG_SCHED_PROC_EXEC); + record_event_all_consumers(PPME_SYSCALL_EXECVE_19_X, + UF_NEVER_DROP, + &event_data, + KMOD_PROG_SCHED_PROC_EXEC); } #endif #ifdef CAPTURE_SCHED_PROC_FORK -TRACEPOINT_PROBE(sched_proc_fork_probe, struct task_struct *parent, struct task_struct *child) -{ +TRACEPOINT_PROBE(sched_proc_fork_probe, struct task_struct *parent, struct task_struct *child) { struct event_data_t event_data; g_n_tracepoint_hit_inc(); @@ -2505,26 +2502,27 @@ TRACEPOINT_PROBE(sched_proc_fork_probe, struct task_struct *parent, struct task_ /* We are not interested in kernel threads. * The current thread here is the `parent`. */ - if(unlikely(current->flags & PF_KTHREAD)) - { - return; + if(unlikely(current->flags & PF_KTHREAD)) { + return; } event_data.category = PPMC_SCHED_PROC_FORK; event_data.event_info.sched_proc_fork_data.child = child; - record_event_all_consumers(PPME_SYSCALL_CLONE_20_X, UF_NEVER_DROP, &event_data, KMOD_PROG_SCHED_PROC_FORK); + record_event_all_consumers(PPME_SYSCALL_CLONE_20_X, + UF_NEVER_DROP, + &event_data, + KMOD_PROG_SCHED_PROC_FORK); } #endif -static int init_ring_buffer(struct ppm_ring_buffer_context *ring, unsigned long buffer_bytes_dim) -{ +static int init_ring_buffer(struct ppm_ring_buffer_context *ring, unsigned long buffer_bytes_dim) { unsigned int j; /* * Allocate the string storage in the ring descriptor */ ring->str_storage = (char *)__get_free_page(GFP_USER); - if (!ring->str_storage) { + if(!ring->str_storage) { pr_err("Error allocating the string storage\n"); goto init_ring_err; } @@ -2535,19 +2533,19 @@ static int init_ring_buffer(struct ppm_ring_buffer_context *ring, unsigned long * the event data generation functions, so that they always operate on a contiguous buffer. */ ring->buffer = vmalloc(buffer_bytes_dim + 2 * PAGE_SIZE); - if (ring->buffer == NULL) { + if(ring->buffer == NULL) { pr_err("Error allocating ring memory\n"); goto init_ring_err; } - for (j = 0; j < buffer_bytes_dim + 2 * PAGE_SIZE; j++) + for(j = 0; j < buffer_bytes_dim + 2 * PAGE_SIZE; j++) ring->buffer[j] = 0; /* * Allocate the buffer info structure */ ring->info = vmalloc(sizeof(struct ppm_ring_buffer_info)); - if (ring->info == NULL) { + if(ring->info == NULL) { pr_err("Error allocating ring memory\n"); goto init_ring_err; } @@ -2567,26 +2565,24 @@ static int init_ring_buffer(struct ppm_ring_buffer_context *ring, unsigned long return 0; } -static void free_ring_buffer(struct ppm_ring_buffer_context *ring) -{ - if (ring->info) { +static void free_ring_buffer(struct ppm_ring_buffer_context *ring) { + if(ring->info) { vfree(ring->info); ring->info = NULL; } - if (ring->buffer) { + if(ring->buffer) { vfree((void *)ring->buffer); ring->buffer = NULL; } - if (ring->str_storage) { + if(ring->str_storage) { free_page((unsigned long)ring->str_storage); ring->str_storage = NULL; } } -static void reset_ring_buffer(struct ppm_ring_buffer_context *ring) -{ +static void reset_ring_buffer(struct ppm_ring_buffer_context *ring) { /* * ring->preempt_count is not reset to 0 on purpose, to prevent a race condition * see ppm_open @@ -2617,97 +2613,93 @@ static void reset_ring_buffer(struct ppm_ring_buffer_context *ring) ring->last_print_time = ppm_nsecs(); } -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 15, 0)) -static void visit_tracepoint(struct tracepoint *tp, void *priv) -{ - if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SYS_ENTER])) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(3, 15, 0)) +static void visit_tracepoint(struct tracepoint *tp, void *priv) { + if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SYS_ENTER])) tp_sys_enter = tp; - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SYS_EXIT])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SYS_EXIT])) tp_sys_exit = tp; - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_PROC_EXIT])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_PROC_EXIT])) tp_sched_process_exit = tp; #ifdef CAPTURE_CONTEXT_SWITCHES - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_SWITCH])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_SWITCH])) tp_sched_switch = tp; #endif #ifdef CAPTURE_SIGNAL_DELIVERIES - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SIGNAL_DELIVER])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SIGNAL_DELIVER])) tp_signal_deliver = tp; #endif #ifdef CAPTURE_PAGE_FAULTS - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_PAGE_FAULT_USER])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_PAGE_FAULT_USER])) tp_page_fault_user = tp; - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_PAGE_FAULT_KERNEL])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_PAGE_FAULT_KERNEL])) tp_page_fault_kernel = tp; #endif #ifdef CAPTURE_SCHED_PROC_EXEC - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_PROC_EXEC])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_PROC_EXEC])) tp_sched_proc_exec = tp; #endif #ifdef CAPTURE_SCHED_PROC_FORK - else if (!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_PROC_FORK])) + else if(!strcmp(tp->name, kmod_prog_names[KMOD_PROG_SCHED_PROC_FORK])) tp_sched_proc_fork = tp; #endif } -static int get_tracepoint_handles(void) -{ +static int get_tracepoint_handles(void) { for_each_kernel_tracepoint(visit_tracepoint, NULL); - if (!tp_sys_enter) { + if(!tp_sys_enter) { pr_err("failed to find sys_enter tracepoint\n"); return -ENOENT; } - if (!tp_sys_exit) { + if(!tp_sys_exit) { pr_err("failed to find sys_exit tracepoint\n"); return -ENOENT; } - if (!tp_sched_process_exit) { + if(!tp_sched_process_exit) { pr_err("failed to find sched_process_exit tracepoint\n"); return -ENOENT; } #ifdef CAPTURE_CONTEXT_SWITCHES - if (!tp_sched_switch) { + if(!tp_sched_switch) { pr_err("failed to find sched_switch tracepoint\n"); return -ENOENT; } #endif #ifdef CAPTURE_SIGNAL_DELIVERIES - if (!tp_signal_deliver) { + if(!tp_signal_deliver) { pr_err("failed to find signal_deliver tracepoint\n"); return -ENOENT; } #endif #ifdef CAPTURE_PAGE_FAULTS - if (!tp_page_fault_user) { + if(!tp_page_fault_user) { pr_notice("failed to find page_fault_user tracepoint, disabling page-faults\n"); g_fault_tracepoint_disabled = true; } - if (!tp_page_fault_kernel) { + if(!tp_page_fault_kernel) { pr_notice("failed to find page_fault_kernel tracepoint, disabling page-faults\n"); g_fault_tracepoint_disabled = true; } #endif #ifdef CAPTURE_SCHED_PROC_EXEC - if (!tp_sched_proc_exec) - { + if(!tp_sched_proc_exec) { pr_err("failed to find 'sched_process_exec' tracepoint\n"); return -ENOENT; } #endif #ifdef CAPTURE_SCHED_PROC_FORK - if (!tp_sched_proc_fork) - { + if(!tp_sched_proc_fork) { pr_err("failed to find 'sched_process_fork' tracepoint\n"); return -ENOENT; } @@ -2716,8 +2708,7 @@ static int get_tracepoint_handles(void) return 0; } #else -static int get_tracepoint_handles(void) -{ +static int get_tracepoint_handles(void) { return 0; } #endif @@ -2733,11 +2724,11 @@ static char *ppm_devnode(struct device *dev, mode_t *mode) #endif /* LINUX_VERSION_CODE > KERNEL_VERSION(3, 3, 0) */ #endif /* LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) */ { - if (mode) { + if(mode) { *mode = 0400; - if (dev) - if (MINOR(dev->devt) == g_ppm_numdevs) + if(dev) + if(MINOR(dev->devt) == g_ppm_numdevs) *mode = 0222; } @@ -2745,18 +2736,17 @@ static char *ppm_devnode(struct device *dev, mode_t *mode) } #endif /* LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) */ -static int do_cpu_callback(unsigned long cpu, long sd_action) -{ +static int do_cpu_callback(unsigned long cpu, long sd_action) { struct ppm_ring_buffer_context *ring; struct ppm_consumer_t *consumer; struct event_data_t event_data; - if (sd_action != 0) { + if(sd_action != 0) { rcu_read_lock(); list_for_each_entry_rcu(consumer, &g_consumer_list, node) { ring = per_cpu_ptr(consumer->ring_buffers, cpu); - if (sd_action == 1) { + if(sd_action == 1) { /* * If the cpu was offline when the consumer was created, * this won't do anything because we never created a ring @@ -2765,7 +2755,7 @@ static int do_cpu_callback(unsigned long cpu, long sd_action) * on this device anyways, so do it in ppm_open. */ ring->cpu_online = true; - } else if (sd_action == 2) { + } else if(sd_action == 2) { ring->cpu_online = false; } } @@ -2780,15 +2770,13 @@ static int do_cpu_callback(unsigned long cpu, long sd_action) return 0; } -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) -static int scap_cpu_online(unsigned int cpu) -{ +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) +static int scap_cpu_online(unsigned int cpu) { vpr_info("scap_cpu_online on cpu %d\n", cpu); return do_cpu_callback(cpu, 1); } -static int scap_cpu_offline(unsigned int cpu) -{ +static int scap_cpu_offline(unsigned int cpu) { vpr_info("scap_cpu_offline on cpu %d\n", cpu); return do_cpu_callback(cpu, 2); } @@ -2796,13 +2784,11 @@ static int scap_cpu_offline(unsigned int cpu) /* * This gets called every time a CPU is added or removed */ -static int cpu_callback(struct notifier_block *self, unsigned long action, - void *hcpu) -{ +static int cpu_callback(struct notifier_block *self, unsigned long action, void *hcpu) { unsigned long cpu = (unsigned long)hcpu; long sd_action = 0; - switch (action) { + switch(action) { case CPU_UP_PREPARE: #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) case CPU_UP_PREPARE_FROZEN: @@ -2819,26 +2805,25 @@ static int cpu_callback(struct notifier_block *self, unsigned long action, break; } - if (do_cpu_callback(cpu, sd_action) < 0) + if(do_cpu_callback(cpu, sd_action) < 0) return NOTIFY_BAD; else return NOTIFY_OK; } static struct notifier_block cpu_notifier = { - .notifier_call = &cpu_callback, - .next = NULL, + .notifier_call = &cpu_callback, + .next = NULL, }; #endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0) */ -static int scap_init(void) -{ +static int scap_init(void) { dev_t dev; unsigned int cpu; unsigned int num_cpus; int ret; int acrret = 0; -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) int hp_ret; #endif int j; @@ -2851,7 +2836,7 @@ static int scap_init(void) pr_info("driver loading, " DRIVER_NAME " " DRIVER_VERSION "\n"); ret = get_tracepoint_handles(); - if (ret < 0) + if(ret < 0) goto init_module_err; num_cpus = 0; @@ -2863,7 +2848,7 @@ static int scap_init(void) * Initialize the user I/O */ acrret = alloc_chrdev_region(&dev, 0, num_cpus + 1, DRIVER_DEVICE_NAME); - if (acrret < 0) { + if(acrret < 0) { pr_err("could not allocate major number for %s\n", DRIVER_DEVICE_NAME); ret = -ENOMEM; goto init_module_err; @@ -2874,7 +2859,7 @@ static int scap_init(void) #else g_ppm_class = class_create(DRIVER_DEVICE_NAME); #endif - if (IS_ERR(g_ppm_class)) { + if(IS_ERR(g_ppm_class)) { pr_err("can't allocate device class\n"); ret = -EFAULT; goto init_module_err; @@ -2891,7 +2876,7 @@ static int scap_init(void) #else g_ppm_devs = kmalloc_array(g_ppm_numdevs, sizeof(struct ppm_device), GFP_KERNEL); #endif - if (!g_ppm_devs) { + if(!g_ppm_devs) { pr_err("can't allocate devices\n"); ret = -ENOMEM; goto init_module_err; @@ -2900,11 +2885,11 @@ static int scap_init(void) /* * We create a unique user level device for each of the ring buffers */ - for (j = 0; j < g_ppm_numdevs; ++j) { + for(j = 0; j < g_ppm_numdevs; ++j) { cdev_init(&g_ppm_devs[j].cdev, &g_ppm_fops); g_ppm_devs[j].dev = MKDEV(g_ppm_major, j); - if (cdev_add(&g_ppm_devs[j].cdev, g_ppm_devs[j].dev, 1) < 0) { + if(cdev_add(&g_ppm_devs[j].cdev, g_ppm_devs[j].dev, 1) < 0) { pr_err("could not allocate chrdev for %s\n", DRIVER_DEVICE_NAME); ret = -EFAULT; goto init_module_err; @@ -2915,13 +2900,14 @@ static int scap_init(void) #else device = class_device_create( #endif - g_ppm_class, NULL, /* no parent device */ - g_ppm_devs[j].dev, - NULL, /* no additional data */ - DRIVER_DEVICE_NAME "%d", - j); + g_ppm_class, + NULL, /* no parent device */ + g_ppm_devs[j].dev, + NULL, /* no additional data */ + DRIVER_DEVICE_NAME "%d", + j); - if (IS_ERR(device)) { + if(IS_ERR(device)) { pr_err("error creating the device for %s\n", DRIVER_DEVICE_NAME); cdev_del(&g_ppm_devs[j].cdev); ret = -EFAULT; @@ -2937,7 +2923,7 @@ static int scap_init(void) /* * Snaplen lookahead initialization */ - if (dpi_lookahead_init() != PPM_SUCCESS) { + if(dpi_lookahead_init() != PPM_SUCCESS) { pr_err("initializing lookahead-based snaplen failed\n"); ret = -EFAULT; goto init_module_err; @@ -2947,12 +2933,12 @@ static int scap_init(void) * Set up our callback in case we get a hotplug even while we are * initializing the cpu structures */ -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) hp_ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, - DRIVER_NAME "/driver:online", - scap_cpu_online, - scap_cpu_offline); - if (hp_ret <= 0) { + DRIVER_NAME "/driver:online", + scap_cpu_online, + scap_cpu_offline); + if(hp_ret <= 0) { pr_err("error registering cpu hotplug callback\n"); ret = hp_ret; goto init_module_err; @@ -2964,29 +2950,29 @@ static int scap_init(void) // Initialize globals g_tracepoints_attached = 0; - for (j = 0; j < KMOD_PROG_ATTACHED_MAX; j++) - { + for(j = 0; j < KMOD_PROG_ATTACHED_MAX; j++) { g_tracepoints_refs[j] = 0; } return 0; init_module_err: - for (j = 0; j < n_created_devices; ++j) { + for(j = 0; j < n_created_devices; ++j) { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) device_destroy( #else class_device_destroy( #endif - g_ppm_class, g_ppm_devs[j].dev); + g_ppm_class, + g_ppm_devs[j].dev); cdev_del(&g_ppm_devs[j].cdev); } - if (g_ppm_class) + if(g_ppm_class) class_destroy(g_ppm_class); - if (acrret == 0) + if(acrret == 0) unregister_chrdev_region(dev, g_ppm_numdevs); kfree(g_ppm_devs); @@ -2994,23 +2980,23 @@ static int scap_init(void) return ret; } -static void scap_exit(void) -{ +static void scap_exit(void) { int j; pr_info("driver unloading\n"); - for (j = 0; j < g_ppm_numdevs; ++j) { + for(j = 0; j < g_ppm_numdevs; ++j) { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) device_destroy( #else class_device_destroy( #endif - g_ppm_class, g_ppm_devs[j].dev); + g_ppm_class, + g_ppm_devs[j].dev); cdev_del(&g_ppm_devs[j].cdev); } - if (g_ppm_class) + if(g_ppm_class) class_destroy(g_ppm_class); unregister_chrdev_region(MKDEV(g_ppm_major, 0), g_ppm_numdevs + 1); @@ -3021,8 +3007,8 @@ static void scap_exit(void) tracepoint_synchronize_unregister(); #endif -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) - if (hp_state > 0) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)) + if(hp_state > 0) cpuhp_remove_state_nocalls(hp_state); #else unregister_cpu_notifier(&cpu_notifier); @@ -3037,8 +3023,7 @@ MODULE_INFO(api_version, PPM_API_CURRENT_VERSION_STRING); MODULE_INFO(schema_version, PPM_SCHEMA_CURRENT_VERSION_STRING); /* the `const` qualifier will be discarded on old kernel versions (<`2.6.36`) */ -static int set_g_buffer_bytes_dim(const char *val, const struct kernel_param *kp) -{ +static int set_g_buffer_bytes_dim(const char *val, const struct kernel_param *kp) { unsigned long dim = 0; /* `kstrtoul` is defined only on these kernels. @@ -3047,8 +3032,7 @@ static int set_g_buffer_bytes_dim(const char *val, const struct kernel_param *kp #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 39) int ret = 0; ret = kstrtoul(val, 10, &dim); - if(ret != 0) - { + if(ret != 0) { pr_err("parsing of 'g_buffer_bytes_dim' failed!\n"); return -EINVAL; } @@ -3056,18 +3040,19 @@ static int set_g_buffer_bytes_dim(const char *val, const struct kernel_param *kp /* You can find more info about the simple_strtoull behavior here! * https://elixir.bootlin.com/linux/latest/source/arch/x86/boot/string.c#L120 */ - char* endp = NULL; + char *endp = NULL; dim = simple_strtoull(val, &endp, 10); - if(!endp || (*endp != '\0')) - { + if(!endp || (*endp != '\0')) { pr_err("parsing of 'g_buffer_bytes_dim' failed!\n"); return -EINVAL; } #endif - if(!validate_buffer_bytes_dim(dim, PAGE_SIZE)) - { - pr_err("the specified per-CPU ring buffer dimension (%lu) is not allowed! Please use a power of 2 and a multiple of the actual page_size (%lu)!\n", dim, PAGE_SIZE); + if(!validate_buffer_bytes_dim(dim, PAGE_SIZE)) { + pr_err("the specified per-CPU ring buffer dimension (%lu) is not allowed! Please use a " + "power of 2 and a multiple of the actual page_size (%lu)!\n", + dim, + PAGE_SIZE); return -EINVAL; } return param_set_ulong(val, kp); @@ -3076,16 +3061,24 @@ static int set_g_buffer_bytes_dim(const char *val, const struct kernel_param *kp #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 36) /* `struct kernel_param_ops` and `module_param_cb` are defined only on kernels >= `2.6.36` */ static const struct kernel_param_ops g_buffer_bytes_dim_ops = { - .set = set_g_buffer_bytes_dim, - .get = param_get_ulong, + .set = set_g_buffer_bytes_dim, + .get = param_get_ulong, }; module_param_cb(g_buffer_bytes_dim, &g_buffer_bytes_dim_ops, &g_buffer_bytes_dim, 0644); #else -module_param_call(g_buffer_bytes_dim, set_g_buffer_bytes_dim, param_get_ulong, &g_buffer_bytes_dim, 0644); -#endif -MODULE_PARM_DESC(g_buffer_bytes_dim, "This is the dimension of a single per-CPU buffer in bytes. Please note: this buffer will be mapped twice in the process virtual memory, so pay attention to its size."); +module_param_call(g_buffer_bytes_dim, + set_g_buffer_bytes_dim, + param_get_ulong, + &g_buffer_bytes_dim, + 0644); +#endif +MODULE_PARM_DESC( + g_buffer_bytes_dim, + "This is the dimension of a single per-CPU buffer in bytes. Please note: this buffer will " + "be mapped twice in the process virtual memory, so pay attention to its size."); module_param(max_consumers, uint, 0444); -MODULE_PARM_DESC(max_consumers, "Maximum number of consumers that can simultaneously open the devices"); +MODULE_PARM_DESC(max_consumers, + "Maximum number of consumers that can simultaneously open the devices"); #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) module_param(verbose, bool, 0444); #endif diff --git a/driver/modern_bpf/CMakeLists.txt b/driver/modern_bpf/CMakeLists.txt index 4bdd04fdbc..906c791c94 100644 --- a/driver/modern_bpf/CMakeLists.txt +++ b/driver/modern_bpf/CMakeLists.txt @@ -2,264 +2,309 @@ # # Copyright (C) 2023 The Falco Authors. # -# This file is dual licensed under either the MIT or GPL 2. See -# MIT.txt or GPL.txt for full copies of the license. +# This file is dual licensed under either the MIT or GPL 2. See MIT.txt or GPL.txt for full copies +# of the license. # option(MODERN_BPF_DEBUG_MODE "Enable BPF debug prints" OFF) option(MODERN_BPF_EXCLUDE_PROGS "Regex to exclude tail-called programs" "") -######################## +# ################################################################################################## # Debug mode -######################## +# ################################################################################################## if(MODERN_BPF_DEBUG_MODE) - set(DEBUG "MODERN_BPF_DEBUG") + set(DEBUG "MODERN_BPF_DEBUG") else() - set(DEBUG "") + set(DEBUG "") endif() message(STATUS "${MODERN_BPF_LOG_PREFIX} MODERN_BPF_DEBUG_MODE: ${MODERN_BPF_DEBUG_MODE}") -######################## +# ################################################################################################## # Check kernel version. -######################## +# ################################################################################################## -# We check it here because the skeleton could be provided with the `MODERN_BPF_SKEL_DIR` env variable -# so the compilation is still possible on older kernels. -execute_process(COMMAND uname -r OUTPUT_VARIABLE UNAME_RESULT OUTPUT_STRIP_TRAILING_WHITESPACE) +# We check it here because the skeleton could be provided with the `MODERN_BPF_SKEL_DIR` env +# variable so the compilation is still possible on older kernels. +execute_process( + COMMAND uname -r + OUTPUT_VARIABLE UNAME_RESULT + OUTPUT_STRIP_TRAILING_WHITESPACE +) string(REGEX MATCH "[0-9]+.[0-9]+" LINUX_KERNEL_VERSION ${UNAME_RESULT}) set(modern_bpf_min_kver_map_x86_64 5.8) set(modern_bpf_min_kver_map_aarch64 5.8) set(modern_bpf_min_kver_map_s390x 5.8) set(modern_bpf_min_kver_map_ppc64le 5.8) -if (LINUX_KERNEL_VERSION VERSION_LESS ${modern_bpf_min_kver_map_${CMAKE_HOST_SYSTEM_PROCESSOR}}) - message(WARNING "${MODERN_BPF_LOG_PREFIX} To run this driver you need a Linux kernel version >= ${modern_bpf_min_kver_map_${CMAKE_HOST_SYSTEM_PROCESSOR}} but actual kernel version is: ${UNAME_RESULT}") +if(LINUX_KERNEL_VERSION VERSION_LESS ${modern_bpf_min_kver_map_${CMAKE_HOST_SYSTEM_PROCESSOR}}) + message( + WARNING + "${MODERN_BPF_LOG_PREFIX} To run this driver you need a Linux kernel version >= ${modern_bpf_min_kver_map_${CMAKE_HOST_SYSTEM_PROCESSOR}} but actual kernel version is: ${UNAME_RESULT}" + ) endif() -######################## +# ################################################################################################## # Get driver version. -######################## +# ################################################################################################## # This is needed to obtain the modern bpf driver version include(compute_versions RESULT_VARIABLE RESULT) if(RESULT STREQUAL NOTFOUND) - message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} problem with compute_versions.cmake in ${CMAKE_MODULE_PATH}") + message( + FATAL_ERROR + "${MODERN_BPF_LOG_PREFIX} problem with compute_versions.cmake in ${CMAKE_MODULE_PATH}" + ) endif() compute_versions(../API_VERSION ../SCHEMA_VERSION) configure_file(../driver_config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/../driver_config.h) -######################## +# ################################################################################################## # Check clang version. -######################## +# ################################################################################################## # If the user doesn't provide the path to `clang` try to find it locally if(NOT MODERN_CLANG_EXE) - find_program(MODERN_CLANG_EXE NAMES clang DOC "Path to clang executable") - if(NOT MODERN_CLANG_EXE) - message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} unable to find clang") - endif() + find_program( + MODERN_CLANG_EXE + NAMES clang + DOC "Path to clang executable" + ) + if(NOT MODERN_CLANG_EXE) + message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} unable to find clang") + endif() endif() # If it is a relative path we convert it to an absolute one relative to the root source directory. -get_filename_component(MODERN_CLANG_EXE "${MODERN_CLANG_EXE}" ABSOLUTE BASE_DIR "${CMAKE_SOURCE_DIR}") +get_filename_component( + MODERN_CLANG_EXE "${MODERN_CLANG_EXE}" ABSOLUTE BASE_DIR "${CMAKE_SOURCE_DIR}" +) message(STATUS "${MODERN_BPF_LOG_PREFIX} clang used by the modern bpf probe: '${MODERN_CLANG_EXE}'") # Check the right clang version (>=12) -execute_process(COMMAND ${MODERN_CLANG_EXE} --version - OUTPUT_VARIABLE CLANG_version_output - ERROR_VARIABLE CLANG_version_error - RESULT_VARIABLE CLANG_version_result - OUTPUT_STRIP_TRAILING_WHITESPACE +execute_process( + COMMAND ${MODERN_CLANG_EXE} --version + OUTPUT_VARIABLE CLANG_version_output + ERROR_VARIABLE CLANG_version_error + RESULT_VARIABLE CLANG_version_result + OUTPUT_STRIP_TRAILING_WHITESPACE ) if(${CLANG_version_result} EQUAL 0) - if("${CLANG_version_output}" MATCHES "clang version ([^\n]+)\n") - # Transform X.Y.Z into X;Y;Z which can then be interpreted as a list - set(CLANG_VERSION "${CMAKE_MATCH_1}") - string(REPLACE "." ";" CLANG_VERSION_LIST ${CLANG_VERSION}) - list(GET CLANG_VERSION_LIST 0 CLANG_VERSION_MAJOR) - - string(COMPARE LESS ${CLANG_VERSION_MAJOR} 12 CLANG_VERSION_MAJOR_LT12) - - if(${CLANG_VERSION_MAJOR_LT12}) - message(WARNING "${MODERN_BPF_LOG_PREFIX} clang '${CLANG_VERSION}' is too old for compiling the modern BPF probe, you need at least '12.0.0' version") - endif() - - message(STATUS "${MODERN_BPF_LOG_PREFIX} Found clang version: ${CLANG_VERSION}") - else() - message(WARNING "${MODERN_BPF_LOG_PREFIX} Failed to parse clang version string: ${CLANG_version_output}") - endif() + if("${CLANG_version_output}" MATCHES "clang version ([^\n]+)\n") + # Transform X.Y.Z into X;Y;Z which can then be interpreted as a list + set(CLANG_VERSION "${CMAKE_MATCH_1}") + string(REPLACE "." ";" CLANG_VERSION_LIST ${CLANG_VERSION}) + list(GET CLANG_VERSION_LIST 0 CLANG_VERSION_MAJOR) + + string(COMPARE LESS ${CLANG_VERSION_MAJOR} 12 CLANG_VERSION_MAJOR_LT12) + + if(${CLANG_VERSION_MAJOR_LT12}) + message( + WARNING + "${MODERN_BPF_LOG_PREFIX} clang '${CLANG_VERSION}' is too old for compiling the modern BPF probe, you need at least '12.0.0' version" + ) + endif() + + message(STATUS "${MODERN_BPF_LOG_PREFIX} Found clang version: ${CLANG_VERSION}") + else() + message( + WARNING + "${MODERN_BPF_LOG_PREFIX} Failed to parse clang version string: ${CLANG_version_output}" + ) + endif() else() - message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} Command \"${MODERN_CLANG_EXE} --version\" failed with output:\n ${CLANG_version_error}") + message( + FATAL_ERROR + "${MODERN_BPF_LOG_PREFIX} Command \"${MODERN_CLANG_EXE} --version\" failed with output:\n ${CLANG_version_error}" + ) endif() -######################## +# ################################################################################################## # Check bpftool version. -######################## +# ################################################################################################## # If the user doesn't provide the path to `bpftool` try to find it locally if(NOT MODERN_BPFTOOL_EXE) - find_program(MODERN_BPFTOOL_EXE NAMES bpftool DOC "Path to bpftool executable") - if(NOT MODERN_BPFTOOL_EXE) - message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} unable to find bpftool on the system") - endif() + find_program( + MODERN_BPFTOOL_EXE + NAMES bpftool + DOC "Path to bpftool executable" + ) + if(NOT MODERN_BPFTOOL_EXE) + message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} unable to find bpftool on the system") + endif() endif() # If it is a relative path we convert it to an absolute one relative to the root source directory. -get_filename_component(MODERN_BPFTOOL_EXE "${MODERN_BPFTOOL_EXE}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}") -message(STATUS "${MODERN_BPF_LOG_PREFIX} bpftool used by the modern bpf probe: '${MODERN_BPFTOOL_EXE}'") - -# Check the right bpftool version -# Since we want bpftool to have the gen skeleton subcommands and both -# gen and skeleton were added together, we can just grep the help -# output for gen. see: -# https://lore.kernel.org/bpf/20191210011438.4182911-12-andriin@fb.com/ +get_filename_component( + MODERN_BPFTOOL_EXE "${MODERN_BPFTOOL_EXE}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}" +) +message( + STATUS "${MODERN_BPF_LOG_PREFIX} bpftool used by the modern bpf probe: '${MODERN_BPFTOOL_EXE}'" +) + +# Check the right bpftool version Since we want bpftool to have the gen skeleton subcommands and +# both gen and skeleton were added together, we can just grep the help output for gen. see: +# https://lore.kernel.org/bpf/20191210011438.4182911-12-andriin@fb.com/ # -# This is not as strict as checking versions, but it also allows -# compiling on bpftool versions for backported kernels. -execute_process(COMMAND sh -c "${MODERN_BPFTOOL_EXE} help 2>&1 | grep -wq 'gen'" - OUTPUT_VARIABLE BPFTOOL_version_output - ERROR_VARIABLE BPFTOOL_version_error - RESULT_VARIABLE BPFTOOL_version_result - OUTPUT_STRIP_TRAILING_WHITESPACE +# This is not as strict as checking versions, but it also allows compiling on bpftool versions for +# backported kernels. +execute_process( + COMMAND sh -c "${MODERN_BPFTOOL_EXE} help 2>&1 | grep -wq 'gen'" + OUTPUT_VARIABLE BPFTOOL_version_output + ERROR_VARIABLE BPFTOOL_version_error + RESULT_VARIABLE BPFTOOL_version_result + OUTPUT_STRIP_TRAILING_WHITESPACE ) if(NOT ${BPFTOOL_version_result} EQUAL 0) - message(WARNING "${MODERN_BPF_LOG_PREFIX} bpftool does not support gen command") + message(WARNING "${MODERN_BPF_LOG_PREFIX} bpftool does not support gen command") endif() -######################## +# ################################################################################################## # Get clang bpf system includes -######################## +# ################################################################################################## execute_process( - COMMAND bash -c "${MODERN_CLANG_EXE} -v -E - < /dev/null 2>&1 | - sed -n '/<...> search starts here:/,/End of search list./{ s| \\(/.*\\)|-idirafter \\1|p }'" - OUTPUT_VARIABLE CLANG_SYSTEM_INCLUDES_output - ERROR_VARIABLE CLANG_SYSTEM_INCLUDES_error - RESULT_VARIABLE CLANG_SYSTEM_INCLUDES_result - OUTPUT_STRIP_TRAILING_WHITESPACE + COMMAND bash -c "${MODERN_CLANG_EXE} -v -E - < /dev/null 2>&1 | + sed -n '/<...> search starts here:/,/End of search list./{ s| \\(/.*\\)|-idirafter \\1|p }'" + OUTPUT_VARIABLE CLANG_SYSTEM_INCLUDES_output + ERROR_VARIABLE CLANG_SYSTEM_INCLUDES_error + RESULT_VARIABLE CLANG_SYSTEM_INCLUDES_result + OUTPUT_STRIP_TRAILING_WHITESPACE ) if(${CLANG_SYSTEM_INCLUDES_result} EQUAL 0) - string(REPLACE "\n" " " CLANG_SYSTEM_INCLUDES "${CLANG_SYSTEM_INCLUDES_output}") - message(STATUS "${MODERN_BPF_LOG_PREFIX} BPF system include flags: ${CLANG_SYSTEM_INCLUDES}") + string(REPLACE "\n" " " CLANG_SYSTEM_INCLUDES "${CLANG_SYSTEM_INCLUDES_output}") + message(STATUS "${MODERN_BPF_LOG_PREFIX} BPF system include flags: ${CLANG_SYSTEM_INCLUDES}") else() - message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} Failed to determine BPF system includes: ${CLANG_SYSTEM_INCLUDES_error}") + message( + FATAL_ERROR + "${MODERN_BPF_LOG_PREFIX} Failed to determine BPF system includes: ${CLANG_SYSTEM_INCLUDES_error}" + ) endif() -######################## +# ################################################################################################## # Get target arch -######################## - -execute_process(COMMAND uname -m - COMMAND sed "s/x86_64/x86/" - COMMAND sed "s/aarch64/arm64/" - COMMAND sed "s/ppc64le/powerpc/" - COMMAND sed "s/mips.*/mips/" - COMMAND sed "s/s390x/s390/" - OUTPUT_VARIABLE ARCH_output - ERROR_VARIABLE ARCH_error - RESULT_VARIABLE ARCH_result - OUTPUT_STRIP_TRAILING_WHITESPACE +# ################################################################################################## + +execute_process( + COMMAND uname -m + COMMAND sed "s/x86_64/x86/" + COMMAND sed "s/aarch64/arm64/" + COMMAND sed "s/ppc64le/powerpc/" + COMMAND sed "s/mips.*/mips/" + COMMAND sed "s/s390x/s390/" + OUTPUT_VARIABLE ARCH_output + ERROR_VARIABLE ARCH_error + RESULT_VARIABLE ARCH_result + OUTPUT_STRIP_TRAILING_WHITESPACE ) if(${ARCH_result} EQUAL 0) - set(ARCH ${ARCH_output}) - message(STATUS "${MODERN_BPF_LOG_PREFIX} Target arch: ${ARCH}") + set(ARCH ${ARCH_output}) + message(STATUS "${MODERN_BPF_LOG_PREFIX} Target arch: ${ARCH}") else() - message(FATAL_ERROR "${MODERN_BPF_LOG_PREFIX} Failed to determine target architecture: ${ARCH_error}") + message( + FATAL_ERROR + "${MODERN_BPF_LOG_PREFIX} Failed to determine target architecture: ${ARCH_error}" + ) endif() -######################## +# ################################################################################################## # Set includes and compilation flags -######################## +# ################################################################################################## # Get modern probe include. list(APPEND MODERN_PROBE_INCLUDE "-I${CMAKE_CURRENT_SOURCE_DIR}") -# Note here we use the libs root directory since we want to avoid conflicts between the `bpf` folder inside -# `driver` and the `libbpf` includes. +# Note here we use the libs root directory since we want to avoid conflicts between the `bpf` folder +# inside `driver` and the `libbpf` includes. set(PPM_INCLUDE ${LIBS_DIR}) -## Set CLANG FLAGS +# Set CLANG FLAGS set(CLANG_FLAGS "") -list(APPEND CLANG_FLAGS - -g -O2 - -target bpf - -D__${DEBUG}__ - -D__TARGET_ARCH_${ARCH} # Match libbpf usage in `/libbpf/src/bpf_tracing.h` - -D__USE_VMLINUX__ # Used to compile without kernel headers. - -I${LIBBPF_INCLUDE} - ${MODERN_PROBE_INCLUDE} - -I${PPM_INCLUDE} - -isystem +list( + APPEND + CLANG_FLAGS + -g + -O2 + -target + bpf + -D__${DEBUG}__ + -D__TARGET_ARCH_${ARCH} # Match libbpf usage in `/libbpf/src/bpf_tracing.h` + -D__USE_VMLINUX__ # Used to compile without kernel headers. + -I${LIBBPF_INCLUDE} + ${MODERN_PROBE_INCLUDE} + -I${PPM_INCLUDE} + -isystem ) message(STATUS "${MODERN_BPF_LOG_PREFIX} Compilation flags: ${CLANG_FLAGS}") -## Search all bpf includes files. (we can use bpf.h files) +# Search all bpf includes files. (we can use bpf.h files) file(GLOB_RECURSE BPF_H_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.h) -## Search all bpf.c files +# Search all bpf.c files file(GLOB_RECURSE BPF_C_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.bpf.c) -######################## +# ################################################################################################## # Generate an `bpf.o` file for every `bpf.c` -######################## +# ################################################################################################## foreach(BPF_C_FILE ${BPF_C_FILES}) - get_filename_component(file_stem ${BPF_C_FILE} NAME_WE) - - if(MODERN_BPF_EXCLUDE_PROGS) - if(${file_stem} MATCHES "${MODERN_BPF_EXCLUDE_PROGS}") - message(STATUS "Exclude file: ${file_stem}") - continue() - endif() - endif() - - set(BPF_O_FILE ${CMAKE_CURRENT_BINARY_DIR}/${file_stem}.bpf.o) - - add_custom_command( - OUTPUT ${BPF_O_FILE} - COMMAND ${MODERN_CLANG_EXE} ${CLANG_FLAGS} ${CLANG_SYSTEM_INCLUDES} -c ${BPF_C_FILE} -o ${BPF_O_FILE} - VERBATIM - DEPENDS libbpf - DEPENDS ${BPF_C_FILE} ${BPF_H_FILES} - COMMENT "${MODERN_BPF_LOG_PREFIX} Building BPF object: ${BPF_O_FILE}" - ) - - list(APPEND BPF_OBJECT_FILES ${BPF_O_FILE}) + get_filename_component(file_stem ${BPF_C_FILE} NAME_WE) + + if(MODERN_BPF_EXCLUDE_PROGS) + if(${file_stem} MATCHES "${MODERN_BPF_EXCLUDE_PROGS}") + message(STATUS "Exclude file: ${file_stem}") + continue() + endif() + endif() + + set(BPF_O_FILE ${CMAKE_CURRENT_BINARY_DIR}/${file_stem}.bpf.o) + + add_custom_command( + OUTPUT ${BPF_O_FILE} + COMMAND ${MODERN_CLANG_EXE} ${CLANG_FLAGS} ${CLANG_SYSTEM_INCLUDES} -c ${BPF_C_FILE} -o + ${BPF_O_FILE} + VERBATIM + DEPENDS libbpf + DEPENDS ${BPF_C_FILE} ${BPF_H_FILES} + COMMENT "${MODERN_BPF_LOG_PREFIX} Building BPF object: ${BPF_O_FILE}" + ) + + list(APPEND BPF_OBJECT_FILES ${BPF_O_FILE}) endforeach() -######################## +# ################################################################################################## # Generate a unique `bpf.o` file -######################## +# ################################################################################################## set(UNIQUE_BPF_O_FILE ${CMAKE_CURRENT_BINARY_DIR}/${UNIQUE_BPF_O_FILE_NAME}.o) add_custom_command( - OUTPUT ${UNIQUE_BPF_O_FILE} - COMMAND ${MODERN_BPFTOOL_EXE} gen object ${UNIQUE_BPF_O_FILE} ${BPF_OBJECT_FILES} - VERBATIM - DEPENDS ${BPF_OBJECT_FILES} - COMMENT "${MODERN_BPF_LOG_PREFIX} Building BPF unique object file: ${UNIQUE_BPF_O_FILE}" + OUTPUT ${UNIQUE_BPF_O_FILE} + COMMAND ${MODERN_BPFTOOL_EXE} gen object ${UNIQUE_BPF_O_FILE} ${BPF_OBJECT_FILES} + VERBATIM + DEPENDS ${BPF_OBJECT_FILES} + COMMENT "${MODERN_BPF_LOG_PREFIX} Building BPF unique object file: ${UNIQUE_BPF_O_FILE}" ) -######################## +# ################################################################################################## # Generate the skeleton file -######################## +# ################################################################################################## set(BPF_SKEL_FILE ${MODERN_BPF_SKEL_DIR}/${UNIQUE_BPF_O_FILE_NAME}.skel.h) add_custom_command( - OUTPUT ${BPF_SKEL_FILE} - COMMAND bash -c "${MODERN_BPFTOOL_EXE} gen skeleton ${UNIQUE_BPF_O_FILE} > ${BPF_SKEL_FILE}" - VERBATIM - DEPENDS ${UNIQUE_BPF_O_FILE} - COMMENT "${MODERN_BPF_LOG_PREFIX} Building BPF skeleton: ${BPF_SKEL_FILE}" + OUTPUT ${BPF_SKEL_FILE} + COMMAND bash -c "${MODERN_BPFTOOL_EXE} gen skeleton ${UNIQUE_BPF_O_FILE} > ${BPF_SKEL_FILE}" + VERBATIM + DEPENDS ${UNIQUE_BPF_O_FILE} + COMMENT "${MODERN_BPF_LOG_PREFIX} Building BPF skeleton: ${BPF_SKEL_FILE}" ) -######################## +# ################################################################################################## # Add the skeleton as a custom target -######################## +# ################################################################################################## add_custom_target(ProbeSkeleton ALL DEPENDS ${BPF_SKEL_FILE}) diff --git a/driver/modern_bpf/definitions/events_dimensions.h b/driver/modern_bpf/definitions/events_dimensions.h index c498c6b274..371538c617 100644 --- a/driver/modern_bpf/definitions/events_dimensions.h +++ b/driver/modern_bpf/definitions/events_dimensions.h @@ -35,7 +35,8 @@ #define GETSOCKNAME_E_SIZE HEADER_LEN #define GETSOCKNAME_X_SIZE HEADER_LEN #define MKDIR_E_SIZE HEADER_LEN + sizeof(uint32_t) + PARAM_LEN -#define MMAP_E_SIZE HEADER_LEN + sizeof(uint64_t) * 3 + sizeof(int64_t) + sizeof(uint32_t) * 2 + PARAM_LEN * 6 +#define MMAP_E_SIZE \ + HEADER_LEN + sizeof(uint64_t) * 3 + sizeof(int64_t) + sizeof(uint32_t) * 2 + PARAM_LEN * 6 #define MMAP_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) * 3 + PARAM_LEN * 4 #define MUNMAP_E_SIZE HEADER_LEN + sizeof(uint64_t) * 2 + PARAM_LEN * 2 #define MUNMAP_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) * 3 + PARAM_LEN * 4 @@ -73,7 +74,8 @@ #define TIMERFD_CREATE_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define USERFAULTFD_E_SIZE HEADER_LEN #define USERFAULTFD_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + PARAM_LEN * 2 -#define SIGNALFD_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint8_t) + PARAM_LEN * 3 +#define SIGNALFD_E_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint8_t) + PARAM_LEN * 3 #define SIGNALFD_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define KILL_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint8_t) + PARAM_LEN * 2 #define KILL_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN @@ -110,7 +112,8 @@ #define FLOCK_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define IOCTL_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) * 2 + PARAM_LEN * 3 #define IOCTL_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN -#define QUOTACTL_E_SIZE HEADER_LEN + sizeof(uint16_t) + sizeof(uint8_t) * 2 + sizeof(uint32_t) + PARAM_LEN * 4 +#define QUOTACTL_E_SIZE \ + HEADER_LEN + sizeof(uint16_t) + sizeof(uint8_t) * 2 + sizeof(uint32_t) + PARAM_LEN * 4 #define UNSHARE_E_SIZE HEADER_LEN + sizeof(uint32_t) + PARAM_LEN #define UNSHARE_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define MOUNT_E_SIZE HEADER_LEN + sizeof(uint32_t) + PARAM_LEN @@ -145,10 +148,12 @@ #define RECVMSG_E_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define READV_E_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define PREADV_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) + PARAM_LEN * 2 -#define PREAD64_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) + PARAM_LEN * 3 +#define PREAD64_E_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) + PARAM_LEN * 3 #define RECVFROM_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + PARAM_LEN * 2 #define FCNTL_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint8_t) + PARAM_LEN * 2 -#define FCNTL_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(int64_t) + sizeof(uint8_t) + PARAM_LEN * 3 +#define FCNTL_X_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(int64_t) + sizeof(uint8_t) + PARAM_LEN * 3 #define SHUTDOWN_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint8_t) + PARAM_LEN * 2 #define SHUTDOWN_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define FSCONFIG_E_SIZE HEADER_LEN @@ -170,7 +175,8 @@ #define MLOCK_E_SIZE HEADER_LEN #define MLOCK_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) * 2 + PARAM_LEN * 3 #define MLOCK2_E_SIZE HEADER_LEN -#define MLOCK2_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) * 2 + PARAM_LEN * 4 +#define MLOCK2_X_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) * 2 + PARAM_LEN * 4 #define MUNLOCK_E_SIZE HEADER_LEN #define MUNLOCK_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) * 2 + PARAM_LEN * 3 #define MLOCKALL_E_SIZE HEADER_LEN @@ -179,27 +185,34 @@ #define MUNLOCKALL_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define READ_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + PARAM_LEN * 2 #define IO_URING_ENTER_E_SIZE HEADER_LEN -#define IO_URING_ENTER_X_SIZE HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint32_t) * 4 + PARAM_LEN * 6 +#define IO_URING_ENTER_X_SIZE \ + HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint32_t) * 4 + PARAM_LEN * 6 #define IO_URING_REGISTER_E_SIZE HEADER_LEN -#define IO_URING_REGISTER_X_SIZE HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint16_t) + sizeof(uint64_t) + sizeof(uint32_t) + PARAM_LEN * 5 +#define IO_URING_REGISTER_X_SIZE \ + HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint16_t) + sizeof(uint64_t) + sizeof(uint32_t) + \ + PARAM_LEN * 5 #define IO_URING_SETUP_E_SIZE HEADER_LEN #define IO_URING_SETUP_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) * 7 + PARAM_LEN * 8 -#define MMAP2_E_SIZE HEADER_LEN + sizeof(uint64_t) * 3 + sizeof(int64_t) + sizeof(uint32_t) * 2 + PARAM_LEN * 6 +#define MMAP2_E_SIZE \ + HEADER_LEN + sizeof(uint64_t) * 3 + sizeof(int64_t) + sizeof(uint32_t) * 2 + PARAM_LEN * 6 #define MMAP2_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) * 3 + PARAM_LEN * 4 #define SEMGET_E_SIZE HEADER_LEN + sizeof(int32_t) * 2 + sizeof(uint32_t) + PARAM_LEN * 3 -#define SEMGET_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN +#define SEMGET_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define SEMCTL_E_SIZE HEADER_LEN + sizeof(int32_t) * 3 + sizeof(uint16_t) + PARAM_LEN * 4 #define SEMCTL_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define SELECT_E_SIZE HEADER_LEN #define SELECT_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN -#define SPLICE_E_SIZE HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint64_t) + sizeof(uint32_t) + PARAM_LEN * 4 +#define SPLICE_E_SIZE \ + HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint64_t) + sizeof(uint32_t) + PARAM_LEN * 4 #define SPLICE_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define RECVMMSG_E_SIZE HEADER_LEN #define RECVMMSG_X_SIZE HEADER_LEN #define SENDMMSG_E_SIZE HEADER_LEN #define SENDMMSG_X_SIZE HEADER_LEN #define SEMOP_E_SIZE HEADER_LEN + sizeof(int32_t) + PARAM_LEN -#define SEMOP_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint16_t) * 4 + sizeof(int16_t) * 2 + PARAM_LEN * 8 +#define SEMOP_X_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint16_t) * 4 + sizeof(int16_t) * 2 + \ + PARAM_LEN * 8 #define GETRESUID_E_SIZE HEADER_LEN #define GETRESUID_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) * 3 + PARAM_LEN * 4 #define SENDFILE_E_SIZE HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint64_t) * 2 + PARAM_LEN * 4 @@ -210,14 +223,18 @@ #define LSTAT_E_SIZE HEADER_LEN #define FSTAT_E_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define FSTAT_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN -#define LSEEK_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) + sizeof(uint8_t) + 3 * PARAM_LEN +#define LSEEK_E_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) + sizeof(uint8_t) + 3 * PARAM_LEN #define LSEEK_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN -#define LLSEEK_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) + sizeof(uint8_t) + 3 * PARAM_LEN +#define LLSEEK_E_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) + sizeof(uint8_t) + 3 * PARAM_LEN #define LLSEEK_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define WRITE_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + PARAM_LEN * 2 #define WRITEV_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + PARAM_LEN * 2 -#define PWRITEV_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) + PARAM_LEN * 3 -#define PWRITE64_E_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) + PARAM_LEN * 3 +#define PWRITEV_E_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) + PARAM_LEN * 3 +#define PWRITE64_E_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) + sizeof(uint64_t) + PARAM_LEN * 3 #define GETRESGID_E_SIZE HEADER_LEN #define GETRESGID_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint32_t) * 3 + PARAM_LEN * 4 #define BRK_E_SIZE HEADER_LEN + sizeof(uint64_t) + PARAM_LEN @@ -229,7 +246,8 @@ #define NANOSLEEP_E_SIZE HEADER_LEN + sizeof(uint64_t) + PARAM_LEN #define NANOSLEEP_X_SIZE HEADER_LEN + sizeof(int64_t) + PARAM_LEN #define PIPE2_E_SIZE HEADER_LEN -#define PIPE2_X_SIZE HEADER_LEN + sizeof(int64_t) * 3 + sizeof(uint64_t) + sizeof(uint32_t) + PARAM_LEN * 5 +#define PIPE2_X_SIZE \ + HEADER_LEN + sizeof(int64_t) * 3 + sizeof(uint64_t) + sizeof(uint32_t) + PARAM_LEN * 5 #define INOTIFY_INIT1_E_SIZE HEADER_LEN #define INOTIFY_INIT1_X_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint16_t) + 2 * PARAM_LEN #define EVENTFD2_E_SIZE HEADER_LEN + sizeof(uint64_t) + PARAM_LEN @@ -256,7 +274,8 @@ #define SETREGID_X_SIZE HEADER_LEN + sizeof(uint32_t) * 2 + sizeof(int64_t) + 3 * PARAM_LEN /* Generic tracepoints events. */ -#define SCHED_SWITCH_SIZE HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) * 2 + sizeof(uint32_t) * 3 + PARAM_LEN * 6 +#define SCHED_SWITCH_SIZE \ + HEADER_LEN + sizeof(int64_t) + sizeof(uint64_t) * 2 + sizeof(uint32_t) * 3 + PARAM_LEN * 6 #define PAGE_FAULT_SIZE HEADER_LEN + sizeof(uint64_t) * 2 + sizeof(uint32_t) + PARAM_LEN * 3 #define SIGNAL_DELIVER_SIZE HEADER_LEN + sizeof(int64_t) * 2 + sizeof(uint8_t) + PARAM_LEN * 3 diff --git a/driver/modern_bpf/definitions/missing_definitions.h b/driver/modern_bpf/definitions/missing_definitions.h index c4e05bf3d8..f2b2062730 100644 --- a/driver/modern_bpf/definitions/missing_definitions.h +++ b/driver/modern_bpf/definitions/missing_definitions.h @@ -12,11 +12,11 @@ /* This header should include different definitions according to different architectures.*/ #ifndef likely -# define likely(X) __builtin_expect(!!(X), 1) +#define likely(X) __builtin_expect(!!(X), 1) #endif #ifndef unlikely -# define unlikely(X) __builtin_expect(!!(X), 0) +#define unlikely(X) __builtin_expect(!!(X), 0) #endif /* @@ -24,8 +24,8 @@ */ /* `/include/linux/sched.h` from kernel source tree. */ -#define PF_EXITING 0x00000004 /* Getting shut down */ -#define PF_KTHREAD 0x00200000 /* I am a kernel thread */ +#define PF_EXITING 0x00000004 /* Getting shut down */ +#define PF_KTHREAD 0x00200000 /* I am a kernel thread */ /*=============================== ARCH SPECIFIC ===========================*/ @@ -113,35 +113,37 @@ /* `/include/uapi/linux/sched.h` from kernel source tree. */ -#define CSIGNAL 0x000000ff /* signal mask to be sent at exit */ -#define CLONE_VM 0x00000100 /* set if VM shared between processes */ -#define CLONE_FS 0x00000200 /* set if fs info shared between processes */ -#define CLONE_FILES 0x00000400 /* set if open files shared between processes */ -#define CLONE_SIGHAND 0x00000800 /* set if signal handlers and blocked signals shared */ -#define CLONE_PIDFD 0x00001000 /* set if a pidfd should be placed in parent */ -#define CLONE_PTRACE 0x00002000 /* set if we want to let tracing continue on the child too */ -#define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ -#define CLONE_PARENT 0x00008000 /* set if we want to have the same parent as the cloner */ -#define CLONE_THREAD 0x00010000 /* Same thread group? */ -#define CLONE_NEWNS 0x00020000 /* New mount namespace group */ -#define CLONE_SYSVSEM 0x00040000 /* share system V SEM_UNDO semantics */ -#define CLONE_SETTLS 0x00080000 /* create a new TLS for the child */ -#define CLONE_PARENT_SETTID 0x00100000 /* set the TID in the parent */ +#define CSIGNAL 0x000000ff /* signal mask to be sent at exit */ +#define CLONE_VM 0x00000100 /* set if VM shared between processes */ +#define CLONE_FS 0x00000200 /* set if fs info shared between processes */ +#define CLONE_FILES 0x00000400 /* set if open files shared between processes */ +#define CLONE_SIGHAND 0x00000800 /* set if signal handlers and blocked signals shared */ +#define CLONE_PIDFD 0x00001000 /* set if a pidfd should be placed in parent */ +#define CLONE_PTRACE 0x00002000 /* set if we want to let tracing continue on the child too */ +#define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ +#define CLONE_PARENT 0x00008000 /* set if we want to have the same parent as the cloner */ +#define CLONE_THREAD 0x00010000 /* Same thread group? */ +#define CLONE_NEWNS 0x00020000 /* New mount namespace group */ +#define CLONE_SYSVSEM 0x00040000 /* share system V SEM_UNDO semantics */ +#define CLONE_SETTLS 0x00080000 /* create a new TLS for the child */ +#define CLONE_PARENT_SETTID 0x00100000 /* set the TID in the parent */ #define CLONE_CHILD_CLEARTID 0x00200000 /* clear the TID in the child */ -#define CLONE_DETACHED 0x00400000 /* Unused, ignored */ -#define CLONE_UNTRACED 0x00800000 /* set if the tracing process can't force CLONE_PTRACE on this clone */ -#define CLONE_CHILD_SETTID 0x01000000 /* set the TID in the child */ -#define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */ -#define CLONE_NEWUTS 0x04000000 /* New utsname namespace */ -#define CLONE_NEWIPC 0x08000000 /* New ipc namespace */ -#define CLONE_NEWUSER 0x10000000 /* New user namespace */ -#define CLONE_NEWPID 0x20000000 /* New pid namespace */ -#define CLONE_NEWNET 0x40000000 /* New network namespace */ -#define CLONE_IO 0x80000000 /* Clone io context */ +#define CLONE_DETACHED 0x00400000 /* Unused, ignored */ +#define CLONE_UNTRACED \ + 0x00800000 /* set if the tracing process can't force CLONE_PTRACE on this clone */ +#define CLONE_CHILD_SETTID 0x01000000 /* set the TID in the child */ +#define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */ +#define CLONE_NEWUTS 0x04000000 /* New utsname namespace */ +#define CLONE_NEWIPC 0x08000000 /* New ipc namespace */ +#define CLONE_NEWUSER 0x10000000 /* New user namespace */ +#define CLONE_NEWPID 0x20000000 /* New pid namespace */ +#define CLONE_NEWNET 0x40000000 /* New network namespace */ +#define CLONE_IO 0x80000000 /* Clone io context */ /* Flags for the clone3() syscall. */ #define CLONE_CLEAR_SIGHAND 0x100000000ULL /* Clear any signal handler and reset to SIG_DFL. */ -#define CLONE_INTO_CGROUP 0x200000000ULL /* Clone into a specific cgroup given the right permissions. */ +#define CLONE_INTO_CGROUP \ + 0x200000000ULL /* Clone into a specific cgroup given the right permissions. */ /* * cloning flags intersect with CSIGNAL so can be used with unshare and clone3 @@ -160,14 +162,14 @@ #define O_WRONLY 00000001 #define O_RDWR 00000002 #define O_CREAT 00000100 /* not fcntl */ -#define O_EXCL 00000200 /* not fcntl */ +#define O_EXCL 00000200 /* not fcntl */ #define O_NOCTTY 00000400 /* not fcntl */ #define O_TRUNC 00001000 /* not fcntl */ #define O_APPEND 00002000 #define O_NONBLOCK 00004000 #define O_NDELAY O_NONBLOCK #define O_DSYNC 00010000 /* used to be O_SYNC, see below */ -#define FASYNC 00020000 /* fcntl, for BSD compatibility */ +#define FASYNC 00020000 /* fcntl, for BSD compatibility */ #if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_s390) @@ -189,10 +191,10 @@ /* `/arch/powerpc/include/uapi/asm/fcntl.h` from kernel source tree. */ -#define O_DIRECTORY 040000 /* must be a directory */ -#define O_NOFOLLOW 0100000 /* don't follow links */ -#define O_LARGEFILE 0200000 -#define O_DIRECT 0400000 /* direct disk access hint */ +#define O_DIRECTORY 040000 /* must be a directory */ +#define O_NOFOLLOW 0100000 /* don't follow links */ +#define O_LARGEFILE 0200000 +#define O_DIRECT 0400000 /* direct disk access hint */ #endif @@ -216,12 +218,18 @@ /* * how->resolve flags for openat2(2). */ -#define RESOLVE_NO_XDEV 0x01 /* Block mount-point crossings (includes bind-mounts). */ +#define RESOLVE_NO_XDEV 0x01 /* Block mount-point crossings (includes bind-mounts). */ #define RESOLVE_NO_MAGICLINKS 0x02 /* Block traversal through procfs-style "magic-links". */ -#define RESOLVE_NO_SYMLINKS 0x04 /* Block traversal through all symlinks (implies OEXT_NO_MAGICLINKS) */ -#define RESOLVE_BENEATH 0x08 /* Block "lexical" trickery like "..", symlinks, and absolute paths which escape the dirfd. */ -#define RESOLVE_IN_ROOT 0x10 /* Make all jumps to "/" and ".." be scoped inside the dirfd (similar to chroot(2)). */ -#define RESOLVE_CACHED 0x20 /* Only complete if resolution can be completed through cached lookup. May return -EAGAIN if that's not possible. */ +#define RESOLVE_NO_SYMLINKS \ + 0x04 /* Block traversal through all symlinks (implies OEXT_NO_MAGICLINKS) */ +#define RESOLVE_BENEATH \ + 0x08 /* Block "lexical" trickery like "..", symlinks, and absolute paths which escape the \ + dirfd. */ +#define RESOLVE_IN_ROOT \ + 0x10 /* Make all jumps to "/" and ".." be scoped inside the dirfd (similar to chroot(2)). */ +#define RESOLVE_CACHED \ + 0x20 /* Only complete if resolution can be completed through cached lookup. May return -EAGAIN \ + if that's not possible. */ ////////////////////////// // io_uring flags @@ -232,11 +240,11 @@ /* * Io_uring_setup flags */ -#define IORING_SETUP_IOPOLL (1U << 0) /* io_context is polled */ -#define IORING_SETUP_SQPOLL (1U << 1) /* SQ poll thread */ -#define IORING_SETUP_SQ_AFF (1U << 2) /* sq_thread_cpu is valid */ -#define IORING_SETUP_CQSIZE (1U << 3) /* app defines CQ size */ -#define IORING_SETUP_CLAMP (1U << 4) /* clamp SQ/CQ ring sizes */ +#define IORING_SETUP_IOPOLL (1U << 0) /* io_context is polled */ +#define IORING_SETUP_SQPOLL (1U << 1) /* SQ poll thread */ +#define IORING_SETUP_SQ_AFF (1U << 2) /* sq_thread_cpu is valid */ +#define IORING_SETUP_CQSIZE (1U << 3) /* app defines CQ size */ +#define IORING_SETUP_CLAMP (1U << 4) /* clamp SQ/CQ ring sizes */ #define IORING_SETUP_ATTACH_WQ (1U << 5) /* attach to existing wq */ #define IORING_SETUP_R_DISABLED (1U << 6) /* start with ring disabled */ @@ -282,9 +290,9 @@ #define PROT_SEM 0x8 /* page may be used for atomic ops */ /* 0x10 reserved for arch-specific use */ /* 0x20 reserved for arch-specific use */ -#define PROT_NONE 0x0 /* page can not be accessed */ +#define PROT_NONE 0x0 /* page can not be accessed */ #define PROT_GROWSDOWN 0x01000000 /* mprotect flag: extend change to start of growsdown vma */ -#define PROT_GROWSUP 0x02000000 /* mprotect flag: extend change to end of growsup vma */ +#define PROT_GROWSUP 0x02000000 /* mprotect flag: extend change to end of growsup vma */ /* `/arch/powerpc/include/uapi/asm/mman.h` from kernel source tree. */ @@ -296,16 +304,16 @@ /* `/include/uapi/linux/mman.h` from kernel source tree. */ -#define MAP_SHARED 0x01 /* Share changes */ -#define MAP_PRIVATE 0x02 /* Changes are private */ +#define MAP_SHARED 0x01 /* Share changes */ +#define MAP_PRIVATE 0x02 /* Changes are private */ #define MAP_SHARED_VALIDATE 0x03 /* share + validate extension flags */ /* `/include/uapi/asm-generic/mman-common.h` from kernel source tree. */ -#define MAP_TYPE 0x0f /* Mask for type of mapping */ -#define MAP_FIXED 0x10 /* Interpret addr exactly */ +#define MAP_TYPE 0x0f /* Mask for type of mapping */ +#define MAP_FIXED 0x10 /* Interpret addr exactly */ #define MAP_ANONYMOUS 0x20 /* don't use a file */ -#define MAP_FILE 0 /* compatibility flags */ +#define MAP_FILE 0 /* compatibility flags */ /* `/arch/x86/include/uapi/asm/mman.h` from kernel source tree. */ @@ -326,9 +334,9 @@ #define MAP_NORESERVE 0x4000 /* don't check for reservations */ #define MAP_POPULATE 0x8000 /* populate (prefault) pagetables */ #define MAP_NONBLOCK 0x10000 /* do not block on IO */ -#define MAP_STACK 0x20000 /* give out an address that is best suited for process/thread stacks */ -#define MAP_HUGETLB 0x40000 /* create a huge page mapping */ -#define MAP_SYNC 0x80000 /* perform synchronous page faults for the mapping */ +#define MAP_STACK 0x20000 /* give out an address that is best suited for process/thread stacks */ +#define MAP_HUGETLB 0x40000 /* create a huge page mapping */ +#define MAP_SYNC 0x80000 /* perform synchronous page faults for the mapping */ /* `/arch/sparc/include/uapi/asm/mman.h` from kernel source tree. */ @@ -369,9 +377,10 @@ #define F_SETLEASE (F_LINUX_SPECIFIC_BASE + 0) #define F_GETLEASE (F_LINUX_SPECIFIC_BASE + 1) -#define F_NOTIFY (F_LINUX_SPECIFIC_BASE + 2) /* Request nofications on a directory. */ -#define F_CANCELLK (F_LINUX_SPECIFIC_BASE + 5) /* Cancel a blocking posix lock. */ -#define F_DUPFD_CLOEXEC (F_LINUX_SPECIFIC_BASE + 6) /* Create a file descriptor with FD_CLOEXEC set. */ +#define F_NOTIFY (F_LINUX_SPECIFIC_BASE + 2) /* Request nofications on a directory. */ +#define F_CANCELLK (F_LINUX_SPECIFIC_BASE + 5) /* Cancel a blocking posix lock. */ +#define F_DUPFD_CLOEXEC \ + (F_LINUX_SPECIFIC_BASE + 6) /* Create a file descriptor with FD_CLOEXEC set. */ /* Set and get of pipe page size array */ #define F_SETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 7) #define F_GETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 8) @@ -413,12 +422,12 @@ #define SO_REUSEPORT 15 /* Powerpc64 has different values for these ones. See /usr/include/asm/socket.h */ #if defined(__TARGET_ARCH_powerpc) -#define SO_RCVLOWAT 16 -#define SO_SNDLOWAT 17 +#define SO_RCVLOWAT 16 +#define SO_SNDLOWAT 17 #define SO_RCVTIMEO_OLD 18 #define SO_SNDTIMEO_OLD 19 -#define SO_PASSCRED 20 -#define SO_PEERCRED 21 +#define SO_PASSCRED 20 +#define SO_PEERCRED 21 #else #define SO_PASSCRED 16 #define SO_PEERCRED 17 @@ -509,7 +518,7 @@ /* We keep names without `OLD` for compatibility with our `sockopt_optname_to_scap()` */ -#define SO_TIMESTAMP 29 /* SO_TIMESTAMP_OLD */ +#define SO_TIMESTAMP 29 /* SO_TIMESTAMP_OLD */ #define SO_TIMESTAMPNS 35 /* SO_TIMESTAMPNS_OLD */ #define SO_TIMESTAMPING 37 /* SO_TIMESTAMPING_OLD */ @@ -594,10 +603,10 @@ /* `include/linux/fs.h` from kernel source tree. */ -#define MNT_FORCE 0x00000001 /* Attempt to forcibily umount */ -#define MNT_DETACH 0x00000002 /* Just detach from the tree */ -#define MNT_EXPIRE 0x00000004 /* Mark for expiry */ -#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */ +#define MNT_FORCE 0x00000001 /* Attempt to forcibily umount */ +#define MNT_DETACH 0x00000002 /* Just detach from the tree */ +#define MNT_EXPIRE 0x00000004 /* Mark for expiry */ +#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */ ////////////////////////// // lseek whence @@ -618,7 +627,7 @@ /* `include/linux/fs.h` from kernel source tree. */ -#define FMODE_CREATED (/*(__force fmode_t) */0x100000) +#define FMODE_CREATED (/*(__force fmode_t) */ 0x100000) ////////////////////////// // flock flags @@ -648,14 +657,14 @@ #define SUBCMDMASK 0x00ff #define SUBCMDSHIFT 8 -#define Q_SYNC 0x800001 /* sync disk copy of a filesystems quotas */ -#define Q_QUOTAON 0x800002 /* turn quotas on */ -#define Q_QUOTAOFF 0x800003 /* turn quotas off */ -#define Q_GETFMT 0x800004 /* get quota format used on given filesystem */ -#define Q_GETINFO 0x800005 /* get information about quota files */ -#define Q_SETINFO 0x800006 /* set information about quota files */ -#define Q_GETQUOTA 0x800007 /* get user quota structure */ -#define Q_SETQUOTA 0x800008 /* set user quota structure */ +#define Q_SYNC 0x800001 /* sync disk copy of a filesystems quotas */ +#define Q_QUOTAON 0x800002 /* turn quotas on */ +#define Q_QUOTAOFF 0x800003 /* turn quotas off */ +#define Q_GETFMT 0x800004 /* get quota format used on given filesystem */ +#define Q_GETINFO 0x800005 /* get information about quota files */ +#define Q_SETINFO 0x800006 /* set information about quota files */ +#define Q_GETQUOTA 0x800007 /* get user quota structure */ +#define Q_SETQUOTA 0x800008 /* set user quota structure */ #define Q_GETNEXTQUOTA 0x800009 /* get disk limits and usage >= ID */ /* Quota format type IDs */ @@ -670,7 +679,7 @@ /* `/include/uapi/linux/dqblk_xfs.h` from kernel source tree. */ -#define XQM_CMD(x) (('X' << 8) + (x)) /* note: forms first QCMD argument */ +#define XQM_CMD(x) (('X' << 8) + (x)) /* note: forms first QCMD argument */ #define XQM_COMMAND(x) (((x) & (0xff << 8)) == ('X' << 8)) /* test if for XFS */ #define XQM_USRQUOTA 0 /* system call user quota type */ @@ -678,14 +687,14 @@ #define XQM_PRJQUOTA 2 /* system call project quota type */ #define XQM_MAXQUOTAS 3 -#define Q_XQUOTAON XQM_CMD(1) /* enable accounting/enforcement */ -#define Q_XQUOTAOFF XQM_CMD(2) /* disable accounting/enforcement */ -#define Q_XGETQUOTA XQM_CMD(3) /* get disk limits and usage */ -#define Q_XSETQLIM XQM_CMD(4) /* set disk limits */ -#define Q_XGETQSTAT XQM_CMD(5) /* get quota subsystem status */ -#define Q_XQUOTARM XQM_CMD(6) /* free disk space used by dquots */ -#define Q_XQUOTASYNC XQM_CMD(7) /* delalloc flush, updates dquots */ -#define Q_XGETQSTATV XQM_CMD(8) /* newer version of get quota */ +#define Q_XQUOTAON XQM_CMD(1) /* enable accounting/enforcement */ +#define Q_XQUOTAOFF XQM_CMD(2) /* disable accounting/enforcement */ +#define Q_XGETQUOTA XQM_CMD(3) /* get disk limits and usage */ +#define Q_XSETQLIM XQM_CMD(4) /* set disk limits */ +#define Q_XGETQSTAT XQM_CMD(5) /* get quota subsystem status */ +#define Q_XQUOTARM XQM_CMD(6) /* free disk space used by dquots */ +#define Q_XQUOTASYNC XQM_CMD(7) /* delalloc flush, updates dquots */ +#define Q_XGETQSTATV XQM_CMD(8) /* newer version of get quota */ #define Q_XGETNEXTQUOTA XQM_CMD(9) /* get disk limits and usage >= ID */ ////////////////////////// @@ -779,9 +788,9 @@ ////////////////////////// /* arch/powerpc/include/uapi/asm/mman.h from kernel source tree. */ #if defined(__TARGET_ARCH_powerpc) -#define MCL_CURRENT 0x2000 /* lock all currently mapped pages */ -#define MCL_FUTURE 0x4000 /* lock all additions to address space */ -#define MCL_ONFAULT 0x8000 /* lock all pages that are faulted in */ +#define MCL_CURRENT 0x2000 /* lock all currently mapped pages */ +#define MCL_FUTURE 0x4000 /* lock all additions to address space */ +#define MCL_ONFAULT 0x8000 /* lock all pages that are faulted in */ #else /* `/include/uapi/asm-generic/mman.h` from kernel source tree. */ #define MCL_CURRENT 1 /* lock all current mappings */ @@ -792,14 +801,14 @@ ////////////////////////// // memfd_create flags ////////////////////////// -# define MFD_CLOEXEC 1U -# define MFD_ALLOW_SEALING 2U -# define MFD_HUGETLB 4U +#define MFD_CLOEXEC 1U +#define MFD_ALLOW_SEALING 2U +#define MFD_HUGETLB 4U ////////////////////////// // pidfd_open flags ////////////////////////// -# define PIDFD_NONBLOCK O_NONBLOCK +#define PIDFD_NONBLOCK O_NONBLOCK /*=============================== FLAGS ===========================*/ @@ -830,36 +839,38 @@ #define AF_KEY 15 /* PF_KEY key management API */ #define AF_NETLINK 16 #define AF_ROUTE AF_NETLINK /* Alias to emulate 4.4BSD */ -#define AF_PACKET 17 /* Packet family */ -#define AF_ASH 18 /* Ash */ -#define AF_ECONET 19 /* Acorn Econet */ -#define AF_ATMSVC 20 /* ATM SVCs */ -#define AF_RDS 21 /* RDS sockets */ -#define AF_SNA 22 /* Linux SNA Project (nutters!) */ -#define AF_IRDA 23 /* IRDA sockets */ -#define AF_PPPOX 24 /* PPPoX sockets */ -#define AF_WANPIPE 25 /* Wanpipe API Sockets */ -#define AF_LLC 26 /* Linux LLC */ -#define AF_IB 27 /* Native InfiniBand address */ -#define AF_MPLS 28 /* MPLS */ -#define AF_CAN 29 /* Controller Area Network */ -#define AF_TIPC 30 /* TIPC sockets */ -#define AF_BLUETOOTH 31 /* Bluetooth sockets */ -#define AF_IUCV 32 /* IUCV sockets */ -#define AF_RXRPC 33 /* RxRPC sockets */ -#define AF_ISDN 34 /* mISDN sockets */ -#define AF_PHONET 35 /* Phonet sockets */ +#define AF_PACKET 17 /* Packet family */ +#define AF_ASH 18 /* Ash */ +#define AF_ECONET 19 /* Acorn Econet */ +#define AF_ATMSVC 20 /* ATM SVCs */ +#define AF_RDS 21 /* RDS sockets */ +#define AF_SNA 22 /* Linux SNA Project (nutters!) */ +#define AF_IRDA 23 /* IRDA sockets */ +#define AF_PPPOX 24 /* PPPoX sockets */ +#define AF_WANPIPE 25 /* Wanpipe API Sockets */ +#define AF_LLC 26 /* Linux LLC */ +#define AF_IB 27 /* Native InfiniBand address */ +#define AF_MPLS 28 /* MPLS */ +#define AF_CAN 29 /* Controller Area Network */ +#define AF_TIPC 30 /* TIPC sockets */ +#define AF_BLUETOOTH 31 /* Bluetooth sockets */ +#define AF_IUCV 32 /* IUCV sockets */ +#define AF_RXRPC 33 /* RxRPC sockets */ +#define AF_ISDN 34 /* mISDN sockets */ +#define AF_PHONET 35 /* Phonet sockets */ #define AF_IEEE802154 36 /* IEEE802154 sockets */ -#define AF_CAIF 37 /* CAIF sockets */ -#define AF_ALG 38 /* Algorithm sockets */ -#define AF_NFC 39 /* NFC sockets */ -#define AF_VSOCK 40 /* vSockets */ -#define AF_KCM 41 /* Kernel Connection Multiplexor*/ -#define AF_QIPCRTR 42 /* Qualcomm IPC Router */ -#define AF_SMC 43 /* smc sockets: reserve number for PF_SMC protocol family that reuses AF_INET address family */ -#define AF_XDP 44 /* XDP sockets */ -#define AF_MCTP 45 /* Management component transport protocol */ -#define AF_MAX 46 /* For now.. */ +#define AF_CAIF 37 /* CAIF sockets */ +#define AF_ALG 38 /* Algorithm sockets */ +#define AF_NFC 39 /* NFC sockets */ +#define AF_VSOCK 40 /* vSockets */ +#define AF_KCM 41 /* Kernel Connection Multiplexor*/ +#define AF_QIPCRTR 42 /* Qualcomm IPC Router */ +#define AF_SMC \ + 43 /* smc sockets: reserve number for PF_SMC protocol family that reuses AF_INET address \ + family */ +#define AF_XDP 44 /* XDP sockets */ +#define AF_MCTP 45 /* Management component transport protocol */ +#define AF_MAX 46 /* For now.. */ ////////////////////////// // Protocol families @@ -987,8 +998,8 @@ * Bit location of each capability (used by user-space library and kernel) */ -#define CAP_TO_INDEX(x) ((x) >> 5) /* 1 << 5 == bits in __u32 */ -#define CAP_TO_MASK(x) (1U << ((x)&31)) /* mask for indexed __u32 */ +#define CAP_TO_INDEX(x) ((x) >> 5) /* 1 << 5 == bits in __u32 */ +#define CAP_TO_MASK(x) (1U << ((x) & 31)) /* mask for indexed __u32 */ /* In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this overrides the restriction of changing file ownership and group @@ -1314,23 +1325,25 @@ /* * Types of directory notifications that may be requested. */ -#define DN_ACCESS 0x00000001 /* File accessed */ -#define DN_MODIFY 0x00000002 /* File modified */ -#define DN_CREATE 0x00000004 /* File created */ -#define DN_DELETE 0x00000008 /* File removed */ -#define DN_RENAME 0x00000010 /* File renamed */ -#define DN_ATTRIB 0x00000020 /* File changed attibutes */ +#define DN_ACCESS 0x00000001 /* File accessed */ +#define DN_MODIFY 0x00000002 /* File modified */ +#define DN_CREATE 0x00000004 /* File created */ +#define DN_DELETE 0x00000008 /* File removed */ +#define DN_RENAME 0x00000010 /* File renamed */ +#define DN_ATTRIB 0x00000020 /* File changed attibutes */ #define DN_MULTISHOT 0x80000000 /* Don't remove notifier */ -#define AT_FDCWD -100 /* Special value used to indicate \ - openat should use the current \ - working directory. */ +#define AT_FDCWD \ + -100 /* Special value used to indicate \ + openat should use the current \ + working directory. */ #define AT_SYMLINK_NOFOLLOW 0x100 /* Do not follow symbolic links. */ -#define AT_REMOVEDIR 0x200 /* Remove directory instead of \ - unlinking file. */ -#define AT_SYMLINK_FOLLOW 0x400 /* Follow symbolic links. */ -#define AT_NO_AUTOMOUNT 0x800 /* Suppress terminal automount traversal */ -#define AT_EMPTY_PATH 0x1000 /* Allow empty relative pathname */ +#define AT_REMOVEDIR \ + 0x200 /* Remove directory instead of \ + unlinking file. */ +#define AT_SYMLINK_FOLLOW 0x400 /* Follow symbolic links. */ +#define AT_NO_AUTOMOUNT 0x800 /* Suppress terminal automount traversal */ +#define AT_EMPTY_PATH 0x1000 /* Allow empty relative pathname */ #define AT_STATX_SYNC_TYPE 0x6000 /* Type of synchronisation required from statx() */ #define AT_STATX_SYNC_AS_STAT 0x0000 /* - Do whatever stat() does */ @@ -1346,7 +1359,7 @@ #define MINORBITS 20 #define MINORMASK ((1U << MINORBITS) - 1) #define MAJOR(dev) ((unsigned int)((dev) >> MINORBITS)) -#define MINOR(dev) ((unsigned int)((dev)&MINORMASK)) +#define MINOR(dev) ((unsigned int)((dev) & MINORMASK)) #define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi)) #define PPM_NULL_RDEV MKDEV(1, 3) @@ -1356,20 +1369,20 @@ /* `/include/uapi/asm-generic/resource.h` from kernel source tree. */ -#define RLIMIT_CPU 0 /* CPU time in sec */ -#define RLIMIT_FSIZE 1 /* Maximum filesize */ -#define RLIMIT_DATA 2 /* max data size */ -#define RLIMIT_STACK 3 /* max stack size */ -#define RLIMIT_CORE 4 /* max core file size */ -#define RLIMIT_RSS 5 /* max resident set size */ -#define RLIMIT_NPROC 6 /* max number of processes */ -#define RLIMIT_NOFILE 7 /* max number of open files */ +#define RLIMIT_CPU 0 /* CPU time in sec */ +#define RLIMIT_FSIZE 1 /* Maximum filesize */ +#define RLIMIT_DATA 2 /* max data size */ +#define RLIMIT_STACK 3 /* max stack size */ +#define RLIMIT_CORE 4 /* max core file size */ +#define RLIMIT_RSS 5 /* max resident set size */ +#define RLIMIT_NPROC 6 /* max number of processes */ +#define RLIMIT_NOFILE 7 /* max number of open files */ #define RLIMIT_MEMLOCK 8 /* max locked-in-memory address space */ -#define RLIMIT_AS 9 /* address space limit */ -#define RLIMIT_LOCKS 10 /* maximum file locks held */ +#define RLIMIT_AS 9 /* address space limit */ +#define RLIMIT_LOCKS 10 /* maximum file locks held */ #define RLIMIT_SIGPENDING 11 /* max number of pending signals */ #define RLIMIT_MSGQUEUE 12 /* maximum bytes in POSIX mqueues */ -#define RLIMIT_NICE 13 /* max nice prio allowed to raise to 0-39 for nice level 19 .. -20 */ +#define RLIMIT_NICE 13 /* max nice prio allowed to raise to 0-39 for nice level 19 .. -20 */ #define RLIMIT_RTPRIO 14 /* maximum realtime priority */ #define RLIMIT_RTTIME 15 /* timeout for RT tasks in us */ #define RLIM_NLIMITS 16 @@ -1379,13 +1392,12 @@ /*=============================== HOST_TO_NETWORK_BYTE_ORDER ===========================*/ /* Swap bytes in 16 bit value. */ -#define __bswap_constant_16(x) \ - ((unsigned short int)((((x) >> 8) & 0xff) | (((x)&0xff) << 8))) +#define __bswap_constant_16(x) ((unsigned short int)((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))) /* Swap bytes in 32 bit value. */ -#define __bswap_constant_32(x) \ - ((((x)&0xff000000) >> 24) | (((x)&0x00ff0000) >> 8) | \ - (((x)&0x0000ff00) << 8) | (((x)&0x000000ff) << 24)) +#define __bswap_constant_32(x) \ + ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | (((x) & 0x0000ff00) << 8) | \ + (((x) & 0x000000ff) << 24)) #define identity(x) x @@ -1443,12 +1455,12 @@ /*=============================== SPLICE SYSCALL =============================*/ -#define SPLICE_F_MOVE (0x01) -#define SPLICE_F_NONBLOCK (0x02) -#define SPLICE_F_MORE (0x04) -#define SPLICE_F_GIFT (0x08) +#define SPLICE_F_MOVE (0x01) +#define SPLICE_F_NONBLOCK (0x02) +#define SPLICE_F_MORE (0x04) +#define SPLICE_F_GIFT (0x08) -#define SPLICE_F_ALL (SPLICE_F_MOVE|SPLICE_F_NONBLOCK|SPLICE_F_MORE|SPLICE_F_GIFT) +#define SPLICE_F_ALL (SPLICE_F_MOVE | SPLICE_F_NONBLOCK | SPLICE_F_MORE | SPLICE_F_GIFT) /*=============================== SPLICE SYSCALL =============================*/ @@ -1456,7 +1468,7 @@ /* `/include/linux/fs.h` from kernel source tree. */ -#define SB_RDONLY 1 /* Mount read-only */ +#define SB_RDONLY 1 /* Mount read-only */ #define S_IMMUTABLE (1 << 3) /* Immutable file */ /* `/include/uapi/linux/stat.h` from kernel source tree. */ @@ -1472,34 +1484,34 @@ #define S_ISUID 0004000 #define S_ISGID 0002000 #define S_ISVTX 0001000 -#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG) -#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR) -#define S_ISLNK(m) (((m)&S_IFMT) == S_IFLNK) +#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) /*=============================== INODE/SUPERBLOCK FLAGS ===========================*/ /*=============================== SOCKETCALL CODES ===========================*/ -#define SYS_SOCKET 1 /* sys_socket(2) */ -#define SYS_BIND 2 /* sys_bind(2) */ -#define SYS_CONNECT 3 /* sys_connect(2) */ -#define SYS_LISTEN 4 /* sys_listen(2) */ -#define SYS_ACCEPT 5 /* sys_accept(2) */ +#define SYS_SOCKET 1 /* sys_socket(2) */ +#define SYS_BIND 2 /* sys_bind(2) */ +#define SYS_CONNECT 3 /* sys_connect(2) */ +#define SYS_LISTEN 4 /* sys_listen(2) */ +#define SYS_ACCEPT 5 /* sys_accept(2) */ #define SYS_GETSOCKNAME 6 /* sys_getsockname(2) */ #define SYS_GETPEERNAME 7 /* sys_getpeername(2) */ #define SYS_SOCKETPAIR 8 /* sys_socketpair(2) */ -#define SYS_SEND 9 /* sys_send(2) */ -#define SYS_RECV 10 /* sys_recv(2) */ -#define SYS_SENDTO 11 /* sys_sendto(2) */ -#define SYS_RECVFROM 12 /* sys_recvfrom(2) */ -#define SYS_SHUTDOWN 13 /* sys_shutdown(2) */ +#define SYS_SEND 9 /* sys_send(2) */ +#define SYS_RECV 10 /* sys_recv(2) */ +#define SYS_SENDTO 11 /* sys_sendto(2) */ +#define SYS_RECVFROM 12 /* sys_recvfrom(2) */ +#define SYS_SHUTDOWN 13 /* sys_shutdown(2) */ #define SYS_SETSOCKOPT 14 /* sys_setsockopt(2) */ #define SYS_GETSOCKOPT 15 /* sys_getsockopt(2) */ -#define SYS_SENDMSG 16 /* sys_sendmsg(2) */ -#define SYS_RECVMSG 17 /* sys_recvmsg(2) */ -#define SYS_ACCEPT4 18 /* sys_accept4(2) */ -#define SYS_RECVMMSG 19 /* sys_recvmmsg(2) */ -#define SYS_SENDMMSG 20 /* sys_sendmmsg(2) */ +#define SYS_SENDMSG 16 /* sys_sendmsg(2) */ +#define SYS_RECVMSG 17 /* sys_recvmsg(2) */ +#define SYS_ACCEPT4 18 /* sys_accept4(2) */ +#define SYS_RECVMMSG 19 /* sys_recvmmsg(2) */ +#define SYS_SENDMMSG 20 /* sys_sendmmsg(2) */ /*=============================== SOCKETCALL CODES ===========================*/ @@ -1508,32 +1520,32 @@ /* `/include/asm-generic/bitsperlong.h` from kernel source tree. */ #define BITS_PER_LONG 64 -#define BIT_WORD(nr) ((nr) / BITS_PER_LONG) +#define BIT_WORD(nr) ((nr) / BITS_PER_LONG) /*=============================== OPENED FILE DESCRIPTORS ===========================*/ /*==================================== PRCTL OPTIONS ================================*/ -#define PR_SET_PDEATHSIG 1 -#define PR_GET_PDEATHSIG 2 -#define PR_GET_DUMPABLE 3 -#define PR_SET_DUMPABLE 4 -#define PR_GET_UNALIGN 5 -#define PR_SET_UNALIGN 6 -#define PR_GET_KEEPCAPS 7 -#define PR_SET_KEEPCAPS 8 -#define PR_GET_FPEMU 9 +#define PR_SET_PDEATHSIG 1 +#define PR_GET_PDEATHSIG 2 +#define PR_GET_DUMPABLE 3 +#define PR_SET_DUMPABLE 4 +#define PR_GET_UNALIGN 5 +#define PR_SET_UNALIGN 6 +#define PR_GET_KEEPCAPS 7 +#define PR_SET_KEEPCAPS 8 +#define PR_GET_FPEMU 9 #define PR_SET_FPEMU 10 -#define PR_GET_FPEXC 11 -#define PR_SET_FPEXC 12 -#define PR_GET_TIMING 13 -#define PR_SET_TIMING 14 -#define PR_SET_NAME 15 -#define PR_GET_NAME 16 -#define PR_GET_ENDIAN 19 -#define PR_SET_ENDIAN 20 -#define PR_GET_SECCOMP 21 -#define PR_SET_SECCOMP 22 +#define PR_GET_FPEXC 11 +#define PR_SET_FPEXC 12 +#define PR_GET_TIMING 13 +#define PR_SET_TIMING 14 +#define PR_SET_NAME 15 +#define PR_GET_NAME 16 +#define PR_GET_ENDIAN 19 +#define PR_SET_ENDIAN 20 +#define PR_GET_SECCOMP 21 +#define PR_SET_SECCOMP 22 #define PR_CAPBSET_READ 23 #define PR_CAPBSET_DROP 24 #define PR_GET_TSC 25 @@ -1542,48 +1554,48 @@ #define PR_SET_SECUREBITS 28 #define PR_SET_TIMERSLACK 29 #define PR_GET_TIMERSLACK 30 -#define PR_TASK_PERF_EVENTS_DISABLE 31 -#define PR_TASK_PERF_EVENTS_ENABLE 32 -#define PR_MCE_KILL 33 +#define PR_TASK_PERF_EVENTS_DISABLE 31 +#define PR_TASK_PERF_EVENTS_ENABLE 32 +#define PR_MCE_KILL 33 #define PR_MCE_KILL_GET 34 -#define PR_SET_MM 35 +#define PR_SET_MM 35 #define PR_SET_PTRACER 0x59616d61 -#define PR_SET_CHILD_SUBREAPER 36 -#define PR_GET_CHILD_SUBREAPER 37 -#define PR_SET_NO_NEW_PRIVS 38 -#define PR_GET_NO_NEW_PRIVS 39 -#define PR_GET_TID_ADDRESS 40 -#define PR_SET_THP_DISABLE 41 -#define PR_GET_THP_DISABLE 42 -#define PR_MPX_ENABLE_MANAGEMENT 43 +#define PR_SET_CHILD_SUBREAPER 36 +#define PR_GET_CHILD_SUBREAPER 37 +#define PR_SET_NO_NEW_PRIVS 38 +#define PR_GET_NO_NEW_PRIVS 39 +#define PR_GET_TID_ADDRESS 40 +#define PR_SET_THP_DISABLE 41 +#define PR_GET_THP_DISABLE 42 +#define PR_MPX_ENABLE_MANAGEMENT 43 #define PR_MPX_DISABLE_MANAGEMENT 44 -#define PR_SET_FP_MODE 45 -#define PR_GET_FP_MODE 46 -#define PR_CAP_AMBIENT 47 -#define PR_SVE_SET_VL 50 -#define PR_SVE_GET_VL 51 -#define PR_GET_SPECULATION_CTRL 52 -#define PR_SET_SPECULATION_CTRL 53 -#define PR_PAC_RESET_KEYS 54 -#define PR_SET_TAGGED_ADDR_CTRL 55 -#define PR_GET_TAGGED_ADDR_CTRL 56 -#define PR_SET_IO_FLUSHER 57 -#define PR_GET_IO_FLUSHER 58 -#define PR_SET_SYSCALL_USER_DISPATCH 59 -#define PR_PAC_SET_ENABLED_KEYS 60 -#define PR_PAC_GET_ENABLED_KEYS 61 -#define PR_SCHED_CORE 62 -#define PR_SME_SET_VL 63 -#define PR_SME_GET_VL 64 -#define PR_SET_VMA 0x53564d41 +#define PR_SET_FP_MODE 45 +#define PR_GET_FP_MODE 46 +#define PR_CAP_AMBIENT 47 +#define PR_SVE_SET_VL 50 +#define PR_SVE_GET_VL 51 +#define PR_GET_SPECULATION_CTRL 52 +#define PR_SET_SPECULATION_CTRL 53 +#define PR_PAC_RESET_KEYS 54 +#define PR_SET_TAGGED_ADDR_CTRL 55 +#define PR_GET_TAGGED_ADDR_CTRL 56 +#define PR_SET_IO_FLUSHER 57 +#define PR_GET_IO_FLUSHER 58 +#define PR_SET_SYSCALL_USER_DISPATCH 59 +#define PR_PAC_SET_ENABLED_KEYS 60 +#define PR_PAC_GET_ENABLED_KEYS 61 +#define PR_SCHED_CORE 62 +#define PR_SME_SET_VL 63 +#define PR_SME_GET_VL 64 +#define PR_SET_VMA 0x53564d41 /*==================================== PRCTL OPTIONS ================================*/ /*==================================== FINIT FLAGS ================================*/ #define MODULE_INIT_IGNORE_MODVERSIONS 1 -#define MODULE_INIT_IGNORE_VERMAGIC 2 -#define MODULE_INIT_COMPRESSED_FILE 4 +#define MODULE_INIT_IGNORE_VERMAGIC 2 +#define MODULE_INIT_COMPRESSED_FILE 4 /*==================================== FINIT FLAGS ================================*/ #endif /* __MISSING_DEFINITIONS_H__ */ diff --git a/driver/modern_bpf/definitions/struct_flavors.h b/driver/modern_bpf/definitions/struct_flavors.h index 3510720020..4e76281ed9 100644 --- a/driver/modern_bpf/definitions/struct_flavors.h +++ b/driver/modern_bpf/definitions/struct_flavors.h @@ -17,13 +17,11 @@ #pragma clang attribute push(__attribute__((preserve_access_index)), apply_to = record) #endif -struct mm_struct___v6_2 -{ +struct mm_struct___v6_2 { struct percpu_counter rss_stat[NR_MM_COUNTERS]; }; -typedef struct -{ +typedef struct { uint64_t val; } kernel_cap_t___v6_3; @@ -31,17 +29,19 @@ typedef struct * versions define COS subset of task_struct with a flavor suffix (which will * be ignored during relocation matching [2]). * - * [1]: https://chromium.googlesource.com/chromiumos/third_party/kernel/+/096925a44076ba5c52faa84d255a847130ff341e%5E%21/#F2 - * [2]: https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/lib/bpf/libbpf.c#n5347 + * [1]: + * https://chromium.googlesource.com/chromiumos/third_party/kernel/+/096925a44076ba5c52faa84d255a847130ff341e%5E%21/#F2 + * [2]: + * https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/lib/bpf/libbpf.c#n5347 */ struct audit_task_info { - kuid_t loginuid; - unsigned int sessionid; - struct audit_context *ctx; + kuid_t loginuid; + unsigned int sessionid; + struct audit_context *ctx; }; struct task_struct___cos { - struct audit_task_info *audit; + struct audit_task_info *audit; }; struct inode___v6_6 { @@ -53,8 +53,8 @@ struct inode___v6_7 { }; struct inode___v6_11 { - int64_t i_mtime_sec; - int64_t i_ctime_sec; + int64_t i_mtime_sec; + int64_t i_ctime_sec; uint32_t i_mtime_nsec; uint32_t i_ctime_nsec; }; @@ -68,15 +68,13 @@ struct inode___v6_11 { */ /* We use this as a fallback for kernels where `struct __kernel_timespec` is not defined. */ -struct modern_bpf__kernel_timespec -{ +struct modern_bpf__kernel_timespec { long int tv_sec; long int tv_nsec; }; /* We use this as a fallback for kernels where `struct __kernel_timex_timeval` is not defined. */ -struct modern_bpf__kernel_timex_timeval -{ +struct modern_bpf__kernel_timex_timeval { long long int tv_sec; long long int tv_usec; }; @@ -86,8 +84,7 @@ struct modern_bpf__kernel_timex_timeval * don't define old_timespec32 (e.g. centos 8 with 4.18 kernel), so we define * it here. */ -struct modern_bpf__kernel_timespec_ia32 -{ +struct modern_bpf__kernel_timespec_ia32 { int tv_sec; int tv_nsec; }; diff --git a/driver/modern_bpf/helpers/base/common.h b/driver/modern_bpf/helpers/base/common.h index 3e66c76880..47c104ac17 100644 --- a/driver/modern_bpf/helpers/base/common.h +++ b/driver/modern_bpf/helpers/base/common.h @@ -29,18 +29,15 @@ */ #undef bpf_printk #ifdef __MODERN_BPF_DEBUG__ -#define bpf_printk(fmt, ...) \ - ({ \ - static char ____fmt[] = fmt "\0"; \ - if(bpf_core_type_exists(struct trace_event_raw_bpf_trace_printk)) \ - { \ - bpf_trace_printk(____fmt, sizeof(____fmt) - 1, ##__VA_ARGS__); \ - } \ - else \ - { \ - ____fmt[sizeof(____fmt) - 2] = '\n'; \ - bpf_trace_printk(____fmt, sizeof(____fmt), ##__VA_ARGS__); \ - } \ +#define bpf_printk(fmt, ...) \ + ({ \ + static char ____fmt[] = fmt "\0"; \ + if(bpf_core_type_exists(struct trace_event_raw_bpf_trace_printk)) { \ + bpf_trace_printk(____fmt, sizeof(____fmt) - 1, ##__VA_ARGS__); \ + } else { \ + ____fmt[sizeof(____fmt) - 2] = '\n'; \ + bpf_trace_printk(____fmt, sizeof(____fmt), ##__VA_ARGS__); \ + } \ }) #else #define bpf_printk(fmt, ...) diff --git a/driver/modern_bpf/helpers/base/maps_getters.h b/driver/modern_bpf/helpers/base/maps_getters.h index f91ba4c207..2dc3477a5e 100644 --- a/driver/modern_bpf/helpers/base/maps_getters.h +++ b/driver/modern_bpf/helpers/base/maps_getters.h @@ -17,53 +17,43 @@ /*=============================== SETTINGS ===========================*/ -static __always_inline uint64_t maps__get_boot_time() -{ +static __always_inline uint64_t maps__get_boot_time() { return g_settings.boot_time; } -static __always_inline uint32_t maps__get_snaplen() -{ +static __always_inline uint32_t maps__get_snaplen() { return g_settings.snaplen; } -static __always_inline bool maps__get_dropping_mode() -{ +static __always_inline bool maps__get_dropping_mode() { return g_settings.dropping_mode; } -static __always_inline uint32_t maps__get_sampling_ratio() -{ +static __always_inline uint32_t maps__get_sampling_ratio() { return g_settings.sampling_ratio; } -static __always_inline bool maps__get_drop_failed() -{ +static __always_inline bool maps__get_drop_failed() { return g_settings.drop_failed; } -static __always_inline bool maps__get_do_dynamic_snaplen() -{ +static __always_inline bool maps__get_do_dynamic_snaplen() { return g_settings.do_dynamic_snaplen; } -static __always_inline uint16_t maps__get_fullcapture_port_range_start() -{ +static __always_inline uint16_t maps__get_fullcapture_port_range_start() { return g_settings.fullcapture_port_range_start; } -static __always_inline uint16_t maps__get_fullcapture_port_range_end() -{ +static __always_inline uint16_t maps__get_fullcapture_port_range_end() { return g_settings.fullcapture_port_range_end; } -static __always_inline uint16_t maps__get_statsd_port() -{ +static __always_inline uint16_t maps__get_statsd_port() { return g_settings.statsd_port; } -static __always_inline int32_t maps__get_scap_tid() -{ +static __always_inline int32_t maps__get_scap_tid() { return g_settings.scap_tid; } @@ -71,23 +61,19 @@ static __always_inline int32_t maps__get_scap_tid() /*=============================== KERNEL CONFIGS ===========================*/ -static __always_inline bool maps__get_is_dropping() -{ +static __always_inline bool maps__get_is_dropping() { return is_dropping; } -static __always_inline void maps__set_is_dropping(bool value) -{ +static __always_inline void maps__set_is_dropping(bool value) { is_dropping = value; } -static __always_inline void* maps__get_socket_file_ops() -{ +static __always_inline void *maps__get_socket_file_ops() { return socket_file_ops; } -static __always_inline void maps__set_socket_file_ops(void* value) -{ +static __always_inline void maps__set_socket_file_ops(void *value) { socket_file_ops = value; } @@ -95,22 +81,20 @@ static __always_inline void maps__set_socket_file_ops(void* value) /*=============================== SAMPLING TABLES ===========================*/ -static __always_inline uint8_t maps__64bit_sampling_syscall_table(uint32_t syscall_id) -{ +static __always_inline uint8_t maps__64bit_sampling_syscall_table(uint32_t syscall_id) { return g_64bit_sampling_syscall_table[syscall_id & (SYSCALL_TABLE_SIZE - 1)]; } -static __always_inline uint8_t maps__64bit_sampling_tracepoint_table(uint32_t event_id) -{ - return g_64bit_sampling_tracepoint_table[event_id < PPM_EVENT_MAX ? event_id : PPM_EVENT_MAX-1]; +static __always_inline uint8_t maps__64bit_sampling_tracepoint_table(uint32_t event_id) { + return g_64bit_sampling_tracepoint_table[event_id < PPM_EVENT_MAX ? event_id + : PPM_EVENT_MAX - 1]; } /*=============================== SAMPLING TABLES ===========================*/ /*=============================== SYSCALL-64 INTERESTING TABLE ===========================*/ -static __always_inline bool maps__64bit_interesting_syscall(uint32_t syscall_id) -{ +static __always_inline bool maps__64bit_interesting_syscall(uint32_t syscall_id) { return g_64bit_interesting_syscalls_table[syscall_id & (SYSCALL_TABLE_SIZE - 1)]; } @@ -118,8 +102,7 @@ static __always_inline bool maps__64bit_interesting_syscall(uint32_t syscall_id) /*=============================== IA32 to 64 TABLE ===========================*/ -static __always_inline uint32_t maps__ia32_to_64(uint32_t syscall_id) -{ +static __always_inline uint32_t maps__ia32_to_64(uint32_t syscall_id) { return g_ia32_to_64_table[syscall_id & (SYSCALL_TABLE_SIZE - 1)]; } @@ -127,10 +110,8 @@ static __always_inline uint32_t maps__ia32_to_64(uint32_t syscall_id) /*=============================== EVENT NUM PARAMS TABLE ===========================*/ -static __always_inline uint8_t maps__get_event_num_params(uint32_t event_id) -{ - if(event_id < 0 || event_id >= PPM_EVENT_MAX) - { +static __always_inline uint8_t maps__get_event_num_params(uint32_t event_id) { + if(event_id < 0 || event_id >= PPM_EVENT_MAX) { return 0; } return g_event_params_table[event_id]; @@ -140,8 +121,7 @@ static __always_inline uint8_t maps__get_event_num_params(uint32_t event_id) /*=============================== PPM_SC TABLE ===========================*/ -static __always_inline uint16_t maps__get_ppm_sc(uint16_t syscall_id) -{ +static __always_inline uint16_t maps__get_ppm_sc(uint16_t syscall_id) { return g_ppm_sc_table[syscall_id & (SYSCALL_TABLE_SIZE - 1)]; } @@ -149,8 +129,7 @@ static __always_inline uint16_t maps__get_ppm_sc(uint16_t syscall_id) /*=============================== AUXILIARY MAPS ===========================*/ -static __always_inline struct auxiliary_map *maps__get_auxiliary_map() -{ +static __always_inline struct auxiliary_map *maps__get_auxiliary_map() { uint32_t cpu_id = (uint32_t)bpf_get_smp_processor_id(); return (struct auxiliary_map *)bpf_map_lookup_elem(&auxiliary_maps, &cpu_id); } @@ -159,8 +138,7 @@ static __always_inline struct auxiliary_map *maps__get_auxiliary_map() /*=============================== COUNTER MAPS ===========================*/ -static __always_inline struct counter_map *maps__get_counter_map() -{ +static __always_inline struct counter_map *maps__get_counter_map() { uint32_t cpu_id = (uint32_t)bpf_get_smp_processor_id(); return (struct counter_map *)bpf_map_lookup_elem(&counter_maps, &cpu_id); } @@ -169,8 +147,7 @@ static __always_inline struct counter_map *maps__get_counter_map() /*=============================== RINGBUF MAPS ===========================*/ -static __always_inline struct ringbuf_map *maps__get_ringbuf_map() -{ +static __always_inline struct ringbuf_map *maps__get_ringbuf_map() { uint32_t cpu_id = (uint32_t)bpf_get_smp_processor_id(); return (struct ringbuf_map *)bpf_map_lookup_elem(&ringbuf_maps, &cpu_id); } diff --git a/driver/modern_bpf/helpers/base/push_data.h b/driver/modern_bpf/helpers/base/push_data.h index a304b8522f..fc4f9d8a27 100644 --- a/driver/modern_bpf/helpers/base/push_data.h +++ b/driver/modern_bpf/helpers/base/push_data.h @@ -78,8 +78,7 @@ /* This enum is used to tell our helpers if they have to * read from kernel or user memory. */ -enum read_memory -{ +enum read_memory { USER = 0, KERNEL = 1, }; @@ -109,8 +108,7 @@ enum read_memory * @param lengths_pos pointer to the first empty slot into the `lengths_arr`. * @param len length to store inside the array (16 bit). */ -static __always_inline void push__param_len(uint8_t *data, uint8_t *lengths_pos, uint16_t len) -{ +static __always_inline void push__param_len(uint8_t *data, uint8_t *lengths_pos, uint16_t len) { *((uint16_t *)&data[SAFE_ACCESS(*lengths_pos)]) = len; *lengths_pos += sizeof(uint16_t); } @@ -135,56 +133,49 @@ static __always_inline void push__param_len(uint8_t *data, uint8_t *lengths_pos, // PUSH FIXED DIMENSIONS /////////////////////////// -static __always_inline void push__u8(uint8_t *data, uint64_t *payload_pos, uint8_t param) -{ +static __always_inline void push__u8(uint8_t *data, uint64_t *payload_pos, uint8_t param) { *((uint8_t *)&data[SAFE_ACCESS(*payload_pos)]) = param; *payload_pos += sizeof(uint8_t); } -static __always_inline void push__u16(uint8_t *data, uint64_t *payload_pos, uint16_t param) -{ +static __always_inline void push__u16(uint8_t *data, uint64_t *payload_pos, uint16_t param) { *((uint16_t *)&data[SAFE_ACCESS(*payload_pos)]) = param; *payload_pos += sizeof(uint16_t); } -static __always_inline void push__u32(uint8_t *data, uint64_t *payload_pos, uint32_t param) -{ +static __always_inline void push__u32(uint8_t *data, uint64_t *payload_pos, uint32_t param) { *((uint32_t *)&data[SAFE_ACCESS(*payload_pos)]) = param; *payload_pos += sizeof(uint32_t); } -static __always_inline void push__u64(uint8_t *data, uint64_t *payload_pos, uint64_t param) -{ +static __always_inline void push__u64(uint8_t *data, uint64_t *payload_pos, uint64_t param) { *((uint64_t *)&data[SAFE_ACCESS(*payload_pos)]) = param; *payload_pos += sizeof(uint64_t); } -static __always_inline void push__s16(uint8_t *data, uint64_t *payload_pos, int16_t param) -{ +static __always_inline void push__s16(uint8_t *data, uint64_t *payload_pos, int16_t param) { *((int16_t *)&data[SAFE_ACCESS(*payload_pos)]) = param; *payload_pos += sizeof(int16_t); } -static __always_inline void push__s32(uint8_t *data, uint64_t *payload_pos, int32_t param) -{ +static __always_inline void push__s32(uint8_t *data, uint64_t *payload_pos, int32_t param) { *((int32_t *)&data[SAFE_ACCESS(*payload_pos)]) = param; *payload_pos += sizeof(int32_t); } -static __always_inline void push__s64(uint8_t *data, uint64_t *payload_pos, int64_t param) -{ +static __always_inline void push__s64(uint8_t *data, uint64_t *payload_pos, int64_t param) { *((int64_t *)&data[SAFE_ACCESS(*payload_pos)]) = param; *payload_pos += sizeof(int64_t); } -static __always_inline void push__ipv6(uint8_t *data, uint64_t *payload_pos, uint32_t ipv6[4]) -{ +static __always_inline void push__ipv6(uint8_t *data, uint64_t *payload_pos, uint32_t ipv6[4]) { __builtin_memcpy(&data[SAFE_ACCESS(*payload_pos)], ipv6, 16); *payload_pos += 16; } -static __always_inline void push__new_character(uint8_t *data, uint64_t *payload_pos, char character) -{ +static __always_inline void push__new_character(uint8_t *data, + uint64_t *payload_pos, + char character) { *((char *)&data[SAFE_ACCESS(*payload_pos)]) = character; *payload_pos += sizeof(char); } @@ -193,8 +184,9 @@ static __always_inline void push__new_character(uint8_t *data, uint64_t *payload * a previous character. Since we overwrite it we don't need to update * `payload_pos`. */ -static __always_inline void push__previous_character(uint8_t *data, uint64_t *payload_pos, char character) -{ +static __always_inline void push__previous_character(uint8_t *data, + uint64_t *payload_pos, + char character) { *((char *)&data[SAFE_ACCESS(*payload_pos - 1)]) = character; } @@ -214,35 +206,34 @@ static __always_inline void push__previous_character(uint8_t *data, uint64_t *pa * @param charbuf_pointer pointer to the charbuf. * @param limit maximum number of bytes that we read in case we don't find a `\0` * @param mem tell where it must read: user-space or kernel-space. - * @return (uint16_t) the number of bytes written in the buffer. Returns '0' if the passed pointer is not valid. - * Returns `1` if the provided pointer points to an empty string "". + * @return (uint16_t) the number of bytes written in the buffer. Returns '0' if the passed pointer + * is not valid. Returns `1` if the provided pointer points to an empty string "". */ -static __always_inline uint16_t push__charbuf(uint8_t *data, uint64_t *payload_pos, unsigned long charbuf_pointer, uint16_t limit, enum read_memory mem) -{ +static __always_inline uint16_t push__charbuf(uint8_t *data, + uint64_t *payload_pos, + unsigned long charbuf_pointer, + uint16_t limit, + enum read_memory mem) { int written_bytes = 0; - if(mem == KERNEL) - { + if(mem == KERNEL) { written_bytes = bpf_probe_read_kernel_str(&data[SAFE_ACCESS(*payload_pos)], - limit, - (char *)charbuf_pointer); - } - else - { + limit, + (char *)charbuf_pointer); + } else { written_bytes = bpf_probe_read_user_str(&data[SAFE_ACCESS(*payload_pos)], - limit, - (char *)charbuf_pointer); + limit, + (char *)charbuf_pointer); } - if(written_bytes < 0) - { + if(written_bytes < 0) { /* This is probably a page fault */ return 0; } - /* Since `bpf_probe_read_user_str` return `0` in case of empty string we push a `\0` and we return 1. */ - if(written_bytes==0) - { + /* Since `bpf_probe_read_user_str` return `0` in case of empty string we push a `\0` and we + * return 1. */ + if(written_bytes == 0) { *((char *)&data[SAFE_ACCESS(*payload_pos)]) = '\0'; written_bytes = 1; } @@ -265,25 +256,24 @@ static __always_inline uint16_t push__charbuf(uint8_t *data, uint64_t *payload_p * @param bytebuf_pointer pointer to the bytebuf. * @param len_to_read bytes that we need to read from the pointer. * @param mem from which memory we need to read: user-space or kernel-space. - * @return (uint16_t) the number of bytes written in the buffer. Could be '0' if the passed pointer is not valid. + * @return (uint16_t) the number of bytes written in the buffer. Could be '0' if the passed pointer + * is not valid. */ -static __always_inline uint16_t push__bytebuf(uint8_t *data, uint64_t *payload_pos, unsigned long bytebuf_pointer, uint16_t len_to_read, enum read_memory mem) -{ - if(mem == KERNEL) - { +static __always_inline uint16_t push__bytebuf(uint8_t *data, + uint64_t *payload_pos, + unsigned long bytebuf_pointer, + uint16_t len_to_read, + enum read_memory mem) { + if(mem == KERNEL) { if(bpf_probe_read_kernel(&data[SAFE_ACCESS(*payload_pos)], - len_to_read, - (void *)bytebuf_pointer) != 0) - { + len_to_read, + (void *)bytebuf_pointer) != 0) { return 0; } - } - else - { + } else { if(bpf_probe_read_user(&data[SAFE_ACCESS(*payload_pos)], - len_to_read, - (void *)bytebuf_pointer) != 0) - { + len_to_read, + (void *)bytebuf_pointer) != 0) { return 0; } } diff --git a/driver/modern_bpf/helpers/base/read_from_task.h b/driver/modern_bpf/helpers/base/read_from_task.h index ee99613710..4160689366 100644 --- a/driver/modern_bpf/helpers/base/read_from_task.h +++ b/driver/modern_bpf/helpers/base/read_from_task.h @@ -14,15 +14,12 @@ * Where not possible it retrieves the normal pointer without BTF info * Kernel version required: 5.11. */ -static __always_inline struct task_struct *get_current_task() -{ - if(bpf_core_enum_value_exists(enum bpf_func_id, BPF_FUNC_get_current_task_btf) - && (bpf_core_enum_value(enum bpf_func_id, BPF_FUNC_get_current_task_btf) == BPF_FUNC_get_current_task_btf)) - { +static __always_inline struct task_struct *get_current_task() { + if(bpf_core_enum_value_exists(enum bpf_func_id, BPF_FUNC_get_current_task_btf) && + (bpf_core_enum_value(enum bpf_func_id, BPF_FUNC_get_current_task_btf) == + BPF_FUNC_get_current_task_btf)) { return (struct task_struct *)bpf_get_current_task_btf(); - } - else - { + } else { return (struct task_struct *)bpf_get_current_task(); } } @@ -32,19 +29,17 @@ static __always_inline struct task_struct *get_current_task() * N.B. Only up to 9 "field accessors" are supported, which should be more * than enough for any practical purpose. */ -#define READ_TASK_FIELD(src, a, ...) \ - ({ \ - ___type((src), a, ##__VA_ARGS__) __r; \ - if(bpf_core_enum_value_exists(enum bpf_func_id, BPF_FUNC_get_current_task_btf) \ - && (bpf_core_enum_value(enum bpf_func_id, BPF_FUNC_get_current_task_btf) == BPF_FUNC_get_current_task_btf)) \ - { \ - __r = ___arrow((src), a, ##__VA_ARGS__); \ - } \ - else \ - { \ - BPF_CORE_READ_INTO(&__r, (src), a, ##__VA_ARGS__); \ - } \ - __r; \ +#define READ_TASK_FIELD(src, a, ...) \ + ({ \ + ___type((src), a, ##__VA_ARGS__) __r; \ + if(bpf_core_enum_value_exists(enum bpf_func_id, BPF_FUNC_get_current_task_btf) && \ + (bpf_core_enum_value(enum bpf_func_id, BPF_FUNC_get_current_task_btf) == \ + BPF_FUNC_get_current_task_btf)) { \ + __r = ___arrow((src), a, ##__VA_ARGS__); \ + } else { \ + BPF_CORE_READ_INTO(&__r, (src), a, ##__VA_ARGS__); \ + } \ + __r; \ }) /* This macro `READ_TASK_FIELD_INTO` is the equivalent of `BPF_CORE_READ_INTO`. @@ -66,15 +61,13 @@ static __always_inline struct task_struct *get_current_task() * } * ... */ -#define READ_TASK_FIELD_INTO(dst, src, a, ...) \ - ({ \ - if(bpf_core_enum_value_exists(enum bpf_func_id, BPF_FUNC_get_current_task_btf) \ - && (bpf_core_enum_value(enum bpf_func_id, BPF_FUNC_get_current_task_btf) == BPF_FUNC_get_current_task_btf)) \ - { \ - *dst = ___arrow((src), a, ##__VA_ARGS__); \ - } \ - else \ - { \ - BPF_CORE_READ_INTO(dst, src, a, ##__VA_ARGS__); \ - } \ +#define READ_TASK_FIELD_INTO(dst, src, a, ...) \ + ({ \ + if(bpf_core_enum_value_exists(enum bpf_func_id, BPF_FUNC_get_current_task_btf) && \ + (bpf_core_enum_value(enum bpf_func_id, BPF_FUNC_get_current_task_btf) == \ + BPF_FUNC_get_current_task_btf)) { \ + *dst = ___arrow((src), a, ##__VA_ARGS__); \ + } else { \ + BPF_CORE_READ_INTO(dst, src, a, ##__VA_ARGS__); \ + } \ }) diff --git a/driver/modern_bpf/helpers/base/shared_size.h b/driver/modern_bpf/helpers/base/shared_size.h index 3c92857faa..61e24dc7ae 100644 --- a/driver/modern_bpf/helpers/base/shared_size.h +++ b/driver/modern_bpf/helpers/base/shared_size.h @@ -63,8 +63,7 @@ /* This enum is used to tell network helpers if the connection outbound * or inbound */ -enum connection_direction -{ +enum connection_direction { OUTBOUND = 0, INBOUND = 1, }; @@ -72,8 +71,7 @@ enum connection_direction /* This enum is used to tell poll helpers if we need requested or returned * events. */ -enum poll_events_direction -{ +enum poll_events_direction { REQUESTED_EVENTS = 0, RETURNED_EVENTS = 1, }; diff --git a/driver/modern_bpf/helpers/base/stats.h b/driver/modern_bpf/helpers/base/stats.h index ffab1059ae..986702b1ac 100644 --- a/driver/modern_bpf/helpers/base/stats.h +++ b/driver/modern_bpf/helpers/base/stats.h @@ -16,14 +16,12 @@ // KERNEL SYSCALL CATEGORY DROP COUNTERS ///////////////////////////////////////// -static __always_inline void compute_event_types_stats(uint16_t event_type, struct counter_map *counter) -{ - if(!counter) - { +static __always_inline void compute_event_types_stats(uint16_t event_type, + struct counter_map *counter) { + if(!counter) { return; } - switch(event_type) - { + switch(event_type) { // enter case PPME_SYSCALL_OPEN_E: case PPME_SYSCALL_CREAT_E: @@ -84,7 +82,7 @@ static __always_inline void compute_event_types_stats(uint16_t event_type, struc break; case PPME_PROCEXIT_1_E: counter->n_drops_buffer_proc_exit++; - break; + break; // exit case PPME_SYSCALL_OPEN_X: case PPME_SYSCALL_CREAT_X: @@ -145,7 +143,7 @@ static __always_inline void compute_event_types_stats(uint16_t event_type, struc break; case PPME_SYSCALL_CLOSE_X: counter->n_drops_buffer_close_exit++; - break; + break; default: break; } diff --git a/driver/modern_bpf/helpers/extract/extract_from_kernel.h b/driver/modern_bpf/helpers/extract/extract_from_kernel.h index 4c58865977..532f53d8ed 100644 --- a/driver/modern_bpf/helpers/extract/extract_from_kernel.h +++ b/driver/modern_bpf/helpers/extract/extract_from_kernel.h @@ -22,8 +22,7 @@ #define DO_PAGE_SHIFT(x) (x) << (IOC_PAGE_SHIFT - 10) /* This enum should simplify the capabilities extraction. */ -enum capability_type -{ +enum capability_type { CAP_INHERITABLE = 0, CAP_PERMITTED = 1, CAP_EFFECTIVE = 2, @@ -43,8 +42,7 @@ enum capability_type * @param regs pointer to the struct where we find the arguments * @return syscall id */ -static __always_inline uint32_t extract__syscall_id(struct pt_regs *regs) -{ +static __always_inline uint32_t extract__syscall_id(struct pt_regs *regs) { #if defined(__TARGET_ARCH_x86) return (uint32_t)regs->orig_ax; #elif defined(__TARGET_ARCH_arm64) @@ -58,8 +56,7 @@ static __always_inline uint32_t extract__syscall_id(struct pt_regs *regs) #endif } -static __always_inline bool bpf_in_ia32_syscall() -{ +static __always_inline bool bpf_in_ia32_syscall() { uint32_t status = 0; struct task_struct *task = get_current_task(); @@ -71,8 +68,7 @@ static __always_inline bool bpf_in_ia32_syscall() // already enforce that CONFIG_THREAD_INFO_IN_TASK is defined, // therefore we already show a warning to the user // when building against an unsupported kernel release. - if(!bpf_core_field_exists(((struct task_struct*)0)->thread_info)) - { + if(!bpf_core_field_exists(((struct task_struct *)0)->thread_info)) { return false; } @@ -101,14 +97,11 @@ static __always_inline bool bpf_in_ia32_syscall() * @return generic unsigned long value that can be a pointer to the arg * or directly the value, it depends on the type of arg. */ -static __always_inline unsigned long extract__syscall_argument(struct pt_regs *regs, int idx) -{ +static __always_inline unsigned long extract__syscall_argument(struct pt_regs *regs, int idx) { unsigned long arg; #if defined(__TARGET_ARCH_x86) - if (bpf_in_ia32_syscall()) - { - switch(idx) - { + if(bpf_in_ia32_syscall()) { + switch(idx) { case 0: arg = BPF_CORE_READ(regs, bx); break; @@ -133,8 +126,7 @@ static __always_inline unsigned long extract__syscall_argument(struct pt_regs *r return arg; } #endif - switch(idx) - { + switch(idx) { case 0: arg = PT_REGS_PARM1_CORE_SYSCALL(regs); break; @@ -173,36 +165,31 @@ static __always_inline unsigned long extract__syscall_argument(struct pt_regs *r * @param num Number of arguments to extract * @param regs Pointer to the struct pt_regs to access arguments and system call ID */ -static __always_inline void extract__network_args(void *argv, int num, struct pt_regs *regs) -{ +static __always_inline void extract__network_args(void *argv, int num, struct pt_regs *regs) { #ifdef __NR_socketcall int id = extract__syscall_id(regs); - if(id == __NR_socketcall) - { + if(id == __NR_socketcall) { unsigned long args_pointer = extract__syscall_argument(regs, 1); bpf_probe_read_user(argv, num * sizeof(unsigned long), (void *)args_pointer); return; } #elif defined(__TARGET_ARCH_x86) int id = extract__syscall_id(regs); - if(bpf_in_ia32_syscall() && id == __NR_ia32_socketcall) - { + if(bpf_in_ia32_syscall() && id == __NR_ia32_socketcall) { // First read all arguments on 32 bits. uint32_t args_u32[6] = {}; unsigned long args_pointer = extract__syscall_argument(regs, 1); bpf_probe_read_user(args_u32, num * sizeof(uint32_t), (void *)args_pointer); unsigned long *dst = (unsigned long *)argv; - for (int i = 0; i < num; i++) - { + for(int i = 0; i < num; i++) { dst[i] = (unsigned long)args_u32[i]; } return; } #endif unsigned long *dst = (unsigned long *)argv; - for (int i = 0; i < num; i++) - { + for(int i = 0; i < num; i++) { dst[i] = extract__syscall_argument(regs, i); } } @@ -219,8 +206,7 @@ static __always_inline void extract__network_args(void *argv, int num, struct pt * @param dev device number extracted directly from the kernel. * @return encoded device number. */ -static __always_inline dev_t encode_dev(dev_t dev) -{ +static __always_inline dev_t encode_dev(dev_t dev) { unsigned int major = MAJOR(dev); unsigned int minor = MINOR(dev); @@ -238,32 +224,27 @@ static __always_inline dev_t encode_dev(dev_t dev) * @return struct file* pointer to the `struct file` associated with the * file descriptor. Return a NULL pointer in case of failure. */ -static __always_inline struct file *extract__file_struct_from_fd(int32_t file_descriptor) -{ +static __always_inline struct file *extract__file_struct_from_fd(int32_t file_descriptor) { struct file *f = NULL; - if(file_descriptor >= 0) - { + if(file_descriptor >= 0) { struct file **fds = NULL; struct fdtable *fdt = NULL; int max_fds = 0; struct task_struct *task = get_current_task(); BPF_CORE_READ_INTO(&fdt, task, files, fdt); - if(unlikely(fdt == NULL)) - { + if(unlikely(fdt == NULL)) { return NULL; } // Try a bound check to avoid reading out of bounds. BPF_CORE_READ_INTO(&max_fds, fdt, max_fds); - if(unlikely(file_descriptor >= max_fds)) - { + if(unlikely(file_descriptor >= max_fds)) { return NULL; } BPF_CORE_READ_INTO(&fds, fdt, fd); - if(fds != NULL) - { + if(fds != NULL) { bpf_probe_read_kernel(&f, sizeof(struct file *), &fds[file_descriptor]); } } @@ -276,11 +257,9 @@ static __always_inline struct file *extract__file_struct_from_fd(int32_t file_de * @param fd generic file descriptor. * @param ino pointer to the inode number we have to fill. */ -static __always_inline void extract__ino_from_fd(int32_t fd, uint64_t *ino) -{ +static __always_inline void extract__ino_from_fd(int32_t fd, uint64_t *ino) { struct file *f = extract__file_struct_from_fd(fd); - if(!f) - { + if(!f) { return; } @@ -293,8 +272,7 @@ static __always_inline void extract__ino_from_fd(int32_t fd, uint64_t *ino) * @param task pointer to task struct. * @return `f_inode` of task exe_file. */ -static __always_inline struct inode *extract__exe_inode_from_task(struct task_struct *task) -{ +static __always_inline struct inode *extract__exe_inode_from_task(struct task_struct *task) { return BPF_CORE_READ(task, mm, exe_file, f_inode); } @@ -304,8 +282,7 @@ static __always_inline struct inode *extract__exe_inode_from_task(struct task_st * @param task pointer to task struct. * @return `f_inode` of task mm. */ -static __always_inline struct file *extract__exe_file_from_task(struct task_struct *task) -{ +static __always_inline struct file *extract__exe_file_from_task(struct task_struct *task) { return READ_TASK_FIELD(task, mm, exe_file); } @@ -316,8 +293,7 @@ static __always_inline struct file *extract__exe_file_from_task(struct task_stru * @param ino pointer to the inode number we have to fill. * @return `i_ino` from f_inode. */ -static __always_inline void extract__ino_from_inode(struct inode *f_inode, uint64_t *ino) -{ +static __always_inline void extract__ino_from_inode(struct inode *f_inode, uint64_t *ino) { BPF_CORE_READ_INTO(ino, f_inode, i_ino); } @@ -327,14 +303,12 @@ static __always_inline void extract__ino_from_inode(struct inode *f_inode, uint6 * @param time timespec64 struct. * @return epoch in ns. */ -static __always_inline uint64_t extract__epoch_ns_from_time(struct timespec64 time) -{ +static __always_inline uint64_t extract__epoch_ns_from_time(struct timespec64 time) { time64_t tv_sec = time.tv_sec; - if (tv_sec < 0) - { + if(tv_sec < 0) { return 0; } - return (tv_sec * (uint64_t) 1000000000 + time.tv_nsec); + return (tv_sec * (uint64_t)1000000000 + time.tv_nsec); } /** @@ -343,16 +317,13 @@ static __always_inline uint64_t extract__epoch_ns_from_time(struct timespec64 ti * @param fd generic file descriptor. * @return PPM_O_F_CREATED if file is created. */ -static __always_inline uint32_t extract__fmode_created_from_fd(int32_t fd) -{ - if(fd < 0) - { - return 0; +static __always_inline uint32_t extract__fmode_created_from_fd(int32_t fd) { + if(fd < 0) { + return 0; } struct file *f = extract__file_struct_from_fd(fd); - if(!f) - { + if(!f) { return 0; } @@ -370,8 +341,7 @@ static __always_inline uint32_t extract__fmode_created_from_fd(int32_t fd) * @param task pointer to the task struct. * @param fdlimit return value passed by reference. */ -static __always_inline void extract__fdlimit(struct task_struct *task, unsigned long *fdlimit) -{ +static __always_inline void extract__fdlimit(struct task_struct *task, unsigned long *fdlimit) { READ_TASK_FIELD_INTO(fdlimit, task, signal, rlim[RLIMIT_NOFILE].rlim_cur); } @@ -397,13 +367,12 @@ static __always_inline void extract__fdlimit(struct task_struct *task, unsigned * @param capability_type type of capability to extract defined by us. * @return PPM encoded capability value */ -static __always_inline uint64_t extract__capability(struct task_struct *task, enum capability_type capability_type) -{ +static __always_inline uint64_t extract__capability(struct task_struct *task, + enum capability_type capability_type) { kernel_cap_t cap_struct; unsigned long capability; - switch(capability_type) - { + switch(capability_type) { case CAP_INHERITABLE: READ_TASK_FIELD_INTO(&cap_struct, task, cred, cap_inheritable); break; @@ -423,8 +392,7 @@ static __always_inline uint64_t extract__capability(struct task_struct *task, en // Kernel 6.3 changed the kernel_cap_struct type from uint32_t[2] to uint64_t. // Luckily enough, it also changed field name from cap to val. - if(bpf_core_field_exists(((struct kernel_cap_struct *)0)->cap)) - { + if(bpf_core_field_exists(((struct kernel_cap_struct *)0)->cap)) { return capabilities_to_scap(((unsigned long)cap_struct.cap[1] << 32) | cap_struct.cap[0]); } kernel_cap_t___v6_3 *new_cap = (kernel_cap_t___v6_3 *)&cap_struct; @@ -442,11 +410,10 @@ static __always_inline uint64_t extract__capability(struct task_struct *task, en * @param type pid type. * @return struct pid * pointer to the right pid struct. */ -static __always_inline struct pid *extract__task_pid_struct(struct task_struct *task, enum pid_type type) -{ +static __always_inline struct pid *extract__task_pid_struct(struct task_struct *task, + enum pid_type type) { struct pid *task_pid = NULL; - switch(type) - { + switch(type) { /* we cannot take this info from signal struct. */ case PIDTYPE_PID: READ_TASK_FIELD_INTO(&task_pid, task, thread_pid); @@ -464,12 +431,10 @@ static __always_inline struct pid *extract__task_pid_struct(struct task_struct * * @param pid pointer to the task pid struct. * @return struct pid_namespace* in which the specified pid was allocated. */ -static __always_inline struct pid_namespace *extract__namespace_of_pid(struct pid *pid) -{ +static __always_inline struct pid_namespace *extract__namespace_of_pid(struct pid *pid) { uint32_t level = 0; struct pid_namespace *ns = NULL; - if(pid) - { + if(pid) { BPF_CORE_READ_INTO(&level, pid, level); BPF_CORE_READ_INTO(&ns, pid, numbers[level].ns); } @@ -484,8 +449,8 @@ static __always_inline struct pid_namespace *extract__namespace_of_pid(struct pi * @param ns pointer to the namespace struct. * @return pid_t id seen from the pid namespace 'ns'. */ -static __always_inline pid_t extract__xid_nr_seen_by_namespace(struct pid *pid, struct pid_namespace *ns) -{ +static __always_inline pid_t extract__xid_nr_seen_by_namespace(struct pid *pid, + struct pid_namespace *ns) { struct upid upid = {0}; pid_t nr = 0; unsigned int pid_level = 0; @@ -493,11 +458,9 @@ static __always_inline pid_t extract__xid_nr_seen_by_namespace(struct pid *pid, BPF_CORE_READ_INTO(&pid_level, pid, level); BPF_CORE_READ_INTO(&ns_level, ns, level); - if(pid && ns_level <= pid_level) - { + if(pid && ns_level <= pid_level) { BPF_CORE_READ_INTO(&upid, pid, numbers[ns_level]); - if(upid.ns == ns) - { + if(upid.ns == ns) { nr = upid.nr; } } @@ -523,10 +486,8 @@ static __always_inline pid_t extract__xid_nr_seen_by_namespace(struct pid *pid, * @param type pid type. * @return `xid` seen from the init namespace. */ -static __always_inline pid_t extract__task_xid_nr(struct task_struct *task, enum pid_type type) -{ - switch(type) - { +static __always_inline pid_t extract__task_xid_nr(struct task_struct *task, enum pid_type type) { + switch(type) { case PIDTYPE_PID: return READ_TASK_FIELD(task, pid); @@ -549,8 +510,7 @@ static __always_inline pid_t extract__task_xid_nr(struct task_struct *task, enum * @param type pid type. * @return `xid` seen from the current task pid namespace. */ -static __always_inline pid_t extract__task_xid_vnr(struct task_struct *task, enum pid_type type) -{ +static __always_inline pid_t extract__task_xid_vnr(struct task_struct *task, enum pid_type type) { struct pid *pid_struct = extract__task_pid_struct(task, type); struct pid_namespace *pid_namespace_struct = extract__namespace_of_pid(pid_struct); return extract__xid_nr_seen_by_namespace(pid_struct, pid_namespace_struct); @@ -564,11 +524,11 @@ static __always_inline pid_t extract__task_xid_vnr(struct task_struct *task, enu * @param type pid type. * @return `start_time` of init task struct from pid namespace seen from current task pid namespace. */ -static __always_inline uint64_t extract__task_pidns_start_time(struct task_struct *task, enum pid_type type, long in_childtid) -{ +static __always_inline uint64_t extract__task_pidns_start_time(struct task_struct *task, + enum pid_type type, + long in_childtid) { // only perform lookup when clone/vfork/fork returns 0 (child process / childtid) - if (in_childtid == 0) - { + if(in_childtid == 0) { struct pid *pid_struct = extract__task_pid_struct(task, type); struct pid_namespace *pid_namespace = extract__namespace_of_pid(pid_struct); return BPF_CORE_READ(pid_namespace, child_reaper, start_time); @@ -586,8 +546,7 @@ static __always_inline uint64_t extract__task_pidns_start_time(struct task_struc * @param task pointer to task struct. * @param pgft_maj return value passed by reference. */ -static __always_inline void extract__pgft_maj(struct task_struct *task, unsigned long *pgft_maj) -{ +static __always_inline void extract__pgft_maj(struct task_struct *task, unsigned long *pgft_maj) { READ_TASK_FIELD_INTO(pgft_maj, task, maj_flt); } @@ -597,8 +556,7 @@ static __always_inline void extract__pgft_maj(struct task_struct *task, unsigned * @param task pointer to task struct. * @param pgft_min return value passed by reference. */ -static __always_inline void extract__pgft_min(struct task_struct *task, unsigned long *pgft_min) -{ +static __always_inline void extract__pgft_min(struct task_struct *task, unsigned long *pgft_min) { READ_TASK_FIELD_INTO(pgft_min, task, min_flt); } @@ -608,8 +566,7 @@ static __always_inline void extract__pgft_min(struct task_struct *task, unsigned * @param mm pointer to mm_struct. * @return number in KB */ -static __always_inline unsigned long extract__vm_size(struct mm_struct *mm) -{ +static __always_inline unsigned long extract__vm_size(struct mm_struct *mm) { unsigned long vm_pages = 0; BPF_CORE_READ_INTO(&vm_pages, mm, total_vm); return DO_PAGE_SHIFT(vm_pages); @@ -621,23 +578,20 @@ static __always_inline unsigned long extract__vm_size(struct mm_struct *mm) * @param mm pointer to mm_struct. * @return number in KB */ -static __always_inline unsigned long extract__vm_rss(struct mm_struct *mm) -{ +static __always_inline unsigned long extract__vm_rss(struct mm_struct *mm) { int64_t file_pages = 0; int64_t anon_pages = 0; int64_t shmem_pages = 0; - /* In recent kernel versions (https://github.com/torvalds/linux/commit/f1a7941243c102a44e8847e3b94ff4ff3ec56f25) - * `struct mm_rss_stat` doesn't exist anymore. + /* In recent kernel versions + * (https://github.com/torvalds/linux/commit/f1a7941243c102a44e8847e3b94ff4ff3ec56f25) `struct + * mm_rss_stat` doesn't exist anymore. */ - if(bpf_core_type_exists(struct mm_rss_stat)) - { + if(bpf_core_type_exists(struct mm_rss_stat)) { BPF_CORE_READ_INTO(&file_pages, mm, rss_stat.count[MM_FILEPAGES].counter); BPF_CORE_READ_INTO(&anon_pages, mm, rss_stat.count[MM_ANONPAGES].counter); BPF_CORE_READ_INTO(&shmem_pages, mm, rss_stat.count[MM_SHMEMPAGES].counter); - } - else - { + } else { struct mm_struct___v6_2 *mm_v6_2 = (void *)mm; BPF_CORE_READ_INTO(&file_pages, mm_v6_2, rss_stat[MM_FILEPAGES].count); BPF_CORE_READ_INTO(&anon_pages, mm_v6_2, rss_stat[MM_ANONPAGES].count); @@ -652,15 +606,11 @@ static __always_inline unsigned long extract__vm_rss(struct mm_struct *mm) * @param mm pointer to mm_struct. * @return number in KB */ -static __always_inline unsigned long extract__vm_swap(struct mm_struct *mm) -{ +static __always_inline unsigned long extract__vm_swap(struct mm_struct *mm) { int64_t swap_entries = 0; - if(bpf_core_type_exists(struct mm_rss_stat)) - { + if(bpf_core_type_exists(struct mm_rss_stat)) { BPF_CORE_READ_INTO(&swap_entries, mm, rss_stat.count[MM_SWAPENTS].counter); - } - else - { + } else { struct mm_struct___v6_2 *mm_v6_2 = (void *)mm; BPF_CORE_READ_INTO(&swap_entries, mm_v6_2, rss_stat[MM_SWAPENTS].count); } @@ -677,8 +627,7 @@ static __always_inline unsigned long extract__vm_swap(struct mm_struct *mm) * @param task pointer to task_struct. * @return encoded tty number */ -static __always_inline uint32_t exctract__tty(struct task_struct *task) -{ +static __always_inline uint32_t exctract__tty(struct task_struct *task) { struct signal_struct *signal; struct tty_struct *tty; struct tty_driver *driver; @@ -691,20 +640,17 @@ static __always_inline uint32_t exctract__tty(struct task_struct *task) checks similar to driver-bpf */ BPF_CORE_READ_INTO(&signal, task, signal); - if (!signal) - { + if(!signal) { return 0; } BPF_CORE_READ_INTO(&tty, signal, tty); - if (!tty) - { + if(!tty) { return 0; } BPF_CORE_READ_INTO(&driver, tty, driver); - if (!driver) - { + if(!driver) { return 0; } @@ -724,20 +670,15 @@ static __always_inline uint32_t exctract__tty(struct task_struct *task) * @param task pointer to task struct * @param loginuid return value by reference */ -static __always_inline void extract__loginuid(struct task_struct *task, uint32_t *loginuid) -{ +static __always_inline void extract__loginuid(struct task_struct *task, uint32_t *loginuid) { *loginuid = UINT32_MAX; - if(bpf_core_field_exists(task->loginuid)) - { + if(bpf_core_field_exists(task->loginuid)) { READ_TASK_FIELD_INTO(loginuid, task, loginuid.val); - } - else - { + } else { struct task_struct___cos *task_cos = (void *)task; - if(bpf_core_field_exists(struct task_struct___cos, audit)) - { + if(bpf_core_field_exists(struct task_struct___cos, audit)) { BPF_CORE_READ_INTO(loginuid, task_cos, audit, loginuid.val); } } @@ -754,26 +695,22 @@ static __always_inline void extract__loginuid(struct task_struct *task, uint32_t * @param flags internal flag representation. * @return scap flag representation. */ -static __always_inline unsigned long extract__clone_flags(struct task_struct *task, unsigned long flags) -{ - unsigned long ppm_flags = clone_flags_to_scap((int) flags); +static __always_inline unsigned long extract__clone_flags(struct task_struct *task, + unsigned long flags) { + unsigned long ppm_flags = clone_flags_to_scap((int)flags); struct pid *pid = extract__task_pid_struct(task, PIDTYPE_PID); struct pid_namespace *ns = extract__namespace_of_pid(pid); unsigned int ns_level; BPF_CORE_READ_INTO(&ns_level, ns, level); - if(ns_level != 0) - { + if(ns_level != 0) { ppm_flags |= PPM_CL_CHILD_IN_PIDNS; - } - else - { + } else { /* This alternative check is meaningful only for the parent and not for the child */ struct pid_namespace *ns_children; READ_TASK_FIELD_INTO(&ns_children, task, nsproxy, pid_ns_for_children); - if(ns_children != ns) - { + if(ns_children != ns) { ppm_flags |= PPM_CL_CHILD_IN_PIDNS; } } @@ -790,8 +727,7 @@ static __always_inline unsigned long extract__clone_flags(struct task_struct *ta * @param task pointer to task struct * @param euid return value by reference */ -static __always_inline void extract__euid(struct task_struct *task, uint32_t *euid) -{ +static __always_inline void extract__euid(struct task_struct *task, uint32_t *euid) { *euid = UINT32_MAX; READ_TASK_FIELD_INTO(euid, task, cred, euid.val); } @@ -802,8 +738,7 @@ static __always_inline void extract__euid(struct task_struct *task, uint32_t *eu * @param task pointer to task struct * @param egid return value by reference */ -static __always_inline void extract__egid(struct task_struct *task, uint32_t *egid) -{ +static __always_inline void extract__egid(struct task_struct *task, uint32_t *egid) { READ_TASK_FIELD_INTO(egid, task, cred, egid.val); } @@ -811,33 +746,29 @@ static __always_inline void extract__egid(struct task_struct *task, uint32_t *eg // EXECVE FLAGS EXTRACTION //////////////////////// -static __always_inline enum ppm_overlay extract__overlay_layer(struct file *file) -{ +static __always_inline enum ppm_overlay extract__overlay_layer(struct file *file) { struct dentry *dentry = (struct dentry *)BPF_CORE_READ(file, f_path.dentry); unsigned long sb_magic = BPF_CORE_READ(dentry, d_sb, s_magic); - if(sb_magic != PPM_OVERLAYFS_SUPER_MAGIC) - { + if(sb_magic != PPM_OVERLAYFS_SUPER_MAGIC) { return PPM_NOT_OVERLAY_FS; } char *vfs_inode = (char *)BPF_CORE_READ(dentry, d_inode); - // We need to compute the size of the inode struct at load time since it can change between kernel versions + // We need to compute the size of the inode struct at load time since it can change between + // kernel versions unsigned long inode_size = bpf_core_type_size(struct inode); - if(!inode_size) - { + if(!inode_size) { return PPM_OVERLAY_LOWER; } struct dentry *upper_dentry = NULL; bpf_probe_read_kernel(&upper_dentry, sizeof(upper_dentry), (char *)vfs_inode + inode_size); - if(!upper_dentry) - { + if(!upper_dentry) { return PPM_OVERLAY_LOWER; } - if (BPF_CORE_READ(upper_dentry, d_inode, i_ino) != 0) - { + if(BPF_CORE_READ(upper_dentry, d_inode, i_ino) != 0) { return PPM_OVERLAY_UPPER; } return PPM_OVERLAY_LOWER; @@ -850,30 +781,25 @@ static __always_inline enum ppm_overlay extract__overlay_layer(struct file *file * inode object and other file attributes. * **/ -static __always_inline bool extract__exe_from_memfd(struct file *file) -{ +static __always_inline bool extract__exe_from_memfd(struct file *file) { struct dentry *dentry = BPF_CORE_READ(file, f_path.dentry); - if(!dentry) - { + if(!dentry) { bpf_printk("extract__exe_from_memfd(): failed to get dentry"); return false; } struct dentry *parent = BPF_CORE_READ(dentry, d_parent); - if(!parent) - { + if(!parent) { bpf_printk("extract__exe_from_memfd(): failed to get parent"); return false; } - if(parent != dentry) - { + if(parent != dentry) { return false; } const unsigned char *name = BPF_CORE_READ(dentry, d_name.name); - if(!name) - { + if(!name) { bpf_printk("extract__exe_from_memfd(): failed to get name"); return false; } @@ -881,15 +807,12 @@ static __always_inline bool extract__exe_from_memfd(struct file *file) const char expected_prefix[] = "memfd:"; char memfd_name[sizeof(expected_prefix)] = {'\0'}; - if(bpf_probe_read_kernel_str(memfd_name, sizeof(memfd_name), name) != sizeof(expected_prefix)) - { + if(bpf_probe_read_kernel_str(memfd_name, sizeof(memfd_name), name) != sizeof(expected_prefix)) { return false; } - for(int i = 0; i < sizeof(expected_prefix); i++) - { - if(expected_prefix[i] != memfd_name[i]) - { + for(int i = 0; i < sizeof(expected_prefix); i++) { + if(expected_prefix[i] != memfd_name[i]) { return false; } } @@ -905,11 +828,12 @@ static __always_inline bool extract__exe_from_memfd(struct file *file) * @param ino pointer to the inode number we have to fill. * @param ol pointer to the overlay layer we have to fill. */ -static __always_inline void extract__dev_ino_overlay_from_fd(int32_t fd, dev_t *dev, uint64_t *ino, enum ppm_overlay *ol) -{ +static __always_inline void extract__dev_ino_overlay_from_fd(int32_t fd, + dev_t *dev, + uint64_t *ino, + enum ppm_overlay *ol) { struct file *f = extract__file_struct_from_fd(fd); - if(!f) - { + if(!f) { return; } @@ -928,50 +852,41 @@ static __always_inline void extract__dev_ino_overlay_from_fd(int32_t fd, dev_t * #define UID_GID_MAP_MAX_BASE_EXTENTS 5 /* UP means get NS id (uid/gid) from kuid/kgid */ -static __always_inline uint32_t bpf_map_id_up(struct uid_gid_map *map, uint32_t id) -{ +static __always_inline uint32_t bpf_map_id_up(struct uid_gid_map *map, uint32_t id) { uint32_t first = 0; uint32_t last = 0; uint32_t nr_extents = BPF_CORE_READ(map, nr_extents); struct uid_gid_extent *extent = NULL; - for(int j = 0; j < UID_GID_MAP_MAX_BASE_EXTENTS; j++) - { - if(j >= nr_extents) - { + for(int j = 0; j < UID_GID_MAP_MAX_BASE_EXTENTS; j++) { + if(j >= nr_extents) { break; } first = BPF_CORE_READ(map, extent[j].lower_first); last = first + BPF_CORE_READ(map, extent[j].count) - 1; - if(id >= first && id <= last) - { + if(id >= first && id <= last) { extent = &map->extent[j]; break; } } /* Map the id or note failure */ - if(extent) - { + if(extent) { uint32_t first = BPF_CORE_READ(extent, first); uint32_t lower_first = BPF_CORE_READ(extent, lower_first); id = id - lower_first + first; - } - else - { + } else { id = (uint32_t)-1; } return id; } -static __always_inline bool groups_search(struct task_struct *task, uint32_t grp) -{ +static __always_inline bool groups_search(struct task_struct *task, uint32_t grp) { struct group_info *group_info = NULL; READ_TASK_FIELD_INTO(&group_info, task, cred, group_info); - if(!group_info) - { + if(!group_info) { return false; } @@ -980,26 +895,19 @@ static __always_inline bool groups_search(struct task_struct *task, uint32_t grp unsigned int mid = 0; uint32_t grp_mid = 0; - for(int j = 0; j < MAX_GROUP_SEARCH_DEPTH; j++) - { - if(left >= right) - { + for(int j = 0; j < MAX_GROUP_SEARCH_DEPTH; j++) { + if(left >= right) { break; } mid = (left + right) / 2; BPF_CORE_READ_INTO(&grp_mid, group_info, gid[mid].val); - if(grp > grp_mid) - { + if(grp > grp_mid) { left = mid + 1; - } - else if(grp < grp_mid) - { + } else if(grp < grp_mid) { right = mid; - } - else - { + } else { return true; } } @@ -1007,20 +915,17 @@ static __always_inline bool groups_search(struct task_struct *task, uint32_t grp return false; } -static __always_inline bool extract__exe_writable(struct task_struct *task, struct inode *inode) -{ +static __always_inline bool extract__exe_writable(struct task_struct *task, struct inode *inode) { umode_t i_mode = BPF_CORE_READ(inode, i_mode); uint32_t i_flags = BPF_CORE_READ(inode, i_flags); long unsigned int s_flags = BPF_CORE_READ(inode, i_sb, s_flags); /* Check superblock permissions, i.e. if the FS is read only */ - if((s_flags & SB_RDONLY) && (S_ISREG(i_mode) || S_ISDIR(i_mode) || S_ISLNK(i_mode))) - { + if((s_flags & SB_RDONLY) && (S_ISREG(i_mode) || S_ISDIR(i_mode) || S_ISLNK(i_mode))) { return false; } - if(i_flags & S_IMMUTABLE) - { + if(i_flags & S_IMMUTABLE) { return false; } @@ -1033,19 +938,17 @@ static __always_inline bool extract__exe_writable(struct task_struct *task, stru READ_TASK_FIELD_INTO(&fsgid, task, cred, fsgid.val); /* HAS_UNMAPPED_ID() */ - if(i_uid == -1 || i_gid == -1) - { + if(i_uid == -1 || i_gid == -1) { return false; } /* inode_owner_or_capable check. If the owner matches the exe counts as writable */ - if(fsuid == i_uid) - { + if(fsuid == i_uid) { return true; } - // Basic file permission check -- this may not work in all cases as kernel functions are more complex - // and take into account different types of ACLs which can use custom function pointers, + // Basic file permission check -- this may not work in all cases as kernel functions are more + // complex and take into account different types of ACLs which can use custom function pointers, // but I don't think we can inspect those in eBPF // basic acl_permission_check() @@ -1054,38 +957,29 @@ static __always_inline bool extract__exe_writable(struct task_struct *task, stru umode_t mode = i_mode; - if(i_uid == fsuid) - { + if(i_uid == fsuid) { mode >>= 6; - } - else - { + } else { bool in_group = false; - if(i_gid == fsgid) - { + if(i_gid == fsgid) { in_group = true; - } - else - { + } else { in_group = groups_search(task, i_gid); } - if(in_group) - { + if(in_group) { mode >>= 3; } } - if((MAY_WRITE & ~mode) == 0) - { + if((MAY_WRITE & ~mode) == 0) { return true; } struct user_namespace *ns; READ_TASK_FIELD_INTO(&ns, task, cred, user_ns); - if(ns == NULL) - { + if(ns == NULL) { return false; } bool kuid_mapped = bpf_map_id_up(&ns->uid_map, i_uid) != (uint32_t)-1; @@ -1095,30 +989,25 @@ static __always_inline bool extract__exe_writable(struct task_struct *task, stru READ_TASK_FIELD_INTO(&cap_struct, task, cred, cap_effective); // Kernel 6.3 changed the kernel_cap_struct type from uint32_t[2] to uint64_t. // Luckily enough, it also changed field name from cap to val. - if(bpf_core_field_exists(((struct kernel_cap_struct *)0)->cap)) - { - if(cap_raised(cap_struct, CAP_DAC_OVERRIDE) && kuid_mapped && kgid_mapped) - { + if(bpf_core_field_exists(((struct kernel_cap_struct *)0)->cap)) { + if(cap_raised(cap_struct, CAP_DAC_OVERRIDE) && kuid_mapped && kgid_mapped) { return true; } - /* Check if the user is capable. Even if it doesn't own the file or the read bits are not set, root with CAP_FOWNER can do what it wants. */ - if(cap_raised(cap_struct, CAP_FOWNER) && kuid_mapped) - { + /* Check if the user is capable. Even if it doesn't own the file or the read bits are not + * set, root with CAP_FOWNER can do what it wants. */ + if(cap_raised(cap_struct, CAP_FOWNER) && kuid_mapped) { return true; } - } - else - { + } else { kernel_cap_t___v6_3 *new_cap = (kernel_cap_t___v6_3 *)&cap_struct; - if(cap_raised___v6_3(*new_cap, CAP_DAC_OVERRIDE) && kuid_mapped && kgid_mapped) - { + if(cap_raised___v6_3(*new_cap, CAP_DAC_OVERRIDE) && kuid_mapped && kgid_mapped) { return true; } - /* Check if the user is capable. Even if it doesn't own the file or the read bits are not set, root with CAP_FOWNER can do what it wants. */ - if(cap_raised___v6_3(*new_cap, CAP_FOWNER) && kuid_mapped) - { + /* Check if the user is capable. Even if it doesn't own the file or the read bits are not + * set, root with CAP_FOWNER can do what it wants. */ + if(cap_raised___v6_3(*new_cap, CAP_FOWNER) && kuid_mapped) { return true; } } @@ -1130,18 +1019,15 @@ static __always_inline bool extract__exe_writable(struct task_struct *task, stru * @brief Return a socket pointer from a file pointer. * @param file pointer to the file struct. */ -static __always_inline struct socket* get_sock_from_file(struct file *file) -{ - if(file == NULL) - { +static __always_inline struct socket *get_sock_from_file(struct file *file) { + if(file == NULL) { return NULL; } struct file_operations *fop = (struct file_operations *)BPF_CORE_READ(file, f_op); - if(fop != maps__get_socket_file_ops()) - { + if(fop != maps__get_socket_file_ops()) { // We are not a socket. return NULL; } - return (struct socket*)BPF_CORE_READ(file, private_data); + return (struct socket *)BPF_CORE_READ(file, private_data); } diff --git a/driver/modern_bpf/helpers/interfaces/attached_programs.h b/driver/modern_bpf/helpers/interfaces/attached_programs.h index 2fc632ecc4..cde3053481 100644 --- a/driver/modern_bpf/helpers/interfaces/attached_programs.h +++ b/driver/modern_bpf/helpers/interfaces/attached_programs.h @@ -11,8 +11,7 @@ #include /* This enum is used to tell if we are considering a syscall or a tracepoint */ -enum intrumentation_type -{ +enum intrumentation_type { MODERN_BPF_SYSCALL = 0, MODERN_BPF_TRACEPOINT = 1, }; @@ -21,14 +20,12 @@ enum intrumentation_type * We treat the syscalls tracepoints in a dedicated way because they could generate * more than one event (1 for each syscall) for this reason we need a dedicated table. */ -static __always_inline bool sampling_logic(void* ctx, uint32_t id, enum intrumentation_type type) -{ +static __always_inline bool sampling_logic(void* ctx, uint32_t id, enum intrumentation_type type) { /* If dropping mode is not enabled we don't perform any sampling * false: means don't drop the syscall * true: means drop the syscall */ - if(!maps__get_dropping_mode()) - { + if(!maps__get_dropping_mode()) { return false; } @@ -37,33 +34,26 @@ static __always_inline bool sampling_logic(void* ctx, uint32_t id, enum intrumen /* If we have a syscall we use the sampling_syscall_table otherwise * with tracepoints we use the sampling_tracepoint_table. */ - if(type == MODERN_BPF_SYSCALL) - { + if(type == MODERN_BPF_SYSCALL) { sampling_flag = maps__64bit_sampling_syscall_table(id); - } - else - { + } else { sampling_flag = maps__64bit_sampling_tracepoint_table(id); } - if(sampling_flag == UF_NEVER_DROP) - { + if(sampling_flag == UF_NEVER_DROP) { return false; } - if(sampling_flag == UF_ALWAYS_DROP) - { + if(sampling_flag == UF_ALWAYS_DROP) { return true; } - if((bpf_ktime_get_boot_ns() % SECOND_TO_NS) >= (SECOND_TO_NS / maps__get_sampling_ratio())) - { + if((bpf_ktime_get_boot_ns() % SECOND_TO_NS) >= (SECOND_TO_NS / maps__get_sampling_ratio())) { /* If we are starting the dropping phase we need to notify the userspace, otherwise, we * simply drop our event. * PLEASE NOTE: this logic is not per-CPU so it is best effort! */ - if(!maps__get_is_dropping()) - { + if(!maps__get_is_dropping()) { /* Here we are not sure we can send the drop_e event to userspace * if the buffer is full, but this is not essential even if we lose * an iteration we will synchronize again the next time the logic is enabled. @@ -75,8 +65,7 @@ static __always_inline bool sampling_logic(void* ctx, uint32_t id, enum intrumen return true; } - if(maps__get_is_dropping()) - { + if(maps__get_is_dropping()) { maps__set_is_dropping(false); bpf_tail_call(ctx, &extra_event_prog_tail_table, T1_DROP_X); bpf_printk("unable to tail call into 'drop_x' prog"); diff --git a/driver/modern_bpf/helpers/interfaces/syscalls_dispatcher.h b/driver/modern_bpf/helpers/interfaces/syscalls_dispatcher.h index 04d35a257c..c0c1e62b2b 100644 --- a/driver/modern_bpf/helpers/interfaces/syscalls_dispatcher.h +++ b/driver/modern_bpf/helpers/interfaces/syscalls_dispatcher.h @@ -13,17 +13,14 @@ #include #include -static __always_inline bool syscalls_dispatcher__64bit_interesting_syscall(uint32_t syscall_id) -{ +static __always_inline bool syscalls_dispatcher__64bit_interesting_syscall(uint32_t syscall_id) { return maps__64bit_interesting_syscall(syscall_id); } -static __always_inline long convert_network_syscalls(struct pt_regs *regs) -{ +static __always_inline long convert_network_syscalls(struct pt_regs *regs) { int socketcall_id = (int)extract__syscall_argument(regs, 0); - switch(socketcall_id) - { + switch(socketcall_id) { #ifdef __NR_socket case SYS_SOCKET: return __NR_socket; @@ -147,10 +144,10 @@ static __always_inline long convert_network_syscalls(struct pt_regs *regs) * ----- x86 with CONFIG_IA32_EMULATION * - `SYS_ACCEPT` is defined but `__NR_accept` is not defined * -> In this case we return a `__NR_accept` - * + * * - `SYS_SEND` is defined but `__NR_send` is not defined * -> In this case we drop the event - * + * * - `SYS_RECV` is defined but `__NR_recv` is not defined * -> In this case we drop the event */ diff --git a/driver/modern_bpf/helpers/store/auxmap_store_params.h b/driver/modern_bpf/helpers/store/auxmap_store_params.h index bfb510c0a1..5887b63d04 100644 --- a/driver/modern_bpf/helpers/store/auxmap_store_params.h +++ b/driver/modern_bpf/helpers/store/auxmap_store_params.h @@ -28,7 +28,8 @@ * { * uint8_t data[AUXILIARY_MAP_SIZE]; // raw space to save our variable-size event. * uint64_t payload_pos; // position of the first empty byte in the `data` buf. - * uint8_t lengths_pos; // position the first empty slot into the lengths array of the event. + * uint8_t lengths_pos; // position the first empty slot into the lengths array of the + *event. * }; * * To better understand the two indexes `payload_pos` and `lengths_pos` @@ -63,8 +64,7 @@ * * @return pointer to the auxmap */ -static __always_inline struct auxiliary_map *auxmap__get() -{ +static __always_inline struct auxiliary_map *auxmap__get() { return maps__get_auxiliary_map(); } @@ -84,8 +84,8 @@ static __always_inline struct auxiliary_map *auxmap__get() * @param auxmap pointer to the auxmap in which we are writing our event header. * @param event_type This is the type of the event that we are writing into the map. */ -static __always_inline void auxmap__preload_event_header(struct auxiliary_map *auxmap, uint16_t event_type) -{ +static __always_inline void auxmap__preload_event_header(struct auxiliary_map *auxmap, + uint16_t event_type) { struct ppm_evt_hdr *hdr = (struct ppm_evt_hdr *)auxmap->data; uint8_t nparams = maps__get_event_num_params(event_type); hdr->ts = maps__get_boot_time() + bpf_ktime_get_boot_ns(); @@ -102,8 +102,7 @@ static __always_inline void auxmap__preload_event_header(struct auxiliary_map *a * * @param auxmap pointer to the auxmap in which we are writing our event header. */ -static __always_inline void auxmap__finalize_event_header(struct auxiliary_map *auxmap) -{ +static __always_inline void auxmap__finalize_event_header(struct auxiliary_map *auxmap) { struct ppm_evt_hdr *hdr = (struct ppm_evt_hdr *)auxmap->data; hdr->len = auxmap->payload_pos; } @@ -120,27 +119,24 @@ static __always_inline void auxmap__finalize_event_header(struct auxiliary_map * * @param auxmap pointer to the auxmap in which we have already written the entire event. * @param ctx BPF prog context */ -static __always_inline void auxmap__submit_event(struct auxiliary_map *auxmap, void* ctx) -{ +static __always_inline void auxmap__submit_event(struct auxiliary_map *auxmap, void *ctx) { struct ringbuf_map *rb = maps__get_ringbuf_map(); - if(!rb) - { + if(!rb) { bpf_tail_call(ctx, &extra_event_prog_tail_table, T1_HOTPLUG_E); bpf_printk("failed to tail call into the 'hotplug' prog"); return; } struct counter_map *counter = maps__get_counter_map(); - if(!counter) - { + if(!counter) { return; } - /* This counts the event seen by the drivers even if they are dropped because the buffer is full. */ + /* This counts the event seen by the drivers even if they are dropped because the buffer is + * full. */ counter->n_evts++; - if(auxmap->payload_pos > MAX_EVENT_SIZE) - { + if(auxmap->payload_pos > MAX_EVENT_SIZE) { counter->n_drops_max_event_size++; return; } @@ -149,8 +145,7 @@ static __always_inline void auxmap__submit_event(struct auxiliary_map *auxmap, v * when a new event is in the buffer. */ int err = bpf_ringbuf_output(rb, auxmap->data, auxmap->payload_pos, BPF_RB_NO_WAKEUP); - if(err) - { + if(err) { counter->n_drops_buffer++; compute_event_types_stats(auxmap->event_type, counter); } @@ -177,8 +172,7 @@ static __always_inline void auxmap__submit_event(struct auxiliary_map *auxmap, v * * @param auxmap pointer to the auxmap in which we are storing the param. */ -static __always_inline void auxmap__store_empty_param(struct auxiliary_map *auxmap) -{ +static __always_inline void auxmap__store_empty_param(struct auxiliary_map *auxmap) { push__param_len(auxmap->data, &auxmap->lengths_pos, 0); } @@ -190,8 +184,7 @@ static __always_inline void auxmap__store_empty_param(struct auxiliary_map *auxm * @param auxmap pointer to the auxmap in which we are storing the param. * @param param param to store */ -static __always_inline void auxmap__store_s32_param(struct auxiliary_map *auxmap, int32_t param) -{ +static __always_inline void auxmap__store_s32_param(struct auxiliary_map *auxmap, int32_t param) { push__s32(auxmap->data, &auxmap->payload_pos, param); push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(int32_t)); } @@ -206,8 +199,7 @@ static __always_inline void auxmap__store_s32_param(struct auxiliary_map *auxmap * @param auxmap pointer to the auxmap in which we are storing the param. * @param param param to store */ -static __always_inline void auxmap__store_s64_param(struct auxiliary_map *auxmap, int64_t param) -{ +static __always_inline void auxmap__store_s64_param(struct auxiliary_map *auxmap, int64_t param) { push__s64(auxmap->data, &auxmap->payload_pos, param); push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(int64_t)); } @@ -223,8 +215,7 @@ static __always_inline void auxmap__store_s64_param(struct auxiliary_map *auxmap * @param auxmap pointer to the auxmap in which we are storing the param. * @param param param to store */ -static __always_inline void auxmap__store_u8_param(struct auxiliary_map *auxmap, uint8_t param) -{ +static __always_inline void auxmap__store_u8_param(struct auxiliary_map *auxmap, uint8_t param) { push__u8(auxmap->data, &auxmap->payload_pos, param); push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(uint8_t)); } @@ -237,8 +228,7 @@ static __always_inline void auxmap__store_u8_param(struct auxiliary_map *auxmap, * @param auxmap pointer to the auxmap in which we are storing the param. * @param param param to store */ -static __always_inline void auxmap__store_u16_param(struct auxiliary_map *auxmap, uint16_t param) -{ +static __always_inline void auxmap__store_u16_param(struct auxiliary_map *auxmap, uint16_t param) { push__u16(auxmap->data, &auxmap->payload_pos, param); push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(uint16_t)); } @@ -257,8 +247,7 @@ static __always_inline void auxmap__store_u16_param(struct auxiliary_map *auxmap * @param auxmap pointer to the auxmap in which we are storing the param. * @param param param to store */ -static __always_inline void auxmap__store_u32_param(struct auxiliary_map *auxmap, uint32_t param) -{ +static __always_inline void auxmap__store_u32_param(struct auxiliary_map *auxmap, uint32_t param) { push__u32(auxmap->data, &auxmap->payload_pos, param); push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(uint32_t)); } @@ -273,8 +262,7 @@ static __always_inline void auxmap__store_u32_param(struct auxiliary_map *auxmap * @param auxmap pointer to the auxmap in which we are storing the param. * @param param param to store */ -static __always_inline void auxmap__store_u64_param(struct auxiliary_map *auxmap, uint64_t param) -{ +static __always_inline void auxmap__store_u64_param(struct auxiliary_map *auxmap, uint64_t param) { push__u64(auxmap->data, &auxmap->payload_pos, param); push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(uint64_t)); } @@ -292,15 +280,20 @@ static __always_inline void auxmap__store_u64_param(struct auxiliary_map *auxmap * @param mem from which memory we need to read: user-space or kernel-space. * @return number of bytes read. */ -static __always_inline uint16_t auxmap__store_charbuf_param(struct auxiliary_map *auxmap, unsigned long charbuf_pointer, uint16_t len_to_read, enum read_memory mem) -{ +static __always_inline uint16_t auxmap__store_charbuf_param(struct auxiliary_map *auxmap, + unsigned long charbuf_pointer, + uint16_t len_to_read, + enum read_memory mem) { uint16_t charbuf_len = 0; /* This check is just for performance reasons. Is useless to check * `len_to_read > 0` here, since `len_to_read` is just the upper bound. */ - if(charbuf_pointer) - { - charbuf_len = push__charbuf(auxmap->data, &auxmap->payload_pos, charbuf_pointer, len_to_read, mem); + if(charbuf_pointer) { + charbuf_len = push__charbuf(auxmap->data, + &auxmap->payload_pos, + charbuf_pointer, + len_to_read, + mem); } /* If we are not able to push anything with `push__charbuf` * `charbuf_len` will be equal to `0` so we will send an @@ -322,13 +315,18 @@ static __always_inline uint16_t auxmap__store_charbuf_param(struct auxiliary_map * @param mem from which memory we need to read: user-space or kernel-space. * @return number of bytes read. */ -static __always_inline uint16_t auxmap__store_bytebuf_param(struct auxiliary_map *auxmap, unsigned long bytebuf_pointer, uint16_t len_to_read, enum read_memory mem) -{ +static __always_inline uint16_t auxmap__store_bytebuf_param(struct auxiliary_map *auxmap, + unsigned long bytebuf_pointer, + uint16_t len_to_read, + enum read_memory mem) { uint16_t bytebuf_len = 0; /* This check is just for performance reasons. */ - if(bytebuf_pointer && len_to_read > 0) - { - bytebuf_len = push__bytebuf(auxmap->data, &auxmap->payload_pos, bytebuf_pointer, len_to_read, mem); + if(bytebuf_pointer && len_to_read > 0) { + bytebuf_len = push__bytebuf(auxmap->data, + &auxmap->payload_pos, + bytebuf_pointer, + len_to_read, + mem); } /* If we are not able to push anything with `push__bytebuf` * `bytebuf_len` will be equal to `0` so we will send an @@ -346,25 +344,25 @@ static __always_inline uint16_t auxmap__store_bytebuf_param(struct auxiliary_map * @param len_to_read len that we can ideally read. * @param max_len max len that we can read. */ -static __always_inline void auxmap__store_charbufarray_as_bytebuf(struct auxiliary_map *auxmap, unsigned long start_pointer, uint16_t len_to_read, uint16_t max_len) -{ - /* Here we read an array of charbufs starting from a pointer. +static __always_inline void auxmap__store_charbufarray_as_bytebuf(struct auxiliary_map *auxmap, + unsigned long start_pointer, + uint16_t len_to_read, + uint16_t max_len) { + /* Here we read an array of charbufs starting from a pointer. * We could also read the array element per element but * since we know the total len we read it as a `bytebuf`. * Since this is an array of charbufs the `\0` after every argument are preserved. * We just need to add a final `\0` in case we args are too long and we have a partial - * read. + * read. */ - if(len_to_read >= max_len) - { + if(len_to_read >= max_len) { len_to_read = max_len; } /* if `auxmap__store_bytebuf_param` returns 0 we will send an empty param. * we don't need the final `\0`. */ - if(auxmap__store_bytebuf_param(auxmap, start_pointer, len_to_read, USER) > 0) - { + if(auxmap__store_bytebuf_param(auxmap, start_pointer, len_to_read, USER) > 0) { // maybe we read only part of the last argument so we need to put a `\0` at the end. push__previous_character(auxmap->data, &auxmap->payload_pos, '\0'); } @@ -377,15 +375,15 @@ static __always_inline void auxmap__store_charbufarray_as_bytebuf(struct auxilia * @param auxmap pointer to the auxmap in which we are storing the param. * @param charbuf pointer array, obtained directly from the syscall (`argv`). */ -static __always_inline void auxmap__store_exe_args_failure(struct auxiliary_map *auxmap, char **array) -{ +static __always_inline void auxmap__store_exe_args_failure(struct auxiliary_map *auxmap, + char **array) { unsigned long charbuf_pointer = 0; uint16_t exe_len = 0; - if(array == NULL) - { + if(array == NULL) { /* We need to store both the exe and the args. - * To be compliant with other drivers we send an empty string as exe not a param with len==0. + * To be compliant with other drivers we send an empty string as exe not a param with + * len==0. */ push__new_character(auxmap->data, &auxmap->payload_pos, '\0'); push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(char)); @@ -395,48 +393,48 @@ static __always_inline void auxmap__store_exe_args_failure(struct auxiliary_map } /* Here we read the pointer to `exe` and we store it */ - if(bpf_probe_read_user(&charbuf_pointer, sizeof(charbuf_pointer), &array[0])) - { + if(bpf_probe_read_user(&charbuf_pointer, sizeof(charbuf_pointer), &array[0])) { /* we cannot read the pointer so `exe` will be `0` */ push__param_len(auxmap->data, &auxmap->lengths_pos, 0); - } - else - { + } else { /* we push the `exe` as a separate arg. */ - exe_len = push__charbuf(auxmap->data, &auxmap->payload_pos, charbuf_pointer, MAX_PROC_EXE, USER); + exe_len = push__charbuf(auxmap->data, + &auxmap->payload_pos, + charbuf_pointer, + MAX_PROC_EXE, + USER); push__param_len(auxmap->data, &auxmap->lengths_pos, exe_len); } - + /* Here we read the pointers to `args` and we store it. * `payload_pos` points after `exe` */ uint64_t initial_payload_pos = auxmap->payload_pos; uint16_t args_len = 0; /* Index 1 because we skip the `exe` */ - for(uint8_t index = 1; index < MAX_CHARBUF_POINTERS; ++index) - { - if(bpf_probe_read_user(&charbuf_pointer, sizeof(charbuf_pointer), &array[index])) - { + for(uint8_t index = 1; index < MAX_CHARBUF_POINTERS; ++index) { + if(bpf_probe_read_user(&charbuf_pointer, sizeof(charbuf_pointer), &array[index])) { break; } - if(!charbuf_pointer) - { + if(!charbuf_pointer) { break; } - args_len += push__charbuf(auxmap->data, &auxmap->payload_pos, charbuf_pointer, MAX_PROC_ARG_ENV, USER); + args_len += push__charbuf(auxmap->data, + &auxmap->payload_pos, + charbuf_pointer, + MAX_PROC_ARG_ENV, + USER); /* the sum of `exe` + `args` should be `<= MAX_PROC_ARG_ENV` */ - if(args_len + exe_len >= MAX_PROC_ARG_ENV) - { + if(args_len + exe_len >= MAX_PROC_ARG_ENV) { args_len = MAX_PROC_ARG_ENV - exe_len; break; } } - if(args_len > 0) - { + if(args_len > 0) { auxmap->payload_pos = initial_payload_pos + args_len; push__previous_character(auxmap->data, &auxmap->payload_pos, '\0'); } @@ -457,37 +455,35 @@ static __always_inline void auxmap__store_exe_args_failure(struct auxiliary_map * @param auxmap pointer to the auxmap in which we are storing the param. * @param array charbuf pointer array, obtained directly from the syscall (`argv` or `envp`). */ -static __always_inline void auxmap__store_env_failure(struct auxiliary_map *auxmap, char **array) -{ +static __always_inline void auxmap__store_env_failure(struct auxiliary_map *auxmap, char **array) { unsigned long charbuf_pointer = 0; uint16_t arg_len = 0; uint16_t total_len = 0; uint64_t initial_payload_pos = auxmap->payload_pos; - if(array == NULL) - { + if(array == NULL) { auxmap__store_empty_param(auxmap); return; } - for(uint8_t index = 0; index < MAX_CHARBUF_POINTERS; ++index) - { - if(bpf_probe_read_user(&charbuf_pointer, sizeof(charbuf_pointer), &array[index])) - { + for(uint8_t index = 0; index < MAX_CHARBUF_POINTERS; ++index) { + if(bpf_probe_read_user(&charbuf_pointer, sizeof(charbuf_pointer), &array[index])) { break; } - if(!charbuf_pointer) - { + if(!charbuf_pointer) { break; } - arg_len = push__charbuf(auxmap->data, &auxmap->payload_pos, charbuf_pointer, MAX_PROC_ARG_ENV, USER); + arg_len = push__charbuf(auxmap->data, + &auxmap->payload_pos, + charbuf_pointer, + MAX_PROC_ARG_ENV, + USER); total_len += arg_len; /* the sum of all env variables lengths should be `<= MAX_PROC_ARG_ENV` */ - if(total_len >= MAX_PROC_ARG_ENV) - { + if(total_len >= MAX_PROC_ARG_ENV) { total_len = MAX_PROC_ARG_ENV; break; } @@ -509,8 +505,9 @@ static __always_inline void auxmap__store_env_failure(struct auxiliary_map *auxm * @param sockaddr_pointer pointer to the sockaddr struct * @param addrlen overall length of the sockaddr struct */ -static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *auxmap, unsigned long sockaddr_pointer, uint16_t addrlen) -{ +static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *auxmap, + unsigned long sockaddr_pointer, + uint16_t addrlen) { uint16_t final_param_len = 0; /* We put the struct sockaddr in our auxmap, since we have to write other @@ -541,8 +538,10 @@ static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *a */ /* If we are not able to save the sockaddr return an empty parameter. */ - if(bpf_probe_read_user((void *)&auxmap->data[MAX_PARAM_SIZE], SAFE_ACCESS(addrlen), (void *)sockaddr_pointer) || addrlen == 0) - { + if(bpf_probe_read_user((void *)&auxmap->data[MAX_PARAM_SIZE], + SAFE_ACCESS(addrlen), + (void *)sockaddr_pointer) || + addrlen == 0) { push__param_len(auxmap->data, &auxmap->lengths_pos, 0); return; } @@ -551,10 +550,8 @@ static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *a struct sockaddr *sockaddr = (struct sockaddr *)&auxmap->data[MAX_PARAM_SIZE]; uint16_t socket_family = sockaddr->sa_family; - switch(socket_family) - { - case AF_INET: - { + switch(socket_family) { + case AF_INET: { /* Map the user-provided address to a sockaddr_in. */ struct sockaddr_in *sockaddr_in = (struct sockaddr_in *)sockaddr; @@ -574,8 +571,7 @@ static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *a break; } - case AF_INET6: - { + case AF_INET6: { /* Map the user-provided address to a sockaddr_in6. */ struct sockaddr_in6 *sockaddr_in6 = (struct sockaddr_in6 *)sockaddr; @@ -596,8 +592,7 @@ static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *a break; } - case AF_UNIX: - { + case AF_UNIX: { /* Map the user-provided address to a sockaddr_un. */ struct sockaddr_un *sockaddr_un = (struct sockaddr_un *)sockaddr; @@ -616,13 +611,10 @@ static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *a unsigned long start_reading_point; /* We skip the two bytes of socket family. */ char first_path_byte = *(char *)sockaddr_un->sun_path; - if(first_path_byte == '\0') - { + if(first_path_byte == '\0') { /* This is an abstract socket address, we need to skip the initial `\0`. */ start_reading_point = (unsigned long)sockaddr_un->sun_path + 1; - } - else - { + } else { start_reading_point = (unsigned long)sockaddr_un->sun_path; } @@ -631,7 +623,11 @@ static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *a * - socket_unix_path (sun_path). */ push__u8(auxmap->data, &auxmap->payload_pos, socket_family_to_scap(socket_family)); - uint16_t written_bytes = push__charbuf(auxmap->data, &auxmap->payload_pos, start_reading_point, MAX_UNIX_SOCKET_PATH, KERNEL); + uint16_t written_bytes = push__charbuf(auxmap->data, + &auxmap->payload_pos, + start_reading_point, + MAX_UNIX_SOCKET_PATH, + KERNEL); final_param_len = FAMILY_SIZE + written_bytes; break; } @@ -657,32 +653,29 @@ static __always_inline void auxmap__store_sockaddr_param(struct auxiliary_map *a * @param direction specifies the connection direction. * @param usrsockaddr pointer to user provided sock address. */ -static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map *auxmap, uint32_t socket_fd, int direction, struct sockaddr *usrsockaddr) -{ +static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map *auxmap, + uint32_t socket_fd, + int direction, + struct sockaddr *usrsockaddr) { uint16_t final_param_len = 0; /* Get the socket family directly from the socket */ uint16_t socket_family = 0; struct file *file = extract__file_struct_from_fd(socket_fd); struct socket *socket = get_sock_from_file(file); - if(socket == NULL) - { + if(socket == NULL) { auxmap__store_empty_param(auxmap); return; } struct sock *sk = BPF_CORE_READ(socket, sk); - if(sk == NULL) - { + if(sk == NULL) { auxmap__store_empty_param(auxmap); return; } BPF_CORE_READ_INTO(&socket_family, sk, __sk_common.skc_family); - switch(socket_family) - { - case AF_INET: - { - + switch(socket_family) { + case AF_INET: { struct inet_sock *inet = (struct inet_sock *)sk; uint32_t ipv4_local = 0; @@ -694,12 +687,14 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * BPF_CORE_READ_INTO(&ipv4_remote, sk, __sk_common.skc_daddr); BPF_CORE_READ_INTO(&port_remote, sk, __sk_common.skc_dport); - /* Kernel doesn't always fill sk->__sk_common in sendto and sendmsg syscalls (as in the case of an UDP connection). - * We fallback to the address from userspace when the kernel-provided address is NULL */ - if (port_remote == 0 && usrsockaddr != NULL) - { + /* Kernel doesn't always fill sk->__sk_common in sendto and sendmsg syscalls (as in the case + * of an UDP connection). We fallback to the address from userspace when the kernel-provided + * address is NULL */ + if(port_remote == 0 && usrsockaddr != NULL) { struct sockaddr_in usrsockaddr_in = {}; - bpf_probe_read_user(&usrsockaddr_in, bpf_core_type_size(struct sockaddr_in), (void *)usrsockaddr); + bpf_probe_read_user(&usrsockaddr_in, + bpf_core_type_size(struct sockaddr_in), + (void *)usrsockaddr); ipv4_remote = usrsockaddr_in.sin_addr.s_addr; port_remote = usrsockaddr_in.sin_port; } @@ -713,15 +708,12 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * */ push__u8(auxmap->data, &auxmap->payload_pos, socket_family_to_scap(socket_family)); - if(direction == OUTBOUND) - { + if(direction == OUTBOUND) { push__u32(auxmap->data, &auxmap->payload_pos, ipv4_local); push__u16(auxmap->data, &auxmap->payload_pos, ntohs(port_local)); push__u32(auxmap->data, &auxmap->payload_pos, ipv4_remote); push__u16(auxmap->data, &auxmap->payload_pos, ntohs(port_remote)); - } - else - { + } else { push__u32(auxmap->data, &auxmap->payload_pos, ipv4_remote); push__u16(auxmap->data, &auxmap->payload_pos, ntohs(port_remote)); push__u32(auxmap->data, &auxmap->payload_pos, ipv4_local); @@ -732,8 +724,7 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * break; } - case AF_INET6: - { + case AF_INET6: { struct inet_sock *inet = (struct inet_sock *)sk; uint32_t ipv6_local[4] = {0, 0, 0, 0}; @@ -746,16 +737,20 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * BPF_CORE_READ_INTO(&ipv6_remote, sk, __sk_common.skc_v6_daddr); BPF_CORE_READ_INTO(&port_remote, sk, __sk_common.skc_dport); - /* Kernel doesn't always fill sk->__sk_common in sendto and sendmsg syscalls (as in the case of an UDP connection). - * We fallback to the address from userspace when the kernel-provided address is NULL */ - if (port_remote == 0 && usrsockaddr != NULL) - { + /* Kernel doesn't always fill sk->__sk_common in sendto and sendmsg syscalls (as in the case + * of an UDP connection). We fallback to the address from userspace when the kernel-provided + * address is NULL */ + if(port_remote == 0 && usrsockaddr != NULL) { struct sockaddr_in6 usrsockaddr_in6 = {}; - bpf_probe_read_user(&usrsockaddr_in6, bpf_core_type_size(struct sockaddr_in6), (void *)usrsockaddr); - bpf_probe_read_kernel(&ipv6_remote, sizeof(uint32_t)*4, usrsockaddr_in6.sin6_addr.in6_u.u6_addr32); + bpf_probe_read_user(&usrsockaddr_in6, + bpf_core_type_size(struct sockaddr_in6), + (void *)usrsockaddr); + bpf_probe_read_kernel(&ipv6_remote, + sizeof(uint32_t) * 4, + usrsockaddr_in6.sin6_addr.in6_u.u6_addr32); port_remote = usrsockaddr_in6.sin6_port; } - + /* Pack the tuple info: * - socket family * - src_ipv6 @@ -765,15 +760,12 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * */ push__u8(auxmap->data, &auxmap->payload_pos, socket_family_to_scap(socket_family)); - if(direction == OUTBOUND) - { + if(direction == OUTBOUND) { push__ipv6(auxmap->data, &auxmap->payload_pos, ipv6_local); push__u16(auxmap->data, &auxmap->payload_pos, ntohs(port_local)); push__ipv6(auxmap->data, &auxmap->payload_pos, ipv6_remote); push__u16(auxmap->data, &auxmap->payload_pos, ntohs(port_remote)); - } - else - { + } else { push__ipv6(auxmap->data, &auxmap->payload_pos, ipv6_remote); push__u16(auxmap->data, &auxmap->payload_pos, ntohs(port_remote)); push__ipv6(auxmap->data, &auxmap->payload_pos, ipv6_local); @@ -783,8 +775,7 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * break; } - case AF_UNIX: - { + case AF_UNIX: { struct unix_sock *socket_local = (struct unix_sock *)sk; struct unix_sock *socket_remote = (struct unix_sock *)BPF_CORE_READ(socket_local, peer); char *path = NULL; @@ -796,14 +787,11 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * * - dest unix_path. */ push__u8(auxmap->data, &auxmap->payload_pos, socket_family_to_scap(socket_family)); - if(direction == OUTBOUND) - { + if(direction == OUTBOUND) { push__u64(auxmap->data, &auxmap->payload_pos, (uint64_t)socket_remote); push__u64(auxmap->data, &auxmap->payload_pos, (uint64_t)socket_local); path = BPF_CORE_READ(socket_remote, addr, name[0].sun_path); - } - else - { + } else { push__u64(auxmap->data, &auxmap->payload_pos, (uint64_t)socket_local); push__u64(auxmap->data, &auxmap->payload_pos, (uint64_t)socket_remote); path = BPF_CORE_READ(socket_local, addr, name[0].sun_path); @@ -811,25 +799,26 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * unsigned long start_reading_point; char first_path_byte = *(char *)path; - if(first_path_byte == '\0') - { + if(first_path_byte == '\0') { /* Please note exceptions in the `sun_path`: * Taken from: https://man7.org/linux/man-pages/man7/unix.7.html * * An `abstract socket address` is distinguished (from a * pathname socket) by the fact that sun_path[0] is a null byte * ('\0'). - * + * * So in this case, we need to skip the initial `\0`. */ start_reading_point = (unsigned long)path + 1; - } - else - { + } else { start_reading_point = (unsigned long)path; } - uint16_t written_bytes = push__charbuf(auxmap->data, &auxmap->payload_pos, start_reading_point, MAX_UNIX_SOCKET_PATH, KERNEL); + uint16_t written_bytes = push__charbuf(auxmap->data, + &auxmap->payload_pos, + start_reading_point, + MAX_UNIX_SOCKET_PATH, + KERNEL); final_param_len = FAMILY_SIZE + KERNEL_POINTER + KERNEL_POINTER + written_bytes; break; } @@ -856,8 +845,11 @@ static __always_inline void auxmap__store_socktuple_param(struct auxiliary_map * * @param option_len actual len of the option * @param optval pointer to the option value */ -static __always_inline void auxmap__store_sockopt_param(struct auxiliary_map *auxmap, int level, int optname, uint16_t option_len, unsigned long optval) -{ +static __always_inline void auxmap__store_sockopt_param(struct auxiliary_map *auxmap, + int level, + int optname, + uint16_t option_len, + unsigned long optval) { /* We use a signed int because in some case we have to convert it to a negative value. */ int32_t val32 = 0; uint64_t val64 = 0; @@ -867,17 +859,15 @@ static __always_inline void auxmap__store_sockopt_param(struct auxiliary_map *au /* Levels different from `SOL_SOCKET` are not supported * right now. */ - if(level != SOL_SOCKET) - { + if(level != SOL_SOCKET) { push__u8(auxmap->data, &auxmap->payload_pos, PPM_SOCKOPT_IDX_UNKNOWN); - total_size_to_push += push__bytebuf(auxmap->data, &auxmap->payload_pos, optval, option_len, USER); + total_size_to_push += + push__bytebuf(auxmap->data, &auxmap->payload_pos, optval, option_len, USER); push__param_len(auxmap->data, &auxmap->lengths_pos, total_size_to_push); return; } - switch(optname) - { - + switch(optname) { case SO_ERROR: push__u8(auxmap->data, &auxmap->payload_pos, PPM_SOCKOPT_IDX_ERRNO); bpf_probe_read_user((void *)&val32, sizeof(val32), (void *)optval); @@ -891,7 +881,9 @@ static __always_inline void auxmap__store_sockopt_param(struct auxiliary_map *au case SO_SNDTIMEO_NEW: push__u8(auxmap->data, &auxmap->payload_pos, PPM_SOCKOPT_IDX_TIMEVAL); bpf_probe_read_user((void *)&tv, sizeof(tv), (void *)optval); - push__u64(auxmap->data, &auxmap->payload_pos, tv.tv_sec * SEC_FACTOR + tv.tv_usec * USEC_FACTOR); + push__u64(auxmap->data, + &auxmap->payload_pos, + tv.tv_sec * SEC_FACTOR + tv.tv_usec * USEC_FACTOR); total_size_to_push += sizeof(uint64_t); break; @@ -952,7 +944,8 @@ static __always_inline void auxmap__store_sockopt_param(struct auxiliary_map *au default: push__u8(auxmap->data, &auxmap->payload_pos, PPM_SOCKOPT_IDX_UNKNOWN); - total_size_to_push += push__bytebuf(auxmap->data, &auxmap->payload_pos, optval, option_len, USER); + total_size_to_push += + push__bytebuf(auxmap->data, &auxmap->payload_pos, optval, option_len, USER); break; } @@ -968,14 +961,14 @@ static __always_inline void auxmap__store_sockopt_param(struct auxiliary_map *au * @param iov_pointer pointer to `iovec` struct array. * @param iov_cnt number of `iovec` structs to be read from userspace. */ -static __always_inline void auxmap__store_iovec_size_param(struct auxiliary_map *auxmap, unsigned long iov_pointer, unsigned long iov_cnt) -{ +static __always_inline void auxmap__store_iovec_size_param(struct auxiliary_map *auxmap, + unsigned long iov_pointer, + unsigned long iov_cnt) { /* We use the second part of our auxmap as a scratch space. */ uint32_t total_iovec_size = iov_cnt * bpf_core_type_size(struct iovec); if(bpf_probe_read_user((void *)&auxmap->data[MAX_PARAM_SIZE], - SAFE_ACCESS(total_iovec_size), - (void *)iov_pointer)) - { + SAFE_ACCESS(total_iovec_size), + (void *)iov_pointer)) { auxmap__store_u32_param(auxmap, 0); return; } @@ -984,10 +977,8 @@ static __always_inline void auxmap__store_iovec_size_param(struct auxiliary_map /* Pointer to iovec structs */ const struct iovec *iovec = (const struct iovec *)&auxmap->data[MAX_PARAM_SIZE]; - for(int j = 0; j < MAX_IOVCNT; j++) - { - if(j == iov_cnt) - { + for(int j = 0; j < MAX_IOVCNT; j++) { + if(j == iov_cnt) { break; } total_size_to_read += iovec[j].iov_len; @@ -1003,15 +994,16 @@ static __always_inline void auxmap__store_iovec_size_param(struct auxiliary_map * @param iov_cnt number of `iovec` structs to be read from userspace. * @param len_to_read imposed snaplen. */ -static __always_inline void auxmap__store_iovec_data_param_64(struct auxiliary_map *auxmap, unsigned long iov_pointer, unsigned long iov_cnt, unsigned long len_to_read) -{ +static __always_inline void auxmap__store_iovec_data_param_64(struct auxiliary_map *auxmap, + unsigned long iov_pointer, + unsigned long iov_cnt, + unsigned long len_to_read) { /* We use the second part of our auxmap as a scratch space. */ unsigned long total_iovec_size = iov_cnt * bpf_core_type_size(struct iovec); if(bpf_probe_read_user((void *)&auxmap->data[MAX_PARAM_SIZE], - SAFE_ACCESS(total_iovec_size), - (void *)iov_pointer)) - { + SAFE_ACCESS(total_iovec_size), + (void *)iov_pointer)) { /* in case of NULL iovec vector we return an empty param */ push__param_len(auxmap->data, &auxmap->lengths_pos, 0); return; @@ -1022,25 +1014,25 @@ static __always_inline void auxmap__store_iovec_data_param_64(struct auxiliary_m /* Pointer to iovec structs */ const struct iovec *iovec = (const struct iovec *)&auxmap->data[MAX_PARAM_SIZE]; uint64_t initial_payload_pos = auxmap->payload_pos; - for(int j = 0; j < MAX_IOVCNT; j++) - { - if(total_size_to_read > len_to_read) - { - /* If we break here it could be that `payload_pos` overcame the max `len_to_read` for this reason - * we have an enforcement after the for loop. + for(int j = 0; j < MAX_IOVCNT; j++) { + if(total_size_to_read > len_to_read) { + /* If we break here it could be that `payload_pos` overcame the max `len_to_read` for + * this reason we have an enforcement after the for loop. */ total_size_to_read = len_to_read; break; } - if(j == iov_cnt) - { + if(j == iov_cnt) { break; } - uint16_t bytes_read = push__bytebuf(auxmap->data, &auxmap->payload_pos, (unsigned long)iovec[j].iov_base, iovec[j].iov_len, USER); - if(!bytes_read) - { + uint16_t bytes_read = push__bytebuf(auxmap->data, + &auxmap->payload_pos, + (unsigned long)iovec[j].iov_base, + iovec[j].iov_len, + USER); + if(!bytes_read) { push__param_len(auxmap->data, &auxmap->lengths_pos, total_size_to_read); return; } @@ -1051,15 +1043,16 @@ static __always_inline void auxmap__store_iovec_data_param_64(struct auxiliary_m push__param_len(auxmap->data, &auxmap->lengths_pos, total_size_to_read); } -static __always_inline void auxmap__store_iovec_data_param_32(struct auxiliary_map *auxmap, unsigned long iov_pointer, unsigned long iov_cnt, unsigned long len_to_read) -{ +static __always_inline void auxmap__store_iovec_data_param_32(struct auxiliary_map *auxmap, + unsigned long iov_pointer, + unsigned long iov_cnt, + unsigned long len_to_read) { /* We use the second part of our auxmap as a scratch space. */ unsigned long total_iovec_size = iov_cnt * bpf_core_type_size(struct compat_iovec); if(bpf_probe_read_user((void *)&auxmap->data[MAX_PARAM_SIZE], - SAFE_ACCESS(total_iovec_size), - (void *)iov_pointer)) - { + SAFE_ACCESS(total_iovec_size), + (void *)iov_pointer)) { /* in case of NULL iovec vector we return an empty param */ push__param_len(auxmap->data, &auxmap->lengths_pos, 0); return; @@ -1068,27 +1061,28 @@ static __always_inline void auxmap__store_iovec_data_param_32(struct auxiliary_m unsigned long total_size_to_read = 0; /* Pointer to iovec structs */ - const struct compat_iovec *compat_iovec = (const struct compat_iovec *)&auxmap->data[MAX_PARAM_SIZE]; + const struct compat_iovec *compat_iovec = + (const struct compat_iovec *)&auxmap->data[MAX_PARAM_SIZE]; uint64_t initial_payload_pos = auxmap->payload_pos; - for(int j = 0; j < MAX_IOVCNT; j++) - { - if(total_size_to_read > len_to_read) - { - /* If we break here it could be that `payload_pos` overcame the max `len_to_read` for this reason - * we have an enforcement after the for loop. + for(int j = 0; j < MAX_IOVCNT; j++) { + if(total_size_to_read > len_to_read) { + /* If we break here it could be that `payload_pos` overcame the max `len_to_read` for + * this reason we have an enforcement after the for loop. */ total_size_to_read = len_to_read; break; } - if(j == iov_cnt) - { + if(j == iov_cnt) { break; } - uint16_t bytes_read = push__bytebuf(auxmap->data, &auxmap->payload_pos, (unsigned long)compat_iovec[j].iov_base, compat_iovec[j].iov_len, USER); - if(!bytes_read) - { + uint16_t bytes_read = push__bytebuf(auxmap->data, + &auxmap->payload_pos, + (unsigned long)compat_iovec[j].iov_base, + compat_iovec[j].iov_len, + USER); + if(!bytes_read) { push__param_len(auxmap->data, &auxmap->lengths_pos, total_size_to_read); return; } @@ -1099,14 +1093,13 @@ static __always_inline void auxmap__store_iovec_data_param_32(struct auxiliary_m push__param_len(auxmap->data, &auxmap->lengths_pos, total_size_to_read); } -static __always_inline void auxmap__store_iovec_data_param(struct auxiliary_map *auxmap, unsigned long iov_pointer, unsigned long iov_cnt, unsigned long len_to_read) -{ - if(!bpf_in_ia32_syscall()) - { +static __always_inline void auxmap__store_iovec_data_param(struct auxiliary_map *auxmap, + unsigned long iov_pointer, + unsigned long iov_cnt, + unsigned long len_to_read) { + if(!bpf_in_ia32_syscall()) { auxmap__store_iovec_data_param_64(auxmap, iov_pointer, iov_cnt, len_to_read); - } - else - { + } else { auxmap__store_iovec_data_param_32(auxmap, iov_pointer, iov_cnt, len_to_read); } } @@ -1119,14 +1112,15 @@ static __always_inline void auxmap__store_iovec_data_param(struct auxiliary_map * @param auxmap pointer to the auxmap in which we are storing the param. * @param msghdr_pointer pointer to `user_msghdr` struct. */ -static __always_inline void auxmap__store_msghdr_size_param(struct auxiliary_map *auxmap, unsigned long msghdr_pointer) -{ +static __always_inline void auxmap__store_msghdr_size_param(struct auxiliary_map *auxmap, + unsigned long msghdr_pointer) { /* Read the usr_msghdr struct into the stack, if we fail, * we return 0. */ struct user_msghdr msghdr = {0}; - if(bpf_probe_read_user((void *)&msghdr, bpf_core_type_size(struct user_msghdr), (void *)msghdr_pointer)) - { + if(bpf_probe_read_user((void *)&msghdr, + bpf_core_type_size(struct user_msghdr), + (void *)msghdr_pointer)) { auxmap__store_u32_param(auxmap, 0); return; } @@ -1140,23 +1134,29 @@ static __always_inline void auxmap__store_msghdr_size_param(struct auxiliary_map * @param auxmap pointer to the auxmap in which we are storing the param. * @param msghdr_pointer pointer to `user_msghdr` struct. * @param len_to_read imposed snaplen. - * + * * @return the `user_msghdr` struct that has been read. */ -static __always_inline struct user_msghdr auxmap__store_msghdr_data_param(struct auxiliary_map *auxmap, unsigned long msghdr_pointer, unsigned long len_to_read) -{ +static __always_inline struct user_msghdr auxmap__store_msghdr_data_param( + struct auxiliary_map *auxmap, + unsigned long msghdr_pointer, + unsigned long len_to_read) { /* Read the usr_msghdr struct into the stack, if we fail, * we return an empty param. */ struct user_msghdr msghdr = {0}; - if(bpf_probe_read_user((void *)&msghdr, bpf_core_type_size(struct user_msghdr), (void *)msghdr_pointer)) - { + if(bpf_probe_read_user((void *)&msghdr, + bpf_core_type_size(struct user_msghdr), + (void *)msghdr_pointer)) { /* in case of NULL msghdr we return an empty param */ push__param_len(auxmap->data, &auxmap->lengths_pos, 0); return msghdr; } - auxmap__store_iovec_data_param(auxmap, (unsigned long)msghdr.msg_iov, msghdr.msg_iovlen, len_to_read); + auxmap__store_iovec_data_param(auxmap, + (unsigned long)msghdr.msg_iov, + msghdr.msg_iovlen, + len_to_read); return msghdr; } @@ -1171,18 +1171,16 @@ static __always_inline struct user_msghdr auxmap__store_msghdr_data_param(struct * @param ret return value to understand which action we have to perform. * @param addr_pointer pointer to the `addr` param taken from syscall registers. */ -static __always_inline void auxmap__store_ptrace_addr_param(struct auxiliary_map *auxmap, long ret, uint64_t addr_pointer) -{ +static __always_inline void auxmap__store_ptrace_addr_param(struct auxiliary_map *auxmap, + long ret, + uint64_t addr_pointer) { push__u8(auxmap->data, &auxmap->payload_pos, PPM_PTRACE_IDX_UINT64); /* The syscall is failed. */ - if(ret < 0) - { + if(ret < 0) { /* We push `0` in case of failure. */ push__u64(auxmap->data, &auxmap->payload_pos, 0); - } - else - { + } else { /* We send the addr pointer as a uint64_t */ push__u64(auxmap->data, &auxmap->payload_pos, addr_pointer); } @@ -1200,11 +1198,12 @@ static __always_inline void auxmap__store_ptrace_addr_param(struct auxiliary_map * @param ptrace_req ptrace request converted in the scap format. * @param data_pointer pointer to the `data` param taken from syscall registers. */ -static __always_inline void auxmap__store_ptrace_data_param(struct auxiliary_map *auxmap, long ret, uint16_t ptrace_req, uint64_t data_pointer) -{ +static __always_inline void auxmap__store_ptrace_data_param(struct auxiliary_map *auxmap, + long ret, + uint16_t ptrace_req, + uint64_t data_pointer) { /* The syscall is failed. */ - if(ret < 0) - { + if(ret < 0) { /* We push `0` in case of failure. */ push__u8(auxmap->data, &auxmap->payload_pos, PPM_PTRACE_IDX_UINT64); push__u64(auxmap->data, &auxmap->payload_pos, 0); @@ -1214,8 +1213,7 @@ static __always_inline void auxmap__store_ptrace_data_param(struct auxiliary_map uint64_t dest = 0; uint16_t total_size_to_push = sizeof(uint8_t); /* 1 byte for the PPM type. */ - switch(ptrace_req) - { + switch(ptrace_req) { case PPM_PTRACE_PEEKTEXT: case PPM_PTRACE_PEEKDATA: case PPM_PTRACE_PEEKUSR: @@ -1261,17 +1259,21 @@ static __always_inline void auxmap__store_ptrace_data_param(struct auxiliary_map * @param cgrp_sub_id enum taken from vmlinux `cgroup_subsys_id`. * @return total len written in the aux map for this `cgroup` subsystem. */ -static __always_inline uint16_t store_cgroup_subsys(struct auxiliary_map *auxmap, struct task_struct *task, enum cgroup_subsys_id cgrp_sub_id) -{ +static __always_inline uint16_t store_cgroup_subsys(struct auxiliary_map *auxmap, + struct task_struct *task, + enum cgroup_subsys_id cgrp_sub_id) { uint16_t total_size = 0; /* Write cgroup subsystem name + '=' into the aux map (example "cpuset="). */ const char *cgroup_subsys_name_ptr; BPF_CORE_READ_INTO(&cgroup_subsys_name_ptr, task, cgroups, subsys[cgrp_sub_id], ss, name); /* This could be 0.*/ - total_size += push__charbuf(auxmap->data, &auxmap->payload_pos, (unsigned long)cgroup_subsys_name_ptr, MAX_PARAM_SIZE, KERNEL); - if(!total_size) - { + total_size += push__charbuf(auxmap->data, + &auxmap->payload_pos, + (unsigned long)cgroup_subsys_name_ptr, + MAX_PARAM_SIZE, + KERNEL); + if(!total_size) { return 0; } /* In BPF all strings are ended with `\0` so here we overwrite the @@ -1285,10 +1287,8 @@ static __always_inline uint16_t store_cgroup_subsys(struct auxiliary_map *auxmap unsigned long cgroup_path_pointers[MAX_CGROUP_PATH_POINTERS] = {0}; uint8_t path_components = 0; - for(int k = 0; k < MAX_CGROUP_PATH_POINTERS; ++k) - { - if(!kn) - { + for(int k = 0; k < MAX_CGROUP_PATH_POINTERS; ++k) { + if(!kn) { break; } path_components++; @@ -1323,11 +1323,13 @@ static __always_inline uint16_t store_cgroup_subsys(struct auxiliary_map *auxmap * * cpuset=/path_part1/path_part2\0 */ - for(int k = MAX_CGROUP_PATH_POINTERS - 1; k >= 0; --k) - { - if(cgroup_path_pointers[k]) - { - total_size += push__charbuf(auxmap->data, &auxmap->payload_pos, cgroup_path_pointers[k], MAX_PARAM_SIZE, KERNEL); + for(int k = MAX_CGROUP_PATH_POINTERS - 1; k >= 0; --k) { + if(cgroup_path_pointers[k]) { + total_size += push__charbuf(auxmap->data, + &auxmap->payload_pos, + cgroup_path_pointers[k], + MAX_PARAM_SIZE, + KERNEL); push__previous_character(auxmap->data, &auxmap->payload_pos, '/'); } } @@ -1350,13 +1352,10 @@ static __always_inline uint16_t store_cgroup_subsys(struct auxiliary_map *auxmap * * We can treat the `2` and the `3` in the same way, adding a char terminator at the end. */ - if(path_components <= 1) - { + if(path_components <= 1) { push__new_character(auxmap->data, &auxmap->payload_pos, '\0'); total_size += 1; - } - else - { + } else { push__previous_character(auxmap->data, &auxmap->payload_pos, '\0'); } @@ -1374,34 +1373,46 @@ static __always_inline uint16_t store_cgroup_subsys(struct auxiliary_map *auxmap * @param auxmap pointer to the auxmap in which we are storing the param. * @param task pointer to the current task struct. */ -static __always_inline void auxmap__store_cgroups_param(struct auxiliary_map *auxmap, struct task_struct *task) -{ +static __always_inline void auxmap__store_cgroups_param(struct auxiliary_map *auxmap, + struct task_struct *task) { uint16_t total_croups_len = 0; - if(bpf_core_enum_value_exists(enum cgroup_subsys_id, cpuset_cgrp_id)) - { - total_croups_len += store_cgroup_subsys(auxmap, task, bpf_core_enum_value(enum cgroup_subsys_id, cpuset_cgrp_id)); - } - if(bpf_core_enum_value_exists(enum cgroup_subsys_id, cpu_cgrp_id)) - { - total_croups_len += store_cgroup_subsys(auxmap, task, bpf_core_enum_value(enum cgroup_subsys_id, cpu_cgrp_id)); - } - if(bpf_core_enum_value_exists(enum cgroup_subsys_id, cpuacct_cgrp_id)) - { - total_croups_len += store_cgroup_subsys(auxmap, task, bpf_core_enum_value(enum cgroup_subsys_id, cpuacct_cgrp_id)); - } - if(bpf_core_enum_value_exists(enum cgroup_subsys_id, io_cgrp_id)) - { - total_croups_len += store_cgroup_subsys(auxmap, task, bpf_core_enum_value(enum cgroup_subsys_id, io_cgrp_id)); - } - if(bpf_core_enum_value_exists(enum cgroup_subsys_id, memory_cgrp_id)) - { - total_croups_len += store_cgroup_subsys(auxmap, task, bpf_core_enum_value(enum cgroup_subsys_id, memory_cgrp_id)); + if(bpf_core_enum_value_exists(enum cgroup_subsys_id, cpuset_cgrp_id)) { + total_croups_len += + store_cgroup_subsys(auxmap, + task, + bpf_core_enum_value(enum cgroup_subsys_id, cpuset_cgrp_id)); + } + if(bpf_core_enum_value_exists(enum cgroup_subsys_id, cpu_cgrp_id)) { + total_croups_len += + store_cgroup_subsys(auxmap, + task, + bpf_core_enum_value(enum cgroup_subsys_id, cpu_cgrp_id)); + } + if(bpf_core_enum_value_exists(enum cgroup_subsys_id, cpuacct_cgrp_id)) { + total_croups_len += + store_cgroup_subsys(auxmap, + task, + bpf_core_enum_value(enum cgroup_subsys_id, cpuacct_cgrp_id)); + } + if(bpf_core_enum_value_exists(enum cgroup_subsys_id, io_cgrp_id)) { + total_croups_len += + store_cgroup_subsys(auxmap, + task, + bpf_core_enum_value(enum cgroup_subsys_id, io_cgrp_id)); + } + if(bpf_core_enum_value_exists(enum cgroup_subsys_id, memory_cgrp_id)) { + total_croups_len += + store_cgroup_subsys(auxmap, + task, + bpf_core_enum_value(enum cgroup_subsys_id, memory_cgrp_id)); } push__param_len(auxmap->data, &auxmap->lengths_pos, total_croups_len); } -static __always_inline void auxmap__store_fdlist_param(struct auxiliary_map *auxmap, unsigned long fds_pointer, uint32_t nfds, enum poll_events_direction dir) -{ +static __always_inline void auxmap__store_fdlist_param(struct auxiliary_map *auxmap, + unsigned long fds_pointer, + uint32_t nfds, + enum poll_events_direction dir) { /* In this helper we push data in this format: * - number of `fd + flags` pairs -> (uint16_t) * - first pair (`fd + flags`) -> (int64_t + int16_t) @@ -1416,9 +1427,8 @@ static __always_inline void auxmap__store_fdlist_param(struct auxiliary_map *aux */ uint32_t structs_size = nfds * bpf_core_type_size(struct pollfd); if(bpf_probe_read_user((void *)&auxmap->data[MAX_PARAM_SIZE], - SAFE_ACCESS(structs_size), - (void *)fds_pointer)) - { + SAFE_ACCESS(structs_size), + (void *)fds_pointer)) { /* pair's number equal to `0` */ auxmap__store_u16_param(auxmap, 0); return; @@ -1432,10 +1442,8 @@ static __always_inline void auxmap__store_fdlist_param(struct auxiliary_map *aux const struct pollfd *fds = (const struct pollfd *)&auxmap->data[MAX_PARAM_SIZE]; /* For every `pollfd` struct we try to push an `fd` (int64_t) + `flags` (int16_t) */ - for(int j = 0; j < MAX_POLLFD; j++) - { - if(j == nfds) - { + for(int j = 0; j < MAX_POLLFD; j++) { + if(j == nfds) { break; } @@ -1443,23 +1451,27 @@ static __always_inline void auxmap__store_fdlist_param(struct auxiliary_map *aux push__s64(auxmap->data, &auxmap->payload_pos, (int64_t)fds[j].fd); /* Push `flags` according to the direction */ - if(dir == REQUESTED_EVENTS) - { - push__s16(auxmap->data, &auxmap->payload_pos, (int16_t)poll_events_to_scap(fds[j].events)); - } - else - { - push__s16(auxmap->data, &auxmap->payload_pos, (int16_t)poll_events_to_scap(fds[j].revents)); + if(dir == REQUESTED_EVENTS) { + push__s16(auxmap->data, + &auxmap->payload_pos, + (int16_t)poll_events_to_scap(fds[j].events)); + } else { + push__s16(auxmap->data, + &auxmap->payload_pos, + (int16_t)poll_events_to_scap(fds[j].revents)); } } /* The param size is: 16 bit for the number of pairs + size of the pairs */ - push__param_len(auxmap->data, &auxmap->lengths_pos, sizeof(uint16_t) + (num_pairs * (sizeof(int64_t) + sizeof(int16_t)))); + push__param_len(auxmap->data, + &auxmap->lengths_pos, + sizeof(uint16_t) + (num_pairs * (sizeof(int64_t) + sizeof(int16_t)))); } -static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t *snaplen, bool only_port_range, ppm_event_code evt_type) -{ - if(!maps__get_do_dynamic_snaplen()) - { +static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, + uint16_t *snaplen, + bool only_port_range, + ppm_event_code evt_type) { + if(!maps__get_do_dynamic_snaplen()) { return; } @@ -1500,8 +1512,7 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t unsigned long args[5] = {0}; struct sockaddr *sockaddr = NULL; - switch(evt_type) - { + switch(evt_type) { case PPME_SOCKET_SENDTO_X: case PPME_SOCKET_RECVFROM_X: extract__network_args(args, 5, regs); @@ -1509,14 +1520,13 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t break; case PPME_SOCKET_RECVMSG_X: - case PPME_SOCKET_SENDMSG_X: - { + case PPME_SOCKET_SENDMSG_X: { extract__network_args(args, 3, regs); - if(bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { struct compat_msghdr compat_mh = {}; - if(likely(bpf_probe_read_user(&compat_mh, bpf_core_type_size(struct compat_msghdr), (void *)args[1]) == 0)) - { + if(likely(bpf_probe_read_user(&compat_mh, + bpf_core_type_size(struct compat_msghdr), + (void *)args[1]) == 0)) { sockaddr = (struct sockaddr *)(unsigned long)(compat_mh.msg_name); } // in any case we break the switch. @@ -1524,12 +1534,10 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t } struct user_msghdr mh = {}; - if(bpf_probe_read_user(&mh, bpf_core_type_size(struct user_msghdr), (void *)args[1]) == 0) - { + if(bpf_probe_read_user(&mh, bpf_core_type_size(struct user_msghdr), (void *)args[1]) == 0) { sockaddr = (struct sockaddr *)mh.msg_name; - } - } - break; + } + } break; default: extract__network_args(args, 3, regs); @@ -1538,20 +1546,17 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t /* All the syscalls involved in this logic have the `fd` as first syscall argument */ int32_t socket_fd = (int32_t)args[0]; - if(socket_fd < 0) - { + if(socket_fd < 0) { return; } struct file *file = extract__file_struct_from_fd(socket_fd); struct socket *socket = get_sock_from_file(file); - if(socket == NULL) - { + if(socket == NULL) { return; } struct sock *sk = BPF_CORE_READ(socket, sk); - if(sk == NULL) - { + if(sk == NULL) { return; } @@ -1560,26 +1565,23 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t /* We perform some checks regarding ports only for these 2 families */ uint16_t socket_family = BPF_CORE_READ(sk, __sk_common.skc_family); - if(socket_family == AF_INET || socket_family == AF_INET6) - { + if(socket_family == AF_INET || socket_family == AF_INET6) { struct inet_sock *inet = (struct inet_sock *)sk; BPF_CORE_READ_INTO(&port_local, inet, inet_sport); BPF_CORE_READ_INTO(&port_remote, sk, __sk_common.skc_dport); port_local = ntohs(port_local); port_remote = ntohs(port_remote); - if(port_remote == 0 && sockaddr != NULL) - { - if(socket_family == AF_INET) - { + if(port_remote == 0 && sockaddr != NULL) { + if(socket_family == AF_INET) { struct sockaddr_in sockaddr_in = {}; bpf_probe_read_user(&sockaddr_in, bpf_core_type_size(struct sockaddr_in), sockaddr); port_remote = ntohs(sockaddr_in.sin_port); - } - else - { + } else { struct sockaddr_in6 sockaddr_in6 = {}; - bpf_probe_read_user(&sockaddr_in6, bpf_core_type_size(struct sockaddr_in6), sockaddr); + bpf_probe_read_user(&sockaddr_in6, + bpf_core_type_size(struct sockaddr_in6), + sockaddr); port_remote = ntohs(sockaddr_in6.sin6_port); } } @@ -1589,30 +1591,23 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t uint16_t min_port = maps__get_fullcapture_port_range_start(); uint16_t max_port = maps__get_fullcapture_port_range_end(); - if(max_port > 0 && - ((port_local >= min_port && port_local <= max_port) || - (port_remote >= min_port && port_remote <= max_port))) - { + if(max_port > 0 && ((port_local >= min_port && port_local <= max_port) || + (port_remote >= min_port && port_remote <= max_port))) { /* Max value since this is a port of interest */ *snaplen = *snaplen > SNAPLEN_FULLCAPTURE_PORT ? *snaplen : SNAPLEN_FULLCAPTURE_PORT; return; - } - else if(port_remote == maps__get_statsd_port()) - { + } else if(port_remote == maps__get_statsd_port()) { /* Expanded snaplen for statsd port */ *snaplen = *snaplen > SNAPLEN_EXTENDED ? *snaplen : SNAPLEN_EXTENDED; return; - } - else if(port_remote == PPM_PORT_DNS) - { + } else if(port_remote == PPM_PORT_DNS) { /* Expanded snaplen for DNS port */ *snaplen = *snaplen > SNAPLEN_DNS_UDP ? *snaplen : SNAPLEN_DNS_UDP; return; } /* If we check only port range without reading syscall data we can stop here */ - if(only_port_range) - { + if(only_port_range) { return; } @@ -1621,31 +1616,25 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t unsigned long data_ptr = args[1]; uint32_t size = (uint32_t)args[2]; - if(bpf_probe_read_user((void *)&buf[0], - DPI_LOOKAHEAD_SIZE, - (void *)data_ptr) != 0) - { + if(bpf_probe_read_user((void *)&buf[0], DPI_LOOKAHEAD_SIZE, (void *)data_ptr) != 0) { return; } /* MYSQL */ - if((port_local == PPM_PORT_MYSQL || port_remote == PPM_PORT_MYSQL) && size >= 5) - { + if((port_local == PPM_PORT_MYSQL || port_remote == PPM_PORT_MYSQL) && size >= 5) { if((buf[0] == 3 || buf[1] == 3 || buf[2] == 3 || buf[3] == 3 || buf[4] == 3) || - (buf[2] == 0 && buf[3] == 0)) - { + (buf[2] == 0 && buf[3] == 0)) { *snaplen = *snaplen > SNAPLEN_EXTENDED ? *snaplen : SNAPLEN_EXTENDED; } return; } /* POSTGRES */ - if((port_local == PPM_PORT_POSTGRES || port_remote == PPM_PORT_POSTGRES) && size >= 7) - { - if((buf[0] == 'Q' && buf[1] == 0) || /* SimpleQuery command */ - (buf[0] == 'P' && buf[1] == 0) || /* Prepare statement command */ + if((port_local == PPM_PORT_POSTGRES || port_remote == PPM_PORT_POSTGRES) && size >= 7) { + if((buf[0] == 'Q' && buf[1] == 0) || /* SimpleQuery command */ + (buf[0] == 'P' && buf[1] == 0) || /* Prepare statement command */ (buf[4] == 0 && buf[5] == 3 && buf[6] == 0) || /* Startup command */ - (buf[0] == 'E' && buf[1] == 0)) /* Error or execute command */ + (buf[0] == 'E' && buf[1] == 0)) /* Error or execute command */ { *snaplen = *snaplen > SNAPLEN_EXTENDED ? *snaplen : SNAPLEN_EXTENDED; } @@ -1655,26 +1644,19 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t /* MONGODB */ int32_t m = *(int32_t *)(&buf[12]); if((port_local == PPM_PORT_MONGODB || port_remote == PPM_PORT_MONGODB) || - (size >= 16 && (m == 1 || (m >= 2001 && m <= 2007)))) - { + (size >= 16 && (m == 1 || (m >= 2001 && m <= 2007)))) { *snaplen = *snaplen > SNAPLEN_EXTENDED ? *snaplen : SNAPLEN_EXTENDED; return; } /* HTTP */ - if(size >= 5) - { + if(size >= 5) { uint32_t h = *(uint32_t *)(&buf[0]); #ifdef __TARGET_ARCH_s390 h = __builtin_bswap32(h); #endif - if(h == BPF_HTTP_GET || - h == BPF_HTTP_POST || - h == BPF_HTTP_PUT || - h == BPF_HTTP_DELETE || - h == BPF_HTTP_TRACE || - h == BPF_HTTP_CONNECT || - h == BPF_HTTP_OPTIONS || + if(h == BPF_HTTP_GET || h == BPF_HTTP_POST || h == BPF_HTTP_PUT || h == BPF_HTTP_DELETE || + h == BPF_HTTP_TRACE || h == BPF_HTTP_CONNECT || h == BPF_HTTP_OPTIONS || (h == BPF_HTTP_PREFIX && buf[4] == '/')) /* "HTTP/" */ { *snaplen = *snaplen > SNAPLEN_EXTENDED ? *snaplen : SNAPLEN_EXTENDED; @@ -1689,7 +1671,8 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t * for saving tmp strings, we need to use our auxmap. * We use the first 64 KB to write data, while we use the last 64 KB to save tmp buffers. * In this case we start from the end (128 KB) and we leave 8192 bytes to please the verifier. - * 4096 bytes are enough but using 8192 simplify extreme cases in which tha path is exactly 4096 bytes. + * 4096 bytes are enough but using 8192 simplify extreme cases in which tha path is exactly 4096 + * bytes. * * 64 KB (Used for data) 64 KB (Used to save tmp buffers) * |---------------------|---------------------| @@ -1734,8 +1717,8 @@ static __always_inline void apply_dynamic_snaplen(struct pt_regs *regs, uint16_t * @param auxmap pointer to the auxmap in which we are storing the param. * @param path pointer to the path struct from which we will extract the path name */ -static __always_inline void auxmap__store_d_path_approx(struct auxiliary_map *auxmap, struct path *path) -{ +static __always_inline void auxmap__store_d_path_approx(struct auxiliary_map *auxmap, + struct path *path) { struct path f_path = {}; bpf_core_read(&f_path, sizeof(struct path), path); struct dentry *dentry = f_path.dentry; @@ -1755,21 +1738,17 @@ static __always_inline void auxmap__store_d_path_approx(struct auxiliary_map *au /* We need the unroll here otherwise the verifier complains about back-edges */ #pragma unroll - for(int i = 0; i < MAX_NUM_COMPONENTS; i++) - { + for(int i = 0; i < MAX_NUM_COMPONENTS; i++) { BPF_CORE_READ_INTO(&d_parent, dentry, d_parent); - if(dentry == mnt_root_p || dentry == d_parent) - { - if(dentry != mnt_root_p) - { + if(dentry == mnt_root_p || dentry == d_parent) { + if(dentry != mnt_root_p) { /* We reached the root (dentry == d_parent) * but not the mount root...there is something weird, stop here. */ break; } - if(mnt_p != mnt_parent_p) - { + if(mnt_p != mnt_parent_p) { /* We reached root, but not global root - continue with mount point path */ BPF_CORE_READ_INTO(&dentry, mnt_p, mnt_mountpoint); BPF_CORE_READ_INTO(&mnt_p, mnt_p, mnt_parent); @@ -1792,11 +1771,12 @@ static __always_inline void auxmap__store_d_path_approx(struct auxiliary_map *au */ current_off = max_buf_len - (d_name.len + 1); - effective_name_len = bpf_probe_read_kernel_str(&(auxmap->data[SAFE_TMP_SCRATCH_ACCESS(current_off)]), - MAX_COMPONENT_LEN, (void *)d_name.name); + effective_name_len = + bpf_probe_read_kernel_str(&(auxmap->data[SAFE_TMP_SCRATCH_ACCESS(current_off)]), + MAX_COMPONENT_LEN, + (void *)d_name.name); - if(effective_name_len <= 1) - { + if(effective_name_len <= 1) { /* If effective_name_len is 0 or 1 we have an error * (path can't be null nor an empty string) */ @@ -1814,8 +1794,7 @@ static __always_inline void auxmap__store_d_path_approx(struct auxiliary_map *au dentry = d_parent; } - if(max_buf_len == MAX_TMP_SCRATCH_LEN) - { + if(max_buf_len == MAX_TMP_SCRATCH_LEN) { /* memfd files have no path in the filesystem so we never decremented the `max_buf_len` */ bpf_core_read(&d_name, sizeof(struct qstr), &(dentry->d_name)); auxmap__store_charbuf_param(auxmap, (unsigned long)d_name.name, MAX_COMPONENT_LEN, KERNEL); @@ -1831,5 +1810,8 @@ static __always_inline void auxmap__store_d_path_approx(struct auxiliary_map *au */ auxmap->data[SAFE_TMP_SCRATCH_ACCESS(MAX_TMP_SCRATCH_LEN - 1)] = '\0'; - auxmap__store_charbuf_param(auxmap, (unsigned long)(&(auxmap->data[max_buf_len])), MAX_COMPONENT_LEN, KERNEL); + auxmap__store_charbuf_param(auxmap, + (unsigned long)(&(auxmap->data[max_buf_len])), + MAX_COMPONENT_LEN, + KERNEL); } diff --git a/driver/modern_bpf/helpers/store/ringbuf_store_params.h b/driver/modern_bpf/helpers/store/ringbuf_store_params.h index 7f3f61c6d1..0dee9f1346 100644 --- a/driver/modern_bpf/helpers/store/ringbuf_store_params.h +++ b/driver/modern_bpf/helpers/store/ringbuf_store_params.h @@ -16,12 +16,18 @@ /* `reserved_size - sizeof(uint64_t)` free space is enough because this is the max dimension * we put in the ring buffer in one atomic operation. */ -#define CHECK_RINGBUF_SPACE(pos, reserved_size) pos >= reserved_size ? reserved_size - sizeof(uint64_t) : pos - -#define PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, size) \ - __builtin_memcpy(&ringbuf->data[CHECK_RINGBUF_SPACE(ringbuf->payload_pos, ringbuf->reserved_event_size)], ¶m, size); \ - ringbuf->payload_pos += size; \ - *((uint16_t *)&ringbuf->data[CHECK_RINGBUF_SPACE(ringbuf->lengths_pos, ringbuf->reserved_event_size)]) = size; \ +#define CHECK_RINGBUF_SPACE(pos, reserved_size) \ + pos >= reserved_size ? reserved_size - sizeof(uint64_t) : pos + +#define PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, size) \ + __builtin_memcpy(&ringbuf->data[CHECK_RINGBUF_SPACE(ringbuf->payload_pos, \ + ringbuf->reserved_event_size)], \ + ¶m, \ + size); \ + ringbuf->payload_pos += size; \ + *((uint16_t *)&ringbuf \ + ->data[CHECK_RINGBUF_SPACE(ringbuf->lengths_pos, ringbuf->reserved_event_size)]) = \ + size; \ ringbuf->lengths_pos += sizeof(uint16_t); /* Concept of ringbuf(ring buffer): @@ -63,13 +69,12 @@ * leakage, that is not obviously allowed in BPF. */ -struct ringbuf_struct -{ - uint8_t *data; /* pointer to the space reserved in the ring buffer. */ - uint64_t payload_pos; /* position of the first empty byte in the `data` buf.*/ - uint8_t lengths_pos; /* position the first empty slot into the lengths array of the event. */ +struct ringbuf_struct { + uint8_t *data; /* pointer to the space reserved in the ring buffer. */ + uint64_t payload_pos; /* position of the first empty byte in the `data` buf.*/ + uint8_t lengths_pos; /* position the first empty slot into the lengths array of the event. */ uint16_t reserved_event_size; /* reserved size in the ringbuf. */ - uint16_t event_type; /* event type we want to send to userspace */ + uint16_t event_type; /* event type we want to send to userspace */ }; ///////////////////////////////// @@ -89,31 +94,31 @@ struct ringbuf_struct * @param event_size exact size of the fixed-size event * @return `1` in case of success, `0` in case of failure. */ -static __always_inline uint32_t ringbuf__reserve_space(struct ringbuf_struct *ringbuf, void* ctx, uint32_t event_size, uint16_t event_type) -{ +static __always_inline uint32_t ringbuf__reserve_space(struct ringbuf_struct *ringbuf, + void *ctx, + uint32_t event_size, + uint16_t event_type) { struct ringbuf_map *rb = maps__get_ringbuf_map(); - if(!rb) - { + if(!rb) { bpf_tail_call(ctx, &extra_event_prog_tail_table, T1_HOTPLUG_E); bpf_printk("failed to tail call into the 'hotplug' prog"); return 0; } struct counter_map *counter = maps__get_counter_map(); - if(!counter) - { + if(!counter) { return 0; } - /* This counts the event seen by the drivers even if they are dropped because the buffer is full. */ + /* This counts the event seen by the drivers even if they are dropped because the buffer is + * full. */ counter->n_evts++; /* If we are not able to reserve space we stop here * the event collection. */ uint8_t *space = bpf_ringbuf_reserve(rb, event_size, 0); - if(!space) - { + if(!space) { counter->n_drops_buffer++; compute_event_types_stats(event_type, counter); return 0; @@ -134,8 +139,7 @@ static __always_inline uint32_t ringbuf__reserve_space(struct ringbuf_struct *ri * * @param ringbuf pointer to the `ringbuf_struct`. */ -static __always_inline void ringbuf__store_event_header(struct ringbuf_struct *ringbuf) -{ +static __always_inline void ringbuf__store_event_header(struct ringbuf_struct *ringbuf) { struct ppm_evt_hdr *hdr = (struct ppm_evt_hdr *)ringbuf->data; uint8_t nparams = maps__get_event_num_params(ringbuf->event_type); hdr->ts = maps__get_boot_time() + bpf_ktime_get_boot_ns(); @@ -148,13 +152,13 @@ static __always_inline void ringbuf__store_event_header(struct ringbuf_struct *r ringbuf->lengths_pos = sizeof(struct ppm_evt_hdr); } -static __always_inline void ringbuf__rewrite_header_for_calibration(struct ringbuf_struct *ringbuf, pid_t vtid) -{ +static __always_inline void ringbuf__rewrite_header_for_calibration(struct ringbuf_struct *ringbuf, + pid_t vtid) { struct ppm_evt_hdr *hdr = (struct ppm_evt_hdr *)ringbuf->data; /* we set this to 0 to recognize this calibration event */ hdr->nparams = 0; - /* we cannot send the tid seen by the init namespace we need to send the tid seen by the current pid namespace - * to be compliant with what scap expects. + /* we cannot send the tid seen by the init namespace we need to send the tid seen by the current + * pid namespace to be compliant with what scap expects. */ hdr->tid = vtid; } @@ -172,8 +176,7 @@ static __always_inline void ringbuf__rewrite_header_for_calibration(struct ringb * * @param ringbuf pointer to the `ringbuf_struct`. */ -static __always_inline void ringbuf__submit_event(struct ringbuf_struct *ringbuf) -{ +static __always_inline void ringbuf__submit_event(struct ringbuf_struct *ringbuf) { bpf_ringbuf_submit(ringbuf->data, BPF_RB_NO_WAKEUP); } @@ -198,8 +201,7 @@ static __always_inline void ringbuf__submit_event(struct ringbuf_struct *ringbuf * @param ringbuf pointer to the `ringbuf_struct`. * @param param param to store. */ -static __always_inline void ringbuf__store_s16(struct ringbuf_struct *ringbuf, int16_t param) -{ +static __always_inline void ringbuf__store_s16(struct ringbuf_struct *ringbuf, int16_t param) { PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, sizeof(int16_t)); } @@ -211,8 +213,7 @@ static __always_inline void ringbuf__store_s16(struct ringbuf_struct *ringbuf, i * @param ringbuf pointer to the `ringbuf_struct`. * @param param param to store. */ -static __always_inline void ringbuf__store_s32(struct ringbuf_struct *ringbuf, int32_t param) -{ +static __always_inline void ringbuf__store_s32(struct ringbuf_struct *ringbuf, int32_t param) { PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, sizeof(int32_t)); } @@ -226,8 +227,7 @@ static __always_inline void ringbuf__store_s32(struct ringbuf_struct *ringbuf, i * @param ringbuf pointer to the `ringbuf_struct`. * @param param param to store */ -static __always_inline void ringbuf__store_s64(struct ringbuf_struct *ringbuf, int64_t param) -{ +static __always_inline void ringbuf__store_s64(struct ringbuf_struct *ringbuf, int64_t param) { PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, sizeof(int64_t)); } @@ -242,8 +242,7 @@ static __always_inline void ringbuf__store_s64(struct ringbuf_struct *ringbuf, i * @param ringbuf pointer to the `ringbuf_struct`. * @param param param to store */ -static __always_inline void ringbuf__store_u8(struct ringbuf_struct *ringbuf, uint8_t param) -{ +static __always_inline void ringbuf__store_u8(struct ringbuf_struct *ringbuf, uint8_t param) { PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, sizeof(uint8_t)); } @@ -257,8 +256,7 @@ static __always_inline void ringbuf__store_u8(struct ringbuf_struct *ringbuf, ui * @param ringbuf pointer to the `ringbuf_struct`. * @param param param to store */ -static __always_inline void ringbuf__store_u16(struct ringbuf_struct *ringbuf, uint16_t param) -{ +static __always_inline void ringbuf__store_u16(struct ringbuf_struct *ringbuf, uint16_t param) { PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, sizeof(uint16_t)); } @@ -276,8 +274,7 @@ static __always_inline void ringbuf__store_u16(struct ringbuf_struct *ringbuf, u * @param ringbuf pointer to the `ringbuf_struct`. * @param param param to store */ -static __always_inline void ringbuf__store_u32(struct ringbuf_struct *ringbuf, uint32_t param) -{ +static __always_inline void ringbuf__store_u32(struct ringbuf_struct *ringbuf, uint32_t param) { PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, sizeof(uint32_t)); } @@ -291,8 +288,7 @@ static __always_inline void ringbuf__store_u32(struct ringbuf_struct *ringbuf, u * @param ringbuf pointer to the `ringbuf_struct`. * @param param param to store */ -static __always_inline void ringbuf__store_u64(struct ringbuf_struct *ringbuf, uint64_t param) -{ +static __always_inline void ringbuf__store_u64(struct ringbuf_struct *ringbuf, uint64_t param) { PUSH_FIXED_SIZE_TO_RINGBUF(ringbuf, param, sizeof(uint64_t)); } @@ -303,8 +299,9 @@ static __always_inline void ringbuf__store_u64(struct ringbuf_struct *ringbuf, u * @param iov_pointer pointer to `iovec` struct array. * @param iov_cnt number of `iovec` structs to be read from userspace. */ -static __always_inline void ringbuf__store_iovec_size_param(struct ringbuf_struct *ringbuf, unsigned long iov_pointer, unsigned long iov_cnt) -{ +static __always_inline void ringbuf__store_iovec_size_param(struct ringbuf_struct *ringbuf, + unsigned long iov_pointer, + unsigned long iov_cnt) { /* The idea here is to use the auxmap of this CPU as a scratch space * and normally use the ringbuf to send data to userspace. Note that * we are running on this CPU so nobody else can use the auxmap in the meanwhile. @@ -313,26 +310,21 @@ static __always_inline void ringbuf__store_iovec_size_param(struct ringbuf_struc */ struct auxiliary_map *auxmap = maps__get_auxiliary_map(); - if(!auxmap) - { + if(!auxmap) { ringbuf__store_u32(ringbuf, 0); return; } uint32_t total_iovec_size = 0; - if(!bpf_in_ia32_syscall()) - { + if(!bpf_in_ia32_syscall()) { total_iovec_size = iov_cnt * bpf_core_type_size(struct iovec); - } - else - { + } else { total_iovec_size = iov_cnt * bpf_core_type_size(struct compat_iovec); } if(bpf_probe_read_user((void *)&auxmap->data[0], - SAFE_ACCESS(total_iovec_size), - (void *)iov_pointer)) - { + SAFE_ACCESS(total_iovec_size), + (void *)iov_pointer)) { ringbuf__store_u32(ringbuf, 0); return; } @@ -340,25 +332,18 @@ static __always_inline void ringbuf__store_iovec_size_param(struct ringbuf_struc uint32_t total_size_to_read = 0; /* Pointer to iovec structs */ - if(!bpf_in_ia32_syscall()) - { + if(!bpf_in_ia32_syscall()) { const struct iovec *iovec = (const struct iovec *)&auxmap->data[0]; - for(int j = 0; j < MAX_IOVCNT; j++) - { - if(j == iov_cnt) - { + for(int j = 0; j < MAX_IOVCNT; j++) { + if(j == iov_cnt) { break; } total_size_to_read += iovec[j].iov_len; } - } - else - { + } else { const struct compat_iovec *iovec = (const struct compat_iovec *)&auxmap->data[0]; - for(int j = 0; j < MAX_IOVCNT; j++) - { - if(j == iov_cnt) - { + for(int j = 0; j < MAX_IOVCNT; j++) { + if(j == iov_cnt) { break; } total_size_to_read += iovec[j].iov_len; diff --git a/driver/modern_bpf/maps/maps.h b/driver/modern_bpf/maps/maps.h index 5a18e06849..ecd77f04d9 100644 --- a/driver/modern_bpf/maps/maps.h +++ b/driver/modern_bpf/maps/maps.h @@ -61,7 +61,7 @@ __weak bool g_64bit_interesting_syscalls_table[SYSCALL_TABLE_SIZE]; * @brief Given the syscall id on 64-bit-architectures returns: * - `UF_NEVER_DROP` if the syscall must not be dropped in the sampling logic. * - `UF_ALWAYS_DROP` if the syscall must always be dropped in the sampling logic. - * - `UF_NONE` if we drop the syscall depends on the sampling ratio. + * - `UF_NONE` if we drop the syscall depends on the sampling ratio. */ __weak uint8_t g_64bit_sampling_syscall_table[SYSCALL_TABLE_SIZE]; @@ -69,7 +69,7 @@ __weak uint8_t g_64bit_sampling_syscall_table[SYSCALL_TABLE_SIZE]; * @brief Given the tracepoint enum returns: * - `UF_NEVER_DROP` if the syscall must not be dropped in the sampling logic. * - `UF_ALWAYS_DROP` if the syscall must always be dropped in the sampling logic. - * - `UF_NONE` if we drop the syscall depends on the sampling ratio. + * - `UF_NONE` if we drop the syscall depends on the sampling ratio. */ /// TOOD: we need to change the dimension! we need to create a dedicated enum for tracepoints! __weak uint8_t g_64bit_sampling_tracepoint_table[PPM_EVENT_MAX]; @@ -95,7 +95,7 @@ __weak bool is_dropping; /** * @brief Pointer we use to understand if we are operating on a socket. */ -__weak void *socket_file_ops = NULL; +__weak void *socket_file_ops = NULL; /*=============================== BPF GLOBAL VARIABLES ===============================*/ @@ -106,8 +106,7 @@ __weak void *socket_file_ops = NULL; * Given the syscall_id, it calls the right bpf program to manage * the syscall enter event. */ -struct -{ +struct { __uint(type, BPF_MAP_TYPE_PROG_ARRAY); __uint(max_entries, SYSCALL_TABLE_SIZE); __type(key, uint32_t); @@ -119,8 +118,7 @@ struct * Given the syscall_id, it calls the right bpf program to manage * the syscall exit event. */ -struct -{ +struct { __uint(type, BPF_MAP_TYPE_PROG_ARRAY); __uint(max_entries, SYSCALL_TABLE_SIZE); __type(key, uint32_t); @@ -136,8 +134,7 @@ struct * Given a predefined tail-code (`extra_event_prog_code`), it calls * the right bpf program. */ -struct -{ +struct { __uint(type, BPF_MAP_TYPE_PROG_ARRAY); __uint(max_entries, TAIL_EXTRA_EVENT_PROG_MAX); __type(key, uint32_t); @@ -165,8 +162,7 @@ struct * map where the event is temporally saved before being * pushed in the ringbuffer. */ -struct -{ +struct { __uint(type, BPF_MAP_TYPE_ARRAY); __type(key, uint32_t); __type(value, struct auxiliary_map); @@ -177,8 +173,7 @@ struct * map where we store the number of events correctly pushed * and the number of events dropped. */ -struct -{ +struct { __uint(type, BPF_MAP_TYPE_ARRAY); __type(key, uint32_t); __type(value, struct counter_map); @@ -189,20 +184,19 @@ struct /*=============================== RINGBUF MAP ===============================*/ /** - * @brief We use this map to let the verifier understand the content of our array of maps (`ringbuf_maps`) + * @brief We use this map to let the verifier understand the content of our array of maps + * (`ringbuf_maps`) */ -struct ringbuf_map -{ +struct ringbuf_map { __uint(type, BPF_MAP_TYPE_RINGBUF); }; /** * @brief This array of maps will contain a variable number of ring buffers * according to the user-provided configuration. It could also contain only - * one buffer shared between all CPUs. + * one buffer shared between all CPUs. */ -struct -{ +struct { __uint(type, BPF_MAP_TYPE_ARRAY_OF_MAPS); __type(key, uint32_t); __type(value, uint32_t); diff --git a/driver/modern_bpf/programs/attached/dispatchers/syscall_enter.bpf.c b/driver/modern_bpf/programs/attached/dispatchers/syscall_enter.bpf.c index 28e9cce7a7..7732b738e2 100644 --- a/driver/modern_bpf/programs/attached/dispatchers/syscall_enter.bpf.c +++ b/driver/modern_bpf/programs/attached/dispatchers/syscall_enter.bpf.c @@ -13,57 +13,43 @@ * TP_PROTO(struct pt_regs *regs, long id), */ SEC("tp_btf/sys_enter") -int BPF_PROG(sys_enter, - struct pt_regs *regs, - long syscall_id) -{ +int BPF_PROG(sys_enter, struct pt_regs *regs, long syscall_id) { int socketcall_syscall_id = -1; - if(bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { #if defined(__TARGET_ARCH_x86) - if (syscall_id == __NR_ia32_socketcall) - { + if(syscall_id == __NR_ia32_socketcall) { socketcall_syscall_id = __NR_ia32_socketcall; - } - else - { + } else { syscall_id = maps__ia32_to_64(syscall_id); // syscalls defined only on 32 bits are dropped here. - if(syscall_id == (uint32_t)-1) - { + if(syscall_id == (uint32_t)-1) { return 0; } } #else return 0; #endif - } - else - { + } else { #ifdef __NR_socketcall socketcall_syscall_id = __NR_socketcall; #endif } /* we convert it here in this way the syscall will be treated exactly as the original one */ - if(syscall_id == socketcall_syscall_id) - { + if(syscall_id == socketcall_syscall_id) { syscall_id = convert_network_syscalls(regs); - if (syscall_id == -1) - { + if(syscall_id == -1) { // We can't do anything since modern bpf filler jump table is syscall indexed return 0; } } - if(!syscalls_dispatcher__64bit_interesting_syscall(syscall_id)) - { + if(!syscalls_dispatcher__64bit_interesting_syscall(syscall_id)) { return 0; } - if(sampling_logic(ctx, syscall_id, MODERN_BPF_SYSCALL)) - { + if(sampling_logic(ctx, syscall_id, MODERN_BPF_SYSCALL)) { return 0; } diff --git a/driver/modern_bpf/programs/attached/dispatchers/syscall_exit.bpf.c b/driver/modern_bpf/programs/attached/dispatchers/syscall_exit.bpf.c index 9205008910..53714500a0 100644 --- a/driver/modern_bpf/programs/attached/dispatchers/syscall_exit.bpf.c +++ b/driver/modern_bpf/programs/attached/dispatchers/syscall_exit.bpf.c @@ -10,80 +10,64 @@ #include #include -#define X86_64_NR_EXECVE 59 -#define X86_64_NR_EXECVEAT 322 +#define X86_64_NR_EXECVE 59 +#define X86_64_NR_EXECVEAT 322 /* From linux tree: /include/trace/events/syscall.h * TP_PROTO(struct pt_regs *regs, long ret), */ SEC("tp_btf/sys_exit") -int BPF_PROG(sys_exit, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(sys_exit, struct pt_regs *regs, long ret) { int socketcall_syscall_id = -1; uint32_t syscall_id = extract__syscall_id(regs); - if(bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { #if defined(__TARGET_ARCH_x86) - if (syscall_id == __NR_ia32_socketcall) - { + if(syscall_id == __NR_ia32_socketcall) { socketcall_syscall_id = __NR_ia32_socketcall; - } - else - { + } else { /* * When a process does execve from 64bit to 32bit, TS_COMPAT is marked true * but the id of the syscall is __NR_execve, so to correctly parse it we need to * use 64bit syscall table. On 32bit __NR_execve is equal to __NR_ia32_oldolduname * which is a very old syscall, not used anymore by most applications */ - if(syscall_id != X86_64_NR_EXECVE && syscall_id != X86_64_NR_EXECVEAT) - { + if(syscall_id != X86_64_NR_EXECVE && syscall_id != X86_64_NR_EXECVEAT) { syscall_id = maps__ia32_to_64(syscall_id); - if(syscall_id == (uint32_t)-1) - { + if(syscall_id == (uint32_t)-1) { return 0; } } } #else - // TODO: unsupported - return 0; + // TODO: unsupported + return 0; #endif - } - else - { + } else { #ifdef __NR_socketcall socketcall_syscall_id = __NR_socketcall; #endif } /* we convert it here in this way the syscall will be treated exactly as the original one */ - if(syscall_id == socketcall_syscall_id) - { + if(syscall_id == socketcall_syscall_id) { syscall_id = convert_network_syscalls(regs); - if (syscall_id == -1) - { + if(syscall_id == -1) { // We can't do anything since modern bpf filler jump table is syscall indexed return 0; } } - if(!syscalls_dispatcher__64bit_interesting_syscall(syscall_id)) - { + if(!syscalls_dispatcher__64bit_interesting_syscall(syscall_id)) { return 0; } - if(sampling_logic(ctx, syscall_id, MODERN_BPF_SYSCALL)) - { + if(sampling_logic(ctx, syscall_id, MODERN_BPF_SYSCALL)) { return 0; } - if (maps__get_drop_failed() && ret < 0) - { + if(maps__get_drop_failed() && ret < 0) { return 0; } diff --git a/driver/modern_bpf/programs/attached/events/page_fault_kernel.bpf.c b/driver/modern_bpf/programs/attached/events/page_fault_kernel.bpf.c index 61dddcc360..f9576a93da 100644 --- a/driver/modern_bpf/programs/attached/events/page_fault_kernel.bpf.c +++ b/driver/modern_bpf/programs/attached/events/page_fault_kernel.bpf.c @@ -15,18 +15,13 @@ */ #ifdef CAPTURE_PAGE_FAULTS SEC("tp_btf/page_fault_kernel") -int BPF_PROG(pf_kernel, - unsigned long address, struct pt_regs *regs, - unsigned long error_code) -{ - if(sampling_logic(ctx, PPME_PAGE_FAULT_E, MODERN_BPF_TRACEPOINT)) - { +int BPF_PROG(pf_kernel, unsigned long address, struct pt_regs *regs, unsigned long error_code) { + if(sampling_logic(ctx, PPME_PAGE_FAULT_E, MODERN_BPF_TRACEPOINT)) { return 0; } struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PAGE_FAULT_SIZE, PPME_PAGE_FAULT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PAGE_FAULT_SIZE, PPME_PAGE_FAULT_E)) { return 0; } diff --git a/driver/modern_bpf/programs/attached/events/page_fault_user.bpf.c b/driver/modern_bpf/programs/attached/events/page_fault_user.bpf.c index 488ebfbc8d..c6179c3aea 100644 --- a/driver/modern_bpf/programs/attached/events/page_fault_user.bpf.c +++ b/driver/modern_bpf/programs/attached/events/page_fault_user.bpf.c @@ -15,18 +15,13 @@ */ #ifdef CAPTURE_PAGE_FAULTS SEC("tp_btf/page_fault_user") -int BPF_PROG(pf_user, - unsigned long address, struct pt_regs *regs, - unsigned long error_code) -{ - if(sampling_logic(ctx, PPME_PAGE_FAULT_E, MODERN_BPF_TRACEPOINT)) - { +int BPF_PROG(pf_user, unsigned long address, struct pt_regs *regs, unsigned long error_code) { + if(sampling_logic(ctx, PPME_PAGE_FAULT_E, MODERN_BPF_TRACEPOINT)) { return 0; } struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PAGE_FAULT_SIZE, PPME_PAGE_FAULT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PAGE_FAULT_SIZE, PPME_PAGE_FAULT_E)) { return 0; } diff --git a/driver/modern_bpf/programs/attached/events/sched_process_exec.bpf.c b/driver/modern_bpf/programs/attached/events/sched_process_exec.bpf.c index 5fc1d98a5a..a8ce62ca52 100644 --- a/driver/modern_bpf/programs/attached/events/sched_process_exec.bpf.c +++ b/driver/modern_bpf/programs/attached/events/sched_process_exec.bpf.c @@ -15,23 +15,18 @@ #ifdef CAPTURE_SCHED_PROC_EXEC /* chose a short name for bpftool debugging*/ SEC("tp_btf/sched_process_exec") -int BPF_PROG(sched_p_exec, - struct task_struct *p, pid_t old_pid, - struct linux_binprm *bprm) -{ +int BPF_PROG(sched_p_exec, struct task_struct *p, pid_t old_pid, struct linux_binprm *bprm) { struct task_struct *task = get_current_task(); uint32_t flags = 0; READ_TASK_FIELD_INTO(&flags, task, flags); /* We are not interested in kernel threads. */ - if(flags & PF_KTHREAD) - { + if(flags & PF_KTHREAD) { return 0; } struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_EXECVE_19_X); @@ -55,12 +50,15 @@ int BPF_PROG(sched_p_exec, READ_TASK_FIELD_INTO(&arg_end_pointer, task, mm, arg_end); /* Parameter 2: exe (type: PT_CHARBUF) */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, total_args_len - exe_arg_len, - MAX_PROC_ARG_ENV - exe_arg_len); + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); /* Parameter 4: tid (type: PT_PID) */ /* this is called `tid` but it is the `pid`. */ @@ -121,13 +119,9 @@ int BPF_PROG(sched_p_exec, } SEC("tp_btf/sched_process_exec") -int BPF_PROG(t1_sched_p_exec, - struct task_struct *p, pid_t old_pid, - struct linux_binprm *bprm) -{ +int BPF_PROG(t1_sched_p_exec, struct task_struct *p, pid_t old_pid, struct linux_binprm *bprm) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -145,8 +139,10 @@ int BPF_PROG(t1_sched_p_exec, READ_TASK_FIELD_INTO(&env_end_pointer, task, mm, env_end); /* Parameter 16: env (type: PT_CHARBUFARRAY) */ - auxmap__store_charbufarray_as_bytebuf(auxmap, env_start_pointer, env_end_pointer - env_start_pointer, - MAX_PROC_ARG_ENV); + auxmap__store_charbufarray_as_bytebuf(auxmap, + env_start_pointer, + env_end_pointer - env_start_pointer, + MAX_PROC_ARG_ENV); /* Parameter 17: tty (type: PT_UINT32) */ uint32_t tty = exctract__tty(task); @@ -166,21 +162,16 @@ int BPF_PROG(t1_sched_p_exec, struct inode *exe_inode = extract__exe_inode_from_task(task); struct file *exe_file = extract__exe_file_from_task(task); - if(extract__exe_writable(task, exe_inode)) - { + if(extract__exe_writable(task, exe_inode)) { flags |= PPM_EXE_WRITABLE; } enum ppm_overlay overlay = extract__overlay_layer(exe_file); - if(overlay == PPM_OVERLAY_UPPER) - { + if(overlay == PPM_OVERLAY_UPPER) { flags |= PPM_EXE_UPPER_LAYER; - } - else if (overlay == PPM_OVERLAY_LOWER) - { + } else if(overlay == PPM_OVERLAY_LOWER) { flags |= PPM_EXE_LOWER_LAYER; } - if(extract__exe_from_memfd(exe_file)) - { + if(extract__exe_from_memfd(exe_file)) { flags |= PPM_EXE_FROM_MEMFD; } @@ -203,21 +194,16 @@ int BPF_PROG(t1_sched_p_exec, extract__ino_from_inode(exe_inode, &ino); auxmap__store_u64_param(auxmap, ino); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ - struct timespec64 time = { 0, 0 }; - if(bpf_core_field_exists(exe_inode->i_ctime)) - { + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ + struct timespec64 time = {0, 0}; + if(bpf_core_field_exists(exe_inode->i_ctime)) { BPF_CORE_READ_INTO(&time, exe_inode, i_ctime); - } - else - { + } else { struct inode___v6_6 *exe_inode_v6_6 = (void *)exe_inode; - if(bpf_core_field_exists(exe_inode_v6_6->__i_ctime)) - { + if(bpf_core_field_exists(exe_inode_v6_6->__i_ctime)) { BPF_CORE_READ_INTO(&time, exe_inode_v6_6, __i_ctime); - } - else - { + } else { struct inode___v6_11 *exe_inode_v6_11 = (void *)exe_inode; BPF_CORE_READ_INTO(&time.tv_sec, exe_inode_v6_11, i_ctime_sec); BPF_CORE_READ_INTO(&time.tv_nsec, exe_inode_v6_11, i_ctime_nsec); @@ -225,20 +211,15 @@ int BPF_PROG(t1_sched_p_exec, } auxmap__store_u64_param(auxmap, extract__epoch_ns_from_time(time)); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ - if(bpf_core_field_exists(exe_inode->i_mtime)) - { + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ + if(bpf_core_field_exists(exe_inode->i_mtime)) { BPF_CORE_READ_INTO(&time, exe_inode, i_mtime); - } - else - { + } else { struct inode___v6_7 *exe_inode_v6_7 = (void *)exe_inode; - if(bpf_core_field_exists(exe_inode_v6_7->__i_mtime)) - { + if(bpf_core_field_exists(exe_inode_v6_7->__i_mtime)) { BPF_CORE_READ_INTO(&time, exe_inode_v6_7, __i_mtime); - } - else - { + } else { struct inode___v6_11 *exe_inode_v6_11 = (void *)exe_inode; BPF_CORE_READ_INTO(&time.tv_sec, exe_inode_v6_11, i_mtime_sec); BPF_CORE_READ_INTO(&time.tv_nsec, exe_inode_v6_11, i_mtime_nsec); @@ -258,11 +239,9 @@ int BPF_PROG(t1_sched_p_exec, } SEC("tp_btf/sys_exit") -int BPF_PROG(t2_sched_p_exec, struct pt_regs *regs, long ret) -{ +int BPF_PROG(t2_sched_p_exec, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -272,12 +251,9 @@ int BPF_PROG(t2_sched_p_exec, struct pt_regs *regs, long ret) struct file *exe_file = extract__exe_file_from_task(task); /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ - if(exe_file != NULL) - { + if(exe_file != NULL) { auxmap__store_d_path_approx(auxmap, &(exe_file->f_path)); - } - else - { + } else { auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/attached/events/sched_process_exit.bpf.c b/driver/modern_bpf/programs/attached/events/sched_process_exit.bpf.c index a8529c7324..9e05b34472 100644 --- a/driver/modern_bpf/programs/attached/events/sched_process_exit.bpf.c +++ b/driver/modern_bpf/programs/attached/events/sched_process_exit.bpf.c @@ -15,12 +15,13 @@ #define MAX_HIERARCHY_TRAVERSE 60 /* 3 possible cases: - * - Looping between all threads of the current thread group we don't find a valid reaper. -> return 0 - * - We cannot loop over all threads of the group due to BPF verifier limits (MAX_THREADS_GROUPS) -> return -1 + * - Looping between all threads of the current thread group we don't find a valid reaper. -> return + * 0 + * - We cannot loop over all threads of the group due to BPF verifier limits (MAX_THREADS_GROUPS) -> + * return -1 * - We find a reaper -> return its `pid` */ -static __always_inline pid_t find_alive_thread(struct task_struct *father) -{ +static __always_inline pid_t find_alive_thread(struct task_struct *father) { struct signal_struct *signal = BPF_CORE_READ(father, signal); struct list_head *head = &(signal->thread_head); struct list_head *next_thread = BPF_CORE_READ(head, next); @@ -29,19 +30,16 @@ static __always_inline pid_t find_alive_thread(struct task_struct *father) for(struct task_struct *t = container_of(next_thread, typeof(struct task_struct), thread_node); next_thread != (head) && cnt < MAX_THREADS_GROUPS; - t = container_of(next_thread, typeof(struct task_struct), thread_node)) - { + t = container_of(next_thread, typeof(struct task_struct), thread_node)) { cnt++; - if(!(BPF_CORE_READ(t, flags) & PF_EXITING)) - { + if(!(BPF_CORE_READ(t, flags) & PF_EXITING)) { return BPF_CORE_READ(t, pid); } next_thread = BPF_CORE_READ(t, thread_node.next); } /* We cannot loop over all threads, we cannot know the right reaper */ - if(cnt == MAX_THREADS_GROUPS) - { + if(cnt == MAX_THREADS_GROUPS) { return -1; } @@ -55,8 +53,7 @@ static __always_inline pid_t find_alive_thread(struct task_struct *father) * child_subreaper for its children (like a service manager) * 3. give it to the init process (PID 1) in our pid namespace */ -static __always_inline pid_t find_new_reaper_pid(struct task_struct *father) -{ +static __always_inline pid_t find_new_reaper_pid(struct task_struct *father) { pid_t reaper_pid = find_alive_thread(father); /* - If we are not able to find the reaper due to BPF @@ -66,8 +63,7 @@ static __always_inline pid_t find_new_reaper_pid(struct task_struct *father) * * - If reaper_pid > 0 we find a valid reaper, we can return. */ - if(reaper_pid != 0) - { + if(reaper_pid != 0) { return reaper_pid; } @@ -83,15 +79,13 @@ static __always_inline pid_t find_new_reaper_pid(struct task_struct *father) * The kernel will destroy all the processes in that namespace. We send a reaper equal to * `0` in userspace. */ - if(child_ns_reaper == father) - { + if(child_ns_reaper == father) { return 0; } /* If there are no sub reapers the reaper is the init process of that namespace */ struct signal_struct *signal = READ_TASK_FIELD(father, signal); - if(!BPF_CORE_READ_BITFIELD_PROBED(signal, has_child_subreaper)) - { + if(!BPF_CORE_READ_BITFIELD_PROBED(signal, has_child_subreaper)) { return child_reaper_pid; } @@ -110,35 +104,31 @@ static __always_inline pid_t find_new_reaper_pid(struct task_struct *father) */ uint8_t cnt = 0; - for(struct task_struct *possible_reaper = READ_TASK_FIELD(father, real_parent); cnt < MAX_HIERARCHY_TRAVERSE; - possible_reaper = BPF_CORE_READ(possible_reaper, real_parent)) - { + for(struct task_struct *possible_reaper = READ_TASK_FIELD(father, real_parent); + cnt < MAX_HIERARCHY_TRAVERSE; + possible_reaper = BPF_CORE_READ(possible_reaper, real_parent)) { cnt++; current_ns_level = BPF_CORE_READ(possible_reaper, thread_pid, level); /* We are crossing the namespace or we are the child_ns_reaper */ - if(father_ns_level != current_ns_level || possible_reaper == child_ns_reaper) - { + if(father_ns_level != current_ns_level || possible_reaper == child_ns_reaper) { return child_reaper_pid; } signal = BPF_CORE_READ(possible_reaper, signal); - if(!BPF_CORE_READ_BITFIELD_PROBED(signal, is_child_subreaper)) - { + if(!BPF_CORE_READ_BITFIELD_PROBED(signal, is_child_subreaper)) { continue; } /* Here again we can return -1 in case we have verifier limits issues */ reaper_pid = find_alive_thread(possible_reaper); - if(reaper_pid != 0) - { + if(reaper_pid != 0) { return reaper_pid; } } /* We cannot traverse all the hierarchy, we cannot know the right reaper */ - if(cnt == MAX_HIERARCHY_TRAVERSE) - { + if(cnt == MAX_HIERARCHY_TRAVERSE) { return -1; } @@ -149,20 +139,18 @@ static __always_inline pid_t find_new_reaper_pid(struct task_struct *father) * TP_PROTO(struct task_struct *p) */ SEC("tp_btf/sched_process_exit") -int BPF_PROG(sched_proc_exit, struct task_struct *task) -{ +int BPF_PROG(sched_proc_exit, struct task_struct *task) { /* NOTE: this is a fixed-size event and so we should use the `ringbuf-approach`. * Unfortunately we are hitting a sort of complexity limit in some kernel versions (<5.10) * It seems like the verifier is not able to recognize the `ringbuf` pointer as a real pointer - * after a certain number of instructions but it considers it as an `invariant` causing a verifier error like: - * R1 invalid mem access 'inv' - * + * after a certain number of instructions but it considers it as an `invariant` causing a + * verifier error like: R1 invalid mem access 'inv' + * * Right now we solved it using the `auxmap-approach` but in the next future maybe we could * switch again to the `ringbuf-approach`. */ struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -182,8 +170,7 @@ int BPF_PROG(sched_proc_exit, struct task_struct *task) /* Parameter 3: sig (type: PT_SIGTYPE) */ uint8_t sig = 0; /* If the process terminates with a signal collect it. */ - if(__WIFSIGNALED(exit_code) != 0) - { + if(__WIFSIGNALED(exit_code) != 0) { sig = __WTERMSIG(exit_code); } auxmap__store_u8_param(auxmap, sig); @@ -201,8 +188,7 @@ int BPF_PROG(sched_proc_exit, struct task_struct *task) int32_t reaper_pid = 0; struct list_head *head = &(task->children); struct list_head *next_child = BPF_CORE_READ(head, next); - if(next_child != head) - { + if(next_child != head) { /* We have at least one child, so we need a reaper for it */ reaper_pid = find_new_reaper_pid(task); } diff --git a/driver/modern_bpf/programs/attached/events/sched_process_fork.bpf.c b/driver/modern_bpf/programs/attached/events/sched_process_fork.bpf.c index 9a3c101fde..f33ccd440a 100644 --- a/driver/modern_bpf/programs/attached/events/sched_process_fork.bpf.c +++ b/driver/modern_bpf/programs/attached/events/sched_process_fork.bpf.c @@ -16,22 +16,18 @@ #ifdef CAPTURE_SCHED_PROC_FORK /* chose a short name for bpftool debugging*/ SEC("tp_btf/sched_process_fork") -int BPF_PROG(sched_p_fork, - struct task_struct *parent, struct task_struct *child) -{ +int BPF_PROG(sched_p_fork, struct task_struct *parent, struct task_struct *child) { struct task_struct *task = get_current_task(); uint32_t flags = 0; READ_TASK_FIELD_INTO(&flags, task, flags); /* We are not interested in kernel threads. */ - if(flags & PF_KTHREAD) - { + if(flags & PF_KTHREAD) { return 0; } struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_CLONE_20_X); @@ -68,12 +64,15 @@ int BPF_PROG(sched_p_fork, /* We need to extract the len of `exe` arg so we can understand * the overall length of the remaining args. */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, - total_args_len - exe_arg_len, MAX_PROC_ARG_ENV - exe_arg_len); + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); /* Parameter 4: tid (type: PT_PID) */ /* this is called `tid` but it is the `pid`. */ @@ -134,12 +133,9 @@ int BPF_PROG(sched_p_fork, } SEC("tp_btf/sched_process_fork") -int BPF_PROG(t1_sched_p_fork, - struct task_struct *parent, struct task_struct *child) -{ +int BPF_PROG(t1_sched_p_fork, struct task_struct *parent, struct task_struct *child) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -159,8 +155,7 @@ int BPF_PROG(t1_sched_p_fork, */ pid_t tid = READ_TASK_FIELD(child, pid); pid_t tgid = READ_TASK_FIELD(child, tgid); - if(tid != tgid) - { + if(tid != tgid) { flags |= PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM; } @@ -172,8 +167,7 @@ int BPF_PROG(t1_sched_p_fork, struct files_struct *parent_file_struct = NULL; READ_TASK_FIELD_INTO(&file_struct, child, files); READ_TASK_FIELD_INTO(&parent_file_struct, parent, files); - if(parent_file_struct == file_struct) - { + if(parent_file_struct == file_struct) { flags |= PPM_CL_CLONE_FILES; } @@ -184,8 +178,7 @@ int BPF_PROG(t1_sched_p_fork, struct pid *pid_struct = extract__task_pid_struct(child, PIDTYPE_PID); struct pid_namespace *pid_namespace_struct = extract__namespace_of_pid(pid_struct); int pidns_level = BPF_CORE_READ(pid_namespace_struct, level); - if(pidns_level != 0) - { + if(pidns_level != 0) { flags |= PPM_CL_CHILD_IN_PIDNS; } auxmap__store_u32_param(auxmap, flags); @@ -218,12 +211,9 @@ int BPF_PROG(t1_sched_p_fork, } SEC("tp_btf/sched_process_fork") -int BPF_PROG(t2_sched_p_fork, - struct task_struct *parent, struct task_struct *child) -{ +int BPF_PROG(t2_sched_p_fork, struct task_struct *parent, struct task_struct *child) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/attached/events/sched_switch.bpf.c b/driver/modern_bpf/programs/attached/events/sched_switch.bpf.c index 43d9a63f52..d639edbd7c 100644 --- a/driver/modern_bpf/programs/attached/events/sched_switch.bpf.c +++ b/driver/modern_bpf/programs/attached/events/sched_switch.bpf.c @@ -14,20 +14,15 @@ * struct task_struct *next) */ SEC("tp_btf/sched_switch") -int BPF_PROG(sched_switch, - bool preempt, struct task_struct *prev, - struct task_struct *next) -{ - if(sampling_logic(ctx, PPME_SCHEDSWITCH_6_E, MODERN_BPF_TRACEPOINT)) - { +int BPF_PROG(sched_switch, bool preempt, struct task_struct *prev, struct task_struct *next) { + if(sampling_logic(ctx, PPME_SCHEDSWITCH_6_E, MODERN_BPF_TRACEPOINT)) { return 0; } - + /// TODO: we could avoid switches from kernel threads to kernel threads (?). struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SCHED_SWITCH_SIZE, PPME_SCHEDSWITCH_6_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SCHED_SWITCH_SIZE, PPME_SCHEDSWITCH_6_E)) { return 0; } diff --git a/driver/modern_bpf/programs/attached/events/signal_deliver.bpf.c b/driver/modern_bpf/programs/attached/events/signal_deliver.bpf.c index a8071e3373..4b455eca05 100644 --- a/driver/modern_bpf/programs/attached/events/signal_deliver.bpf.c +++ b/driver/modern_bpf/programs/attached/events/signal_deliver.bpf.c @@ -13,17 +13,13 @@ * TP_PROTO(int sig, struct kernel_siginfo *info, struct k_sigaction *ka) */ SEC("tp_btf/signal_deliver") -int BPF_PROG(signal_deliver, - int sig, struct kernel_siginfo *info, struct k_sigaction *ka) -{ - if(sampling_logic(ctx, PPME_SIGNALDELIVER_E, MODERN_BPF_TRACEPOINT)) - { +int BPF_PROG(signal_deliver, int sig, struct kernel_siginfo *info, struct k_sigaction *ka) { + if(sampling_logic(ctx, PPME_SIGNALDELIVER_E, MODERN_BPF_TRACEPOINT)) { return 0; } struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNAL_DELIVER_SIZE, PPME_SIGNALDELIVER_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNAL_DELIVER_SIZE, PPME_SIGNALDELIVER_E)) { return 0; } @@ -34,10 +30,8 @@ int BPF_PROG(signal_deliver, /* Try to find the source pid */ pid_t spid = 0; - if(info != NULL) - { - switch(sig) - { + if(info != NULL) { + switch(sig) { case SIGKILL: spid = info->_sifields._kill._pid; break; @@ -46,15 +40,11 @@ int BPF_PROG(signal_deliver, case SIGHUP: case SIGINT: case SIGTSTP: - case SIGQUIT: - { + case SIGQUIT: { int si_code = info->si_code; - if(si_code == SI_USER || - si_code == SI_QUEUE || - si_code <= 0) - { + if(si_code == SI_USER || si_code == SI_QUEUE || si_code <= 0) { /* This is equivalent to `info->si_pid` where - * `si_pid` is a macro `_sifields._kill._pid` + * `si_pid` is a macro `_sifields._kill._pid` */ spid = info->_sifields._kill._pid; } @@ -70,8 +60,7 @@ int BPF_PROG(signal_deliver, break; } - if(sig >= SIGRTMIN && sig <= SIGRTMAX) - { + if(sig >= SIGRTMIN && sig <= SIGRTMAX) { spid = info->_sifields._rt._pid; } } diff --git a/driver/modern_bpf/programs/tail_called/events/custom_logic/drop.bpf.c b/driver/modern_bpf/programs/tail_called/events/custom_logic/drop.bpf.c index 9d67af75fb..49f90f9f32 100644 --- a/driver/modern_bpf/programs/tail_called/events/custom_logic/drop.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/custom_logic/drop.bpf.c @@ -11,11 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(t1_drop_e) -{ +int BPF_PROG(t1_drop_e) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DROP_E_SIZE, PPME_DROP_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DROP_E_SIZE, PPME_DROP_E)) { return 0; } @@ -36,11 +34,9 @@ int BPF_PROG(t1_drop_e) /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(t1_drop_x) -{ +int BPF_PROG(t1_drop_x) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DROP_X_SIZE, PPME_DROP_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DROP_X_SIZE, PPME_DROP_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/custom_logic/hotplug.bpf.c b/driver/modern_bpf/programs/tail_called/events/custom_logic/hotplug.bpf.c index ba06557232..256fddfa0f 100644 --- a/driver/modern_bpf/programs/tail_called/events/custom_logic/hotplug.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/custom_logic/hotplug.bpf.c @@ -9,27 +9,25 @@ #include SEC("tp_btf/sys_enter") -int BPF_PROG(t1_hotplug_e) -{ +int BPF_PROG(t1_hotplug_e) { /* We assume that the ring buffer for CPU 0 is always there so we send the * HOT-PLUG event through this buffer. */ uint32_t cpu_0 = 0; struct ringbuf_map *rb = bpf_map_lookup_elem(&ringbuf_maps, &cpu_0); - if(!rb) - { + if(!rb) { bpf_printk("unable to obtain the ring buffer for CPU 0"); return 0; } struct counter_map *counter = bpf_map_lookup_elem(&counter_maps, &cpu_0); - if(!counter) - { + if(!counter) { bpf_printk("unable to obtain the counter map for CPU 0"); return 0; } - /* This counts the event seen by the drivers even if they are dropped because the buffer is full. */ + /* This counts the event seen by the drivers even if they are dropped because the buffer is + * full. */ counter->n_evts++; /* If we are not able to reserve space we stop here @@ -39,8 +37,7 @@ int BPF_PROG(t1_hotplug_e) ringbuf.reserved_event_size = HOTPLUG_E_SIZE; ringbuf.event_type = PPME_CPU_HOTPLUG_E; ringbuf.data = bpf_ringbuf_reserve(rb, HOTPLUG_E_SIZE, 0); - if(!ringbuf.data) - { + if(!ringbuf.data) { counter->n_drops_buffer++; return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept.bpf.c index 8a5973895a..5efa008f14 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(accept_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(accept_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, ACCEPT_E_SIZE, PPME_SOCKET_ACCEPT_5_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, ACCEPT_E_SIZE, PPME_SOCKET_ACCEPT_5_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(accept_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(accept_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(accept_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -72,8 +64,7 @@ int BPF_PROG(accept_x, uint8_t queuepct = 0; /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ - if(ret >= 0) - { + if(ret >= 0) { auxmap__store_socktuple_param(auxmap, (int32_t)ret, INBOUND, NULL); /* Collect parameters at the beginning to manage socketcalls */ @@ -87,22 +78,17 @@ int BPF_PROG(accept_x, */ struct file *file = extract__file_struct_from_fd((int32_t)socket_fd); struct socket *socket = get_sock_from_file(file); - if(socket != NULL) - { + if(socket != NULL) { struct sock *sk = BPF_CORE_READ(socket, sk); - if(sk != NULL) - { + if(sk != NULL) { BPF_CORE_READ_INTO(&queuelen, sk, sk_ack_backlog); BPF_CORE_READ_INTO(&queuemax, sk, sk_max_ack_backlog); - if(queuelen && queuemax) - { + if(queuelen && queuemax) { queuepct = (uint8_t)((uint64_t)queuelen * 100 / queuemax); } } } - } - else - { + } else { auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept4.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept4.bpf.c index 0180a5652d..034c015e4b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept4.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/accept4.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(accept4_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(accept4_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, ACCEPT4_E_SIZE, PPME_SOCKET_ACCEPT4_6_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, ACCEPT4_E_SIZE, PPME_SOCKET_ACCEPT4_6_E)) { return 0; } @@ -44,13 +40,9 @@ int BPF_PROG(accept4_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(accept4_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(accept4_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -76,8 +68,7 @@ int BPF_PROG(accept4_x, uint8_t queuepct = 0; /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ - if(ret >= 0) - { + if(ret >= 0) { auxmap__store_socktuple_param(auxmap, (int32_t)ret, INBOUND, NULL); /* Collect parameters at the beginning to manage socketcalls */ @@ -91,22 +82,17 @@ int BPF_PROG(accept4_x, */ struct file *file = extract__file_struct_from_fd((int32_t)socket_fd); struct socket *socket = get_sock_from_file(file); - if(socket != NULL) - { + if(socket != NULL) { struct sock *sk = BPF_CORE_READ(socket, sk); - if(sk != NULL) - { + if(sk != NULL) { BPF_CORE_READ_INTO(&queuelen, sk, sk_ack_backlog); BPF_CORE_READ_INTO(&queuemax, sk, sk_max_ack_backlog); - if(queuelen && queuemax) - { + if(queuelen && queuemax) { queuepct = (uint8_t)((uint64_t)queuelen * 100 / queuemax); } } } - } - else - { + } else { auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/access.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/access.bpf.c index dfd825d510..fd71693a0c 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/access.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/access.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(access_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(access_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, ACCESS_E_SIZE, PPME_SYSCALL_ACCESS_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, ACCESS_E_SIZE, PPME_SYSCALL_ACCESS_E)) { return 0; } @@ -42,13 +38,9 @@ int BPF_PROG(access_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(access_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(access_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bind.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bind.bpf.c index 7e9736bea4..b980be086a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bind.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bind.bpf.c @@ -12,17 +12,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(bind_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(bind_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to easily manage socketcalls */ unsigned long socket_fd = 0; extract__network_args(&socket_fd, 1, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, BIND_E_SIZE, PPME_SOCKET_BIND_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, BIND_E_SIZE, PPME_SOCKET_BIND_E)) { return 0; } @@ -45,18 +41,13 @@ int BPF_PROG(bind_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(bind_x, - struct pt_regs *regs, - long ret) -{ - if(maps__get_dropping_mode() && ret < 0) - { +int BPF_PROG(bind_x, struct pt_regs *regs, long ret) { + if(maps__get_dropping_mode() && ret < 0) { return 0; } struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bpf.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bpf.bpf.c index 5e0c75cb0e..d13fe1666f 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bpf.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/bpf.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(bpf_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(bpf_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, BPF_E_SIZE, PPME_SYSCALL_BPF_2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, BPF_E_SIZE, PPME_SYSCALL_BPF_2_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(bpf_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(bpf_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(bpf_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, BPF_X_SIZE, PPME_SYSCALL_BPF_2_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, BPF_X_SIZE, PPME_SYSCALL_BPF_2_X)) { return 0; } @@ -60,8 +52,7 @@ int BPF_PROG(bpf_x, /* Parameter 2: cmd (type: PT_INT32) */ unsigned long cmd = extract__syscall_argument(regs, 0); - ringbuf__store_s32(&ringbuf,(int32_t)bpf_cmd_to_scap(cmd)); - + ringbuf__store_s32(&ringbuf, (int32_t)bpf_cmd_to_scap(cmd)); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/brk.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/brk.bpf.c index 47b661a0e7..679594cd2a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/brk.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/brk.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(brk_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(brk_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, BRK_E_SIZE, PPME_SYSCALL_BRK_4_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, BRK_E_SIZE, PPME_SYSCALL_BRK_4_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(brk_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(brk_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(brk_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, BRK_X_SIZE, PPME_SYSCALL_BRK_4_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, BRK_X_SIZE, PPME_SYSCALL_BRK_4_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/capset.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/capset.bpf.c index 61f6733e4f..aec9278646 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/capset.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/capset.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(capset_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(capset_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CAPSET_E_SIZE, PPME_SYSCALL_CAPSET_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CAPSET_E_SIZE, PPME_SYSCALL_CAPSET_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(capset_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(capset_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(capset_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CAPSET_X_SIZE, PPME_SYSCALL_CAPSET_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CAPSET_X_SIZE, PPME_SYSCALL_CAPSET_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chdir.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chdir.bpf.c index d43784286a..c7a0d52b6d 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chdir.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chdir.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(chdir_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(chdir_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CHDIR_E_SIZE, PPME_SYSCALL_CHDIR_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CHDIR_E_SIZE, PPME_SYSCALL_CHDIR_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(chdir_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(chdir_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(chdir_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chmod.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chmod.bpf.c index c92f1b9d35..c3fe03887f 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chmod.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chmod.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(chmod_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(chmod_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CHMOD_E_SIZE, PPME_SYSCALL_CHMOD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CHMOD_E_SIZE, PPME_SYSCALL_CHMOD_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(chmod_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(chmod_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(chmod_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chown.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chown.bpf.c index 8e6431388f..a8aaa7d06f 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chown.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chown.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(chown_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(chown_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CHOWN_E_SIZE, PPME_SYSCALL_CHOWN_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CHOWN_E_SIZE, PPME_SYSCALL_CHOWN_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(chown_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(chown_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(chown_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chroot.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chroot.bpf.c index 6cd604ad4c..0a98215e0a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chroot.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/chroot.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(chroot_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(chroot_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CHROOT_E_SIZE, PPME_SYSCALL_CHROOT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CHROOT_E_SIZE, PPME_SYSCALL_CHROOT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(chroot_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(chroot_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(chroot_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone.bpf.c index b77b3b1eb1..682566b755 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(clone_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(clone_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CLONE_E_SIZE, PPME_SYSCALL_CLONE_20_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CLONE_E_SIZE, PPME_SYSCALL_CLONE_20_E)) { return 0; } @@ -40,26 +36,20 @@ int BPF_PROG(clone_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(clone_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(clone_x, struct pt_regs *regs, long ret) { /* We already catch the clone child event with our `sched_process_fork` tracepoint, * for this reason we don't need also this instrumentation. Please note that we use * the aforementioned tracepoint only for the child event but we need to catch also * the father event or the failure case, for this reason we check the `ret==0` */ #ifdef CAPTURE_SCHED_PROC_FORK - if(ret == 0) - { + if(ret == 0) { return 0; } #endif struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_CLONE_20_X); @@ -74,8 +64,7 @@ int BPF_PROG(clone_x, /* We can extract `exe` (Parameter 2) and `args`(Parameter 3) only if the * syscall doesn't fail. Otherwise, they will send empty parameters. */ - if(ret >= 0) - { + if(ret >= 0) { unsigned long arg_start_pointer = 0; unsigned long arg_end_pointer = 0; @@ -87,15 +76,16 @@ int BPF_PROG(clone_x, READ_TASK_FIELD_INTO(&arg_end_pointer, task, mm, arg_end); /* Parameter 2: exe (type: PT_CHARBUF) */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, - total_args_len - exe_arg_len, MAX_PROC_ARG_ENV - exe_arg_len); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); + } else { /* Parameter 2: exe (type: PT_CHARBUF) */ auxmap__store_empty_param(auxmap); @@ -165,13 +155,9 @@ int BPF_PROG(clone_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t1_clone_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t1_clone_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -225,13 +211,9 @@ int BPF_PROG(t1_clone_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t2_clone_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t2_clone_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone3.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone3.bpf.c index 0ac39c92e3..c87ffec713 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone3.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/clone3.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(clone3_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(clone3_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CLONE3_E_SIZE, PPME_SYSCALL_CLONE3_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CLONE3_E_SIZE, PPME_SYSCALL_CLONE3_E)) { return 0; } @@ -40,26 +36,20 @@ int BPF_PROG(clone3_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(clone3_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(clone3_x, struct pt_regs *regs, long ret) { /* We already catch the clone3 child event with our `sched_process_fork` tracepoint, * for this reason we don't need also this instrumentation. Please note that we use * the aforementioned tracepoint only for the child event but we need to catch also * the father event or the failure case, for this reason we check the `ret==0` */ #ifdef CAPTURE_SCHED_PROC_FORK - if(ret == 0) - { + if(ret == 0) { return 0; } #endif struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_CLONE3_X); @@ -74,8 +64,7 @@ int BPF_PROG(clone3_x, /* We can extract `exe` (Parameter 2) and `args`(Parameter 3) only if the * syscall doesn't fail. Otherwise, they will send empty parameters. */ - if(ret >= 0) - { + if(ret >= 0) { unsigned long arg_start_pointer = 0; unsigned long arg_end_pointer = 0; @@ -87,15 +76,16 @@ int BPF_PROG(clone3_x, READ_TASK_FIELD_INTO(&arg_end_pointer, task, mm, arg_end); /* Parameter 2: exe (type: PT_CHARBUF) */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, - total_args_len - exe_arg_len, MAX_PROC_ARG_ENV - exe_arg_len); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); + } else { /* Parameter 2: exe (type: PT_CHARBUF) */ auxmap__store_empty_param(auxmap); @@ -165,13 +155,9 @@ int BPF_PROG(clone3_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t1_clone3_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t1_clone3_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -185,11 +171,12 @@ int BPF_PROG(t1_clone3_x, /* Parameter 16: flags (type: PT_FLAGS32) */ /* the `clone_args` struct is defined since kernel version 5.3 */ unsigned long flags = 0; - if(bpf_core_type_exists(struct clone_args)) - { + if(bpf_core_type_exists(struct clone_args)) { unsigned long cl_args_pointer = extract__syscall_argument(regs, 0); struct clone_args cl_args = {0}; - bpf_probe_read_user((void *)&cl_args, bpf_core_type_size(struct clone_args), (void *)cl_args_pointer); + bpf_probe_read_user((void *)&cl_args, + bpf_core_type_size(struct clone_args), + (void *)cl_args_pointer); flags = extract__clone_flags(task, cl_args.flags); } auxmap__store_u32_param(auxmap, (uint32_t)flags); @@ -222,13 +209,9 @@ int BPF_PROG(t1_clone3_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t2_clone3_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t2_clone3_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/close.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/close.bpf.c index 063158d9dd..93c51c89c8 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/close.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/close.bpf.c @@ -11,16 +11,11 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(close_e, - struct pt_regs *regs, - long id) -{ - if(maps__get_dropping_mode()) - { +int BPF_PROG(close_e, struct pt_regs *regs, long id) { + if(maps__get_dropping_mode()) { int32_t fd = (int32_t)extract__syscall_argument(regs, 0); /* We drop the event if we are closing a negative file descriptor */ - if(fd < 0) - { + if(fd < 0) { return 0; } @@ -28,30 +23,26 @@ int BPF_PROG(close_e, uint32_t max_fds = 0; BPF_CORE_READ_INTO(&max_fds, task, files, fdt, max_fds); /* We drop the event if the fd is >= than `max_fds` */ - if(fd >= max_fds) - { + if(fd >= max_fds) { return 0; } /* We drop the event if the fd is not open */ long unsigned int entry = 0; long unsigned int *open_fds = BPF_CORE_READ(task, files, fdt, open_fds); - if(open_fds == NULL) - { + if(open_fds == NULL) { return 0; } - if(bpf_probe_read_kernel(&entry, sizeof(entry), (const void *)&(open_fds[BIT_WORD(fd)])) == 0) - { - if(!(1UL & (entry >> (fd & (BITS_PER_LONG - 1))))) - { + if(bpf_probe_read_kernel(&entry, sizeof(entry), (const void *)&(open_fds[BIT_WORD(fd)])) == + 0) { + if(!(1UL & (entry >> (fd & (BITS_PER_LONG - 1))))) { return 0; } } } struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CLOSE_E_SIZE, PPME_SYSCALL_CLOSE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CLOSE_E_SIZE, PPME_SYSCALL_CLOSE_E)) { return 0; } @@ -75,18 +66,13 @@ int BPF_PROG(close_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(close_x, - struct pt_regs *regs, - long ret) -{ - if(maps__get_dropping_mode() && ret < 0) - { +int BPF_PROG(close_x, struct pt_regs *regs, long ret) { + if(maps__get_dropping_mode() && ret < 0) { return 0; } struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, CLOSE_X_SIZE, PPME_SYSCALL_CLOSE_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, CLOSE_X_SIZE, PPME_SYSCALL_CLOSE_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/connect.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/connect.bpf.c index bf9c49927d..3e36f4d953 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/connect.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/connect.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(connect_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(connect_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SOCKET_CONNECT_E); @@ -51,13 +47,9 @@ int BPF_PROG(connect_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(connect_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(connect_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -73,12 +65,9 @@ int BPF_PROG(connect_x, /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* We need a valid sockfd to extract source data.*/ - if(ret == 0 || ret == -EINPROGRESS) - { + if(ret == 0 || ret == -EINPROGRESS) { auxmap__store_socktuple_param(auxmap, (int32_t)socket_fd, OUTBOUND, NULL); - } - else - { + } else { auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/copy_file_range.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/copy_file_range.bpf.c index 8f5af10b92..80336c49c3 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/copy_file_range.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/copy_file_range.bpf.c @@ -11,13 +11,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(copy_file_range_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(copy_file_range_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, COPY_FILE_RANGE_E_SIZE, PPME_SYSCALL_COPY_FILE_RANGE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + COPY_FILE_RANGE_E_SIZE, + PPME_SYSCALL_COPY_FILE_RANGE_E)) { return 0; } @@ -49,13 +48,12 @@ int BPF_PROG(copy_file_range_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(copy_file_range_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(copy_file_range_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, COPY_FILE_RANGE_X_SIZE, PPME_SYSCALL_COPY_FILE_RANGE_X)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + COPY_FILE_RANGE_X_SIZE, + PPME_SYSCALL_COPY_FILE_RANGE_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/creat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/creat.bpf.c index 2801504810..617c239a75 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/creat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/creat.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(creat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(creat_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -47,13 +43,9 @@ int BPF_PROG(creat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(creat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(creat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -77,8 +69,7 @@ int BPF_PROG(creat_x, enum ppm_overlay ol = PPM_NOT_OVERLAY_FS; uint16_t creat_flags = 0; - if(ret > 0) - { + if(ret > 0) { extract__dev_ino_overlay_from_fd(ret, &dev, &ino, &ol); } @@ -89,12 +80,9 @@ int BPF_PROG(creat_x, auxmap__store_u64_param(auxmap, ino); /* Parameter 6: creat_flags (type: PT_FLAGS16) */ - if(ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { creat_flags |= PPM_FD_UPPER_LAYER_CREAT; - } - else if(ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { creat_flags |= PPM_FD_LOWER_LAYER_CREAT; } auxmap__store_u16_param(auxmap, creat_flags); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/delete_module.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/delete_module.bpf.c index 90daf4f053..da08bff07f 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/delete_module.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/delete_module.bpf.c @@ -12,11 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(delete_module_e, struct pt_regs *regs, long id) -{ +int BPF_PROG(delete_module_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DELETE_MODULE_E_SIZE, PPME_SYSCALL_DELETE_MODULE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DELETE_MODULE_E_SIZE, PPME_SYSCALL_DELETE_MODULE_E)) { return 0; } @@ -38,11 +36,9 @@ int BPF_PROG(delete_module_e, struct pt_regs *regs, long id) /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(delete_module_x, struct pt_regs *regs, long ret) -{ +int BPF_PROG(delete_module_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup.bpf.c index ae1bd6b2d9..301db7ba22 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(dup_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(dup_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DUP_E_SIZE, PPME_SYSCALL_DUP_1_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DUP_E_SIZE, PPME_SYSCALL_DUP_1_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(dup_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(dup_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(dup_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DUP_X_SIZE, PPME_SYSCALL_DUP_1_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DUP_X_SIZE, PPME_SYSCALL_DUP_1_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup2.bpf.c index 8907cc89eb..54201dbb1a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup2.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(dup2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(dup2_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DUP2_E_SIZE, PPME_SYSCALL_DUP2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DUP2_E_SIZE, PPME_SYSCALL_DUP2_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(dup2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(dup2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(dup2_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DUP2_X_SIZE, PPME_SYSCALL_DUP2_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DUP2_X_SIZE, PPME_SYSCALL_DUP2_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup3.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup3.bpf.c index 7a7239764e..3e833f137c 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup3.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/dup3.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(dup3_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(dup3_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DUP3_E_SIZE, PPME_SYSCALL_DUP3_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DUP3_E_SIZE, PPME_SYSCALL_DUP3_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(dup3_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(dup3_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(dup3_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, DUP3_X_SIZE, PPME_SYSCALL_DUP3_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, DUP3_X_SIZE, PPME_SYSCALL_DUP3_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create.bpf.c index f2aa442214..35f3cde769 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create.bpf.c @@ -1,39 +1,35 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* -* Copyright (C) 2023 The Falco Authors. -* -* This file is dual licensed under either the MIT or GPL 2. See MIT.txt -* or GPL2.txt for full copies of the license. -*/ + * Copyright (C) 2023 The Falco Authors. + * + * This file is dual licensed under either the MIT or GPL 2. See MIT.txt + * or GPL2.txt for full copies of the license. + */ #include /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(epoll_create_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE_E_SIZE, PPME_SYSCALL_EPOLL_CREATE_E)) - { - return 0; - } +int BPF_PROG(epoll_create_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE_E_SIZE, PPME_SYSCALL_EPOLL_CREATE_E)) { + return 0; + } - ringbuf__store_event_header(&ringbuf); + ringbuf__store_event_header(&ringbuf); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: size (type: PT_INT32) */ - int32_t size = (int32_t)extract__syscall_argument(regs, 0); - ringbuf__store_s32(&ringbuf, size); + /* Parameter 1: size (type: PT_INT32) */ + int32_t size = (int32_t)extract__syscall_argument(regs, 0); + ringbuf__store_s32(&ringbuf, size); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - ringbuf__submit_event(&ringbuf); + ringbuf__submit_event(&ringbuf); - return 0; + return 0; } /*=============================== ENTER EVENT ===========================*/ @@ -41,28 +37,24 @@ int BPF_PROG(epoll_create_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(epoll_create_x, - struct pt_regs *regs, - long ret) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE_X_SIZE, PPME_SYSCALL_EPOLL_CREATE_X)) - { - return 0; - } +int BPF_PROG(epoll_create_x, struct pt_regs *regs, long ret) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE_X_SIZE, PPME_SYSCALL_EPOLL_CREATE_X)) { + return 0; + } - ringbuf__store_event_header(&ringbuf); + ringbuf__store_event_header(&ringbuf); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO)*/ - ringbuf__store_s64(&ringbuf, ret); + /* Parameter 1: res (type: PT_ERRNO)*/ + ringbuf__store_s64(&ringbuf, ret); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - ringbuf__submit_event(&ringbuf); + ringbuf__submit_event(&ringbuf); - return 0; + return 0; } /*=============================== EXIT EVENT ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create1.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create1.bpf.c index 230c870573..159a4b6e6e 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create1.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_create1.bpf.c @@ -1,9 +1,9 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* -* Copyright (C) 2023 The Falco Authors. -* -* This file is dual licensed under either the MIT or GPL 2. See MIT.txt -* or GPL2.txt for full copies of the license. + * Copyright (C) 2023 The Falco Authors. + * + * This file is dual licensed under either the MIT or GPL 2. See MIT.txt + * or GPL2.txt for full copies of the license. */ #include @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(epoll_create1_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(epoll_create1_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE1_E_SIZE, PPME_SYSCALL_EPOLL_CREATE1_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE1_E_SIZE, PPME_SYSCALL_EPOLL_CREATE1_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(epoll_create1_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(epoll_create1_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(epoll_create1_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE1_X_SIZE, PPME_SYSCALL_EPOLL_CREATE1_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_CREATE1_X_SIZE, PPME_SYSCALL_EPOLL_CREATE1_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_wait.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_wait.bpf.c index ab17b3f758..01aa162b74 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_wait.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/epoll_wait.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(epoll_wait_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(epoll_wait_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_WAIT_E_SIZE, PPME_SYSCALL_EPOLLWAIT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_WAIT_E_SIZE, PPME_SYSCALL_EPOLLWAIT_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(epoll_wait_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(epoll_wait_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(epoll_wait_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_WAIT_X_SIZE, PPME_SYSCALL_EPOLLWAIT_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EPOLL_WAIT_X_SIZE, PPME_SYSCALL_EPOLLWAIT_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd.bpf.c index c76cd1e3b4..890e76de71 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(eventfd_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(eventfd_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD_E_SIZE, PPME_SYSCALL_EVENTFD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD_E_SIZE, PPME_SYSCALL_EVENTFD_E)) { return 0; } @@ -47,13 +43,9 @@ int BPF_PROG(eventfd_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(eventfd_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(eventfd_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD_X_SIZE, PPME_SYSCALL_EVENTFD_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD_X_SIZE, PPME_SYSCALL_EVENTFD_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd2.bpf.c index 3a31315f5f..bd8284e566 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/eventfd2.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(eventfd2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(eventfd2_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD2_E_SIZE, PPME_SYSCALL_EVENTFD2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD2_E_SIZE, PPME_SYSCALL_EVENTFD2_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(eventfd2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(eventfd2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(eventfd2_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD2_X_SIZE, PPME_SYSCALL_EVENTFD2_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, EVENTFD2_X_SIZE, PPME_SYSCALL_EVENTFD2_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execve.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execve.bpf.c index 671376409f..dbbd9390b8 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execve.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execve.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(execve_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(execve_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_EXECVE_19_E); @@ -41,26 +37,21 @@ int BPF_PROG(execve_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(execve_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(execve_x, struct pt_regs *regs, long ret) { /* On some recent kernels the execve/execveat issue is solved: * https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?h=linux-5.15.y&id=42eede3ae05bbf32cb0d87940b466ec5a76aca3f - * BTW we already catch the event with our `sched_process_exec` tracepoint, for this reason we don't need also this instrumentation. - * Please note that we still need to catch the syscall failure for this reason we check the `ret==0`. + * BTW we already catch the event with our `sched_process_exec` tracepoint, for this reason we don't + * need also this instrumentation. Please note that we still need to catch the syscall failure for + * this reason we check the `ret==0`. */ #ifdef CAPTURE_SCHED_PROC_EXEC - if(ret == 0) - { + if(ret == 0) { return 0; } #endif struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_EXECVE_19_X); @@ -75,8 +66,7 @@ int BPF_PROG(execve_x, /* In case of success we take `exe` and `args` directly from the kernel * otherwise we get them from the syscall arguments. */ - if(ret == 0) - { + if(ret == 0) { unsigned long arg_start_pointer = 0; unsigned long arg_end_pointer = 0; @@ -91,15 +81,16 @@ int BPF_PROG(execve_x, /* We need to extract the len of `exe` arg so we can understand * the overall length of the remaining args. */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, - total_args_len - exe_arg_len, MAX_PROC_ARG_ENV - exe_arg_len); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); + } else { unsigned long argv = extract__syscall_argument(regs, 1); /* Parameter 2: exe (type: PT_CHARBUF) */ @@ -169,13 +160,9 @@ int BPF_PROG(execve_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t1_execve_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t1_execve_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -189,8 +176,7 @@ int BPF_PROG(t1_execve_x, /* In case of success we take `env` directly from the kernel * otherwise we get them from the syscall arguments. */ - if(ret == 0) - { + if(ret == 0) { unsigned long env_start_pointer = 0; unsigned long env_end_pointer = 0; @@ -198,11 +184,11 @@ int BPF_PROG(t1_execve_x, READ_TASK_FIELD_INTO(&env_end_pointer, task, mm, env_end); /* Parameter 16: env (type: PT_CHARBUFARRAY) */ - auxmap__store_charbufarray_as_bytebuf(auxmap, env_start_pointer, env_end_pointer - env_start_pointer, - MAX_PROC_ARG_ENV); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + env_start_pointer, + env_end_pointer - env_start_pointer, + MAX_PROC_ARG_ENV); + } else { /* Parameter 16: env (type: PT_CHARBUFARRAY) */ unsigned long envp = extract__syscall_argument(regs, 2); auxmap__store_env_failure(auxmap, (char **)envp); @@ -226,21 +212,16 @@ int BPF_PROG(t1_execve_x, struct inode *exe_inode = extract__exe_inode_from_task(task); struct file *exe_file = extract__exe_file_from_task(task); - if(extract__exe_writable(task, exe_inode)) - { + if(extract__exe_writable(task, exe_inode)) { flags |= PPM_EXE_WRITABLE; } enum ppm_overlay overlay = extract__overlay_layer(exe_file); - if(overlay == PPM_OVERLAY_UPPER) - { + if(overlay == PPM_OVERLAY_UPPER) { flags |= PPM_EXE_UPPER_LAYER; - } - else if (overlay == PPM_OVERLAY_LOWER) - { + } else if(overlay == PPM_OVERLAY_LOWER) { flags |= PPM_EXE_LOWER_LAYER; } - if(extract__exe_from_memfd(exe_file)) - { + if(extract__exe_from_memfd(exe_file)) { flags |= PPM_EXE_FROM_MEMFD; } @@ -263,21 +244,16 @@ int BPF_PROG(t1_execve_x, extract__ino_from_inode(exe_inode, &ino); auxmap__store_u64_param(auxmap, ino); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ - struct timespec64 time = { 0, 0 }; - if(bpf_core_field_exists(exe_inode->i_ctime)) - { + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ + struct timespec64 time = {0, 0}; + if(bpf_core_field_exists(exe_inode->i_ctime)) { BPF_CORE_READ_INTO(&time, exe_inode, i_ctime); - } - else - { + } else { struct inode___v6_6 *exe_inode_v6_6 = (void *)exe_inode; - if(bpf_core_field_exists(exe_inode_v6_6->__i_ctime)) - { + if(bpf_core_field_exists(exe_inode_v6_6->__i_ctime)) { BPF_CORE_READ_INTO(&time, exe_inode_v6_6, __i_ctime); - } - else - { + } else { struct inode___v6_11 *exe_inode_v6_11 = (void *)exe_inode; BPF_CORE_READ_INTO(&time.tv_sec, exe_inode_v6_11, i_ctime_sec); BPF_CORE_READ_INTO(&time.tv_nsec, exe_inode_v6_11, i_ctime_nsec); @@ -285,20 +261,15 @@ int BPF_PROG(t1_execve_x, } auxmap__store_u64_param(auxmap, extract__epoch_ns_from_time(time)); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ - if(bpf_core_field_exists(exe_inode->i_mtime)) - { + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ + if(bpf_core_field_exists(exe_inode->i_mtime)) { BPF_CORE_READ_INTO(&time, exe_inode, i_mtime); - } - else - { + } else { struct inode___v6_7 *exe_inode_v6_7 = (void *)exe_inode; - if(bpf_core_field_exists(exe_inode_v6_7->__i_mtime)) - { + if(bpf_core_field_exists(exe_inode_v6_7->__i_mtime)) { BPF_CORE_READ_INTO(&time, exe_inode_v6_7, __i_mtime); - } - else - { + } else { struct inode___v6_11 *exe_inode_v6_11 = (void *)exe_inode; BPF_CORE_READ_INTO(&time.tv_sec, exe_inode_v6_11, i_mtime_sec); BPF_CORE_READ_INTO(&time.tv_nsec, exe_inode_v6_11, i_mtime_nsec); @@ -318,11 +289,9 @@ int BPF_PROG(t1_execve_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t2_execve_x, struct pt_regs *regs, long ret) -{ +int BPF_PROG(t2_execve_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -332,12 +301,9 @@ int BPF_PROG(t2_execve_x, struct pt_regs *regs, long ret) struct file *exe_file = extract__exe_file_from_task(task); /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ - if(exe_file != NULL) - { + if(exe_file != NULL) { auxmap__store_d_path_approx(auxmap, &(exe_file->f_path)); - } - else - { + } else { auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execveat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execveat.bpf.c index 19fdc766b7..38174f9628 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execveat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/execveat.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(execveat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(execveat_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_EXECVEAT_E); @@ -26,8 +22,7 @@ int BPF_PROG(execveat_e, /* Parameter 1: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -58,26 +53,21 @@ int BPF_PROG(execveat_e, * the call is successful. */ SEC("tp_btf/sys_exit") -int BPF_PROG(execveat_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(execveat_x, struct pt_regs *regs, long ret) { /* On some recent kernels the execve/execveat issue is solved: * https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?h=linux-5.15.y&id=42eede3ae05bbf32cb0d87940b466ec5a76aca3f - * BTW we already catch the event with our `sched_process_exec` tracepoint, for this reason we don't need also this instrumentation. - * Please note that we still need to catch the syscall failure for this reason we check the `ret==0`. + * BTW we already catch the event with our `sched_process_exec` tracepoint, for this reason we don't + * need also this instrumentation. Please note that we still need to catch the syscall failure for + * this reason we check the `ret==0`. */ #ifdef CAPTURE_SCHED_PROC_EXEC - if(ret == 0) - { + if(ret == 0) { return 0; } #endif struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_EXECVEAT_X); @@ -92,8 +82,7 @@ int BPF_PROG(execveat_x, /* In case of success we take `exe` and `args` directly from the kernel * otherwise we get them from the syscall arguments. */ - if(ret == 0) - { + if(ret == 0) { unsigned long arg_start_pointer = 0; unsigned long arg_end_pointer = 0; @@ -105,15 +94,16 @@ int BPF_PROG(execveat_x, READ_TASK_FIELD_INTO(&arg_end_pointer, task, mm, arg_end); /* Parameter 2: exe (type: PT_CHARBUF) */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, - total_args_len - exe_arg_len, MAX_PROC_ARG_ENV - exe_arg_len); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); + } else { unsigned long argv = extract__syscall_argument(regs, 2); /* Parameter 2: exe (type: PT_CHARBUF) */ @@ -183,13 +173,9 @@ int BPF_PROG(execveat_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t1_execveat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t1_execveat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -203,8 +189,7 @@ int BPF_PROG(t1_execveat_x, /* In case of success we take `env` directly from the kernel * otherwise we get them from the syscall arguments. */ - if(ret == 0) - { + if(ret == 0) { unsigned long env_start_pointer = 0; unsigned long env_end_pointer = 0; @@ -212,11 +197,11 @@ int BPF_PROG(t1_execveat_x, READ_TASK_FIELD_INTO(&env_end_pointer, task, mm, env_end); /* Parameter 16: env (type: PT_CHARBUFARRAY) */ - auxmap__store_charbufarray_as_bytebuf(auxmap, env_start_pointer, env_end_pointer - env_start_pointer, - MAX_PROC_ARG_ENV); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + env_start_pointer, + env_end_pointer - env_start_pointer, + MAX_PROC_ARG_ENV); + } else { /* Parameter 16: env (type: PT_CHARBUFARRAY) */ unsigned long envp = extract__syscall_argument(regs, 3); auxmap__store_env_failure(auxmap, (char **)envp); @@ -240,21 +225,16 @@ int BPF_PROG(t1_execveat_x, struct inode *exe_inode = extract__exe_inode_from_task(task); struct file *exe_file = extract__exe_file_from_task(task); - if(extract__exe_writable(task, exe_inode)) - { + if(extract__exe_writable(task, exe_inode)) { flags |= PPM_EXE_WRITABLE; } enum ppm_overlay overlay = extract__overlay_layer(exe_file); - if(overlay == PPM_OVERLAY_UPPER) - { + if(overlay == PPM_OVERLAY_UPPER) { flags |= PPM_EXE_UPPER_LAYER; - } - else if (overlay == PPM_OVERLAY_LOWER) - { + } else if(overlay == PPM_OVERLAY_LOWER) { flags |= PPM_EXE_LOWER_LAYER; } - if(extract__exe_from_memfd(exe_file)) - { + if(extract__exe_from_memfd(exe_file)) { flags |= PPM_EXE_FROM_MEMFD; } auxmap__store_u32_param(auxmap, flags); @@ -276,21 +256,16 @@ int BPF_PROG(t1_execveat_x, extract__ino_from_inode(exe_inode, &ino); auxmap__store_u64_param(auxmap, ino); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ - struct timespec64 time = { 0, 0 }; - if(bpf_core_field_exists(exe_inode->i_ctime)) - { + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ + struct timespec64 time = {0, 0}; + if(bpf_core_field_exists(exe_inode->i_ctime)) { BPF_CORE_READ_INTO(&time, exe_inode, i_ctime); - } - else - { + } else { struct inode___v6_6 *exe_inode_v6_6 = (void *)exe_inode; - if(bpf_core_field_exists(exe_inode_v6_6->__i_ctime)) - { + if(bpf_core_field_exists(exe_inode_v6_6->__i_ctime)) { BPF_CORE_READ_INTO(&time, exe_inode_v6_6, __i_ctime); - } - else - { + } else { struct inode___v6_11 *exe_inode_v6_11 = (void *)exe_inode; BPF_CORE_READ_INTO(&time.tv_sec, exe_inode_v6_11, i_ctime_sec); BPF_CORE_READ_INTO(&time.tv_nsec, exe_inode_v6_11, i_ctime_nsec); @@ -298,20 +273,15 @@ int BPF_PROG(t1_execveat_x, } auxmap__store_u64_param(auxmap, extract__epoch_ns_from_time(time)); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ - if(bpf_core_field_exists(exe_inode->i_mtime)) - { + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ + if(bpf_core_field_exists(exe_inode->i_mtime)) { BPF_CORE_READ_INTO(&time, exe_inode, i_mtime); - } - else - { + } else { struct inode___v6_7 *exe_inode_v6_7 = (void *)exe_inode; - if(bpf_core_field_exists(exe_inode_v6_7->__i_mtime)) - { + if(bpf_core_field_exists(exe_inode_v6_7->__i_mtime)) { BPF_CORE_READ_INTO(&time, exe_inode_v6_7, __i_mtime); - } - else - { + } else { struct inode___v6_11 *exe_inode_v6_11 = (void *)exe_inode; BPF_CORE_READ_INTO(&time.tv_sec, exe_inode_v6_11, i_mtime_sec); BPF_CORE_READ_INTO(&time.tv_nsec, exe_inode_v6_11, i_mtime_nsec); @@ -331,11 +301,9 @@ int BPF_PROG(t1_execveat_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t2_execveat_x, struct pt_regs *regs, long ret) -{ +int BPF_PROG(t2_execveat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -345,12 +313,9 @@ int BPF_PROG(t2_execveat_x, struct pt_regs *regs, long ret) struct file *exe_file = extract__exe_file_from_task(task); /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ - if(exe_file != NULL) - { + if(exe_file != NULL) { auxmap__store_d_path_approx(auxmap, &(exe_file->f_path)); - } - else - { + } else { auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchdir.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchdir.bpf.c index 81d5ba2023..8d348f959f 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchdir.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchdir.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fchdir_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fchdir_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHDIR_E_SIZE, PPME_SYSCALL_FCHDIR_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHDIR_E_SIZE, PPME_SYSCALL_FCHDIR_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(fchdir_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fchdir_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(fchdir_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHDIR_X_SIZE, PPME_SYSCALL_FCHDIR_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHDIR_X_SIZE, PPME_SYSCALL_FCHDIR_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmod.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmod.bpf.c index cbe958ed21..0be335b573 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmod.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmod.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fchmod_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fchmod_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHMOD_E_SIZE, PPME_SYSCALL_FCHMOD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHMOD_E_SIZE, PPME_SYSCALL_FCHMOD_E)) { return 0; } @@ -39,14 +35,9 @@ int BPF_PROG(fchmod_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fchmod_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(fchmod_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHMOD_X_SIZE, PPME_SYSCALL_FCHMOD_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHMOD_X_SIZE, PPME_SYSCALL_FCHMOD_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmodat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmodat.bpf.c index 516d6e6e22..929b3bccb0 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmodat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchmodat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fchmodat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fchmodat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHMODAT_E_SIZE, PPME_SYSCALL_FCHMODAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHMODAT_E_SIZE, PPME_SYSCALL_FCHMODAT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(fchmodat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fchmodat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(fchmodat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(fchmodat_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchown.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchown.bpf.c index 096af6d5fe..bbfeddfbde 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchown.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchown.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fchown_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fchown_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHOWN_E_SIZE, PPME_SYSCALL_FCHOWN_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHOWN_E_SIZE, PPME_SYSCALL_FCHOWN_E)) { return 0; } @@ -39,14 +35,9 @@ int BPF_PROG(fchown_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fchown_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(fchown_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHOWN_X_SIZE, PPME_SYSCALL_FCHOWN_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHOWN_X_SIZE, PPME_SYSCALL_FCHOWN_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchownat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchownat.bpf.c index c668d54033..f3c703e61f 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchownat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fchownat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fchownat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fchownat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCHOWNAT_E_SIZE, PPME_SYSCALL_FCHOWNAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCHOWNAT_E_SIZE, PPME_SYSCALL_FCHOWNAT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(fchownat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fchownat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(fchownat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(fchownat_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fcntl.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fcntl.bpf.c index d913d74658..8ab8c29aac 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fcntl.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fcntl.bpf.c @@ -8,11 +8,9 @@ #include -static __always_inline bool check_fcntl_dropping(struct pt_regs *regs) -{ +static __always_inline bool check_fcntl_dropping(struct pt_regs *regs) { int cmd = (int32_t)extract__syscall_argument(regs, 1); - if(cmd != F_DUPFD && cmd != F_DUPFD_CLOEXEC) - { + if(cmd != F_DUPFD && cmd != F_DUPFD_CLOEXEC) { return true; } return false; @@ -21,18 +19,13 @@ static __always_inline bool check_fcntl_dropping(struct pt_regs *regs) /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fcntl_e, - struct pt_regs *regs, - long id) -{ - if(maps__get_dropping_mode() && check_fcntl_dropping(regs)) - { +int BPF_PROG(fcntl_e, struct pt_regs *regs, long id) { + if(maps__get_dropping_mode() && check_fcntl_dropping(regs)) { return 0; } struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCNTL_E_SIZE, PPME_SYSCALL_FCNTL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCNTL_E_SIZE, PPME_SYSCALL_FCNTL_E)) { return 0; } @@ -60,18 +53,13 @@ int BPF_PROG(fcntl_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fcntl_x, - struct pt_regs *regs, - long ret) -{ - if(maps__get_dropping_mode() && check_fcntl_dropping(regs)) - { +int BPF_PROG(fcntl_x, struct pt_regs *regs, long ret) { + if(maps__get_dropping_mode() && check_fcntl_dropping(regs)) { return 0; } struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FCNTL_X_SIZE, PPME_SYSCALL_FCNTL_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FCNTL_X_SIZE, PPME_SYSCALL_FCNTL_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/finit_module.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/finit_module.bpf.c index 67a06e3b94..924a39bd98 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/finit_module.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/finit_module.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(finit_module_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(finit_module_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FINIT_MODULE_E_SIZE, PPME_SYSCALL_FINIT_MODULE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FINIT_MODULE_E_SIZE, PPME_SYSCALL_FINIT_MODULE_E)) { return 0; } @@ -33,8 +29,6 @@ int BPF_PROG(finit_module_e, ringbuf__submit_event(&ringbuf); return 0; - - } /*=============================== ENTER EVENT ===========================*/ @@ -42,13 +36,9 @@ int BPF_PROG(finit_module_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(finit_module_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(finit_module_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -71,7 +61,6 @@ int BPF_PROG(finit_module_x, uint32_t flags = extract__syscall_argument(regs, 2); auxmap__store_s32_param(auxmap, finit_module_flags_to_scap(flags)); - /*=============================== COLLECT PARAMETERS ===========================*/ auxmap__finalize_event_header(auxmap); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/flock.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/flock.bpf.c index 4260238471..a5c350286b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/flock.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/flock.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(flock_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(flock_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FLOCK_E_SIZE, PPME_SYSCALL_FLOCK_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FLOCK_E_SIZE, PPME_SYSCALL_FLOCK_E)) { return 0; } @@ -31,7 +27,7 @@ int BPF_PROG(flock_e, /* Parameter 2: operation (type: PT_FLAGS32) */ unsigned long operation = extract__syscall_argument(regs, 1); - ringbuf__store_u32(&ringbuf, flock_flags_to_scap((int) operation)); + ringbuf__store_u32(&ringbuf, flock_flags_to_scap((int)operation)); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -45,13 +41,9 @@ int BPF_PROG(flock_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(flock_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(flock_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FLOCK_X_SIZE, PPME_SYSCALL_FLOCK_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FLOCK_X_SIZE, PPME_SYSCALL_FLOCK_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fork.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fork.bpf.c index 00d24543da..87d870fb08 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fork.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fork.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fork_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fork_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FORK_E_SIZE, PPME_SYSCALL_FORK_20_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FORK_E_SIZE, PPME_SYSCALL_FORK_20_E)) { return 0; } @@ -40,26 +36,20 @@ int BPF_PROG(fork_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fork_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(fork_x, struct pt_regs *regs, long ret) { /* We already catch the fork child event with our `sched_process_fork` tracepoint, * for this reason we don't need also this instrumentation. Please note that we use * the aforementioned tracepoint only for the child event but we need to catch also * the father event or the failure case, for this reason we check the `ret==0` */ #ifdef CAPTURE_SCHED_PROC_FORK - if(ret == 0) - { + if(ret == 0) { return 0; } #endif struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_FORK_20_X); @@ -74,8 +64,7 @@ int BPF_PROG(fork_x, /* We can extract `exe` (Parameter 2) and `args`(Parameter 3) only if the * syscall doesn't fail. Otherwise, they will send empty parameters. */ - if(ret >= 0) - { + if(ret >= 0) { unsigned long arg_start_pointer = 0; unsigned long arg_end_pointer = 0; @@ -89,15 +78,16 @@ int BPF_PROG(fork_x, READ_TASK_FIELD_INTO(&arg_end_pointer, task, mm, arg_end); /* Parameter 2: exe (type: PT_CHARBUF) */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, - total_args_len - exe_arg_len, MAX_PROC_ARG_ENV - exe_arg_len); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); + } else { /* Parameter 2: exe (type: PT_CHARBUF) */ auxmap__store_empty_param(auxmap); @@ -167,13 +157,9 @@ int BPF_PROG(fork_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t1_fork_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t1_fork_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -217,13 +203,9 @@ int BPF_PROG(t1_fork_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t2_fork_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t2_fork_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fsconfig.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fsconfig.bpf.c index 89c1a1a1cc..d1facea82d 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fsconfig.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fsconfig.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fsconfig_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fsconfig_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FSCONFIG_E_SIZE, PPME_SYSCALL_FSCONFIG_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FSCONFIG_E_SIZE, PPME_SYSCALL_FSCONFIG_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(fsconfig_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fsconfig_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(fsconfig_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -73,8 +65,7 @@ int BPF_PROG(fsconfig_x, int aux = extract__syscall_argument(regs, 4); - if(ret < 0) - { + if(ret < 0) { /* If the syscall fails we push empty params to userspace. */ /* Parameter 5: value_bytebuf (type: PT_BYTEBUF) */ @@ -82,15 +73,13 @@ int BPF_PROG(fsconfig_x, /* Parameter 6: value_charbuf (type: PT_CHARBUF) */ auxmap__store_empty_param(auxmap); - } - else - { + } else { unsigned long value_pointer = extract__syscall_argument(regs, 3); - /* According to the command we need to understand what value we have to push to userspace. */ + /* According to the command we need to understand what value we have to push to userspace. + */ /* see https://elixir.bootlin.com/linux/latest/source/fs/fsopen.c#L271 */ - switch(scap_cmd) - { + switch(scap_cmd) { case PPM_FSCONFIG_SET_FLAG: case PPM_FSCONFIG_SET_FD: case PPM_FSCONFIG_CMD_CREATE: diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fstat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fstat.bpf.c index 469dcbf4d4..ab899a37d4 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fstat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/fstat.bpf.c @@ -6,19 +6,14 @@ * or GPL2.txt for full copies of the license. */ - #include /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(fstat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(fstat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FSTAT_E_SIZE, PPME_SYSCALL_FSTAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FSTAT_E_SIZE, PPME_SYSCALL_FSTAT_E)) { return 0; } @@ -42,13 +37,9 @@ int BPF_PROG(fstat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(fstat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(fstat_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FSTAT_X_SIZE, PPME_SYSCALL_FSTAT_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FSTAT_X_SIZE, PPME_SYSCALL_FSTAT_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/futex.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/futex.bpf.c index 02fd3974d5..c901387355 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/futex.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/futex.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(futex_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(futex_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FUTEX_E_SIZE, PPME_SYSCALL_FUTEX_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FUTEX_E_SIZE, PPME_SYSCALL_FUTEX_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(futex_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(futex_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(futex_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, FUTEX_X_SIZE, PPME_SYSCALL_FUTEX_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, FUTEX_X_SIZE, PPME_SYSCALL_FUTEX_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/generic.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/generic.bpf.c index 47705685fd..9975816d7b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/generic.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/generic.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(generic_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(generic_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GENERIC_E_SIZE, PPME_GENERIC_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GENERIC_E_SIZE, PPME_GENERIC_E)) { return 0; } @@ -30,8 +26,7 @@ int BPF_PROG(generic_e, // validated the converted 32bit->64bit syscall ID for us, // otherwise the event would've been discarded. #if defined(__TARGET_ARCH_x86) - if(bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { id = maps__ia32_to_64(id); } #endif @@ -55,13 +50,9 @@ int BPF_PROG(generic_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(generic_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(generic_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GENERIC_X_SIZE, PPME_GENERIC_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GENERIC_X_SIZE, PPME_GENERIC_X)) { return 0; } @@ -75,8 +66,7 @@ int BPF_PROG(generic_x, // validated the converted 32bit->64bit syscall ID for us, // otherwise the event would've been discarded. #if defined(__TARGET_ARCH_x86) - if(bpf_in_ia32_syscall()) - { + if(bpf_in_ia32_syscall()) { id = maps__ia32_to_64(id); } #endif diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getcwd.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getcwd.bpf.c index 3e3fc37e2d..68003a4706 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getcwd.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getcwd.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getcwd_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(getcwd_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETCWD_E_SIZE, PPME_SYSCALL_GETCWD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETCWD_E_SIZE, PPME_SYSCALL_GETCWD_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(getcwd_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getcwd_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getcwd_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -57,15 +49,13 @@ int BPF_PROG(getcwd_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - /* we get the path only in case of success, in case of failure we would read only userspace junk */ - if(ret >= 0) - { + /* we get the path only in case of success, in case of failure we would read only userspace junk + */ + if(ret >= 0) { /* Parameter 2: path (type: PT_CHARBUF) */ unsigned long path_pointer = extract__syscall_argument(regs, 0); auxmap__store_charbuf_param(auxmap, path_pointer, MAX_PATH, USER); - } - else - { + } else { /* Parameter 2: path (type: PT_CHARBUF) */ auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents.bpf.c index ca877c10f6..ccf832b8c5 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getdents_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(getdents_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS_E_SIZE, PPME_SYSCALL_GETDENTS_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS_E_SIZE, PPME_SYSCALL_GETDENTS_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(getdents_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getdents_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getdents_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS_X_SIZE, PPME_SYSCALL_GETDENTS_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS_X_SIZE, PPME_SYSCALL_GETDENTS_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents64.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents64.bpf.c index adacc19e6f..3ec34d142c 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents64.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getdents64.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getdents64_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(getdents64_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS64_E_SIZE, PPME_SYSCALL_GETDENTS64_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS64_E_SIZE, PPME_SYSCALL_GETDENTS64_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(getdents64_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getdents64_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getdents64_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS64_X_SIZE, PPME_SYSCALL_GETDENTS64_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETDENTS64_X_SIZE, PPME_SYSCALL_GETDENTS64_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getegid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getegid.bpf.c index 1e9f5ef9db..d45e721ed2 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getegid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getegid.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getegid_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETEGID_E_SIZE, PPME_SYSCALL_GETEGID_E)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getegid_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETEGID_E_SIZE, PPME_SYSCALL_GETEGID_E)) { + return 0; + } + + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -37,23 +33,18 @@ int BPF_PROG(getegid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getegid_x, - struct pt_regs *regs, - long ret) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETEGID_X_SIZE, PPME_SYSCALL_GETEGID_X)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getegid_x, struct pt_regs *regs, long ret) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETEGID_X_SIZE, PPME_SYSCALL_GETEGID_X)) { + return 0; + } + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: egid (type: PT_GID) */ - ringbuf__store_u32(&ringbuf, (uint32_t)ret); + /* Parameter 1: egid (type: PT_GID) */ + ringbuf__store_u32(&ringbuf, (uint32_t)ret); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/geteuid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/geteuid.bpf.c index 61dac4a222..aebbff35ae 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/geteuid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/geteuid.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(geteuid_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETEUID_E_SIZE, PPME_SYSCALL_GETEUID_E)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(geteuid_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETEUID_E_SIZE, PPME_SYSCALL_GETEUID_E)) { + return 0; + } + + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -37,23 +33,18 @@ int BPF_PROG(geteuid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(geteuid_x, - struct pt_regs *regs, - long ret) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETEUID_X_SIZE, PPME_SYSCALL_GETEUID_X)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(geteuid_x, struct pt_regs *regs, long ret) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETEUID_X_SIZE, PPME_SYSCALL_GETEUID_X)) { + return 0; + } + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: euid (type: PT_UID) */ - ringbuf__store_u32(&ringbuf, (uint32_t)ret); + /* Parameter 1: euid (type: PT_UID) */ + ringbuf__store_u32(&ringbuf, (uint32_t)ret); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getgid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getgid.bpf.c index 2f73342a9d..d24fa144c9 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getgid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getgid.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getgid_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETGID_E_SIZE, PPME_SYSCALL_GETGID_E)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getgid_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETGID_E_SIZE, PPME_SYSCALL_GETGID_E)) { + return 0; + } + + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -37,23 +33,18 @@ int BPF_PROG(getgid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getgid_x, - struct pt_regs *regs, - long ret) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETGID_X_SIZE, PPME_SYSCALL_GETGID_X)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getgid_x, struct pt_regs *regs, long ret) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETGID_X_SIZE, PPME_SYSCALL_GETGID_X)) { + return 0; + } + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: gid (type: PT_GID) */ - ringbuf__store_u32(&ringbuf, (uint32_t)ret); + /* Parameter 1: gid (type: PT_GID) */ + ringbuf__store_u32(&ringbuf, (uint32_t)ret); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getpeername.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getpeername.bpf.c index 9550a63711..7162d5da48 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getpeername.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getpeername.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getpeername_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(getpeername_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETPEERNAME_E_SIZE, PPME_SOCKET_GETPEERNAME_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETPEERNAME_E_SIZE, PPME_SOCKET_GETPEERNAME_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(getpeername_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getpeername_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getpeername_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETPEERNAME_X_SIZE, PPME_SOCKET_GETPEERNAME_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETPEERNAME_X_SIZE, PPME_SOCKET_GETPEERNAME_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresgid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresgid.bpf.c index eff2a8030d..c591a96768 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresgid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresgid.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getresgid_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESGID_E_SIZE, PPME_SYSCALL_GETRESGID_E)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getresgid_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESGID_E_SIZE, PPME_SYSCALL_GETRESGID_E)) { + return 0; + } + + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -37,21 +33,17 @@ int BPF_PROG(getresgid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getresgid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getresgid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESGID_X_SIZE, PPME_SYSCALL_GETRESGID_X)) - { - return 0; - } + if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESGID_X_SIZE, PPME_SYSCALL_GETRESGID_X)) { + return 0; + } ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ + /* Parameter 1: res (type: PT_ERRNO) */ ringbuf__store_s64(&ringbuf, ret); /* Parameter 2: rgid (type: PT_GID) */ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresuid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresuid.bpf.c index 45e21dc653..3d013d91c1 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresuid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getresuid.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getresuid_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESUID_E_SIZE, PPME_SYSCALL_GETRESUID_E)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getresuid_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESUID_E_SIZE, PPME_SYSCALL_GETRESUID_E)) { + return 0; + } + + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -37,21 +33,17 @@ int BPF_PROG(getresuid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getresuid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getresuid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESUID_X_SIZE, PPME_SYSCALL_GETRESUID_X)) - { - return 0; - } + if(!ringbuf__reserve_space(&ringbuf, ctx, GETRESUID_X_SIZE, PPME_SYSCALL_GETRESUID_X)) { + return 0; + } ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ + /* Parameter 1: res (type: PT_ERRNO) */ ringbuf__store_s64(&ringbuf, ret); /* Parameter 2: ruid (type: PT_UID) */ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getrlimit.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getrlimit.bpf.c index eb6971a7b1..51a4a6c0d4 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getrlimit.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getrlimit.bpf.c @@ -13,13 +13,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getrlimit_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(getrlimit_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETRLIMIT_E_SIZE, PPME_SYSCALL_GETRLIMIT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETRLIMIT_E_SIZE, PPME_SYSCALL_GETRLIMIT_E)) { return 0; } @@ -43,13 +39,9 @@ int BPF_PROG(getrlimit_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getrlimit_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getrlimit_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETRLIMIT_X_SIZE, PPME_SYSCALL_GETRLIMIT_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETRLIMIT_X_SIZE, PPME_SYSCALL_GETRLIMIT_X)) { return 0; } @@ -61,8 +53,7 @@ int BPF_PROG(getrlimit_x, ringbuf__store_s64(&ringbuf, ret); /* We get the kernel values only if the syscall is successful otherwise we return -1. */ - if(ret == 0) - { + if(ret == 0) { struct rlimit rl = {0}; unsigned long rlimit_pointer = extract__syscall_argument(regs, 1); bpf_probe_read_user((void *)&rl, bpf_core_type_size(struct rlimit), (void *)rlimit_pointer); @@ -72,9 +63,7 @@ int BPF_PROG(getrlimit_x, /* Parameter 3: max (type: PT_INT64)*/ ringbuf__store_s64(&ringbuf, rl.rlim_max); - } - else - { + } else { /* Parameter 2: cur (type: PT_INT64)*/ ringbuf__store_s64(&ringbuf, -1); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockname.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockname.bpf.c index 96628a51cc..cc3c0e6197 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockname.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockname.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getsockname_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(getsockname_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETSOCKNAME_E_SIZE, PPME_SOCKET_GETSOCKNAME_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETSOCKNAME_E_SIZE, PPME_SOCKET_GETSOCKNAME_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(getsockname_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getsockname_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getsockname_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETSOCKNAME_X_SIZE, PPME_SOCKET_GETSOCKNAME_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETSOCKNAME_X_SIZE, PPME_SOCKET_GETSOCKNAME_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockopt.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockopt.bpf.c index 626f769872..f2643c07f1 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockopt.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getsockopt.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getsockopt_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(getsockopt_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETSOCKOPT_E_SIZE, PPME_SOCKET_GETSOCKOPT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, GETSOCKOPT_E_SIZE, PPME_SOCKET_GETSOCKOPT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(getsockopt_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getsockopt_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(getsockopt_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getuid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getuid.bpf.c index 297f22fa04..461d18c15a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getuid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/getuid.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(getuid_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETUID_E_SIZE, PPME_SYSCALL_GETUID_E)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getuid_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETUID_E_SIZE, PPME_SYSCALL_GETUID_E)) { + return 0; + } + + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -37,23 +33,18 @@ int BPF_PROG(getuid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(getuid_x, - struct pt_regs *regs, - long ret) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, GETUID_X_SIZE, PPME_SYSCALL_GETUID_X)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(getuid_x, struct pt_regs *regs, long ret) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, GETUID_X_SIZE, PPME_SYSCALL_GETUID_X)) { + return 0; + } + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: uid (type: PT_UID) */ - ringbuf__store_u32(&ringbuf, (uint32_t)ret); + /* Parameter 1: uid (type: PT_UID) */ + ringbuf__store_u32(&ringbuf, (uint32_t)ret); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/init_module.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/init_module.bpf.c index 31320f2208..cec78a40dc 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/init_module.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/init_module.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(init_module_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(init_module_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, INIT_MODULE_E_SIZE, PPME_SYSCALL_INIT_MODULE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, INIT_MODULE_E_SIZE, PPME_SYSCALL_INIT_MODULE_E)) { return 0; } @@ -33,8 +29,6 @@ int BPF_PROG(init_module_e, ringbuf__submit_event(&ringbuf); return 0; - - } /*=============================== ENTER EVENT ===========================*/ @@ -42,13 +36,9 @@ int BPF_PROG(init_module_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(init_module_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(init_module_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -72,7 +62,6 @@ int BPF_PROG(init_module_x, unsigned long uargs_ptr = extract__syscall_argument(regs, 2); auxmap__store_charbuf_param(auxmap, uargs_ptr, MAX_PROC_ARG_ENV, USER); - /*=============================== COLLECT PARAMETERS ===========================*/ auxmap__finalize_event_header(auxmap); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init.bpf.c index bf2d295f3c..de95403feb 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(inotify_init_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(inotify_init_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT_E_SIZE, PPME_SYSCALL_INOTIFY_INIT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT_E_SIZE, PPME_SYSCALL_INOTIFY_INIT_E)) { return 0; } @@ -44,13 +40,9 @@ int BPF_PROG(inotify_init_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(inotify_init_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(inotify_init_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT_X_SIZE, PPME_SYSCALL_INOTIFY_INIT_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT_X_SIZE, PPME_SYSCALL_INOTIFY_INIT_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init1.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init1.bpf.c index 549fa2db4c..6dc0d1da11 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init1.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/inotify_init1.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(inotify_init1_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(inotify_init1_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT1_E_SIZE, PPME_SYSCALL_INOTIFY_INIT1_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT1_E_SIZE, PPME_SYSCALL_INOTIFY_INIT1_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(inotify_init1_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(inotify_init1_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(inotify_init1_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT1_X_SIZE, PPME_SYSCALL_INOTIFY_INIT1_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, INOTIFY_INIT1_X_SIZE, PPME_SYSCALL_INOTIFY_INIT1_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_enter.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_enter.bpf.c index 04d31f389d..6371213cf7 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_enter.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_enter.bpf.c @@ -11,13 +11,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(io_uring_enter_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(io_uring_enter_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IO_URING_ENTER_E_SIZE, PPME_SYSCALL_IO_URING_ENTER_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + IO_URING_ENTER_E_SIZE, + PPME_SYSCALL_IO_URING_ENTER_E)) { return 0; } @@ -39,13 +38,12 @@ int BPF_PROG(io_uring_enter_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(io_uring_enter_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(io_uring_enter_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IO_URING_ENTER_X_SIZE, PPME_SYSCALL_IO_URING_ENTER_X)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + IO_URING_ENTER_X_SIZE, + PPME_SYSCALL_IO_URING_ENTER_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_register.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_register.bpf.c index a931339efd..cc9058394b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_register.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_register.bpf.c @@ -11,13 +11,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(io_uring_register_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(io_uring_register_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IO_URING_REGISTER_E_SIZE, PPME_SYSCALL_IO_URING_REGISTER_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + IO_URING_REGISTER_E_SIZE, + PPME_SYSCALL_IO_URING_REGISTER_E)) { return 0; } @@ -39,13 +38,12 @@ int BPF_PROG(io_uring_register_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(io_uring_register_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(io_uring_register_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IO_URING_REGISTER_X_SIZE, PPME_SYSCALL_IO_URING_REGISTER_X)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + IO_URING_REGISTER_X_SIZE, + PPME_SYSCALL_IO_URING_REGISTER_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_setup.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_setup.bpf.c index b4af1e70af..9fa8bc49f8 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_setup.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/io_uring_setup.bpf.c @@ -11,13 +11,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(io_uring_setup_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(io_uring_setup_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IO_URING_SETUP_E_SIZE, PPME_SYSCALL_IO_URING_SETUP_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + IO_URING_SETUP_E_SIZE, + PPME_SYSCALL_IO_URING_SETUP_E)) { return 0; } @@ -39,13 +38,12 @@ int BPF_PROG(io_uring_setup_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(io_uring_setup_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(io_uring_setup_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IO_URING_SETUP_X_SIZE, PPME_SYSCALL_IO_URING_SETUP_X)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + IO_URING_SETUP_X_SIZE, + PPME_SYSCALL_IO_URING_SETUP_X)) { return 0; } @@ -66,11 +64,12 @@ int BPF_PROG(io_uring_setup_x, * `struct io_uring_params` defined in their vmlinux, for this reason, we send * empty params. */ - if(bpf_core_type_exists(struct io_uring_params)) - { + if(bpf_core_type_exists(struct io_uring_params)) { unsigned long params_pointer = extract__syscall_argument(regs, 1); struct io_uring_params params = {0}; - bpf_probe_read_user((void *)¶ms, bpf_core_type_size(struct io_uring_params), (void *)params_pointer); + bpf_probe_read_user((void *)¶ms, + bpf_core_type_size(struct io_uring_params), + (void *)params_pointer); /* Parameter 3: sq_entries (type: PT_UINT32) */ ringbuf__store_u32(&ringbuf, params.sq_entries); @@ -89,9 +88,7 @@ int BPF_PROG(io_uring_setup_x, /* Parameter 8: features (type: PT_FLAGS32) */ ringbuf__store_u32(&ringbuf, (uint32_t)io_uring_setup_feats_to_scap(params.features)); - } - else - { + } else { /* Parameter 3: sq_entries (type: PT_UINT32) */ ringbuf__store_u32(&ringbuf, 0); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ioctl.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ioctl.bpf.c index 83800d0ae2..b70ea3cf95 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ioctl.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ioctl.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(ioctl_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(ioctl_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IOCTL_E_SIZE, PPME_SYSCALL_IOCTL_3_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, IOCTL_E_SIZE, PPME_SYSCALL_IOCTL_3_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(ioctl_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(ioctl_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(ioctl_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, IOCTL_X_SIZE, PPME_SYSCALL_IOCTL_3_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, IOCTL_X_SIZE, PPME_SYSCALL_IOCTL_3_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/kill.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/kill.bpf.c index 6c9b2bbaa9..a16f7f5780 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/kill.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/kill.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(kill_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(kill_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, KILL_E_SIZE, PPME_SYSCALL_KILL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, KILL_E_SIZE, PPME_SYSCALL_KILL_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(kill_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(kill_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(kill_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, KILL_X_SIZE, PPME_SYSCALL_KILL_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, KILL_X_SIZE, PPME_SYSCALL_KILL_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lchown.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lchown.bpf.c index 0ac5298888..5af19d6f17 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lchown.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lchown.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(lchown_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(lchown_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LCHOWN_E_SIZE, PPME_SYSCALL_LCHOWN_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LCHOWN_E_SIZE, PPME_SYSCALL_LCHOWN_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(lchown_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(lchown_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(lchown_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/link.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/link.bpf.c index 782648b1ed..7017d509ce 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/link.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/link.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(link_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(link_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LINK_E_SIZE, PPME_SYSCALL_LINK_2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LINK_E_SIZE, PPME_SYSCALL_LINK_2_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(link_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(link_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(link_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/linkat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/linkat.bpf.c index e3797186c6..ec1879c0e8 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/linkat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/linkat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(linkat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(linkat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LINKAT_E_SIZE, PPME_SYSCALL_LINKAT_2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LINKAT_E_SIZE, PPME_SYSCALL_LINKAT_2_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(linkat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(linkat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(linkat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(linkat_x, /* Parameter 2: olddirfd (type: PT_FD) */ int32_t olddirfd = (int32_t)extract__syscall_argument(regs, 0); - if(olddirfd == AT_FDCWD) - { + if(olddirfd == AT_FDCWD) { olddirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)olddirfd); @@ -71,8 +62,7 @@ int BPF_PROG(linkat_x, /* Parameter 4: newdirfd (type: PT_FD) */ int32_t newdirfd = (int32_t)extract__syscall_argument(regs, 2); - if(newdirfd == AT_FDCWD) - { + if(newdirfd == AT_FDCWD) { newdirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)newdirfd); @@ -83,7 +73,7 @@ int BPF_PROG(linkat_x, /* Parameter 6: flags (type: PT_FLAGS32) */ unsigned long flags = extract__syscall_argument(regs, 4); - auxmap__store_u32_param(auxmap, linkat_flags_to_scap((int32_t) flags)); + auxmap__store_u32_param(auxmap, linkat_flags_to_scap((int32_t)flags)); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/listen.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/listen.bpf.c index fe6a4369b2..d16483f291 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/listen.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/listen.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(listen_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(listen_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long args[2] = {0}; extract__network_args(args, 2, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LISTEN_E_SIZE, PPME_SOCKET_LISTEN_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LISTEN_E_SIZE, PPME_SOCKET_LISTEN_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(listen_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(listen_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(listen_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LISTEN_X_SIZE, PPME_SOCKET_LISTEN_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LISTEN_X_SIZE, PPME_SOCKET_LISTEN_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/llseek.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/llseek.bpf.c index 7730372dee..f34e0f188c 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/llseek.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/llseek.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(llseek_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(llseek_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LLSEEK_E_SIZE, PPME_SYSCALL_LLSEEK_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LLSEEK_E_SIZE, PPME_SYSCALL_LLSEEK_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(llseek_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(llseek_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(llseek_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LLSEEK_X_SIZE, PPME_SYSCALL_LLSEEK_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LLSEEK_X_SIZE, PPME_SYSCALL_LLSEEK_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lseek.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lseek.bpf.c index 8389c84b27..c2d0fb4203 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lseek.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lseek.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(lseek_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(lseek_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LSEEK_E_SIZE, PPME_SYSCALL_LSEEK_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LSEEK_E_SIZE, PPME_SYSCALL_LSEEK_E)) { return 0; } @@ -47,13 +43,9 @@ int BPF_PROG(lseek_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(lseek_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(lseek_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LSEEK_X_SIZE, PPME_SYSCALL_LSEEK_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LSEEK_X_SIZE, PPME_SYSCALL_LSEEK_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lstat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lstat.bpf.c index de066a9508..97d73c19ff 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lstat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/lstat.bpf.c @@ -6,20 +6,15 @@ * or GPL2.txt for full copies of the license. */ - #include #include /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(lstat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(lstat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, LSTAT_E_SIZE, PPME_SYSCALL_LSTAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, LSTAT_E_SIZE, PPME_SYSCALL_LSTAT_E)) { return 0; } @@ -41,13 +36,9 @@ int BPF_PROG(lstat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(lstat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(lstat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/memfd_create.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/memfd_create.bpf.c index 2536ec725d..0f5b7fa747 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/memfd_create.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/memfd_create.bpf.c @@ -12,17 +12,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(memfd_create_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MEMFD_CREATE_E_SIZE, PPME_SYSCALL_MEMFD_CREATE_E)) - { - return 0; - } - - ringbuf__store_event_header(&ringbuf); +int BPF_PROG(memfd_create_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, MEMFD_CREATE_E_SIZE, PPME_SYSCALL_MEMFD_CREATE_E)) { + return 0; + } + + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -38,37 +34,33 @@ int BPF_PROG(memfd_create_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(memfd_create_x, - struct pt_regs *regs, - long ret) -{ - struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { +int BPF_PROG(memfd_create_x, struct pt_regs *regs, long ret) { + struct auxiliary_map *auxmap = auxmap__get(); + if(!auxmap) { return 0; } - auxmap__preload_event_header(auxmap, PPME_SYSCALL_MEMFD_CREATE_X); + auxmap__preload_event_header(auxmap, PPME_SYSCALL_MEMFD_CREATE_X); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: ret (type: PT_FD) */ - auxmap__store_s64_param(auxmap, ret); + /* Parameter 1: ret (type: PT_FD) */ + auxmap__store_s64_param(auxmap, ret); - /* Parameter 2: file name (type: PT_CHARBUF) */ - unsigned long name_pointer = extract__syscall_argument(regs, 0); - auxmap__store_charbuf_param(auxmap, name_pointer, MAX_PATH, USER); + /* Parameter 2: file name (type: PT_CHARBUF) */ + unsigned long name_pointer = extract__syscall_argument(regs, 0); + auxmap__store_charbuf_param(auxmap, name_pointer, MAX_PATH, USER); - /* Parameter 3: flags (type: PT_FLAGS32) */ - uint32_t flags = (uint32_t)extract__syscall_argument(regs, 1); - auxmap__store_u32_param(auxmap, memfd_create_flags_to_scap(flags)); - /*=============================== COLLECT PARAMETERS ===========================*/ + /* Parameter 3: flags (type: PT_FLAGS32) */ + uint32_t flags = (uint32_t)extract__syscall_argument(regs, 1); + auxmap__store_u32_param(auxmap, memfd_create_flags_to_scap(flags)); + /*=============================== COLLECT PARAMETERS ===========================*/ - auxmap__finalize_event_header(auxmap); + auxmap__finalize_event_header(auxmap); - auxmap__submit_event(auxmap, ctx); + auxmap__submit_event(auxmap, ctx); - return 0; + return 0; } /*=============================== EXIT EVENT ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdir.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdir.bpf.c index 9818d052c5..8e5b13a9c1 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdir.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdir.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mkdir_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mkdir_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MKDIR_E_SIZE, PPME_SYSCALL_MKDIR_2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MKDIR_E_SIZE, PPME_SYSCALL_MKDIR_2_E)) { return 0; } @@ -42,13 +38,9 @@ int BPF_PROG(mkdir_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mkdir_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mkdir_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdirat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdirat.bpf.c index 3df5497b93..8d7245189e 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdirat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mkdirat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mkdirat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mkdirat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MKDIRAT_E_SIZE, PPME_SYSCALL_MKDIRAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MKDIRAT_E_SIZE, PPME_SYSCALL_MKDIRAT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(mkdirat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mkdirat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mkdirat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(mkdirat_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknod.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknod.bpf.c index f087f06398..651e63281a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknod.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknod.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mknod_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mknod_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MKNOD_E_SIZE, PPME_SYSCALL_MKNOD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MKNOD_E_SIZE, PPME_SYSCALL_MKNOD_E)) { return 0; } @@ -33,8 +29,6 @@ int BPF_PROG(mknod_e, ringbuf__submit_event(&ringbuf); return 0; - - } /*=============================== ENTER EVENT ===========================*/ @@ -42,13 +36,9 @@ int BPF_PROG(mknod_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mknod_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mknod_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -65,13 +55,12 @@ int BPF_PROG(mknod_x, /* Parameter 3: mode (type: PT_MODE) */ uint32_t mode = (uint32_t)extract__syscall_argument(regs, 1); - auxmap__store_u32_param(auxmap,mknod_mode_to_scap(mode)); + auxmap__store_u32_param(auxmap, mknod_mode_to_scap(mode)); /* Parameter 4: dev (type: PT_UINT32) */ uint32_t dev = (uint32_t)extract__syscall_argument(regs, 2); auxmap__store_u32_param(auxmap, encode_dev(dev)); - /*=============================== COLLECT PARAMETERS ===========================*/ auxmap__finalize_event_header(auxmap); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknodat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknodat.bpf.c index 25725f2e83..a29c845192 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknodat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mknodat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mknodat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mknodat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MKNODAT_E_SIZE, PPME_SYSCALL_MKNODAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MKNODAT_E_SIZE, PPME_SYSCALL_MKNODAT_E)) { return 0; } @@ -33,8 +29,6 @@ int BPF_PROG(mknodat_e, ringbuf__submit_event(&ringbuf); return 0; - - } /*=============================== ENTER EVENT ===========================*/ @@ -42,13 +36,9 @@ int BPF_PROG(mknodat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mknodat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mknodat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -61,8 +51,7 @@ int BPF_PROG(mknodat_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -79,7 +68,6 @@ int BPF_PROG(mknodat_x, uint32_t dev = (uint32_t)extract__syscall_argument(regs, 3); auxmap__store_u32_param(auxmap, encode_dev(dev)); - /*=============================== COLLECT PARAMETERS ===========================*/ auxmap__finalize_event_header(auxmap); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock.bpf.c index 29b9854cd2..925cdf03d7 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mlock_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mlock_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK_E_SIZE, PPME_SYSCALL_MLOCK_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK_E_SIZE, PPME_SYSCALL_MLOCK_E)) { return 0; } @@ -37,13 +33,9 @@ int BPF_PROG(mlock_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mlock_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mlock_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK_X_SIZE, PPME_SYSCALL_MLOCK_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK_X_SIZE, PPME_SYSCALL_MLOCK_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock2.bpf.c index 4e6458e883..518decea87 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlock2.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mlock2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mlock2_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK2_E_SIZE, PPME_SYSCALL_MLOCK2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK2_E_SIZE, PPME_SYSCALL_MLOCK2_E)) { return 0; } @@ -37,13 +33,9 @@ int BPF_PROG(mlock2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mlock2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mlock2_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK2_X_SIZE, PPME_SYSCALL_MLOCK2_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCK2_X_SIZE, PPME_SYSCALL_MLOCK2_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlockall.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlockall.bpf.c index 70c9e7d3df..c196e7b504 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlockall.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mlockall.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mlockall_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mlockall_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCKALL_E_SIZE, PPME_SYSCALL_MLOCKALL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCKALL_E_SIZE, PPME_SYSCALL_MLOCKALL_E)) { return 0; } @@ -37,13 +33,9 @@ int BPF_PROG(mlockall_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mlockall_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mlockall_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCKALL_X_SIZE, PPME_SYSCALL_MLOCKALL_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MLOCKALL_X_SIZE, PPME_SYSCALL_MLOCKALL_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap.bpf.c index 9d9b2ddf2c..67007645da 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mmap_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mmap_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP_E_SIZE, PPME_SYSCALL_MMAP_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP_E_SIZE, PPME_SYSCALL_MMAP_E)) { return 0; } @@ -61,13 +57,9 @@ int BPF_PROG(mmap_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mmap_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mmap_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP_X_SIZE, PPME_SYSCALL_MMAP_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP_X_SIZE, PPME_SYSCALL_MMAP_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap2.bpf.c index f0decd9b56..e83cbaa9c0 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mmap2.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mmap2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mmap2_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP2_E_SIZE, PPME_SYSCALL_MMAP2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP2_E_SIZE, PPME_SYSCALL_MMAP2_E)) { return 0; } @@ -61,13 +57,9 @@ int BPF_PROG(mmap2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mmap2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mmap2_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP2_X_SIZE, PPME_SYSCALL_MMAP2_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MMAP2_X_SIZE, PPME_SYSCALL_MMAP2_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mount.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mount.bpf.c index 57f0691c0f..75a56b2b08 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mount.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mount.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(mount_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mount_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MOUNT_E_SIZE, PPME_SYSCALL_MOUNT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MOUNT_E_SIZE, PPME_SYSCALL_MOUNT_E)) { return 0; } @@ -37,8 +33,7 @@ int BPF_PROG(mount_e, * and is ignored if specified. */ /* Check the magic number 0xC0ED in the top 16 bits and ignore it if specified. */ - if((flags & PPM_MS_MGC_MSK) == PPM_MS_MGC_VAL) - { + if((flags & PPM_MS_MGC_MSK) == PPM_MS_MGC_VAL) { flags &= ~PPM_MS_MGC_MSK; } ringbuf__store_u32(&ringbuf, flags); @@ -55,13 +50,9 @@ int BPF_PROG(mount_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mount_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mount_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mprotect.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mprotect.bpf.c index e8e1226e4f..b9714fd97d 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mprotect.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/mprotect.bpf.c @@ -11,13 +11,9 @@ #include SEC("tp_btf/sys_enter") -int BPF_PROG(mprotect_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(mprotect_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MPROTECT_E_SIZE, PPME_SYSCALL_MPROTECT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MPROTECT_E_SIZE, PPME_SYSCALL_MPROTECT_E)) { return 0; } @@ -49,17 +45,13 @@ int BPF_PROG(mprotect_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(mprotect_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(mprotect_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MPROTECT_X_SIZE, PPME_SYSCALL_MPROTECT_X)) - { - return 0; - } + if(!ringbuf__reserve_space(&ringbuf, ctx, MPROTECT_X_SIZE, PPME_SYSCALL_MPROTECT_X)) { + return 0; + } - ringbuf__store_event_header(&ringbuf); + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlock.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlock.bpf.c index 4f709f85dc..528c4c8915 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlock.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlock.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(munlock_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(munlock_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCK_E_SIZE, PPME_SYSCALL_MUNLOCK_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCK_E_SIZE, PPME_SYSCALL_MUNLOCK_E)) { return 0; } @@ -37,13 +33,9 @@ int BPF_PROG(munlock_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(munlock_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(munlock_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCK_X_SIZE, PPME_SYSCALL_MUNLOCK_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCK_X_SIZE, PPME_SYSCALL_MUNLOCK_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlockall.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlockall.bpf.c index e6a5f6c22a..b67490fbd2 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlockall.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munlockall.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(munlockall_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(munlockall_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCKALL_E_SIZE, PPME_SYSCALL_MUNLOCKALL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCKALL_E_SIZE, PPME_SYSCALL_MUNLOCKALL_E)) { return 0; } @@ -37,13 +33,9 @@ int BPF_PROG(munlockall_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(munlockall_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(munlockall_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCKALL_X_SIZE, PPME_SYSCALL_MUNLOCKALL_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MUNLOCKALL_X_SIZE, PPME_SYSCALL_MUNLOCKALL_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munmap.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munmap.bpf.c index 7673c342a8..637deb70f7 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munmap.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/munmap.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(munmap_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(munmap_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MUNMAP_E_SIZE, PPME_SYSCALL_MUNMAP_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MUNMAP_E_SIZE, PPME_SYSCALL_MUNMAP_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(munmap_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(munmap_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(munmap_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, MUNMAP_X_SIZE, PPME_SYSCALL_MUNMAP_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, MUNMAP_X_SIZE, PPME_SYSCALL_MUNMAP_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/nanosleep.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/nanosleep.bpf.c index 48a943c5db..7e88c76407 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/nanosleep.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/nanosleep.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(nanosleep_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(nanosleep_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, NANOSLEEP_E_SIZE, PPME_SYSCALL_NANOSLEEP_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, NANOSLEEP_E_SIZE, PPME_SYSCALL_NANOSLEEP_E)) { return 0; } @@ -28,14 +24,11 @@ int BPF_PROG(nanosleep_e, /* Parameter 1: req (type: PT_RELTIME) */ uint64_t nanosec = 0; unsigned long ts_pointer = extract__syscall_argument(regs, 0); - if(bpf_core_type_exists(struct __kernel_timespec)) - { + if(bpf_core_type_exists(struct __kernel_timespec)) { struct __kernel_timespec ts = {0}; bpf_probe_read_user(&ts, bpf_core_type_size(struct __kernel_timespec), (void *)ts_pointer); nanosec = ((uint64_t)ts.tv_sec) * SECOND_TO_NS + ts.tv_nsec; - } - else - { + } else { struct modern_bpf__kernel_timespec ts = {0}; bpf_probe_read_user(&ts, sizeof(ts), (void *)ts_pointer); nanosec = ((uint64_t)ts.tv_sec) * SECOND_TO_NS + ts.tv_nsec; @@ -54,13 +47,9 @@ int BPF_PROG(nanosleep_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(nanosleep_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(nanosleep_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, NANOSLEEP_X_SIZE, PPME_SYSCALL_NANOSLEEP_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, NANOSLEEP_X_SIZE, PPME_SYSCALL_NANOSLEEP_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/newfstatat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/newfstatat.bpf.c index 9f63846190..ab543ced66 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/newfstatat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/newfstatat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(newfstatat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(newfstatat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, NEWFSTATAT_E_SIZE, PPME_SYSCALL_NEWFSTATAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, NEWFSTATAT_E_SIZE, PPME_SYSCALL_NEWFSTATAT_E)) { return 0; } @@ -33,8 +29,6 @@ int BPF_PROG(newfstatat_e, ringbuf__submit_event(&ringbuf); return 0; - - } /*=============================== ENTER EVENT ===========================*/ @@ -42,13 +36,9 @@ int BPF_PROG(newfstatat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(newfstatat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(newfstatat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -61,8 +51,7 @@ int BPF_PROG(newfstatat_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -75,7 +64,6 @@ int BPF_PROG(newfstatat_x, uint32_t flags = (uint32_t)extract__syscall_argument(regs, 3); auxmap__store_u32_param(auxmap, newfstatat_flags_to_scap(flags)); - /*=============================== COLLECT PARAMETERS ===========================*/ auxmap__finalize_event_header(auxmap); @@ -85,4 +73,4 @@ int BPF_PROG(newfstatat_x, return 0; } -/*=============================== EXIT EVENT ===========================*/ \ No newline at end of file +/*=============================== EXIT EVENT ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open.bpf.c index 756911ff94..3dedae2768 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(open_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(open_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -51,13 +47,9 @@ int BPF_PROG(open_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(open_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(open_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -69,8 +61,7 @@ int BPF_PROG(open_x, uint64_t ino = 0; enum ppm_overlay ol = PPM_NOT_OVERLAY_FS; - if(ret > 0) - { + if(ret > 0) { extract__dev_ino_overlay_from_fd(ret, &dev, &ino, &ol); } @@ -86,12 +77,9 @@ int BPF_PROG(open_x, uint32_t scap_flags = (uint32_t)open_flags_to_scap(flags); /* update scap flags if file is created */ scap_flags |= extract__fmode_created_from_fd(ret); - if(ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { scap_flags |= PPM_FD_UPPER_LAYER; - } - else if(ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { scap_flags |= PPM_FD_LOWER_LAYER; } auxmap__store_u32_param(auxmap, scap_flags); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open_by_handle_at.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open_by_handle_at.bpf.c index e3eadab08b..da09ec6e1b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open_by_handle_at.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/open_by_handle_at.bpf.c @@ -12,13 +12,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(open_by_handle_at_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(open_by_handle_at_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, OPEN_BY_HANDLE_AT_E_SIZE, PPME_SYSCALL_OPEN_BY_HANDLE_AT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + OPEN_BY_HANDLE_AT_E_SIZE, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_E)) { return 0; } @@ -40,13 +39,9 @@ int BPF_PROG(open_by_handle_at_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(open_by_handle_at_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(open_by_handle_at_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +54,7 @@ int BPF_PROG(open_by_handle_at_x, /* Parameter 2: mountfd (type: PT_FD) */ int32_t mountfd = (int32_t)extract__syscall_argument(regs, 0); - if(mountfd == AT_FDCWD) - { + if(mountfd == AT_FDCWD) { mountfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)mountfd); @@ -72,15 +66,13 @@ int BPF_PROG(open_by_handle_at_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t1_open_by_handle_at_x, struct pt_regs *regs, long ret) -{ +int BPF_PROG(t1_open_by_handle_at_x, struct pt_regs *regs, long ret) { dev_t dev = 0; uint64_t ino = 0; enum ppm_overlay ol = PPM_NOT_OVERLAY_FS; struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -89,40 +81,30 @@ int BPF_PROG(t1_open_by_handle_at_x, struct pt_regs *regs, long ret) uint32_t flags = (uint32_t)extract__syscall_argument(regs, 2); flags = (uint32_t)open_flags_to_scap(flags); /* We collect dev, ino and overlay from the file descriptor only if it is valid */ - if(ret > 0) - { + if(ret > 0) { extract__dev_ino_overlay_from_fd(ret, &dev, &ino, &ol); /* Parameter 3: flags (type: PT_FLAGS32) */ /* update flags if file is created */ flags |= extract__fmode_created_from_fd(ret); - if(ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if(ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } } auxmap__store_u32_param(auxmap, flags); /* We collect the file path from the file descriptor only if it is valid */ - if(ret > 0) - { + if(ret > 0) { /* Parameter 4: path (type: PT_FSPATH) */ struct file *f = extract__file_struct_from_fd(ret); - if(f != NULL) - { + if(f != NULL) { auxmap__store_d_path_approx(auxmap, &(f->f_path)); - } - else - { + } else { auxmap__store_empty_param(auxmap); } - } - else - { + } else { auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat.bpf.c index b9e400b9ac..786bdd663e 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(openat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(openat_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -27,8 +23,7 @@ int BPF_PROG(openat_e, /* Parameter 1: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -59,13 +54,9 @@ int BPF_PROG(openat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(openat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(openat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -77,8 +68,7 @@ int BPF_PROG(openat_x, uint64_t ino = 0; enum ppm_overlay ol = PPM_NOT_OVERLAY_FS; - if(ret > 0) - { + if(ret > 0) { extract__dev_ino_overlay_from_fd(ret, &dev, &ino, &ol); } @@ -87,8 +77,7 @@ int BPF_PROG(openat_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -102,12 +91,9 @@ int BPF_PROG(openat_x, uint32_t scap_flags = (uint32_t)open_flags_to_scap(flags); /* update flags if file is created */ scap_flags |= extract__fmode_created_from_fd(ret); - if(ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { scap_flags |= PPM_FD_UPPER_LAYER; - } - else if(ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { scap_flags |= PPM_FD_LOWER_LAYER; } auxmap__store_u32_param(auxmap, scap_flags); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat2.bpf.c index ab33ece2ef..63b0a9307e 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/openat2.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(openat2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(openat2_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -27,8 +23,7 @@ int BPF_PROG(openat2_e, /* Parameter 1: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -40,7 +35,9 @@ int BPF_PROG(openat2_e, /* the `open_how` struct is defined since kernel version 5.6 */ unsigned long open_how_pointer = extract__syscall_argument(regs, 2); struct open_how how = {0}; - bpf_probe_read_user((void *)&how, bpf_core_type_size(struct open_how), (void *)open_how_pointer); + bpf_probe_read_user((void *)&how, + bpf_core_type_size(struct open_how), + (void *)open_how_pointer); /* Parameter 3: flags (type: PT_FLAGS32) */ auxmap__store_u32_param(auxmap, open_flags_to_scap(how.flags)); @@ -65,13 +62,9 @@ int BPF_PROG(openat2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(openat2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(openat2_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -83,8 +76,7 @@ int BPF_PROG(openat2_x, uint64_t ino = 0; enum ppm_overlay ol = PPM_NOT_OVERLAY_FS; - if(ret > 0) - { + if(ret > 0) { extract__dev_ino_overlay_from_fd(ret, &dev, &ino, &ol); } @@ -93,8 +85,7 @@ int BPF_PROG(openat2_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -106,18 +97,17 @@ int BPF_PROG(openat2_x, /* the `open_how` struct is defined since kernel version 5.6 */ unsigned long open_how_pointer = extract__syscall_argument(regs, 2); struct open_how how = {0}; - bpf_probe_read_user((void *)&how, bpf_core_type_size(struct open_how), (void *)open_how_pointer); + bpf_probe_read_user((void *)&how, + bpf_core_type_size(struct open_how), + (void *)open_how_pointer); /* Parameter 4: flags (type: PT_FLAGS32) */ uint32_t flags = open_flags_to_scap(how.flags); /* update flags if file is created */ flags |= extract__fmode_created_from_fd(ret); - if(ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if(ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_getfd.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_getfd.bpf.c index 4c17b88346..d4dd11309a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_getfd.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_getfd.bpf.c @@ -11,27 +11,23 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(pidfd_getfd_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_GETFD_E_SIZE, PPME_SYSCALL_PIDFD_GETFD_E)) - { +int BPF_PROG(pidfd_getfd_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_GETFD_E_SIZE, PPME_SYSCALL_PIDFD_GETFD_E)) { return 0; } - ringbuf__store_event_header(&ringbuf); + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - - // Here we have no parameters to collect. + + // Here we have no parameters to collect. /*=============================== COLLECT PARAMETERS ===========================*/ - ringbuf__submit_event(&ringbuf); + ringbuf__submit_event(&ringbuf); - return 0; + return 0; } /*=============================== ENTER EVENT ===========================*/ @@ -39,42 +35,38 @@ int BPF_PROG(pidfd_getfd_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(pidfd_getfd_x, - struct pt_regs *regs, - long ret) - -{ - - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_GETFD_X_SIZE, PPME_SYSCALL_PIDFD_GETFD_X)) - { +int BPF_PROG(pidfd_getfd_x, struct pt_regs *regs, long ret) + +{ + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_GETFD_X_SIZE, PPME_SYSCALL_PIDFD_GETFD_X)) { return 0; } - ringbuf__store_event_header(&ringbuf); + ringbuf__store_event_header(&ringbuf); /*=============================== COLLECT PARAMETERS ===========================*/ - - /* Parameter 1: ret (type: PT_FD) */ - ringbuf__store_s64(&ringbuf, ret); - /* Parameter 2: pidfd (type: PT_FD) */ - int32_t pidfd = (int32_t)extract__syscall_argument(regs, 0); - ringbuf__store_s64(&ringbuf, (int64_t)pidfd); + /* Parameter 1: ret (type: PT_FD) */ + ringbuf__store_s64(&ringbuf, ret); + + /* Parameter 2: pidfd (type: PT_FD) */ + int32_t pidfd = (int32_t)extract__syscall_argument(regs, 0); + ringbuf__store_s64(&ringbuf, (int64_t)pidfd); - /* Parameter 3: targetfd (type: PT_FD) */ - int32_t targetfd = (int32_t)extract__syscall_argument(regs, 1); - ringbuf__store_s64(&ringbuf, (int64_t)targetfd); + /* Parameter 3: targetfd (type: PT_FD) */ + int32_t targetfd = (int32_t)extract__syscall_argument(regs, 1); + ringbuf__store_s64(&ringbuf, (int64_t)targetfd); - /* Parameter 4: flags (type: PT_UINT32)*/ - uint32_t flags = (uint32_t)extract__syscall_argument(regs, 2); - ringbuf__store_u32(&ringbuf, flags); + /* Parameter 4: flags (type: PT_UINT32)*/ + uint32_t flags = (uint32_t)extract__syscall_argument(regs, 2); + ringbuf__store_u32(&ringbuf, flags); /*=============================== COLLECT PARAMETERS ===========================*/ - ringbuf__submit_event(&ringbuf); + ringbuf__submit_event(&ringbuf); - return 0; + return 0; } /*=============================== EXIT EVENT ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_open.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_open.bpf.c index 492686e71f..f46602eaa0 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_open.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pidfd_open.bpf.c @@ -11,27 +11,23 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(pidfd_open_e, - struct pt_regs *regs, - long id) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_OPEN_E_SIZE, PPME_SYSCALL_PIDFD_OPEN_E)) - { - return 0; - } +int BPF_PROG(pidfd_open_e, struct pt_regs *regs, long id) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_OPEN_E_SIZE, PPME_SYSCALL_PIDFD_OPEN_E)) { + return 0; + } - ringbuf__store_event_header(&ringbuf); + ringbuf__store_event_header(&ringbuf); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - // Here we have no parameters to collect. + // Here we have no parameters to collect. - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - ringbuf__submit_event(&ringbuf); + ringbuf__submit_event(&ringbuf); - return 0; + return 0; } /*=============================== ENTER EVENT ===========================*/ @@ -39,39 +35,32 @@ int BPF_PROG(pidfd_open_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(pidfd_open_x, - struct pt_regs *regs, - long ret) -{ - struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_OPEN_X_SIZE, PPME_SYSCALL_PIDFD_OPEN_X)) - { - return 0; - } +int BPF_PROG(pidfd_open_x, struct pt_regs *regs, long ret) { + struct ringbuf_struct ringbuf; + if(!ringbuf__reserve_space(&ringbuf, ctx, PIDFD_OPEN_X_SIZE, PPME_SYSCALL_PIDFD_OPEN_X)) { + return 0; + } - ringbuf__store_event_header(&ringbuf); + ringbuf__store_event_header(&ringbuf); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_FD) */ + /* Parameter 1: res (type: PT_FD) */ ringbuf__store_s64(&ringbuf, ret); - /* Parameter 2: pid (type: PT_PID)*/ - pid_t pid = (int32_t)extract__syscall_argument(regs, 0); - ringbuf__store_s64(&ringbuf, (int64_t)pid); + /* Parameter 2: pid (type: PT_PID)*/ + pid_t pid = (int32_t)extract__syscall_argument(regs, 0); + ringbuf__store_s64(&ringbuf, (int64_t)pid); - /* Parameter 3: pid (type: PT_FLAGS32)*/ - uint32_t flags = (uint32_t)extract__syscall_argument(regs, 1); - ringbuf__store_u32(&ringbuf, pidfd_open_flags_to_scap(flags)); + /* Parameter 3: pid (type: PT_FLAGS32)*/ + uint32_t flags = (uint32_t)extract__syscall_argument(regs, 1); + ringbuf__store_u32(&ringbuf, pidfd_open_flags_to_scap(flags)); - /*=============================== COLLECT PARAMETERS ===========================*/ + /*=============================== COLLECT PARAMETERS ===========================*/ - ringbuf__submit_event(&ringbuf); + ringbuf__submit_event(&ringbuf); - return 0; + return 0; } /*=============================== EXIT EVENT ===========================*/ - - - diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe.bpf.c index 658a8df7e9..9a6e165173 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(pipe_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(pipe_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE_E_SIZE, PPME_SYSCALL_PIPE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE_E_SIZE, PPME_SYSCALL_PIPE_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(pipe_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(pipe_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(pipe_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE_X_SIZE, PPME_SYSCALL_PIPE_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE_X_SIZE, PPME_SYSCALL_PIPE_X)) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(pipe_x, int32_t pipefd[2] = {-1, -1}; /* This is a pointer to the vector with the 2 file descriptors. */ unsigned long fd_vector_pointer = extract__syscall_argument(regs, 0); - if(bpf_probe_read_user((void *)pipefd, sizeof(pipefd), (void *)fd_vector_pointer) != 0) - { + if(bpf_probe_read_user((void *)pipefd, sizeof(pipefd), (void *)fd_vector_pointer) != 0) { pipefd[0] = -1; pipefd[1] = -1; } @@ -73,8 +64,7 @@ int BPF_PROG(pipe_x, uint64_t ino = 0; /* On success, pipe returns `0` */ - if(ret == 0) - { + if(ret == 0) { extract__ino_from_fd(pipefd[0], &ino); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe2.bpf.c index 4317b53f18..3ce8237dcd 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pipe2.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(pipe2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(pipe2_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE2_E_SIZE, PPME_SYSCALL_PIPE2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE2_E_SIZE, PPME_SYSCALL_PIPE2_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(pipe2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(pipe2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(pipe2_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE2_X_SIZE, PPME_SYSCALL_PIPE2_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PIPE2_X_SIZE, PPME_SYSCALL_PIPE2_X)) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(pipe2_x, int32_t pipefd[2] = {-1, -1}; /* This is a pointer to the vector with the 2 file descriptors. */ unsigned long fd_vector_pointer = extract__syscall_argument(regs, 0); - if(bpf_probe_read_user((void *)pipefd, sizeof(pipefd), (void *)fd_vector_pointer) != 0) - { + if(bpf_probe_read_user((void *)pipefd, sizeof(pipefd), (void *)fd_vector_pointer) != 0) { pipefd[0] = -1; pipefd[1] = -1; } @@ -73,8 +64,7 @@ int BPF_PROG(pipe2_x, uint64_t ino = 0; /* On success, pipe returns `0` */ - if(ret == 0) - { + if(ret == 0) { extract__ino_from_fd(pipefd[0], &ino); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/poll.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/poll.bpf.c index 4a8845c149..c3f42a0516 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/poll.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/poll.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(poll_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(poll_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -30,8 +26,8 @@ int BPF_PROG(poll_e, uint32_t nfds = (uint32_t)extract__syscall_argument(regs, 1); /* Parameter 1: fds (type: PT_FDLIST) */ - /* We are in the enter event so we get the requested events, the returned events are only available - * in the exit event. + /* We are in the enter event so we get the requested events, the returned events are only + * available in the exit event. */ auxmap__store_fdlist_param(auxmap, fds_pointer, nfds, REQUESTED_EVENTS); @@ -54,13 +50,9 @@ int BPF_PROG(poll_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(poll_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(poll_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ppoll.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ppoll.bpf.c index 12359d568b..934f0d22e6 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ppoll.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ppoll.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(ppoll_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(ppoll_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -30,31 +26,27 @@ int BPF_PROG(ppoll_e, uint32_t nfds = (uint32_t)extract__syscall_argument(regs, 1); /* Parameter 1: fds (type: PT_FDLIST) */ - /* We are in the enter event so we get the requested events, the returned events are only available - * in the exit event. + /* We are in the enter event so we get the requested events, the returned events are only + * available in the exit event. */ auxmap__store_fdlist_param(auxmap, fds_pointer, nfds, REQUESTED_EVENTS); /* Parameter 2: timeout (type: PT_RELTIME) */ uint64_t nanosec = 0; unsigned long ts_pointer = extract__syscall_argument(regs, 2); - if(!bpf_in_ia32_syscall()) - { - if(bpf_core_type_exists(struct __kernel_timespec)) - { + if(!bpf_in_ia32_syscall()) { + if(bpf_core_type_exists(struct __kernel_timespec)) { struct __kernel_timespec ts = {0}; - bpf_probe_read_user(&ts, bpf_core_type_size(struct __kernel_timespec), (void *)ts_pointer); + bpf_probe_read_user(&ts, + bpf_core_type_size(struct __kernel_timespec), + (void *)ts_pointer); nanosec = ((uint64_t)ts.tv_sec) * SECOND_TO_NS + ts.tv_nsec; - } - else - { + } else { struct modern_bpf__kernel_timespec ts = {0}; bpf_probe_read_user(&ts, sizeof(ts), (void *)ts_pointer); nanosec = ((uint64_t)ts.tv_sec) * SECOND_TO_NS + ts.tv_nsec; } - } - else - { + } else { struct modern_bpf__kernel_timespec_ia32 ts = {0}; bpf_probe_read_user(&ts, sizeof(ts), (void *)ts_pointer); nanosec = ((uint32_t)ts.tv_sec) * SECOND_TO_NS + ts.tv_nsec; @@ -64,13 +56,10 @@ int BPF_PROG(ppoll_e, /* Parameter 3: sigmask (type: PT_SIGSET) */ long unsigned int sigmask[1] = {0}; unsigned long sigmask_pointer = extract__syscall_argument(regs, 3); - if(bpf_probe_read_user(&sigmask, sizeof(sigmask), (void *)sigmask_pointer)) - { + if(bpf_probe_read_user(&sigmask, sizeof(sigmask), (void *)sigmask_pointer)) { /* In case of invalid pointer, return 0 */ auxmap__store_u32_param(auxmap, (uint32_t)0); - } - else - { + } else { auxmap__store_u32_param(auxmap, (uint32_t)sigmask[0]); } @@ -88,13 +77,9 @@ int BPF_PROG(ppoll_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(ppoll_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(ppoll_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prctl.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prctl.bpf.c index d36498d837..2ed50d1457 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prctl.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prctl.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(prctl_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(prctl_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PRCTL_E_SIZE, PPME_SYSCALL_PRCTL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PRCTL_E_SIZE, PPME_SYSCALL_PRCTL_E)) { return 0; } @@ -33,8 +29,6 @@ int BPF_PROG(prctl_e, ringbuf__submit_event(&ringbuf); return 0; - - } /*=============================== ENTER EVENT ===========================*/ @@ -42,13 +36,9 @@ int BPF_PROG(prctl_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(prctl_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(prctl_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -67,28 +57,28 @@ int BPF_PROG(prctl_x, unsigned long arg2 = extract__syscall_argument(regs, 1); - switch(option){ - case PPM_PR_GET_NAME: - case PPM_PR_SET_NAME: - /* Parameter 3: arg2_str (type: PT_CHARBUF) */ - auxmap__store_charbuf_param(auxmap, arg2, MAX_PATH, USER); - /* Parameter 4: arg2_int (type: PT_INT64) */ - auxmap__store_s64_param(auxmap, 0); - break; - case PPM_PR_GET_CHILD_SUBREAPER: - /* Parameter 3: arg2_str (type: PT_CHARBUF) */ - auxmap__store_empty_param(auxmap); - bpf_probe_read_user(&reaper_attr, sizeof(reaper_attr), (void*)arg2); - /* Parameter 4: arg2_int (type: PT_INT64) */ - auxmap__store_s64_param(auxmap, (int64_t)reaper_attr); - break; - case PPM_PR_SET_CHILD_SUBREAPER: - default: - /* Parameter 3: arg2_str (type: PT_CHARBUF) */ - auxmap__store_empty_param(auxmap); - /* Parameter 4: arg2_int (type: PT_INT64) */ - auxmap__store_s64_param(auxmap, arg2); - break; + switch(option) { + case PPM_PR_GET_NAME: + case PPM_PR_SET_NAME: + /* Parameter 3: arg2_str (type: PT_CHARBUF) */ + auxmap__store_charbuf_param(auxmap, arg2, MAX_PATH, USER); + /* Parameter 4: arg2_int (type: PT_INT64) */ + auxmap__store_s64_param(auxmap, 0); + break; + case PPM_PR_GET_CHILD_SUBREAPER: + /* Parameter 3: arg2_str (type: PT_CHARBUF) */ + auxmap__store_empty_param(auxmap); + bpf_probe_read_user(&reaper_attr, sizeof(reaper_attr), (void *)arg2); + /* Parameter 4: arg2_int (type: PT_INT64) */ + auxmap__store_s64_param(auxmap, (int64_t)reaper_attr); + break; + case PPM_PR_SET_CHILD_SUBREAPER: + default: + /* Parameter 3: arg2_str (type: PT_CHARBUF) */ + auxmap__store_empty_param(auxmap); + /* Parameter 4: arg2_int (type: PT_INT64) */ + auxmap__store_s64_param(auxmap, arg2); + break; } /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pread64.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pread64.bpf.c index 69504dd1e3..35b61a31e6 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pread64.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pread64.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(pread64_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(pread64_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PREAD64_E_SIZE, PPME_SYSCALL_PREAD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PREAD64_E_SIZE, PPME_SYSCALL_PREAD_E)) { return 0; } @@ -50,13 +46,9 @@ int BPF_PROG(pread64_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(pread64_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(pread64_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -67,24 +59,20 @@ int BPF_PROG(pread64_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - if(ret > 0) - { + if(ret > 0) { /* We read the minimum between `snaplen` and what we really * have in the buffer. */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SYSCALL_PREAD_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } /* Parameter 2: data (type: PT_BYTEBUF) */ unsigned long data_ptr = extract__syscall_argument(regs, 1); auxmap__store_bytebuf_param(auxmap, data_ptr, snaplen, USER); - } - else - { + } else { /* Parameter 2: data (type: PT_BYTEBUF) */ auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/preadv.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/preadv.bpf.c index 8ea07bbc03..f62a03853f 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/preadv.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/preadv.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(preadv_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(preadv_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PREADV_E_SIZE, PPME_SYSCALL_PREADV_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PREADV_E_SIZE, PPME_SYSCALL_PREADV_E)) { return 0; } @@ -46,13 +42,9 @@ int BPF_PROG(preadv_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(preadv_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(preadv_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -63,8 +55,7 @@ int BPF_PROG(preadv_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - if(ret > 0) - { + if(ret > 0) { /* Parameter 2: size (type: PT_UINT32) */ auxmap__store_u32_param(auxmap, (uint32_t)ret); @@ -73,8 +64,7 @@ int BPF_PROG(preadv_x, */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SYSCALL_PREADV_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } @@ -83,9 +73,7 @@ int BPF_PROG(preadv_x, //* Parameter 3: data (type: PT_BYTEBUF) */ auxmap__store_iovec_data_param(auxmap, iov_pointer, iov_cnt, snaplen); - } - else - { + } else { /* Parameter 2: size (type: PT_UINT32) */ auxmap__store_u32_param(auxmap, 0); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prlimit64.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prlimit64.bpf.c index ae2c8647d2..adea2e2881 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prlimit64.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/prlimit64.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(prlimit64_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(prlimit64_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PRLIMIT64_E_SIZE, PPME_SYSCALL_PRLIMIT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PRLIMIT64_E_SIZE, PPME_SYSCALL_PRLIMIT_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(prlimit64_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(prlimit64_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(prlimit64_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PRLIMIT64_X_SIZE, PPME_SYSCALL_PRLIMIT_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PRLIMIT64_X_SIZE, PPME_SYSCALL_PRLIMIT_X)) { return 0; } @@ -64,7 +56,9 @@ int BPF_PROG(prlimit64_x, struct rlimit new_rlimit = {0}; unsigned long rlimit_pointer = extract__syscall_argument(regs, 2); - bpf_probe_read_user((void *)&new_rlimit, bpf_core_type_size(struct rlimit), (void *)rlimit_pointer); + bpf_probe_read_user((void *)&new_rlimit, + bpf_core_type_size(struct rlimit), + (void *)rlimit_pointer); /* Parameter 2: newcur (type: PT_INT64) */ ringbuf__store_s64(&ringbuf, new_rlimit.rlim_cur); @@ -76,19 +70,18 @@ int BPF_PROG(prlimit64_x, * struct will be not filled by the kernel. */ struct rlimit old_rlimit = {0}; - if(ret == 0) - { + if(ret == 0) { rlimit_pointer = extract__syscall_argument(regs, 3); - bpf_probe_read_user((void *)&old_rlimit, bpf_core_type_size(struct rlimit), (void *)rlimit_pointer); + bpf_probe_read_user((void *)&old_rlimit, + bpf_core_type_size(struct rlimit), + (void *)rlimit_pointer); /* Parameter 4: oldcur (type: PT_INT64) */ ringbuf__store_s64(&ringbuf, old_rlimit.rlim_cur); /* Parameter 5: oldmax (type: PT_INT64) */ - ringbuf__store_s64(&ringbuf, old_rlimit.rlim_max); - } - else - { + ringbuf__store_s64(&ringbuf, old_rlimit.rlim_max); + } else { /* Parameter 4: oldcur (type: PT_INT64) */ ringbuf__store_s64(&ringbuf, -1); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_readv.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_readv.bpf.c index cc65b63b49..532e30ca6b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_readv.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_readv.bpf.c @@ -12,13 +12,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(process_vm_readv_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(process_vm_readv_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PROCESS_VM_READV_E_SIZE, PPME_SYSCALL_PROCESS_VM_READV_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + PROCESS_VM_READV_E_SIZE, + PPME_SYSCALL_PROCESS_VM_READV_E)) { return 0; } @@ -40,19 +39,14 @@ int BPF_PROG(process_vm_readv_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(process_vm_readv_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(process_vm_readv_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_PROCESS_VM_READV_X); - /*=============================== COLLECT PARAMETERS ===========================*/ /* Parameter 1: res (type: PT_INT64) */ @@ -62,15 +56,13 @@ int BPF_PROG(process_vm_readv_x, int64_t pid = extract__syscall_argument(regs, 0); auxmap__store_s64_param(auxmap, pid); - if(ret > 0) - { + if(ret > 0) { /* We read the minimum between `snaplen` and what we really * have in the buffer. */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SYSCALL_PROCESS_VM_READV_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } @@ -79,9 +71,7 @@ int BPF_PROG(process_vm_readv_x, /* Parameter 3: data (type: PT_BYTEBUF) */ auxmap__store_iovec_data_param(auxmap, iov_pointer, iov_cnt, snaplen); - } - else - { + } else { /* Parameter 3: data (type: PT_BYTEBUF) */ auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_writev.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_writev.bpf.c index 039fe106db..3afa1e4a1b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_writev.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/process_vm_writev.bpf.c @@ -12,13 +12,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(process_vm_writev_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(process_vm_writev_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PROCESS_VM_WRITEV_E_SIZE, PPME_SYSCALL_PROCESS_VM_WRITEV_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + PROCESS_VM_WRITEV_E_SIZE, + PPME_SYSCALL_PROCESS_VM_WRITEV_E)) { return 0; } @@ -40,19 +39,14 @@ int BPF_PROG(process_vm_writev_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(process_vm_writev_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(process_vm_writev_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_PROCESS_VM_WRITEV_X); - /*=============================== COLLECT PARAMETERS ===========================*/ /* Parameter 1: res (type: PT_INT64) */ @@ -62,15 +56,13 @@ int BPF_PROG(process_vm_writev_x, int64_t pid = extract__syscall_argument(regs, 0); auxmap__store_s64_param(auxmap, pid); - if(ret > 0) - { + if(ret > 0) { /* We read the minimum between `snaplen` and what we really * have in the buffer. */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SYSCALL_PROCESS_VM_WRITEV_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } @@ -79,9 +71,7 @@ int BPF_PROG(process_vm_writev_x, //* Parameter 3: data (type: PT_BYTEBUF) */ auxmap__store_iovec_data_param(auxmap, iov_pointer, iov_cnt, snaplen); - } - else - { + } else { /* Parameter 3: data (type: PT_BYTEBUF) */ auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ptrace.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ptrace.bpf.c index dbb63ef554..bc6c1e9e64 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ptrace.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/ptrace.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(ptrace_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(ptrace_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PTRACE_E_SIZE, PPME_SYSCALL_PTRACE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PTRACE_E_SIZE, PPME_SYSCALL_PTRACE_E)) { return 0; } @@ -46,13 +42,9 @@ int BPF_PROG(ptrace_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(ptrace_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(ptrace_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwrite64.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwrite64.bpf.c index 02b6cf3965..8a8c5f4777 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwrite64.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwrite64.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(pwrite64_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(pwrite64_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PWRITE64_E_SIZE, PPME_SYSCALL_PWRITE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PWRITE64_E_SIZE, PPME_SYSCALL_PWRITE_E)) { return 0; } @@ -50,13 +46,9 @@ int BPF_PROG(pwrite64_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(pwrite64_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(pwrite64_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -73,8 +65,7 @@ int BPF_PROG(pwrite64_x, int64_t bytes_to_read = ret > 0 ? ret : extract__syscall_argument(regs, 2); uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SYSCALL_PWRITE_X); - if((int64_t)snaplen > bytes_to_read) - { + if((int64_t)snaplen > bytes_to_read) { snaplen = bytes_to_read; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwritev.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwritev.bpf.c index 501dad7da5..ce90fd71eb 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwritev.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/pwritev.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(pwritev_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(pwritev_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, PWRITEV_E_SIZE, PPME_SYSCALL_PWRITEV_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, PWRITEV_E_SIZE, PPME_SYSCALL_PWRITEV_E)) { return 0; } @@ -52,13 +48,9 @@ int BPF_PROG(pwritev_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(pwritev_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(pwritev_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -76,8 +68,7 @@ int BPF_PROG(pwritev_x, */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SYSCALL_PWRITEV_X); - if(ret > 0 && snaplen > ret) - { + if(ret > 0 && snaplen > ret) { snaplen = ret; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/quotactl.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/quotactl.bpf.c index 01cdf5ae0a..c8fb6e0b5c 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/quotactl.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/quotactl.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(quotactl_e, - struct pt_regs *regs, - long syscall_id) -{ +int BPF_PROG(quotactl_e, struct pt_regs *regs, long syscall_id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, QUOTACTL_E_SIZE, PPME_SYSCALL_QUOTACTL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, QUOTACTL_E_SIZE, PPME_SYSCALL_QUOTACTL_E)) { return 0; } @@ -36,23 +32,17 @@ int BPF_PROG(quotactl_e, /* Parameter 3: id (type: PT_UINT32) */ uint32_t id = (uint32_t)extract__syscall_argument(regs, 2); - if(scap_cmd != PPM_Q_GETQUOTA && - scap_cmd != PPM_Q_SETQUOTA && - scap_cmd != PPM_Q_XGETQUOTA && - scap_cmd != PPM_Q_XSETQLIM) - { + if(scap_cmd != PPM_Q_GETQUOTA && scap_cmd != PPM_Q_SETQUOTA && scap_cmd != PPM_Q_XGETQUOTA && + scap_cmd != PPM_Q_XSETQLIM) { /* In this case `id` don't represent a `userid` or a `groupid` */ ringbuf__store_u32(&ringbuf, 0); - } - else - { + } else { ringbuf__store_u32(&ringbuf, id); } /* Parameter 4: quota_fmt (type: PT_FLAGS8) */ uint8_t quota_fmt = PPM_QFMT_NOT_USED; - if(scap_cmd == PPM_Q_QUOTAON) - { + if(scap_cmd == PPM_Q_QUOTAON) { quota_fmt = quotactl_fmt_to_scap(id); } ringbuf__store_u8(&ringbuf, quota_fmt); @@ -69,13 +59,9 @@ int BPF_PROG(quotactl_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(quotactl_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(quotactl_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -104,13 +90,10 @@ int BPF_PROG(quotactl_x, unsigned long addr_pointer = extract__syscall_argument(regs, 3); /* We get `quotafilepath` only for `QUOTAON` command. */ - if(scap_cmd == PPM_Q_QUOTAON) - { + if(scap_cmd == PPM_Q_QUOTAON) { /* Parameter 3: quotafilepath (type: PT_CHARBUF) */ auxmap__store_charbuf_param(auxmap, addr_pointer, MAX_PATH, USER); - } - else - { + } else { /* Parameter 3: quotafilepath (type: PT_CHARBUF) */ auxmap__store_empty_param(auxmap); } @@ -124,38 +107,35 @@ int BPF_PROG(quotactl_x, uint64_t dqb_btime = 0; uint64_t dqb_itime = 0; - if(bpf_core_type_exists(struct if_dqblk) && (scap_cmd == PPM_Q_GETQUOTA || scap_cmd == PPM_Q_SETQUOTA)) - { + if(bpf_core_type_exists(struct if_dqblk) && + (scap_cmd == PPM_Q_GETQUOTA || scap_cmd == PPM_Q_SETQUOTA)) { struct if_dqblk dqblk = {0}; - bpf_probe_read_user((void *)&dqblk, bpf_core_type_size(struct if_dqblk), (void *)addr_pointer); + bpf_probe_read_user((void *)&dqblk, + bpf_core_type_size(struct if_dqblk), + (void *)addr_pointer); /* Please note that `dqblk` struct could be filled with values different from `0`, * even if these values are not valid, so we need to explicitly send `0`. */ - if(dqblk.dqb_valid & QIF_BLIMITS) - { + if(dqblk.dqb_valid & QIF_BLIMITS) { dqb_bhardlimit = dqblk.dqb_bhardlimit; dqb_bsoftlimit = dqblk.dqb_bsoftlimit; } - if(dqblk.dqb_valid & QIF_SPACE) - { + if(dqblk.dqb_valid & QIF_SPACE) { dqb_curspace = dqblk.dqb_curspace; } - if(dqblk.dqb_valid & QIF_ILIMITS) - { + if(dqblk.dqb_valid & QIF_ILIMITS) { dqb_ihardlimit = dqblk.dqb_ihardlimit; dqb_isoftlimit = dqblk.dqb_isoftlimit; } - if(dqblk.dqb_valid & QIF_BTIME) - { + if(dqblk.dqb_valid & QIF_BTIME) { dqb_btime = dqblk.dqb_btime; } - if(dqblk.dqb_valid & QIF_ITIME) - { + if(dqblk.dqb_valid & QIF_ITIME) { dqb_itime = dqblk.dqb_itime; } } @@ -185,24 +165,23 @@ int BPF_PROG(quotactl_x, uint64_t dqi_igrace = 0; uint64_t dqi_flags = 0; - if(bpf_core_type_exists(struct if_dqinfo) && (scap_cmd == PPM_Q_GETINFO || scap_cmd == PPM_Q_SETINFO)) - { + if(bpf_core_type_exists(struct if_dqinfo) && + (scap_cmd == PPM_Q_GETINFO || scap_cmd == PPM_Q_SETINFO)) { struct if_dqinfo dqinfo = {0}; - bpf_probe_read_user((void *)&dqinfo, bpf_core_type_size(struct if_dqinfo), (void *)addr_pointer); + bpf_probe_read_user((void *)&dqinfo, + bpf_core_type_size(struct if_dqinfo), + (void *)addr_pointer); - if(dqinfo.dqi_valid & IIF_BGRACE) - { + if(dqinfo.dqi_valid & IIF_BGRACE) { dqi_bgrace = dqinfo.dqi_bgrace; } - if(dqinfo.dqi_valid & IIF_IGRACE) - { + if(dqinfo.dqi_valid & IIF_IGRACE) { /* Parameter 12: dqi_igrace (type: PT_RELTIME) */ dqi_igrace = dqinfo.dqi_igrace; } - if(dqinfo.dqi_valid & IIF_FLAGS) - { + if(dqinfo.dqi_valid & IIF_FLAGS) { /* Parameter 13: dqi_flags (type: PT_FLAGS8) */ dqi_flags = dqinfo.dqi_flags; } @@ -219,8 +198,7 @@ int BPF_PROG(quotactl_x, /* Parameter 14: quota_fmt_out (type: PT_FLAGS8) */ uint32_t quota_fmt_out = PPM_QFMT_NOT_USED; - if(scap_cmd == PPM_Q_GETFMT) - { + if(scap_cmd == PPM_Q_GETFMT) { uint32_t quota_fmt_out_tmp = 0; bpf_probe_read_user("a_fmt_out_tmp, sizeof(quota_fmt_out_tmp), (void *)addr_pointer); quota_fmt_out = quotactl_fmt_to_scap(quota_fmt_out_tmp); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/read.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/read.bpf.c index 1de99834ef..db4ea28e43 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/read.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/read.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(read_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(read_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, READ_E_SIZE, PPME_SYSCALL_READ_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, READ_E_SIZE, PPME_SYSCALL_READ_E)) { return 0; } @@ -46,13 +42,9 @@ int BPF_PROG(read_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(read_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(read_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -63,24 +55,20 @@ int BPF_PROG(read_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - if(ret > 0) - { + if(ret > 0) { /* We read the minimum between `snaplen` and what we really * have in the buffer. */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SYSCALL_READ_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } /* Parameter 2: data (type: PT_BYTEBUF) */ unsigned long data_pointer = extract__syscall_argument(regs, 1); auxmap__store_bytebuf_param(auxmap, data_pointer, snaplen, USER); - } - else - { + } else { /* Parameter 2: data (type: PT_BYTEBUF) */ auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/readv.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/readv.bpf.c index 0b454d9661..07a79b41e5 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/readv.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/readv.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(readv_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(readv_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, READV_E_SIZE, PPME_SYSCALL_READV_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, READV_E_SIZE, PPME_SYSCALL_READV_E)) { return 0; } @@ -42,13 +38,9 @@ int BPF_PROG(readv_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(readv_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(readv_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(readv_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - if(ret > 0) - { + if(ret > 0) { /* Parameter 2: size (type: PT_UINT32) */ auxmap__store_u32_param(auxmap, (uint32_t)ret); @@ -69,8 +60,7 @@ int BPF_PROG(readv_x, */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SYSCALL_READV_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } @@ -79,9 +69,7 @@ int BPF_PROG(readv_x, //* Parameter 3: data (type: PT_BYTEBUF) */ auxmap__store_iovec_data_param(auxmap, iov_pointer, iov_cnt, snaplen); - } - else - { + } else { /* Parameter 2: size (type: PT_UINT32) */ auxmap__store_u32_param(auxmap, 0); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recv.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recv.bpf.c index d52bbe0da1..72dce1fc21 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recv.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recv.bpf.c @@ -12,17 +12,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(recv_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(recv_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long args[3] = {0}; extract__network_args(args, 3, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RECV_E_SIZE, PPME_SOCKET_RECV_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RECV_E_SIZE, PPME_SOCKET_RECV_E)) { return 0; } @@ -50,13 +46,9 @@ int BPF_PROG(recv_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(recv_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(recv_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -67,25 +59,21 @@ int BPF_PROG(recv_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - if(ret > 0) - { + if(ret > 0) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long args[2] = {0}; extract__network_args(args, 2, regs); uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SOCKET_RECV_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } /* Parameter 2: data (type: PT_BYTEBUF) */ unsigned long data_pointer = args[1]; auxmap__store_bytebuf_param(auxmap, data_pointer, snaplen, USER); - } - else - { + } else { /* Parameter 2: data (type: PT_BYTEBUF) */ auxmap__store_empty_param(auxmap); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvfrom.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvfrom.bpf.c index 236327e349..ceba3632ef 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvfrom.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvfrom.bpf.c @@ -12,17 +12,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(recvfrom_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(recvfrom_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long args[3] = {0}; extract__network_args(args, 3, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RECVFROM_E_SIZE, PPME_SOCKET_RECVFROM_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RECVFROM_E_SIZE, PPME_SOCKET_RECVFROM_E)) { return 0; } @@ -50,13 +46,9 @@ int BPF_PROG(recvfrom_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(recvfrom_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(recvfrom_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -67,15 +59,13 @@ int BPF_PROG(recvfrom_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - if(ret >= 0) - { + if(ret >= 0) { /* We read the minimum between `snaplen` and what we really * have in the buffer. */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SOCKET_RECVFROM_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } @@ -91,9 +81,7 @@ int BPF_PROG(recvfrom_x, uint32_t socket_fd = (uint32_t)args[0]; struct sockaddr *usrsockaddr = (struct sockaddr *)args[4]; auxmap__store_socktuple_param(auxmap, socket_fd, INBOUND, usrsockaddr); - } - else - { + } else { /* Parameter 2: data (type: PT_BYTEBUF) */ auxmap__store_empty_param(auxmap); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmmsg.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmmsg.bpf.c index 6dc1ac389b..117f12fa94 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmmsg.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmmsg.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(recvmmsg_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(recvmmsg_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RECVMMSG_E_SIZE, PPME_SOCKET_RECVMMSG_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RECVMMSG_E_SIZE, PPME_SOCKET_RECVMMSG_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(recvmmsg_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(recvmmsg_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(recvmmsg_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RECVMMSG_X_SIZE, PPME_SOCKET_RECVMMSG_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RECVMMSG_X_SIZE, PPME_SOCKET_RECVMMSG_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmsg.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmsg.bpf.c index 868cd38c46..d1a0d57875 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmsg.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/recvmsg.bpf.c @@ -12,17 +12,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(recvmsg_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(recvmsg_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long socket_fd = 0; extract__network_args(&socket_fd, 1, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RECVMSG_E_SIZE, PPME_SOCKET_RECVMSG_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RECVMSG_E_SIZE, PPME_SOCKET_RECVMSG_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(recvmsg_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(recvmsg_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(recvmsg_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -62,9 +54,7 @@ int BPF_PROG(recvmsg_x, /* Parameter 1: res (type: PT_ERRNO) */ auxmap__store_s64_param(auxmap, ret); - if(ret >= 0) - { - + if(ret >= 0) { /* Parameter 2: size (type: PT_UINT32) */ auxmap__store_u32_param(auxmap, (uint32_t)ret); @@ -73,8 +63,7 @@ int BPF_PROG(recvmsg_x, */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SOCKET_RECVMSG_X); - if(snaplen > ret) - { + if(snaplen > ret) { snaplen = ret; } @@ -84,22 +73,23 @@ int BPF_PROG(recvmsg_x, /* Parameter 3: data (type: PT_BYTEBUF) */ unsigned long msghdr_pointer = args[1]; - struct user_msghdr msghhdr = auxmap__store_msghdr_data_param(auxmap, msghdr_pointer, snaplen); + struct user_msghdr msghhdr = + auxmap__store_msghdr_data_param(auxmap, msghdr_pointer, snaplen); /* Parameter 4: tuple (type: PT_SOCKTUPLE) */ uint32_t socket_fd = (uint32_t)args[0]; auxmap__store_socktuple_param(auxmap, socket_fd, INBOUND, msghhdr.msg_name); /* Parameter 5: msg_control (type: PT_BYTEBUF) */ - if (msghhdr.msg_control != NULL) - { - auxmap__store_bytebuf_param(auxmap, (unsigned long)msghhdr.msg_control, msghhdr.msg_controllen, USER); + if(msghhdr.msg_control != NULL) { + auxmap__store_bytebuf_param(auxmap, + (unsigned long)msghhdr.msg_control, + msghhdr.msg_controllen, + USER); } else { auxmap__store_empty_param(auxmap); } - } - else - { + } else { /* Parameter 2: size (type: PT_UINT32) */ auxmap__store_u32_param(auxmap, 0); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rename.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rename.bpf.c index d0b6491167..dc252d6aa8 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rename.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rename.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(rename_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(rename_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RENAME_E_SIZE, PPME_SYSCALL_RENAME_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RENAME_E_SIZE, PPME_SYSCALL_RENAME_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(rename_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(rename_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(rename_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat.bpf.c index 27a5ea028a..b1edf9b0a4 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(renameat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(renameat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RENAMEAT_E_SIZE, PPME_SYSCALL_RENAMEAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RENAMEAT_E_SIZE, PPME_SYSCALL_RENAMEAT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(renameat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(renameat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(renameat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(renameat_x, /* Parameter 2: olddirfd (type: PT_FD) */ int32_t olddirfd = (int32_t)extract__syscall_argument(regs, 0); - if(olddirfd == AT_FDCWD) - { + if(olddirfd == AT_FDCWD) { olddirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)olddirfd); @@ -71,8 +62,7 @@ int BPF_PROG(renameat_x, /* Parameter 4: newdirfd (type: PT_FD) */ int32_t newdirfd = (int32_t)extract__syscall_argument(regs, 2); - if(newdirfd == AT_FDCWD) - { + if(newdirfd == AT_FDCWD) { newdirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)newdirfd); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat2.bpf.c index 7c003e6a5a..4d96aabb4e 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/renameat2.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(renameat2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(renameat2_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RENAMEAT2_E_SIZE, PPME_SYSCALL_RENAMEAT2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RENAMEAT2_E_SIZE, PPME_SYSCALL_RENAMEAT2_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(renameat2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(renameat2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(renameat2_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(renameat2_x, /* Parameter 2: olddirfd (type: PT_FD) */ int32_t olddirfd = (int32_t)extract__syscall_argument(regs, 0); - if(olddirfd == AT_FDCWD) - { + if(olddirfd == AT_FDCWD) { olddirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)olddirfd); @@ -71,8 +62,7 @@ int BPF_PROG(renameat2_x, /* Parameter 4: newdirfd (type: PT_FD) */ int32_t newdirfd = (int32_t)extract__syscall_argument(regs, 2); - if(newdirfd == AT_FDCWD) - { + if(newdirfd == AT_FDCWD) { newdirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)newdirfd); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rmdir.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rmdir.bpf.c index 92d8f705c3..419a169717 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rmdir.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/rmdir.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(rmdir_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(rmdir_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, RMDIR_E_SIZE, PPME_SYSCALL_RMDIR_2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, RMDIR_E_SIZE, PPME_SYSCALL_RMDIR_2_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(rmdir_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(rmdir_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(rmdir_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/seccomp.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/seccomp.bpf.c index cd39366496..7c806af647 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/seccomp.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/seccomp.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(seccomp_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(seccomp_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SECCOMP_E_SIZE, PPME_SYSCALL_SECCOMP_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SECCOMP_E_SIZE, PPME_SYSCALL_SECCOMP_E)) { return 0; } @@ -44,13 +40,9 @@ int BPF_PROG(seccomp_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(seccomp_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(seccomp_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SECCOMP_X_SIZE, PPME_SYSCALL_SECCOMP_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SECCOMP_X_SIZE, PPME_SYSCALL_SECCOMP_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/select.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/select.bpf.c index 71c85e9a92..8638949bbc 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/select.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/select.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(select_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(select_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SELECT_E_SIZE, PPME_SYSCALL_SELECT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SELECT_E_SIZE, PPME_SYSCALL_SELECT_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(select_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(select_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(select_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SELECT_X_SIZE, PPME_SYSCALL_SELECT_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SELECT_X_SIZE, PPME_SYSCALL_SELECT_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semctl.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semctl.bpf.c index 35ab4e81e0..9d39edcb66 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semctl.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semctl.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(semctl_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(semctl_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SEMCTL_E_SIZE, PPME_SYSCALL_SEMCTL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SEMCTL_E_SIZE, PPME_SYSCALL_SEMCTL_E)) { return 0; } @@ -39,8 +35,7 @@ int BPF_PROG(semctl_e, /* Parameter 4: val (type: PT_INT32) */ int32_t val = 0; - if(cmd == SETVAL) - { + if(cmd == SETVAL) { val = (int32_t)extract__syscall_argument(regs, 3); } ringbuf__store_s32(&ringbuf, val); @@ -53,13 +48,9 @@ int BPF_PROG(semctl_e, } SEC("tp_btf/sys_exit") -int BPF_PROG(semctl_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(semctl_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SEMCTL_X_SIZE, PPME_SYSCALL_SEMCTL_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SEMCTL_X_SIZE, PPME_SYSCALL_SEMCTL_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semget.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semget.bpf.c index 0753f84619..78a96158a2 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semget.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semget.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(semget_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(semget_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SEMGET_E_SIZE, PPME_SYSCALL_SEMGET_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SEMGET_E_SIZE, PPME_SYSCALL_SEMGET_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(semget_e, } SEC("tp_btf/sys_exit") -int BPF_PROG(semget_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(semget_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SEMGET_X_SIZE, PPME_SYSCALL_SEMGET_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SEMGET_X_SIZE, PPME_SYSCALL_SEMGET_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semop.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semop.bpf.c index cfbebc861a..54b869e082 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semop.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/semop.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(semop_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(semop_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SEMOP_E_SIZE, PPME_SYSCALL_SEMOP_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SEMOP_E_SIZE, PPME_SYSCALL_SEMOP_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(semop_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(semop_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(semop_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SEMOP_X_SIZE, PPME_SYSCALL_SEMOP_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SEMOP_X_SIZE, PPME_SYSCALL_SEMOP_X)) { return 0; } @@ -66,23 +58,20 @@ int BPF_PROG(semop_x, struct sembuf sops[2] = {0}; unsigned long sops_pointer = extract__syscall_argument(regs, 1); - if(ret != 0 || sops_pointer == 0 || nsops == 0) - { + if(ret != 0 || sops_pointer == 0 || nsops == 0) { /* We send all 0 when one of these is true: * - the syscall fails (ret != 0) * - `sops_pointer` is NULL * - `nsops` is 0 */ - } - else if(nsops == 1) - { + } else if(nsops == 1) { /* If we have just one entry the second will be empty, we don't fill it */ bpf_probe_read_user((void *)sops, bpf_core_type_size(struct sembuf), (void *)sops_pointer); - } - else - { + } else { /* If `nsops>1` we read just the first 2 entries. */ - bpf_probe_read_user((void *)sops, bpf_core_type_size(struct sembuf) * 2, (void *)sops_pointer); + bpf_probe_read_user((void *)sops, + bpf_core_type_size(struct sembuf) * 2, + (void *)sops_pointer); } /* Parameter 3: sem_num_0 (type: PT_UINT16) */ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/send.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/send.bpf.c index c68bfeba29..95a427fda7 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/send.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/send.bpf.c @@ -12,17 +12,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(send_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(send_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long args[3] = {0}; extract__network_args(args, 3, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SEND_E_SIZE, PPME_SOCKET_SEND_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SEND_E_SIZE, PPME_SOCKET_SEND_E)) { return 0; } @@ -50,13 +46,9 @@ int BPF_PROG(send_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(send_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(send_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -74,8 +66,7 @@ int BPF_PROG(send_x, int64_t bytes_to_read = ret > 0 ? ret : args[2]; uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SOCKET_SEND_X); - if((int64_t)snaplen > bytes_to_read) - { + if((int64_t)snaplen > bytes_to_read) { snaplen = bytes_to_read; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendfile.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendfile.bpf.c index 7dcc6bd3bd..e66b78c019 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendfile.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendfile.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(sendfile_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(sendfile_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SENDFILE_E_SIZE, PPME_SYSCALL_SENDFILE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SENDFILE_E_SIZE, PPME_SYSCALL_SENDFILE_E)) { return 0; } @@ -55,13 +51,9 @@ int BPF_PROG(sendfile_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(sendfile_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(sendfile_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SENDFILE_X_SIZE, PPME_SYSCALL_SENDFILE_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SENDFILE_X_SIZE, PPME_SYSCALL_SENDFILE_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmmsg.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmmsg.bpf.c index 678c8326ff..36c80463e5 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmmsg.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmmsg.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(sendmmsg_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(sendmmsg_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SENDMMSG_E_SIZE, PPME_SOCKET_SENDMMSG_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SENDMMSG_E_SIZE, PPME_SOCKET_SENDMMSG_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(sendmmsg_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(sendmmsg_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(sendmmsg_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SENDMMSG_X_SIZE, PPME_SOCKET_SENDMMSG_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SENDMMSG_X_SIZE, PPME_SOCKET_SENDMMSG_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmsg.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmsg.bpf.c index af63dab1f5..f5307a78de 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmsg.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendmsg.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(sendmsg_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(sendmsg_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SOCKET_SENDMSG_E); @@ -43,15 +39,12 @@ int BPF_PROG(sendmsg_e, * the `bpf_probe_read()` call we fail. Probably we have to move it * in the exit event. */ - if(socket_fd >= 0) - { + if(socket_fd >= 0) { struct sockaddr *usrsockaddr; - struct msghdr *msg = (struct msghdr*)msghdr_pointer; + struct msghdr *msg = (struct msghdr *)msghdr_pointer; BPF_CORE_READ_USER_INTO(&usrsockaddr, msg, msg_name); auxmap__store_socktuple_param(auxmap, socket_fd, OUTBOUND, usrsockaddr); - } - else - { + } else { auxmap__store_empty_param(auxmap); } @@ -69,13 +62,9 @@ int BPF_PROG(sendmsg_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(sendmsg_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(sendmsg_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -97,8 +86,7 @@ int BPF_PROG(sendmsg_x, */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SOCKET_SENDMSG_X); - if(ret > 0 && snaplen > ret) - { + if(ret > 0 && snaplen > ret) { snaplen = ret; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendto.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendto.bpf.c index fc888a976c..3fdd6a8a9b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendto.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/sendto.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(sendto_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(sendto_e, struct pt_regs *regs, long id) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SOCKET_SENDTO_E); @@ -43,13 +39,10 @@ int BPF_PROG(sendto_e, * the `bpf_probe_read()` call we fail. Probably we have to move it * in the exit event. */ - if(socket_fd >= 0) - { + if(socket_fd >= 0) { struct sockaddr *usrsockaddr = (struct sockaddr *)args[4]; auxmap__store_socktuple_param(auxmap, socket_fd, OUTBOUND, usrsockaddr); - } - else - { + } else { auxmap__store_empty_param(auxmap); } @@ -67,13 +60,9 @@ int BPF_PROG(sendto_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(sendto_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(sendto_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -94,8 +83,7 @@ int BPF_PROG(sendto_x, int64_t bytes_to_read = ret > 0 ? ret : args[2]; uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SOCKET_SENDTO_X); - if((int64_t)snaplen > bytes_to_read) - { + if((int64_t)snaplen > bytes_to_read) { snaplen = bytes_to_read; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setgid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setgid.bpf.c index aa8e73c058..6dfae9e213 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setgid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setgid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setgid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setgid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETGID_E_SIZE, PPME_SYSCALL_SETGID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETGID_E_SIZE, PPME_SYSCALL_SETGID_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(setgid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setgid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setgid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETGID_X_SIZE, PPME_SYSCALL_SETGID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETGID_X_SIZE, PPME_SYSCALL_SETGID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setns.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setns.bpf.c index 56aec052d2..87b36d1a35 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setns.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setns.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setns_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setns_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETNS_E_SIZE, PPME_SYSCALL_SETNS_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETNS_E_SIZE, PPME_SYSCALL_SETNS_E)) { return 0; } @@ -31,7 +27,7 @@ int BPF_PROG(setns_e, /* Parameter 2: nstype (type: PT_FLAGS32) */ unsigned long nstype = extract__syscall_argument(regs, 1); - ringbuf__store_u32(&ringbuf, clone_flags_to_scap((int) nstype)); + ringbuf__store_u32(&ringbuf, clone_flags_to_scap((int)nstype)); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -45,13 +41,9 @@ int BPF_PROG(setns_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setns_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setns_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETNS_X_SIZE, PPME_SYSCALL_SETNS_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETNS_X_SIZE, PPME_SYSCALL_SETNS_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setpgid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setpgid.bpf.c index fd2b017917..ea54ad2042 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setpgid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setpgid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setpgid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setpgid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETPGID_E_SIZE, PPME_SYSCALL_SETPGID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETPGID_E_SIZE, PPME_SYSCALL_SETPGID_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(setpgid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setpgid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setpgid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETPGID_X_SIZE, PPME_SYSCALL_SETPGID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETPGID_X_SIZE, PPME_SYSCALL_SETPGID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setregid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setregid.bpf.c index 3c1018c475..66f10515b3 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setregid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setregid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setregid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setregid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETREGID_E_SIZE, PPME_SYSCALL_SETREGID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETREGID_E_SIZE, PPME_SYSCALL_SETREGID_E)) { return 0; } @@ -37,13 +33,9 @@ int BPF_PROG(setregid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setregid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setregid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETREGID_X_SIZE, PPME_SYSCALL_SETREGID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETREGID_X_SIZE, PPME_SYSCALL_SETREGID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresgid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresgid.bpf.c index 426f4ce108..69fe107f75 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresgid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresgid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setresgid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setresgid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESGID_E_SIZE, PPME_SYSCALL_SETRESGID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESGID_E_SIZE, PPME_SYSCALL_SETRESGID_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(setresgid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setresgid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setresgid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESGID_X_SIZE, PPME_SYSCALL_SETRESGID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESGID_X_SIZE, PPME_SYSCALL_SETRESGID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresuid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresuid.bpf.c index 317a96ee69..9e1d6ea468 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresuid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setresuid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setresuid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setresuid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESUID_E_SIZE, PPME_SYSCALL_SETRESUID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESUID_E_SIZE, PPME_SYSCALL_SETRESUID_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(setresuid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setresuid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setresuid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESUID_X_SIZE, PPME_SYSCALL_SETRESUID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETRESUID_X_SIZE, PPME_SYSCALL_SETRESUID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setreuid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setreuid.bpf.c index c9e790fd5d..058a18b606 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setreuid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setreuid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setreuid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setreuid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETREUID_E_SIZE, PPME_SYSCALL_SETREUID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETREUID_E_SIZE, PPME_SYSCALL_SETREUID_E)) { return 0; } @@ -37,13 +33,9 @@ int BPF_PROG(setreuid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setreuid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setreuid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETREUID_X_SIZE, PPME_SYSCALL_SETREUID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETREUID_X_SIZE, PPME_SYSCALL_SETREUID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setrlimit.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setrlimit.bpf.c index 48f59ebf97..420cecda92 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setrlimit.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setrlimit.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setrlimit_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setrlimit_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETRLIMIT_E_SIZE, PPME_SYSCALL_SETRLIMIT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETRLIMIT_E_SIZE, PPME_SYSCALL_SETRLIMIT_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(setrlimit_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setrlimit_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setrlimit_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETRLIMIT_X_SIZE, PPME_SYSCALL_SETRLIMIT_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETRLIMIT_X_SIZE, PPME_SYSCALL_SETRLIMIT_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsid.bpf.c index 54c1c0441f..35c98acbfc 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setsid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setsid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETSID_E_SIZE, PPME_SYSCALL_SETSID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETSID_E_SIZE, PPME_SYSCALL_SETSID_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(setsid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setsid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setsid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETSID_X_SIZE, PPME_SYSCALL_SETSID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETSID_X_SIZE, PPME_SYSCALL_SETSID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsockopt.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsockopt.bpf.c index d47a3d6b3a..3e5c92359a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsockopt.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setsockopt.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setsockopt_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setsockopt_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETSOCKOPT_E_SIZE, PPME_SOCKET_SETSOCKOPT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETSOCKOPT_E_SIZE, PPME_SOCKET_SETSOCKOPT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(setsockopt_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setsockopt_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setsockopt_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setuid.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setuid.bpf.c index 300efc7cea..bde1f8295b 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setuid.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/setuid.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(setuid_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(setuid_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETUID_E_SIZE, PPME_SYSCALL_SETUID_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETUID_E_SIZE, PPME_SYSCALL_SETUID_E)) { return 0; } @@ -41,13 +37,9 @@ int BPF_PROG(setuid_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(setuid_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(setuid_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SETUID_X_SIZE, PPME_SYSCALL_SETUID_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SETUID_X_SIZE, PPME_SYSCALL_SETUID_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/shutdown.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/shutdown.bpf.c index 396db0c946..55fede6ca2 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/shutdown.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/shutdown.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(shutdown_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(shutdown_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to easily manage socketcalls */ unsigned long args[2] = {0}; extract__network_args(args, 2, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SHUTDOWN_E_SIZE, PPME_SOCKET_SHUTDOWN_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SHUTDOWN_E_SIZE, PPME_SOCKET_SHUTDOWN_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(shutdown_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(shutdown_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(shutdown_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SHUTDOWN_X_SIZE, PPME_SOCKET_SHUTDOWN_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SHUTDOWN_X_SIZE, PPME_SOCKET_SHUTDOWN_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd.bpf.c index a02eeb4044..a38f70d05a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(signalfd_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(signalfd_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD_E_SIZE, PPME_SYSCALL_SIGNALFD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD_E_SIZE, PPME_SYSCALL_SIGNALFD_E)) { return 0; } @@ -51,13 +47,9 @@ int BPF_PROG(signalfd_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(signalfd_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(signalfd_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD_X_SIZE, PPME_SYSCALL_SIGNALFD_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD_X_SIZE, PPME_SYSCALL_SIGNALFD_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd4.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd4.bpf.c index 95e3a02f16..3097ad382e 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd4.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/signalfd4.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(signalfd4_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(signalfd4_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD4_E_SIZE, PPME_SYSCALL_SIGNALFD4_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD4_E_SIZE, PPME_SYSCALL_SIGNALFD4_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(signalfd4_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(signalfd4_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(signalfd4_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD4_X_SIZE, PPME_SYSCALL_SIGNALFD4_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SIGNALFD4_X_SIZE, PPME_SYSCALL_SIGNALFD4_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socket.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socket.bpf.c index d22bd71ea9..35c3c002e0 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socket.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socket.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(socket_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(socket_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning so we can easily manage socketcalls */ unsigned long args[3] = {0}; extract__network_args(args, 3, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKET_E_SIZE, PPME_SOCKET_SOCKET_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKET_E_SIZE, PPME_SOCKET_SOCKET_E)) { return 0; } @@ -56,13 +52,9 @@ int BPF_PROG(socket_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(socket_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(socket_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKET_X_SIZE, PPME_SOCKET_SOCKET_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKET_X_SIZE, PPME_SOCKET_SOCKET_X)) { return 0; } @@ -74,8 +66,7 @@ int BPF_PROG(socket_x, ringbuf__store_s64(&ringbuf, ret); /* Just called once by our scap process */ - if(ret >= 0 && maps__get_socket_file_ops() == NULL) - { + if(ret >= 0 && maps__get_socket_file_ops() == NULL) { struct task_struct *task = get_current_task(); /* Please note that in `g_settings.scap_tid` scap will put its virtual tid * if it is running inside a container. If we want to extract the same information @@ -83,13 +74,11 @@ int BPF_PROG(socket_x, */ pid_t vtid = extract__task_xid_vnr(task, PIDTYPE_PID); /* it means that scap is performing the calibration */ - if(vtid == maps__get_scap_tid()) - { + if(vtid == maps__get_scap_tid()) { struct file *f = extract__file_struct_from_fd(ret); - if(f) - { + if(f) { struct file_operations *f_op = (struct file_operations *)BPF_CORE_READ(f, f_op); - maps__set_socket_file_ops((void*)f_op); + maps__set_socket_file_ops((void *)f_op); /* we need to rewrite the event header */ ringbuf__rewrite_header_for_calibration(&ringbuf, vtid); } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socketpair.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socketpair.bpf.c index 4d8a1dc2a7..5338fd9af1 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socketpair.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/socketpair.bpf.c @@ -11,17 +11,13 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(socketpair_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(socketpair_e, struct pt_regs *regs, long id) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long args[3] = {0}; extract__network_args(args, 3, regs); struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKETPAIR_E_SIZE, PPME_SOCKET_SOCKETPAIR_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKETPAIR_E_SIZE, PPME_SOCKET_SOCKETPAIR_E)) { return 0; } @@ -56,13 +52,9 @@ int BPF_PROG(socketpair_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(socketpair_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(socketpair_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKETPAIR_X_SIZE, PPME_SOCKET_SOCKETPAIR_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SOCKETPAIR_X_SIZE, PPME_SOCKET_SOCKETPAIR_X)) { return 0; } @@ -79,8 +71,7 @@ int BPF_PROG(socketpair_x, unsigned long fds_pointer = 0; /* In case of success we have 0. */ - if(ret == 0) - { + if(ret == 0) { /* Collect parameters at the beginning to manage socketcalls */ unsigned long args[4] = {0}; extract__network_args(args, 4, regs); @@ -92,8 +83,7 @@ int BPF_PROG(socketpair_x, /* Get source and peer. */ struct file *file = extract__file_struct_from_fd((int32_t)fds[0]); struct socket *socket = get_sock_from_file(file); - if(socket != NULL) - { + if(socket != NULL) { BPF_CORE_READ_INTO(&source, socket, sk); struct unix_sock *us = (struct unix_sock *)source; BPF_CORE_READ_INTO(&peer, us, peer); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/splice.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/splice.bpf.c index 685d3e742b..5498157ed5 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/splice.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/splice.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(splice_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(splice_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SPLICE_E_SIZE, PPME_SYSCALL_SPLICE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SPLICE_E_SIZE, PPME_SYSCALL_SPLICE_E)) { return 0; } @@ -53,13 +49,9 @@ int BPF_PROG(splice_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(splice_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(splice_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SPLICE_X_SIZE, PPME_SYSCALL_SPLICE_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SPLICE_X_SIZE, PPME_SYSCALL_SPLICE_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/stat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/stat.bpf.c index 89a8dbecf3..d85967434a 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/stat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/stat.bpf.c @@ -6,20 +6,15 @@ * or GPL2.txt for full copies of the license. */ - #include #include /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(stat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(stat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, STAT_E_SIZE, PPME_SYSCALL_STAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, STAT_E_SIZE, PPME_SYSCALL_STAT_E)) { return 0; } @@ -41,13 +36,9 @@ int BPF_PROG(stat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(stat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(stat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlink.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlink.bpf.c index 805b06690d..f6fd68a290 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlink.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlink.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(symlink_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(symlink_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SYMLINK_E_SIZE, PPME_SYSCALL_SYMLINK_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SYMLINK_E_SIZE, PPME_SYSCALL_SYMLINK_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(symlink_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(symlink_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(symlink_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlinkat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlinkat.bpf.c index 5611329af5..45d94128fc 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlinkat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/symlinkat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(symlinkat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(symlinkat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, SYMLINKAT_E_SIZE, PPME_SYSCALL_SYMLINKAT_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, SYMLINKAT_E_SIZE, PPME_SYSCALL_SYMLINKAT_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(symlinkat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(symlinkat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(symlinkat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -63,8 +55,7 @@ int BPF_PROG(symlinkat_x, /* Parameter 3: linkdirfd (type: PT_FD) */ int32_t linkdirfd = (int32_t)extract__syscall_argument(regs, 1); - if(linkdirfd == AT_FDCWD) - { + if(linkdirfd == AT_FDCWD) { linkdirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)linkdirfd); diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tgkill.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tgkill.bpf.c index ad0fdf7a55..9affe99d9c 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tgkill.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tgkill.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(tgkill_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(tgkill_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, TGKILL_E_SIZE, PPME_SYSCALL_TGKILL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, TGKILL_E_SIZE, PPME_SYSCALL_TGKILL_E)) { return 0; } @@ -49,13 +45,9 @@ int BPF_PROG(tgkill_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(tgkill_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(tgkill_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, TGKILL_X_SIZE, PPME_SYSCALL_TGKILL_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, TGKILL_X_SIZE, PPME_SYSCALL_TGKILL_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/timerfd_create.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/timerfd_create.bpf.c index d9d3281882..0e891ac938 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/timerfd_create.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/timerfd_create.bpf.c @@ -11,13 +11,12 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(timerfd_create_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(timerfd_create_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, TIMERFD_CREATE_E_SIZE, PPME_SYSCALL_TIMERFD_CREATE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + TIMERFD_CREATE_E_SIZE, + PPME_SYSCALL_TIMERFD_CREATE_E)) { return 0; } @@ -45,13 +44,12 @@ int BPF_PROG(timerfd_create_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(timerfd_create_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(timerfd_create_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, TIMERFD_CREATE_X_SIZE, PPME_SYSCALL_TIMERFD_CREATE_X)) - { + if(!ringbuf__reserve_space(&ringbuf, + ctx, + TIMERFD_CREATE_X_SIZE, + PPME_SYSCALL_TIMERFD_CREATE_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tkill.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tkill.bpf.c index a9308a336d..1cd4e1d7eb 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tkill.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/tkill.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(tkill_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(tkill_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, TKILL_E_SIZE, PPME_SYSCALL_TKILL_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, TKILL_E_SIZE, PPME_SYSCALL_TKILL_E)) { return 0; } @@ -45,13 +41,9 @@ int BPF_PROG(tkill_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(tkill_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(tkill_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, TKILL_X_SIZE, PPME_SYSCALL_TKILL_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, TKILL_X_SIZE, PPME_SYSCALL_TKILL_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount.bpf.c index b3a3652b41..d05962c6c0 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(umount_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(umount_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, UMOUNT_E_SIZE, PPME_SYSCALL_UMOUNT_1_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, UMOUNT_E_SIZE, PPME_SYSCALL_UMOUNT_1_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(umount_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(umount_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(umount_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount2.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount2.bpf.c index a6d3a61961..8e5f6c1d90 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount2.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/umount2.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(umount2_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(umount2_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, UMOUNT2_E_SIZE, PPME_SYSCALL_UMOUNT2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, UMOUNT2_E_SIZE, PPME_SYSCALL_UMOUNT2_E)) { return 0; } @@ -42,13 +38,9 @@ int BPF_PROG(umount2_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(umount2_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(umount2_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlink.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlink.bpf.c index 852a0c898f..41cdfdc132 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlink.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlink.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(unlink_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(unlink_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, UNLINK_E_SIZE, PPME_SYSCALL_UNLINK_2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, UNLINK_E_SIZE, PPME_SYSCALL_UNLINK_2_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(unlink_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(unlink_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(unlink_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlinkat.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlinkat.bpf.c index aa4510f163..eef96a8a52 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlinkat.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unlinkat.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(unlinkat_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(unlinkat_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, UNLINKAT_E_SIZE, PPME_SYSCALL_UNLINKAT_2_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, UNLINKAT_E_SIZE, PPME_SYSCALL_UNLINKAT_2_E)) { return 0; } @@ -40,13 +36,9 @@ int BPF_PROG(unlinkat_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(unlinkat_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(unlinkat_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -59,8 +51,7 @@ int BPF_PROG(unlinkat_x, /* Parameter 2: dirfd (type: PT_FD) */ int32_t dirfd = (int32_t)extract__syscall_argument(regs, 0); - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } auxmap__store_s64_param(auxmap, (int64_t)dirfd); @@ -71,7 +62,7 @@ int BPF_PROG(unlinkat_x, /* Parameter 4: flags (type: PT_FLAGS32) */ unsigned long flags = extract__syscall_argument(regs, 2); - auxmap__store_u32_param(auxmap, unlinkat_flags_to_scap((int32_t) flags)); + auxmap__store_u32_param(auxmap, unlinkat_flags_to_scap((int32_t)flags)); /*=============================== COLLECT PARAMETERS ===========================*/ diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unshare.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unshare.bpf.c index 3f4b9a1d67..f8f2c316b2 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unshare.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/unshare.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(unshare_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(unshare_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, UNSHARE_E_SIZE, PPME_SYSCALL_UNSHARE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, UNSHARE_E_SIZE, PPME_SYSCALL_UNSHARE_E)) { return 0; } @@ -27,7 +23,7 @@ int BPF_PROG(unshare_e, /* Parameter 1: flags (type: PT_FLAGS32) */ unsigned long flags = extract__syscall_argument(regs, 0); - ringbuf__store_u32(&ringbuf, clone_flags_to_scap((int) flags)); + ringbuf__store_u32(&ringbuf, clone_flags_to_scap((int)flags)); /*=============================== COLLECT PARAMETERS ===========================*/ @@ -41,13 +37,9 @@ int BPF_PROG(unshare_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(unshare_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(unshare_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, UNSHARE_X_SIZE, PPME_SYSCALL_UNSHARE_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, UNSHARE_X_SIZE, PPME_SYSCALL_UNSHARE_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/userfaultfd.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/userfaultfd.bpf.c index d0a796d438..6a8830c185 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/userfaultfd.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/userfaultfd.bpf.c @@ -11,13 +11,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(userfaultfd_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(userfaultfd_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, USERFAULTFD_E_SIZE, PPME_SYSCALL_USERFAULTFD_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, USERFAULTFD_E_SIZE, PPME_SYSCALL_USERFAULTFD_E)) { return 0; } @@ -39,13 +35,9 @@ int BPF_PROG(userfaultfd_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(userfaultfd_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(userfaultfd_x, struct pt_regs *regs, long ret) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, USERFAULTFD_X_SIZE, PPME_SYSCALL_USERFAULTFD_X)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, USERFAULTFD_X_SIZE, PPME_SYSCALL_USERFAULTFD_X)) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/vfork.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/vfork.bpf.c index d4f45e7d31..544d5ebffd 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/vfork.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/vfork.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(vfork_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(vfork_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, VFORK_E_SIZE, PPME_SYSCALL_VFORK_20_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, VFORK_E_SIZE, PPME_SYSCALL_VFORK_20_E)) { return 0; } @@ -40,26 +36,20 @@ int BPF_PROG(vfork_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(vfork_x, - struct pt_regs *regs, - long ret) -{ - +int BPF_PROG(vfork_x, struct pt_regs *regs, long ret) { /* We already catch the vfork child event with our `sched_process_fork` tracepoint, * for this reason we don't need also this instrumentation. Please note that we use * the aforementioned tracepoint only for the child event but we need to catch also * the father event or the failure case, for this reason we check the `ret==0` */ #ifdef CAPTURE_SCHED_PROC_FORK - if(ret == 0) - { + if(ret == 0) { return 0; } #endif struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } auxmap__preload_event_header(auxmap, PPME_SYSCALL_VFORK_20_X); @@ -74,8 +64,7 @@ int BPF_PROG(vfork_x, /* We can extract `exe` (Parameter 2) and `args`(Parameter 3) only if the * syscall doesn't fail. Otherwise, they will send empty parameters. */ - if(ret >= 0) - { + if(ret >= 0) { unsigned long arg_start_pointer = 0; unsigned long arg_end_pointer = 0; @@ -89,15 +78,16 @@ int BPF_PROG(vfork_x, READ_TASK_FIELD_INTO(&arg_end_pointer, task, mm, arg_end); /* Parameter 2: exe (type: PT_CHARBUF) */ - uint16_t exe_arg_len = auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); + uint16_t exe_arg_len = + auxmap__store_charbuf_param(auxmap, arg_start_pointer, MAX_PROC_EXE, USER); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ unsigned long total_args_len = arg_end_pointer - arg_start_pointer; - auxmap__store_charbufarray_as_bytebuf(auxmap, arg_start_pointer + exe_arg_len, - total_args_len - exe_arg_len, MAX_PROC_ARG_ENV - exe_arg_len); - } - else - { + auxmap__store_charbufarray_as_bytebuf(auxmap, + arg_start_pointer + exe_arg_len, + total_args_len - exe_arg_len, + MAX_PROC_ARG_ENV - exe_arg_len); + } else { /* Parameter 2: exe (type: PT_CHARBUF) */ auxmap__store_empty_param(auxmap); @@ -165,13 +155,9 @@ int BPF_PROG(vfork_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t1_vfork_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t1_vfork_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -215,13 +201,9 @@ int BPF_PROG(t1_vfork_x, } SEC("tp_btf/sys_exit") -int BPF_PROG(t2_vfork_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(t2_vfork_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/write.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/write.bpf.c index 0e34c0123d..45fcfb392c 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/write.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/write.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(write_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(write_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, WRITE_E_SIZE, PPME_SYSCALL_WRITE_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, WRITE_E_SIZE, PPME_SYSCALL_WRITE_E)) { return 0; } @@ -46,13 +42,9 @@ int BPF_PROG(write_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(write_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(write_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -69,8 +61,7 @@ int BPF_PROG(write_x, int64_t bytes_to_read = ret > 0 ? ret : extract__syscall_argument(regs, 2); uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, false, PPME_SYSCALL_WRITE_X); - if((int64_t)snaplen > bytes_to_read) - { + if((int64_t)snaplen > bytes_to_read) { snaplen = bytes_to_read; } diff --git a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/writev.bpf.c b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/writev.bpf.c index 6ed8f6e6c4..ab9fc8ccb6 100644 --- a/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/writev.bpf.c +++ b/driver/modern_bpf/programs/tail_called/events/syscall_dispatched_events/writev.bpf.c @@ -12,13 +12,9 @@ /*=============================== ENTER EVENT ===========================*/ SEC("tp_btf/sys_enter") -int BPF_PROG(writev_e, - struct pt_regs *regs, - long id) -{ +int BPF_PROG(writev_e, struct pt_regs *regs, long id) { struct ringbuf_struct ringbuf; - if(!ringbuf__reserve_space(&ringbuf, ctx, WRITEV_E_SIZE, PPME_SYSCALL_WRITEV_E)) - { + if(!ringbuf__reserve_space(&ringbuf, ctx, WRITEV_E_SIZE, PPME_SYSCALL_WRITEV_E)) { return 0; } @@ -48,13 +44,9 @@ int BPF_PROG(writev_e, /*=============================== EXIT EVENT ===========================*/ SEC("tp_btf/sys_exit") -int BPF_PROG(writev_x, - struct pt_regs *regs, - long ret) -{ +int BPF_PROG(writev_x, struct pt_regs *regs, long ret) { struct auxiliary_map *auxmap = auxmap__get(); - if(!auxmap) - { + if(!auxmap) { return 0; } @@ -72,8 +64,7 @@ int BPF_PROG(writev_x, */ uint16_t snaplen = maps__get_snaplen(); apply_dynamic_snaplen(regs, &snaplen, true, PPME_SYSCALL_WRITEV_X); - if(ret > 0 && snaplen > ret) - { + if(ret > 0 && snaplen > ret) { snaplen = ret; } diff --git a/driver/modern_bpf/shared_definitions/struct_definitions.h b/driver/modern_bpf/shared_definitions/struct_definitions.h index c97d89c0a0..8bda9ff949 100644 --- a/driver/modern_bpf/shared_definitions/struct_definitions.h +++ b/driver/modern_bpf/shared_definitions/struct_definitions.h @@ -22,18 +22,17 @@ * @brief General settings shared among all the CPUs. * */ -struct capture_settings -{ - uint64_t boot_time; /* boot time. */ - uint32_t snaplen; /* we use it when we want to read a maximum size from an event and no more. */ - bool dropping_mode; /* this flag actives the sampling logic */ - uint32_t sampling_ratio; /* this config tells tracepoints when they have to drop events */ - bool drop_failed; /* whether to drop failed syscalls (exit events) */ - bool do_dynamic_snaplen; /* enforce snaplen according to the event content */ +struct capture_settings { + uint64_t boot_time; /* boot time. */ + uint32_t snaplen; /* we use it when we want to read a maximum size from an event and no more. */ + bool dropping_mode; /* this flag actives the sampling logic */ + uint32_t sampling_ratio; /* this config tells tracepoints when they have to drop events */ + bool drop_failed; /* whether to drop failed syscalls (exit events) */ + bool do_dynamic_snaplen; /* enforce snaplen according to the event content */ uint16_t fullcapture_port_range_start; /* first interesting port */ uint16_t fullcapture_port_range_end; /* last interesting port */ - uint16_t statsd_port; /* port for statsd metrics */ - int32_t scap_tid; /* tid of the scap process */ + uint16_t statsd_port; /* port for statsd metrics */ + int32_t scap_tid; /* tid of the scap process */ }; /** @@ -43,12 +42,11 @@ struct capture_settings * * To have more info about the event format, please look at `helpers/base/push_data.h` */ -struct auxiliary_map -{ +struct auxiliary_map { uint8_t data[AUXILIARY_MAP_SIZE]; /* raw space to save our variable-size event. */ - uint64_t payload_pos; /* position of the first empty byte in the `data` buf. */ - uint8_t lengths_pos; /* position the first empty slot into the lengths array of the event. */ - uint16_t event_type; /* event type we want to send to userspace */ + uint64_t payload_pos; /* position of the first empty byte in the `data` buf. */ + uint8_t lengths_pos; /* position the first empty slot into the lengths array of the event. */ + uint16_t event_type; /* event type we want to send to userspace */ }; /* These per-cpu maps are used to carry the number of drops and @@ -59,11 +57,11 @@ struct auxiliary_map * @brief These per-cpu maps are used to carry the number of dropped and * processed events. */ -struct counter_map -{ - uint64_t n_evts; /* Number of events correctly sent to userspace. */ - uint64_t n_drops_buffer; /* Number of drops due to a full ringbuf. */ - /* Kernel side drops due to full buffer for categories of system calls. Not all system calls of interest are mapped into one of the categories. */ +struct counter_map { + uint64_t n_evts; /* Number of events correctly sent to userspace. */ + uint64_t n_drops_buffer; /* Number of drops due to a full ringbuf. */ + /* Kernel side drops due to full buffer for categories of system calls. Not all system calls of + * interest are mapped into one of the categories. */ uint64_t n_drops_buffer_clone_fork_enter; uint64_t n_drops_buffer_clone_fork_exit; uint64_t n_drops_buffer_execve_enter; @@ -75,7 +73,9 @@ struct counter_map uint64_t n_drops_buffer_dir_file_enter; uint64_t n_drops_buffer_dir_file_exit; uint64_t n_drops_buffer_other_interest_enter; - uint64_t n_drops_buffer_other_interest_exit; /* Category of other system calls of interest, not all other system calls that did not match a category from above. */ + uint64_t n_drops_buffer_other_interest_exit; /* Category of other system calls of interest, not + all other system calls that did not match a + category from above. */ uint64_t n_drops_buffer_close_exit; uint64_t n_drops_buffer_proc_exit; uint64_t n_drops_max_event_size; /* Number of drops due to an excessive event size (>64KB). */ diff --git a/driver/ppm.h b/driver/ppm.h index 912c220bc5..9d92273358 100644 --- a/driver/ppm.h +++ b/driver/ppm.h @@ -49,7 +49,7 @@ struct ppm_ring_buffer_context { nanoseconds last_print_time; uint32_t nevents; atomic_t preempt_count; - char *str_storage; /* String storage. Size is one page. */ + char *str_storage; /* String storage. Size is one page. */ }; /* @@ -67,21 +67,21 @@ long ppm_strncpy_from_user(char *to, const char __user *from, unsigned long n); */ #ifdef CONFIG_MIPS - #define SYSCALL_TABLE_ID0 __NR_Linux +#define SYSCALL_TABLE_ID0 __NR_Linux #elif defined CONFIG_ARM - #define SYSCALL_TABLE_ID0 __NR_SYSCALL_BASE +#define SYSCALL_TABLE_ID0 __NR_SYSCALL_BASE #elif defined CONFIG_X86 || defined CONFIG_SUPERH - #define SYSCALL_TABLE_ID0 0 +#define SYSCALL_TABLE_ID0 0 #elif defined CONFIG_PPC64 - #define SYSCALL_TABLE_ID0 0 +#define SYSCALL_TABLE_ID0 0 #elif defined CONFIG_S390 - #define SYSCALL_TABLE_ID0 0 +#define SYSCALL_TABLE_ID0 0 #elif defined CONFIG_ARM64 - #define SYSCALL_TABLE_ID0 0 +#define SYSCALL_TABLE_ID0 0 #elif defined CONFIG_RISCV - #define SYSCALL_TABLE_ID0 0 +#define SYSCALL_TABLE_ID0 0 #elif defined CONFIG_LOONGARCH - #define SYSCALL_TABLE_ID0 0 +#define SYSCALL_TABLE_ID0 0 #endif extern const struct syscall_evt_pair g_syscall_table[]; @@ -91,7 +91,9 @@ extern const struct ppm_event_info g_event_info[]; extern const struct syscall_evt_pair g_syscall_ia32_table[]; #endif -extern void ppm_syscall_get_arguments(struct task_struct *task, struct pt_regs *regs, unsigned long *args); +extern void ppm_syscall_get_arguments(struct task_struct *task, + struct pt_regs *regs, + unsigned long *args); #define NS_TO_SEC(_ns) ((_ns) / 1000000000) #define MORE_THAN_ONE_SECOND_AHEAD(_ns1, _ns2) ((_ns1) - (_ns2) > 1000000000) diff --git a/driver/ppm_api_version.h b/driver/ppm_api_version.h index 76784e671c..52a6d35d45 100644 --- a/driver/ppm_api_version.h +++ b/driver/ppm_api_version.h @@ -19,8 +19,10 @@ * bits 0-23: patch version */ -#define PPM_VERSION_PACK(val, bits, shift) ((((unsigned long long)(val)) & ((1ULL << (bits)) - 1)) << (shift)) -#define PPM_VERSION_UNPACK(val, bits, shift) ((((unsigned long long)(val)) >> (shift)) & ((1ULL << (bits)) - 1)) +#define PPM_VERSION_PACK(val, bits, shift) \ + ((((unsigned long long)(val)) & ((1ULL << (bits)) - 1)) << (shift)) +#define PPM_VERSION_UNPACK(val, bits, shift) \ + ((((unsigned long long)(val)) >> (shift)) & ((1ULL << (bits)) - 1)) /* extract components from an API version number */ #define PPM_API_VERSION_MAJOR(ver) PPM_VERSION_UNPACK(ver, 19, 44) @@ -28,32 +30,31 @@ #define PPM_API_VERSION_PATCH(ver) PPM_VERSION_UNPACK(ver, 24, 0) /* build an API version number from components */ -#define PPM_API_VERSION(major, minor, patch) \ - PPM_VERSION_PACK(major, 19, 44) | \ - PPM_VERSION_PACK(minor, 20, 24) | \ - PPM_VERSION_PACK(patch, 24, 0) +#define PPM_API_VERSION(major, minor, patch) \ + PPM_VERSION_PACK(major, 19, 44) | PPM_VERSION_PACK(minor, 20, 24) | \ + PPM_VERSION_PACK(patch, 24, 0) -#define PPM_API_CURRENT_VERSION PPM_API_VERSION( \ - PPM_API_CURRENT_VERSION_MAJOR, \ - PPM_API_CURRENT_VERSION_MINOR, \ - PPM_API_CURRENT_VERSION_PATCH) +#define PPM_API_CURRENT_VERSION \ + PPM_API_VERSION(PPM_API_CURRENT_VERSION_MAJOR, \ + PPM_API_CURRENT_VERSION_MINOR, \ + PPM_API_CURRENT_VERSION_PATCH) -#define PPM_SCHEMA_CURRENT_VERSION PPM_API_VERSION( \ - PPM_SCHEMA_CURRENT_VERSION_MAJOR, \ - PPM_SCHEMA_CURRENT_VERSION_MINOR, \ - PPM_SCHEMA_CURRENT_VERSION_PATCH) +#define PPM_SCHEMA_CURRENT_VERSION \ + PPM_API_VERSION(PPM_SCHEMA_CURRENT_VERSION_MAJOR, \ + PPM_SCHEMA_CURRENT_VERSION_MINOR, \ + PPM_SCHEMA_CURRENT_VERSION_PATCH) #define __PPM_STRINGIFY1(x) #x #define __PPM_STRINGIFY(x) __PPM_STRINGIFY1(x) -#define PPM_API_CURRENT_VERSION_STRING \ - __PPM_STRINGIFY(PPM_API_CURRENT_VERSION_MAJOR) "." \ - __PPM_STRINGIFY(PPM_API_CURRENT_VERSION_MINOR) "." \ - __PPM_STRINGIFY(PPM_API_CURRENT_VERSION_PATCH) +#define PPM_API_CURRENT_VERSION_STRING \ + __PPM_STRINGIFY(PPM_API_CURRENT_VERSION_MAJOR) \ + "." __PPM_STRINGIFY(PPM_API_CURRENT_VERSION_MINOR) "." __PPM_STRINGIFY( \ + PPM_API_CURRENT_VERSION_PATCH) -#define PPM_SCHEMA_CURRENT_VERSION_STRING \ - __PPM_STRINGIFY(PPM_SCHEMA_CURRENT_VERSION_MAJOR) "." \ - __PPM_STRINGIFY(PPM_SCHEMA_CURRENT_VERSION_MINOR) "." \ - __PPM_STRINGIFY(PPM_SCHEMA_CURRENT_VERSION_PATCH) +#define PPM_SCHEMA_CURRENT_VERSION_STRING \ + __PPM_STRINGIFY(PPM_SCHEMA_CURRENT_VERSION_MAJOR) \ + "." __PPM_STRINGIFY(PPM_SCHEMA_CURRENT_VERSION_MINOR) "." __PPM_STRINGIFY( \ + PPM_SCHEMA_CURRENT_VERSION_PATCH) #endif diff --git a/driver/ppm_consumer.h b/driver/ppm_consumer.h index 89f5f936c0..319f24f4c7 100644 --- a/driver/ppm_consumer.h +++ b/driver/ppm_consumer.h @@ -14,7 +14,7 @@ or GPL2.txt for full copies of the license. #include struct ppm_consumer_t { - unsigned int id; // numeric id for the consumer (ie: registration index) + unsigned int id; // numeric id for the consumer (ie: registration index) struct task_struct *consumer_id; #ifdef __percpu struct ppm_ring_buffer_context __percpu *ring_buffers; @@ -41,4 +41,4 @@ struct ppm_consumer_t { typedef struct ppm_consumer_t ppm_consumer_t; -#endif // CONSUMER_H_ +#endif // CONSUMER_H_ diff --git a/driver/ppm_cputime.c b/driver/ppm_cputime.c index d20ac4baa9..55803e1b5a 100644 --- a/driver/ppm_cputime.c +++ b/driver/ppm_cputime.c @@ -11,9 +11,9 @@ or GPL2.txt for full copies of the license. // These function are taken from the linux kernel and are used only // on versions that don't export task_cputime_adjusted() -#if (LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) -#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 37)) +#if(LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 37)) #include #else #include @@ -37,9 +37,8 @@ or GPL2.txt for full copies of the license. #include "ppm.h" #include "ppm_version.h" -#if (defined CONFIG_VIRT_CPU_ACCOUNTING_NATIVE) || (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 30)) -void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st) -{ +#if(defined CONFIG_VIRT_CPU_ACCOUNTING_NATIVE) || (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 30)) +void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st) { *ut = p->utime; *st = p->stime; } @@ -51,7 +50,8 @@ void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t * #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 13, 0)) || (PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(7, 7)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 13, 0)) || \ + (PPM_RHEL_RELEASE_CODE > 0 && PPM_RHEL_RELEASE_CODE >= PPM_RHEL_RELEASE_VERSION(7, 7)) #define ppm_vtime_starttime(tsk) ((tsk)->vtime.starttime) #define ppm_vtime_seqlock(tsk) (&(tsk)->vtime.seqlock) #define ppm_vtime_state(tsk) ((tsk)->vtime.state) @@ -61,23 +61,23 @@ void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t * #define ppm_vtime_state(tsk) ((tsk)->vtime_snap_whence) #endif -static unsigned long long vtime_delta(struct task_struct *tsk) -{ +static unsigned long long vtime_delta(struct task_struct *tsk) { unsigned long long clock; clock = local_clock(); - if (clock < ppm_vtime_starttime(tsk)) + if(clock < ppm_vtime_starttime(tsk)) return 0; return clock - ppm_vtime_starttime(tsk); } -static void -fetch_task_cputime(struct task_struct *t, - cputime_t *u_dst, cputime_t *s_dst, - cputime_t *u_src, cputime_t *s_src, - cputime_t *udelta, cputime_t *sdelta) -{ +static void fetch_task_cputime(struct task_struct *t, + cputime_t *u_dst, + cputime_t *s_dst, + cputime_t *u_src, + cputime_t *s_src, + cputime_t *udelta, + cputime_t *sdelta) { unsigned int seq; unsigned long long delta; @@ -87,14 +87,13 @@ fetch_task_cputime(struct task_struct *t, seq = read_seqbegin(ppm_vtime_seqlock(t)); - if (u_dst) + if(u_dst) *u_dst = *u_src; - if (s_dst) + if(s_dst) *s_dst = *s_src; /* Task is sleeping, nothing to add */ - if (ppm_vtime_state(t) == VTIME_SLEEPING || - is_idle_task(t)) + if(ppm_vtime_state(t) == VTIME_SLEEPING || is_idle_task(t)) continue; delta = vtime_delta(t); @@ -103,92 +102,84 @@ fetch_task_cputime(struct task_struct *t, * Task runs either in user or kernel space, add pending nohz time to * the right place. */ - if (ppm_vtime_state(t) == VTIME_USER || t->flags & PF_VCPU) { + if(ppm_vtime_state(t) == VTIME_USER || t->flags & PF_VCPU) { *udelta = delta; } else { - if (ppm_vtime_state(t) == VTIME_SYS) + if(ppm_vtime_state(t) == VTIME_SYS) *sdelta = delta; } - } while (read_seqretry(ppm_vtime_seqlock(t), seq)); + } while(read_seqretry(ppm_vtime_seqlock(t), seq)); } -void task_cputime(struct task_struct *t, cputime_t *utime, cputime_t *stime) -{ +void task_cputime(struct task_struct *t, cputime_t *utime, cputime_t *stime) { cputime_t udelta, sdelta; - fetch_task_cputime(t, utime, stime, &t->utime, - &t->stime, &udelta, &sdelta); - if (utime) + fetch_task_cputime(t, utime, stime, &t->utime, &t->stime, &udelta, &sdelta); + if(utime) *utime += udelta; - if (stime) + if(stime) *stime += sdelta; } #elif LINUX_VERSION_CODE < KERNEL_VERSION(3, 9, 0) -static inline void task_cputime(struct task_struct *t, - cputime_t *utime, cputime_t *stime) -{ - if (utime) - *utime = t->utime; - if (stime) - *stime = t->stime; +static inline void task_cputime(struct task_struct *t, cputime_t *utime, cputime_t *stime) { + if(utime) + *utime = t->utime; + if(stime) + *stime = t->stime; } #endif /* CONFIG_VIRT_CPU_ACCOUNTING_GEN */ -uint64_t nsecs_to_jiffies64(uint64_t n) -{ -#if (NSEC_PER_SEC % HZ) == 0 - /* Common case, HZ = 100, 128, 200, 250, 256, 500, 512, 1000 etc. */ - return div_u64(n, NSEC_PER_SEC / HZ); -#elif (HZ % 512) == 0 - /* overflow after 292 years if HZ = 1024 */ - return div_u64(n * HZ / 512, NSEC_PER_SEC / 512); +uint64_t nsecs_to_jiffies64(uint64_t n) { +#if(NSEC_PER_SEC % HZ) == 0 + /* Common case, HZ = 100, 128, 200, 250, 256, 500, 512, 1000 etc. */ + return div_u64(n, NSEC_PER_SEC / HZ); +#elif(HZ % 512) == 0 + /* overflow after 292 years if HZ = 1024 */ + return div_u64(n * HZ / 512, NSEC_PER_SEC / 512); #else - /* - * Generic case - optimized for cases where HZ is a multiple of 3. - * overflow after 64.99 years, exact for HZ = 60, 72, 90, 120 etc. - */ - return div_u64(n * 9, (9ull * NSEC_PER_SEC + HZ / 2) / HZ); + /* + * Generic case - optimized for cases where HZ is a multiple of 3. + * overflow after 64.99 years, exact for HZ = 60, 72, 90, 120 etc. + */ + return div_u64(n * 9, (9ull * NSEC_PER_SEC + HZ / 2) / HZ); #endif } -unsigned long nsecs_to_jiffies(uint64_t n) -{ - return (unsigned long)nsecs_to_jiffies64(n); +unsigned long nsecs_to_jiffies(uint64_t n) { + return (unsigned long)nsecs_to_jiffies64(n); } #ifndef nsecs_to_cputime #ifdef msecs_to_cputime -#define nsecs_to_cputime(__nsecs) \ - msecs_to_cputime(div_u64((__nsecs), NSEC_PER_MSEC)) +#define nsecs_to_cputime(__nsecs) msecs_to_cputime(div_u64((__nsecs), NSEC_PER_MSEC)) #else -#define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs) +#define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs) #endif #endif -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 8, 0)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(3, 8, 0)) /* * Perform (stime * rtime) / total, but avoid multiplication overflow by * loosing precision when the numbers are big. */ -static cputime_t scale_stime(uint64_t stime, uint64_t rtime, uint64_t total) -{ +static cputime_t scale_stime(uint64_t stime, uint64_t rtime, uint64_t total) { uint64_t scaled; - for (;;) { + for(;;) { /* Make sure "rtime" is the bigger of stime/rtime */ - if (stime > rtime) + if(stime > rtime) swap(rtime, stime); /* Make sure 'total' fits in 32 bits */ - if (total >> 32) + if(total >> 32) goto drop_precision; /* Does rtime (and thus stime) fit in 32 bits? */ - if (!(rtime >> 32)) + if(!(rtime >> 32)) break; /* Can we just balance rtime/stime rather than dropping bits? */ - if (stime >> 31) + if(stime >> 31) goto drop_precision; /* We can grow stime and shrink rtime and try to make them both fit */ @@ -196,7 +187,7 @@ static cputime_t scale_stime(uint64_t stime, uint64_t rtime, uint64_t total) rtime >>= 1; continue; -drop_precision: + drop_precision: /* We drop from rtime, it has more bits than stime */ rtime >>= 1; total >>= 1; @@ -206,8 +197,8 @@ static cputime_t scale_stime(uint64_t stime, uint64_t rtime, uint64_t total) * Make sure gcc understands that this is a 32x32->64 multiply, * followed by a 64/32->64 divide. */ - scaled = div_u64((uint64_t) (uint32_t) stime * (uint64_t) (uint32_t) rtime, (uint32_t)total); - return (__force cputime_t) scaled; + scaled = div_u64((uint64_t)(uint32_t)stime * (uint64_t)(uint32_t)rtime, (uint32_t)total); + return (__force cputime_t)scaled; } /* @@ -219,11 +210,10 @@ static cputime_t scale_stime(uint64_t stime, uint64_t rtime, uint64_t total) * Normally a caller will only go through this loop once, or not * at all in case a previous caller updated counter the same jiffy. */ -static void cputime_advance(cputime_t *counter, cputime_t new) -{ +static void cputime_advance(cputime_t *counter, cputime_t new) { cputime_t old; - while (new > (old = ACCESS_ONCE(*counter))) + while(new > (old = ACCESS_ONCE(*counter))) cmpxchg_cputime(counter, old, new); } @@ -232,13 +222,13 @@ static void cputime_advance(cputime_t *counter, cputime_t new) * runtime accounting. */ static void cputime_adjust(struct task_cputime *curr, -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0)) - struct prev_cputime *prev, +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0)) + struct prev_cputime *prev, #else - struct cputime *prev, + struct cputime *prev, #endif - cputime_t *ut, cputime_t *st) -{ + cputime_t *ut, + cputime_t *st) { cputime_t rtime, stime, utime; /* @@ -258,21 +248,22 @@ static void cputime_adjust(struct task_cputime *curr, * time is bigger than already exported. Note that can happen, that we * provided bigger values due to scaling inaccuracy on big numbers. */ - if (prev->stime + prev->utime >= rtime) + if(prev->stime + prev->utime >= rtime) goto out; stime = curr->stime; utime = curr->utime; - if (utime == 0) { + if(utime == 0) { stime = rtime; - } else if (stime == 0) { + } else if(stime == 0) { utime = rtime; } else { cputime_t total = stime + utime; stime = scale_stime((__force uint64_t)stime, - (__force uint64_t)rtime, (__force uint64_t)total); + (__force uint64_t)rtime, + (__force uint64_t)total); utime = rtime - stime; } @@ -284,13 +275,12 @@ static void cputime_adjust(struct task_cputime *curr, *st = prev->stime; } -void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st) -{ +void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st) { struct task_cputime cputime = { #ifdef CONFIG_SCHED_BFS - .sum_exec_runtime = tsk_seruntime(p), + .sum_exec_runtime = tsk_seruntime(p), #else - .sum_exec_runtime = p->se.sum_exec_runtime, + .sum_exec_runtime = p->se.sum_exec_runtime, #endif }; @@ -300,23 +290,21 @@ void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t * #else /* LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0) */ -static cputime_t scale_utime(cputime_t utime, cputime_t rtime, cputime_t total) -{ - uint64_t temp = (__force uint64_t) rtime; +static cputime_t scale_utime(cputime_t utime, cputime_t rtime, cputime_t total) { + uint64_t temp = (__force uint64_t)rtime; - temp *= (__force uint64_t) utime; + temp *= (__force uint64_t)utime; - if (sizeof(cputime_t) == 4) - temp = div_u64(temp, (__force uint32_t) total); + if(sizeof(cputime_t) == 4) + temp = div_u64(temp, (__force uint32_t)total); else - temp = div64_u64(temp, (__force uint64_t) total); + temp = div64_u64(temp, (__force uint64_t)total); - return (__force cputime_t) temp; + return (__force cputime_t)temp; } // Taken from task_times(struct task_struct *p, cputime_t *ut, cputime_t *st) -void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st) -{ +void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st) { cputime_t rtime, utime = p->utime, total = utime + p->stime; /* @@ -324,7 +312,7 @@ void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t * */ rtime = nsecs_to_cputime(p->se.sum_exec_runtime); - if (total) + if(total) utime = scale_utime(utime, rtime, total); else utime = rtime; @@ -340,21 +328,21 @@ void ppm_task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t * } #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 8, 0)) */ -#endif /* (defined CONFIG_VIRT_CPU_ACCOUNTING_NATIVE) || (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 30)) */ +#endif /* (defined CONFIG_VIRT_CPU_ACCOUNTING_NATIVE) || (LINUX_VERSION_CODE < KERNEL_VERSION(2, \ + 6, 30)) */ #endif /* (LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) */ -#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 11, 0)) +#if(LINUX_VERSION_CODE >= KERNEL_VERSION(4, 11, 0)) #include #include /* * Implementation copied from kernel/time/time.c in 4.11.0 */ -uint64_t nsec_to_clock_t(uint64_t x) -{ -#if (NSEC_PER_SEC % USER_HZ) == 0 +uint64_t nsec_to_clock_t(uint64_t x) { +#if(NSEC_PER_SEC % USER_HZ) == 0 return div_u64(x, NSEC_PER_SEC / USER_HZ); -#elif (USER_HZ % 512) == 0 +#elif(USER_HZ % 512) == 0 return div_u64(x * USER_HZ / 512, NSEC_PER_SEC / 512); #else /* diff --git a/driver/ppm_events.c b/driver/ppm_events.c index 64e4f0d1c6..8d8bde5bdd 100644 --- a/driver/ppm_events.c +++ b/driver/ppm_events.c @@ -8,7 +8,7 @@ or GPL2.txt for full copies of the license. */ -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include #include @@ -45,22 +45,20 @@ or GPL2.txt for full copies of the license. #define ppm_access_ok access_ok_noprefault #else #ifdef HAS_ACCESS_OK_2 -#define ppm_access_ok(type, addr, size) access_ok(addr, size) +#define ppm_access_ok(type, addr, size) access_ok(addr, size) #else -#define ppm_access_ok(type, addr, size) access_ok(type, addr, size) +#define ppm_access_ok(type, addr, size) access_ok(type, addr, size) #endif #endif -static void memory_dump(char *p, size_t size) -{ +static void memory_dump(char *p, size_t size) { unsigned int j; - for (j = 0; j < size; j += 8) + for(j = 0; j < size; j += 8) pr_info("%*ph\n", 8, &p[j]); } -static inline bool in_port_range(uint16_t port, uint16_t min, uint16_t max) -{ +static inline bool in_port_range(uint16_t port, uint16_t min, uint16_t max) { return port >= min && port <= max; } @@ -85,13 +83,12 @@ uint32_t g_http_resp_intval; * The risk is that if the buffer is partially paged out, we get an error. * Returns the number of bytes NOT read. */ -unsigned long ppm_copy_from_user(void *to, const void __user *from, unsigned long n) -{ +unsigned long ppm_copy_from_user(void *to, const void __user *from, unsigned long n) { unsigned long res = n; pagefault_disable(); - if (likely(ppm_access_ok(VERIFY_READ, from, n))) + if(likely(ppm_access_ok(VERIFY_READ, from, n))) res = __copy_from_user_inatomic(to, from, n); pagefault_enable(); @@ -106,11 +103,12 @@ unsigned long ppm_copy_from_user(void *to, const void __user *from, unsigned lon * returns when: * 1. there's an error (returns `-1`). * 2. the terminator is found. (the `\0` is computed in the overall length) - * 3. we have read `n` bytes. (in this case, we don't have the `\0` but it's ok we will add it in the caller) + * 3. we have read `n` bytes. (in this case, we don't have the `\0` but it's ok we will add it in + * the caller) */ -/// TODO: we need to change the return value to `int` and the third param from `unsigned long n` to 'uint32_t n` -long ppm_strncpy_from_user(char *to, const char __user *from, unsigned long n) -{ +/// TODO: we need to change the return value to `int` and the third param from `unsigned long n` to +/// 'uint32_t n` +long ppm_strncpy_from_user(char *to, const char __user *from, unsigned long n) { long string_length = 0; long res = -1; unsigned long bytes_to_read = 4; @@ -118,20 +116,20 @@ long ppm_strncpy_from_user(char *to, const char __user *from, unsigned long n) pagefault_disable(); - while (n) { + while(n) { /* * Read bytes_to_read bytes at a time, and look for the terminator. Should be fast * since the copy_from_user is optimized for the processor */ - if (n < bytes_to_read) + if(n < bytes_to_read) bytes_to_read = n; - if (!ppm_access_ok(VERIFY_READ, from, bytes_to_read)) { + if(!ppm_access_ok(VERIFY_READ, from, bytes_to_read)) { res = -1; goto strncpy_end; } - if (__copy_from_user_inatomic(to, from, bytes_to_read)) { + if(__copy_from_user_inatomic(to, from, bytes_to_read)) { /* * Page fault */ @@ -142,11 +140,11 @@ long ppm_strncpy_from_user(char *to, const char __user *from, unsigned long n) n -= bytes_to_read; from += bytes_to_read; - for (j = 0; j < bytes_to_read; ++j) { + for(j = 0; j < bytes_to_read; ++j) { ++string_length; /* Check if `*to` is the `\0`. */ - if (!*to) { + if(!*to) { res = string_length; goto strncpy_end; } @@ -162,8 +160,7 @@ long ppm_strncpy_from_user(char *to, const char __user *from, unsigned long n) return res; } -int32_t dpi_lookahead_init(void) -{ +int32_t dpi_lookahead_init(void) { g_http_options_intval = (*(uint32_t *)HTTP_OPTIONS_STR); g_http_get_intval = (*(uint32_t *)HTTP_GET_STR); g_http_head_intval = (*(uint32_t *)HTTP_HEAD_STR); @@ -177,8 +174,7 @@ int32_t dpi_lookahead_init(void) return PPM_SUCCESS; } -inline int sock_getname(struct socket* sock, struct sockaddr* sock_address, int peer) -{ +inline int sock_getname(struct socket *sock, struct sockaddr *sock_address, int peer) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 8, 0) /* * Avoid calling sock->ops->getname(), because in certain kernel versions, @@ -197,18 +193,17 @@ inline int sock_getname(struct socket* sock, struct sockaddr* sock_address, int struct sock *sk = sock->sk; switch(sk->sk_family) { - case AF_INET: - { + case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *)sock_address; struct inet_sock *inet = (struct inet_sock *)sk; sin->sin_family = AF_INET; - if (peer) { + if(peer) { sin->sin_port = inet->inet_dport; sin->sin_addr.s_addr = inet->inet_daddr; } else { uint32_t addr = inet->inet_rcv_saddr; - if (!addr) { + if(!addr) { addr = inet->inet_saddr; } sin->sin_port = inet->inet_sport; @@ -216,19 +211,18 @@ inline int sock_getname(struct socket* sock, struct sockaddr* sock_address, int } break; } - case AF_INET6: - { + case AF_INET6: { struct sockaddr_in6 *sin = (struct sockaddr_in6 *)sock_address; struct inet_sock *inet = (struct inet_sock *)sk; struct ipv6_pinfo *np = (struct ipv6_pinfo *)inet->pinet6; sin->sin6_family = AF_INET6; - if (peer) { + if(peer) { sin->sin6_port = inet->inet_dport; sin->sin6_addr = sk->sk_v6_daddr; } else { sin->sin6_addr = sk->sk_v6_rcv_saddr; - if (ipv6_addr_any(&sin->sin6_addr)) { + if(ipv6_addr_any(&sin->sin6_addr)) { sin->sin6_addr = np->saddr; } sin->sin6_port = inet->inet_sport; @@ -236,27 +230,26 @@ inline int sock_getname(struct socket* sock, struct sockaddr* sock_address, int break; } - case AF_UNIX: - { + case AF_UNIX: { struct sockaddr_un *sunaddr = (struct sockaddr_un *)sock_address; struct unix_sock *u; struct unix_address *u_addr = NULL; - if (peer) { + if(peer) { sk = ((struct unix_sock *)sk)->peer; - if (!sk) { + if(!sk) { return -ENOTCONN; } } u = (struct unix_sock *)sk; u_addr = u->addr; - if (!u_addr) { + if(!u_addr) { sunaddr->sun_family = AF_UNIX; sunaddr->sun_path[0] = 0; } else { unsigned int len = u_addr->len; - if (unlikely(len > sizeof(struct sockaddr_storage))) { + if(unlikely(len > sizeof(struct sockaddr_storage))) { len = sizeof(struct sockaddr_storage); } memcpy(sunaddr, u_addr->name, len); @@ -271,7 +264,7 @@ inline int sock_getname(struct socket* sock, struct sockaddr* sock_address, int return 0; #elif LINUX_VERSION_CODE >= KERNEL_VERSION(4, 17, 0) int ret = sock->ops->getname(sock, sock_address, peer); - if (ret >= 0) + if(ret >= 0) ret = 0; return ret; #else @@ -302,8 +295,9 @@ inline int sock_getname(struct socket* sock, struct sockaddr* sock_address, int * HTTP, mongodb, and statsd. * 5. If none of the above apply, return args->consumer->snaplen. */ -inline uint32_t compute_snaplen(struct event_filler_arguments *args, char *buf, uint32_t lookahead_size) -{ +inline uint32_t compute_snaplen(struct event_filler_arguments *args, + char *buf, + uint32_t lookahead_size) { uint32_t res = args->consumer->snaplen; int err = 0; struct socket *sock = NULL; @@ -326,8 +320,7 @@ inline uint32_t compute_snaplen(struct event_filler_arguments *args, char *buf, goto done; socket_family = sk->sk_family; - if(socket_family == AF_INET || socket_family == AF_INET6) - { + if(socket_family == AF_INET || socket_family == AF_INET6) { struct inet_sock *inet = (struct inet_sock *)sk; struct sockaddr *sockaddr = NULL; struct sockaddr_in sockaddr_in = {}; @@ -344,8 +337,7 @@ inline uint32_t compute_snaplen(struct event_filler_arguments *args, char *buf, goto done; #endif - switch(args->event_type) - { + switch(args->event_type) { case PPME_SOCKET_SENDTO_X: case PPME_SOCKET_RECVFROM_X: // Reading directly from this could cause a page fault. @@ -354,8 +346,7 @@ inline uint32_t compute_snaplen(struct event_filler_arguments *args, char *buf, break; case PPME_SOCKET_RECVMSG_X: - case PPME_SOCKET_SENDMSG_X: - { + case PPME_SOCKET_SENDMSG_X: { #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 19, 0) struct user_msghdr mh = {}; #else @@ -363,42 +354,33 @@ inline uint32_t compute_snaplen(struct event_filler_arguments *args, char *buf, #endif #ifdef CONFIG_COMPAT - if(args->compat) - { + if(args->compat) { struct compat_msghdr compat_mh = {}; - if(likely(ppm_copy_from_user(&compat_mh, (const void *)compat_ptr(args->args[1]), - sizeof(compat_mh))==0)) - { + if(likely(ppm_copy_from_user(&compat_mh, + (const void *)compat_ptr(args->args[1]), + sizeof(compat_mh)) == 0)) { sockaddr = (struct sockaddr *)compat_ptr(compat_mh.msg_name); } // in any case we break the switch. break; } #endif - if(likely(ppm_copy_from_user(&mh, (const void *)args->args[1], sizeof(mh))==0)) - { - sockaddr = (struct sockaddr*)mh.msg_name; + if(likely(ppm_copy_from_user(&mh, (const void *)args->args[1], sizeof(mh)) == 0)) { + sockaddr = (struct sockaddr *)mh.msg_name; } - } - break; + } break; default: break; } - if(port_remote == 0 && sockaddr != NULL) - { - if(socket_family == AF_INET) - { - if(ppm_copy_from_user(&sockaddr_in, sockaddr, sizeof(struct sockaddr_in)) == 0) - { + if(port_remote == 0 && sockaddr != NULL) { + if(socket_family == AF_INET) { + if(ppm_copy_from_user(&sockaddr_in, sockaddr, sizeof(struct sockaddr_in)) == 0) { port_remote = ntohs(sockaddr_in.sin_port); } - } - else - { - if(ppm_copy_from_user(&sockaddr_in6, sockaddr, sizeof(struct sockaddr_in6)) == 0) - { + } else { + if(ppm_copy_from_user(&sockaddr_in6, sockaddr, sizeof(struct sockaddr_in6)) == 0) { port_remote = ntohs(sockaddr_in6.sin6_port); } } @@ -407,61 +389,48 @@ inline uint32_t compute_snaplen(struct event_filler_arguments *args, char *buf, min_port = args->consumer->fullcapture_port_range_start; max_port = args->consumer->fullcapture_port_range_end; - if(max_port > 0 && - (in_port_range(port_local, min_port, max_port) || in_port_range(port_remote, min_port, max_port))) - { + if(max_port > 0 && (in_port_range(port_local, min_port, max_port) || + in_port_range(port_remote, min_port, max_port))) { res = res > SNAPLEN_FULLCAPTURE_PORT ? res : SNAPLEN_FULLCAPTURE_PORT; goto done; - } - else if(port_remote == args->consumer->statsd_port) - { + } else if(port_remote == args->consumer->statsd_port) { res = res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; goto done; - } - else if(port_remote == PPM_PORT_DNS) - { + } else if(port_remote == PPM_PORT_DNS) { res = res > SNAPLEN_DNS_UDP ? res : SNAPLEN_DNS_UDP; goto done; - } - else if((port_local == PPM_PORT_MYSQL || port_remote == PPM_PORT_MYSQL) && lookahead_size >= 5) - { + } else if((port_local == PPM_PORT_MYSQL || port_remote == PPM_PORT_MYSQL) && + lookahead_size >= 5) { if((buf[0] == 3 || buf[1] == 3 || buf[2] == 3 || buf[3] == 3 || buf[4] == 3) || - (buf[2] == 0 && buf[3] == 0)) - { + (buf[2] == 0 && buf[3] == 0)) { res = res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; goto done; } - } - else if((port_local == PPM_PORT_POSTGRES || port_remote == PPM_PORT_POSTGRES) && lookahead_size >= 7) - { - if((buf[0] == 'Q' && buf[1] == 0) || /* SimpleQuery command */ - (buf[0] == 'P' && buf[1] == 0) || /* Prepare statement command */ + } else if((port_local == PPM_PORT_POSTGRES || port_remote == PPM_PORT_POSTGRES) && + lookahead_size >= 7) { + if((buf[0] == 'Q' && buf[1] == 0) || /* SimpleQuery command */ + (buf[0] == 'P' && buf[1] == 0) || /* Prepare statement command */ (buf[4] == 0 && buf[5] == 3 && buf[6] == 0) || /* startup command */ - (buf[0] == 'E' && buf[1] == 0) /* error or execute command */ - ) - { + (buf[0] == 'E' && buf[1] == 0) /* error or execute command */ + ) { res = res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; goto done; } - } - else if((port_local == PPM_PORT_MONGODB || port_remote == PPM_PORT_MONGODB) || - (lookahead_size >= 16 && - (*(int32_t *)(buf + 12) == 1 || /* matches header */ - *(int32_t *)(buf + 12) == 2001 || *(int32_t *)(buf + 12) == 2002 || *(int32_t *)(buf + 12) == 2003 || - *(int32_t *)(buf + 12) == 2004 || *(int32_t *)(buf + 12) == 2005 || *(int32_t *)(buf + 12) == 2006 || - *(int32_t *)(buf + 12) == 2007))) - { + } else if((port_local == PPM_PORT_MONGODB || port_remote == PPM_PORT_MONGODB) || + (lookahead_size >= 16 && + (*(int32_t *)(buf + 12) == 1 || /* matches header */ + *(int32_t *)(buf + 12) == 2001 || *(int32_t *)(buf + 12) == 2002 || + *(int32_t *)(buf + 12) == 2003 || *(int32_t *)(buf + 12) == 2004 || + *(int32_t *)(buf + 12) == 2005 || *(int32_t *)(buf + 12) == 2006 || + *(int32_t *)(buf + 12) == 2007))) { res = res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; goto done; - } - else if(lookahead_size >= 5) - { + } else if(lookahead_size >= 5) { if(*(uint32_t *)buf == g_http_get_intval || *(uint32_t *)buf == g_http_post_intval || *(uint32_t *)buf == g_http_put_intval || *(uint32_t *)buf == g_http_delete_intval || *(uint32_t *)buf == g_http_trace_intval || *(uint32_t *)buf == g_http_connect_intval || *(uint32_t *)buf == g_http_options_intval || - ((*(uint32_t *)buf == g_http_resp_intval) && (buf[4] == '/'))) - { + ((*(uint32_t *)buf == g_http_resp_intval) && (buf[4] == '/'))) { res = res > SNAPLEN_EXTENDED ? res : SNAPLEN_EXTENDED; goto done; } @@ -471,19 +440,18 @@ inline uint32_t compute_snaplen(struct event_filler_arguments *args, char *buf, return res; } -int push_empty_param(struct event_filler_arguments *args) -{ +int push_empty_param(struct event_filler_arguments *args) { uint16_t *psize = (uint16_t *)(args->buffer + args->curarg * sizeof(uint16_t)); - if (unlikely(args->curarg >= args->nargs)) - { - pr_err("(%u)val_to_ring: too many arguments for event #%u, type=%u, curarg=%u, nargs=%u tid:%u\n", - smp_processor_id(), - args->nevents, - (uint32_t)args->event_type, - args->curarg, - args->nargs, - current->pid); + if(unlikely(args->curarg >= args->nargs)) { + pr_err("(%u)val_to_ring: too many arguments for event #%u, type=%u, curarg=%u, nargs=%u " + "tid:%u\n", + smp_processor_id(), + args->nevents, + (uint32_t)args->event_type, + args->curarg, + args->nargs, + current->pid); memory_dump(args->buffer - sizeof(struct ppm_evt_hdr), 32); ASSERT(0); return PPM_FAILURE_BUG; @@ -503,37 +471,41 @@ int push_empty_param(struct event_filler_arguments *args) * - fromuser is ignored for numeric types * - dyn_idx is ignored for everything other than PT_DYN */ -int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_len, bool fromuser, uint8_t dyn_idx) -{ +int val_to_ring(struct event_filler_arguments *args, + uint64_t val, + uint32_t val_len, + bool fromuser, + uint8_t dyn_idx) { const struct ppm_param_info *param_info; int len = -1; uint16_t *psize = (uint16_t *)(args->buffer + args->curarg * sizeof(uint16_t)); uint32_t max_arg_size = args->arg_data_size; - if (unlikely(args->curarg >= args->nargs)) { - pr_err("(%u)val_to_ring: too many arguments for event #%u, type=%u, curarg=%u, nargs=%u tid:%u\n", - smp_processor_id(), - args->nevents, - (uint32_t)args->event_type, - args->curarg, - args->nargs, - current->pid); + if(unlikely(args->curarg >= args->nargs)) { + pr_err("(%u)val_to_ring: too many arguments for event #%u, type=%u, curarg=%u, nargs=%u " + "tid:%u\n", + smp_processor_id(), + args->nevents, + (uint32_t)args->event_type, + args->curarg, + args->nargs, + current->pid); memory_dump(args->buffer - sizeof(struct ppm_evt_hdr), 32); ASSERT(0); return PPM_FAILURE_BUG; } - if (unlikely(args->arg_data_size == 0)) + if(unlikely(args->arg_data_size == 0)) return PPM_FAILURE_BUFFER_FULL; - if (max_arg_size > PPM_MAX_ARG_SIZE) + if(max_arg_size > PPM_MAX_ARG_SIZE) max_arg_size = PPM_MAX_ARG_SIZE; param_info = &(g_event_info[args->event_type].params[args->curarg]); - if (param_info->type == PT_DYN && param_info->info != NULL) { + if(param_info->type == PT_DYN && param_info->info != NULL) { const struct ppm_param_info *dyn_params; - if (unlikely(dyn_idx >= param_info->ninfo)) { + if(unlikely(dyn_idx >= param_info->ninfo)) { ASSERT(0); return PPM_FAILURE_BUG; } @@ -541,7 +513,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ dyn_params = (const struct ppm_param_info *)param_info->info; param_info = &dyn_params[dyn_idx]; - if (likely(max_arg_size >= sizeof(uint8_t))) { + if(likely(max_arg_size >= sizeof(uint8_t))) { *(uint8_t *)(args->buffer + args->arg_data_offset) = dyn_idx; len = sizeof(uint8_t); } else { @@ -555,46 +527,43 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ *psize = 0; } - switch (param_info->type) { + switch(param_info->type) { case PT_CHARBUF: case PT_FSPATH: case PT_FSRELPATH: - if(unlikely(val == 0)) - { + if(unlikely(val == 0)) { /* Send an empty param when we have a null pointer `val==0` */ len = 0; break; } - - if(fromuser) - { + if(fromuser) { len = ppm_strncpy_from_user(args->buffer + args->arg_data_offset, - (const char __user *)(unsigned long)val, max_arg_size); + (const char __user *)(unsigned long)val, + max_arg_size); - if(unlikely(len < 0)) - { + if(unlikely(len < 0)) { len = 0; break; } /* Two possible cases here: * - * 1. `len < max_arg_size`, the terminator is always there, and `len` takes it into account, - * so we need to do nothing. We just push a `\0` to an empty byte to avoid an if - * case. + * 1. `len < max_arg_size`, the terminator is always there, and `len` takes it into + * account, so we need to do nothing. We just push a `\0` to an empty byte to avoid an + * if case. * - * 2. `len == max_arg_size`, the terminator is not there but we cannot push an additional - * char for this reason we overwrite the last char and we don't increment `len`. + * 2. `len == max_arg_size`, the terminator is not there but we cannot push an + * additional char for this reason we overwrite the last char and we don't increment + * `len`. */ *(char *)(args->buffer + args->arg_data_offset + max_arg_size - 1) = '\0'; - } - else - { + } else { #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) - // strscpy is available since kernel 4.3.0: https://github.com/torvalds/linux/commit/30035e45753b708e7d47a98398500ca005e02b86 + // strscpy is available since kernel 4.3.0: + // https://github.com/torvalds/linux/commit/30035e45753b708e7d47a98398500ca005e02b86 len = (int)strscpy(args->buffer + args->arg_data_offset, - (const char *)(unsigned long)val, - max_arg_size); + (const char *)(unsigned long)val, + max_arg_size); /* WARNING: `strscpy` returns the length of the string it creates or -E2BIG in case * the resulting string would not fit inside the destination string. * (see https://elixir.bootlin.com/linux/latest/source/lib/string.c#L122 and @@ -605,25 +574,23 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ * * Two possible cases here: * - * 1. `len < max_arg_size`, the terminator is always there, but `len` doesn't take it into account, - * so we need to increment the `len`. + * 1. `len < max_arg_size`, the terminator is always there, but `len` doesn't take it + * into account, so we need to increment the `len`. * * 2. `len == -E2BIG`, the source string is >= than `max_arg_size`. `strscpy` copied - * `max_arg_size - 1` and added the `\0` at the end, so our final copied `len` is `max_arg_size`. + * `max_arg_size - 1` and added the `\0` at the end, so our final copied `len` is + * `max_arg_size`. */ - if (len == -E2BIG) - { + if(len == -E2BIG) { len = max_arg_size; - } - else - { + } else { len++; } #else // Use old `strlcpy`. len = (int)strlcpy(args->buffer + args->arg_data_offset, - (const char *)(unsigned long)val, - max_arg_size); + (const char *)(unsigned long)val, + max_arg_size); /* WARNING: `strlcpy` returns the length of the string it tries to create * so `len` could also be greater than `max_arg_size`, but please note that the copied * charbuf is at max `max_arg_size` (where the last byte is used for the `\0`). @@ -632,16 +599,16 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ * * Two possible cases here: * - * 1. `len < max_arg_size`, the terminator is always there, but `len` doesn't take it into account, - * so we need to increment the `len`. Note that if the source string has exactly `max_arg_size` - * characters the returned `len` is `max_arg_size-1` so we need to do `len++` to obtain the copied size. + * 1. `len < max_arg_size`, the terminator is always there, but `len` doesn't take it + * into account, so we need to increment the `len`. Note that if the source string has + * exactly `max_arg_size` characters the returned `len` is `max_arg_size-1` so we need + * to do `len++` to obtain the copied size. * - * 2. `len >= max_arg_size`, the source string is greater than `max_arg_size`. `strlcpy` copied - * `max_arg_size - 1` and added the `\0` at the end, so our final copied `len` is `max_arg_size` we have just - * to resize it and we have done. + * 2. `len >= max_arg_size`, the source string is greater than `max_arg_size`. `strlcpy` + * copied `max_arg_size - 1` and added the `\0` at the end, so our final copied `len` is + * `max_arg_size` we have just to resize it and we have done. */ - if(++len >= max_arg_size) - { + if(++len >= max_arg_size) { len = max_arg_size; } #endif @@ -649,76 +616,73 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ break; case PT_BYTEBUF: - if (likely(val != 0 && val_len)) { - if (fromuser) - { + if(likely(val != 0 && val_len)) { + if(fromuser) { /* * Copy the lookahead portion of the buffer that we will use DPI-based * snaplen calculation */ uint32_t dpi_lookahead_size = DPI_LOOKAHEAD_SIZE; - if (dpi_lookahead_size > val_len) + if(dpi_lookahead_size > val_len) dpi_lookahead_size = val_len; - if (unlikely(dpi_lookahead_size >= max_arg_size)) + if(unlikely(dpi_lookahead_size >= max_arg_size)) return PPM_FAILURE_BUFFER_FULL; /* Returns the number of bytes NOT read. */ len = (int)ppm_copy_from_user(args->buffer + args->arg_data_offset, - (const void __user *)(unsigned long)val, - dpi_lookahead_size); + (const void __user *)(unsigned long)val, + dpi_lookahead_size); - if(unlikely(len != 0)) - { + if(unlikely(len != 0)) { goto send_empty_bytebuf_param; } /* * Check if there's more to copy */ - if (likely((dpi_lookahead_size != val_len))) { + if(likely((dpi_lookahead_size != val_len))) { /* * Calculate the snaplen */ - if (likely(args->enforce_snaplen)) { + if(likely(args->enforce_snaplen)) { uint32_t sl = args->consumer->snaplen; - sl = compute_snaplen(args, args->buffer + args->arg_data_offset, dpi_lookahead_size); - if (val_len > sl) + sl = compute_snaplen(args, + args->buffer + args->arg_data_offset, + dpi_lookahead_size); + if(val_len > sl) val_len = sl; } - if (unlikely((val_len) >= max_arg_size)) + if(unlikely((val_len) >= max_arg_size)) val_len = max_arg_size; - if (val_len > dpi_lookahead_size) { - len = (int)ppm_copy_from_user(args->buffer + args->arg_data_offset + dpi_lookahead_size, - (const uint8_t __user *)(unsigned long)val + dpi_lookahead_size, - val_len - dpi_lookahead_size); + if(val_len > dpi_lookahead_size) { + len = (int)ppm_copy_from_user( + args->buffer + args->arg_data_offset + dpi_lookahead_size, + (const uint8_t __user *)(unsigned long)val + dpi_lookahead_size, + val_len - dpi_lookahead_size); - if (unlikely(len != 0)) - { + if(unlikely(len != 0)) { goto send_empty_bytebuf_param; } } } len = val_len; - } - else - { - if (likely(args->enforce_snaplen)) { + } else { + if(likely(args->enforce_snaplen)) { uint32_t sl = compute_snaplen(args, (char *)(unsigned long)val, val_len); - if (val_len > sl) + if(val_len > sl) val_len = sl; } - if (unlikely(val_len >= max_arg_size)) + if(unlikely(val_len >= max_arg_size)) return PPM_FAILURE_BUFFER_FULL; - memcpy(args->buffer + args->arg_data_offset, - (void *)(unsigned long)val, val_len); + memcpy(args->buffer + args->arg_data_offset, (void *)(unsigned long)val, val_len); len = val_len; } @@ -730,35 +694,29 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ * - we have read `0` bytes. * - we faced an error while reading. */ -send_empty_bytebuf_param: + send_empty_bytebuf_param: len = 0; break; case PT_SOCKADDR: case PT_SOCKTUPLE: case PT_FDLIST: - if(likely(val != 0)) - { - if (unlikely(val_len >= max_arg_size)) + if(likely(val != 0)) { + if(unlikely(val_len >= max_arg_size)) return PPM_FAILURE_BUFFER_FULL; - if(fromuser) - { + if(fromuser) { len = (int)ppm_copy_from_user(args->buffer + args->arg_data_offset, - (const void __user *)(unsigned long)val, - val_len); + (const void __user *)(unsigned long)val, + val_len); - if(unlikely(len != 0)) - { + if(unlikely(len != 0)) { goto send_empty_sock_param; } len = val_len; - } - else - { - memcpy(args->buffer + args->arg_data_offset, - (void *)(unsigned long)val, val_len); + } else { + memcpy(args->buffer + args->arg_data_offset, (void *)(unsigned long)val, val_len); len = val_len; } @@ -766,7 +724,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ break; } -send_empty_sock_param: + send_empty_sock_param: len = 0; break; @@ -774,7 +732,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ case PT_ENUMFLAGS8: case PT_UINT8: case PT_SIGTYPE: - if (likely(max_arg_size >= sizeof(uint8_t))) { + if(likely(max_arg_size >= sizeof(uint8_t))) { *(uint8_t *)(args->buffer + args->arg_data_offset) = (uint8_t)val; len = sizeof(uint8_t); } else { @@ -786,7 +744,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ case PT_ENUMFLAGS16: case PT_UINT16: case PT_SYSCALLID: - if (likely(max_arg_size >= sizeof(uint16_t))) { + if(likely(max_arg_size >= sizeof(uint16_t))) { *(uint16_t *)(args->buffer + args->arg_data_offset) = (uint16_t)val; len = sizeof(uint16_t); } else { @@ -801,7 +759,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ case PT_GID: case PT_SIGSET: case PT_ENUMFLAGS32: - if (likely(max_arg_size >= sizeof(uint32_t))) { + if(likely(max_arg_size >= sizeof(uint32_t))) { *(uint32_t *)(args->buffer + args->arg_data_offset) = (uint32_t)val; len = sizeof(uint32_t); } else { @@ -812,7 +770,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ case PT_RELTIME: case PT_ABSTIME: case PT_UINT64: - if (likely(max_arg_size >= sizeof(uint64_t))) { + if(likely(max_arg_size >= sizeof(uint64_t))) { *(uint64_t *)(args->buffer + args->arg_data_offset) = (uint64_t)val; len = sizeof(uint64_t); } else { @@ -821,7 +779,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ break; case PT_INT8: - if (likely(max_arg_size >= sizeof(int8_t))) { + if(likely(max_arg_size >= sizeof(int8_t))) { *(int8_t *)(args->buffer + args->arg_data_offset) = (int8_t)(long)val; len = sizeof(int8_t); } else { @@ -830,7 +788,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ break; case PT_INT16: - if (likely(max_arg_size >= sizeof(int16_t))) { + if(likely(max_arg_size >= sizeof(int16_t))) { *(int16_t *)(args->buffer + args->arg_data_offset) = (int16_t)(long)val; len = sizeof(int16_t); } else { @@ -839,7 +797,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ break; case PT_INT32: - if (likely(max_arg_size >= sizeof(int32_t))) { + if(likely(max_arg_size >= sizeof(int32_t))) { *(int32_t *)(args->buffer + args->arg_data_offset) = (int32_t)(long)val; len = sizeof(int32_t); } else { @@ -851,7 +809,7 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ case PT_ERRNO: case PT_FD: case PT_PID: - if (likely(max_arg_size >= sizeof(int64_t))) { + if(likely(max_arg_size >= sizeof(int64_t))) { *(int64_t *)(args->buffer + args->arg_data_offset) = (int64_t)(long)val; len = sizeof(int64_t); } else { @@ -861,10 +819,11 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ break; default: ASSERT(0); - pr_err("val_to_ring: invalid argument type %d. Event %u (%s) might have less parameters than what has been declared in nparams\n", - (int)g_event_info[args->event_type].params[args->curarg].type, - (uint32_t)args->event_type, - g_event_info[args->event_type].name); + pr_err("val_to_ring: invalid argument type %d. Event %u (%s) might have less parameters " + "than what has been declared in nparams\n", + (int)g_event_info[args->event_type].params[args->curarg].type, + (uint32_t)args->event_type, + g_event_info[args->event_type].name); return PPM_FAILURE_BUG; } @@ -882,24 +841,23 @@ int val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_ /* static struct socket *ppm_sockfd_lookup_light(int fd, int *err, int *fput_needed) { - struct file *file; - struct socket *sock; - - *err = -EBADF; - file = fget_light(fd, fput_needed); - if (file) { - sock = sock_from_file(file, err); - if (sock) - return sock; - fput_light(file, *fput_needed); - } - return NULL; + struct file *file; + struct socket *sock; + + *err = -EBADF; + file = fget_light(fd, fput_needed); + if (file) { + sock = sock_from_file(file, err); + if (sock) + return sock; + fput_light(file, *fput_needed); + } + return NULL; } */ -static void unix_socket_path(char *dest, const char *path, size_t size) -{ - if (path[0] == '\0') { +static void unix_socket_path(char *dest, const char *path, size_t size) { + if(path[0] == '\0') { /* * Extract from: https://man7.org/linux/man-pages/man7/unix.7.html * an abstract socket address is distinguished (from a @@ -908,15 +866,12 @@ static void unix_socket_path(char *dest, const char *path, size_t size) * the additional bytes in sun_path that are covered by the * specified length of the address structure. */ - snprintf(dest, - size, - "@%s", - path + 1); + snprintf(dest, size, "@%s", path + 1); } else { snprintf(dest, - size, - "%s", - path); /* we assume this will be smaller than (targetbufsize - (1 + 8 + 8)) */ + size, + "%s", + path); /* we assume this will be smaller than (targetbufsize - (1 + 8 + 8)) */ } } @@ -925,10 +880,9 @@ static void unix_socket_path(char *dest, const char *path, size_t size) * targetbuf */ uint16_t pack_addr(struct sockaddr *usrsockaddr, - int ulen, - char *targetbuf, - uint16_t targetbufsize) -{ + int ulen, + char *targetbuf, + uint16_t targetbufsize) { uint32_t ip; uint16_t port; sa_family_t family = usrsockaddr->sa_family; @@ -938,7 +892,7 @@ uint16_t pack_addr(struct sockaddr *usrsockaddr, uint16_t size; char *dest; - switch (family) { + switch(family) { case AF_INET: /* * Map the user-provided address to a sockaddr_in @@ -978,9 +932,7 @@ uint16_t pack_addr(struct sockaddr *usrsockaddr, size = 1 + 16 + 2; /* family + ip + port */ *targetbuf = socket_family_to_scap((uint8_t)family); - memcpy(targetbuf + 1, - usrsockaddr_in6->sin6_addr.s6_addr, - 16); + memcpy(targetbuf + 1, usrsockaddr_in6->sin6_addr.s6_addr, 16); *(uint16_t *)(targetbuf + 17) = port; break; @@ -994,7 +946,7 @@ uint16_t pack_addr(struct sockaddr *usrsockaddr, * Put a 0 at the end of struct sockaddr_un because * the user might not have considered it in the length */ - if (ulen == sizeof(struct sockaddr_storage)) + if(ulen == sizeof(struct sockaddr_storage)) *(((char *)usrsockaddr_un) + ulen - 1) = 0; else *(((char *)usrsockaddr_un) + ulen) = 0; @@ -1025,13 +977,12 @@ uint16_t pack_addr(struct sockaddr *usrsockaddr, * targetbuf */ uint16_t fd_to_socktuple(int fd, - struct sockaddr *usrsockaddr, - int ulen, - bool use_userdata, - bool is_inbound, - char *targetbuf, - uint16_t targetbufsize) -{ + struct sockaddr *usrsockaddr, + int ulen, + bool use_userdata, + bool is_inbound, + char *targetbuf, + uint16_t targetbufsize) { int err = 0; sa_family_t family; uint32_t sip; @@ -1058,12 +1009,12 @@ uint16_t fd_to_socktuple(int fd, */ sock = sockfd_lookup(fd, &err); - if (unlikely(!sock || !(sock->sk))) { + if(unlikely(!sock || !(sock->sk))) { /* * This usually happens if the call failed without being able to establish a connection, * i.e. if it didn't return something like SE_EINPROGRESS. */ - if (sock) + if(sock) sockfd_put(sock); return 0; } @@ -1075,21 +1026,21 @@ uint16_t fd_to_socktuple(int fd, /* * Extract and pack the info, based on the family */ - switch (family) { + switch(family) { case AF_INET: - if (!use_userdata) { + if(!use_userdata) { err = sock_getname(sock, (struct sockaddr *)&peer_address, 1); - if (err == 0) { - if (is_inbound) { - sip = ((struct sockaddr_in *) &peer_address)->sin_addr.s_addr; - sport = ntohs(((struct sockaddr_in *) &peer_address)->sin_port); - dip = ((struct sockaddr_in *) &sock_address)->sin_addr.s_addr; - dport = ntohs(((struct sockaddr_in *) &sock_address)->sin_port); + if(err == 0) { + if(is_inbound) { + sip = ((struct sockaddr_in *)&peer_address)->sin_addr.s_addr; + sport = ntohs(((struct sockaddr_in *)&peer_address)->sin_port); + dip = ((struct sockaddr_in *)&sock_address)->sin_addr.s_addr; + dport = ntohs(((struct sockaddr_in *)&sock_address)->sin_port); } else { - sip = ((struct sockaddr_in *) &sock_address)->sin_addr.s_addr; - sport = ntohs(((struct sockaddr_in *) &sock_address)->sin_port); - dip = ((struct sockaddr_in *) &peer_address)->sin_addr.s_addr; - dport = ntohs(((struct sockaddr_in *) &peer_address)->sin_port); + sip = ((struct sockaddr_in *)&sock_address)->sin_addr.s_addr; + sport = ntohs(((struct sockaddr_in *)&sock_address)->sin_port); + dip = ((struct sockaddr_in *)&peer_address)->sin_addr.s_addr; + dport = ntohs(((struct sockaddr_in *)&peer_address)->sin_port); } } else { sip = 0; @@ -1103,8 +1054,7 @@ uint16_t fd_to_socktuple(int fd, */ usrsockaddr_in = (struct sockaddr_in *)usrsockaddr; - if (is_inbound) - { + if(is_inbound) { /* To take peer address info we try to use the kernel where possible. * TCP allows us to obtain the right information, while the kernel doesn't fill * `sk->__sk_common.skc_daddr` for UDP connection. @@ -1114,22 +1064,20 @@ uint16_t fd_to_socktuple(int fd, */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 13, 0) sport = ntohs(sock->sk->__sk_common.skc_dport); - if(sport != 0) - { + if(sport != 0) { /* We can read from the kernel */ sip = sock->sk->__sk_common.skc_daddr; - } - else + } else #endif { sip = usrsockaddr_in->sin_addr.s_addr; sport = ntohs(usrsockaddr_in->sin_port); } - dip = ((struct sockaddr_in *) &sock_address)->sin_addr.s_addr; - dport = ntohs(((struct sockaddr_in *) &sock_address)->sin_port); + dip = ((struct sockaddr_in *)&sock_address)->sin_addr.s_addr; + dport = ntohs(((struct sockaddr_in *)&sock_address)->sin_port); } else { - sip = ((struct sockaddr_in *) &sock_address)->sin_addr.s_addr; - sport = ntohs(((struct sockaddr_in *) &sock_address)->sin_port); + sip = ((struct sockaddr_in *)&sock_address)->sin_addr.s_addr; + sport = ntohs(((struct sockaddr_in *)&sock_address)->sin_port); dip = usrsockaddr_in->sin_addr.s_addr; dport = ntohs(usrsockaddr_in->sin_port); } @@ -1148,20 +1096,20 @@ uint16_t fd_to_socktuple(int fd, break; case AF_INET6: - if (!use_userdata) { + if(!use_userdata) { err = sock_getname(sock, (struct sockaddr *)&peer_address, 1); ASSERT(err == 0); - if (is_inbound) { - sip6 = ((struct sockaddr_in6 *) &peer_address)->sin6_addr.s6_addr; - sport = ntohs(((struct sockaddr_in6 *) &peer_address)->sin6_port); - dip6 = ((struct sockaddr_in6 *) &sock_address)->sin6_addr.s6_addr; - dport = ntohs(((struct sockaddr_in6 *) &sock_address)->sin6_port); + if(is_inbound) { + sip6 = ((struct sockaddr_in6 *)&peer_address)->sin6_addr.s6_addr; + sport = ntohs(((struct sockaddr_in6 *)&peer_address)->sin6_port); + dip6 = ((struct sockaddr_in6 *)&sock_address)->sin6_addr.s6_addr; + dport = ntohs(((struct sockaddr_in6 *)&sock_address)->sin6_port); } else { - sip6 = ((struct sockaddr_in6 *) &sock_address)->sin6_addr.s6_addr; - sport = ntohs(((struct sockaddr_in6 *) &sock_address)->sin6_port); - dip6 = ((struct sockaddr_in6 *) &peer_address)->sin6_addr.s6_addr; - dport = ntohs(((struct sockaddr_in6 *) &peer_address)->sin6_port); + sip6 = ((struct sockaddr_in6 *)&sock_address)->sin6_addr.s6_addr; + sport = ntohs(((struct sockaddr_in6 *)&sock_address)->sin6_port); + dip6 = ((struct sockaddr_in6 *)&peer_address)->sin6_addr.s6_addr; + dport = ntohs(((struct sockaddr_in6 *)&peer_address)->sin6_port); } } else { /* @@ -1169,27 +1117,24 @@ uint16_t fd_to_socktuple(int fd, */ usrsockaddr_in6 = (struct sockaddr_in6 *)usrsockaddr; - if (is_inbound) - { + if(is_inbound) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 13, 0) sport = ntohs(sock->sk->__sk_common.skc_dport); - if(sport != 0) - { + if(sport != 0) { /* We can read from the kernel */ sip6 = sock->sk->__sk_common.skc_v6_daddr.in6_u.u6_addr8; - } - else + } else #endif { /* Fallback to userspace struct */ sip6 = usrsockaddr_in6->sin6_addr.s6_addr; sport = ntohs(usrsockaddr_in6->sin6_port); } - dip6 = ((struct sockaddr_in6 *) &sock_address)->sin6_addr.s6_addr; - dport = ntohs(((struct sockaddr_in6 *) &sock_address)->sin6_port); + dip6 = ((struct sockaddr_in6 *)&sock_address)->sin6_addr.s6_addr; + dport = ntohs(((struct sockaddr_in6 *)&sock_address)->sin6_port); } else { - sip6 = ((struct sockaddr_in6 *) &sock_address)->sin6_addr.s6_addr; - sport = ntohs(((struct sockaddr_in6 *) &sock_address)->sin6_port); + sip6 = ((struct sockaddr_in6 *)&sock_address)->sin6_addr.s6_addr; + sport = ntohs(((struct sockaddr_in6 *)&sock_address)->sin6_port); dip6 = usrsockaddr_in6->sin6_addr.s6_addr; dport = ntohs(usrsockaddr_in6->sin6_port); } @@ -1201,13 +1146,9 @@ uint16_t fd_to_socktuple(int fd, size = 1 + 16 + 16 + 2 + 2; /* family + sip + dip + sport + dport */ *targetbuf = socket_family_to_scap((uint8_t)family); - memcpy(targetbuf + 1, - sip6, - 16); + memcpy(targetbuf + 1, sip6, 16); *(uint16_t *)(targetbuf + 17) = sport; - memcpy(targetbuf + 19, - dip6, - 16); + memcpy(targetbuf + 19, dip6, 16); *(uint16_t *)(targetbuf + 35) = dport; break; @@ -1220,7 +1161,7 @@ uint16_t fd_to_socktuple(int fd, *targetbuf = socket_family_to_scap(family); - if (is_inbound) { + if(is_inbound) { *(uint64_t *)(targetbuf + 1) = (uint64_t)(unsigned long)us; *(uint64_t *)(targetbuf + 1 + 8) = (uint64_t)(unsigned long)speer; } else { @@ -1233,14 +1174,14 @@ uint16_t fd_to_socktuple(int fd, */ size = 1 + 8 + 8; - if (!use_userdata) { - if (is_inbound) { - us_name = ((struct sockaddr_un *) &sock_address)->sun_path; + if(!use_userdata) { + if(is_inbound) { + us_name = ((struct sockaddr_un *)&sock_address)->sun_path; } else { err = sock_getname(sock, (struct sockaddr *)&peer_address, 1); ASSERT(err == 0); - us_name = ((struct sockaddr_un *) &peer_address)->sun_path; + us_name = ((struct sockaddr_un *)&peer_address)->sun_path; } } else { /* @@ -1252,13 +1193,13 @@ uint16_t fd_to_socktuple(int fd, * Put a 0 at the end of struct sockaddr_un because * the user might not have considered it in the length */ - if (ulen == sizeof(struct sockaddr_storage)) + if(ulen == sizeof(struct sockaddr_storage)) *(((char *)usrsockaddr_un) + ulen - 1) = 0; else *(((char *)usrsockaddr_un) + ulen) = 0; - if (is_inbound) - us_name = ((struct sockaddr_un *) &sock_address)->sun_path; + if(is_inbound) + us_name = ((struct sockaddr_un *)&sock_address)->sun_path; else us_name = usrsockaddr_un->sun_path; } @@ -1283,15 +1224,14 @@ uint16_t fd_to_socktuple(int fd, return size; } -int addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr *kaddr) -{ - if (unlikely(ulen < 0 || ulen > sizeof(struct sockaddr_storage))) +int addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr *kaddr) { + if(unlikely(ulen < 0 || ulen > sizeof(struct sockaddr_storage))) return -EINVAL; - if (unlikely(ulen == 0)) + if(unlikely(ulen == 0)) return 0; - if (unlikely(ppm_copy_from_user(kaddr, uaddr, ulen))) + if(unlikely(ppm_copy_from_user(kaddr, uaddr, ulen))) return -EFAULT; return 0; @@ -1301,8 +1241,11 @@ int addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr *kaddr) * Parses the list of buffers of a xreadv or xwritev call, and pushes the size * (and optionally the data) to the ring. */ -int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struct iovec __user *iovsrc, unsigned long iovcnt, int64_t retval, int flags) -{ +int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, + const struct iovec __user *iovsrc, + unsigned long iovcnt, + int64_t retval, + int flags) { int32_t res; const struct iovec *iov; uint64_t copylen; @@ -1317,13 +1260,13 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc copylen = iovcnt * sizeof(struct iovec); - if (unlikely(iovcnt >= 0xffffffff)) + if(unlikely(iovcnt >= 0xffffffff)) return PPM_FAILURE_BUFFER_FULL; - if (unlikely(copylen >= STR_STORAGE_SIZE)) + if(unlikely(copylen >= STR_STORAGE_SIZE)) return PPM_FAILURE_BUFFER_FULL; - if (unlikely(ppm_copy_from_user(args->str_storage, iovsrc, copylen))) + if(unlikely(ppm_copy_from_user(args->str_storage, iovsrc, copylen))) return PPM_FAILURE_INVALID_USER_MEMORY; iov = (const struct iovec *)(args->str_storage); @@ -1334,16 +1277,16 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc /* * Size */ - if (flags & PRB_FLAG_PUSH_SIZE) { - for (j = 0; j < iovcnt; j++) + if(flags & PRB_FLAG_PUSH_SIZE) { + for(j = 0; j < iovcnt; j++) size += iov[j].iov_len; /* * Size is the total size of the buffers provided by the user. The number of * received bytes can be smaller */ - if ((flags & PRB_FLAG_IS_WRITE) == 0) - if (size > retval) + if((flags & PRB_FLAG_IS_WRITE) == 0) + if(size > retval) size = retval; res = val_to_ring(args, size, 0, false, 0); @@ -1353,8 +1296,8 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc /* * data */ - if (flags & PRB_FLAG_PUSH_DATA) { - if (retval > 0 && iovcnt > 0) { + if(flags & PRB_FLAG_PUSH_DATA) { + if(retval > 0 && iovcnt > 0) { /* * Retrieve the FD. It will be used for dynamic snaplen calculation. */ @@ -1366,9 +1309,9 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc */ bufsize = 0; - for (j = 0; j < iovcnt; j++) { - if ((flags & PRB_FLAG_IS_WRITE) == 0) { - if (bufsize >= retval) { + for(j = 0; j < iovcnt; j++) { + if((flags & PRB_FLAG_IS_WRITE) == 0) { + if(bufsize >= retval) { ASSERT(bufsize >= retval); /* @@ -1385,11 +1328,10 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc tocopy_len = min(iov[j].iov_len, targetbuflen - bufsize - 1); } - notcopied_len = (int)ppm_copy_from_user(targetbuf + bufsize, - iov[j].iov_base, - tocopy_len); + notcopied_len = + (int)ppm_copy_from_user(targetbuf + bufsize, iov[j].iov_base, tocopy_len); - if (unlikely(notcopied_len != 0)) { + if(unlikely(notcopied_len != 0)) { /* * This means we had a page fault. Skip this event. */ @@ -1398,7 +1340,7 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc bufsize += tocopy_len; - if (tocopy_len != iov[j].iov_len) { + if(tocopy_len != iov[j].iov_len) { /* * No space left in the args->str_storage buffer. * Copy must stop here. @@ -1409,11 +1351,7 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc args->enforce_snaplen = true; - res = val_to_ring(args, - (unsigned long)targetbuf, - bufsize, - false, - 0); + res = val_to_ring(args, (unsigned long)targetbuf, bufsize, false, 0); CHECK_RES(res); } else { res = val_to_ring(args, 0, 0, false, 0); @@ -1424,14 +1362,16 @@ int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struc return PPM_SUCCESS; } - #ifdef CONFIG_COMPAT /* * Parses the list of buffers of a xreadv or xwritev call, and pushes the size * (and optionally the data) to the ring. */ -int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, const struct compat_iovec __user *iovsrc, unsigned long iovcnt, int64_t retval, int flags) -{ +int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, + const struct compat_iovec __user *iovsrc, + unsigned long iovcnt, + int64_t retval, + int flags) { int32_t res; const struct compat_iovec *iov; uint64_t copylen; @@ -1446,13 +1386,13 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons copylen = iovcnt * sizeof(struct compat_iovec); - if (unlikely(iovcnt >= 0xffffffff)) + if(unlikely(iovcnt >= 0xffffffff)) return PPM_FAILURE_BUFFER_FULL; - if (unlikely(copylen >= STR_STORAGE_SIZE)) + if(unlikely(copylen >= STR_STORAGE_SIZE)) return PPM_FAILURE_BUFFER_FULL; - if (unlikely(ppm_copy_from_user(args->str_storage, iovsrc, copylen))) + if(unlikely(ppm_copy_from_user(args->str_storage, iovsrc, copylen))) return PPM_FAILURE_INVALID_USER_MEMORY; iov = (const struct compat_iovec *)(args->str_storage); @@ -1463,16 +1403,16 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons /* * Size */ - if (flags & PRB_FLAG_PUSH_SIZE) { - for (j = 0; j < iovcnt; j++) + if(flags & PRB_FLAG_PUSH_SIZE) { + for(j = 0; j < iovcnt; j++) size += iov[j].iov_len; /* * Size is the total size of the buffers provided by the user. The number of * received bytes can be smaller */ - if ((flags & PRB_FLAG_IS_WRITE) == 0) - if (size > retval) + if((flags & PRB_FLAG_IS_WRITE) == 0) + if(size > retval) size = retval; res = val_to_ring(args, size, 0, false, 0); @@ -1482,8 +1422,8 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons /* * data */ - if (flags & PRB_FLAG_PUSH_DATA) { - if (retval > 0 && iovcnt > 0) { + if(flags & PRB_FLAG_PUSH_DATA) { + if(retval > 0 && iovcnt > 0) { /* * Retrieve the FD. It will be used for dynamic snaplen calculation. */ @@ -1495,9 +1435,9 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons */ bufsize = 0; - for (j = 0; j < iovcnt; j++) { - if ((flags & PRB_FLAG_IS_WRITE) == 0) { - if (bufsize >= retval) { + for(j = 0; j < iovcnt; j++) { + if((flags & PRB_FLAG_IS_WRITE) == 0) { + if(bufsize >= retval) { ASSERT(bufsize >= retval); /* @@ -1515,10 +1455,10 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons } notcopied_len = (int)ppm_copy_from_user(targetbuf + bufsize, - compat_ptr(iov[j].iov_base), - tocopy_len); + compat_ptr(iov[j].iov_base), + tocopy_len); - if (unlikely(notcopied_len != 0)) { + if(unlikely(notcopied_len != 0)) { /* * This means we had a page fault. Skip this event. */ @@ -1527,7 +1467,7 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons bufsize += tocopy_len; - if (tocopy_len != iov[j].iov_len) { + if(tocopy_len != iov[j].iov_len) { /* * No space left in the args->str_storage buffer. * Copy must stop here. @@ -1538,11 +1478,7 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons args->enforce_snaplen = true; - res = val_to_ring(args, - (unsigned long)targetbuf, - bufsize, - false, - 0); + res = val_to_ring(args, (unsigned long)targetbuf, bufsize, false, 0); CHECK_RES(res); } else { res = val_to_ring(args, 0, 0, false, 0); @@ -1565,8 +1501,7 @@ int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, cons * filler function. * The arguments to extract are be specified in g_ppm_events. */ -int f_sys_autofill(struct event_filler_arguments *args) -{ +int f_sys_autofill(struct event_filler_arguments *args) { int res; unsigned long val; uint32_t j; @@ -1575,19 +1510,19 @@ int f_sys_autofill(struct event_filler_arguments *args) const struct ppm_event_entry *evinfo = &g_ppm_events[args->event_type]; ASSERT(evinfo->n_autofill_args <= PPM_MAX_AUTOFILL_ARGS); - for (j = 0; j < evinfo->n_autofill_args; j++) { - if (evinfo->autofill_args[j].id >= 0) { + for(j = 0; j < evinfo->n_autofill_args; j++) { + if(evinfo->autofill_args[j].id >= 0) { val = args->args[evinfo->autofill_args[j].id]; res = val_to_ring(args, val, 0, true, 0); CHECK_RES(res); - } else if (evinfo->autofill_args[j].id == AF_ID_RETVAL) { + } else if(evinfo->autofill_args[j].id == AF_ID_RETVAL) { /* * Return value */ retval = (int64_t)(long)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - } else if (evinfo->autofill_args[j].id == AF_ID_USEDEFAULT) { + } else if(evinfo->autofill_args[j].id == AF_ID_USEDEFAULT) { /* * Default Value */ diff --git a/driver/ppm_events.h b/driver/ppm_events.h index 97a2481200..d54e7df2c0 100644 --- a/driver/ppm_events.h +++ b/driver/ppm_events.h @@ -31,9 +31,9 @@ struct fault_data_t { struct event_filler_arguments { ppm_consumer_t *consumer; - char *buffer; /* the buffer that will be filled with the data */ + char *buffer; /* the buffer that will be filled with the data */ uint32_t buffer_size; /* the space in the ring buffer available for this event */ - uint32_t syscall_id; /* the system call ID */ + uint32_t syscall_id; /* the system call ID */ #ifdef PPM_ENABLE_SENTINEL uint32_t sentinel; #endif @@ -42,14 +42,16 @@ struct event_filler_arguments { uint32_t nargs; uint32_t arg_data_offset; uint32_t arg_data_size; - ppm_event_code event_type; /* the event type */ + ppm_event_code event_type; /* the event type */ /* Eventually convert this to an event_info union and move all the * below per-event params in this union, it's not good to waste kernel * stack since all this stuff is always exclusive */ struct pt_regs *regs; /* the registers containing the call arguments */ - struct task_struct *sched_prev; /* for context switch events, the task that is being scheduled out */ - struct task_struct *sched_next; /* for context switch events, the task that is being scheduled in */ + struct task_struct + *sched_prev; /* for context switch events, the task that is being scheduled out */ + struct task_struct + *sched_next; /* for context switch events, the task that is being scheduled in */ #ifdef CAPTURE_SCHED_PROC_FORK struct task_struct *child; /* for sched_process_fork events, this is the child task */ @@ -60,9 +62,9 @@ struct event_filler_arguments { bool compat; int fd; /* Passed by some of the fillers to val_to_ring to compute the snaplen dynamically */ bool enforce_snaplen; - int signo; /* Signal number */ - __kernel_pid_t spid; /* PID of source process */ - __kernel_pid_t dpid; /* PID of destination process */ + int signo; /* Signal number */ + __kernel_pid_t spid; /* PID of source process */ + __kernel_pid_t dpid; /* PID of destination process */ struct fault_data_t fault_data; /* For page faults */ }; @@ -86,20 +88,37 @@ extern const struct ppm_event_entry g_ppm_events[]; */ int32_t dpi_lookahead_init(void); int32_t push_empty_param(struct event_filler_arguments *args); -int32_t val_to_ring(struct event_filler_arguments *args, uint64_t val, uint32_t val_len, bool fromuser, uint8_t dyn_idx); +int32_t val_to_ring(struct event_filler_arguments *args, + uint64_t val, + uint32_t val_len, + bool fromuser, + uint8_t dyn_idx); uint16_t pack_addr(struct sockaddr *usrsockaddr, int ulen, char *targetbuf, uint16_t targetbufsize); -uint16_t fd_to_socktuple(int fd, struct sockaddr *usrsockaddr, int ulen, bool use_userdata, bool is_inbound, char *targetbuf, uint16_t targetbufsize); +uint16_t fd_to_socktuple(int fd, + struct sockaddr *usrsockaddr, + int ulen, + bool use_userdata, + bool is_inbound, + char *targetbuf, + uint16_t targetbufsize); int addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr *kaddr); -int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, const struct iovec __user *iovsrc, unsigned long iovcnt, int64_t retval, int flags); +int32_t parse_readv_writev_bufs(struct event_filler_arguments *args, + const struct iovec __user *iovsrc, + unsigned long iovcnt, + int64_t retval, + int flags); #ifdef CONFIG_COMPAT -int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, const struct compat_iovec __user *iovsrc, unsigned long iovcnt, int64_t retval, int flags); +int32_t compat_parse_readv_writev_bufs(struct event_filler_arguments *args, + const struct compat_iovec __user *iovsrc, + unsigned long iovcnt, + int64_t retval, + int flags); #endif -static inline int add_sentinel(struct event_filler_arguments *args) -{ +static inline int add_sentinel(struct event_filler_arguments *args) { #ifdef PPM_ENABLE_SENTINEL - if (likely(args->arg_data_size >= sizeof(uint32_t))) { + if(likely(args->arg_data_size >= sizeof(uint32_t))) { *(uint32_t *)(args->buffer + args->arg_data_offset) = args->sentinel; args->arg_data_offset += 4; args->arg_data_size -= 4; diff --git a/driver/ppm_events_public.h b/driver/ppm_events_public.h index 00da731076..7d01ab76d4 100644 --- a/driver/ppm_events_public.h +++ b/driver/ppm_events_public.h @@ -13,7 +13,7 @@ or GPL2.txt for full copies of the license. #ifdef __KERNEL__ #include -#elif defined(__USE_VMLINUX__ ) +#elif defined(__USE_VMLINUX__) /* In the modern probe, if we have the vmlinux.h we need nothing here. */ #else #include @@ -29,7 +29,9 @@ or GPL2.txt for full copies of the license. * Macros for packing in different build environments */ #if defined(_WIN32) -#define _packed __pragma(pack(push, 1)); __pragma(pack(pop)) +#define _packed \ + __pragma(pack(push, 1)); \ + __pragma(pack(pop)) #else #define _packed __attribute__((packed)) #endif @@ -37,91 +39,96 @@ or GPL2.txt for full copies of the license. /* * Limits */ -#define PPM_MAX_EVENT_PARAMS (1 << 5) /* Max number of parameters an event can have */ +#define PPM_MAX_EVENT_PARAMS (1 << 5) /* Max number of parameters an event can have */ #define PPM_MAX_NAME_LEN 32 /* * Socket families */ -#define PPM_AF_UNSPEC 0 -#define PPM_AF_UNIX 1 /* Unix domain sockets */ -#define PPM_AF_LOCAL 1 /* POSIX name for PPM_AF_UNIX */ -#define PPM_AF_INET 2 /* Internet IP Protocol */ -#define PPM_AF_AX25 3 /* Amateur Radio AX.25 */ -#define PPM_AF_IPX 4 /* Novell IPX */ -#define PPM_AF_APPLETALK 5 /* AppleTalk DDP */ -#define PPM_AF_NETROM 6 /* Amateur Radio NET/ROM */ -#define PPM_AF_BRIDGE 7 /* Multiprotocol bridge */ -#define PPM_AF_ATMPVC 8 /* ATM PVCs */ -#define PPM_AF_X25 9 /* Reserved for X.25 project */ -#define PPM_AF_INET6 10 /* IP version 6 */ -#define PPM_AF_ROSE 11 /* Amateur Radio X.25 PLP */ -#define PPM_AF_DECnet 12 /* Reserved for DECnet project */ -#define PPM_AF_NETBEUI 13 /* Reserved for 802.2LLC project*/ -#define PPM_AF_SECURITY 14 /* Security callback pseudo AF */ -#define PPM_AF_KEY 15 /* PF_KEY key management API */ -#define PPM_AF_NETLINK 16 -#define PPM_AF_ROUTE PPM_AF_NETLINK /* Alias to emulate 4.4BSD */ -#define PPM_AF_PACKET 17 /* Packet family */ -#define PPM_AF_ASH 18 /* Ash */ -#define PPM_AF_ECONET 19 /* Acorn Econet */ -#define PPM_AF_ATMSVC 20 /* ATM SVCs */ -#define PPM_AF_RDS 21 /* RDS sockets */ -#define PPM_AF_SNA 22 /* Linux SNA Project (nutters!) */ -#define PPM_AF_IRDA 23 /* IRDA sockets */ -#define PPM_AF_PPPOX 24 /* PPPoX sockets */ -#define PPM_AF_WANPIPE 25 /* Wanpipe API Sockets */ -#define PPM_AF_LLC 26 /* Linux LLC */ -#define PPM_AF_CAN 29 /* Controller Area Network */ -#define PPM_AF_TIPC 30 /* TIPC sockets */ -#define PPM_AF_BLUETOOTH 31 /* Bluetooth sockets */ -#define PPM_AF_IUCV 32 /* IUCV sockets */ -#define PPM_AF_RXRPC 33 /* RxRPC sockets */ -#define PPM_AF_ISDN 34 /* mISDN sockets */ -#define PPM_AF_PHONET 35 /* Phonet sockets */ -#define PPM_AF_IEEE802154 36 /* IEEE802154 sockets */ -#define PPM_AF_CAIF 37 /* CAIF sockets */ -#define PPM_AF_ALG 38 /* Algorithm sockets */ -#define PPM_AF_NFC 39 /* NFC sockets */ +#define PPM_AF_UNSPEC 0 +#define PPM_AF_UNIX 1 /* Unix domain sockets */ +#define PPM_AF_LOCAL 1 /* POSIX name for PPM_AF_UNIX */ +#define PPM_AF_INET 2 /* Internet IP Protocol */ +#define PPM_AF_AX25 3 /* Amateur Radio AX.25 */ +#define PPM_AF_IPX 4 /* Novell IPX */ +#define PPM_AF_APPLETALK 5 /* AppleTalk DDP */ +#define PPM_AF_NETROM 6 /* Amateur Radio NET/ROM */ +#define PPM_AF_BRIDGE 7 /* Multiprotocol bridge */ +#define PPM_AF_ATMPVC 8 /* ATM PVCs */ +#define PPM_AF_X25 9 /* Reserved for X.25 project */ +#define PPM_AF_INET6 10 /* IP version 6 */ +#define PPM_AF_ROSE 11 /* Amateur Radio X.25 PLP */ +#define PPM_AF_DECnet 12 /* Reserved for DECnet project */ +#define PPM_AF_NETBEUI 13 /* Reserved for 802.2LLC project*/ +#define PPM_AF_SECURITY 14 /* Security callback pseudo AF */ +#define PPM_AF_KEY 15 /* PF_KEY key management API */ +#define PPM_AF_NETLINK 16 +#define PPM_AF_ROUTE PPM_AF_NETLINK /* Alias to emulate 4.4BSD */ +#define PPM_AF_PACKET 17 /* Packet family */ +#define PPM_AF_ASH 18 /* Ash */ +#define PPM_AF_ECONET 19 /* Acorn Econet */ +#define PPM_AF_ATMSVC 20 /* ATM SVCs */ +#define PPM_AF_RDS 21 /* RDS sockets */ +#define PPM_AF_SNA 22 /* Linux SNA Project (nutters!) */ +#define PPM_AF_IRDA 23 /* IRDA sockets */ +#define PPM_AF_PPPOX 24 /* PPPoX sockets */ +#define PPM_AF_WANPIPE 25 /* Wanpipe API Sockets */ +#define PPM_AF_LLC 26 /* Linux LLC */ +#define PPM_AF_CAN 29 /* Controller Area Network */ +#define PPM_AF_TIPC 30 /* TIPC sockets */ +#define PPM_AF_BLUETOOTH 31 /* Bluetooth sockets */ +#define PPM_AF_IUCV 32 /* IUCV sockets */ +#define PPM_AF_RXRPC 33 /* RxRPC sockets */ +#define PPM_AF_ISDN 34 /* mISDN sockets */ +#define PPM_AF_PHONET 35 /* Phonet sockets */ +#define PPM_AF_IEEE802154 36 /* IEEE802154 sockets */ +#define PPM_AF_CAIF 37 /* CAIF sockets */ +#define PPM_AF_ALG 38 /* Algorithm sockets */ +#define PPM_AF_NFC 39 /* NFC sockets */ /* * File flags */ -#define PPM_O_NONE 0 -#define PPM_O_RDONLY (1 << 0) /* Open for reading only */ -#define PPM_O_WRONLY (1 << 1) /* Open for writing only */ -#define PPM_O_RDWR (PPM_O_RDONLY | PPM_O_WRONLY) /* Open for reading and writing */ -#define PPM_O_CREAT (1 << 2) /* Create a new file if it doesn't exist. */ -#define PPM_O_APPEND (1 << 3) /* If set, the file offset shall be set to the end of the file prior to each write. */ -#define PPM_O_DSYNC (1 << 4) -#define PPM_O_EXCL (1 << 5) -#define PPM_O_NONBLOCK (1 << 6) -#define PPM_O_SYNC (1 << 7) -#define PPM_O_TRUNC (1 << 8) -#define PPM_O_DIRECT (1 << 9) +#define PPM_O_NONE 0 +#define PPM_O_RDONLY (1 << 0) /* Open for reading only */ +#define PPM_O_WRONLY (1 << 1) /* Open for writing only */ +#define PPM_O_RDWR (PPM_O_RDONLY | PPM_O_WRONLY) /* Open for reading and writing */ +#define PPM_O_CREAT (1 << 2) /* Create a new file if it doesn't exist. */ +#define PPM_O_APPEND \ + (1 << 3) /* If set, the file offset shall be set to the end of the file prior to each write. \ + */ +#define PPM_O_DSYNC (1 << 4) +#define PPM_O_EXCL (1 << 5) +#define PPM_O_NONBLOCK (1 << 6) +#define PPM_O_SYNC (1 << 7) +#define PPM_O_TRUNC (1 << 8) +#define PPM_O_DIRECT (1 << 9) #define PPM_O_DIRECTORY (1 << 10) #define PPM_O_LARGEFILE (1 << 11) -#define PPM_O_CLOEXEC (1 << 12) -#define PPM_O_TMPFILE (1 << 13) +#define PPM_O_CLOEXEC (1 << 12) +#define PPM_O_TMPFILE (1 << 13) /* Flags added by syscall probe: */ -#define PPM_O_F_CREATED (1 << 14) /* file created during the syscall */ +#define PPM_O_F_CREATED (1 << 14) /* file created during the syscall */ #define PPM_FD_UPPER_LAYER (1 << 15) /* file is from upper layer */ #define PPM_FD_LOWER_LAYER (1 << 16) /* file is from upper layer */ /* * creat flags */ -/* These flags serve the same puropse as the flags PPM_FD_UPPER_LAYER and PPM_FD_LOWER_LAYER in the 'File flags' section. - * They are used in creat system call because it doesn't have a 'flags' parameter that can be used. - * This redifintion is needed because this 'creat_flags' parameter is 16 bits and the aforementioned flags are over 16 bits. +/* These flags serve the same puropse as the flags PPM_FD_UPPER_LAYER and PPM_FD_LOWER_LAYER in the + * 'File flags' section. They are used in creat system call because it doesn't have a 'flags' + * parameter that can be used. This redifintion is needed because this 'creat_flags' parameter is 16 + * bits and the aforementioned flags are over 16 bits. */ -#define PPM_FD_UPPER_LAYER_CREAT (1 << 0) /* file is from upper layer. Equivalent to PPM_FD_UPPER_LAYER */ -#define PPM_FD_LOWER_LAYER_CREAT (1 << 1) /* file is from upper layer. Equivalent to PPM_FD_LOWER_LAYER */ +#define PPM_FD_UPPER_LAYER_CREAT \ + (1 << 0) /* file is from upper layer. Equivalent to PPM_FD_UPPER_LAYER */ +#define PPM_FD_LOWER_LAYER_CREAT \ + (1 << 1) /* file is from upper layer. Equivalent to PPM_FD_LOWER_LAYER */ /* * File modes */ -#define PPM_S_NONE 0 +#define PPM_S_NONE 0 #define PPM_S_IXOTH (1 << 0) #define PPM_S_IWOTH (1 << 1) #define PPM_S_IROTH (1 << 2) @@ -138,10 +145,10 @@ or GPL2.txt for full copies of the license. /* * mknod() modes */ -#define PPM_S_IFREG 0100000 -#define PPM_S_IFCHR 0020000 -#define PPM_S_IFBLK 0060000 -#define PPM_S_IFIFO 0010000 +#define PPM_S_IFREG 0100000 +#define PPM_S_IFCHR 0020000 +#define PPM_S_IFBLK 0060000 +#define PPM_S_IFIFO 0010000 #define PPM_S_IFSOCK 0140000 /* @@ -173,28 +180,37 @@ or GPL2.txt for full copies of the license. #define PPM_CL_CLONE_THREAD (1 << 13) #define PPM_CL_CLONE_UNTRACED (1 << 14) #define PPM_CL_CLONE_VM (1 << 15) -#define PPM_CL_CLONE_INVERTED (1 << 16) /* libsinsp-specific flag. It's set if clone() returned in */ - /* the child process before than in the parent process. */ -#define PPM_CL_NAME_CHANGED (1 << 17) /* libsinsp-specific flag. Set when the thread name changes */ - /* (for example because execve was called) */ -#define PPM_CL_CLOSED (1 << 18) /* thread has been closed. */ -#define PPM_CL_ACTIVE (1 << 19) /* libsinsp-specific flag. Set in the first non-clone event for - this thread. */ +#define PPM_CL_CLONE_INVERTED \ + (1 << 16) /* libsinsp-specific flag. It's set if clone() returned in */ + /* the child process before than in the parent process. */ +#define PPM_CL_NAME_CHANGED \ + (1 << 17) /* libsinsp-specific flag. Set when the thread name changes \ + */ + /* (for example because execve was called) */ +#define PPM_CL_CLOSED (1 << 18) /* thread has been closed. */ +#define PPM_CL_ACTIVE \ + (1 << 19) /* libsinsp-specific flag. Set in the first non-clone event for \ + this thread. */ #define PPM_CL_CLONE_NEWUSER (1 << 20) -#define PPM_CL_PIPE_SRC (1 << 21) /* libsinsp-specific flag. Set if this thread has been - detected to be the source in a shell pipe. */ -#define PPM_CL_PIPE_DST (1 << 22) /* libsinsp-specific flag. Set if this thread has been - detected to be the destination in a shell pipe. */ +#define PPM_CL_PIPE_SRC \ + (1 << 21) /* libsinsp-specific flag. Set if this thread has been \ + detected to be the source in a shell pipe. */ +#define PPM_CL_PIPE_DST \ + (1 << 22) /* libsinsp-specific flag. Set if this thread has been \ + detected to be the destination in a shell pipe. */ #define PPM_CL_CLONE_CHILD_CLEARTID (1 << 23) #define PPM_CL_CLONE_CHILD_SETTID (1 << 24) #define PPM_CL_CLONE_SETTLS (1 << 25) #define PPM_CL_CLONE_STOPPED (1 << 26) #define PPM_CL_CLONE_VFORK (1 << 27) #define PPM_CL_CLONE_NEWCGROUP (1 << 28) -#define PPM_CL_CHILD_IN_PIDNS (1<<29) /* true if the thread created by clone() is *not* - in the init pid namespace */ -#define PPM_CL_IS_MAIN_THREAD (1 << 30) /* libsinsp-specific flag. Set if this is the main thread */ - /* in envs where main thread tid != pid.*/ +#define PPM_CL_CHILD_IN_PIDNS \ + (1 << 29) /* true if the thread created by clone() is *not* \ + in the init pid namespace */ +#define PPM_CL_IS_MAIN_THREAD \ + (1 << 30) /* libsinsp-specific flag. Set if this is the main thread \ + */ + /* in envs where main thread tid != pid.*/ /* * Futex Operations @@ -212,7 +228,7 @@ or GPL2.txt for full copies of the license. #define PPM_FU_FUTEX_WAKE_BITSET 10 #define PPM_FU_FUTEX_WAIT_REQUEUE_PI 11 #define PPM_FU_FUTEX_CMP_REQUEUE_PI 12 -#define PPM_FU_FUTEX_PRIVATE_FLAG 128 +#define PPM_FU_FUTEX_PRIVATE_FLAG 128 #define PPM_FU_FUTEX_CLOCK_REALTIME 256 /* @@ -240,43 +256,43 @@ or GPL2.txt for full copies of the license. /* * mount() flags */ -#define PPM_MS_RDONLY (1<<0) -#define PPM_MS_NOSUID (1<<1) -#define PPM_MS_NODEV (1<<2) -#define PPM_MS_NOEXEC (1<<3) -#define PPM_MS_SYNCHRONOUS (1<<4) -#define PPM_MS_REMOUNT (1<<5) -#define PPM_MS_MANDLOCK (1<<6) -#define PPM_MS_DIRSYNC (1<<7) - -#define PPM_MS_NOATIME (1<<10) -#define PPM_MS_NODIRATIME (1<<11) -#define PPM_MS_BIND (1<<12) -#define PPM_MS_MOVE (1<<13) -#define PPM_MS_REC (1<<14) -#define PPM_MS_SILENT (1<<15) -#define PPM_MS_POSIXACL (1<<16) -#define PPM_MS_UNBINDABLE (1<<17) -#define PPM_MS_PRIVATE (1<<18) -#define PPM_MS_SLAVE (1<<19) -#define PPM_MS_SHARED (1<<20) -#define PPM_MS_RELATIME (1<<21) -#define PPM_MS_KERNMOUNT (1<<22) -#define PPM_MS_I_VERSION (1<<23) -#define PPM_MS_STRICTATIME (1<<24) -#define PPM_MS_LAZYTIME (1<<25) - -#define PPM_MS_NOSEC (1<<28) -#define PPM_MS_BORN (1<<29) -#define PPM_MS_ACTIVE (1<<30) -#define PPM_MS_NOUSER (1<<31) +#define PPM_MS_RDONLY (1 << 0) +#define PPM_MS_NOSUID (1 << 1) +#define PPM_MS_NODEV (1 << 2) +#define PPM_MS_NOEXEC (1 << 3) +#define PPM_MS_SYNCHRONOUS (1 << 4) +#define PPM_MS_REMOUNT (1 << 5) +#define PPM_MS_MANDLOCK (1 << 6) +#define PPM_MS_DIRSYNC (1 << 7) + +#define PPM_MS_NOATIME (1 << 10) +#define PPM_MS_NODIRATIME (1 << 11) +#define PPM_MS_BIND (1 << 12) +#define PPM_MS_MOVE (1 << 13) +#define PPM_MS_REC (1 << 14) +#define PPM_MS_SILENT (1 << 15) +#define PPM_MS_POSIXACL (1 << 16) +#define PPM_MS_UNBINDABLE (1 << 17) +#define PPM_MS_PRIVATE (1 << 18) +#define PPM_MS_SLAVE (1 << 19) +#define PPM_MS_SHARED (1 << 20) +#define PPM_MS_RELATIME (1 << 21) +#define PPM_MS_KERNMOUNT (1 << 22) +#define PPM_MS_I_VERSION (1 << 23) +#define PPM_MS_STRICTATIME (1 << 24) +#define PPM_MS_LAZYTIME (1 << 25) + +#define PPM_MS_NOSEC (1 << 28) +#define PPM_MS_BORN (1 << 29) +#define PPM_MS_ACTIVE (1 << 30) +#define PPM_MS_NOUSER (1 << 31) /* * umount() flags */ -#define PPM_MNT_FORCE (1 << 0) -#define PPM_MNT_DETACH (1 << 1) -#define PPM_MNT_EXPIRE (1 << 2) +#define PPM_MNT_FORCE (1 << 0) +#define PPM_MNT_DETACH (1 << 1) +#define PPM_MNT_EXPIRE (1 << 2) #define PPM_UMOUNT_NOFOLLOW (1 << 3) /* @@ -300,35 +316,34 @@ or GPL2.txt for full copies of the license. /* * linkat() flags */ -#define PPM_AT_SYMLINK_FOLLOW 0x400 -#define PPM_AT_EMPTY_PATH 0x1000 +#define PPM_AT_SYMLINK_FOLLOW 0x400 +#define PPM_AT_EMPTY_PATH 0x1000 /* * newfstatat() flags */ -#define PPM_AT_NO_AUTOMOUNT 0x800 -#define PPM_AT_SYMLINK_NOFOLLOW 0x100 - +#define PPM_AT_NO_AUTOMOUNT 0x800 +#define PPM_AT_SYMLINK_NOFOLLOW 0x100 /* * rlimit resources */ -#define PPM_RLIMIT_CPU 0 /* CPU time in sec */ -#define PPM_RLIMIT_FSIZE 1 /* Maximum filesize */ -#define PPM_RLIMIT_DATA 2 /* max data size */ -#define PPM_RLIMIT_STACK 3 /* max stack size */ -#define PPM_RLIMIT_CORE 4 /* max core file size */ -#define PPM_RLIMIT_RSS 5 /* max resident set size */ -#define PPM_RLIMIT_NPROC 6 /* max number of processes */ -#define PPM_RLIMIT_NOFILE 7 /* max number of open files */ -#define PPM_RLIMIT_MEMLOCK 8 /* max locked-in-memory address space */ -#define PPM_RLIMIT_AS 9 /* address space limit */ -#define PPM_RLIMIT_LOCKS 10 /* maximum file locks held */ +#define PPM_RLIMIT_CPU 0 /* CPU time in sec */ +#define PPM_RLIMIT_FSIZE 1 /* Maximum filesize */ +#define PPM_RLIMIT_DATA 2 /* max data size */ +#define PPM_RLIMIT_STACK 3 /* max stack size */ +#define PPM_RLIMIT_CORE 4 /* max core file size */ +#define PPM_RLIMIT_RSS 5 /* max resident set size */ +#define PPM_RLIMIT_NPROC 6 /* max number of processes */ +#define PPM_RLIMIT_NOFILE 7 /* max number of open files */ +#define PPM_RLIMIT_MEMLOCK 8 /* max locked-in-memory address space */ +#define PPM_RLIMIT_AS 9 /* address space limit */ +#define PPM_RLIMIT_LOCKS 10 /* maximum file locks held */ #define PPM_RLIMIT_SIGPENDING 11 /* max number of pending signals */ -#define PPM_RLIMIT_MSGQUEUE 12 /* maximum bytes in POSIX mqueues */ -#define PPM_RLIMIT_NICE 13 /* max nice prio allowed to raise to 0-39 for nice level 19 .. -20 */ -#define PPM_RLIMIT_RTPRIO 14 /* maximum realtime priority */ -#define PPM_RLIMIT_RTTIME 15 /* timeout for RT tasks in us */ +#define PPM_RLIMIT_MSGQUEUE 12 /* maximum bytes in POSIX mqueues */ +#define PPM_RLIMIT_NICE 13 /* max nice prio allowed to raise to 0-39 for nice level 19 .. -20 */ +#define PPM_RLIMIT_RTPRIO 14 /* maximum realtime priority */ +#define PPM_RLIMIT_RTTIME 15 /* timeout for RT tasks in us */ #define PPM_RLIMIT_UNKNOWN 255 /* CPU time in sec */ /* @@ -376,60 +391,60 @@ or GPL2.txt for full copies of the license. * getsockopt/setsockopt options * SOL_SOCKET only currently */ -#define PPM_SOCKOPT_UNKNOWN 0 -#define PPM_SOCKOPT_SO_DEBUG 1 -#define PPM_SOCKOPT_SO_REUSEADDR 2 -#define PPM_SOCKOPT_SO_TYPE 3 -#define PPM_SOCKOPT_SO_ERROR 4 -#define PPM_SOCKOPT_SO_DONTROUTE 5 -#define PPM_SOCKOPT_SO_BROADCAST 6 -#define PPM_SOCKOPT_SO_SNDBUF 7 -#define PPM_SOCKOPT_SO_RCVBUF 8 -#define PPM_SOCKOPT_SO_SNDBUFFORCE 32 -#define PPM_SOCKOPT_SO_RCVBUFFORCE 33 -#define PPM_SOCKOPT_SO_KEEPALIVE 9 -#define PPM_SOCKOPT_SO_OOBINLINE 10 -#define PPM_SOCKOPT_SO_NO_CHECK 11 -#define PPM_SOCKOPT_SO_PRIORITY 12 -#define PPM_SOCKOPT_SO_LINGER 13 -#define PPM_SOCKOPT_SO_BSDCOMPAT 14 -#define PPM_SOCKOPT_SO_REUSEPORT 15 -#define PPM_SOCKOPT_SO_PASSCRED 16 -#define PPM_SOCKOPT_SO_PEERCRED 17 -#define PPM_SOCKOPT_SO_RCVLOWAT 18 -#define PPM_SOCKOPT_SO_SNDLOWAT 19 -#define PPM_SOCKOPT_SO_RCVTIMEO 20 -#define PPM_SOCKOPT_SO_SNDTIMEO 21 -#define PPM_SOCKOPT_SO_SECURITY_AUTHENTICATION 22 -#define PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_TRANSPORT 23 -#define PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_NETWORK 24 -#define PPM_SOCKOPT_SO_BINDTODEVICE 25 -#define PPM_SOCKOPT_SO_ATTACH_FILTER 26 -#define PPM_SOCKOPT_SO_DETACH_FILTER 27 -#define PPM_SOCKOPT_SO_PEERNAME 28 -#define PPM_SOCKOPT_SO_TIMESTAMP 29 -#define PPM_SOCKOPT_SO_ACCEPTCONN 30 -#define PPM_SOCKOPT_SO_PEERSEC 31 -#define PPM_SOCKOPT_SO_PASSSEC 34 -#define PPM_SOCKOPT_SO_TIMESTAMPNS 35 -#define PPM_SOCKOPT_SO_MARK 36 -#define PPM_SOCKOPT_SO_TIMESTAMPING 37 -#define PPM_SOCKOPT_SO_PROTOCOL 38 -#define PPM_SOCKOPT_SO_DOMAIN 39 -#define PPM_SOCKOPT_SO_RXQ_OVFL 40 -#define PPM_SOCKOPT_SO_WIFI_STATUS 41 -#define PPM_SOCKOPT_SO_PEEK_OFF 42 -#define PPM_SOCKOPT_SO_NOFCS 43 -#define PPM_SOCKOPT_SO_LOCK_FILTER 44 -#define PPM_SOCKOPT_SO_SELECT_ERR_QUEUE 45 -#define PPM_SOCKOPT_SO_BUSY_POLL 46 -#define PPM_SOCKOPT_SO_MAX_PACING_RATE 47 -#define PPM_SOCKOPT_SO_BPF_EXTENSIONS 48 -#define PPM_SOCKOPT_SO_INCOMING_CPU 49 -#define PPM_SOCKOPT_SO_ATTACH_BPF 50 -#define PPM_SOCKOPT_SO_PEERGROUPS 51 -#define PPM_SOCKOPT_SO_MEMINFO 52 -#define PPM_SOCKOPT_SO_COOKIE 53 +#define PPM_SOCKOPT_UNKNOWN 0 +#define PPM_SOCKOPT_SO_DEBUG 1 +#define PPM_SOCKOPT_SO_REUSEADDR 2 +#define PPM_SOCKOPT_SO_TYPE 3 +#define PPM_SOCKOPT_SO_ERROR 4 +#define PPM_SOCKOPT_SO_DONTROUTE 5 +#define PPM_SOCKOPT_SO_BROADCAST 6 +#define PPM_SOCKOPT_SO_SNDBUF 7 +#define PPM_SOCKOPT_SO_RCVBUF 8 +#define PPM_SOCKOPT_SO_SNDBUFFORCE 32 +#define PPM_SOCKOPT_SO_RCVBUFFORCE 33 +#define PPM_SOCKOPT_SO_KEEPALIVE 9 +#define PPM_SOCKOPT_SO_OOBINLINE 10 +#define PPM_SOCKOPT_SO_NO_CHECK 11 +#define PPM_SOCKOPT_SO_PRIORITY 12 +#define PPM_SOCKOPT_SO_LINGER 13 +#define PPM_SOCKOPT_SO_BSDCOMPAT 14 +#define PPM_SOCKOPT_SO_REUSEPORT 15 +#define PPM_SOCKOPT_SO_PASSCRED 16 +#define PPM_SOCKOPT_SO_PEERCRED 17 +#define PPM_SOCKOPT_SO_RCVLOWAT 18 +#define PPM_SOCKOPT_SO_SNDLOWAT 19 +#define PPM_SOCKOPT_SO_RCVTIMEO 20 +#define PPM_SOCKOPT_SO_SNDTIMEO 21 +#define PPM_SOCKOPT_SO_SECURITY_AUTHENTICATION 22 +#define PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_TRANSPORT 23 +#define PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_NETWORK 24 +#define PPM_SOCKOPT_SO_BINDTODEVICE 25 +#define PPM_SOCKOPT_SO_ATTACH_FILTER 26 +#define PPM_SOCKOPT_SO_DETACH_FILTER 27 +#define PPM_SOCKOPT_SO_PEERNAME 28 +#define PPM_SOCKOPT_SO_TIMESTAMP 29 +#define PPM_SOCKOPT_SO_ACCEPTCONN 30 +#define PPM_SOCKOPT_SO_PEERSEC 31 +#define PPM_SOCKOPT_SO_PASSSEC 34 +#define PPM_SOCKOPT_SO_TIMESTAMPNS 35 +#define PPM_SOCKOPT_SO_MARK 36 +#define PPM_SOCKOPT_SO_TIMESTAMPING 37 +#define PPM_SOCKOPT_SO_PROTOCOL 38 +#define PPM_SOCKOPT_SO_DOMAIN 39 +#define PPM_SOCKOPT_SO_RXQ_OVFL 40 +#define PPM_SOCKOPT_SO_WIFI_STATUS 41 +#define PPM_SOCKOPT_SO_PEEK_OFF 42 +#define PPM_SOCKOPT_SO_NOFCS 43 +#define PPM_SOCKOPT_SO_LOCK_FILTER 44 +#define PPM_SOCKOPT_SO_SELECT_ERR_QUEUE 45 +#define PPM_SOCKOPT_SO_BUSY_POLL 46 +#define PPM_SOCKOPT_SO_MAX_PACING_RATE 47 +#define PPM_SOCKOPT_SO_BPF_EXTENSIONS 48 +#define PPM_SOCKOPT_SO_INCOMING_CPU 49 +#define PPM_SOCKOPT_SO_ATTACH_BPF 50 +#define PPM_SOCKOPT_SO_PEERGROUPS 51 +#define PPM_SOCKOPT_SO_MEMINFO 52 +#define PPM_SOCKOPT_SO_COOKIE 53 /* * getsockopt/setsockopt dynamic params @@ -441,7 +456,7 @@ or GPL2.txt for full copies of the license. #define PPM_SOCKOPT_IDX_TIMEVAL 4 #define PPM_SOCKOPT_IDX_MAX 5 - /* +/* * ptrace requests */ #define PPM_PTRACE_UNKNOWN 0 @@ -500,300 +515,301 @@ or GPL2.txt for full copies of the license. /* * memory protection flags */ -#define PPM_PROT_NONE 0 -#define PPM_PROT_READ (1 << 0) -#define PPM_PROT_WRITE (1 << 1) -#define PPM_PROT_EXEC (1 << 2) -#define PPM_PROT_SEM (1 << 3) -#define PPM_PROT_GROWSDOWN (1 << 4) -#define PPM_PROT_GROWSUP (1 << 5) -#define PPM_PROT_SAO (1 << 6) +#define PPM_PROT_NONE 0 +#define PPM_PROT_READ (1 << 0) +#define PPM_PROT_WRITE (1 << 1) +#define PPM_PROT_EXEC (1 << 2) +#define PPM_PROT_SEM (1 << 3) +#define PPM_PROT_GROWSDOWN (1 << 4) +#define PPM_PROT_GROWSUP (1 << 5) +#define PPM_PROT_SAO (1 << 6) /* * mmap flags */ -#define PPM_MAP_SHARED (1 << 0) -#define PPM_MAP_PRIVATE (1 << 1) -#define PPM_MAP_FIXED (1 << 2) -#define PPM_MAP_ANONYMOUS (1 << 3) -#define PPM_MAP_32BIT (1 << 4) -#define PPM_MAP_RENAME (1 << 5) -#define PPM_MAP_NORESERVE (1 << 6) -#define PPM_MAP_POPULATE (1 << 7) -#define PPM_MAP_NONBLOCK (1 << 8) -#define PPM_MAP_GROWSDOWN (1 << 9) -#define PPM_MAP_DENYWRITE (1 << 10) -#define PPM_MAP_EXECUTABLE (1 << 11) -#define PPM_MAP_INHERIT (1 << 12) -#define PPM_MAP_FILE (1 << 13) -#define PPM_MAP_LOCKED (1 << 14) +#define PPM_MAP_SHARED (1 << 0) +#define PPM_MAP_PRIVATE (1 << 1) +#define PPM_MAP_FIXED (1 << 2) +#define PPM_MAP_ANONYMOUS (1 << 3) +#define PPM_MAP_32BIT (1 << 4) +#define PPM_MAP_RENAME (1 << 5) +#define PPM_MAP_NORESERVE (1 << 6) +#define PPM_MAP_POPULATE (1 << 7) +#define PPM_MAP_NONBLOCK (1 << 8) +#define PPM_MAP_GROWSDOWN (1 << 9) +#define PPM_MAP_DENYWRITE (1 << 10) +#define PPM_MAP_EXECUTABLE (1 << 11) +#define PPM_MAP_INHERIT (1 << 12) +#define PPM_MAP_FILE (1 << 13) +#define PPM_MAP_LOCKED (1 << 14) /* * splice flags */ -#define PPM_SPLICE_F_MOVE (1 << 0) -#define PPM_SPLICE_F_NONBLOCK (1 << 1) -#define PPM_SPLICE_F_MORE (1 << 2) -#define PPM_SPLICE_F_GIFT (1 << 3) +#define PPM_SPLICE_F_MOVE (1 << 0) +#define PPM_SPLICE_F_NONBLOCK (1 << 1) +#define PPM_SPLICE_F_MORE (1 << 2) +#define PPM_SPLICE_F_GIFT (1 << 3) /* * quotactl cmds */ -#define PPM_Q_QUOTAON (1 << 0) -#define PPM_Q_QUOTAOFF (1 << 1) -#define PPM_Q_GETFMT (1 << 2) -#define PPM_Q_GETINFO (1 << 3) -#define PPM_Q_SETINFO (1 << 4) -#define PPM_Q_GETQUOTA (1 << 5) -#define PPM_Q_SETQUOTA (1 << 6) -#define PPM_Q_SYNC (1 << 7) -#define PPM_Q_XQUOTAON (1 << 8) -#define PPM_Q_XQUOTAOFF (1 << 9) -#define PPM_Q_XGETQUOTA (1 << 10) -#define PPM_Q_XSETQLIM (1 << 11) -#define PPM_Q_XGETQSTAT (1 << 12) -#define PPM_Q_XQUOTARM (1 << 13) -#define PPM_Q_XQUOTASYNC (1 << 14) -#define PPM_Q_XGETQSTATV (1 << 15) +#define PPM_Q_QUOTAON (1 << 0) +#define PPM_Q_QUOTAOFF (1 << 1) +#define PPM_Q_GETFMT (1 << 2) +#define PPM_Q_GETINFO (1 << 3) +#define PPM_Q_SETINFO (1 << 4) +#define PPM_Q_GETQUOTA (1 << 5) +#define PPM_Q_SETQUOTA (1 << 6) +#define PPM_Q_SYNC (1 << 7) +#define PPM_Q_XQUOTAON (1 << 8) +#define PPM_Q_XQUOTAOFF (1 << 9) +#define PPM_Q_XGETQUOTA (1 << 10) +#define PPM_Q_XSETQLIM (1 << 11) +#define PPM_Q_XGETQSTAT (1 << 12) +#define PPM_Q_XQUOTARM (1 << 13) +#define PPM_Q_XQUOTASYNC (1 << 14) +#define PPM_Q_XGETQSTATV (1 << 15) /* * quotactl types */ -#define PPM_USRQUOTA (1 << 0) -#define PPM_GRPQUOTA (1 << 1) +#define PPM_USRQUOTA (1 << 0) +#define PPM_GRPQUOTA (1 << 1) /* * quotactl dqi_flags */ -#define PPM_DQF_NONE (1 << 0) -#define PPM_V1_DQF_RSQUASH (1 << 1) +#define PPM_DQF_NONE (1 << 0) +#define PPM_V1_DQF_RSQUASH (1 << 1) /* * quotactl quotafmts */ -#define PPM_QFMT_NOT_USED (1 << 0) -#define PPM_QFMT_VFS_OLD (1 << 1) -#define PPM_QFMT_VFS_V0 (1 << 2) -#define PPM_QFMT_VFS_V1 (1 << 3) +#define PPM_QFMT_NOT_USED (1 << 0) +#define PPM_QFMT_VFS_OLD (1 << 1) +#define PPM_QFMT_VFS_V0 (1 << 2) +#define PPM_QFMT_VFS_V1 (1 << 3) /* * Semop flags */ -#define PPM_IPC_NOWAIT (1 << 0) -#define PPM_SEM_UNDO (1 << 1) +#define PPM_IPC_NOWAIT (1 << 0) +#define PPM_SEM_UNDO (1 << 1) /* * Semget flags */ -#define PPM_IPC_CREAT (1 << 13) -#define PPM_IPC_EXCL (1 << 14) +#define PPM_IPC_CREAT (1 << 13) +#define PPM_IPC_EXCL (1 << 14) -#define PPM_IPC_STAT (1 << 0) -#define PPM_IPC_SET (1 << 1) -#define PPM_IPC_RMID (1 << 2) -#define PPM_IPC_INFO (1 << 3) -#define PPM_SEM_INFO (1 << 4) -#define PPM_SEM_STAT (1 << 5) -#define PPM_GETALL (1 << 6) -#define PPM_GETNCNT (1 << 7) -#define PPM_GETPID (1 << 8) -#define PPM_GETVAL (1 << 9) -#define PPM_GETZCNT (1 << 10) -#define PPM_SETALL (1 << 11) -#define PPM_SETVAL (1 << 12) +#define PPM_IPC_STAT (1 << 0) +#define PPM_IPC_SET (1 << 1) +#define PPM_IPC_RMID (1 << 2) +#define PPM_IPC_INFO (1 << 3) +#define PPM_SEM_INFO (1 << 4) +#define PPM_SEM_STAT (1 << 5) +#define PPM_GETALL (1 << 6) +#define PPM_GETNCNT (1 << 7) +#define PPM_GETPID (1 << 8) +#define PPM_GETVAL (1 << 9) +#define PPM_GETZCNT (1 << 10) +#define PPM_SETALL (1 << 11) +#define PPM_SETVAL (1 << 12) /* * Access flags */ -#define PPM_F_OK (0) -#define PPM_X_OK (1 << 0) -#define PPM_W_OK (1 << 1) -#define PPM_R_OK (1 << 2) +#define PPM_F_OK (0) +#define PPM_X_OK (1 << 0) +#define PPM_W_OK (1 << 1) +#define PPM_R_OK (1 << 2) /* * Page fault flags */ -#define PPM_PF_PROTECTION_VIOLATION (1 << 0) -#define PPM_PF_PAGE_NOT_PRESENT (1 << 1) -#define PPM_PF_WRITE_ACCESS (1 << 2) -#define PPM_PF_READ_ACCESS (1 << 3) -#define PPM_PF_USER_FAULT (1 << 4) -#define PPM_PF_SUPERVISOR_FAULT (1 << 5) -#define PPM_PF_RESERVED_PAGE (1 << 6) -#define PPM_PF_INSTRUCTION_FETCH (1 << 7) - +#define PPM_PF_PROTECTION_VIOLATION (1 << 0) +#define PPM_PF_PAGE_NOT_PRESENT (1 << 1) +#define PPM_PF_WRITE_ACCESS (1 << 2) +#define PPM_PF_READ_ACCESS (1 << 3) +#define PPM_PF_USER_FAULT (1 << 4) +#define PPM_PF_SUPERVISOR_FAULT (1 << 5) +#define PPM_PF_RESERVED_PAGE (1 << 6) +#define PPM_PF_INSTRUCTION_FETCH (1 << 7) /* * Rename flags */ -#define PPM_RENAME_NOREPLACE (1 << 0) /* Don't overwrite target */ -#define PPM_RENAME_EXCHANGE (1 << 1) /* Exchange source and dest */ -#define PPM_RENAME_WHITEOUT (1 << 2) /* Whiteout source */ +#define PPM_RENAME_NOREPLACE (1 << 0) /* Don't overwrite target */ +#define PPM_RENAME_EXCHANGE (1 << 1) /* Exchange source and dest */ +#define PPM_RENAME_WHITEOUT (1 << 2) /* Whiteout source */ /* * Openat2 resolve flags */ -#define PPM_RESOLVE_BENEATH (1 << 0) -#define PPM_RESOLVE_IN_ROOT (1 << 1) -#define PPM_RESOLVE_NO_MAGICLINKS (1 << 2) -#define PPM_RESOLVE_NO_SYMLINKS (1 << 3) -#define PPM_RESOLVE_NO_XDEV (1 << 4) -#define PPM_RESOLVE_CACHED (1 << 5) +#define PPM_RESOLVE_BENEATH (1 << 0) +#define PPM_RESOLVE_IN_ROOT (1 << 1) +#define PPM_RESOLVE_NO_MAGICLINKS (1 << 2) +#define PPM_RESOLVE_NO_SYMLINKS (1 << 3) +#define PPM_RESOLVE_NO_XDEV (1 << 4) +#define PPM_RESOLVE_CACHED (1 << 5) /* * Execve family additional flags. */ -#define PPM_EXE_WRITABLE (1 << 0) -#define PPM_EXE_UPPER_LAYER (1 << 1) -#define PPM_EXE_FROM_MEMFD (1 << 2) -#define PPM_EXE_LOWER_LAYER (1 << 3) - +#define PPM_EXE_WRITABLE (1 << 0) +#define PPM_EXE_UPPER_LAYER (1 << 1) +#define PPM_EXE_FROM_MEMFD (1 << 2) +#define PPM_EXE_LOWER_LAYER (1 << 3) + /* * Execveat flags */ -#define PPM_EXVAT_AT_EMPTY_PATH (1 << 0) /* If pathname is an empty string, operate on the file referred to by dirfd */ -#define PPM_EXVAT_AT_SYMLINK_NOFOLLOW (1 << 1) /* If the file is a symbolic link, then the call fails */ +#define PPM_EXVAT_AT_EMPTY_PATH \ + (1 << 0) /* If pathname is an empty string, operate on the file referred to by dirfd */ +#define PPM_EXVAT_AT_SYMLINK_NOFOLLOW \ + (1 << 1) /* If the file is a symbolic link, then the call fails */ /* * Io_uring_setup flags */ -#define PPM_IORING_SETUP_IOPOLL (1<<0) -#define PPM_IORING_SETUP_SQPOLL (1<<1) -#define PPM_IORING_SQ_NEED_WAKEUP (1<<2) -#define PPM_IORING_SETUP_SQ_AFF (1<<3) -#define PPM_IORING_SETUP_CQSIZE (1<<4) -#define PPM_IORING_SETUP_CLAMP (1<<5) -#define PPM_IORING_SETUP_ATTACH_WQ (1<<6) -#define PPM_IORING_SETUP_R_DISABLED (1<<7) +#define PPM_IORING_SETUP_IOPOLL (1 << 0) +#define PPM_IORING_SETUP_SQPOLL (1 << 1) +#define PPM_IORING_SQ_NEED_WAKEUP (1 << 2) +#define PPM_IORING_SETUP_SQ_AFF (1 << 3) +#define PPM_IORING_SETUP_CQSIZE (1 << 4) +#define PPM_IORING_SETUP_CLAMP (1 << 5) +#define PPM_IORING_SETUP_ATTACH_WQ (1 << 6) +#define PPM_IORING_SETUP_R_DISABLED (1 << 7) /* * Io_uring_setup feats */ -#define PPM_IORING_FEAT_SINGLE_MMAP (1<<0) -#define PPM_IORING_FEAT_NODROP (1<<1) -#define PPM_IORING_FEAT_SUBMIT_STABLE (1<<2) -#define PPM_IORING_FEAT_RW_CUR_POS (1<<3) -#define PPM_IORING_FEAT_CUR_PERSONALITY (1<<4) -#define PPM_IORING_FEAT_FAST_POLL (1<<5) -#define PPM_IORING_FEAT_POLL_32BITS (1<<6) -#define PPM_IORING_FEAT_SQPOLL_NONFIXED (1<<7) -#define PPM_IORING_FEAT_ENTER_EXT_ARG (1<<8) -#define PPM_IORING_FEAT_NATIVE_WORKERS (1<<9) -#define PPM_IORING_FEAT_RSRC_TAGS (1<<10) +#define PPM_IORING_FEAT_SINGLE_MMAP (1 << 0) +#define PPM_IORING_FEAT_NODROP (1 << 1) +#define PPM_IORING_FEAT_SUBMIT_STABLE (1 << 2) +#define PPM_IORING_FEAT_RW_CUR_POS (1 << 3) +#define PPM_IORING_FEAT_CUR_PERSONALITY (1 << 4) +#define PPM_IORING_FEAT_FAST_POLL (1 << 5) +#define PPM_IORING_FEAT_POLL_32BITS (1 << 6) +#define PPM_IORING_FEAT_SQPOLL_NONFIXED (1 << 7) +#define PPM_IORING_FEAT_ENTER_EXT_ARG (1 << 8) +#define PPM_IORING_FEAT_NATIVE_WORKERS (1 << 9) +#define PPM_IORING_FEAT_RSRC_TAGS (1 << 10) /* * Io_uring_enter flags */ -#define PPM_IORING_ENTER_GETEVENTS (1<<0) -#define PPM_IORING_ENTER_SQ_WAKEUP (1<<1) -#define PPM_IORING_ENTER_SQ_WAIT (1<<2) -#define PPM_IORING_ENTER_EXT_ARG (1<<3) +#define PPM_IORING_ENTER_GETEVENTS (1 << 0) +#define PPM_IORING_ENTER_SQ_WAKEUP (1 << 1) +#define PPM_IORING_ENTER_SQ_WAIT (1 << 2) +#define PPM_IORING_ENTER_EXT_ARG (1 << 3) /* * Io_uring_register opcodes */ -#define PPM_IORING_REGISTER_BUFFERS 0 -#define PPM_IORING_UNREGISTER_BUFFERS 1 -#define PPM_IORING_REGISTER_FILES 2 -#define PPM_IORING_UNREGISTER_FILES 3 -#define PPM_IORING_REGISTER_EVENTFD 4 -#define PPM_IORING_UNREGISTER_EVENTFD 5 -#define PPM_IORING_REGISTER_FILES_UPDATE 6 -#define PPM_IORING_REGISTER_EVENTFD_ASYNC 7 -#define PPM_IORING_REGISTER_PROBE 8 -#define PPM_IORING_REGISTER_PERSONALITY 9 -#define PPM_IORING_UNREGISTER_PERSONALITY 10 -#define PPM_IORING_REGISTER_RESTRICTIONS 11 -#define PPM_IORING_REGISTER_ENABLE_RINGS 12 -#define PPM_IORING_REGISTER_FILES2 13 -#define PPM_IORING_REGISTER_FILES_UPDATE2 14 -#define PPM_IORING_REGISTER_BUFFERS2 15 -#define PPM_IORING_REGISTER_BUFFERS_UPDATE 16 -#define PPM_IORING_REGISTER_IOWQ_AFF 17 -#define PPM_IORING_UNREGISTER_IOWQ_AFF 18 -#define PPM_IORING_REGISTER_IOWQ_MAX_WORKERS 19 -#define PPM_IORING_REGISTER_RING_FDS 20 -#define PPM_IORING_UNREGISTER_RING_FDS 21 +#define PPM_IORING_REGISTER_BUFFERS 0 +#define PPM_IORING_UNREGISTER_BUFFERS 1 +#define PPM_IORING_REGISTER_FILES 2 +#define PPM_IORING_UNREGISTER_FILES 3 +#define PPM_IORING_REGISTER_EVENTFD 4 +#define PPM_IORING_UNREGISTER_EVENTFD 5 +#define PPM_IORING_REGISTER_FILES_UPDATE 6 +#define PPM_IORING_REGISTER_EVENTFD_ASYNC 7 +#define PPM_IORING_REGISTER_PROBE 8 +#define PPM_IORING_REGISTER_PERSONALITY 9 +#define PPM_IORING_UNREGISTER_PERSONALITY 10 +#define PPM_IORING_REGISTER_RESTRICTIONS 11 +#define PPM_IORING_REGISTER_ENABLE_RINGS 12 +#define PPM_IORING_REGISTER_FILES2 13 +#define PPM_IORING_REGISTER_FILES_UPDATE2 14 +#define PPM_IORING_REGISTER_BUFFERS2 15 +#define PPM_IORING_REGISTER_BUFFERS_UPDATE 16 +#define PPM_IORING_REGISTER_IOWQ_AFF 17 +#define PPM_IORING_UNREGISTER_IOWQ_AFF 18 +#define PPM_IORING_REGISTER_IOWQ_MAX_WORKERS 19 +#define PPM_IORING_REGISTER_RING_FDS 20 +#define PPM_IORING_UNREGISTER_RING_FDS 21 /* * MlocKall flags */ -#define PPM_MLOCKALL_MCL_CURRENT (1<<0) -#define PPM_MLOCKALL_MCL_FUTURE (1<<1) -#define PPM_MLOCKALL_MCL_ONFAULT (1<<2) +#define PPM_MLOCKALL_MCL_CURRENT (1 << 0) +#define PPM_MLOCKALL_MCL_FUTURE (1 << 1) +#define PPM_MLOCKALL_MCL_ONFAULT (1 << 2) /* * Mlock2 flags */ -#define PPM_MLOCK_ONFAULT (1<<0) +#define PPM_MLOCK_ONFAULT (1 << 0) /* * Memfd_create flags */ -#define PPM_MFD_CLOEXEC (1<<0) -#define PPM_MFD_ALLOW_SEALING (1<<1) -#define PPM_MFD_HUGETLB (1<<2) +#define PPM_MFD_CLOEXEC (1 << 0) +#define PPM_MFD_ALLOW_SEALING (1 << 1) +#define PPM_MFD_HUGETLB (1 << 2) /* * Fsconfig flags */ -#define PPM_FSCONFIG_SET_FLAG 0 -#define PPM_FSCONFIG_SET_STRING 1 -#define PPM_FSCONFIG_SET_BINARY 2 -#define PPM_FSCONFIG_SET_PATH 3 -#define PPM_FSCONFIG_SET_PATH_EMPTY 4 -#define PPM_FSCONFIG_SET_FD 5 -#define PPM_FSCONFIG_CMD_CREATE 6 -#define PPM_FSCONFIG_CMD_RECONFIGURE 7 +#define PPM_FSCONFIG_SET_FLAG 0 +#define PPM_FSCONFIG_SET_STRING 1 +#define PPM_FSCONFIG_SET_BINARY 2 +#define PPM_FSCONFIG_SET_PATH 3 +#define PPM_FSCONFIG_SET_PATH_EMPTY 4 +#define PPM_FSCONFIG_SET_FD 5 +#define PPM_FSCONFIG_CMD_CREATE 6 +#define PPM_FSCONFIG_CMD_RECONFIGURE 7 /* * Epoll_create1 flags */ -#define PPM_EPOLL_CLOEXEC (1 << 0) +#define PPM_EPOLL_CLOEXEC (1 << 0) /* * Prctl flags */ -//taken from https://github.com/torvalds/linux/blob/master/include/uapi/linux/prctl.h +// taken from https://github.com/torvalds/linux/blob/master/include/uapi/linux/prctl.h /* Values to pass as first argument to prctl() */ -#define PPM_PR_SET_PDEATHSIG 1 /* Second arg is a signal */ -#define PPM_PR_GET_PDEATHSIG 2 /* Second arg is a ptr to return the signal */ +#define PPM_PR_SET_PDEATHSIG 1 /* Second arg is a signal */ +#define PPM_PR_GET_PDEATHSIG 2 /* Second arg is a ptr to return the signal */ /* Get/set current->mm->dumpable */ -#define PPM_PR_GET_DUMPABLE 3 -#define PPM_PR_SET_DUMPABLE 4 +#define PPM_PR_GET_DUMPABLE 3 +#define PPM_PR_SET_DUMPABLE 4 /* Get/set unaligned access control bits (if meaningful) */ -#define PPM_PR_GET_UNALIGN 5 -#define PPM_PR_SET_UNALIGN 6 +#define PPM_PR_GET_UNALIGN 5 +#define PPM_PR_SET_UNALIGN 6 /* Get/set whether or not to drop capabilities on setuid() away from * uid 0 (as per security/commoncap.c) */ -#define PPM_PR_GET_KEEPCAPS 7 -#define PPM_PR_SET_KEEPCAPS 8 +#define PPM_PR_GET_KEEPCAPS 7 +#define PPM_PR_SET_KEEPCAPS 8 /* Get/set floating-point emulation control bits (if meaningful) */ -#define PPM_PR_GET_FPEMU 9 +#define PPM_PR_GET_FPEMU 9 #define PPM_PR_SET_FPEMU 10 /* Get/set floating-point exception mode (if meaningful) */ -#define PPM_PR_GET_FPEXC 11 -#define PPM_PR_SET_FPEXC 12 +#define PPM_PR_GET_FPEXC 11 +#define PPM_PR_SET_FPEXC 12 /* Get/set whether we use statistical process timing or accurate timestamp * based process timing */ -#define PPM_PR_GET_TIMING 13 -#define PPM_PR_SET_TIMING 14 +#define PPM_PR_GET_TIMING 13 +#define PPM_PR_SET_TIMING 14 -#define PPM_PR_SET_NAME 15 /* Set process name */ -#define PPM_PR_GET_NAME 16 /* Get process name */ +#define PPM_PR_SET_NAME 15 /* Set process name */ +#define PPM_PR_GET_NAME 16 /* Get process name */ /* Get/set process endian */ -#define PPM_PR_GET_ENDIAN 19 -#define PPM_PR_SET_ENDIAN 20 +#define PPM_PR_GET_ENDIAN 19 +#define PPM_PR_SET_ENDIAN 20 /* Get/set process seccomp mode */ -#define PPM_PR_GET_SECCOMP 21 -#define PPM_PR_SET_SECCOMP 22 +#define PPM_PR_GET_SECCOMP 21 +#define PPM_PR_SET_SECCOMP 22 /* Get/set the capability bounding set (as per security/commoncap.c) */ #define PPM_PR_CAPBSET_READ 23 @@ -808,63 +824,63 @@ or GPL2.txt for full copies of the license. #define PPM_PR_SET_SECUREBITS 28 /* - * pidfd_open flags -*/ -#define PPM_PIDFD_NONBLOCK (1<<0) + * pidfd_open flags + */ +#define PPM_PIDFD_NONBLOCK (1 << 0) /* - * finit_module flags -*/ -#define PPM_MODULE_INIT_IGNORE_MODVERSIONS 1 -#define PPM_MODULE_INIT_IGNORE_VERMAGIC 2 -#define PPM_MODULE_INIT_COMPRESSED_FILE 4 + * finit_module flags + */ +#define PPM_MODULE_INIT_IGNORE_MODVERSIONS 1 +#define PPM_MODULE_INIT_IGNORE_VERMAGIC 2 +#define PPM_MODULE_INIT_COMPRESSED_FILE 4 /* * delete_module flags -*/ -#define PPM_DELETE_MODULE_O_TRUNC (1 << 0) -#define PPM_DELETE_MODULE_O_NONBLOCK (1 << 1) - -/* - * bpf_commands -*/ -#define PPM_BPF_MAP_CREATE 0 -#define PPM_BPF_MAP_LOOKUP_ELEM 1 -#define PPM_BPF_MAP_UPDATE_ELEM 2 -#define PPM_BPF_MAP_DELETE_ELEM 3 -#define PPM_BPF_MAP_GET_NEXT_KEY 4 -#define PPM_BPF_PROG_LOAD 5 -#define PPM_BPF_OBJ_PIN 6 -#define PPM_BPF_OBJ_GET 7 -#define PPM_BPF_PROG_ATTACH 8 -#define PPM_BPF_PROG_DETACH 9 -#define PPM_BPF_PROG_TEST_RUN 10 -#define PPM_BPF_PROG_RUN PPM_BPF_PROG_TEST_RUN -#define PPM_BPF_PROG_GET_NEXT_ID 11 -#define PPM_BPF_MAP_GET_NEXT_ID 12 -#define PPM_BPF_PROG_GET_FD_BY_ID 13 -#define PPM_BPF_MAP_GET_FD_BY_ID 14 -#define PPM_BPF_OBJ_GET_INFO_BY_FD 15 -#define PPM_BPF_PROG_QUERY 16 -#define PPM_BPF_RAW_TRACEPOINT_OPEN 17 -#define PPM_BPF_BTF_LOAD 18 -#define PPM_BPF_BTF_GET_FD_BY_ID 19 -#define PPM_BPF_TASK_FD_QUERY 20 -#define PPM_BPF_MAP_LOOKUP_AND_DELETE_ELEM 21 -#define PPM_BPF_MAP_FREEZE 22 -#define PPM_BPF_BTF_GET_NEXT_ID 23 -#define PPM_BPF_MAP_LOOKUP_BATCH 24 -#define PPM_BPF_MAP_LOOKUP_AND_DELETE_BATCH 25 -#define PPM_BPF_MAP_UPDATE_BATCH 26 -#define PPM_BPF_MAP_DELETE_BATCH 27 -#define PPM_BPF_LINK_CREATE 28 -#define PPM_BPF_LINK_UPDATE 29 -#define PPM_BPF_LINK_GET_FD_BY_ID 30 -#define PPM_BPF_LINK_GET_NEXT_ID 31 -#define PPM_BPF_ENABLE_STATS 32 -#define PPM_BPF_ITER_CREATE 33 -#define PPM_BPF_LINK_DETACH 34 -#define PPM_BPF_PROG_BIND_MAP 35 + */ +#define PPM_DELETE_MODULE_O_TRUNC (1 << 0) +#define PPM_DELETE_MODULE_O_NONBLOCK (1 << 1) + +/* + * bpf_commands + */ +#define PPM_BPF_MAP_CREATE 0 +#define PPM_BPF_MAP_LOOKUP_ELEM 1 +#define PPM_BPF_MAP_UPDATE_ELEM 2 +#define PPM_BPF_MAP_DELETE_ELEM 3 +#define PPM_BPF_MAP_GET_NEXT_KEY 4 +#define PPM_BPF_PROG_LOAD 5 +#define PPM_BPF_OBJ_PIN 6 +#define PPM_BPF_OBJ_GET 7 +#define PPM_BPF_PROG_ATTACH 8 +#define PPM_BPF_PROG_DETACH 9 +#define PPM_BPF_PROG_TEST_RUN 10 +#define PPM_BPF_PROG_RUN PPM_BPF_PROG_TEST_RUN +#define PPM_BPF_PROG_GET_NEXT_ID 11 +#define PPM_BPF_MAP_GET_NEXT_ID 12 +#define PPM_BPF_PROG_GET_FD_BY_ID 13 +#define PPM_BPF_MAP_GET_FD_BY_ID 14 +#define PPM_BPF_OBJ_GET_INFO_BY_FD 15 +#define PPM_BPF_PROG_QUERY 16 +#define PPM_BPF_RAW_TRACEPOINT_OPEN 17 +#define PPM_BPF_BTF_LOAD 18 +#define PPM_BPF_BTF_GET_FD_BY_ID 19 +#define PPM_BPF_TASK_FD_QUERY 20 +#define PPM_BPF_MAP_LOOKUP_AND_DELETE_ELEM 21 +#define PPM_BPF_MAP_FREEZE 22 +#define PPM_BPF_BTF_GET_NEXT_ID 23 +#define PPM_BPF_MAP_LOOKUP_BATCH 24 +#define PPM_BPF_MAP_LOOKUP_AND_DELETE_BATCH 25 +#define PPM_BPF_MAP_UPDATE_BATCH 26 +#define PPM_BPF_MAP_DELETE_BATCH 27 +#define PPM_BPF_LINK_CREATE 28 +#define PPM_BPF_LINK_UPDATE 29 +#define PPM_BPF_LINK_GET_FD_BY_ID 30 +#define PPM_BPF_LINK_GET_NEXT_ID 31 +#define PPM_BPF_ENABLE_STATS 32 +#define PPM_BPF_ITER_CREATE 33 +#define PPM_BPF_LINK_DETACH 34 +#define PPM_BPF_PROG_BIND_MAP 35 /* * Get/set the timerslack as used by poll/select/nanosleep @@ -873,22 +889,21 @@ or GPL2.txt for full copies of the license. #define PPM_PR_SET_TIMERSLACK 29 #define PPM_PR_GET_TIMERSLACK 30 -#define PPM_PR_TASK_PERF_EVENTS_DISABLE 31 -#define PPM_PR_TASK_PERF_EVENTS_ENABLE 32 +#define PPM_PR_TASK_PERF_EVENTS_DISABLE 31 +#define PPM_PR_TASK_PERF_EVENTS_ENABLE 32 /* * Set early/late kill mode for hwpoison memory corruption. * This influences when the process gets killed on a memory corruption. */ -#define PPM_PR_MCE_KILL 33 - +#define PPM_PR_MCE_KILL 33 #define PPM_PR_MCE_KILL_GET 34 /* * Tune up process memory map specifics. */ -#define PPM_PR_SET_MM 35 +#define PPM_PR_SET_MM 35 /* * Set specific pid that is allowed to ptrace the current task. @@ -896,8 +911,8 @@ or GPL2.txt for full copies of the license. */ #define PPM_PR_SET_PTRACER 0x59616d61 -#define PPM_PR_SET_CHILD_SUBREAPER 36 -#define PPM_PR_GET_CHILD_SUBREAPER 37 +#define PPM_PR_SET_CHILD_SUBREAPER 36 +#define PPM_PR_GET_CHILD_SUBREAPER 37 /* * If no_new_privs is set, then operations that grant new privileges (i.e. @@ -913,64 +928,63 @@ or GPL2.txt for full copies of the license. * * See Documentation/userspace-api/no_new_privs.rst for more details. */ -#define PPM_PR_SET_NO_NEW_PRIVS 38 -#define PPM_PR_GET_NO_NEW_PRIVS 39 +#define PPM_PR_SET_NO_NEW_PRIVS 38 +#define PPM_PR_GET_NO_NEW_PRIVS 39 -#define PPM_PR_GET_TID_ADDRESS 40 +#define PPM_PR_GET_TID_ADDRESS 40 -#define PPM_PR_SET_THP_DISABLE 41 -#define PPM_PR_GET_THP_DISABLE 42 +#define PPM_PR_SET_THP_DISABLE 41 +#define PPM_PR_GET_THP_DISABLE 42 /* * No longer implemented, but left here to ensure the numbers stay reserved: */ -#define PPM_PR_MPX_ENABLE_MANAGEMENT 43 +#define PPM_PR_MPX_ENABLE_MANAGEMENT 43 #define PPM_PR_MPX_DISABLE_MANAGEMENT 44 -#define PPM_PR_SET_FP_MODE 45 -#define PPM_PR_GET_FP_MODE 46 +#define PPM_PR_SET_FP_MODE 45 +#define PPM_PR_GET_FP_MODE 46 /* Control the ambient capability set */ -#define PPM_PR_CAP_AMBIENT 47 +#define PPM_PR_CAP_AMBIENT 47 /* arm64 Scalable Vector Extension controls */ /* Flag values must be kept in sync with ptrace NT_ARM_SVE interface */ -#define PPM_PR_SVE_SET_VL 50 /* set task vector length */ -#define PPM_PR_SVE_GET_VL 51 /* get task vector length */ +#define PPM_PR_SVE_SET_VL 50 /* set task vector length */ +#define PPM_PR_SVE_GET_VL 51 /* get task vector length */ /* Per task speculation control */ -#define PPM_PR_GET_SPECULATION_CTRL 52 -#define PPM_PR_SET_SPECULATION_CTRL 53 +#define PPM_PR_GET_SPECULATION_CTRL 52 +#define PPM_PR_SET_SPECULATION_CTRL 53 /* Reset arm64 pointer authentication keys */ -#define PPM_PR_PAC_RESET_KEYS 54 +#define PPM_PR_PAC_RESET_KEYS 54 /* Tagged user address controls for arm64 */ -#define PPM_PR_SET_TAGGED_ADDR_CTRL 55 -#define PPM_PR_GET_TAGGED_ADDR_CTRL 56 +#define PPM_PR_SET_TAGGED_ADDR_CTRL 55 +#define PPM_PR_GET_TAGGED_ADDR_CTRL 56 /* Control reclaim behavior when allocating memory */ -#define PPM_PR_SET_IO_FLUSHER 57 -#define PPM_PR_GET_IO_FLUSHER 58 +#define PPM_PR_SET_IO_FLUSHER 57 +#define PPM_PR_GET_IO_FLUSHER 58 /* Dispatch syscalls to a userspace handler */ -#define PPM_PR_SET_SYSCALL_USER_DISPATCH 59 +#define PPM_PR_SET_SYSCALL_USER_DISPATCH 59 /* Set/get enabled arm64 pointer authentication keys */ -#define PPM_PR_PAC_SET_ENABLED_KEYS 60 -#define PPM_PR_PAC_GET_ENABLED_KEYS 61 +#define PPM_PR_PAC_SET_ENABLED_KEYS 60 +#define PPM_PR_PAC_GET_ENABLED_KEYS 61 /* Request the scheduler to share a core */ -#define PPM_PR_SCHED_CORE 62 +#define PPM_PR_SCHED_CORE 62 /* arm64 Scalable Matrix Extension controls */ /* Flag values must be in sync with SVE versions */ -#define PPM_PR_SME_SET_VL 63 /* set task vector length */ -#define PPM_PR_SME_GET_VL 64 /* get task vector length */ +#define PPM_PR_SME_SET_VL 63 /* set task vector length */ +#define PPM_PR_SME_GET_VL 64 /* get task vector length */ /* Bits common to PR_SME_SET_VL and PR_SME_GET_VL */ -#define PPM_PR_SET_VMA 0x53564d41 - +#define PPM_PR_SET_VMA 0x53564d41 /* * SuS says limits have to be unsigned. @@ -979,59 +993,59 @@ or GPL2.txt for full copies of the license. * Some architectures override this (for compatibility reasons): */ #ifndef RLIM_INFINITY -# define RLIM_INFINITY (~0UL) +#define RLIM_INFINITY (~0UL) #endif /* * Capabilities */ -#define PPM_CAP_CHOWN 1UL << 0 -#define PPM_CAP_DAC_OVERRIDE 1UL << 1 -#define PPM_CAP_DAC_READ_SEARCH 1UL << 2 -#define PPM_CAP_FOWNER 1UL << 3 -#define PPM_CAP_FSETID 1UL << 4 -#define PPM_CAP_KILL 1UL << 5 -#define PPM_CAP_SETGID 1UL << 6 -#define PPM_CAP_SETUID 1UL << 7 -#define PPM_CAP_SETPCAP 1UL << 8 -#define PPM_CAP_LINUX_IMMUTABLE 1UL << 9 -#define PPM_CAP_NET_BIND_SERVICE 1UL << 10 -#define PPM_CAP_NET_BROADCAST 1UL << 11 -#define PPM_CAP_NET_ADMIN 1UL << 12 -#define PPM_CAP_NET_RAW 1UL << 13 -#define PPM_CAP_IPC_LOCK 1UL << 14 -#define PPM_CAP_IPC_OWNER 1UL << 15 -#define PPM_CAP_SYS_MODULE 1UL << 16 -#define PPM_CAP_SYS_RAWIO 1UL << 17 -#define PPM_CAP_SYS_CHROOT 1UL << 18 -#define PPM_CAP_SYS_PTRACE 1UL << 19 -#define PPM_CAP_SYS_PACCT 1UL << 20 -#define PPM_CAP_SYS_ADMIN 1UL << 21 -#define PPM_CAP_SYS_BOOT 1UL << 22 -#define PPM_CAP_SYS_NICE 1UL << 23 -#define PPM_CAP_SYS_RESOURCE 1UL << 24 -#define PPM_CAP_SYS_TIME 1UL << 25 -#define PPM_CAP_SYS_TTY_CONFIG 1UL << 26 -#define PPM_CAP_MKNOD 1UL << 27 -#define PPM_CAP_LEASE 1UL << 28 -#define PPM_CAP_AUDIT_WRITE 1UL << 29 -#define PPM_CAP_AUDIT_CONTROL 1UL << 30 -#define PPM_CAP_SETFCAP 1UL << 31 -#define PPM_CAP_MAC_OVERRIDE 1UL << 32 -#define PPM_CAP_MAC_ADMIN 1UL << 33 -#define PPM_CAP_SYSLOG 1UL << 34 -#define PPM_CAP_WAKE_ALARM 1UL << 35 -#define PPM_CAP_BLOCK_SUSPEND 1UL << 36 -#define PPM_CAP_AUDIT_READ 1UL << 37 -#define PPM_CAP_PERFMON 1UL << 38 -#define PPM_CAP_BPF 1UL << 39 -#define PPM_CAP_CHECKPOINT_RESTORE 1UL << 40 +#define PPM_CAP_CHOWN 1UL << 0 +#define PPM_CAP_DAC_OVERRIDE 1UL << 1 +#define PPM_CAP_DAC_READ_SEARCH 1UL << 2 +#define PPM_CAP_FOWNER 1UL << 3 +#define PPM_CAP_FSETID 1UL << 4 +#define PPM_CAP_KILL 1UL << 5 +#define PPM_CAP_SETGID 1UL << 6 +#define PPM_CAP_SETUID 1UL << 7 +#define PPM_CAP_SETPCAP 1UL << 8 +#define PPM_CAP_LINUX_IMMUTABLE 1UL << 9 +#define PPM_CAP_NET_BIND_SERVICE 1UL << 10 +#define PPM_CAP_NET_BROADCAST 1UL << 11 +#define PPM_CAP_NET_ADMIN 1UL << 12 +#define PPM_CAP_NET_RAW 1UL << 13 +#define PPM_CAP_IPC_LOCK 1UL << 14 +#define PPM_CAP_IPC_OWNER 1UL << 15 +#define PPM_CAP_SYS_MODULE 1UL << 16 +#define PPM_CAP_SYS_RAWIO 1UL << 17 +#define PPM_CAP_SYS_CHROOT 1UL << 18 +#define PPM_CAP_SYS_PTRACE 1UL << 19 +#define PPM_CAP_SYS_PACCT 1UL << 20 +#define PPM_CAP_SYS_ADMIN 1UL << 21 +#define PPM_CAP_SYS_BOOT 1UL << 22 +#define PPM_CAP_SYS_NICE 1UL << 23 +#define PPM_CAP_SYS_RESOURCE 1UL << 24 +#define PPM_CAP_SYS_TIME 1UL << 25 +#define PPM_CAP_SYS_TTY_CONFIG 1UL << 26 +#define PPM_CAP_MKNOD 1UL << 27 +#define PPM_CAP_LEASE 1UL << 28 +#define PPM_CAP_AUDIT_WRITE 1UL << 29 +#define PPM_CAP_AUDIT_CONTROL 1UL << 30 +#define PPM_CAP_SETFCAP 1UL << 31 +#define PPM_CAP_MAC_OVERRIDE 1UL << 32 +#define PPM_CAP_MAC_ADMIN 1UL << 33 +#define PPM_CAP_SYSLOG 1UL << 34 +#define PPM_CAP_WAKE_ALARM 1UL << 35 +#define PPM_CAP_BLOCK_SUSPEND 1UL << 36 +#define PPM_CAP_AUDIT_READ 1UL << 37 +#define PPM_CAP_PERFMON 1UL << 38 +#define PPM_CAP_BPF 1UL << 39 +#define PPM_CAP_CHECKPOINT_RESTORE 1UL << 40 /* * RLIMIT_STACK default maximum - some architectures override it: */ #ifndef _STK_LIM_MAX -# define _STK_LIM_MAX RLIM_INFINITY +#define _STK_LIM_MAX RLIM_INFINITY #endif /* @@ -1058,8 +1072,7 @@ enum ppm_capture_category { PPMC_SCHED_PROC_FORK = 6, }; -enum ppm_overlay -{ +enum ppm_overlay { PPM_NOT_OVERLAY_FS = 0, PPM_OVERLAY_UPPER = 1, PPM_OVERLAY_LOWER = 2, @@ -1086,7 +1099,7 @@ typedef enum { PPME_SYSCALL_CLONE_11_E = 14, PPME_SYSCALL_CLONE_11_X = 15, PPME_PROCEXIT_E = 16, - PPME_PROCEXIT_X = 17, /* This should never be called */ + PPME_PROCEXIT_X = 17, /* This should never be called */ PPME_SOCKET_SOCKET_E = 18, PPME_SOCKET_SOCKET_X = 19, PPME_SOCKET_BIND_E = 20, @@ -1217,13 +1230,13 @@ typedef enum { PPME_SYSCALL_PRLIMIT_E = 144, PPME_SYSCALL_PRLIMIT_X = 145, PPME_SCHEDSWITCH_1_E = 146, - PPME_SCHEDSWITCH_1_X = 147, /* This should never be called */ - PPME_DROP_E = 148, /* For internal use */ - PPME_DROP_X = 149, /* For internal use */ - PPME_SYSCALL_FCNTL_E = 150, /* For internal use */ - PPME_SYSCALL_FCNTL_X = 151, /* For internal use */ + PPME_SCHEDSWITCH_1_X = 147, /* This should never be called */ + PPME_DROP_E = 148, /* For internal use */ + PPME_DROP_X = 149, /* For internal use */ + PPME_SYSCALL_FCNTL_E = 150, /* For internal use */ + PPME_SYSCALL_FCNTL_X = 151, /* For internal use */ PPME_SCHEDSWITCH_6_E = 152, - PPME_SCHEDSWITCH_6_X = 153, /* This should never be called */ + PPME_SCHEDSWITCH_6_X = 153, /* This should never be called */ PPME_SYSCALL_EXECVE_13_E = 154, PPME_SYSCALL_EXECVE_13_X = 155, PPME_SYSCALL_CLONE_16_E = 156, @@ -1257,9 +1270,9 @@ typedef enum { PPME_SYSCALL_VFORK_E = 184, PPME_SYSCALL_VFORK_X = 185, PPME_PROCEXIT_1_E = 186, - PPME_PROCEXIT_1_X = 187, /* This should never be called */ + PPME_PROCEXIT_1_X = 187, /* This should never be called */ PPME_SYSCALL_SENDFILE_E = 188, - PPME_SYSCALL_SENDFILE_X = 189, /* This should never be called */ + PPME_SYSCALL_SENDFILE_X = 189, /* This should never be called */ PPME_SYSCALL_QUOTACTL_E = 190, PPME_SYSCALL_QUOTACTL_X = 191, PPME_SYSCALL_SETRESUID_E = 192, @@ -1305,7 +1318,7 @@ typedef enum { PPME_SIGNALDELIVER_E = 232, PPME_SIGNALDELIVER_X = 233, /* This should never be called */ PPME_PROCINFO_E = 234, - PPME_PROCINFO_X = 235, /* This should never be called */ + PPME_PROCINFO_X = 235, /* This should never be called */ PPME_SYSCALL_GETDENTS_E = 236, PPME_SYSCALL_GETDENTS_X = 237, PPME_SYSCALL_GETDENTS64_E = 238, @@ -1504,7 +1517,6 @@ typedef enum { } ppm_event_code; /*@}*/ - /* ----------- Used only by modern BPF probe ----------- * "Tx_" stands for "extra tail call number x for the event after '_'". * For example "T1_EXECVE_X" stands for: @@ -1513,8 +1525,7 @@ typedef enum { * - `X` = means that we need this extra tail call for the exit event, `E` means enter the event. * */ -enum extra_event_prog_code -{ +enum extra_event_prog_code { T1_EXECVE_X = 0, T1_EXECVEAT_X = 1, T1_CLONE_X = 2, @@ -1531,7 +1542,7 @@ enum extra_event_prog_code T1_DROP_E = 13, T1_DROP_X = 14, T1_HOTPLUG_E = 15, - T1_OPEN_BY_HANDLE_AT_X =16, + T1_OPEN_BY_HANDLE_AT_X = 16, T2_EXECVE_X = 17, T2_EXECVEAT_X = 18, T2_SCHED_PROC_EXEC = 19, @@ -1542,503 +1553,512 @@ enum extra_event_prog_code * System-independent syscall codes */ -#define PPM_SC_FIELDS \ - PPM_SC_X(UNKNOWN, 0) \ - PPM_SC_X(RESTART_SYSCALL, 1) \ - PPM_SC_X(EXIT, 2) \ - PPM_SC_X(READ, 3) \ - PPM_SC_X(WRITE, 4) \ - PPM_SC_X(OPEN, 5) \ - PPM_SC_X(CLOSE, 6) \ - PPM_SC_X(CREAT, 7) \ - PPM_SC_X(LINK, 8) \ - PPM_SC_X(UNLINK, 9) \ - PPM_SC_X(CHDIR, 10) \ - PPM_SC_X(TIME, 11) \ - PPM_SC_X(MKNOD, 12) \ - PPM_SC_X(CHMOD, 13) \ - PPM_SC_X(STAT, 14) \ - PPM_SC_X(LSEEK, 15) \ - PPM_SC_X(GETPID, 16) \ - PPM_SC_X(MOUNT, 17) \ - PPM_SC_X(PTRACE, 18) \ - PPM_SC_X(ALARM, 19) \ - PPM_SC_X(FSTAT, 20) \ - PPM_SC_X(PAUSE, 21) \ - PPM_SC_X(UTIME, 22) \ - PPM_SC_X(ACCESS, 23) \ - PPM_SC_X(SYNC, 24) \ - PPM_SC_X(KILL, 25) \ - PPM_SC_X(RENAME, 26) \ - PPM_SC_X(MKDIR, 27) \ - PPM_SC_X(RMDIR, 28) \ - PPM_SC_X(DUP, 29) \ - PPM_SC_X(PIPE, 30) \ - PPM_SC_X(TIMES, 31) \ - PPM_SC_X(BRK, 32) \ - PPM_SC_X(ACCT, 33) \ - PPM_SC_X(IOCTL, 34) \ - PPM_SC_X(FCNTL, 35) \ - PPM_SC_X(SETPGID, 36) \ - PPM_SC_X(UMASK, 37) \ - PPM_SC_X(CHROOT, 38) \ - PPM_SC_X(USTAT, 39) \ - PPM_SC_X(DUP2, 40) \ - PPM_SC_X(GETPPID, 41) \ - PPM_SC_X(GETPGRP, 42) \ - PPM_SC_X(SETSID, 43) \ - PPM_SC_X(SETHOSTNAME, 44) \ - PPM_SC_X(SETRLIMIT, 45) \ - PPM_SC_X(GETRUSAGE, 46) \ - PPM_SC_X(GETTIMEOFDAY, 47) \ - PPM_SC_X(SETTIMEOFDAY, 48) \ - PPM_SC_X(SYMLINK, 49) \ - PPM_SC_X(LSTAT, 50) \ - PPM_SC_X(READLINK, 51) \ - PPM_SC_X(USELIB, 52) \ - PPM_SC_X(SWAPON, 53) \ - PPM_SC_X(REBOOT, 54) \ - PPM_SC_X(MMAP, 55) \ - PPM_SC_X(MUNMAP, 56) \ - PPM_SC_X(TRUNCATE, 57) \ - PPM_SC_X(FTRUNCATE, 58) \ - PPM_SC_X(FCHMOD, 59) \ - PPM_SC_X(GETPRIORITY, 60) \ - PPM_SC_X(SETPRIORITY, 61) \ - PPM_SC_X(STATFS, 62) \ - PPM_SC_X(FSTATFS, 63) \ - PPM_SC_X(SYSLOG, 64) \ - PPM_SC_X(SETITIMER, 65) \ - PPM_SC_X(GETITIMER, 66) \ - PPM_SC_X(UNAME, 67) \ - PPM_SC_X(VHANGUP, 68) \ - PPM_SC_X(WAIT4, 69) \ - PPM_SC_X(SWAPOFF, 70) \ - PPM_SC_X(SYSINFO, 71) \ - PPM_SC_X(FSYNC, 72) \ - PPM_SC_X(SETDOMAINNAME, 73) \ - PPM_SC_X(ADJTIMEX, 74) \ - PPM_SC_X(MPROTECT, 75) \ - PPM_SC_X(INIT_MODULE, 76) \ - PPM_SC_X(DELETE_MODULE, 77) \ - PPM_SC_X(QUOTACTL, 78) \ - PPM_SC_X(GETPGID, 79) \ - PPM_SC_X(FCHDIR, 80) \ - PPM_SC_X(SYSFS, 81) \ - PPM_SC_X(PERSONALITY, 82) \ - PPM_SC_X(GETDENTS, 83) \ - PPM_SC_X(SELECT, 84) \ - PPM_SC_X(FLOCK, 85) \ - PPM_SC_X(MSYNC, 86) \ - PPM_SC_X(READV, 87) \ - PPM_SC_X(WRITEV, 88) \ - PPM_SC_X(GETSID, 89) \ - PPM_SC_X(FDATASYNC, 90) \ - PPM_SC_X(MLOCK, 91) \ - PPM_SC_X(MUNLOCK, 92) \ - PPM_SC_X(MLOCKALL, 93) \ - PPM_SC_X(MUNLOCKALL, 94) \ - PPM_SC_X(SCHED_SETPARAM, 95) \ - PPM_SC_X(SCHED_GETPARAM, 96) \ - PPM_SC_X(SCHED_SETSCHEDULER, 97) \ - PPM_SC_X(SCHED_GETSCHEDULER, 98) \ - PPM_SC_X(SCHED_YIELD, 99) \ - PPM_SC_X(SCHED_GET_PRIORITY_MAX, 100) \ - PPM_SC_X(SCHED_GET_PRIORITY_MIN, 101) \ - PPM_SC_X(SCHED_RR_GET_INTERVAL, 102) \ - PPM_SC_X(NANOSLEEP, 103) \ - PPM_SC_X(MREMAP, 104) \ - PPM_SC_X(POLL, 105) \ - PPM_SC_X(PRCTL, 106) \ - PPM_SC_X(RT_SIGACTION, 107) \ - PPM_SC_X(RT_SIGPROCMASK, 108) \ - PPM_SC_X(RT_SIGPENDING, 109) \ - PPM_SC_X(RT_SIGTIMEDWAIT, 110) \ - PPM_SC_X(RT_SIGQUEUEINFO, 111) \ - PPM_SC_X(RT_SIGSUSPEND, 112) \ - PPM_SC_X(GETCWD, 113) \ - PPM_SC_X(CAPGET, 114) \ - PPM_SC_X(CAPSET, 115) \ - PPM_SC_X(SENDFILE, 116) \ - PPM_SC_X(GETRLIMIT, 117) \ - PPM_SC_X(LCHOWN, 118) \ - PPM_SC_X(GETUID, 119) \ - PPM_SC_X(GETGID, 120) \ - PPM_SC_X(GETEUID, 121) \ - PPM_SC_X(GETEGID, 122) \ - PPM_SC_X(SETREUID, 123) \ - PPM_SC_X(SETREGID, 124) \ - PPM_SC_X(GETGROUPS, 125) \ - PPM_SC_X(SETGROUPS, 126) \ - PPM_SC_X(FCHOWN, 127) \ - PPM_SC_X(SETRESUID, 128) \ - PPM_SC_X(GETRESUID, 129) \ - PPM_SC_X(SETRESGID, 130) \ - PPM_SC_X(GETRESGID, 131) \ - PPM_SC_X(CHOWN, 132) \ - PPM_SC_X(SETUID, 133) \ - PPM_SC_X(SETGID, 134) \ - PPM_SC_X(SETFSUID, 135) \ - PPM_SC_X(SETFSGID, 136) \ - PPM_SC_X(PIVOT_ROOT, 137) \ - PPM_SC_X(MINCORE, 138) \ - PPM_SC_X(MADVISE, 139) \ - PPM_SC_X(GETTID, 140) \ - PPM_SC_X(SETXATTR, 141) \ - PPM_SC_X(LSETXATTR, 142) \ - PPM_SC_X(FSETXATTR, 143) \ - PPM_SC_X(GETXATTR, 144) \ - PPM_SC_X(LGETXATTR, 145) \ - PPM_SC_X(FGETXATTR, 146) \ - PPM_SC_X(LISTXATTR, 147) \ - PPM_SC_X(LLISTXATTR, 148) \ - PPM_SC_X(FLISTXATTR, 149) \ - PPM_SC_X(REMOVEXATTR, 150) \ - PPM_SC_X(LREMOVEXATTR, 151) \ - PPM_SC_X(FREMOVEXATTR, 152) \ - PPM_SC_X(TKILL, 153) \ - PPM_SC_X(FUTEX, 154) \ - PPM_SC_X(SCHED_SETAFFINITY, 155) \ - PPM_SC_X(SCHED_GETAFFINITY, 156) \ - PPM_SC_X(SET_THREAD_AREA, 157) \ - PPM_SC_X(GET_THREAD_AREA, 158) \ - PPM_SC_X(IO_SETUP, 159) \ - PPM_SC_X(IO_DESTROY, 160) \ - PPM_SC_X(IO_GETEVENTS, 161) \ - PPM_SC_X(IO_SUBMIT, 162) \ - PPM_SC_X(IO_CANCEL, 163) \ - PPM_SC_X(EXIT_GROUP, 164) \ - PPM_SC_X(EPOLL_CREATE, 165) \ - PPM_SC_X(EPOLL_CTL, 166) \ - PPM_SC_X(EPOLL_WAIT, 167) \ - PPM_SC_X(REMAP_FILE_PAGES, 168) \ - PPM_SC_X(SET_TID_ADDRESS, 169) \ - PPM_SC_X(TIMER_CREATE, 170) \ - PPM_SC_X(TIMER_SETTIME, 171) \ - PPM_SC_X(TIMER_GETTIME, 172) \ - PPM_SC_X(TIMER_GETOVERRUN, 173) \ - PPM_SC_X(TIMER_DELETE, 174) \ - PPM_SC_X(CLOCK_SETTIME, 175) \ - PPM_SC_X(CLOCK_GETTIME, 176) \ - PPM_SC_X(CLOCK_GETRES, 177) \ - PPM_SC_X(CLOCK_NANOSLEEP, 178) \ - PPM_SC_X(TGKILL, 179) \ - PPM_SC_X(UTIMES, 180) \ - PPM_SC_X(MQ_OPEN, 181) \ - PPM_SC_X(MQ_UNLINK, 182) \ - PPM_SC_X(MQ_TIMEDSEND, 183) \ - PPM_SC_X(MQ_TIMEDRECEIVE, 184) \ - PPM_SC_X(MQ_NOTIFY, 185) \ - PPM_SC_X(MQ_GETSETATTR, 186) \ - PPM_SC_X(KEXEC_LOAD, 187) \ - PPM_SC_X(WAITID, 188) \ - PPM_SC_X(ADD_KEY, 189) \ - PPM_SC_X(REQUEST_KEY, 190) \ - PPM_SC_X(KEYCTL, 191) \ - PPM_SC_X(IOPRIO_SET, 192) \ - PPM_SC_X(IOPRIO_GET, 193) \ - PPM_SC_X(INOTIFY_INIT, 194) \ - PPM_SC_X(INOTIFY_ADD_WATCH, 195) \ - PPM_SC_X(INOTIFY_RM_WATCH, 196) \ - PPM_SC_X(OPENAT, 197) \ - PPM_SC_X(MKDIRAT, 198) \ - PPM_SC_X(MKNODAT, 199) \ - PPM_SC_X(FCHOWNAT, 200) \ - PPM_SC_X(FUTIMESAT, 201) \ - PPM_SC_X(UNLINKAT, 202) \ - PPM_SC_X(RENAMEAT, 203) \ - PPM_SC_X(LINKAT, 204) \ - PPM_SC_X(SYMLINKAT, 205) \ - PPM_SC_X(READLINKAT, 206) \ - PPM_SC_X(FCHMODAT, 207) \ - PPM_SC_X(FACCESSAT, 208) \ - PPM_SC_X(PSELECT6, 209) \ - PPM_SC_X(PPOLL, 210) \ - PPM_SC_X(UNSHARE, 211) \ - PPM_SC_X(SET_ROBUST_LIST, 212) \ - PPM_SC_X(GET_ROBUST_LIST, 213) \ - PPM_SC_X(SPLICE, 214) \ - PPM_SC_X(TEE, 215) \ - PPM_SC_X(VMSPLICE, 216) \ - PPM_SC_X(GETCPU, 217) \ - PPM_SC_X(EPOLL_PWAIT, 218) \ - PPM_SC_X(UTIMENSAT, 219) \ - PPM_SC_X(SIGNALFD, 220) \ - PPM_SC_X(TIMERFD_CREATE, 221) \ - PPM_SC_X(EVENTFD, 222) \ - PPM_SC_X(TIMERFD_SETTIME, 223) \ - PPM_SC_X(TIMERFD_GETTIME, 224) \ - PPM_SC_X(SIGNALFD4, 225) \ - PPM_SC_X(EVENTFD2, 226) \ - PPM_SC_X(EPOLL_CREATE1, 227) \ - PPM_SC_X(DUP3, 228) \ - PPM_SC_X(PIPE2, 229) \ - PPM_SC_X(INOTIFY_INIT1, 230) \ - PPM_SC_X(PREADV, 231) \ - PPM_SC_X(PWRITEV, 232) \ - PPM_SC_X(RT_TGSIGQUEUEINFO, 233) \ - PPM_SC_X(PERF_EVENT_OPEN, 234) \ - PPM_SC_X(FANOTIFY_INIT, 235) \ - PPM_SC_X(PRLIMIT64, 236) \ - PPM_SC_X(CLOCK_ADJTIME, 237) \ - PPM_SC_X(SYNCFS, 238) \ - PPM_SC_X(SETNS, 239) \ - PPM_SC_X(GETDENTS64, 240) \ - PPM_SC_X(SOCKET, 241) \ - PPM_SC_X(BIND, 242) \ - PPM_SC_X(CONNECT, 243) \ - PPM_SC_X(LISTEN, 244) \ - PPM_SC_X(ACCEPT, 245) \ - PPM_SC_X(GETSOCKNAME, 246) \ - PPM_SC_X(GETPEERNAME, 247) \ - PPM_SC_X(SOCKETPAIR, 248) \ - PPM_SC_X(SENDTO, 249) \ - PPM_SC_X(RECVFROM, 250) \ - PPM_SC_X(SHUTDOWN, 251) \ - PPM_SC_X(SETSOCKOPT, 252) \ - PPM_SC_X(GETSOCKOPT, 253) \ - PPM_SC_X(SENDMSG, 254) \ - PPM_SC_X(SENDMMSG, 255) \ - PPM_SC_X(RECVMSG, 256) \ - PPM_SC_X(RECVMMSG, 257) \ - PPM_SC_X(ACCEPT4, 258) \ - PPM_SC_X(SEMOP, 259) \ - PPM_SC_X(SEMGET, 260) \ - PPM_SC_X(SEMCTL, 261) \ - PPM_SC_X(MSGSND, 262) \ - PPM_SC_X(MSGRCV, 263) \ - PPM_SC_X(MSGGET, 264) \ - PPM_SC_X(MSGCTL, 265) \ - PPM_SC_X(SHMDT, 266) \ - PPM_SC_X(SHMGET, 267) \ - PPM_SC_X(SHMCTL, 268) \ - PPM_SC_X(STATFS64, 269) \ - PPM_SC_X(FSTATFS64, 270) \ - PPM_SC_X(FSTATAT64, 271) \ - PPM_SC_X(SENDFILE64, 272) \ - PPM_SC_X(UGETRLIMIT, 273) \ - PPM_SC_X(BDFLUSH, 274) \ - PPM_SC_X(SIGPROCMASK, 275) \ - PPM_SC_X(IPC, 276) \ - PPM_SC_X(SOCKETCALL, 277) \ - PPM_SC_X(STAT64, 278) \ - PPM_SC_X(LSTAT64, 279) \ - PPM_SC_X(FSTAT64, 280) \ - PPM_SC_X(FCNTL64, 281) \ - PPM_SC_X(MMAP2, 282) \ - PPM_SC_X(_NEWSELECT, 283) \ - PPM_SC_X(SGETMASK, 284) \ - PPM_SC_X(SSETMASK, 285) \ - PPM_SC_X(SIGPENDING, 286) \ - PPM_SC_X(OLDUNAME, 287) \ - PPM_SC_X(UMOUNT, 288) \ - PPM_SC_X(SIGNAL, 289) \ - PPM_SC_X(NICE, 290) \ - PPM_SC_X(STIME, 291) \ - PPM_SC_X(_LLSEEK, 292) \ - PPM_SC_X(WAITPID, 293) \ - PPM_SC_X(PREAD64, 294) \ - PPM_SC_X(PWRITE64, 295) \ - PPM_SC_X(ARCH_PRCTL, 296) \ - PPM_SC_X(SHMAT, 297) \ - PPM_SC_X(RT_SIGRETURN, 298) \ - PPM_SC_X(FALLOCATE, 299) \ - PPM_SC_X(NEWFSTATAT, 300) \ - PPM_SC_X(PROCESS_VM_READV, 301) \ - PPM_SC_X(PROCESS_VM_WRITEV, 302) \ - PPM_SC_X(FORK, 303) \ - PPM_SC_X(VFORK, 304) \ - PPM_SC_X(SETUID32, 305) \ - PPM_SC_X(GETUID32, 306) \ - PPM_SC_X(SETGID32, 307) \ - PPM_SC_X(GETEUID32, 308) \ - PPM_SC_X(GETGID32, 309) \ - PPM_SC_X(SETRESUID32, 310) \ - PPM_SC_X(SETRESGID32, 311) \ - PPM_SC_X(GETRESUID32, 312) \ - PPM_SC_X(GETRESGID32, 313) \ - PPM_SC_X(FINIT_MODULE, 314) \ - PPM_SC_X(BPF, 315) \ - PPM_SC_X(SECCOMP, 316) \ - PPM_SC_X(SIGALTSTACK, 317) \ - PPM_SC_X(GETRANDOM, 318) \ - PPM_SC_X(FADVISE64, 319) \ - PPM_SC_X(RENAMEAT2, 320) \ - PPM_SC_X(USERFAULTFD, 321) \ - PPM_SC_X(OPENAT2, 322) \ - PPM_SC_X(UMOUNT2, 323) \ - PPM_SC_X(EXECVE, 324) \ - PPM_SC_X(EXECVEAT, 325) \ - PPM_SC_X(COPY_FILE_RANGE, 326) \ - PPM_SC_X(CLONE, 327) \ - PPM_SC_X(CLONE3, 328) \ - PPM_SC_X(OPEN_BY_HANDLE_AT, 329) \ - PPM_SC_X(IO_URING_SETUP, 330) \ - PPM_SC_X(IO_URING_ENTER, 331) \ - PPM_SC_X(IO_URING_REGISTER, 332) \ - PPM_SC_X(MLOCK2, 333) \ - PPM_SC_X(GETEGID32, 334) \ - PPM_SC_X(FSCONFIG, 335) \ - PPM_SC_X(FSPICK, 336) \ - PPM_SC_X(FSMOUNT, 337) \ - PPM_SC_X(FSOPEN, 338) \ - PPM_SC_X(OPEN_TREE, 339) \ - PPM_SC_X(MOVE_MOUNT, 340) \ - PPM_SC_X(MOUNT_SETATTR, 341) \ - PPM_SC_X(MEMFD_CREATE, 342) \ - PPM_SC_X(MEMFD_SECRET, 343) \ - PPM_SC_X(IOPERM, 344) \ - PPM_SC_X(KEXEC_FILE_LOAD, 345) \ - PPM_SC_X(PIDFD_GETFD, 346) \ - PPM_SC_X(PIDFD_OPEN, 347) \ - PPM_SC_X(PIDFD_SEND_SIGNAL, 348) \ - PPM_SC_X(PKEY_ALLOC, 349) \ - PPM_SC_X(PKEY_MPROTECT, 350) \ - PPM_SC_X(PKEY_FREE, 351) \ +#define PPM_SC_FIELDS \ + PPM_SC_X(UNKNOWN, 0) \ + PPM_SC_X(RESTART_SYSCALL, 1) \ + PPM_SC_X(EXIT, 2) \ + PPM_SC_X(READ, 3) \ + PPM_SC_X(WRITE, 4) \ + PPM_SC_X(OPEN, 5) \ + PPM_SC_X(CLOSE, 6) \ + PPM_SC_X(CREAT, 7) \ + PPM_SC_X(LINK, 8) \ + PPM_SC_X(UNLINK, 9) \ + PPM_SC_X(CHDIR, 10) \ + PPM_SC_X(TIME, 11) \ + PPM_SC_X(MKNOD, 12) \ + PPM_SC_X(CHMOD, 13) \ + PPM_SC_X(STAT, 14) \ + PPM_SC_X(LSEEK, 15) \ + PPM_SC_X(GETPID, 16) \ + PPM_SC_X(MOUNT, 17) \ + PPM_SC_X(PTRACE, 18) \ + PPM_SC_X(ALARM, 19) \ + PPM_SC_X(FSTAT, 20) \ + PPM_SC_X(PAUSE, 21) \ + PPM_SC_X(UTIME, 22) \ + PPM_SC_X(ACCESS, 23) \ + PPM_SC_X(SYNC, 24) \ + PPM_SC_X(KILL, 25) \ + PPM_SC_X(RENAME, 26) \ + PPM_SC_X(MKDIR, 27) \ + PPM_SC_X(RMDIR, 28) \ + PPM_SC_X(DUP, 29) \ + PPM_SC_X(PIPE, 30) \ + PPM_SC_X(TIMES, 31) \ + PPM_SC_X(BRK, 32) \ + PPM_SC_X(ACCT, 33) \ + PPM_SC_X(IOCTL, 34) \ + PPM_SC_X(FCNTL, 35) \ + PPM_SC_X(SETPGID, 36) \ + PPM_SC_X(UMASK, 37) \ + PPM_SC_X(CHROOT, 38) \ + PPM_SC_X(USTAT, 39) \ + PPM_SC_X(DUP2, 40) \ + PPM_SC_X(GETPPID, 41) \ + PPM_SC_X(GETPGRP, 42) \ + PPM_SC_X(SETSID, 43) \ + PPM_SC_X(SETHOSTNAME, 44) \ + PPM_SC_X(SETRLIMIT, 45) \ + PPM_SC_X(GETRUSAGE, 46) \ + PPM_SC_X(GETTIMEOFDAY, 47) \ + PPM_SC_X(SETTIMEOFDAY, 48) \ + PPM_SC_X(SYMLINK, 49) \ + PPM_SC_X(LSTAT, 50) \ + PPM_SC_X(READLINK, 51) \ + PPM_SC_X(USELIB, 52) \ + PPM_SC_X(SWAPON, 53) \ + PPM_SC_X(REBOOT, 54) \ + PPM_SC_X(MMAP, 55) \ + PPM_SC_X(MUNMAP, 56) \ + PPM_SC_X(TRUNCATE, 57) \ + PPM_SC_X(FTRUNCATE, 58) \ + PPM_SC_X(FCHMOD, 59) \ + PPM_SC_X(GETPRIORITY, 60) \ + PPM_SC_X(SETPRIORITY, 61) \ + PPM_SC_X(STATFS, 62) \ + PPM_SC_X(FSTATFS, 63) \ + PPM_SC_X(SYSLOG, 64) \ + PPM_SC_X(SETITIMER, 65) \ + PPM_SC_X(GETITIMER, 66) \ + PPM_SC_X(UNAME, 67) \ + PPM_SC_X(VHANGUP, 68) \ + PPM_SC_X(WAIT4, 69) \ + PPM_SC_X(SWAPOFF, 70) \ + PPM_SC_X(SYSINFO, 71) \ + PPM_SC_X(FSYNC, 72) \ + PPM_SC_X(SETDOMAINNAME, 73) \ + PPM_SC_X(ADJTIMEX, 74) \ + PPM_SC_X(MPROTECT, 75) \ + PPM_SC_X(INIT_MODULE, 76) \ + PPM_SC_X(DELETE_MODULE, 77) \ + PPM_SC_X(QUOTACTL, 78) \ + PPM_SC_X(GETPGID, 79) \ + PPM_SC_X(FCHDIR, 80) \ + PPM_SC_X(SYSFS, 81) \ + PPM_SC_X(PERSONALITY, 82) \ + PPM_SC_X(GETDENTS, 83) \ + PPM_SC_X(SELECT, 84) \ + PPM_SC_X(FLOCK, 85) \ + PPM_SC_X(MSYNC, 86) \ + PPM_SC_X(READV, 87) \ + PPM_SC_X(WRITEV, 88) \ + PPM_SC_X(GETSID, 89) \ + PPM_SC_X(FDATASYNC, 90) \ + PPM_SC_X(MLOCK, 91) \ + PPM_SC_X(MUNLOCK, 92) \ + PPM_SC_X(MLOCKALL, 93) \ + PPM_SC_X(MUNLOCKALL, 94) \ + PPM_SC_X(SCHED_SETPARAM, 95) \ + PPM_SC_X(SCHED_GETPARAM, 96) \ + PPM_SC_X(SCHED_SETSCHEDULER, 97) \ + PPM_SC_X(SCHED_GETSCHEDULER, 98) \ + PPM_SC_X(SCHED_YIELD, 99) \ + PPM_SC_X(SCHED_GET_PRIORITY_MAX, 100) \ + PPM_SC_X(SCHED_GET_PRIORITY_MIN, 101) \ + PPM_SC_X(SCHED_RR_GET_INTERVAL, 102) \ + PPM_SC_X(NANOSLEEP, 103) \ + PPM_SC_X(MREMAP, 104) \ + PPM_SC_X(POLL, 105) \ + PPM_SC_X(PRCTL, 106) \ + PPM_SC_X(RT_SIGACTION, 107) \ + PPM_SC_X(RT_SIGPROCMASK, 108) \ + PPM_SC_X(RT_SIGPENDING, 109) \ + PPM_SC_X(RT_SIGTIMEDWAIT, 110) \ + PPM_SC_X(RT_SIGQUEUEINFO, 111) \ + PPM_SC_X(RT_SIGSUSPEND, 112) \ + PPM_SC_X(GETCWD, 113) \ + PPM_SC_X(CAPGET, 114) \ + PPM_SC_X(CAPSET, 115) \ + PPM_SC_X(SENDFILE, 116) \ + PPM_SC_X(GETRLIMIT, 117) \ + PPM_SC_X(LCHOWN, 118) \ + PPM_SC_X(GETUID, 119) \ + PPM_SC_X(GETGID, 120) \ + PPM_SC_X(GETEUID, 121) \ + PPM_SC_X(GETEGID, 122) \ + PPM_SC_X(SETREUID, 123) \ + PPM_SC_X(SETREGID, 124) \ + PPM_SC_X(GETGROUPS, 125) \ + PPM_SC_X(SETGROUPS, 126) \ + PPM_SC_X(FCHOWN, 127) \ + PPM_SC_X(SETRESUID, 128) \ + PPM_SC_X(GETRESUID, 129) \ + PPM_SC_X(SETRESGID, 130) \ + PPM_SC_X(GETRESGID, 131) \ + PPM_SC_X(CHOWN, 132) \ + PPM_SC_X(SETUID, 133) \ + PPM_SC_X(SETGID, 134) \ + PPM_SC_X(SETFSUID, 135) \ + PPM_SC_X(SETFSGID, 136) \ + PPM_SC_X(PIVOT_ROOT, 137) \ + PPM_SC_X(MINCORE, 138) \ + PPM_SC_X(MADVISE, 139) \ + PPM_SC_X(GETTID, 140) \ + PPM_SC_X(SETXATTR, 141) \ + PPM_SC_X(LSETXATTR, 142) \ + PPM_SC_X(FSETXATTR, 143) \ + PPM_SC_X(GETXATTR, 144) \ + PPM_SC_X(LGETXATTR, 145) \ + PPM_SC_X(FGETXATTR, 146) \ + PPM_SC_X(LISTXATTR, 147) \ + PPM_SC_X(LLISTXATTR, 148) \ + PPM_SC_X(FLISTXATTR, 149) \ + PPM_SC_X(REMOVEXATTR, 150) \ + PPM_SC_X(LREMOVEXATTR, 151) \ + PPM_SC_X(FREMOVEXATTR, 152) \ + PPM_SC_X(TKILL, 153) \ + PPM_SC_X(FUTEX, 154) \ + PPM_SC_X(SCHED_SETAFFINITY, 155) \ + PPM_SC_X(SCHED_GETAFFINITY, 156) \ + PPM_SC_X(SET_THREAD_AREA, 157) \ + PPM_SC_X(GET_THREAD_AREA, 158) \ + PPM_SC_X(IO_SETUP, 159) \ + PPM_SC_X(IO_DESTROY, 160) \ + PPM_SC_X(IO_GETEVENTS, 161) \ + PPM_SC_X(IO_SUBMIT, 162) \ + PPM_SC_X(IO_CANCEL, 163) \ + PPM_SC_X(EXIT_GROUP, 164) \ + PPM_SC_X(EPOLL_CREATE, 165) \ + PPM_SC_X(EPOLL_CTL, 166) \ + PPM_SC_X(EPOLL_WAIT, 167) \ + PPM_SC_X(REMAP_FILE_PAGES, 168) \ + PPM_SC_X(SET_TID_ADDRESS, 169) \ + PPM_SC_X(TIMER_CREATE, 170) \ + PPM_SC_X(TIMER_SETTIME, 171) \ + PPM_SC_X(TIMER_GETTIME, 172) \ + PPM_SC_X(TIMER_GETOVERRUN, 173) \ + PPM_SC_X(TIMER_DELETE, 174) \ + PPM_SC_X(CLOCK_SETTIME, 175) \ + PPM_SC_X(CLOCK_GETTIME, 176) \ + PPM_SC_X(CLOCK_GETRES, 177) \ + PPM_SC_X(CLOCK_NANOSLEEP, 178) \ + PPM_SC_X(TGKILL, 179) \ + PPM_SC_X(UTIMES, 180) \ + PPM_SC_X(MQ_OPEN, 181) \ + PPM_SC_X(MQ_UNLINK, 182) \ + PPM_SC_X(MQ_TIMEDSEND, 183) \ + PPM_SC_X(MQ_TIMEDRECEIVE, 184) \ + PPM_SC_X(MQ_NOTIFY, 185) \ + PPM_SC_X(MQ_GETSETATTR, 186) \ + PPM_SC_X(KEXEC_LOAD, 187) \ + PPM_SC_X(WAITID, 188) \ + PPM_SC_X(ADD_KEY, 189) \ + PPM_SC_X(REQUEST_KEY, 190) \ + PPM_SC_X(KEYCTL, 191) \ + PPM_SC_X(IOPRIO_SET, 192) \ + PPM_SC_X(IOPRIO_GET, 193) \ + PPM_SC_X(INOTIFY_INIT, 194) \ + PPM_SC_X(INOTIFY_ADD_WATCH, 195) \ + PPM_SC_X(INOTIFY_RM_WATCH, 196) \ + PPM_SC_X(OPENAT, 197) \ + PPM_SC_X(MKDIRAT, 198) \ + PPM_SC_X(MKNODAT, 199) \ + PPM_SC_X(FCHOWNAT, 200) \ + PPM_SC_X(FUTIMESAT, 201) \ + PPM_SC_X(UNLINKAT, 202) \ + PPM_SC_X(RENAMEAT, 203) \ + PPM_SC_X(LINKAT, 204) \ + PPM_SC_X(SYMLINKAT, 205) \ + PPM_SC_X(READLINKAT, 206) \ + PPM_SC_X(FCHMODAT, 207) \ + PPM_SC_X(FACCESSAT, 208) \ + PPM_SC_X(PSELECT6, 209) \ + PPM_SC_X(PPOLL, 210) \ + PPM_SC_X(UNSHARE, 211) \ + PPM_SC_X(SET_ROBUST_LIST, 212) \ + PPM_SC_X(GET_ROBUST_LIST, 213) \ + PPM_SC_X(SPLICE, 214) \ + PPM_SC_X(TEE, 215) \ + PPM_SC_X(VMSPLICE, 216) \ + PPM_SC_X(GETCPU, 217) \ + PPM_SC_X(EPOLL_PWAIT, 218) \ + PPM_SC_X(UTIMENSAT, 219) \ + PPM_SC_X(SIGNALFD, 220) \ + PPM_SC_X(TIMERFD_CREATE, 221) \ + PPM_SC_X(EVENTFD, 222) \ + PPM_SC_X(TIMERFD_SETTIME, 223) \ + PPM_SC_X(TIMERFD_GETTIME, 224) \ + PPM_SC_X(SIGNALFD4, 225) \ + PPM_SC_X(EVENTFD2, 226) \ + PPM_SC_X(EPOLL_CREATE1, 227) \ + PPM_SC_X(DUP3, 228) \ + PPM_SC_X(PIPE2, 229) \ + PPM_SC_X(INOTIFY_INIT1, 230) \ + PPM_SC_X(PREADV, 231) \ + PPM_SC_X(PWRITEV, 232) \ + PPM_SC_X(RT_TGSIGQUEUEINFO, 233) \ + PPM_SC_X(PERF_EVENT_OPEN, 234) \ + PPM_SC_X(FANOTIFY_INIT, 235) \ + PPM_SC_X(PRLIMIT64, 236) \ + PPM_SC_X(CLOCK_ADJTIME, 237) \ + PPM_SC_X(SYNCFS, 238) \ + PPM_SC_X(SETNS, 239) \ + PPM_SC_X(GETDENTS64, 240) \ + PPM_SC_X(SOCKET, 241) \ + PPM_SC_X(BIND, 242) \ + PPM_SC_X(CONNECT, 243) \ + PPM_SC_X(LISTEN, 244) \ + PPM_SC_X(ACCEPT, 245) \ + PPM_SC_X(GETSOCKNAME, 246) \ + PPM_SC_X(GETPEERNAME, 247) \ + PPM_SC_X(SOCKETPAIR, 248) \ + PPM_SC_X(SENDTO, 249) \ + PPM_SC_X(RECVFROM, 250) \ + PPM_SC_X(SHUTDOWN, 251) \ + PPM_SC_X(SETSOCKOPT, 252) \ + PPM_SC_X(GETSOCKOPT, 253) \ + PPM_SC_X(SENDMSG, 254) \ + PPM_SC_X(SENDMMSG, 255) \ + PPM_SC_X(RECVMSG, 256) \ + PPM_SC_X(RECVMMSG, 257) \ + PPM_SC_X(ACCEPT4, 258) \ + PPM_SC_X(SEMOP, 259) \ + PPM_SC_X(SEMGET, 260) \ + PPM_SC_X(SEMCTL, 261) \ + PPM_SC_X(MSGSND, 262) \ + PPM_SC_X(MSGRCV, 263) \ + PPM_SC_X(MSGGET, 264) \ + PPM_SC_X(MSGCTL, 265) \ + PPM_SC_X(SHMDT, 266) \ + PPM_SC_X(SHMGET, 267) \ + PPM_SC_X(SHMCTL, 268) \ + PPM_SC_X(STATFS64, 269) \ + PPM_SC_X(FSTATFS64, 270) \ + PPM_SC_X(FSTATAT64, 271) \ + PPM_SC_X(SENDFILE64, 272) \ + PPM_SC_X(UGETRLIMIT, 273) \ + PPM_SC_X(BDFLUSH, 274) \ + PPM_SC_X(SIGPROCMASK, 275) \ + PPM_SC_X(IPC, 276) \ + PPM_SC_X(SOCKETCALL, 277) \ + PPM_SC_X(STAT64, 278) \ + PPM_SC_X(LSTAT64, 279) \ + PPM_SC_X(FSTAT64, 280) \ + PPM_SC_X(FCNTL64, 281) \ + PPM_SC_X(MMAP2, 282) \ + PPM_SC_X(_NEWSELECT, 283) \ + PPM_SC_X(SGETMASK, 284) \ + PPM_SC_X(SSETMASK, 285) \ + PPM_SC_X(SIGPENDING, 286) \ + PPM_SC_X(OLDUNAME, 287) \ + PPM_SC_X(UMOUNT, 288) \ + PPM_SC_X(SIGNAL, 289) \ + PPM_SC_X(NICE, 290) \ + PPM_SC_X(STIME, 291) \ + PPM_SC_X(_LLSEEK, 292) \ + PPM_SC_X(WAITPID, 293) \ + PPM_SC_X(PREAD64, 294) \ + PPM_SC_X(PWRITE64, 295) \ + PPM_SC_X(ARCH_PRCTL, 296) \ + PPM_SC_X(SHMAT, 297) \ + PPM_SC_X(RT_SIGRETURN, 298) \ + PPM_SC_X(FALLOCATE, 299) \ + PPM_SC_X(NEWFSTATAT, 300) \ + PPM_SC_X(PROCESS_VM_READV, 301) \ + PPM_SC_X(PROCESS_VM_WRITEV, 302) \ + PPM_SC_X(FORK, 303) \ + PPM_SC_X(VFORK, 304) \ + PPM_SC_X(SETUID32, 305) \ + PPM_SC_X(GETUID32, 306) \ + PPM_SC_X(SETGID32, 307) \ + PPM_SC_X(GETEUID32, 308) \ + PPM_SC_X(GETGID32, 309) \ + PPM_SC_X(SETRESUID32, 310) \ + PPM_SC_X(SETRESGID32, 311) \ + PPM_SC_X(GETRESUID32, 312) \ + PPM_SC_X(GETRESGID32, 313) \ + PPM_SC_X(FINIT_MODULE, 314) \ + PPM_SC_X(BPF, 315) \ + PPM_SC_X(SECCOMP, 316) \ + PPM_SC_X(SIGALTSTACK, 317) \ + PPM_SC_X(GETRANDOM, 318) \ + PPM_SC_X(FADVISE64, 319) \ + PPM_SC_X(RENAMEAT2, 320) \ + PPM_SC_X(USERFAULTFD, 321) \ + PPM_SC_X(OPENAT2, 322) \ + PPM_SC_X(UMOUNT2, 323) \ + PPM_SC_X(EXECVE, 324) \ + PPM_SC_X(EXECVEAT, 325) \ + PPM_SC_X(COPY_FILE_RANGE, 326) \ + PPM_SC_X(CLONE, 327) \ + PPM_SC_X(CLONE3, 328) \ + PPM_SC_X(OPEN_BY_HANDLE_AT, 329) \ + PPM_SC_X(IO_URING_SETUP, 330) \ + PPM_SC_X(IO_URING_ENTER, 331) \ + PPM_SC_X(IO_URING_REGISTER, 332) \ + PPM_SC_X(MLOCK2, 333) \ + PPM_SC_X(GETEGID32, 334) \ + PPM_SC_X(FSCONFIG, 335) \ + PPM_SC_X(FSPICK, 336) \ + PPM_SC_X(FSMOUNT, 337) \ + PPM_SC_X(FSOPEN, 338) \ + PPM_SC_X(OPEN_TREE, 339) \ + PPM_SC_X(MOVE_MOUNT, 340) \ + PPM_SC_X(MOUNT_SETATTR, 341) \ + PPM_SC_X(MEMFD_CREATE, 342) \ + PPM_SC_X(MEMFD_SECRET, 343) \ + PPM_SC_X(IOPERM, 344) \ + PPM_SC_X(KEXEC_FILE_LOAD, 345) \ + PPM_SC_X(PIDFD_GETFD, 346) \ + PPM_SC_X(PIDFD_OPEN, 347) \ + PPM_SC_X(PIDFD_SEND_SIGNAL, 348) \ + PPM_SC_X(PKEY_ALLOC, 349) \ + PPM_SC_X(PKEY_MPROTECT, 350) \ + PPM_SC_X(PKEY_FREE, 351) \ PPM_SC_X(LANDLOCK_CREATE_RULESET, 352) \ - PPM_SC_X(QUOTACTL_FD, 353) \ - PPM_SC_X(LANDLOCK_RESTRICT_SELF, 354) \ - PPM_SC_X(LANDLOCK_ADD_RULE, 355) \ - PPM_SC_X(EPOLL_PWAIT2, 356) \ - PPM_SC_X(MIGRATE_PAGES, 357) \ - PPM_SC_X(MOVE_PAGES, 358) \ - PPM_SC_X(PREADV2, 359) \ - PPM_SC_X(PWRITEV2, 360) \ - PPM_SC_X(KCMP, 361) \ - PPM_SC_X(SCHED_SETATTR, 362) \ - PPM_SC_X(MBIND, 363) \ - PPM_SC_X(EPOLL_CTL_OLD, 364) \ - PPM_SC_X(LOOKUP_DCOOKIE, 365) \ - PPM_SC_X(MODIFY_LDT, 366) \ - PPM_SC_X(STATX, 367) \ - PPM_SC_X(SET_MEMPOLICY, 368) \ - PPM_SC_X(IO_PGETEVENTS, 369) \ + PPM_SC_X(QUOTACTL_FD, 353) \ + PPM_SC_X(LANDLOCK_RESTRICT_SELF, 354) \ + PPM_SC_X(LANDLOCK_ADD_RULE, 355) \ + PPM_SC_X(EPOLL_PWAIT2, 356) \ + PPM_SC_X(MIGRATE_PAGES, 357) \ + PPM_SC_X(MOVE_PAGES, 358) \ + PPM_SC_X(PREADV2, 359) \ + PPM_SC_X(PWRITEV2, 360) \ + PPM_SC_X(KCMP, 361) \ + PPM_SC_X(SCHED_SETATTR, 362) \ + PPM_SC_X(MBIND, 363) \ + PPM_SC_X(EPOLL_CTL_OLD, 364) \ + PPM_SC_X(LOOKUP_DCOOKIE, 365) \ + PPM_SC_X(MODIFY_LDT, 366) \ + PPM_SC_X(STATX, 367) \ + PPM_SC_X(SET_MEMPOLICY, 368) \ + PPM_SC_X(IO_PGETEVENTS, 369) \ PPM_SC_X(SET_MEMPOLICY_HOME_NODE, 370) \ - PPM_SC_X(SEMTIMEDOP, 371) \ - PPM_SC_X(GET_KERNEL_SYMS, 372) \ - PPM_SC_X(READAHEAD, 373) \ - PPM_SC_X(FUTEX_WAITV, 374) \ - PPM_SC_X(GETPMSG, 375) \ - PPM_SC_X(NAME_TO_HANDLE_AT, 376) \ - PPM_SC_X(PROCESS_MRELEASE, 377) \ - PPM_SC_X(NFSSERVCTL, 378) \ - PPM_SC_X(EPOLL_WAIT_OLD, 379) \ - PPM_SC_X(RSEQ, 380) \ - PPM_SC_X(CREATE_MODULE, 381) \ - /*PPM_SC_X(NA_1, 382)*/ \ - PPM_SC_X(SCHED_GETATTR, 383) \ - PPM_SC_X(FACCESSAT2, 384) \ - PPM_SC_X(_SYSCTL, 385) \ - PPM_SC_X(QUERY_MODULE, 386) \ - PPM_SC_X(GET_MEMPOLICY, 387) \ - PPM_SC_X(SYNC_FILE_RANGE, 388) \ - PPM_SC_X(PROCESS_MADVISE, 389) \ - PPM_SC_X(MEMBARRIER, 390) \ - PPM_SC_X(IOPL, 391) \ - PPM_SC_X(CLOSE_RANGE, 392) \ - PPM_SC_X(FANOTIFY_MARK, 393) \ - PPM_SC_X(RECV, 394) \ - PPM_SC_X(SEND, 395) \ - PPM_SC_X(SCHED_PROCESS_EXIT, 396) \ - PPM_SC_X(SCHED_SWITCH, 397) \ - PPM_SC_X(PAGE_FAULT_USER, 398) \ - PPM_SC_X(PAGE_FAULT_KERNEL, 399) \ - PPM_SC_X(SIGNAL_DELIVER, 400) \ - PPM_SC_X(TIMERFD, 401) \ - PPM_SC_X(S390_PCI_MMIO_READ, 402) \ - PPM_SC_X(SIGACTION, 403) \ - PPM_SC_X(S390_PCI_MMIO_WRITE, 404) \ - PPM_SC_X(READDIR, 405) \ - PPM_SC_X(S390_STHYI, 406) \ - PPM_SC_X(SIGSUSPEND, 407) \ - PPM_SC_X(IDLE, 408) \ - PPM_SC_X(S390_RUNTIME_INSTR, 409) \ - PPM_SC_X(SIGRETURN, 410) \ - PPM_SC_X(S390_GUARDED_STORAGE, 411) \ - PPM_SC_X(CACHESTAT, 412) \ - PPM_SC_X(FCHMODAT2, 413) \ - PPM_SC_X(MAP_SHADOW_STACK, 414) \ - PPM_SC_X(RISCV_FLUSH_ICACHE, 415) \ - PPM_SC_X(RISCV_HWPROBE, 416) \ - PPM_SC_X(FUTEX_WAKE, 417) \ - PPM_SC_X(FUTEX_REQUEUE, 418) \ - PPM_SC_X(FUTEX_WAIT, 419) \ - PPM_SC_X(OLDSTAT, 420) \ - PPM_SC_X(SWITCH_ENDIAN, 421) \ - PPM_SC_X(MULTIPLEXER, 422) \ - PPM_SC_X(OLDLSTAT, 423) \ - PPM_SC_X(SPU_CREATE, 424) \ - PPM_SC_X(SYNC_FILE_RANGE2, 425) \ - PPM_SC_X(OLDFSTAT, 426) \ - PPM_SC_X(SPU_RUN, 427) \ - PPM_SC_X(SWAPCONTEXT, 428) \ - PPM_SC_X(PCICONFIG_WRITE, 429) \ - PPM_SC_X(RTAS, 430) \ - PPM_SC_X(PCICONFIG_READ, 431) \ - PPM_SC_X(SYS_DEBUG_SETCONTEXT, 432) \ - PPM_SC_X(VM86, 433) \ - PPM_SC_X(OLDOLDUNAME, 434) \ - PPM_SC_X(SUBPAGE_PROT, 435) \ - PPM_SC_X(PCICONFIG_IOBASE, 436) \ - PPM_SC_X(LISTMOUNT, 437) \ - PPM_SC_X(STATMOUNT, 438) \ - PPM_SC_X(LSM_GET_SELF_ATTR, 439) \ - PPM_SC_X(LSM_SET_SELF_ATTR, 440) \ - PPM_SC_X(LSM_LIST_MODULES, 441) \ - PPM_SC_X(MSEAL, 442) \ + PPM_SC_X(SEMTIMEDOP, 371) \ + PPM_SC_X(GET_KERNEL_SYMS, 372) \ + PPM_SC_X(READAHEAD, 373) \ + PPM_SC_X(FUTEX_WAITV, 374) \ + PPM_SC_X(GETPMSG, 375) \ + PPM_SC_X(NAME_TO_HANDLE_AT, 376) \ + PPM_SC_X(PROCESS_MRELEASE, 377) \ + PPM_SC_X(NFSSERVCTL, 378) \ + PPM_SC_X(EPOLL_WAIT_OLD, 379) \ + PPM_SC_X(RSEQ, 380) \ + PPM_SC_X(CREATE_MODULE, 381) \ + /*PPM_SC_X(NA_1, 382)*/ \ + PPM_SC_X(SCHED_GETATTR, 383) \ + PPM_SC_X(FACCESSAT2, 384) \ + PPM_SC_X(_SYSCTL, 385) \ + PPM_SC_X(QUERY_MODULE, 386) \ + PPM_SC_X(GET_MEMPOLICY, 387) \ + PPM_SC_X(SYNC_FILE_RANGE, 388) \ + PPM_SC_X(PROCESS_MADVISE, 389) \ + PPM_SC_X(MEMBARRIER, 390) \ + PPM_SC_X(IOPL, 391) \ + PPM_SC_X(CLOSE_RANGE, 392) \ + PPM_SC_X(FANOTIFY_MARK, 393) \ + PPM_SC_X(RECV, 394) \ + PPM_SC_X(SEND, 395) \ + PPM_SC_X(SCHED_PROCESS_EXIT, 396) \ + PPM_SC_X(SCHED_SWITCH, 397) \ + PPM_SC_X(PAGE_FAULT_USER, 398) \ + PPM_SC_X(PAGE_FAULT_KERNEL, 399) \ + PPM_SC_X(SIGNAL_DELIVER, 400) \ + PPM_SC_X(TIMERFD, 401) \ + PPM_SC_X(S390_PCI_MMIO_READ, 402) \ + PPM_SC_X(SIGACTION, 403) \ + PPM_SC_X(S390_PCI_MMIO_WRITE, 404) \ + PPM_SC_X(READDIR, 405) \ + PPM_SC_X(S390_STHYI, 406) \ + PPM_SC_X(SIGSUSPEND, 407) \ + PPM_SC_X(IDLE, 408) \ + PPM_SC_X(S390_RUNTIME_INSTR, 409) \ + PPM_SC_X(SIGRETURN, 410) \ + PPM_SC_X(S390_GUARDED_STORAGE, 411) \ + PPM_SC_X(CACHESTAT, 412) \ + PPM_SC_X(FCHMODAT2, 413) \ + PPM_SC_X(MAP_SHADOW_STACK, 414) \ + PPM_SC_X(RISCV_FLUSH_ICACHE, 415) \ + PPM_SC_X(RISCV_HWPROBE, 416) \ + PPM_SC_X(FUTEX_WAKE, 417) \ + PPM_SC_X(FUTEX_REQUEUE, 418) \ + PPM_SC_X(FUTEX_WAIT, 419) \ + PPM_SC_X(OLDSTAT, 420) \ + PPM_SC_X(SWITCH_ENDIAN, 421) \ + PPM_SC_X(MULTIPLEXER, 422) \ + PPM_SC_X(OLDLSTAT, 423) \ + PPM_SC_X(SPU_CREATE, 424) \ + PPM_SC_X(SYNC_FILE_RANGE2, 425) \ + PPM_SC_X(OLDFSTAT, 426) \ + PPM_SC_X(SPU_RUN, 427) \ + PPM_SC_X(SWAPCONTEXT, 428) \ + PPM_SC_X(PCICONFIG_WRITE, 429) \ + PPM_SC_X(RTAS, 430) \ + PPM_SC_X(PCICONFIG_READ, 431) \ + PPM_SC_X(SYS_DEBUG_SETCONTEXT, 432) \ + PPM_SC_X(VM86, 433) \ + PPM_SC_X(OLDOLDUNAME, 434) \ + PPM_SC_X(SUBPAGE_PROT, 435) \ + PPM_SC_X(PCICONFIG_IOBASE, 436) \ + PPM_SC_X(LISTMOUNT, 437) \ + PPM_SC_X(STATMOUNT, 438) \ + PPM_SC_X(LSM_GET_SELF_ATTR, 439) \ + PPM_SC_X(LSM_SET_SELF_ATTR, 440) \ + PPM_SC_X(LSM_LIST_MODULES, 441) \ + PPM_SC_X(MSEAL, 442) \ PPM_SC_X(URETPROBE, 443) typedef enum { #define PPM_SC_X(name, value) PPM_SC_##name = (value), PPM_SC_FIELDS #undef PPM_SC_X - PPM_SC_MAX, + PPM_SC_MAX, } ppm_sc_code; /* * Event information enums */ enum ppm_event_category { - EC_UNKNOWN = 0, /* Unknown event created just to fill the pair ENTER/EXIT */ - EC_OTHER = 1, /* No specific category */ - EC_FILE = 2, /* File operation (open, close...) or file I/O */ - EC_NET = 3, /* Network operation (socket, bind...) or network I/O */ - EC_IPC = 4, /* IPC operation (pipe, futex...) or IPC I/O (e.g. on a pipe) */ - EC_MEMORY = 5, /* Memory-related operation (e.g. brk) */ - EC_PROCESS = 6, /* Process-related operation (fork, clone...) */ - EC_SLEEP = 7, /* Plain sleep */ - EC_SYSTEM = 8, /* System-related operations (e.g. reboot) */ - EC_SIGNAL = 9, /* Signal-related operations (e.g. signal) */ - EC_USER = 10, /* User-related operations (e.g. getuid) */ - EC_TIME = 11, /* Time-related syscalls (e.g. gettimeofday) */ - EC_PROCESSING = 12, /* User level processing. Never used for system calls */ - EC_IO_BASE = 32,/* used for masking */ - EC_IO_READ = 32,/* General I/O read (can be file, socket, IPC...) */ - EC_IO_WRITE = 33,/* General I/O write (can be file, socket, IPC...) */ - EC_IO_OTHER = 34,/* General I/O that is neither read not write (can be file, socket, IPC...) */ - EC_WAIT = (1 << 6), /* General wait (can be file, socket, IPC...) */ - EC_SCHEDULER = (1 << 7), /* Scheduler event (e.g. context switch) */ - EC_INTERNAL = (1 << 8), /* Internal event generated by the libraries and not by drivers */ - EC_SYSCALL = (1 << 9), /* Event generated by a syscall */ - EC_TRACEPOINT = (1 << 10), /* Event generated by a tracepoint */ - EC_PLUGIN = (1 << 11), /* Event generated by a plugin */ - EC_METAEVENT = (1 << 12), /* Meta-event not generated by a source but used for notifications or enrichment */ + EC_UNKNOWN = 0, /* Unknown event created just to fill the pair ENTER/EXIT */ + EC_OTHER = 1, /* No specific category */ + EC_FILE = 2, /* File operation (open, close...) or file I/O */ + EC_NET = 3, /* Network operation (socket, bind...) or network I/O */ + EC_IPC = 4, /* IPC operation (pipe, futex...) or IPC I/O (e.g. on a pipe) */ + EC_MEMORY = 5, /* Memory-related operation (e.g. brk) */ + EC_PROCESS = 6, /* Process-related operation (fork, clone...) */ + EC_SLEEP = 7, /* Plain sleep */ + EC_SYSTEM = 8, /* System-related operations (e.g. reboot) */ + EC_SIGNAL = 9, /* Signal-related operations (e.g. signal) */ + EC_USER = 10, /* User-related operations (e.g. getuid) */ + EC_TIME = 11, /* Time-related syscalls (e.g. gettimeofday) */ + EC_PROCESSING = 12, /* User level processing. Never used for system calls */ + EC_IO_BASE = 32, /* used for masking */ + EC_IO_READ = 32, /* General I/O read (can be file, socket, IPC...) */ + EC_IO_WRITE = 33, /* General I/O write (can be file, socket, IPC...) */ + EC_IO_OTHER = 34, /* General I/O that is neither read not write (can be file, socket, IPC...) */ + EC_WAIT = (1 << 6), /* General wait (can be file, socket, IPC...) */ + EC_SCHEDULER = (1 << 7), /* Scheduler event (e.g. context switch) */ + EC_INTERNAL = (1 << 8), /* Internal event generated by the libraries and not by drivers */ + EC_SYSCALL = (1 << 9), /* Event generated by a syscall */ + EC_TRACEPOINT = (1 << 10), /* Event generated by a tracepoint */ + EC_PLUGIN = (1 << 11), /* Event generated by a plugin */ + EC_METAEVENT = (1 << 12), /* Meta-event not generated by a source but used for notifications or + enrichment */ }; enum ppm_event_flags { EF_NONE = 0, - EF_CREATES_FD = (1 << 0), /* This event creates an FD (e.g. open). NOTE: a parser MUST always be created when this flag is set, to parse fd and add it to threadinfo list of fds */ - EF_DESTROYS_FD = (1 << 1), /* This event destroys an FD (e.g. close). NOTE: a parser MUST always be created when this flag is set, to parse fd and erasing it from threadinfo list (using sinsp_parser::erase_fd) */ - EF_USES_FD = (1 << 2), /* This event operates on an FD. */ - EF_READS_FROM_FD = (1 << 3), /* This event reads data from an FD. */ - EF_WRITES_TO_FD = (1 << 4), /* This event writes data to an FD. */ - EF_MODIFIES_STATE = (1 << 5), /* This event causes the machine state to change and should not be dropped by the filtering engine. */ - EF_UNUSED = (1 << 6), /* This event is not used */ - EF_WAITS = (1 << 7), /* This event reads data from an FD. */ - EF_SKIPPARSERESET = (1 << 8), /* This event shouldn't pollute the parser lastevent state tracker. */ + EF_CREATES_FD = + (1 << 0), /* This event creates an FD (e.g. open). NOTE: a parser MUST always be created + when this flag is set, to parse fd and add it to threadinfo list of fds */ + EF_DESTROYS_FD = (1 << 1), /* This event destroys an FD (e.g. close). NOTE: a parser MUST always + be created when this flag is set, to parse fd and erasing it from + threadinfo list (using sinsp_parser::erase_fd) */ + EF_USES_FD = (1 << 2), /* This event operates on an FD. */ + EF_READS_FROM_FD = (1 << 3), /* This event reads data from an FD. */ + EF_WRITES_TO_FD = (1 << 4), /* This event writes data to an FD. */ + EF_MODIFIES_STATE = (1 << 5), /* This event causes the machine state to change and should not be + dropped by the filtering engine. */ + EF_UNUSED = (1 << 6), /* This event is not used */ + EF_WAITS = (1 << 7), /* This event reads data from an FD. */ + EF_SKIPPARSERESET = + (1 << 8), /* This event shouldn't pollute the parser lastevent state tracker. */ EF_OLD_VERSION = (1 << 9), /* This event is kept for backward compatibility */ - // EF_DROP_SIMPLE_CONS = (1 << 10), /* This event can be skipped by consumers that privilege low overhead to full event capture */ SUPPORT DROPPED - EF_LARGE_PAYLOAD = (1 << 11), /* This event has a large payload, ie: up to UINT32_MAX bytes. DO NOT USE ON syscalls-driven events!!! */ + // EF_DROP_SIMPLE_CONS = (1 << 10), /* This event can be skipped by consumers that privilege low + // overhead to full event capture */ SUPPORT DROPPED + EF_LARGE_PAYLOAD = (1 << 11), /* This event has a large payload, ie: up to UINT32_MAX bytes. DO + NOT USE ON syscalls-driven events!!! */ }; /* @@ -2054,55 +2074,65 @@ enum ppm_param_type { PT_UINT16 = 6, PT_UINT32 = 7, PT_UINT64 = 8, - PT_CHARBUF = 9, /* A printable buffer of bytes, NULL terminated */ - PT_BYTEBUF = 10, /* A raw buffer of bytes not suitable for printing */ - PT_ERRNO = 11, /* this is an INT64, but will be interpreted as an error code */ - PT_SOCKADDR = 12, /* A sockaddr structure, 1byte family + data */ + PT_CHARBUF = 9, /* A printable buffer of bytes, NULL terminated */ + PT_BYTEBUF = 10, /* A raw buffer of bytes not suitable for printing */ + PT_ERRNO = 11, /* this is an INT64, but will be interpreted as an error code */ + PT_SOCKADDR = 12, /* A sockaddr structure, 1byte family + data */ PT_SOCKTUPLE = 13, /* A sockaddr tuple,1byte family + 12byte data + 12byte data */ - PT_FD = 14, /* An fd, 64bit */ - PT_PID = 15, /* A pid/tid, 64bit */ - PT_FDLIST = 16, /* A list of fds, 16bit count + count * (64bit fd + 16bit flags) */ - PT_FSPATH = 17, /* A string containing a relative or absolute file system path, null terminated */ - PT_SYSCALLID = 18, /* A 16bit system call ID. Can be used as a key for the g_ppm_sc_names table. */ + PT_FD = 14, /* An fd, 64bit */ + PT_PID = 15, /* A pid/tid, 64bit */ + PT_FDLIST = 16, /* A list of fds, 16bit count + count * (64bit fd + 16bit flags) */ + PT_FSPATH = + 17, /* A string containing a relative or absolute file system path, null terminated */ + PT_SYSCALLID = + 18, /* A 16bit system call ID. Can be used as a key for the g_ppm_sc_names table. */ PT_SIGTYPE = 19, /* An 8bit signal number */ PT_RELTIME = 20, /* A relative time. Seconds * 10^9 + nanoseconds. 64bit. */ - PT_ABSTIME = 21, /* An absolute time interval. Seconds from epoch * 10^9 + nanoseconds. 64bit. */ + PT_ABSTIME = + 21, /* An absolute time interval. Seconds from epoch * 10^9 + nanoseconds. 64bit. */ PT_PORT = 22, /* A TCP/UDP prt. 2 bytes. */ - PT_L4PROTO = 23, /* A 1 byte IP protocol type. */ + PT_L4PROTO = 23, /* A 1 byte IP protocol type. */ PT_SOCKFAMILY = 24, /* A 1 byte socket family. */ - PT_BOOL = 25, /* A boolean value, 4 bytes. */ - PT_IPV4ADDR = 26, /* A 4 byte raw IPv4 address. */ - PT_DYN = 27, /* Type can vary depending on the context. Used for filter fields like evt.rawarg. */ - PT_FLAGS8 = 28, /* this is an UINT8, but will be interpreted as 8 bit flags. */ - PT_FLAGS16 = 29, /* this is an UINT16, but will be interpreted as 16 bit flags. */ - PT_FLAGS32 = 30, /* this is an UINT32, but will be interpreted as 32 bit flags. */ - PT_UID = 31, /* this is an UINT32, MAX_UINT32 will be interpreted as no value. */ - PT_GID = 32, /* this is an UINT32, MAX_UINT32 will be interpreted as no value. */ - PT_DOUBLE = 33, /* this is a double precision floating point number. */ - PT_SIGSET = 34, /* sigset_t. I only store the lower UINT32 of it */ - PT_CHARBUFARRAY = 35, /* Pointer to an array of strings, exported by the user events decoder. 64bit. For internal use only. */ - PT_CHARBUF_PAIR_ARRAY = 36, /* Pointer to an array of string pairs, exported by the user events decoder. 64bit. For internal use only. */ - PT_IPV4NET = 37, /* An IPv4 network. */ - PT_IPV6ADDR = 38, /* A 16 byte raw IPv6 address. */ - PT_IPV6NET = 39, /* An IPv6 network. */ - PT_IPADDR = 40, /* Either an IPv4 or IPv6 address. The length indicates which one it is. */ - PT_IPNET = 41, /* Either an IPv4 or IPv6 network. The length indicates which one it is. */ - PT_MODE = 42, /* a 32 bit bitmask to represent file modes. */ - PT_FSRELPATH = 43, /* A path relative to a dirfd. */ - PT_ENUMFLAGS8 = 44, /* this is an UINT8, but will be interpreted as an enum flag, ie: contiguous values flag. */ - PT_ENUMFLAGS16 = 45, /* this is an UINT16, but will be interpreted as an enum flag, ie: contiguous values flag. */ - PT_ENUMFLAGS32 = 46, /* this is an UINT32, but will be interpreted as an enum flag, ie: contiguous values flag. */ - PT_MAX = 47 /* array size */ + PT_BOOL = 25, /* A boolean value, 4 bytes. */ + PT_IPV4ADDR = 26, /* A 4 byte raw IPv4 address. */ + PT_DYN = 27, /* Type can vary depending on the context. Used for filter fields like evt.rawarg. + */ + PT_FLAGS8 = 28, /* this is an UINT8, but will be interpreted as 8 bit flags. */ + PT_FLAGS16 = 29, /* this is an UINT16, but will be interpreted as 16 bit flags. */ + PT_FLAGS32 = 30, /* this is an UINT32, but will be interpreted as 32 bit flags. */ + PT_UID = 31, /* this is an UINT32, MAX_UINT32 will be interpreted as no value. */ + PT_GID = 32, /* this is an UINT32, MAX_UINT32 will be interpreted as no value. */ + PT_DOUBLE = 33, /* this is a double precision floating point number. */ + PT_SIGSET = 34, /* sigset_t. I only store the lower UINT32 of it */ + PT_CHARBUFARRAY = 35, /* Pointer to an array of strings, exported by the user events decoder. + 64bit. For internal use only. */ + PT_CHARBUF_PAIR_ARRAY = 36, /* Pointer to an array of string pairs, exported by the user events + decoder. 64bit. For internal use only. */ + PT_IPV4NET = 37, /* An IPv4 network. */ + PT_IPV6ADDR = 38, /* A 16 byte raw IPv6 address. */ + PT_IPV6NET = 39, /* An IPv6 network. */ + PT_IPADDR = 40, /* Either an IPv4 or IPv6 address. The length indicates which one it is. */ + PT_IPNET = 41, /* Either an IPv4 or IPv6 network. The length indicates which one it is. */ + PT_MODE = 42, /* a 32 bit bitmask to represent file modes. */ + PT_FSRELPATH = 43, /* A path relative to a dirfd. */ + PT_ENUMFLAGS8 = 44, /* this is an UINT8, but will be interpreted as an enum flag, ie: contiguous + values flag. */ + PT_ENUMFLAGS16 = 45, /* this is an UINT16, but will be interpreted as an enum flag, ie: + contiguous values flag. */ + PT_ENUMFLAGS32 = 46, /* this is an UINT32, but will be interpreted as an enum flag, ie: + contiguous values flag. */ + PT_MAX = 47 /* array size */ }; enum ppm_print_format { PF_NA = 0, - PF_DEC = 1, /* decimal */ - PF_HEX = 2, /* hexadecimal */ - PF_10_PADDED_DEC = 3, /* decimal padded to 10 digits, useful to print the fractional part of a ns timestamp */ + PF_DEC = 1, /* decimal */ + PF_HEX = 2, /* hexadecimal */ + PF_10_PADDED_DEC = 3, /* decimal padded to 10 digits, useful to print the fractional part of a + ns timestamp */ PF_ID = 4, PF_DIR = 5, - PF_OCT = 6, /* octal */ + PF_OCT = 6, /* octal */ }; /*! @@ -2113,18 +2143,20 @@ struct ppm_name_value { uint32_t value; }; -#define DIRFD_PARAM(_param_num) ((void*)_param_num) +#define DIRFD_PARAM(_param_num) ((void *)_param_num) /*! \brief Event parameter information. */ struct ppm_param_info { - char name[PPM_MAX_NAME_LEN]; /**< Parameter name, e.g. 'size'. */ - enum ppm_param_type type; /**< Parameter type, e.g. 'uint16', 'string'... */ - enum ppm_print_format fmt; /**< If this is a numeric parameter, this flag specifies if it should be rendered as decimal or hex. */ - const void *info; /**< If this is a flags parameter, it points to an array of ppm_name_value, - if this is a FSRELPATH parameter, it references the related dirfd, - else if this is a dynamic parameter it points to an array of ppm_param_info */ + char name[PPM_MAX_NAME_LEN]; /**< Parameter name, e.g. 'size'. */ + enum ppm_param_type type; /**< Parameter type, e.g. 'uint16', 'string'... */ + enum ppm_print_format fmt; /**< If this is a numeric parameter, this flag specifies if it should + be rendered as decimal or hex. */ + const void + *info; /**< If this is a flags parameter, it points to an array of ppm_name_value, + if this is a FSRELPATH parameter, it references the related dirfd, + else if this is a dynamic parameter it points to an array of ppm_param_info */ uint8_t ninfo; /**< Number of entry in the info array. */ }; @@ -2134,10 +2166,10 @@ struct ppm_param_info { is supported by the infrastructure. */ struct ppm_event_info { - char name[PPM_MAX_NAME_LEN]; /**< Name. */ + char name[PPM_MAX_NAME_LEN]; /**< Name. */ enum ppm_event_category category; /**< Event category, e.g. 'file', 'net', etc. */ - enum ppm_event_flags flags; /**< flags for this event. */ - uint32_t nparams; /**< Number of parameter in the params array. */ + enum ppm_event_flags flags; /**< flags for this event. */ + uint32_t nparams; /**< Number of parameter in the params array. */ struct ppm_param_info params[PPM_MAX_EVENT_PARAMS]; /**< parameters descriptions. */ }; @@ -2151,10 +2183,10 @@ struct ppm_evt_hdr { #ifdef PPM_ENABLE_SENTINEL uint32_t sentinel_begin; #endif - uint64_t ts; /* timestamp, in nanoseconds from epoch */ - uint64_t tid; /* the tid of the thread that generated this event */ - uint32_t len; /* the event len, including the header */ - uint16_t type; /* the event type */ + uint64_t ts; /* timestamp, in nanoseconds from epoch */ + uint64_t tid; /* the tid of the thread that generated this event */ + uint32_t len; /* the event len, including the header */ + uint16_t type; /* the event type */ uint32_t nparams; /* the number of parameters of the event */ }; #pragma pack(pop) @@ -2162,7 +2194,7 @@ struct ppm_evt_hdr { /* * IOCTL codes */ -#define PPM_IOCTL_MAGIC 's' +#define PPM_IOCTL_MAGIC 's' // #define PPM_IOCTL_DISABLE_CAPTURE _IO(PPM_IOCTL_MAGIC, 0) Support dropped // #define PPM_IOCTL_ENABLE_CAPTURE _IO(PPM_IOCTL_MAGIC, 1) Support dropped #define PPM_IOCTL_DISABLE_DROPPING_MODE _IO(PPM_IOCTL_MAGIC, 2) @@ -2192,8 +2224,9 @@ struct ppm_evt_hdr { // #define PPM_IOCTL_MANAGE_TP _IO(PPM_IOCTL_MAGIC, 26) Support dropped // #define PPM_IOCTL_GET_TPMASK _IO(PPM_IOCTL_MAGIC, 27) Support dropped // #define PPM_IOCTL_ZERO_SYSCALLS _IO(PPM_IOCTL_MAGIC, 28) Support dropped -#define PPM_IOCTL_ENABLE_SYSCALL _IO(PPM_IOCTL_MAGIC, 29) // this replaces PPM_IOCTL_MASK_SET_EVENT -#define PPM_IOCTL_DISABLE_SYSCALL _IO(PPM_IOCTL_MAGIC, 30) // this replaces PPM_IOCTL_MASK_UNSET_EVENT +#define PPM_IOCTL_ENABLE_SYSCALL _IO(PPM_IOCTL_MAGIC, 29) // this replaces PPM_IOCTL_MASK_SET_EVENT +#define PPM_IOCTL_DISABLE_SYSCALL \ + _IO(PPM_IOCTL_MAGIC, 30) // this replaces PPM_IOCTL_MASK_UNSET_EVENT #define PPM_IOCTL_ENABLE_TP _IO(PPM_IOCTL_MAGIC, 31) #define PPM_IOCTL_DISABLE_TP _IO(PPM_IOCTL_MAGIC, 32) #define PPM_IOCTL_ENABLE_DROPFAILED _IO(PPM_IOCTL_MAGIC, 33) @@ -2274,8 +2307,9 @@ enum syscall_flags { UF_USED = (1 << 0), UF_NEVER_DROP = (1 << 1), UF_ALWAYS_DROP = (1 << 2), - // UF_SIMPLEDRIVER_KEEP = (1 << 3), ///< Mark a syscall to be kept in simpledriver mode, see scap_enable_simpledriver_mode() -> SUPPORT DROPPED - UF_ATOMIC = (1 << 4), ///< The handler should not block (interrupt context) + // UF_SIMPLEDRIVER_KEEP = (1 << 3), ///< Mark a syscall to be kept in simpledriver mode, see + // scap_enable_simpledriver_mode() -> SUPPORT DROPPED + UF_ATOMIC = (1 << 4), ///< The handler should not block (interrupt context) }; struct syscall_evt_pair { @@ -2320,7 +2354,7 @@ enum autofill_paramtype { APT_SOCK, }; -typedef int (*filler_callback_t) (struct event_filler_arguments *args); +typedef int (*filler_callback_t)(struct event_filler_arguments *args); struct ppm_event_entry { filler_callback_t filler_callback; @@ -2333,10 +2367,10 @@ struct ppm_event_entry { /* * parse_readv_writev_bufs flags */ -#define PRB_FLAG_PUSH_SIZE 1 -#define PRB_FLAG_PUSH_DATA 2 -#define PRB_FLAG_PUSH_ALL (PRB_FLAG_PUSH_SIZE | PRB_FLAG_PUSH_DATA) -#define PRB_FLAG_IS_WRITE 4 +#define PRB_FLAG_PUSH_SIZE 1 +#define PRB_FLAG_PUSH_DATA 2 +#define PRB_FLAG_PUSH_ALL (PRB_FLAG_PUSH_SIZE | PRB_FLAG_PUSH_DATA) +#define PRB_FLAG_IS_WRITE 4 /* * Return codes @@ -2346,6 +2380,7 @@ struct ppm_event_entry { #define PPM_FAILURE_INVALID_USER_MEMORY -2 #define PPM_FAILURE_BUG -3 #define PPM_SKIP_EVENT -4 -#define PPM_FAILURE_FRAME_SCRATCH_MAP_FULL -5 /* this is used only inside bpf, kernel module does not have a frame scratch map*/ +#define PPM_FAILURE_FRAME_SCRATCH_MAP_FULL \ + -5 /* this is used only inside bpf, kernel module does not have a frame scratch map*/ #endif /* EVENTS_PUBLIC_H_ */ diff --git a/driver/ppm_fillers.c b/driver/ppm_fillers.c index 169f9af8f4..bb83eb05a0 100644 --- a/driver/ppm_fillers.c +++ b/driver/ppm_fillers.c @@ -7,7 +7,7 @@ This file is dual licensed under either the MIT or GPL 2. See MIT.txt or GPL2.txt for full copies of the license. */ -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include #include @@ -67,9 +67,8 @@ struct ovl_entry { static enum ppm_overlay ppm_get_overlay_layer(struct file *file); -static inline struct pid_namespace *pid_ns_for_children(struct task_struct *task) -{ -#if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 11, 0)) +static inline struct pid_namespace *pid_ns_for_children(struct task_struct *task) { +#if(LINUX_VERSION_CODE < KERNEL_VERSION(3, 11, 0)) return task->nsproxy->pid_ns; #else return task->nsproxy->pid_ns_for_children; @@ -83,29 +82,24 @@ static inline struct pid_namespace *pid_ns_for_children(struct task_struct *task * inode object and other file attributes. * **/ -static inline uint32_t get_exe_from_memfd(const struct file *exe_file) -{ +static inline uint32_t get_exe_from_memfd(const struct file *exe_file) { #if defined(CONFIG_MEMFD_CREATE) && CONFIG_MEMFD_CREATE == 1 const char expected_prefix[] = "memfd:"; - if(!(exe_file && - exe_file->f_path.dentry && - exe_file->f_path.dentry == exe_file->f_path.dentry->d_parent)) - { + if(!(exe_file && exe_file->f_path.dentry && + exe_file->f_path.dentry == exe_file->f_path.dentry->d_parent)) { return 0; } - if(strncmp(exe_file->f_path.dentry->d_name.name, expected_prefix, sizeof(expected_prefix) - 1) == 0) - { - return PPM_EXE_FROM_MEMFD; - - } + if(strncmp(exe_file->f_path.dentry->d_name.name, + expected_prefix, + sizeof(expected_prefix) - 1) == 0) { + return PPM_EXE_FROM_MEMFD; + } #endif return 0; } - -int f_sys_generic(struct event_filler_arguments *args) -{ +int f_sys_generic(struct event_filler_arguments *args) { int res; long table_index = args->syscall_id - SYSCALL_TABLE_ID0; @@ -113,8 +107,7 @@ int f_sys_generic(struct event_filler_arguments *args) * name */ - if (likely(table_index >= 0 && - table_index < SYSCALL_TABLE_SIZE)) { + if(likely(table_index >= 0 && table_index < SYSCALL_TABLE_SIZE)) { ppm_sc_code sc_code = g_syscall_table[table_index].ppm_sc; /* @@ -123,7 +116,7 @@ int f_sys_generic(struct event_filler_arguments *args) res = val_to_ring(args, sc_code, 0, false, 0); CHECK_RES(res); - if (args->event_type == PPME_GENERIC_E) { + if(args->event_type == PPME_GENERIC_E) { /* * nativeID */ @@ -132,20 +125,18 @@ int f_sys_generic(struct event_filler_arguments *args) } } else { ASSERT(false); - res = val_to_ring(args, (uint64_t)"", 0, false, 0); + res = val_to_ring(args, (uint64_t) "", 0, false, 0); CHECK_RES(res); } return add_sentinel(args); } -int f_sys_empty(struct event_filler_arguments *args) -{ +int f_sys_empty(struct event_filler_arguments *args) { return add_sentinel(args); } -int f_sys_single(struct event_filler_arguments *args) -{ +int f_sys_single(struct event_filler_arguments *args) { int res; unsigned long val; @@ -156,8 +147,7 @@ int f_sys_single(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_single_x(struct event_filler_arguments *args) -{ +int f_sys_single_x(struct event_filler_arguments *args) { int res; int64_t retval; @@ -168,8 +158,7 @@ int f_sys_single_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fstat_e(struct event_filler_arguments *args) -{ +int f_sys_fstat_e(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; int32_t fd = 0; @@ -183,31 +172,30 @@ int f_sys_fstat_e(struct event_filler_arguments *args) return add_sentinel(args); } -static inline void get_ino_from_fd(int64_t fd, uint64_t* ino) -{ +static inline void get_ino_from_fd(int64_t fd, uint64_t *ino) { struct files_struct *files; struct fdtable *fdt; struct inode *inode; struct file *file; - if (fd < 0) + if(fd < 0) return; files = current->files; - if (unlikely(!files)) + if(unlikely(!files)) return; spin_lock(&files->file_lock); fdt = files_fdtable(files); - if (unlikely(fd > fdt->max_fds)) + if(unlikely(fd > fdt->max_fds)) goto out_unlock; file = fdt->fd[fd]; - if (unlikely(!file)) + if(unlikely(!file)) goto out_unlock; inode = file_inode(file); - if (unlikely(!inode)) + if(unlikely(!inode)) goto out_unlock; *ino = inode->i_ino; @@ -217,40 +205,42 @@ static inline void get_ino_from_fd(int64_t fd, uint64_t* ino) return; } -static inline void get_dev_ino_overlay_from_fd(int64_t fd, uint32_t* dev, uint64_t* ino, enum ppm_overlay *ol) -{ +static inline void get_dev_ino_overlay_from_fd(int64_t fd, + uint32_t *dev, + uint64_t *ino, + enum ppm_overlay *ol) { struct files_struct *files; struct fdtable *fdt; struct inode *inode; struct super_block *sb; struct file *file; - if (fd < 0) + if(fd < 0) return; files = current->files; - if (unlikely(!files)) + if(unlikely(!files)) return; spin_lock(&files->file_lock); fdt = files_fdtable(files); - if (unlikely(fd > fdt->max_fds)) + if(unlikely(fd > fdt->max_fds)) goto out_unlock; file = fdt->fd[fd]; - if (unlikely(!file)) + if(unlikely(!file)) goto out_unlock; *ol = ppm_get_overlay_layer(file); inode = file_inode(file); - if (unlikely(!inode)) + if(unlikely(!inode)) goto out_unlock; *ino = inode->i_ino; sb = inode->i_sb; - if (unlikely(!sb)) + if(unlikely(!sb)) goto out_unlock; *dev = new_encode_dev(sb->s_dev); @@ -260,31 +250,30 @@ static inline void get_dev_ino_overlay_from_fd(int64_t fd, uint32_t* dev, uint64 return; } -static inline void get_fd_fmode_created(int64_t fd, unsigned long* flags) -{ +static inline void get_fd_fmode_created(int64_t fd, unsigned long *flags) { /* FMODE_CREATED flag was introduced in kernel 4.19 and it's not present in earlier versions */ #if LINUX_VERSION_CODE > KERNEL_VERSION(4, 19, 0) struct files_struct *files; struct fdtable *fdt; struct file *file; - if (fd < 0) + if(fd < 0) return; files = current->files; - if (unlikely(!files)) + if(unlikely(!files)) return; spin_lock(&files->file_lock); fdt = files_fdtable(files); - if (unlikely(fd > fdt->max_fds)) + if(unlikely(fd > fdt->max_fds)) goto out_unlock; file = fdt->fd[fd]; - if (unlikely(!file)) + if(unlikely(!file)) goto out_unlock; - if (file->f_mode & FMODE_CREATED) + if(file->f_mode & FMODE_CREATED) *flags |= PPM_O_F_CREATED; out_unlock: @@ -293,8 +282,7 @@ static inline void get_fd_fmode_created(int64_t fd, unsigned long* flags) return; } -int f_sys_open_e(struct event_filler_arguments *args) -{ +int f_sys_open_e(struct event_filler_arguments *args) { unsigned long val; unsigned long flags; unsigned long modes; @@ -309,7 +297,8 @@ int f_sys_open_e(struct event_filler_arguments *args) /* * Flags - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ syscall_get_arguments_deprecated(args, 1, 1, &flags); res = val_to_ring(args, open_flags_to_scap(flags), 0, false, 0); @@ -325,8 +314,7 @@ int f_sys_open_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_open_x(struct event_filler_arguments *args) -{ +int f_sys_open_x(struct event_filler_arguments *args) { unsigned long val; unsigned long flags; unsigned long scap_flags; @@ -344,7 +332,6 @@ int f_sys_open_x(struct event_filler_arguments *args) res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - /* * name */ @@ -356,18 +343,16 @@ int f_sys_open_x(struct event_filler_arguments *args) /* * Flags - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ syscall_get_arguments_deprecated(args, 1, 1, &flags); scap_flags = open_flags_to_scap(flags); /* update scap flags if file is created */ get_fd_fmode_created(retval, &scap_flags); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { scap_flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { scap_flags |= PPM_FD_LOWER_LAYER; } res = val_to_ring(args, scap_flags, 0, false, 0); @@ -395,8 +380,7 @@ int f_sys_open_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_read_e(struct event_filler_arguments *args) -{ +int f_sys_read_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -415,8 +399,7 @@ int f_sys_read_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_read_x(struct event_filler_arguments *args) -{ +int f_sys_read_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -438,7 +421,7 @@ int f_sys_read_x(struct event_filler_arguments *args) /* * data */ - if (retval < 0) { + if(retval < 0) { /* * The operation failed, return an empty buffer */ @@ -464,8 +447,7 @@ int f_sys_read_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_write_e(struct event_filler_arguments *args) -{ +int f_sys_write_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -484,8 +466,7 @@ int f_sys_write_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_write_x(struct event_filler_arguments *args) -{ +int f_sys_write_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -518,8 +499,7 @@ int f_sys_write_x(struct event_filler_arguments *args) /* * get_mm_exe_file is only exported in some kernel versions */ -static struct file *ppm_get_mm_exe_file(struct mm_struct *mm) -{ +static struct file *ppm_get_mm_exe_file(struct mm_struct *mm) { struct file *exe_file; /* @@ -532,7 +512,7 @@ static struct file *ppm_get_mm_exe_file(struct mm_struct *mm) #if defined(get_file_rcu) rcu_read_lock(); exe_file = rcu_dereference(mm->exe_file); - if (exe_file && !get_file_rcu(exe_file)) + if(exe_file && !get_file_rcu(exe_file)) exe_file = NULL; rcu_read_unlock(); #elif LINUX_VERSION_CODE >= KERNEL_VERSION(6, 7, 0) @@ -546,7 +526,7 @@ static struct file *ppm_get_mm_exe_file(struct mm_struct *mm) * VM_EXECUTABLE vmas */ down_read(&mm->mmap_sem); exe_file = mm->exe_file; - if (exe_file) + if(exe_file) get_file(exe_file); up_read(&mm->mmap_sem); #endif @@ -559,8 +539,7 @@ static struct file *ppm_get_mm_exe_file(struct mm_struct *mm) * https://github.com/torvalds/linux/commit/69c978232aaa99476f9bd002c2a29a84fa3779b5 * Hence the crap in these two functions */ -static unsigned long ppm_get_mm_counter(struct mm_struct *mm, int member) -{ +static unsigned long ppm_get_mm_counter(struct mm_struct *mm, int member) { long val = 0; #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 4, 0) @@ -568,28 +547,25 @@ static unsigned long ppm_get_mm_counter(struct mm_struct *mm, int member) #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 34) val = atomic_long_read(&mm->rss_stat.count[member]); - if (val < 0) + if(val < 0) val = 0; #endif return val; } -static unsigned long ppm_get_mm_swap(struct mm_struct *mm) -{ +static unsigned long ppm_get_mm_swap(struct mm_struct *mm) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 34) return ppm_get_mm_counter(mm, MM_SWAPENTS); #endif return 0; } -static unsigned long ppm_get_mm_rss(struct mm_struct *mm) -{ +static unsigned long ppm_get_mm_rss(struct mm_struct *mm) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 4, 0) return get_mm_rss(mm); #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 34) - return ppm_get_mm_counter(mm, MM_FILEPAGES) + - ppm_get_mm_counter(mm, MM_ANONPAGES); + return ppm_get_mm_counter(mm, MM_FILEPAGES) + ppm_get_mm_counter(mm, MM_ANONPAGES); #else return get_mm_rss(mm); #endif @@ -598,12 +574,11 @@ static unsigned long ppm_get_mm_rss(struct mm_struct *mm) #ifdef CONFIG_CGROUPS #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 34) -static int ppm_cgroup_path(const struct cgroup *cgrp, char *buf, int buflen) -{ +static int ppm_cgroup_path(const struct cgroup *cgrp, char *buf, int buflen) { char *start; struct dentry *dentry = rcu_dereference(cgrp->dentry); - if (!dentry) { + if(!dentry) { /* * Inactive subsystems have no dentry for their root * cgroup @@ -615,20 +590,20 @@ static int ppm_cgroup_path(const struct cgroup *cgrp, char *buf, int buflen) start = buf + buflen; *--start = '\0'; - for (;;) { + for(;;) { int len = dentry->d_name.len; start -= len; - if (start < buf) + if(start < buf) return -ENAMETOOLONG; memcpy(start, cgrp->dentry->d_name.name, len); cgrp = cgrp->parent; - if (!cgrp) + if(!cgrp) break; dentry = rcu_dereference(cgrp->dentry); - if (!cgrp->parent) + if(!cgrp->parent) continue; - if (--start < buf) + if(--start < buf) return -ENAMETOOLONG; *start = '/'; } @@ -637,8 +612,7 @@ static int ppm_cgroup_path(const struct cgroup *cgrp, char *buf, int buflen) } #endif -static int append_cgroup(const char *subsys_name, int subsys_id, char *buf, int *available) -{ +static int append_cgroup(const char *subsys_name, int subsys_id, char *buf, int *available) { int pathlen; int subsys_len; char *path; @@ -653,21 +627,22 @@ static int append_cgroup(const char *subsys_name, int subsys_id, char *buf, int struct cgroup_subsys_state *css = task_subsys_state(current, subsys_id); #endif - if (!css) { + if(!css) { ASSERT(false); return 1; } - if (!css->cgroup) { + if(!css->cgroup) { ASSERT(false); return 1; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 9, 0) - // According to https://github.com/torvalds/linux/commit/4c737b41de7f4eef2a593803bad1b918dd718b10 - // cgroup_path now returns an int again + // According to + // https://github.com/torvalds/linux/commit/4c737b41de7f4eef2a593803bad1b918dd718b10 cgroup_path + // now returns an int again res = cgroup_path(css->cgroup, buf, *available); - if (res < 0) { + if(res < 0) { ASSERT(false); path = "NA"; } else { @@ -675,13 +650,13 @@ static int append_cgroup(const char *subsys_name, int subsys_id, char *buf, int } #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 15, 0) path = cgroup_path(css->cgroup, buf, *available); - if (!path) { + if(!path) { ASSERT(false); path = "NA"; } #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 34) res = cgroup_path(css->cgroup, buf, *available); - if (res < 0) { + if(res < 0) { ASSERT(false); path = "NA"; } else { @@ -689,7 +664,7 @@ static int append_cgroup(const char *subsys_name, int subsys_id, char *buf, int } #else res = ppm_cgroup_path(css->cgroup, buf, *available); - if (res < 0) { + if(res < 0) { ASSERT(false); path = "NA"; } else { @@ -699,7 +674,7 @@ static int append_cgroup(const char *subsys_name, int subsys_id, char *buf, int pathlen = strlen(path); subsys_len = strlen(subsys_name); - if (subsys_len + 1 + pathlen + 1 > *available) + if(subsys_len + 1 + pathlen + 1 > *available) return 1; memmove(buf + subsys_len + 1, path, pathlen); @@ -713,23 +688,35 @@ static int append_cgroup(const char *subsys_name, int subsys_id, char *buf, int } #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 15, 0) -#define SUBSYS(_x) \ -if (append_cgroup(#_x, _x ## _cgrp_id, args->str_storage + STR_STORAGE_SIZE - available, &available)) \ - goto cgroups_error; +#define SUBSYS(_x) \ + if(append_cgroup(#_x, \ + _x##_cgrp_id, \ + args->str_storage + STR_STORAGE_SIZE - available, \ + &available)) \ + goto cgroups_error; #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 10, 0) #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option) -#define SUBSYS(_x) \ -if (append_cgroup(#_x, _x ## _subsys_id, args->str_storage + STR_STORAGE_SIZE - available, &available)) \ - goto cgroups_error; +#define SUBSYS(_x) \ + if(append_cgroup(#_x, \ + _x##_subsys_id, \ + args->str_storage + STR_STORAGE_SIZE - available, \ + &available)) \ + goto cgroups_error; #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 7, 0) #define IS_SUBSYS_ENABLED(option) IS_ENABLED(option) -#define SUBSYS(_x) \ -if (append_cgroup(#_x, _x ## _subsys_id, args->str_storage + STR_STORAGE_SIZE - available, &available)) \ - goto cgroups_error; +#define SUBSYS(_x) \ + if(append_cgroup(#_x, \ + _x##_subsys_id, \ + args->str_storage + STR_STORAGE_SIZE - available, \ + &available)) \ + goto cgroups_error; #else -#define SUBSYS(_x) \ -if (append_cgroup(#_x, _x ## _subsys_id, args->str_storage + STR_STORAGE_SIZE - available, &available)) \ - goto cgroups_error; +#define SUBSYS(_x) \ + if(append_cgroup(#_x, \ + _x##_subsys_id, \ + args->str_storage + STR_STORAGE_SIZE - available, \ + &available)) \ + goto cgroups_error; #endif #endif @@ -738,31 +725,26 @@ if (append_cgroup(#_x, _x ## _subsys_id, args->str_storage + STR_STORAGE_SIZE - * concatenates them to a single \0-separated string. Return the length of these * strings with the final '\0' included. */ -static int accumulate_argv_or_env(const void __user * argv, char *str_storage) -{ +static int accumulate_argv_or_env(const void __user *argv, char *str_storage) { int len = 0; int ret = 0; - const char __user * p = NULL; - - for (;;) { + const char __user *p = NULL; - if (argv == NULL) + for(;;) { + if(argv == NULL) break; - if (unlikely(ppm_get_user(p, argv))) - { + if(unlikely(ppm_get_user(p, argv))) { /* We return what we read until now */ break; } - if (p == NULL) + if(p == NULL) break; /* ppm_strncpy_from_user includes the trailing \0 */ - ret = ppm_strncpy_from_user(&str_storage[len], p, - STR_STORAGE_SIZE-len); - if(ret < 0) - { + ret = ppm_strncpy_from_user(&str_storage[len], p, STR_STORAGE_SIZE - len); + if(ret < 0) { /* We ignore the failed read. We will try to read from the same position in * the next iteration. */ @@ -770,8 +752,7 @@ static int accumulate_argv_or_env(const void __user * argv, char *str_storage) } len += ret; - if(len >= STR_STORAGE_SIZE) - { + if(len >= STR_STORAGE_SIZE) { len = STR_STORAGE_SIZE; break; } @@ -779,12 +760,9 @@ static int accumulate_argv_or_env(const void __user * argv, char *str_storage) argv += sizeof(argv); } - if(len>0) - { - str_storage[len-1] = '\0'; - } - else - { + if(len > 0) { + str_storage[len - 1] = '\0'; + } else { str_storage[0] = '\0'; } return len; @@ -792,32 +770,27 @@ static int accumulate_argv_or_env(const void __user * argv, char *str_storage) #ifdef CONFIG_COMPAT /* compat version that deals correctly with 32bits pointers of argv */ -static int compat_accumulate_argv_or_env(compat_uptr_t argv, - char *str_storage) -{ +static int compat_accumulate_argv_or_env(compat_uptr_t argv, char *str_storage) { int len = 0; int ret = 0; const char __user *p = NULL; - for (;;) { + for(;;) { compat_uptr_t compat_p = 0; - if (compat_ptr(argv) == NULL) + if(compat_ptr(argv) == NULL) break; - if (unlikely(ppm_get_user(compat_p, compat_ptr(argv)))) - { + if(unlikely(ppm_get_user(compat_p, compat_ptr(argv)))) { /* We return what we read until now */ break; } p = compat_ptr(compat_p); - if (p == NULL) + if(p == NULL) break; /* ppm_strncpy_from_user includes the trailing \0 */ - ret = ppm_strncpy_from_user(&str_storage[len], p, - STR_STORAGE_SIZE-len); - if(ret < 0) - { + ret = ppm_strncpy_from_user(&str_storage[len], p, STR_STORAGE_SIZE - len); + if(ret < 0) { /* We ignore the failed read. We will try to read from the same position in * the next iteration. */ @@ -825,8 +798,7 @@ static int compat_accumulate_argv_or_env(compat_uptr_t argv, } len += ret; - if(len >= STR_STORAGE_SIZE) - { + if(len >= STR_STORAGE_SIZE) { len = STR_STORAGE_SIZE; break; } @@ -834,20 +806,16 @@ static int compat_accumulate_argv_or_env(compat_uptr_t argv, argv += sizeof(argv); } - if(len>0) - { - str_storage[len-1] = '\0'; - } - else - { + if(len > 0) { + str_storage[len - 1] = '\0'; + } else { str_storage[0] = '\0'; } return len; } #endif -static uint32_t ppm_get_tty(void) -{ +static uint32_t ppm_get_tty(void) { /* Locking of the signal structures seems too complicated across * multiple kernel versions to get it right, so simply do protected * memory accesses, and in the worst case we get some garbage, @@ -863,28 +831,28 @@ static uint32_t ppm_get_tty(void) uint32_t tty_nr = 0; sig = current->signal; - if (!sig) + if(!sig) return 0; - if (unlikely(copy_from_kernel_nofault(&tty, &sig->tty, sizeof(tty)))) + if(unlikely(copy_from_kernel_nofault(&tty, &sig->tty, sizeof(tty)))) return 0; - if (!tty) + if(!tty) return 0; - if (unlikely(copy_from_kernel_nofault(&index, &tty->index, sizeof(index)))) + if(unlikely(copy_from_kernel_nofault(&index, &tty->index, sizeof(index)))) return 0; - if (unlikely(copy_from_kernel_nofault(&driver, &tty->driver, sizeof(driver)))) + if(unlikely(copy_from_kernel_nofault(&driver, &tty->driver, sizeof(driver)))) return 0; - if (!driver) + if(!driver) return 0; - if (unlikely(copy_from_kernel_nofault(&major, &driver->major, sizeof(major)))) + if(unlikely(copy_from_kernel_nofault(&major, &driver->major, sizeof(major)))) return 0; - if (unlikely(copy_from_kernel_nofault(&minor_start, &driver->minor_start, sizeof(minor_start)))) + if(unlikely(copy_from_kernel_nofault(&minor_start, &driver->minor_start, sizeof(minor_start)))) return 0; tty_nr = new_encode_dev(MKDEV(major, minor_start) + index); @@ -892,54 +860,47 @@ static uint32_t ppm_get_tty(void) return tty_nr; } -static enum ppm_overlay ppm_get_overlay_layer(struct file *file) -{ +static enum ppm_overlay ppm_get_overlay_layer(struct file *file) { // 3.18 is the Kernel version where overlayfs was introduced #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 18, 0) return PPM_NOT_OVERLAY_FS; -#else - struct dentry * dentry = NULL; - struct super_block* sb = NULL; +#else + struct dentry *dentry = NULL; + struct super_block *sb = NULL; struct dentry *upper_dentry = NULL; - struct inode * upper_ino = NULL; - - if(!file) - { + struct inode *upper_ino = NULL; + + if(!file) { return PPM_NOT_OVERLAY_FS; } dentry = file->f_path.dentry; - if(!dentry) - { + if(!dentry) { return PPM_NOT_OVERLAY_FS; } - + sb = dentry->d_sb; - if(!sb) - { + if(!sb) { return PPM_NOT_OVERLAY_FS; } - - if(sb->s_magic != PPM_OVERLAYFS_SUPER_MAGIC) - { + + if(sb->s_magic != PPM_OVERLAYFS_SUPER_MAGIC) { return PPM_NOT_OVERLAY_FS; } #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 13, 0) // New scope to avoid `ISO C90 forbids mixed declarations and code` error { - struct ovl_entry *oe = (struct ovl_entry*)(dentry->d_fsdata); - if(!oe) - { + struct ovl_entry *oe = (struct ovl_entry *)(dentry->d_fsdata); + if(!oe) { return PPM_OVERLAY_LOWER; } upper_dentry = oe->__upperdentry; } #else { - char *vfs_inode = (char*)dentry->d_inode; - if(!vfs_inode) - { + char *vfs_inode = (char *)dentry->d_inode; + if(!vfs_inode) { return PPM_OVERLAY_LOWER; } @@ -949,31 +910,27 @@ static enum ppm_overlay ppm_get_overlay_layer(struct file *file) // todo!: this is dangerous we should find a way to check it at compile time. upper_dentry = *(struct dentry **)(vfs_inode + sizeof(struct inode)); } -#endif // LINUX_VERSION_CODE < KERNEL_VERSION(4, 13, 0) - if(!upper_dentry) - { +#endif // LINUX_VERSION_CODE < KERNEL_VERSION(4, 13, 0) + if(!upper_dentry) { return PPM_OVERLAY_LOWER; } upper_ino = upper_dentry->d_inode; - if(!upper_ino) - { + if(!upper_ino) { return PPM_OVERLAY_LOWER; } - if(upper_ino->i_ino != 0) - { + if(upper_ino->i_ino != 0) { return PPM_OVERLAY_UPPER; } return PPM_OVERLAY_LOWER; -#endif // LINUX_VERSION_CODE < KERNEL_VERSION(3, 18, 0) +#endif // LINUX_VERSION_CODE < KERNEL_VERSION(3, 18, 0) } -int f_proc_startupdate(struct event_filler_arguments *args) -{ +int f_proc_startupdate(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; - unsigned int exe_len = 0; /* the length of the executable string */ - int args_len = 0; /*the combined length of the arguments string + executable string */ + unsigned int exe_len = 0; /* the length of the executable string */ + int args_len = 0; /*the combined length of the arguments string + executable string */ struct mm_struct *mm = current->mm; int64_t retval; int ptid; @@ -995,10 +952,8 @@ int f_proc_startupdate(struct event_filler_arguments *args) res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - if (unlikely(retval < 0 && - args->event_type != PPME_SYSCALL_EXECVE_19_X && - args->event_type != PPME_SYSCALL_EXECVEAT_X)) { - + if(unlikely(retval < 0 && args->event_type != PPME_SYSCALL_EXECVE_19_X && + args->event_type != PPME_SYSCALL_EXECVEAT_X)) { /* The call failed, but this syscall has no exe, args * anyway, so I report empty ones */ *args->str_storage = 0; @@ -1015,21 +970,20 @@ int f_proc_startupdate(struct event_filler_arguments *args) res = val_to_ring(args, (int64_t)(long)args->str_storage, 0, false, 0); CHECK_RES(res); } else { - - if (likely(retval >= 0)) { + if(likely(retval >= 0)) { /* * The call succeeded. Get exe, args from the current * process; put one \0-separated exe-args string into * str_storage */ - if (unlikely(!mm)) { + if(unlikely(!mm)) { args->str_storage[0] = 0; pr_info("f_proc_startupdate drop, mm=NULL\n"); return PPM_FAILURE_BUG; } - if (unlikely(!mm->arg_end)) { + if(unlikely(!mm->arg_end)) { args->str_storage[0] = 0; pr_info("f_proc_startupdate drop, mm->arg_end=NULL\n"); return PPM_FAILURE_BUG; @@ -1037,17 +991,18 @@ int f_proc_startupdate(struct event_filler_arguments *args) args_len = mm->arg_end - mm->arg_start; - if (args_len) { - if (args_len > STR_STORAGE_SIZE) + if(args_len) { + if(args_len > STR_STORAGE_SIZE) args_len = STR_STORAGE_SIZE; - if (unlikely(ppm_copy_from_user(args->str_storage, (const void __user *)mm->arg_start, args_len))) + if(unlikely(ppm_copy_from_user(args->str_storage, + (const void __user *)mm->arg_start, + args_len))) args_len = 0; else args->str_storage[args_len - 1] = 0; } } else { - /* * The execve or execveat call failed. We get exe, args from the * input args; put one \0-separated exe-args string into @@ -1055,8 +1010,7 @@ int f_proc_startupdate(struct event_filler_arguments *args) */ args->str_storage[0] = 0; - switch (args->event_type) - { + switch(args->event_type) { case PPME_SYSCALL_EXECVE_19_X: syscall_get_arguments_deprecated(args, 1, 1, &val); break; @@ -1070,21 +1024,19 @@ int f_proc_startupdate(struct event_filler_arguments *args) break; } #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) - args_len = compat_accumulate_argv_or_env((compat_uptr_t)val, - args->str_storage); + if(unlikely(args->compat)) + args_len = compat_accumulate_argv_or_env((compat_uptr_t)val, args->str_storage); else #endif - args_len = accumulate_argv_or_env((const char __user *)val, - args->str_storage); + args_len = accumulate_argv_or_env((const char __user *)val, args->str_storage); } - if (args_len == 0) + if(args_len == 0) *args->str_storage = 0; exe_len = strnlen(args->str_storage, args_len); // we add the `\0` terminator - if (exe_len < args_len) + if(exe_len < args_len) ++exe_len; /* @@ -1096,11 +1048,14 @@ int f_proc_startupdate(struct event_filler_arguments *args) /* * Args */ - res = val_to_ring(args, (int64_t)(long)args->str_storage + exe_len, args_len - exe_len, false, 0); + res = val_to_ring(args, + (int64_t)(long)args->str_storage + exe_len, + args_len - exe_len, + false, + 0); CHECK_RES(res); } - /* * tid */ @@ -1117,10 +1072,10 @@ int f_proc_startupdate(struct event_filler_arguments *args) * ptid */ #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20) - if (current->real_parent) + if(current->real_parent) ptid = current->real_parent->pid; #else - if (current->parent) + if(current->parent) ptid = current->parent->pid; #endif else @@ -1158,10 +1113,10 @@ int f_proc_startupdate(struct event_filler_arguments *args) res = val_to_ring(args, current->min_flt, 0, false, 0); CHECK_RES(res); - if (mm) { - total_vm = mm->total_vm << (PAGE_SHIFT-10); - total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT-10); - swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT-10); + if(mm) { + total_vm = mm->total_vm << (PAGE_SHIFT - 10); + total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT - 10); + swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT - 10); } /* @@ -1199,14 +1154,15 @@ int f_proc_startupdate(struct event_filler_arguments *args) rcu_read_unlock(); #endif - res = val_to_ring(args, (int64_t)(long)args->str_storage, STR_STORAGE_SIZE - available, false, 0); + res = val_to_ring(args, + (int64_t)(long)args->str_storage, + STR_STORAGE_SIZE - available, + false, + 0); CHECK_RES(res); - if (args->event_type == PPME_SYSCALL_CLONE_20_X || - args->event_type == PPME_SYSCALL_FORK_20_X || - args->event_type == PPME_SYSCALL_VFORK_20_X || - args->event_type == PPME_SYSCALL_CLONE3_X) - { + if(args->event_type == PPME_SYSCALL_CLONE_20_X || args->event_type == PPME_SYSCALL_FORK_20_X || + args->event_type == PPME_SYSCALL_VFORK_20_X || args->event_type == PPME_SYSCALL_CLONE3_X) { /* * clone-only parameters */ @@ -1228,8 +1184,7 @@ int f_proc_startupdate(struct event_filler_arguments *args) /* * flags */ - switch (args->event_type) - { + switch(args->event_type) { case PPME_SYSCALL_CLONE_20_X: #ifdef CONFIG_S390 syscall_get_arguments_deprecated(args, 1, 1, &val); @@ -1242,12 +1197,9 @@ int f_proc_startupdate(struct event_filler_arguments *args) #ifdef __NR_clone3 syscall_get_arguments_deprecated(args, 0, 1, &val); res = ppm_copy_from_user(&cl_args, (void *)val, sizeof(struct clone_args)); - if (unlikely(res != 0)) - { + if(unlikely(res != 0)) { val = 0; - } - else - { + } else { val = cl_args.flags; } #else @@ -1264,7 +1216,7 @@ int f_proc_startupdate(struct event_filler_arguments *args) if(pidns != &init_pid_ns || pid_ns_for_children(current) != pidns) in_pidns = PPM_CL_CHILD_IN_PIDNS; #endif - res = val_to_ring(args, (uint64_t)clone_flags_to_scap((int) val) | in_pidns, 0, false, 0); + res = val_to_ring(args, (uint64_t)clone_flags_to_scap((int)val) | in_pidns, 0, false, 0); CHECK_RES(res); /* @@ -1309,8 +1261,7 @@ int f_proc_startupdate(struct event_filler_arguments *args) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 17, 0) // only perform lookup when clone/vfork/fork returns 0 (child process / childtid) - if(retval == 0 && pidns && pidns->child_reaper) - { + if(retval == 0 && pidns && pidns->child_reaper) { pidns_init_start_time = pidns->child_reaper->start_time; } res = val_to_ring(args, pidns_init_start_time, 0, false, 0); @@ -1320,8 +1271,8 @@ int f_proc_startupdate(struct event_filler_arguments *args) #endif CHECK_RES(res); - } else if (args->event_type == PPME_SYSCALL_EXECVE_19_X || - args->event_type == PPME_SYSCALL_EXECVEAT_X) { + } else if(args->event_type == PPME_SYSCALL_EXECVE_19_X || + args->event_type == PPME_SYSCALL_EXECVEAT_X) { /* * execve family parameters. */ @@ -1330,7 +1281,7 @@ int f_proc_startupdate(struct event_filler_arguments *args) bool exe_writable = false; enum ppm_overlay exe_layer = PPM_NOT_OVERLAY_FS; struct file *exe_file = NULL; - uint32_t flags = 0; // execve additional flags + uint32_t flags = 0; // execve additional flags unsigned long i_ino = 0; unsigned long ctime = 0; unsigned long mtime = 0; @@ -1339,20 +1290,22 @@ int f_proc_startupdate(struct event_filler_arguments *args) uint64_t cap_permitted = 0; uint64_t cap_effective = 0; uint32_t euid = UINT32_MAX; - char* buf = (char*)args->str_storage; + char *buf = (char *)args->str_storage; char *trusted_exepath = NULL; - if (likely(retval >= 0)) { + if(likely(retval >= 0)) { /* * Already checked for mm validity */ env_len = mm->env_end - mm->env_start; - if (env_len) { - if (env_len > STR_STORAGE_SIZE) + if(env_len) { + if(env_len > STR_STORAGE_SIZE) env_len = STR_STORAGE_SIZE; - if (unlikely(ppm_copy_from_user(args->str_storage, (const void __user *)mm->env_start, env_len))) + if(unlikely(ppm_copy_from_user(args->str_storage, + (const void __user *)mm->env_start, + env_len))) env_len = 0; else args->str_storage[env_len - 1] = 0; @@ -1361,8 +1314,7 @@ int f_proc_startupdate(struct event_filler_arguments *args) /* * The call failed, so get the env from the arguments */ - switch (args->event_type) - { + switch(args->event_type) { case PPME_SYSCALL_EXECVE_19_X: syscall_get_arguments_deprecated(args, 2, 1, &val); break; @@ -1376,16 +1328,14 @@ int f_proc_startupdate(struct event_filler_arguments *args) break; } #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) - env_len = compat_accumulate_argv_or_env((compat_uptr_t)val, - args->str_storage); + if(unlikely(args->compat)) + env_len = compat_accumulate_argv_or_env((compat_uptr_t)val, args->str_storage); else #endif - env_len = accumulate_argv_or_env((const char __user *)val, - args->str_storage); + env_len = accumulate_argv_or_env((const char __user *)val, args->str_storage); } - if (env_len == 0) + if(env_len == 0) *args->str_storage = 0; /* @@ -1405,15 +1355,19 @@ int f_proc_startupdate(struct event_filler_arguments *args) * pgid */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24) - res = val_to_ring(args, (int64_t)task_pgrp_nr_ns(current, task_active_pid_ns(current)), 0, false, 0); + res = val_to_ring(args, + (int64_t)task_pgrp_nr_ns(current, task_active_pid_ns(current)), + 0, + false, + 0); #else res = val_to_ring(args, (int64_t)process_group(current), 0, false, 0); #endif CHECK_RES(res); /* - * loginuid - */ + * loginuid + */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0) loginuid = from_kuid(current_user_ns(), audit_get_loginuid(current)); #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25) @@ -1430,28 +1384,32 @@ int f_proc_startupdate(struct event_filler_arguments *args) exe_file = ppm_get_mm_exe_file(mm); - if (exe_file != NULL) { + if(exe_file != NULL) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 39) - if (file_inode(exe_file) != NULL) - { + if(file_inode(exe_file) != NULL) { /* Support exe_writable */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) exe_writable |= (file_permission(exe_file, MAY_WRITE | MAY_NOT_BLOCK) == 0); - exe_writable |= inode_owner_or_capable(file_mnt_idmap(exe_file), file_inode(exe_file)); + exe_writable |= + inode_owner_or_capable(file_mnt_idmap(exe_file), file_inode(exe_file)); #elif LINUX_VERSION_CODE >= KERNEL_VERSION(5, 12, 0) - exe_writable |= (inode_permission(current_user_ns(), file_inode(exe_file), MAY_WRITE | MAY_NOT_BLOCK) == 0); + exe_writable |= (inode_permission(current_user_ns(), + file_inode(exe_file), + MAY_WRITE | MAY_NOT_BLOCK) == 0); exe_writable |= inode_owner_or_capable(current_user_ns(), file_inode(exe_file)); #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 1, 0) - exe_writable |= (inode_permission(file_inode(exe_file), MAY_WRITE | MAY_NOT_BLOCK) == 0); + exe_writable |= + (inode_permission(file_inode(exe_file), MAY_WRITE | MAY_NOT_BLOCK) == 0); exe_writable |= inode_owner_or_capable(file_inode(exe_file)); #endif /* - * Kernels < 3.1.0 doesn't support the exe_writable flags due to the MAY_NOT_BLOCK not being - * available. This limitation is related to the fact that this function (f_sched_prog_exec) - * is in a RCU critical section: this means that this function (and its callee) MUST NOT - * call functions that can yield the processor (e.g. inode_permission that deep down in its - * call stack calls a down_read()). This is addressed after the Kernel 3.1.0 where the - * MAY_OT_BLOCK flag is introduced and avoids the processor to being yield. + * Kernels < 3.1.0 doesn't support the exe_writable flags due to the MAY_NOT_BLOCK + * not being available. This limitation is related to the fact that this function + * (f_sched_prog_exec) is in a RCU critical section: this means that this function + * (and its callee) MUST NOT call functions that can yield the processor (e.g. + * inode_permission that deep down in its call stack calls a down_read()). This is + * addressed after the Kernel 3.1.0 where the MAY_OT_BLOCK flag is introduced and + * avoids the processor to being yield. */ /* Support exe_upper_layer and exe_lower_layer */ @@ -1464,21 +1422,22 @@ int f_proc_startupdate(struct event_filler_arguments *args) i_ino = file_inode(exe_file)->i_ino; /* Support exe_file ctime - * During kernel versions `i_ctime` changed from `struct timespec` to `struct timespec64` - * but fields names should be always the same. + * During kernel versions `i_ctime` changed from `struct timespec` to `struct + * timespec64` but fields names should be always the same. */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 6, 0) { struct timespec64 inode_ctime; inode_ctime = inode_get_ctime(file_inode(exe_file)); - ctime = inode_ctime.tv_sec * (uint64_t) 1000000000 + inode_ctime.tv_nsec; + ctime = inode_ctime.tv_sec * (uint64_t)1000000000 + inode_ctime.tv_nsec; } #else - ctime = file_inode(exe_file)->i_ctime.tv_sec * (uint64_t) 1000000000 + file_inode(exe_file)->i_ctime.tv_nsec; + ctime = file_inode(exe_file)->i_ctime.tv_sec * (uint64_t)1000000000 + + file_inode(exe_file)->i_ctime.tv_nsec; #endif /* Support exe_file mtime - * During kernel versions `i_mtime` changed from `struct timespec` to `struct timespec64` - * but fields names should be always the same. + * During kernel versions `i_mtime` changed from `struct timespec` to `struct + * timespec64` but fields names should be always the same. */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 7, 0) { @@ -1487,7 +1446,8 @@ int f_proc_startupdate(struct event_filler_arguments *args) mtime = inode_mtime.tv_sec * (uint64_t)1000000000 + inode_mtime.tv_nsec; } #else - mtime = file_inode(exe_file)->i_mtime.tv_sec * (uint64_t) 1000000000 + file_inode(exe_file)->i_mtime.tv_nsec; + mtime = file_inode(exe_file)->i_mtime.tv_sec * (uint64_t)1000000000 + + file_inode(exe_file)->i_mtime.tv_nsec; #endif } #endif @@ -1500,25 +1460,22 @@ int f_proc_startupdate(struct event_filler_arguments *args) * https://github.com/torvalds/linux/blob/2dde18cd1d8fac735875f2e4987f11817cc0bc2c/fs/d_path.c#L255 * This is unhandy to manage in userspace, for this reason, we can remove it here */ - if(trusted_exepath != NULL) - { + if(trusted_exepath != NULL) { char deleted_suffix[] = " (deleted)"; int diff_len = strlen(trusted_exepath) - strlen(deleted_suffix); if(diff_len > 0 && - (strncmp(&trusted_exepath[diff_len], deleted_suffix, sizeof(deleted_suffix)) == 0)) - { + (strncmp(&trusted_exepath[diff_len], deleted_suffix, sizeof(deleted_suffix)) == 0)) { trusted_exepath[diff_len] = '\0'; } } - if (exe_writable) { + if(exe_writable) { flags |= PPM_EXE_WRITABLE; } - if (exe_layer == PPM_OVERLAY_UPPER) { + if(exe_layer == PPM_OVERLAY_UPPER) { flags |= PPM_EXE_UPPER_LAYER; - } - else if (exe_layer == PPM_OVERLAY_LOWER) { + } else if(exe_layer == PPM_OVERLAY_LOWER) { flags |= PPM_EXE_LOWER_LAYER; } @@ -1535,7 +1492,8 @@ int f_proc_startupdate(struct event_filler_arguments *args) */ cred = get_current_cred(); #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0) - cap_inheritable = ((uint64_t)cred->cap_inheritable.cap[1] << 32) | cred->cap_inheritable.cap[0]; + cap_inheritable = + ((uint64_t)cred->cap_inheritable.cap[1] << 32) | cred->cap_inheritable.cap[0]; cap_permitted = ((uint64_t)cred->cap_permitted.cap[1] << 32) | cred->cap_permitted.cap[0]; cap_effective = ((uint64_t)cred->cap_effective.cap[1] << 32) | cred->cap_effective.cap[0]; #else @@ -1565,11 +1523,13 @@ int f_proc_startupdate(struct event_filler_arguments *args) res = val_to_ring(args, i_ino, 0, false, 0); CHECK_RES(res); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ res = val_to_ring(args, ctime, 0, false, 0); CHECK_RES(res); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ res = val_to_ring(args, mtime, 0, false, 0); CHECK_RES(res); @@ -1591,8 +1551,7 @@ int f_proc_startupdate(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_execve_e(struct event_filler_arguments *args) -{ +int f_sys_execve_e(struct event_filler_arguments *args) { int res; unsigned long val; @@ -1606,8 +1565,7 @@ int f_sys_execve_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_execveat_e(struct event_filler_arguments *args) -{ +int f_sys_execveat_e(struct event_filler_arguments *args) { int res; unsigned long val; unsigned long flags; @@ -1618,8 +1576,7 @@ int f_sys_execveat_e(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) - { + if(fd == AT_FDCWD) { fd = PPM_AT_FDCWD; } @@ -1645,8 +1602,7 @@ int f_sys_execveat_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_socket_bind_e(struct event_filler_arguments *args) -{ +int f_sys_socket_bind_e(struct event_filler_arguments *args) { int res = 0; int32_t fd = 0; unsigned long val = 0; @@ -1661,8 +1617,7 @@ int f_sys_socket_bind_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_socket_bind_x(struct event_filler_arguments *args) -{ +int f_sys_socket_bind_x(struct event_filler_arguments *args) { int res; int64_t retval; int err = 0; @@ -1690,37 +1645,29 @@ int f_sys_socket_bind_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); - if (usrsockaddr != NULL && val != 0) { + if(usrsockaddr != NULL && val != 0) { /* * Copy the address */ err = addr_to_kernel(usrsockaddr, val, (struct sockaddr *)&address); - if (likely(err >= 0)) { + if(likely(err >= 0)) { /* * Convert the fd into socket endpoint information */ - size = pack_addr((struct sockaddr *)&address, - val, - targetbuf, - STR_STORAGE_SIZE); + size = pack_addr((struct sockaddr *)&address, val, targetbuf, STR_STORAGE_SIZE); } } /* * Copy the endpoint info into the ring */ - res = val_to_ring(args, - (uint64_t)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)targetbuf, size, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_connect_e(struct event_filler_arguments *args) -{ +int f_sys_connect_e(struct event_filler_arguments *args) { int res; int err = 0; int fd; @@ -1736,7 +1683,7 @@ int f_sys_connect_e(struct event_filler_arguments *args) res = val_to_ring(args, fd, 0, true, 0); CHECK_RES(res); - if (fd >= 0) { + if(fd >= 0) { /* * Get the address */ @@ -1749,19 +1696,16 @@ int f_sys_connect_e(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); - if (usrsockaddr != NULL && val != 0) { + if(usrsockaddr != NULL && val != 0) { /* - * Copy the address - */ + * Copy the address + */ err = addr_to_kernel(usrsockaddr, val, (struct sockaddr *)&address); - if (likely(err >= 0)) { + if(likely(err >= 0)) { /* - * Convert the fd into socket endpoint information - */ - size = pack_addr((struct sockaddr *)&address, - val, - targetbuf, - STR_STORAGE_SIZE); + * Convert the fd into socket endpoint information + */ + size = pack_addr((struct sockaddr *)&address, val, targetbuf, STR_STORAGE_SIZE); } } } @@ -1769,18 +1713,13 @@ int f_sys_connect_e(struct event_filler_arguments *args) /* * Copy the endpoint info into the ring */ - res = val_to_ring(args, - (uint64_t)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)targetbuf, size, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_connect_x(struct event_filler_arguments *args) -{ +int f_sys_connect_x(struct event_filler_arguments *args) { int res; int64_t retval; int err = 0; @@ -1805,7 +1744,7 @@ int f_sys_connect_x(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int)val; - if (fd >= 0) { + if(fd >= 0) { /* * Get the address */ @@ -1818,22 +1757,22 @@ int f_sys_connect_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); - if (usrsockaddr != NULL && val != 0) { + if(usrsockaddr != NULL && val != 0) { /* * Copy the address */ err = addr_to_kernel(usrsockaddr, val, (struct sockaddr *)&address); - if (likely(err >= 0)) { + if(likely(err >= 0)) { /* * Convert the fd into socket endpoint information */ size = fd_to_socktuple(fd, - (struct sockaddr *)&address, - val, - true, - false, - targetbuf, - STR_STORAGE_SIZE); + (struct sockaddr *)&address, + val, + true, + false, + targetbuf, + STR_STORAGE_SIZE); } } } @@ -1841,11 +1780,7 @@ int f_sys_connect_x(struct event_filler_arguments *args) /* * Copy the endpoint info into the ring */ - res = val_to_ring(args, - (uint64_t)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)targetbuf, size, false, 0); CHECK_RES(res); res = val_to_ring(args, fd, 0, false, 0); @@ -1854,8 +1789,7 @@ int f_sys_connect_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_socketpair_x(struct event_filler_arguments *args) -{ +int f_sys_socketpair_x(struct event_filler_arguments *args) { int res; int64_t retval; unsigned long val; @@ -1876,19 +1810,19 @@ int f_sys_socketpair_x(struct event_filler_arguments *args) /* * If the call was successful, copy the FDs */ - if (likely(retval == 0)) { + if(likely(retval == 0)) { /* * fds */ syscall_get_arguments_deprecated(args, 3, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(fds, (const void __user *)val, sizeof(fds)))) + if(unlikely(ppm_copy_from_user(fds, (const void __user *)val, sizeof(fds)))) return PPM_FAILURE_INVALID_USER_MEMORY; #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(fds, (const void __user *)compat_ptr(val), sizeof(fds)))) + if(unlikely(ppm_copy_from_user(fds, (const void __user *)compat_ptr(val), sizeof(fds)))) return PPM_FAILURE_INVALID_USER_MEMORY; } #endif @@ -1901,17 +1835,17 @@ int f_sys_socketpair_x(struct event_filler_arguments *args) /* get socket source and peer address */ sock = sockfd_lookup(fds[0], &err); - if (likely(sock != NULL)) { + if(likely(sock != NULL)) { us = unix_sk(sock->sk); speer = us->peer; res = val_to_ring(args, (unsigned long)us, 0, false, 0); - if (unlikely(res != PPM_SUCCESS)) { + if(unlikely(res != PPM_SUCCESS)) { sockfd_put(sock); return res; } res = val_to_ring(args, (unsigned long)speer, 0, false, 0); - if (unlikely(res != PPM_SUCCESS)) { + if(unlikely(res != PPM_SUCCESS)) { sockfd_put(sock); return res; } @@ -1937,201 +1871,206 @@ int f_sys_socketpair_x(struct event_filler_arguments *args) return add_sentinel(args); } -static int parse_sockopt(struct event_filler_arguments *args, int level, int optname, const void __user *optval, int optlen) -{ +static int parse_sockopt(struct event_filler_arguments *args, + int level, + int optname, + const void __user *optval, + int optlen) { int32_t val32 = 0; uint64_t val64 = 0; struct __aux_timeval tv = {0}; - if(level != SOL_SOCKET) - { + if(level != SOL_SOCKET) { return val_to_ring(args, (unsigned long)optval, optlen, true, PPM_SOCKOPT_IDX_UNKNOWN); } - switch (optname) { + switch(optname) { #ifdef SO_ERROR - case SO_ERROR: - /* in case of failure we have to clear again the value */ - if(unlikely(ppm_copy_from_user(&val32, optval, sizeof(val32)))) - { - val32 = 0; - } - return val_to_ring(args, (int64_t)-val32, 0, false, PPM_SOCKOPT_IDX_ERRNO); + case SO_ERROR: + /* in case of failure we have to clear again the value */ + if(unlikely(ppm_copy_from_user(&val32, optval, sizeof(val32)))) { + val32 = 0; + } + return val_to_ring(args, (int64_t)-val32, 0, false, PPM_SOCKOPT_IDX_ERRNO); #endif #ifdef SO_RCVTIMEO - case SO_RCVTIMEO: + case SO_RCVTIMEO: #endif -#if (defined(SO_RCVTIMEO_OLD) && !defined(SO_RCVTIMEO)) || (defined(SO_RCVTIMEO_OLD) && (SO_RCVTIMEO_OLD != SO_RCVTIMEO)) - case SO_RCVTIMEO_OLD: +#if(defined(SO_RCVTIMEO_OLD) && !defined(SO_RCVTIMEO)) || \ + (defined(SO_RCVTIMEO_OLD) && (SO_RCVTIMEO_OLD != SO_RCVTIMEO)) + case SO_RCVTIMEO_OLD: #endif -#if (defined(SO_RCVTIMEO_NEW) && !defined(SO_RCVTIMEO)) || (defined(SO_RCVTIMEO_NEW) && (SO_RCVTIMEO_NEW != SO_RCVTIMEO)) - case SO_RCVTIMEO_NEW: +#if(defined(SO_RCVTIMEO_NEW) && !defined(SO_RCVTIMEO)) || \ + (defined(SO_RCVTIMEO_NEW) && (SO_RCVTIMEO_NEW != SO_RCVTIMEO)) + case SO_RCVTIMEO_NEW: #endif #ifdef SO_SNDTIMEO - case SO_SNDTIMEO: + case SO_SNDTIMEO: #endif -#if (defined(SO_SNDTIMEO_OLD) && !defined(SO_SNDTIMEO)) || (defined(SO_SNDTIMEO_OLD) && (SO_SNDTIMEO_OLD != SO_SNDTIMEO)) - case SO_SNDTIMEO_OLD: +#if(defined(SO_SNDTIMEO_OLD) && !defined(SO_SNDTIMEO)) || \ + (defined(SO_SNDTIMEO_OLD) && (SO_SNDTIMEO_OLD != SO_SNDTIMEO)) + case SO_SNDTIMEO_OLD: #endif -#if (defined(SO_SNDTIMEO_NEW) && !defined(SO_SNDTIMEO)) || (defined(SO_SNDTIMEO_NEW) && (SO_SNDTIMEO_NEW != SO_SNDTIMEO)) - case SO_SNDTIMEO_NEW: +#if(defined(SO_SNDTIMEO_NEW) && !defined(SO_SNDTIMEO)) || \ + (defined(SO_SNDTIMEO_NEW) && (SO_SNDTIMEO_NEW != SO_SNDTIMEO)) + case SO_SNDTIMEO_NEW: #endif - if(unlikely(ppm_copy_from_user(&tv, optval, sizeof(tv)))) - { - tv.tv_sec = 0; - tv.tv_usec = 0; - } - return val_to_ring(args, tv.tv_sec * SECOND_IN_NS + tv.tv_usec * USECOND_IN_NS, 0, false, PPM_SOCKOPT_IDX_TIMEVAL); + if(unlikely(ppm_copy_from_user(&tv, optval, sizeof(tv)))) { + tv.tv_sec = 0; + tv.tv_usec = 0; + } + return val_to_ring(args, + tv.tv_sec * SECOND_IN_NS + tv.tv_usec * USECOND_IN_NS, + 0, + false, + PPM_SOCKOPT_IDX_TIMEVAL); #ifdef SO_COOKIE - case SO_COOKIE: - if(unlikely(ppm_copy_from_user(&val64, optval, sizeof(val64)))) - { - val64 = 0; - } - return val_to_ring(args, val64, 0, false, PPM_SOCKOPT_IDX_UINT64); + case SO_COOKIE: + if(unlikely(ppm_copy_from_user(&val64, optval, sizeof(val64)))) { + val64 = 0; + } + return val_to_ring(args, val64, 0, false, PPM_SOCKOPT_IDX_UINT64); #endif #ifdef SO_DEBUG - case SO_DEBUG: + case SO_DEBUG: #endif #ifdef SO_REUSEADDR - case SO_REUSEADDR: + case SO_REUSEADDR: #endif #ifdef SO_TYPE - case SO_TYPE: + case SO_TYPE: #endif #ifdef SO_DONTROUTE - case SO_DONTROUTE: + case SO_DONTROUTE: #endif #ifdef SO_BROADCAST - case SO_BROADCAST: + case SO_BROADCAST: #endif #ifdef SO_SNDBUF - case SO_SNDBUF: + case SO_SNDBUF: #endif #ifdef SO_RCVBUF - case SO_RCVBUF: + case SO_RCVBUF: #endif #ifdef SO_SNDBUFFORCE - case SO_SNDBUFFORCE: + case SO_SNDBUFFORCE: #endif #ifdef SO_RCVBUFFORCE - case SO_RCVBUFFORCE: + case SO_RCVBUFFORCE: #endif #ifdef SO_KEEPALIVE - case SO_KEEPALIVE: + case SO_KEEPALIVE: #endif #ifdef SO_OOBINLINE - case SO_OOBINLINE: + case SO_OOBINLINE: #endif #ifdef SO_NO_CHECK - case SO_NO_CHECK: + case SO_NO_CHECK: #endif #ifdef SO_PRIORITY - case SO_PRIORITY: + case SO_PRIORITY: #endif #ifdef SO_BSDCOMPAT - case SO_BSDCOMPAT: + case SO_BSDCOMPAT: #endif #ifdef SO_REUSEPORT - case SO_REUSEPORT: + case SO_REUSEPORT: #endif #ifdef SO_PASSCRED - case SO_PASSCRED: + case SO_PASSCRED: #endif #ifdef SO_RCVLOWAT - case SO_RCVLOWAT: + case SO_RCVLOWAT: #endif #ifdef SO_SNDLOWAT - case SO_SNDLOWAT: + case SO_SNDLOWAT: #endif #ifdef SO_SECURITY_AUTHENTICATION - case SO_SECURITY_AUTHENTICATION: + case SO_SECURITY_AUTHENTICATION: #endif #ifdef SO_SECURITY_ENCRYPTION_TRANSPORT - case SO_SECURITY_ENCRYPTION_TRANSPORT: + case SO_SECURITY_ENCRYPTION_TRANSPORT: #endif #ifdef SO_SECURITY_ENCRYPTION_NETWORK - case SO_SECURITY_ENCRYPTION_NETWORK: + case SO_SECURITY_ENCRYPTION_NETWORK: #endif #ifdef SO_BINDTODEVICE - case SO_BINDTODEVICE: + case SO_BINDTODEVICE: #endif #ifdef SO_DETACH_FILTER - case SO_DETACH_FILTER: + case SO_DETACH_FILTER: #endif #ifdef SO_TIMESTAMP - case SO_TIMESTAMP: + case SO_TIMESTAMP: #endif #ifdef SO_ACCEPTCONN - case SO_ACCEPTCONN: + case SO_ACCEPTCONN: #endif #ifdef SO_PEERSEC - case SO_PEERSEC: + case SO_PEERSEC: #endif #ifdef SO_PASSSEC - case SO_PASSSEC: + case SO_PASSSEC: #endif #ifdef SO_TIMESTAMPNS - case SO_TIMESTAMPNS: + case SO_TIMESTAMPNS: #endif #ifdef SO_MARK - case SO_MARK: + case SO_MARK: #endif #ifdef SO_TIMESTAMPING - case SO_TIMESTAMPING: + case SO_TIMESTAMPING: #endif #ifdef SO_PROTOCOL - case SO_PROTOCOL: + case SO_PROTOCOL: #endif #ifdef SO_DOMAIN - case SO_DOMAIN: + case SO_DOMAIN: #endif #ifdef SO_RXQ_OVFL - case SO_RXQ_OVFL: + case SO_RXQ_OVFL: #endif #ifdef SO_WIFI_STATUS - case SO_WIFI_STATUS: + case SO_WIFI_STATUS: #endif #ifdef SO_PEEK_OFF - case SO_PEEK_OFF: + case SO_PEEK_OFF: #endif #ifdef SO_NOFCS - case SO_NOFCS: + case SO_NOFCS: #endif #ifdef SO_LOCK_FILTER - case SO_LOCK_FILTER: + case SO_LOCK_FILTER: #endif #ifdef SO_SELECT_ERR_QUEUE - case SO_SELECT_ERR_QUEUE: + case SO_SELECT_ERR_QUEUE: #endif #ifdef SO_BUSY_POLL - case SO_BUSY_POLL: + case SO_BUSY_POLL: #endif #ifdef SO_MAX_PACING_RATE - case SO_MAX_PACING_RATE: + case SO_MAX_PACING_RATE: #endif #ifdef SO_BPF_EXTENSIONS - case SO_BPF_EXTENSIONS: + case SO_BPF_EXTENSIONS: #endif #ifdef SO_INCOMING_CPU - case SO_INCOMING_CPU: + case SO_INCOMING_CPU: #endif - if(unlikely(ppm_copy_from_user(&val32, optval, sizeof(val32)))) - { - val32 = 0; - } - return val_to_ring(args, val32, 0, false, PPM_SOCKOPT_IDX_UINT32); + if(unlikely(ppm_copy_from_user(&val32, optval, sizeof(val32)))) { + val32 = 0; + } + return val_to_ring(args, val32, 0, false, PPM_SOCKOPT_IDX_UINT32); - default: - return val_to_ring(args, (unsigned long)optval, optlen, true, PPM_SOCKOPT_IDX_UNKNOWN); + default: + return val_to_ring(args, (unsigned long)optval, optlen, true, PPM_SOCKOPT_IDX_UNKNOWN); } } -int f_sys_setsockopt_x(struct event_filler_arguments *args) -{ +int f_sys_setsockopt_x(struct event_filler_arguments *args) { int res = 0; long retval = 0; unsigned long val[5] = {0}; @@ -2159,7 +2098,7 @@ int f_sys_setsockopt_x(struct event_filler_arguments *args) CHECK_RES(res); /* Parameter 5: optval (type: PT_DYN) */ - res = parse_sockopt(args, val[1], val[2], (const void __user*)val[3], val[4]); + res = parse_sockopt(args, val[1], val[2], (const void __user *)val[3], val[4]); CHECK_RES(res); /* Parameter 6: optlen (type: PT_UINT32) */ @@ -2169,8 +2108,7 @@ int f_sys_setsockopt_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_getsockopt_x(struct event_filler_arguments *args) -{ +int f_sys_getsockopt_x(struct event_filler_arguments *args) { int res = 0; int64_t retval = 0; uint32_t optlen = 0; @@ -2203,13 +2141,12 @@ int f_sys_getsockopt_x(struct event_filler_arguments *args) */ /* Extract optlen */ - if(unlikely(ppm_copy_from_user(&optlen, (const void __user*)val[4], sizeof(optlen)))) - { + if(unlikely(ppm_copy_from_user(&optlen, (const void __user *)val[4], sizeof(optlen)))) { optlen = 0; } /* Parameter 5: optval (type: PT_DYN) */ - res = parse_sockopt(args, val[1], val[2], (const void __user*)val[3], optlen); + res = parse_sockopt(args, val[1], val[2], (const void __user *)val[3], optlen); CHECK_RES(res); /* Parameter 6: optlen (type: PT_UINT32) */ @@ -2219,8 +2156,7 @@ int f_sys_getsockopt_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_accept4_e(struct event_filler_arguments *args) -{ +int f_sys_accept4_e(struct event_filler_arguments *args) { int res; /* @@ -2234,8 +2170,7 @@ int f_sys_accept4_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_accept_x(struct event_filler_arguments *args) -{ +int f_sys_accept_x(struct event_filler_arguments *args) { int res; int fd; char *targetbuf = args->str_storage; @@ -2254,18 +2189,11 @@ int f_sys_accept_x(struct event_filler_arguments *args) res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); - if (fd >= 0) - { + if(fd >= 0) { /* * Convert the fd into socket endpoint information */ - size = fd_to_socktuple(fd, - NULL, - 0, - false, - true, - targetbuf, - STR_STORAGE_SIZE); + size = fd_to_socktuple(fd, NULL, 0, false, true, targetbuf, STR_STORAGE_SIZE); /* * queuepct */ @@ -2273,27 +2201,21 @@ int f_sys_accept_x(struct event_filler_arguments *args) sock = sockfd_lookup(srvskfd, &err); - if (sock && sock->sk) { + if(sock && sock->sk) { ack_backlog = sock->sk->sk_ack_backlog; max_ack_backlog = sock->sk->sk_max_ack_backlog; } - if (sock) + if(sock) sockfd_put(sock); - if (max_ack_backlog) + if(max_ack_backlog) queuepct = (unsigned long)ack_backlog * 100 / max_ack_backlog; /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ - res = val_to_ring(args, - (uint64_t)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)targetbuf, size, false, 0); CHECK_RES(res); - } - else - { + } else { /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ res = push_empty_param(args); CHECK_RES(res); @@ -2314,8 +2236,7 @@ int f_sys_accept_x(struct event_filler_arguments *args) return add_sentinel(args); } -static int f_sys_send_e_common(struct event_filler_arguments *args, int *fd) -{ +static int f_sys_send_e_common(struct event_filler_arguments *args, int *fd) { int res; unsigned long size; unsigned long val; @@ -2342,20 +2263,18 @@ static int f_sys_send_e_common(struct event_filler_arguments *args, int *fd) return PPM_SUCCESS; } -int f_sys_send_e(struct event_filler_arguments *args) -{ +int f_sys_send_e(struct event_filler_arguments *args) { int res; int fd; res = f_sys_send_e_common(args, &fd); - if (likely(res == PPM_SUCCESS)) + if(likely(res == PPM_SUCCESS)) return add_sentinel(args); return res; } -int f_sys_sendto_e(struct event_filler_arguments *args) -{ +int f_sys_sendto_e(struct event_filler_arguments *args) { unsigned long val; int res; uint16_t size = 0; @@ -2385,40 +2304,35 @@ int f_sys_sendto_e(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 5, 1, &val); - if (usrsockaddr != NULL && val != 0) { + if(usrsockaddr != NULL && val != 0) { /* * Copy the address */ err = addr_to_kernel(usrsockaddr, val, (struct sockaddr *)&address); - if (likely(err >= 0)) { + if(likely(err >= 0)) { /* * Convert the fd into socket endpoint information */ size = fd_to_socktuple(fd, - (struct sockaddr *)&address, - val, - true, - false, - targetbuf, - STR_STORAGE_SIZE); + (struct sockaddr *)&address, + val, + true, + false, + targetbuf, + STR_STORAGE_SIZE); } } /* * Copy the endpoint info into the ring */ - res = val_to_ring(args, - (uint64_t)(unsigned long)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)(unsigned long)targetbuf, size, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_send_x(struct event_filler_arguments *args) -{ +int f_sys_send_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -2451,8 +2365,7 @@ int f_sys_send_x(struct event_filler_arguments *args) return add_sentinel(args); } -static int f_sys_recv_x_common(struct event_filler_arguments *args, int64_t *retval) -{ +static int f_sys_recv_x_common(struct event_filler_arguments *args, int64_t *retval) { int res; unsigned long val; unsigned long bufsize; @@ -2474,7 +2387,7 @@ static int f_sys_recv_x_common(struct event_filler_arguments *args, int64_t *ret /* * data */ - if (*retval < 0) { + if(*retval < 0) { /* * The operation failed, return an empty buffer */ @@ -2496,20 +2409,18 @@ static int f_sys_recv_x_common(struct event_filler_arguments *args, int64_t *ret return res; } -int f_sys_recv_x(struct event_filler_arguments *args) -{ +int f_sys_recv_x(struct event_filler_arguments *args) { int res; int64_t retval; res = f_sys_recv_x_common(args, &retval); - if (likely(res == PPM_SUCCESS)) + if(likely(res == PPM_SUCCESS)) return add_sentinel(args); return res; } -int f_sys_recvfrom_e(struct event_filler_arguments *args) -{ +int f_sys_recvfrom_e(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; int32_t fd = 0; @@ -2528,8 +2439,7 @@ int f_sys_recvfrom_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_recvfrom_x(struct event_filler_arguments *args) -{ +int f_sys_recvfrom_x(struct event_filler_arguments *args) { unsigned long val; int res; uint16_t size = 0; @@ -2547,7 +2457,7 @@ int f_sys_recvfrom_x(struct event_filler_arguments *args) res = f_sys_recv_x_common(args, &retval); CHECK_RES(res); - if (retval >= 0) { + if(retval >= 0) { /* * Get the fd */ @@ -2564,15 +2474,18 @@ int f_sys_recvfrom_x(struct event_filler_arguments *args) * Get the address len */ syscall_get_arguments_deprecated(args, 5, 1, &val); - if (usrsockaddr != NULL && val != 0) { + if(usrsockaddr != NULL && val != 0) { #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(&addrlen, (const void __user *)val, sizeof(addrlen)))) + if(unlikely( + ppm_copy_from_user(&addrlen, (const void __user *)val, sizeof(addrlen)))) return PPM_FAILURE_INVALID_USER_MEMORY; #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(&addrlen, (const void __user *)compat_ptr(val), sizeof(addrlen)))) + if(unlikely(ppm_copy_from_user(&addrlen, + (const void __user *)compat_ptr(val), + sizeof(addrlen)))) return PPM_FAILURE_INVALID_USER_MEMORY; } #endif @@ -2581,47 +2494,36 @@ int f_sys_recvfrom_x(struct event_filler_arguments *args) * Copy the address */ err = addr_to_kernel(usrsockaddr, addrlen, (struct sockaddr *)&address); - if (likely(err >= 0)) { + if(likely(err >= 0)) { /* * Convert the fd into socket endpoint information */ size = fd_to_socktuple(fd, - (struct sockaddr *)&address, - addrlen, - true, - true, - targetbuf, - STR_STORAGE_SIZE); + (struct sockaddr *)&address, + addrlen, + true, + true, + targetbuf, + STR_STORAGE_SIZE); } } else { /* - * Get socket endpoint information from fd if the user-provided *sockaddr is NULL - */ - size = fd_to_socktuple(fd, - NULL, - 0, - false, - true, - targetbuf, - STR_STORAGE_SIZE); + * Get socket endpoint information from fd if the user-provided *sockaddr is NULL + */ + size = fd_to_socktuple(fd, NULL, 0, false, true, targetbuf, STR_STORAGE_SIZE); } } /* * Copy the endpoint info into the ring */ - res = val_to_ring(args, - (uint64_t)(unsigned long)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)(unsigned long)targetbuf, size, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_sendmsg_e(struct event_filler_arguments *args) -{ +int f_sys_sendmsg_e(struct event_filler_arguments *args) { int res; unsigned long val; #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 19, 0) @@ -2658,9 +2560,9 @@ int f_sys_sendmsg_e(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 1, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(&mh, (const void __user *)val, sizeof(mh)))) + if(unlikely(ppm_copy_from_user(&mh, (const void __user *)val, sizeof(mh)))) return PPM_FAILURE_INVALID_USER_MEMORY; /* @@ -2669,8 +2571,11 @@ int f_sys_sendmsg_e(struct event_filler_arguments *args) iov = (const struct iovec __user *)mh.msg_iov; iovcnt = mh.msg_iovlen; - res = parse_readv_writev_bufs(args, iov, iovcnt, args->consumer->snaplen, PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); - + res = parse_readv_writev_bufs(args, + iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); CHECK_RES(res); @@ -2681,7 +2586,9 @@ int f_sys_sendmsg_e(struct event_filler_arguments *args) addrlen = mh.msg_namelen; #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(&compat_mh, (const void __user *)compat_ptr(val), sizeof(compat_mh)))) + if(unlikely(ppm_copy_from_user(&compat_mh, + (const void __user *)compat_ptr(val), + sizeof(compat_mh)))) return PPM_FAILURE_INVALID_USER_MEMORY; /* @@ -2690,8 +2597,11 @@ int f_sys_sendmsg_e(struct event_filler_arguments *args) compat_iov = (const struct compat_iovec __user *)compat_ptr(compat_mh.msg_iov); iovcnt = compat_mh.msg_iovlen; - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, args->consumer->snaplen, PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); - + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); CHECK_RES(res); @@ -2703,38 +2613,33 @@ int f_sys_sendmsg_e(struct event_filler_arguments *args) } #endif - if (usrsockaddr != NULL && addrlen != 0) { + if(usrsockaddr != NULL && addrlen != 0) { /* * Copy the address */ err = addr_to_kernel(usrsockaddr, addrlen, (struct sockaddr *)&address); - if (likely(err >= 0)) { + if(likely(err >= 0)) { /* * Convert the fd into socket endpoint information */ size = fd_to_socktuple(fd, - (struct sockaddr *)&address, - addrlen, - true, - false, - targetbuf, - STR_STORAGE_SIZE); + (struct sockaddr *)&address, + addrlen, + true, + false, + targetbuf, + STR_STORAGE_SIZE); } } /* Copy the endpoint info into the ring */ - res = val_to_ring(args, - (uint64_t)(unsigned long)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)(unsigned long)targetbuf, size, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_sendmsg_x(struct event_filler_arguments *args) -{ +int f_sys_sendmsg_x(struct event_filler_arguments *args) { int res; unsigned long val; long retval; @@ -2763,25 +2668,28 @@ int f_sys_sendmsg_x(struct event_filler_arguments *args) /* Parameter 2: data (type: PT_BYTEBUF) */ #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(&mh, (const void __user *)val, sizeof(mh)))) - { + if(unlikely(ppm_copy_from_user(&mh, (const void __user *)val, sizeof(mh)))) { res = val_to_ring(args, 0, 0, false, 0); CHECK_RES(res); return add_sentinel(args); } - iov = (const struct iovec __user *)mh.msg_iov; iovcnt = mh.msg_iovlen; - res = parse_readv_writev_bufs(args, iov, iovcnt, args->consumer->snaplen, PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); + res = parse_readv_writev_bufs(args, + iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); CHECK_RES(res); #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(&compat_mh, (const void __user *)compat_ptr(val), sizeof(compat_mh)))) - { + if(unlikely(ppm_copy_from_user(&compat_mh, + (const void __user *)compat_ptr(val), + sizeof(compat_mh)))) { res = val_to_ring(args, 0, 0, false, 0); CHECK_RES(res); return add_sentinel(args); @@ -2790,7 +2698,11 @@ int f_sys_sendmsg_x(struct event_filler_arguments *args) compat_iov = (const struct compat_iovec __user *)compat_ptr(compat_mh.msg_iov); iovcnt = compat_mh.msg_iovlen; - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, args->consumer->snaplen, PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); CHECK_RES(res); } #endif @@ -2798,8 +2710,7 @@ int f_sys_sendmsg_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_listen_e(struct event_filler_arguments *args) -{ +int f_sys_listen_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -2820,8 +2731,7 @@ int f_sys_listen_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_recvmsg_e(struct event_filler_arguments *args) -{ +int f_sys_recvmsg_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -2835,8 +2745,7 @@ int f_sys_recvmsg_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_recvmsg_x(struct event_filler_arguments *args) -{ +int f_sys_recvmsg_x(struct event_filler_arguments *args) { int res; unsigned long val; int64_t retval; @@ -2867,8 +2776,7 @@ int f_sys_recvmsg_x(struct event_filler_arguments *args) /* If the syscall fails we are not able to collect reliable params * so we return empty ones. */ - if(retval < 0) - { + if(retval < 0) { /* Parameter 2: size (type: PT_UINT32) */ res = val_to_ring(args, 0, 0, false, 0); CHECK_RES(res); @@ -2894,9 +2802,9 @@ int f_sys_recvmsg_x(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 1, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(&mh, (const void __user *)val, sizeof(mh)))) + if(unlikely(ppm_copy_from_user(&mh, (const void __user *)val, sizeof(mh)))) return PPM_FAILURE_INVALID_USER_MEMORY; /* @@ -2908,7 +2816,9 @@ int f_sys_recvmsg_x(struct event_filler_arguments *args) res = parse_readv_writev_bufs(args, iov, iovcnt, retval, PRB_FLAG_PUSH_ALL); #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(&compat_mh, (const void __user *)compat_ptr(val), sizeof(compat_mh)))) + if(unlikely(ppm_copy_from_user(&compat_mh, + (const void __user *)compat_ptr(val), + sizeof(compat_mh)))) return PPM_FAILURE_INVALID_USER_MEMORY; /* @@ -2926,7 +2836,7 @@ int f_sys_recvmsg_x(struct event_filler_arguments *args) /* * tuple */ - if (retval >= 0) { + if(retval >= 0) { /* * Get the fd */ @@ -2939,44 +2849,37 @@ int f_sys_recvmsg_x(struct event_filler_arguments *args) usrsockaddr = (struct sockaddr __user *)mh.msg_name; addrlen = mh.msg_namelen; - if (usrsockaddr != NULL && addrlen != 0) { + if(usrsockaddr != NULL && addrlen != 0) { /* * Copy the address */ err = addr_to_kernel(usrsockaddr, addrlen, (struct sockaddr *)&address); - if (likely(err >= 0)) { + if(likely(err >= 0)) { /* * Convert the fd into socket endpoint information */ size = fd_to_socktuple(fd, - (struct sockaddr *)&address, - addrlen, - true, - true, - targetbuf, - STR_STORAGE_SIZE); + (struct sockaddr *)&address, + addrlen, + true, + true, + targetbuf, + STR_STORAGE_SIZE); } } } /* Copy the endpoint info into the ring */ - res = val_to_ring(args, - (uint64_t)(unsigned long)targetbuf, - size, - false, - 0); + res = val_to_ring(args, (uint64_t)(unsigned long)targetbuf, size, false, 0); CHECK_RES(res); /* - msg_control: ancillary data. + msg_control: ancillary data. */ - if (mh.msg_control != NULL && mh.msg_controllen > 0) - { + if(mh.msg_control != NULL && mh.msg_controllen > 0) { res = val_to_ring(args, (uint64_t)mh.msg_control, (uint32_t)mh.msg_controllen, true, 0); CHECK_RES(res); - } - else - { + } else { /* pushing empty data */ res = push_empty_param(args); CHECK_RES(res); @@ -2985,8 +2888,7 @@ int f_sys_recvmsg_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_creat_e(struct event_filler_arguments *args) -{ +int f_sys_creat_e(struct event_filler_arguments *args) { unsigned long val; unsigned long modes; int res; @@ -3008,8 +2910,7 @@ int f_sys_creat_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_creat_x(struct event_filler_arguments *args) -{ +int f_sys_creat_x(struct event_filler_arguments *args) { unsigned long val; unsigned long modes; uint32_t dev = 0; @@ -3056,12 +2957,9 @@ int f_sys_creat_x(struct event_filler_arguments *args) /* * creat_flags */ - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { creat_flags |= PPM_FD_UPPER_LAYER_CREAT; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { creat_flags |= PPM_FD_LOWER_LAYER_CREAT; } res = val_to_ring(args, creat_flags, 0, false, 0); @@ -3070,8 +2968,7 @@ int f_sys_creat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_pipe_x(struct event_filler_arguments *args) -{ +int f_sys_pipe_x(struct event_filler_arguments *args) { int res = 0; int64_t retval = 0; unsigned long val = 0; @@ -3087,17 +2984,17 @@ int f_sys_pipe_x(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 0, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(pipefd, (const void __user *)val, sizeof(pipefd)))) - { + if(unlikely(ppm_copy_from_user(pipefd, (const void __user *)val, sizeof(pipefd)))) { pipefd[0] = -1; pipefd[1] = -1; } #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(pipefd, (const void __user *)compat_ptr(val), sizeof(pipefd)))) - { + if(unlikely(ppm_copy_from_user(pipefd, + (const void __user *)compat_ptr(val), + sizeof(pipefd)))) { pipefd[0] = -1; pipefd[1] = -1; } @@ -3113,8 +3010,7 @@ int f_sys_pipe_x(struct event_filler_arguments *args) CHECK_RES(res); /* On success, pipe returns `0` */ - if(retval == 0) - { + if(retval == 0) { get_ino_from_fd(pipefd[0], &ino); } @@ -3125,8 +3021,7 @@ int f_sys_pipe_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_pipe2_x(struct event_filler_arguments *args) -{ +int f_sys_pipe2_x(struct event_filler_arguments *args) { int res = 0; int64_t retval = 0; unsigned long val = 0; @@ -3142,17 +3037,17 @@ int f_sys_pipe2_x(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 0, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(pipefd, (const void __user *)val, sizeof(pipefd)))) - { + if(unlikely(ppm_copy_from_user(pipefd, (const void __user *)val, sizeof(pipefd)))) { pipefd[0] = -1; pipefd[1] = -1; } #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(pipefd, (const void __user *)compat_ptr(val), sizeof(pipefd)))) - { + if(unlikely(ppm_copy_from_user(pipefd, + (const void __user *)compat_ptr(val), + sizeof(pipefd)))) { pipefd[0] = -1; pipefd[1] = -1; } @@ -3168,8 +3063,7 @@ int f_sys_pipe2_x(struct event_filler_arguments *args) CHECK_RES(res); /* On success, pipe returns `0` */ - if(retval == 0) - { + if(retval == 0) { get_ino_from_fd(pipefd[0], &ino); } @@ -3185,8 +3079,7 @@ int f_sys_pipe2_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_eventfd_e(struct event_filler_arguments *args) -{ +int f_sys_eventfd_e(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; @@ -3205,8 +3098,7 @@ int f_sys_eventfd_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_eventfd2_e(struct event_filler_arguments *args) -{ +int f_sys_eventfd2_e(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; @@ -3218,8 +3110,7 @@ int f_sys_eventfd2_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_eventfd2_x(struct event_filler_arguments *args) -{ +int f_sys_eventfd2_x(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; long retval = 0; @@ -3237,8 +3128,7 @@ int f_sys_eventfd2_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_shutdown_e(struct event_filler_arguments *args) -{ +int f_sys_shutdown_e(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; int32_t fd = 0; @@ -3259,8 +3149,7 @@ int f_sys_shutdown_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_futex_e(struct event_filler_arguments *args) -{ +int f_sys_futex_e(struct event_filler_arguments *args) { int res; unsigned long val; @@ -3288,8 +3177,7 @@ int f_sys_futex_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_lseek_e(struct event_filler_arguments *args) -{ +int f_sys_lseek_e(struct event_filler_arguments *args) { unsigned long val; int32_t fd; int res; @@ -3319,8 +3207,7 @@ int f_sys_lseek_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_llseek_e(struct event_filler_arguments *args) -{ +int f_sys_llseek_e(struct event_filler_arguments *args) { unsigned long val; int res; unsigned long oh; @@ -3356,8 +3243,7 @@ int f_sys_llseek_e(struct event_filler_arguments *args) return add_sentinel(args); } -static int poll_parse_fds(struct event_filler_arguments *args, bool enter_event) -{ +static int poll_parse_fds(struct event_filler_arguments *args, bool enter_event) { struct pollfd *fds; char *targetbuf; unsigned long val; @@ -3377,7 +3263,7 @@ static int poll_parse_fds(struct event_filler_arguments *args, bool enter_event) * Check if we have enough space to store both the fd list * from user space and the temporary buffer to serialize to the ring */ - if (unlikely(sizeof(struct pollfd) * nfds + 2 + 10 * nfds > STR_STORAGE_SIZE)) + if(unlikely(sizeof(struct pollfd) * nfds + 2 + 10 * nfds > STR_STORAGE_SIZE)) return PPM_FAILURE_BUFFER_FULL; /* Get the fds pointer */ @@ -3390,13 +3276,16 @@ static int poll_parse_fds(struct event_filler_arguments *args, bool enter_event) * in this case `0`. */ #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(fds, (const void __user *)val, nfds * sizeof(struct pollfd)))) + if(unlikely( + ppm_copy_from_user(fds, (const void __user *)val, nfds * sizeof(struct pollfd)))) nfds = 0; #ifdef CONFIG_COMPAT } else { - if (unlikely(ppm_copy_from_user(fds, (const void __user *)compat_ptr(val), nfds * sizeof(struct pollfd)))) + if(unlikely(ppm_copy_from_user(fds, + (const void __user *)compat_ptr(val), + nfds * sizeof(struct pollfd)))) nfds = 0; } #endif @@ -3405,8 +3294,8 @@ static int poll_parse_fds(struct event_filler_arguments *args, bool enter_event) targetbuf = args->str_storage + nfds * sizeof(struct pollfd); /* Copy each fd into the temporary buffer */ - for (j = 0; j < nfds; j++) { - if (enter_event) { + for(j = 0; j < nfds; j++) { + if(enter_event) { flags = poll_events_to_scap(fds[j].events); } else { flags = poll_events_to_scap(fds[j].revents); @@ -3422,8 +3311,7 @@ static int poll_parse_fds(struct event_filler_arguments *args, bool enter_event) return val_to_ring(args, (uint64_t)(unsigned long)targetbuf, pos, false, 0); } -int f_sys_poll_e(struct event_filler_arguments *args) -{ +int f_sys_poll_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -3440,14 +3328,13 @@ int f_sys_poll_e(struct event_filler_arguments *args) return add_sentinel(args); } -static int timespec_parse(struct event_filler_arguments *args, unsigned long val) -{ +static int timespec_parse(struct event_filler_arguments *args, unsigned long val) { uint64_t longtime = 0; int cfulen = 0; char *targetbuf = args->str_storage; #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 18, 0) - struct __kernel_timespec* tts = (struct __kernel_timespec *)targetbuf; + struct __kernel_timespec *tts = (struct __kernel_timespec *)targetbuf; #else struct timespec *tts = (struct timespec *)targetbuf; #endif @@ -3461,18 +3348,18 @@ static int timespec_parse(struct event_filler_arguments *args, unsigned long val * We copy the timespec structure and then convert it to a 64bit relative time */ #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif cfulen = (int)ppm_copy_from_user(targetbuf, (void __user *)val, sizeof(*tts)); - if(likely(cfulen == 0)) - { + if(likely(cfulen == 0)) { longtime = ((uint64_t)tts->tv_sec) * 1000000000 + tts->tv_nsec; } #ifdef CONFIG_COMPAT } else { - cfulen = (int)ppm_copy_from_user(targetbuf, (void __user *)compat_ptr(val), sizeof(struct compat_timespec)); - if(likely(cfulen == 0)) - { + cfulen = (int)ppm_copy_from_user(targetbuf, + (void __user *)compat_ptr(val), + sizeof(struct compat_timespec)); + if(likely(cfulen == 0)) { longtime = ((uint64_t)compat_tts->tv_sec) * 1000000000 + compat_tts->tv_nsec; } } @@ -3481,8 +3368,7 @@ static int timespec_parse(struct event_filler_arguments *args, unsigned long val return val_to_ring(args, longtime, 0, false, 0); } -int f_sys_ppoll_e(struct event_filler_arguments *args) -{ +int f_sys_ppoll_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; @@ -3497,8 +3383,7 @@ int f_sys_ppoll_e(struct event_filler_arguments *args) /* Parameter 3: sigmask (type: PT_SIGSET) */ syscall_get_arguments_deprecated(args, 3, 1, &val); - if (val == (unsigned long)NULL || ppm_copy_from_user(&val, (void __user *)val, sizeof(val))) - { + if(val == (unsigned long)NULL || ppm_copy_from_user(&val, (void __user *)val, sizeof(val))) { val = 0; } res = val_to_ring(args, (uint32_t)val, 0, false, 0); @@ -3508,8 +3393,7 @@ int f_sys_ppoll_e(struct event_filler_arguments *args) } /* This is the same for poll() and ppoll() */ -int f_sys_poll_x(struct event_filler_arguments *args) -{ +int f_sys_poll_x(struct event_filler_arguments *args) { int64_t retval; int res; @@ -3526,8 +3410,7 @@ int f_sys_poll_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mount_e(struct event_filler_arguments *args) -{ +int f_sys_mount_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -3536,7 +3419,7 @@ int f_sys_mount_e(struct event_filler_arguments *args) * See http://lxr.free-electrons.com/source/fs/namespace.c?v=4.2#L2650 */ syscall_get_arguments_deprecated(args, 3, 1, &val); - if ((val & PPM_MS_MGC_MSK) == PPM_MS_MGC_VAL) + if((val & PPM_MS_MGC_MSK) == PPM_MS_MGC_VAL) val &= ~PPM_MS_MGC_MSK; res = val_to_ring(args, val, 0, false, 0); CHECK_RES(res); @@ -3544,8 +3427,7 @@ int f_sys_mount_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_openat_e(struct event_filler_arguments *args) -{ +int f_sys_openat_e(struct event_filler_arguments *args) { unsigned long val; unsigned long flags; unsigned long modes; @@ -3557,7 +3439,7 @@ int f_sys_openat_e(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -3571,7 +3453,8 @@ int f_sys_openat_e(struct event_filler_arguments *args) CHECK_RES(res); /* * Flags - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ syscall_get_arguments_deprecated(args, 2, 1, &flags); res = val_to_ring(args, open_flags_to_scap(flags), 0, false, 0); @@ -3587,8 +3470,7 @@ int f_sys_openat_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_openat_x(struct event_filler_arguments *args) -{ +int f_sys_openat_x(struct event_filler_arguments *args) { unsigned long val; unsigned long flags; unsigned long scap_flags; @@ -3610,7 +3492,7 @@ int f_sys_openat_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -3626,18 +3508,16 @@ int f_sys_openat_x(struct event_filler_arguments *args) get_dev_ino_overlay_from_fd(retval, &dev, &ino, &ol); /* * Flags - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ syscall_get_arguments_deprecated(args, 2, 1, &flags); scap_flags = open_flags_to_scap(flags); /* update scap flags if file is created */ get_fd_fmode_created(retval, &scap_flags); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { scap_flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { scap_flags |= PPM_FD_LOWER_LAYER; } res = val_to_ring(args, scap_flags, 0, false, 0); @@ -3663,8 +3543,7 @@ int f_sys_openat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_unlinkat_x(struct event_filler_arguments *args) -{ +int f_sys_unlinkat_x(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; long retval = 0; @@ -3678,8 +3557,7 @@ int f_sys_unlinkat_x(struct event_filler_arguments *args) /* Parameter 2: dirfd (type: PT_FD) */ syscall_get_arguments_deprecated(args, 0, 1, &val); dirfd = (int32_t)val; - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } res = val_to_ring(args, (int64_t)dirfd, 0, false, 0); @@ -3692,14 +3570,13 @@ int f_sys_unlinkat_x(struct event_filler_arguments *args) /* Parameter 4: flags (type: PT_FLAGS32) */ syscall_get_arguments_deprecated(args, 2, 1, &val); - res = val_to_ring(args, unlinkat_flags_to_scap((int32_t) val), 0, false, 0); + res = val_to_ring(args, unlinkat_flags_to_scap((int32_t)val), 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_linkat_x(struct event_filler_arguments *args) -{ +int f_sys_linkat_x(struct event_filler_arguments *args) { unsigned long val; unsigned long flags; int res; @@ -3714,7 +3591,7 @@ int f_sys_linkat_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); - if ((int)val == AT_FDCWD) + if((int)val == AT_FDCWD) val = PPM_AT_FDCWD; res = val_to_ring(args, val, 0, false, 0); @@ -3732,7 +3609,7 @@ int f_sys_linkat_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); - if ((int)val == AT_FDCWD) + if((int)val == AT_FDCWD) val = PPM_AT_FDCWD; res = val_to_ring(args, val, 0, false, 0); @@ -3747,17 +3624,17 @@ int f_sys_linkat_x(struct event_filler_arguments *args) /* * Flags - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ syscall_get_arguments_deprecated(args, 4, 1, &flags); - res = val_to_ring(args, linkat_flags_to_scap((int32_t) flags), 0, false, 0); + res = val_to_ring(args, linkat_flags_to_scap((int32_t)flags), 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_pread64_e(struct event_filler_arguments *args) -{ +int f_sys_pread64_e(struct event_filler_arguments *args) { unsigned long val; unsigned long size; int res; @@ -3783,21 +3660,21 @@ int f_sys_pread64_e(struct event_filler_arguments *args) * pos */ #ifndef CAPTURE_64BIT_ARGS_SINGLE_REGISTER -{ - unsigned long pos0; - unsigned long pos1; + { + unsigned long pos0; + unsigned long pos1; #if defined CONFIG_X86 - syscall_get_arguments_deprecated(args, 3, 1, &pos0); - syscall_get_arguments_deprecated(args, 4, 1, &pos1); + syscall_get_arguments_deprecated(args, 3, 1, &pos0); + syscall_get_arguments_deprecated(args, 4, 1, &pos1); #elif defined CONFIG_ARM && CONFIG_AEABI - syscall_get_arguments_deprecated(args, 4, 1, &pos0); - syscall_get_arguments_deprecated(args, 5, 1, &pos1); + syscall_get_arguments_deprecated(args, 4, 1, &pos0); + syscall_get_arguments_deprecated(args, 5, 1, &pos1); #else - #error This architecture/abi not yet supported +#error This architecture/abi not yet supported #endif - pos64 = merge_64(pos1, pos0); -} + pos64 = merge_64(pos1, pos0); + } #else syscall_get_arguments_deprecated(args, 3, 1, &pos64); #endif @@ -3808,8 +3685,7 @@ int f_sys_pread64_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_pwrite64_e(struct event_filler_arguments *args) -{ +int f_sys_pwrite64_e(struct event_filler_arguments *args) { unsigned long val; unsigned long size; int res; @@ -3843,7 +3719,7 @@ int f_sys_pwrite64_e(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 4, 1, &pos0); syscall_get_arguments_deprecated(args, 5, 1, &pos1); #else - #error This architecture/abi not yet supported +#error This architecture/abi not yet supported #endif pos64 = merge_64(pos1, pos0); } @@ -3857,8 +3733,7 @@ int f_sys_pwrite64_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_preadv_e(struct event_filler_arguments *args) -{ +int f_sys_preadv_e(struct event_filler_arguments *args) { unsigned long val; int res; int32_t fd; @@ -3880,11 +3755,11 @@ int f_sys_preadv_e(struct event_filler_arguments *args) unsigned long pos0; unsigned long pos1; /* - * Note that in preadv and pwritev have NO 64-bit arguments in the - * syscall (despite having one in the userspace API), so no alignment - * requirements apply here. For an overly-detailed discussion about - * this, see https://lwn.net/Articles/311630/ - */ + * Note that in preadv and pwritev have NO 64-bit arguments in the + * syscall (despite having one in the userspace API), so no alignment + * requirements apply here. For an overly-detailed discussion about + * this, see https://lwn.net/Articles/311630/ + */ syscall_get_arguments_deprecated(args, 3, 1, &pos0); syscall_get_arguments_deprecated(args, 4, 1, &pos1); @@ -3900,8 +3775,7 @@ int f_sys_preadv_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_readv_e(struct event_filler_arguments *args) -{ +int f_sys_readv_e(struct event_filler_arguments *args) { unsigned long val; int32_t fd; int res; @@ -3917,8 +3791,7 @@ int f_sys_readv_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_readv_preadv_x(struct event_filler_arguments *args) -{ +int f_sys_readv_preadv_x(struct event_filler_arguments *args) { unsigned long val; int64_t retval; int res; @@ -3931,26 +3804,28 @@ int f_sys_readv_preadv_x(struct event_filler_arguments *args) res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - if(retval > 0) - { + if(retval > 0) { syscall_get_arguments_deprecated(args, 1, 1, &val); syscall_get_arguments_deprecated(args, 2, 1, &iovcnt); - #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) { - const struct compat_iovec __user *compat_iov = (const struct compat_iovec __user *)compat_ptr(val); - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, retval, PRB_FLAG_PUSH_ALL); +#ifdef CONFIG_COMPAT + if(unlikely(args->compat)) { + const struct compat_iovec __user *compat_iov = + (const struct compat_iovec __user *)compat_ptr(val); + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + retval, + PRB_FLAG_PUSH_ALL); } else - #endif +#endif { const struct iovec __user *iov = (const struct iovec __user *)val; res = parse_readv_writev_bufs(args, iov, iovcnt, retval, PRB_FLAG_PUSH_ALL); } CHECK_RES(res); - } - else - { + } else { /* pushing a zero size */ res = val_to_ring(args, 0, 0, false, 0); CHECK_RES(res); @@ -3963,8 +3838,7 @@ int f_sys_readv_preadv_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_writev_e(struct event_filler_arguments *args) -{ +int f_sys_writev_e(struct event_filler_arguments *args) { unsigned long val; int res; int32_t fd = 0; @@ -3984,24 +3858,29 @@ int f_sys_writev_e(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 1, 1, &val); #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) { - const struct compat_iovec __user *compat_iov = (const struct compat_iovec __user *)compat_ptr(val); - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, - args->consumer->snaplen, - PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); + if(unlikely(args->compat)) { + const struct compat_iovec __user *compat_iov = + (const struct compat_iovec __user *)compat_ptr(val); + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); } else #endif { const struct iovec __user *iov = (const struct iovec __user *)val; - res = parse_readv_writev_bufs(args, iov, iovcnt, args->consumer->snaplen, - PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); + res = parse_readv_writev_bufs(args, + iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); } /* if there was an error we send a size equal to `0`. * we can improve this in the future but at least we don't lose the whole event. */ - if(res == PPM_FAILURE_INVALID_USER_MEMORY) - { + if(res == PPM_FAILURE_INVALID_USER_MEMORY) { res = val_to_ring(args, 0, 0, true, 0); } @@ -4010,8 +3889,7 @@ int f_sys_writev_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_writev_pwritev_x(struct event_filler_arguments *args) -{ +int f_sys_writev_pwritev_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -4029,27 +3907,34 @@ int f_sys_writev_pwritev_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &iovcnt); - /* * Copy the buffer */ syscall_get_arguments_deprecated(args, 1, 1, &val); #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) { - const struct compat_iovec __user *compat_iov = (const struct compat_iovec __user *)compat_ptr(val); - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, args->consumer->snaplen, PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); + if(unlikely(args->compat)) { + const struct compat_iovec __user *compat_iov = + (const struct compat_iovec __user *)compat_ptr(val); + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); } else #endif { const struct iovec __user *iov = (const struct iovec __user *)val; - res = parse_readv_writev_bufs(args, iov, iovcnt, args->consumer->snaplen, PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); + res = parse_readv_writev_bufs(args, + iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_DATA | PRB_FLAG_IS_WRITE); } /* if there was an error we send an empty param. * we can improve this in the future but at least we don't lose the whole event. */ - if(res == PPM_FAILURE_INVALID_USER_MEMORY) - { + if(res == PPM_FAILURE_INVALID_USER_MEMORY) { res = push_empty_param(args); } @@ -4058,8 +3943,7 @@ int f_sys_writev_pwritev_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_pwritev_e(struct event_filler_arguments *args) -{ +int f_sys_pwritev_e(struct event_filler_arguments *args) { unsigned long val; int res; unsigned long pos64; @@ -4084,25 +3968,29 @@ int f_sys_pwritev_e(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 1, 1, &val); #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) - { - const struct compat_iovec __user *compat_iov = (const struct compat_iovec __user *)compat_ptr(val); - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, - args->consumer->snaplen, - PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); + if(unlikely(args->compat)) { + const struct compat_iovec __user *compat_iov = + (const struct compat_iovec __user *)compat_ptr(val); + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); } else #endif { const struct iovec __user *iov = (const struct iovec __user *)val; - res = parse_readv_writev_bufs(args, iov, iovcnt, args->consumer->snaplen, - PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); + res = parse_readv_writev_bufs(args, + iov, + iovcnt, + args->consumer->snaplen, + PRB_FLAG_PUSH_SIZE | PRB_FLAG_IS_WRITE); } /* if there was an error we send a size equal to 0. * we can improve this in the future but at least we don't lose the whole event. */ - if(res == PPM_FAILURE_INVALID_USER_MEMORY) - { + if(res == PPM_FAILURE_INVALID_USER_MEMORY) { res = val_to_ring(args, 0, 0, true, 0); } @@ -4114,11 +4002,11 @@ int f_sys_pwritev_e(struct event_filler_arguments *args) unsigned long pos0 = 0; unsigned long pos1 = 0; /* - * Note that in preadv and pwritev have NO 64-bit arguments in the - * syscall (despite having one in the userspace API), so no alignment - * requirements apply here. For an overly-detailed discussion about - * this, see https://lwn.net/Articles/311630/ - */ + * Note that in preadv and pwritev have NO 64-bit arguments in the + * syscall (despite having one in the userspace API), so no alignment + * requirements apply here. For an overly-detailed discussion about + * this, see https://lwn.net/Articles/311630/ + */ syscall_get_arguments_deprecated(args, 3, 1, &pos0); syscall_get_arguments_deprecated(args, 4, 1, &pos1); @@ -4134,8 +4022,7 @@ int f_sys_pwritev_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_nanosleep_e(struct event_filler_arguments *args) -{ +int f_sys_nanosleep_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -4146,8 +4033,7 @@ int f_sys_nanosleep_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_getrlimit_setrlimit_e(struct event_filler_arguments *args) -{ +int f_sys_getrlimit_setrlimit_e(struct event_filler_arguments *args) { uint8_t ppm_resource; unsigned long val; int res; @@ -4184,43 +4070,33 @@ int f_sys_getrlimit_x(struct event_filler_arguments *args) { /* * Copy the user structure and extract cur and max */ - if(retval == 0) - { + if(retval == 0) { syscall_get_arguments_deprecated(args, 1, 1, &val); #ifdef CONFIG_COMPAT - if(!args->compat) - { + if(!args->compat) { #endif - if(unlikely(ppm_copy_from_user(&rl, (const void __user *)val, sizeof(struct rlimit)))) - { + if(unlikely(ppm_copy_from_user(&rl, (const void __user *)val, sizeof(struct rlimit)))) { cur = 0; max = 0; - } - else - { + } else { cur = rl.rlim_cur; max = rl.rlim_max; } #ifdef CONFIG_COMPAT - } - else - { - if(unlikely(ppm_copy_from_user(&compat_rl, (const void __user *)compat_ptr(val), sizeof(struct compat_rlimit)))) - { + } else { + if(unlikely(ppm_copy_from_user(&compat_rl, + (const void __user *)compat_ptr(val), + sizeof(struct compat_rlimit)))) { cur = 0; max = 0; - } - else - { + } else { cur = compat_rl.rlim_cur; max = compat_rl.rlim_max; } } #endif - } - else - { + } else { cur = -1; max = -1; } @@ -4236,8 +4112,7 @@ int f_sys_getrlimit_x(struct event_filler_arguments *args) { return add_sentinel(args); } -int f_sys_setrlimit_x(struct event_filler_arguments *args) -{ +int f_sys_setrlimit_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -4259,14 +4134,16 @@ int f_sys_setrlimit_x(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 1, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif ppm_copy_from_user(&rl, (const void __user *)val, sizeof(struct rlimit)); cur = rl.rlim_cur; max = rl.rlim_max; #ifdef CONFIG_COMPAT } else { - ppm_copy_from_user(&compat_rl, (const void __user *)compat_ptr(val), sizeof(struct compat_rlimit)); + ppm_copy_from_user(&compat_rl, + (const void __user *)compat_ptr(val), + sizeof(struct compat_rlimit)); cur = compat_rl.rlim_cur; max = compat_rl.rlim_max; } @@ -4288,8 +4165,7 @@ int f_sys_setrlimit_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_prlimit_e(struct event_filler_arguments *args) -{ +int f_sys_prlimit_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; pid_t pid = 0; @@ -4308,8 +4184,7 @@ int f_sys_prlimit_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_prlimit_x(struct event_filler_arguments *args) -{ +int f_sys_prlimit_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -4333,7 +4208,7 @@ int f_sys_prlimit_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif ppm_copy_from_user(&rl, (const void __user *)val, sizeof(struct rlimit)); newcur = rl.rlim_cur; @@ -4354,42 +4229,33 @@ int f_sys_prlimit_x(struct event_filler_arguments *args) res = val_to_ring(args, newmax, 0, false, 0); CHECK_RES(res); - if(retval == 0) - { + if(retval == 0) { syscall_get_arguments_deprecated(args, 3, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif - if (unlikely(ppm_copy_from_user(&rl, (const void __user *)val, sizeof(struct rlimit)))) - { + if(unlikely(ppm_copy_from_user(&rl, (const void __user *)val, sizeof(struct rlimit)))) { oldcur = 0; oldmax = 0; - } - else - { + } else { oldcur = rl.rlim_cur; oldmax = rl.rlim_max; } #ifdef CONFIG_COMPAT - } - else - { - if (unlikely(ppm_copy_from_user(&compat_rl, (const void __user *)val, sizeof(struct compat_rlimit)))) - { + } else { + if(unlikely(ppm_copy_from_user(&compat_rl, + (const void __user *)val, + sizeof(struct compat_rlimit)))) { oldcur = 0; oldmax = 0; - } - else - { + } else { oldcur = compat_rl.rlim_cur; oldmax = compat_rl.rlim_max; } } #endif - } - else - { + } else { oldcur = -1; oldmax = -1; } @@ -4418,15 +4284,14 @@ int f_sys_prlimit_x(struct event_filler_arguments *args) #ifdef CAPTURE_CONTEXT_SWITCHES -int f_sched_switch_e(struct event_filler_arguments *args) -{ +int f_sched_switch_e(struct event_filler_arguments *args) { int res; long total_vm = 0; long total_rss = 0; long swap = 0; struct mm_struct *mm = NULL; - if (args->sched_prev == NULL || args->sched_next == NULL) { + if(args->sched_prev == NULL || args->sched_next == NULL) { ASSERT(false); return -1; } @@ -4450,10 +4315,10 @@ int f_sched_switch_e(struct event_filler_arguments *args) CHECK_RES(res); mm = args->sched_prev->mm; - if (mm) { - total_vm = mm->total_vm << (PAGE_SHIFT-10); - total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT-10); - swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT-10); + if(mm) { + total_vm = mm->total_vm << (PAGE_SHIFT - 10); + total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT - 10); + swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT - 10); } /* @@ -4487,8 +4352,7 @@ int f_sched_switch_e(struct event_filler_arguments *args) } #endif /* CAPTURE_CONTEXT_SWITCHES */ -int f_sched_drop(struct event_filler_arguments *args) -{ +int f_sched_drop(struct event_filler_arguments *args) { int res; /* @@ -4500,8 +4364,7 @@ int f_sched_drop(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fcntl_e(struct event_filler_arguments *args) -{ +int f_sys_fcntl_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -4520,8 +4383,7 @@ int f_sys_fcntl_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fcntl_x(struct event_filler_arguments *args) -{ +int f_sys_fcntl_x(struct event_filler_arguments *args) { int64_t retval; unsigned long val = 0; int res = 0; @@ -4546,14 +4408,13 @@ int f_sys_fcntl_x(struct event_filler_arguments *args) return add_sentinel(args); } -static inline int parse_ptrace_addr(struct event_filler_arguments *args, uint16_t request) -{ +static inline int parse_ptrace_addr(struct event_filler_arguments *args, uint16_t request) { unsigned long val; uint64_t dst; uint8_t idx; syscall_get_arguments_deprecated(args, 2, 1, &val); - switch (request) { + switch(request) { default: idx = PPM_PTRACE_IDX_UINT64; dst = (uint64_t)val; @@ -4562,29 +4423,30 @@ static inline int parse_ptrace_addr(struct event_filler_arguments *args, uint16_ return val_to_ring(args, dst, 0, false, idx); } -static inline int parse_ptrace_data(struct event_filler_arguments *args, uint16_t request) -{ +static inline int parse_ptrace_data(struct event_filler_arguments *args, uint16_t request) { unsigned long val; unsigned long len; uint64_t dst; uint8_t idx; syscall_get_arguments_deprecated(args, 3, 1, &val); - switch (request) { + switch(request) { case PPM_PTRACE_PEEKTEXT: case PPM_PTRACE_PEEKDATA: case PPM_PTRACE_PEEKUSR: idx = PPM_PTRACE_IDX_UINT64; #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif len = ppm_copy_from_user(&dst, (const void __user *)val, sizeof(long)); #ifdef CONFIG_COMPAT } else { - len = ppm_copy_from_user(&dst, (const void __user *)compat_ptr(val), sizeof(compat_long_t)); + len = ppm_copy_from_user(&dst, + (const void __user *)compat_ptr(val), + sizeof(compat_long_t)); } #endif - if (unlikely(len != 0)) + if(unlikely(len != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; break; @@ -4609,8 +4471,7 @@ static inline int parse_ptrace_data(struct event_filler_arguments *args, uint16_ return val_to_ring(args, dst, 0, false, idx); } -int f_sys_ptrace_e(struct event_filler_arguments *args) -{ +int f_sys_ptrace_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; pid_t pid = 0; @@ -4629,8 +4490,7 @@ int f_sys_ptrace_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_ptrace_x(struct event_filler_arguments *args) -{ +int f_sys_ptrace_x(struct event_filler_arguments *args) { unsigned long val; int64_t retval; uint16_t request; @@ -4643,7 +4503,7 @@ int f_sys_ptrace_x(struct event_filler_arguments *args) res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - if (retval < 0) { + if(retval < 0) { res = val_to_ring(args, 0, 0, false, 0); CHECK_RES(res); @@ -4668,8 +4528,7 @@ int f_sys_ptrace_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_brk_munmap_mmap_x(struct event_filler_arguments *args) -{ +int f_sys_brk_munmap_mmap_x(struct event_filler_arguments *args) { int64_t retval; int res = 0; struct mm_struct *mm = current->mm; @@ -4681,10 +4540,10 @@ int f_sys_brk_munmap_mmap_x(struct event_filler_arguments *args) res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - if (mm) { - total_vm = mm->total_vm << (PAGE_SHIFT-10); - total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT-10); - swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT-10); + if(mm) { + total_vm = mm->total_vm << (PAGE_SHIFT - 10); + total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT - 10); + swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT - 10); } /* @@ -4708,8 +4567,7 @@ int f_sys_brk_munmap_mmap_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mmap_e(struct event_filler_arguments *args) -{ +int f_sys_mmap_e(struct event_filler_arguments *args) { unsigned long val; int32_t fd = 0; int res; @@ -4760,8 +4618,7 @@ int f_sys_mmap_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mprotect_e(struct event_filler_arguments *args) -{ +int f_sys_mprotect_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -4789,8 +4646,7 @@ int f_sys_mprotect_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mprotect_x(struct event_filler_arguments *args) -{ +int f_sys_mprotect_x(struct event_filler_arguments *args) { int res; int64_t retval; @@ -4801,8 +4657,7 @@ int f_sys_mprotect_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_renameat_x(struct event_filler_arguments *args) -{ +int f_sys_renameat_x(struct event_filler_arguments *args) { unsigned long val; int res; int32_t fd; @@ -4817,7 +4672,7 @@ int f_sys_renameat_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -4835,7 +4690,7 @@ int f_sys_renameat_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -4851,8 +4706,7 @@ int f_sys_renameat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_renameat2_x(struct event_filler_arguments *args) -{ +int f_sys_renameat2_x(struct event_filler_arguments *args) { unsigned long val; int res; int32_t fd; @@ -4867,7 +4721,7 @@ int f_sys_renameat2_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -4885,7 +4739,7 @@ int f_sys_renameat2_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -4898,7 +4752,6 @@ int f_sys_renameat2_x(struct event_filler_arguments *args) res = val_to_ring(args, val, 0, true, 0); CHECK_RES(res); - /* * flags */ @@ -4909,8 +4762,7 @@ int f_sys_renameat2_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_symlinkat_x(struct event_filler_arguments *args) -{ +int f_sys_symlinkat_x(struct event_filler_arguments *args) { unsigned long val; int res; int32_t fd; @@ -4932,7 +4784,7 @@ int f_sys_symlinkat_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 1, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -4948,8 +4800,7 @@ int f_sys_symlinkat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_openat2_e(struct event_filler_arguments *args) -{ +int f_sys_openat2_e(struct event_filler_arguments *args) { unsigned long resolve; unsigned long flags; unsigned long val; @@ -4965,7 +4816,7 @@ int f_sys_openat2_e(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -4978,14 +4829,13 @@ int f_sys_openat2_e(struct event_filler_arguments *args) res = val_to_ring(args, val, 0, true, 0); CHECK_RES(res); - #ifdef __NR_openat2 /* * how: we get the data structure, and put its fields in the buffer one by one */ syscall_get_arguments_deprecated(args, 2, 1, &val); res = ppm_copy_from_user(&how, (void *)val, sizeof(struct open_how)); - if (unlikely(res != 0)) + if(unlikely(res != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; flags = open_flags_to_scap(how.flags); @@ -4998,21 +4848,24 @@ int f_sys_openat2_e(struct event_filler_arguments *args) #endif /* * flags (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = val_to_ring(args, flags, 0, true, 0); CHECK_RES(res); /* * mode (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = val_to_ring(args, mode, 0, true, 0); CHECK_RES(res); /* * resolve (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = val_to_ring(args, resolve, 0, true, 0); CHECK_RES(res); @@ -5020,8 +4873,7 @@ int f_sys_openat2_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_openat2_x(struct event_filler_arguments *args) -{ +int f_sys_openat2_x(struct event_filler_arguments *args) { unsigned long resolve; unsigned long flags; unsigned long val; @@ -5045,7 +4897,7 @@ int f_sys_openat2_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -5058,14 +4910,13 @@ int f_sys_openat2_x(struct event_filler_arguments *args) res = val_to_ring(args, val, 0, true, 0); CHECK_RES(res); - #ifdef __NR_openat2 /* * how: we get the data structure, and put its fields in the buffer one by one */ syscall_get_arguments_deprecated(args, 2, 1, &val); res = ppm_copy_from_user(&how, (void *)val, sizeof(struct open_how)); - if (unlikely(res != 0)) + if(unlikely(res != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; flags = open_flags_to_scap(how.flags); @@ -5081,16 +4932,14 @@ int f_sys_openat2_x(struct event_filler_arguments *args) /* * flags (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ /* update flags if file is created */ get_fd_fmode_created(retval, &flags); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } res = val_to_ring(args, flags, 0, true, 0); @@ -5098,14 +4947,16 @@ int f_sys_openat2_x(struct event_filler_arguments *args) /* * mode (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = val_to_ring(args, mode, 0, true, 0); CHECK_RES(res); /* * resolve (extracted from open_how structure) - * Note that we convert them into the ppm portable representation before pushing them to the ring + * Note that we convert them into the ppm portable representation before pushing them to the + * ring */ res = val_to_ring(args, resolve, 0, true, 0); CHECK_RES(res); @@ -5125,8 +4976,7 @@ int f_sys_openat2_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_copy_file_range_e(struct event_filler_arguments *args) -{ +int f_sys_copy_file_range_e(struct event_filler_arguments *args) { unsigned long val = 0; int32_t fdin = 0; unsigned long offin = 0; @@ -5140,15 +4990,15 @@ int f_sys_copy_file_range_e(struct event_filler_arguments *args) CHECK_RES(res); /* - * offin - */ + * offin + */ syscall_get_arguments_deprecated(args, 1, 1, &offin); res = val_to_ring(args, offin, 0, false, 0); CHECK_RES(res); /* - * len - */ + * len + */ syscall_get_arguments_deprecated(args, 4, 1, &len); res = val_to_ring(args, len, 0, false, 0); CHECK_RES(res); @@ -5156,8 +5006,7 @@ int f_sys_copy_file_range_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_copy_file_range_x(struct event_filler_arguments *args) -{ +int f_sys_copy_file_range_x(struct event_filler_arguments *args) { unsigned long val = 0; unsigned long offout = 0; int64_t retval = 0; @@ -5183,8 +5032,7 @@ int f_sys_copy_file_range_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_open_by_handle_at_x(struct event_filler_arguments *args) -{ +int f_sys_open_by_handle_at_x(struct event_filler_arguments *args) { unsigned long val = 0; unsigned long flags = 0; int res = 0; @@ -5203,8 +5051,7 @@ int f_sys_open_by_handle_at_x(struct event_filler_arguments *args) /* Parameter 2: mountfd (type: PT_FD) */ syscall_get_arguments_deprecated(args, 0, 1, &val); mountfd = (int32_t)val; - if(mountfd == AT_FDCWD) - { + if(mountfd == AT_FDCWD) { mountfd = PPM_AT_FDCWD; } res = val_to_ring(args, (int64_t)mountfd, 0, false, 0); @@ -5217,32 +5064,27 @@ int f_sys_open_by_handle_at_x(struct event_filler_arguments *args) flags = open_flags_to_scap(val); /* update flags if file is created */ get_fd_fmode_created(retval, &flags); - if (ol == PPM_OVERLAY_UPPER) - { + if(ol == PPM_OVERLAY_UPPER) { flags |= PPM_FD_UPPER_LAYER; - } - else if (ol == PPM_OVERLAY_LOWER) - { + } else if(ol == PPM_OVERLAY_LOWER) { flags |= PPM_FD_LOWER_LAYER; } res = val_to_ring(args, flags, 0, false, 0); CHECK_RES(res); /* Parameter 4: path (type: PT_FSPATH) */ - if (retval > 0) - { + if(retval > 0) { /* String storage size is exactly one page. * PAGE_SIZE = 4096 byte like PATH_MAX in unix conventions. */ - char* buf = (char*)args->str_storage; + char *buf = (char *)args->str_storage; struct file *file; file = fget(retval); - if(likely(file)) - { + if(likely(file)) { /* `pathname` will be a pointer inside the buffer `buf` - * where the file path effectively starts. - */ + * where the file path effectively starts. + */ pathname = d_path(&file->f_path, buf, PAGE_SIZE); fput(file); } @@ -5262,8 +5104,7 @@ int f_sys_open_by_handle_at_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_io_uring_setup_x(struct event_filler_arguments *args) -{ +int f_sys_io_uring_setup_x(struct event_filler_arguments *args) { int res = 0; long retval = 0; unsigned long val = 0; @@ -5282,8 +5123,7 @@ int f_sys_io_uring_setup_x(struct event_filler_arguments *args) struct io_uring_params params = {0}; syscall_get_arguments_deprecated(args, 1, 1, &val); res = ppm_copy_from_user(¶ms, (void *)val, sizeof(struct io_uring_params)); - if(unlikely(res != 0)) - { + if(unlikely(res != 0)) { memset(¶ms, 0, sizeof(params)); } @@ -5339,8 +5179,7 @@ int f_sys_io_uring_setup_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_io_uring_enter_x(struct event_filler_arguments *args) -{ +int f_sys_io_uring_enter_x(struct event_filler_arguments *args) { int res = 0; int32_t fd = 0; unsigned long val = 0; @@ -5382,8 +5221,7 @@ int f_sys_io_uring_enter_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_io_uring_register_x (struct event_filler_arguments *args) -{ +int f_sys_io_uring_register_x(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; int32_t fd = 0; @@ -5401,7 +5239,7 @@ int f_sys_io_uring_register_x (struct event_filler_arguments *args) /* Parameter 3: opcode (type: PT_UINT32) */ syscall_get_arguments_deprecated(args, 1, 1, &val); - res = val_to_ring(args, io_uring_register_opcodes_to_scap(val) , 0 , true, 0); + res = val_to_ring(args, io_uring_register_opcodes_to_scap(val), 0, true, 0); CHECK_RES(res); /* Parameter 4: arg (type: PT_UINT64) */ @@ -5417,8 +5255,7 @@ int f_sys_io_uring_register_x (struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_inotify_init_e(struct event_filler_arguments *args) -{ +int f_sys_inotify_init_e(struct event_filler_arguments *args) { /* Parameter 1: flags (type: PT_UINT8) */ /* We have nothing to extract from the kernel here so we send `0`. * This is done to preserve the `PPME_SYSCALL_INOTIFY_INIT_E` event with 1 param. @@ -5429,8 +5266,7 @@ int f_sys_inotify_init_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_inotify_init1_x(struct event_filler_arguments *args) -{ +int f_sys_inotify_init1_x(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; @@ -5447,8 +5283,7 @@ int f_sys_inotify_init1_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mlock_x(struct event_filler_arguments *args) -{ +int f_sys_mlock_x(struct event_filler_arguments *args) { unsigned long val; int64_t retval = (int64_t)syscall_get_return_value(current, args->regs); @@ -5470,8 +5305,7 @@ int f_sys_mlock_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mlock2_x(struct event_filler_arguments *args) -{ +int f_sys_mlock2_x(struct event_filler_arguments *args) { unsigned long val; int64_t retval = (int64_t)syscall_get_return_value(current, args->regs); @@ -5499,8 +5333,7 @@ int f_sys_mlock2_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_munlock_x(struct event_filler_arguments *args) -{ +int f_sys_munlock_x(struct event_filler_arguments *args) { unsigned long val; int64_t retval = (int64_t)syscall_get_return_value(current, args->regs); @@ -5522,8 +5355,7 @@ int f_sys_munlock_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mlockall_x(struct event_filler_arguments *args) -{ +int f_sys_mlockall_x(struct event_filler_arguments *args) { unsigned long val; int64_t retval = (int64_t)syscall_get_return_value(current, args->regs); @@ -5539,8 +5371,7 @@ int f_sys_mlockall_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_munlockall_x(struct event_filler_arguments *args) -{ +int f_sys_munlockall_x(struct event_filler_arguments *args) { int64_t retval = (int64_t)syscall_get_return_value(current, args->regs); int res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); @@ -5548,8 +5379,7 @@ int f_sys_munlockall_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fsconfig_x(struct event_filler_arguments *args) -{ +int f_sys_fsconfig_x(struct event_filler_arguments *args) { unsigned long res = 0; int64_t ret = 0; @@ -5586,8 +5416,7 @@ int f_sys_fsconfig_x(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 4, 1, &aux); - if(ret < 0) - { + if(ret < 0) { /* If the syscall fails we push empty params to userspace. */ /* Parameter 5: value_bytebuf (type: PT_BYTEBUF) */ @@ -5597,15 +5426,13 @@ int f_sys_fsconfig_x(struct event_filler_arguments *args) /* Parameter 6: value_charbuf (type: PT_CHARBUF) */ res = val_to_ring(args, 0, 0, true, 0); CHECK_RES(res); - } - else - { + } else { syscall_get_arguments_deprecated(args, 3, 1, &value_pointer); - /* According to the command we need to understand what value we have to push to userspace. */ + /* According to the command we need to understand what value we have to push to userspace. + */ /* see https://elixir.bootlin.com/linux/latest/source/fs/fsopen.c#L271 */ - switch(scap_cmd) - { + switch(scap_cmd) { case PPM_FSCONFIG_SET_FLAG: case PPM_FSCONFIG_SET_FD: case PPM_FSCONFIG_CMD_CREATE: @@ -5671,8 +5498,7 @@ int f_sys_fsconfig_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_signalfd_e(struct event_filler_arguments *args) -{ +int f_sys_signalfd_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -5698,8 +5524,7 @@ int f_sys_signalfd_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_signalfd4_e(struct event_filler_arguments *args) -{ +int f_sys_signalfd4_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -5718,8 +5543,7 @@ int f_sys_signalfd4_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_signalfd4_x(struct event_filler_arguments *args) -{ +int f_sys_signalfd4_x(struct event_filler_arguments *args) { int res = 0; unsigned long val = 0; long retval = 0; @@ -5737,8 +5561,7 @@ int f_sys_signalfd4_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_epoll_create_e(struct event_filler_arguments *args) -{ +int f_sys_epoll_create_e(struct event_filler_arguments *args) { unsigned long size; int res; @@ -5752,8 +5575,7 @@ int f_sys_epoll_create_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_epoll_create_x(struct event_filler_arguments *args) -{ +int f_sys_epoll_create_x(struct event_filler_arguments *args) { int64_t retval; int res; @@ -5764,8 +5586,7 @@ int f_sys_epoll_create_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_epoll_create1_e(struct event_filler_arguments *args) -{ +int f_sys_epoll_create1_e(struct event_filler_arguments *args) { unsigned long flags; int res; @@ -5779,8 +5600,7 @@ int f_sys_epoll_create1_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_epoll_create1_x(struct event_filler_arguments *args) -{ +int f_sys_epoll_create1_x(struct event_filler_arguments *args) { int64_t retval; int res; @@ -5791,8 +5611,7 @@ int f_sys_epoll_create1_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_dup_e(struct event_filler_arguments *args) -{ +int f_sys_dup_e(struct event_filler_arguments *args) { int res; unsigned long val; int32_t fd = 0; @@ -5801,15 +5620,14 @@ int f_sys_dup_e(struct event_filler_arguments *args) * oldfd */ syscall_get_arguments_deprecated(args, 0, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_dup_x(struct event_filler_arguments *args) -{ +int f_sys_dup_x(struct event_filler_arguments *args) { int res; unsigned long val; int32_t fd = 0; @@ -5822,15 +5640,14 @@ int f_sys_dup_x(struct event_filler_arguments *args) * oldfd */ syscall_get_arguments_deprecated(args, 0, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_dup2_e(struct event_filler_arguments *args) -{ +int f_sys_dup2_e(struct event_filler_arguments *args) { int res; unsigned long val; int32_t fd = 0; @@ -5839,15 +5656,14 @@ int f_sys_dup2_e(struct event_filler_arguments *args) * oldfd */ syscall_get_arguments_deprecated(args, 0, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_dup2_x(struct event_filler_arguments *args) -{ +int f_sys_dup2_x(struct event_filler_arguments *args) { int res; unsigned long val; int32_t fd = 0; @@ -5860,7 +5676,7 @@ int f_sys_dup2_x(struct event_filler_arguments *args) * oldfd */ syscall_get_arguments_deprecated(args, 0, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); @@ -5868,15 +5684,14 @@ int f_sys_dup2_x(struct event_filler_arguments *args) * newfd */ syscall_get_arguments_deprecated(args, 1, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int32_t)fd, 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_dup3_e(struct event_filler_arguments *args) -{ +int f_sys_dup3_e(struct event_filler_arguments *args) { int res; unsigned long val; int32_t fd = 0; @@ -5885,15 +5700,14 @@ int f_sys_dup3_e(struct event_filler_arguments *args) * oldfd */ syscall_get_arguments_deprecated(args, 0, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_dup3_x(struct event_filler_arguments *args) -{ +int f_sys_dup3_x(struct event_filler_arguments *args) { int res; unsigned long val; int32_t fd = 0; @@ -5906,7 +5720,7 @@ int f_sys_dup3_x(struct event_filler_arguments *args) * oldfd */ syscall_get_arguments_deprecated(args, 0, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); @@ -5914,7 +5728,7 @@ int f_sys_dup3_x(struct event_filler_arguments *args) * newfd */ syscall_get_arguments_deprecated(args, 1, 1, &val); - fd = (int32_t) val; + fd = (int32_t)val; res = val_to_ring(args, (int64_t)fd, 0, false, 0); CHECK_RES(res); @@ -5922,7 +5736,7 @@ int f_sys_dup3_x(struct event_filler_arguments *args) * flags */ syscall_get_arguments_deprecated(args, 2, 1, &val); - res = val_to_ring(args, dup3_flags_to_scap((int) val), 0, false, 0); + res = val_to_ring(args, dup3_flags_to_scap((int)val), 0, false, 0); CHECK_RES(res); return add_sentinel(args); @@ -5935,16 +5749,15 @@ int f_sys_dup3_x(struct event_filler_arguments *args) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 4, 0) -static pid_t find_alive_thread(struct task_struct *father) -{ +static pid_t find_alive_thread(struct task_struct *father) { struct task_struct *t = father; #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 19, 0) while_each_thread(father, t) { -#else /* Kernel 3.19.0 switched to `for_each_thread` macro */ +#else /* Kernel 3.19.0 switched to `for_each_thread` macro */ for_each_thread(father, t) { #endif /* LINUX_VERSION_CODE < KERNEL_VERSION(3, 19, 0) */ /* We add an extra check here for `t != NULL` just to be sure */ - if (t != NULL && (!(t->flags & PF_EXITING))) + if(t != NULL && (!(t->flags & PF_EXITING))) return t->pid; } return 0; @@ -5956,8 +5769,7 @@ static pid_t find_alive_thread(struct task_struct *father) * child_subreaper for its children (like a service manager) * 3. give it to the init process (PID 1) in our pid namespace */ -static pid_t find_new_reaper_pid(struct task_struct *father) -{ +static pid_t find_new_reaper_pid(struct task_struct *father) { struct task_struct *possible_reaper; /* This is the namespace level of the thread that is dying, we will * use it to check that the reaper will be always in the same namespace. @@ -5969,8 +5781,7 @@ static pid_t find_new_reaper_pid(struct task_struct *father) pid_t reaper_pid = find_alive_thread(father); /* If `reaper_pid!=0` when we found an alive thread, that's enough */ - if(reaper_pid != 0) - { + if(reaper_pid != 0) { return reaper_pid; } @@ -5979,14 +5790,12 @@ static pid_t find_new_reaper_pid(struct task_struct *father) * The kernel will destroy all the processes in that namespace. We send a reaper equal to * `0` in userspace. */ - if(child_ns_reaper == father) - { + if(child_ns_reaper == father) { return 0; } /* If there are no sub reapers the reaper is the init process of that namespace */ - if(!father->signal->has_child_subreaper) - { + if(!father->signal->has_child_subreaper) { return child_ns_reaper->pid; } @@ -5998,26 +5807,21 @@ static pid_t find_new_reaper_pid(struct task_struct *father) * We check pid->level, this is slightly more efficient than * task_active_pid_ns(reaper) != task_active_pid_ns(father). */ - for(possible_reaper = father->real_parent; - task_pid(possible_reaper)->level == father_ns_level; - possible_reaper = possible_reaper->real_parent) - { + for(possible_reaper = father->real_parent; task_pid(possible_reaper)->level == father_ns_level; + possible_reaper = possible_reaper->real_parent) { /* Here we could also check for child_ns_reaper * but the kernel checks against init_task, so we are fine. */ - if(possible_reaper == &init_task) - { + if(possible_reaper == &init_task) { return child_ns_reaper->pid; } - if(!possible_reaper->signal->is_child_subreaper) - { + if(!possible_reaper->signal->is_child_subreaper) { continue; } reaper_pid = find_alive_thread(possible_reaper); - if(reaper_pid != 0) - { + if(reaper_pid != 0) { return reaper_pid; } } @@ -6026,21 +5830,18 @@ static pid_t find_new_reaper_pid(struct task_struct *father) } #else -static pid_t find_new_reaper_pid(struct task_struct *father) -{ +static pid_t find_new_reaper_pid(struct task_struct *father) { return -1; } #endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(3, 4, 0) */ - -int f_sys_procexit_e(struct event_filler_arguments *args) -{ +int f_sys_procexit_e(struct event_filler_arguments *args) { int res; pid_t reaper_pid = 0; - if (args->sched_prev == NULL) { + if(args->sched_prev == NULL) { ASSERT(false); return -1; } @@ -6055,8 +5856,7 @@ int f_sys_procexit_e(struct event_filler_arguments *args) /* Parameter 3: sig (type: PT_SIGTYPE) */ /* If signaled -> signum, else 0 */ - if (__WIFSIGNALED(args->sched_prev->exit_code)) - { + if(__WIFSIGNALED(args->sched_prev->exit_code)) { res = val_to_ring(args, __WTERMSIG(args->sched_prev->exit_code), 0, false, 0); } else { res = val_to_ring(args, 0, 0, false, 0); @@ -6073,8 +5873,7 @@ int f_sys_procexit_e(struct event_filler_arguments *args) * We send `reaper_pid==0` if the userspace still has some children * it will manage them with its userspace logic. */ - if(!list_empty(¤t->children)) - { + if(!list_empty(¤t->children)) { /* We have at least one child, so we need a reaper for it */ reaper_pid = find_new_reaper_pid(current); } @@ -6084,8 +5883,7 @@ int f_sys_procexit_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_sendfile_e(struct event_filler_arguments *args) -{ +int f_sys_sendfile_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; off_t offset = 0; @@ -6104,13 +5902,12 @@ int f_sys_sendfile_e(struct event_filler_arguments *args) res = val_to_ring(args, (int64_t)in_fd, 0, true, 0); CHECK_RES(res); - /* Parameter 3: offset (type: PT_UINT64) */ syscall_get_arguments_deprecated(args, 2, 1, &val); - if (val != 0) { + if(val != 0) { #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif res = ppm_copy_from_user(&offset, (void *)val, sizeof(off_t)); #ifdef CONFIG_COMPAT @@ -6118,7 +5915,7 @@ int f_sys_sendfile_e(struct event_filler_arguments *args) res = ppm_copy_from_user(&offset, (void *)compat_ptr(val), sizeof(compat_off_t)); } #endif - if (unlikely(res)) + if(unlikely(res)) val = 0; else val = offset; @@ -6135,8 +5932,7 @@ int f_sys_sendfile_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_sendfile_x(struct event_filler_arguments *args) -{ +int f_sys_sendfile_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -6154,9 +5950,9 @@ int f_sys_sendfile_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); - if (val != 0) { + if(val != 0) { #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif res = ppm_copy_from_user(&offset, (void *)val, sizeof(off_t)); #ifdef CONFIG_COMPAT @@ -6164,7 +5960,7 @@ int f_sys_sendfile_x(struct event_filler_arguments *args) res = ppm_copy_from_user(&offset, (void *)compat_ptr(val), sizeof(compat_off_t)); } #endif - if (unlikely(res)) + if(unlikely(res)) val = 0; else val = offset; @@ -6176,8 +5972,7 @@ int f_sys_sendfile_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_quotactl_e(struct event_filler_arguments *args) -{ +int f_sys_quotactl_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; uint32_t id = 0; @@ -6199,24 +5994,18 @@ int f_sys_quotactl_e(struct event_filler_arguments *args) /* Parameter 3: id (type: PT_UINT32) */ syscall_get_arguments_deprecated(args, 2, 1, &val); id = (uint32_t)val; - if ((scap_cmd != PPM_Q_GETQUOTA) && - (scap_cmd != PPM_Q_SETQUOTA) && - (scap_cmd != PPM_Q_XGETQUOTA) && - (scap_cmd != PPM_Q_XSETQLIM)) - { + if((scap_cmd != PPM_Q_GETQUOTA) && (scap_cmd != PPM_Q_SETQUOTA) && + (scap_cmd != PPM_Q_XGETQUOTA) && (scap_cmd != PPM_Q_XSETQLIM)) { /* In this case `id` don't represent a `userid` or a `groupid` */ res = val_to_ring(args, 0, 0, false, 0); - } - else - { + } else { res = val_to_ring(args, id, 0, false, 0); } CHECK_RES(res); /* Parameter 4: quota_fmt (type: PT_FLAGS8) */ quota_fmt = PPM_QFMT_NOT_USED; - if(scap_cmd == PPM_Q_QUOTAON) - { + if(scap_cmd == PPM_Q_QUOTAON) { quota_fmt = quotactl_fmt_to_scap(id); } res = val_to_ring(args, quota_fmt, 0, false, 0); @@ -6225,8 +6014,7 @@ int f_sys_quotactl_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_quotactl_x(struct event_filler_arguments *args) -{ +int f_sys_quotactl_x(struct event_filler_arguments *args) { unsigned long val, len; int res; int64_t retval; @@ -6263,24 +6051,23 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) /* * get quotafilepath only for QUOTAON */ - if (cmd == PPM_Q_QUOTAON) + if(cmd == PPM_Q_QUOTAON) res = val_to_ring(args, val, 0, true, 0); else res = val_to_ring(args, 0, 0, false, 0); CHECK_RES(res); - /* * dqblk fields if present */ dqblk.dqb_valid = 0; - if ((cmd == PPM_Q_GETQUOTA) || (cmd == PPM_Q_SETQUOTA)) { + if((cmd == PPM_Q_GETQUOTA) || (cmd == PPM_Q_SETQUOTA)) { len = ppm_copy_from_user(&dqblk, (void *)val, sizeof(struct if_dqblk)); - if (unlikely(len != 0)) + if(unlikely(len != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; } - if (dqblk.dqb_valid & QIF_BLIMITS) { + if(dqblk.dqb_valid & QIF_BLIMITS) { res = val_to_ring(args, dqblk.dqb_bhardlimit, 0, false, 0); CHECK_RES(res); res = val_to_ring(args, dqblk.dqb_bsoftlimit, 0, false, 0); @@ -6292,7 +6079,7 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_SPACE) { + if(dqblk.dqb_valid & QIF_SPACE) { res = val_to_ring(args, dqblk.dqb_curspace, 0, false, 0); CHECK_RES(res); } else { @@ -6300,7 +6087,7 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_ILIMITS) { + if(dqblk.dqb_valid & QIF_ILIMITS) { res = val_to_ring(args, dqblk.dqb_ihardlimit, 0, false, 0); CHECK_RES(res); res = val_to_ring(args, dqblk.dqb_isoftlimit, 0, false, 0); @@ -6312,7 +6099,7 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_BTIME) { + if(dqblk.dqb_valid & QIF_BTIME) { res = val_to_ring(args, dqblk.dqb_btime, 0, false, 0); CHECK_RES(res); } else { @@ -6320,7 +6107,7 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) CHECK_RES(res); } - if (dqblk.dqb_valid & QIF_ITIME) { + if(dqblk.dqb_valid & QIF_ITIME) { res = val_to_ring(args, dqblk.dqb_itime, 0, false, 0); CHECK_RES(res); } else { @@ -6332,13 +6119,13 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) * dqinfo fields if present */ dqinfo.dqi_valid = 0; - if ((cmd == PPM_Q_GETINFO) || (cmd == PPM_Q_SETINFO)) { + if((cmd == PPM_Q_GETINFO) || (cmd == PPM_Q_SETINFO)) { len = ppm_copy_from_user(&dqinfo, (void *)val, sizeof(struct if_dqinfo)); - if (unlikely(len != 0)) + if(unlikely(len != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; } - if (dqinfo.dqi_valid & IIF_BGRACE) { + if(dqinfo.dqi_valid & IIF_BGRACE) { res = val_to_ring(args, dqinfo.dqi_bgrace, 0, false, 0); CHECK_RES(res); } else { @@ -6346,7 +6133,7 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) CHECK_RES(res); } - if (dqinfo.dqi_valid & IIF_IGRACE) { + if(dqinfo.dqi_valid & IIF_IGRACE) { res = val_to_ring(args, dqinfo.dqi_igrace, 0, false, 0); CHECK_RES(res); } else { @@ -6354,7 +6141,7 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) CHECK_RES(res); } - if (dqinfo.dqi_valid & IIF_FLAGS) { + if(dqinfo.dqi_valid & IIF_FLAGS) { res = val_to_ring(args, dqinfo.dqi_flags, 0, false, 0); CHECK_RES(res); } else { @@ -6363,9 +6150,9 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) } quota_fmt_out = PPM_QFMT_NOT_USED; - if (cmd == PPM_Q_GETFMT) { + if(cmd == PPM_Q_GETFMT) { len = ppm_copy_from_user("a_fmt_out, (void *)val, sizeof(uint32_t)); - if (unlikely(len != 0)) + if(unlikely(len != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; quota_fmt_out = quotactl_fmt_to_scap(quota_fmt_out); } @@ -6375,8 +6162,7 @@ int f_sys_quotactl_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_scapevent_e(struct event_filler_arguments *args) -{ +int f_sys_scapevent_e(struct event_filler_arguments *args) { int res; /* @@ -6394,8 +6180,7 @@ int f_sys_scapevent_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_getresuid_and_gid_x(struct event_filler_arguments *args) -{ +int f_sys_getresuid_and_gid_x(struct event_filler_arguments *args) { int res; unsigned long val, len; uint32_t uid; @@ -6413,7 +6198,7 @@ int f_sys_getresuid_and_gid_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 0, 1, &val); #ifdef CONFIG_COMPAT - if (!args->compat) { + if(!args->compat) { #endif len = ppm_copy_from_user(&uid, (void *)val, sizeof(uint32_t)); #ifdef CONFIG_COMPAT @@ -6421,7 +6206,7 @@ int f_sys_getresuid_and_gid_x(struct event_filler_arguments *args) len = ppm_copy_from_user(&uid, (void *)compat_ptr(val), sizeof(uint32_t)); } #endif - if (unlikely(len != 0)) + if(unlikely(len != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; res = val_to_ring(args, uid, 0, false, 0); @@ -6432,7 +6217,7 @@ int f_sys_getresuid_and_gid_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 1, 1, &val); len = ppm_copy_from_user(&uid, (void *)val, sizeof(uint32_t)); - if (unlikely(len != 0)) + if(unlikely(len != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; res = val_to_ring(args, uid, 0, false, 0); @@ -6443,7 +6228,7 @@ int f_sys_getresuid_and_gid_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 2, 1, &val); len = ppm_copy_from_user(&uid, (void *)val, sizeof(uint32_t)); - if (unlikely(len != 0)) + if(unlikely(len != 0)) return PPM_FAILURE_INVALID_USER_MEMORY; res = val_to_ring(args, uid, 0, false, 0); @@ -6452,8 +6237,7 @@ int f_sys_getresuid_and_gid_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_flock_e(struct event_filler_arguments *args) -{ +int f_sys_flock_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; uint32_t flags = 0; @@ -6467,15 +6251,14 @@ int f_sys_flock_e(struct event_filler_arguments *args) /* Parameter 2: operation (type: PT_FLAGS32) */ syscall_get_arguments_deprecated(args, 1, 1, &val); - flags = flock_flags_to_scap((int) val); + flags = flock_flags_to_scap((int)val); res = val_to_ring(args, flags, 0, false, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_ioctl_e(struct event_filler_arguments *args) -{ +int f_sys_ioctl_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -6499,8 +6282,7 @@ int f_sys_ioctl_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mkdir_e(struct event_filler_arguments *args) -{ +int f_sys_mkdir_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; @@ -6512,8 +6294,7 @@ int f_sys_mkdir_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_setns_e(struct event_filler_arguments *args) -{ +int f_sys_setns_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int32_t fd = 0; @@ -6526,14 +6307,13 @@ int f_sys_setns_e(struct event_filler_arguments *args) /* Parameter 2: nstype (type: PT_FLAGS32) */ syscall_get_arguments_deprecated(args, 1, 1, &val); - res = val_to_ring(args, clone_flags_to_scap((int) val), 0, true, 0); + res = val_to_ring(args, clone_flags_to_scap((int)val), 0, true, 0); CHECK_RES(res); return add_sentinel(args); } -int f_sys_setpgid_e(struct event_filler_arguments *args) -{ +int f_sys_setpgid_e(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; pid_t pid = 0; @@ -6554,8 +6334,7 @@ int f_sys_setpgid_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_unshare_e(struct event_filler_arguments *args) -{ +int f_sys_unshare_e(struct event_filler_arguments *args) { unsigned long val; int res; uint32_t flags; @@ -6564,7 +6343,7 @@ int f_sys_unshare_e(struct event_filler_arguments *args) * get type, parse as clone flags as it's a subset of it */ syscall_get_arguments_deprecated(args, 0, 1, &val); - flags = clone_flags_to_scap((int) val); + flags = clone_flags_to_scap((int)val); res = val_to_ring(args, flags, 0, true, 0); CHECK_RES(res); @@ -6572,8 +6351,7 @@ int f_sys_unshare_e(struct event_filler_arguments *args) } #ifdef CAPTURE_SIGNAL_DELIVERIES -int f_sys_signaldeliver_e(struct event_filler_arguments *args) -{ +int f_sys_signaldeliver_e(struct event_filler_arguments *args) { int res; /* @@ -6599,8 +6377,7 @@ int f_sys_signaldeliver_e(struct event_filler_arguments *args) #endif #ifdef CAPTURE_PAGE_FAULTS -int f_sys_pagefault_e(struct event_filler_arguments *args) -{ +int f_sys_pagefault_e(struct event_filler_arguments *args) { int res; res = val_to_ring(args, args->fault_data.address, 0, false, 0); @@ -6616,8 +6393,7 @@ int f_sys_pagefault_e(struct event_filler_arguments *args) } #endif -int f_cpu_hotplug_e(struct event_filler_arguments *args) -{ +int f_cpu_hotplug_e(struct event_filler_arguments *args) { int res; /* @@ -6635,9 +6411,8 @@ int f_cpu_hotplug_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_semop_x(struct event_filler_arguments *args) -{ - unsigned long nsops = 0 ; +int f_sys_semop_x(struct event_filler_arguments *args) { + unsigned long nsops = 0; int res = 0; long retval = 0; struct sembuf *sops_pointer = NULL; @@ -6654,29 +6429,22 @@ int f_sys_semop_x(struct event_filler_arguments *args) CHECK_RES(res); /* Extract pointer to the `sembuf` struct */ - syscall_get_arguments_deprecated(args, 1, 1, (unsigned long *) &sops_pointer); + syscall_get_arguments_deprecated(args, 1, 1, (unsigned long *)&sops_pointer); - if(retval != 0 || sops_pointer == 0 || nsops == 0) - { + if(retval != 0 || sops_pointer == 0 || nsops == 0) { /* We send all 0 when one of these is true: * - the syscall fails (retval != 0) * - `sops_pointer` is NULL * - `nsops` is 0 */ - } - else if(nsops == 1) - { + } else if(nsops == 1) { /* If we have just one entry the second will be empty, we don't fill it */ - if(unlikely(ppm_copy_from_user(sops, (void *)sops_pointer, sizeof(struct sembuf)))) - { + if(unlikely(ppm_copy_from_user(sops, (void *)sops_pointer, sizeof(struct sembuf)))) { memset(&sops, 0, sizeof(sops)); } - } - else - { + } else { /* If `nsops>1` we read just the first 2 entries. */ - if(unlikely(ppm_copy_from_user(sops, (void *)sops_pointer, 2 * sizeof(struct sembuf)))) - { + if(unlikely(ppm_copy_from_user(sops, (void *)sops_pointer, 2 * sizeof(struct sembuf)))) { memset(&sops, 0, sizeof(sops)); } } @@ -6708,8 +6476,7 @@ int f_sys_semop_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_semget_e(struct event_filler_arguments *args) -{ +int f_sys_semget_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -6737,8 +6504,7 @@ int f_sys_semget_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_semctl_e(struct event_filler_arguments *args) -{ +int f_sys_semctl_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -6766,7 +6532,7 @@ int f_sys_semctl_e(struct event_filler_arguments *args) /* * optional argument semun/val */ - if (val == SETVAL) + if(val == SETVAL) syscall_get_arguments_deprecated(args, 3, 1, &val); else val = 0; @@ -6776,8 +6542,7 @@ int f_sys_semctl_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_access_e(struct event_filler_arguments *args) -{ +int f_sys_access_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -6791,8 +6556,7 @@ int f_sys_access_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fchdir_e(struct event_filler_arguments *args) -{ +int f_sys_fchdir_e(struct event_filler_arguments *args) { int res = 0; int32_t fd = 0; unsigned long val = 0; @@ -6805,8 +6569,7 @@ int f_sys_fchdir_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fchdir_x(struct event_filler_arguments *args) -{ +int f_sys_fchdir_x(struct event_filler_arguments *args) { int64_t res = 0; /* Parameter 1: res (type: PT_ERRNO)*/ @@ -6816,8 +6579,7 @@ int f_sys_fchdir_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_close_e(struct event_filler_arguments *args) -{ +int f_sys_close_e(struct event_filler_arguments *args) { int res = 0; int32_t fd = 0; unsigned long val = 0; @@ -6830,8 +6592,7 @@ int f_sys_close_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_close_x(struct event_filler_arguments *args) -{ +int f_sys_close_x(struct event_filler_arguments *args) { int64_t res = 0; /* Parameter 1: res (type: PT_ERRNO)*/ @@ -6841,8 +6602,7 @@ int f_sys_close_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_bpf_e(struct event_filler_arguments *args) -{ +int f_sys_bpf_e(struct event_filler_arguments *args) { int res = 0; int32_t cmd = 0; unsigned long val = 0; @@ -6855,8 +6615,7 @@ int f_sys_bpf_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_bpf_x(struct event_filler_arguments *args) -{ +int f_sys_bpf_x(struct event_filler_arguments *args) { int res = 0; int64_t fd = 0; unsigned long val = 0; @@ -6875,8 +6634,7 @@ int f_sys_bpf_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mkdirat_x(struct event_filler_arguments *args) -{ +int f_sys_mkdirat_x(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int64_t retval = 0; @@ -6890,8 +6648,7 @@ int f_sys_mkdirat_x(struct event_filler_arguments *args) /* Parameter 2: dirfd (type: PT_FD) */ syscall_get_arguments_deprecated(args, 0, 1, &val); dirfd = (int32_t)val; - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } res = val_to_ring(args, (int64_t)dirfd, 0, false, 0); @@ -6910,8 +6667,7 @@ int f_sys_mkdirat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fchmodat_x(struct event_filler_arguments *args) -{ +int f_sys_fchmodat_x(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int64_t retval = 0; @@ -6925,8 +6681,7 @@ int f_sys_fchmodat_x(struct event_filler_arguments *args) /* Parameter 2: dirfd (type: PT_FD) */ syscall_get_arguments_deprecated(args, 0, 1, &val); dirfd = (int32_t)val; - if(dirfd == AT_FDCWD) - { + if(dirfd == AT_FDCWD) { dirfd = PPM_AT_FDCWD; } res = val_to_ring(args, (int64_t)dirfd, 0, false, 0); @@ -6945,8 +6700,7 @@ int f_sys_fchmodat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_chmod_x(struct event_filler_arguments *args) -{ +int f_sys_chmod_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -6972,8 +6726,7 @@ int f_sys_chmod_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fchmod_x(struct event_filler_arguments *args) -{ +int f_sys_fchmod_x(struct event_filler_arguments *args) { unsigned long val = 0; int res = 0; int64_t retval = 0; @@ -6998,8 +6751,7 @@ int f_sys_fchmod_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_chown_x(struct event_filler_arguments *args) -{ +int f_sys_chown_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -7030,8 +6782,7 @@ int f_sys_chown_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_lchown_x(struct event_filler_arguments *args) -{ +int f_sys_lchown_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -7062,8 +6813,7 @@ int f_sys_lchown_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fchown_x(struct event_filler_arguments *args) -{ +int f_sys_fchown_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -7095,8 +6845,7 @@ int f_sys_fchown_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_fchownat_x(struct event_filler_arguments *args) -{ +int f_sys_fchownat_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -7111,7 +6860,7 @@ int f_sys_fchownat_x(struct event_filler_arguments *args) syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, false, 0); @@ -7143,8 +6892,7 @@ int f_sys_fchownat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_capset_x(struct event_filler_arguments *args) -{ +int f_sys_capset_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -7191,8 +6939,7 @@ int f_sys_capset_x(struct event_filler_arguments *args) return res; } -int f_sys_splice_e(struct event_filler_arguments *args) -{ +int f_sys_splice_e(struct event_filler_arguments *args) { unsigned long val; int32_t fd_in, fd_out; int res; @@ -7222,8 +6969,7 @@ int f_sys_splice_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_umount_x(struct event_filler_arguments *args) -{ +int f_sys_umount_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -7241,8 +6987,7 @@ int f_sys_umount_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_umount2_e(struct event_filler_arguments *args) -{ +int f_sys_umount2_e(struct event_filler_arguments *args) { unsigned long val; int res; @@ -7254,8 +6999,7 @@ int f_sys_umount2_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_umount2_x(struct event_filler_arguments *args) -{ +int f_sys_umount2_x(struct event_filler_arguments *args) { unsigned long val; int res; int64_t retval; @@ -7273,8 +7017,7 @@ int f_sys_umount2_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_getcwd_x(struct event_filler_arguments *args) -{ +int f_sys_getcwd_x(struct event_filler_arguments *args) { unsigned long val; /* Parameter 1: res (type: PT_ERRNO) */ @@ -7282,15 +7025,13 @@ int f_sys_getcwd_x(struct event_filler_arguments *args) int res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - /* we get the path only in case of success, in case of failure we would read only userspace junk */ - if(retval >= 0) - { + /* we get the path only in case of success, in case of failure we would read only userspace junk + */ + if(retval >= 0) { /* Parameter 2: path (type: PT_CHARBUF) */ syscall_get_arguments_deprecated(args, 0, 1, &val); res = val_to_ring(args, val, 0, true, 0); - } - else - { + } else { /* Parameter 2: path (type: PT_CHARBUF) */ push_empty_param(args); } @@ -7300,8 +7041,7 @@ int f_sys_getcwd_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_getdents_e(struct event_filler_arguments *args) -{ +int f_sys_getdents_e(struct event_filler_arguments *args) { unsigned long val; int32_t fd = 0; int res; @@ -7315,8 +7055,7 @@ int f_sys_getdents_e(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_getdents64_e(struct event_filler_arguments *args) -{ +int f_sys_getdents64_e(struct event_filler_arguments *args) { unsigned long val; int32_t fd = 0; int res; @@ -7331,8 +7070,7 @@ int f_sys_getdents64_e(struct event_filler_arguments *args) } #ifdef CAPTURE_SCHED_PROC_EXEC -int f_sched_prog_exec(struct event_filler_arguments *args) -{ +int f_sched_prog_exec(struct event_filler_arguments *args) { int res = 0; struct mm_struct *mm = current->mm; int args_len = 0; @@ -7358,7 +7096,7 @@ int f_sched_prog_exec(struct event_filler_arguments *args) uint64_t cap_permitted = 0; uint64_t cap_effective = 0; uint32_t euid = UINT32_MAX; - char* buf = (char*)args->str_storage; + char *buf = (char *)args->str_storage; char *trusted_exepath = NULL; /* Parameter 1: res (type: PT_ERRNO) */ @@ -7368,19 +7106,17 @@ int f_sched_prog_exec(struct event_filler_arguments *args) res = val_to_ring(args, 0, 0, false, 0); CHECK_RES(res); /* - * The call always succeed so get `exe`, `args` from the current - * process; put one \0-separated exe-args string into - * str_storage - */ - if(unlikely(!mm)) - { + * The call always succeed so get `exe`, `args` from the current + * process; put one \0-separated exe-args string into + * str_storage + */ + if(unlikely(!mm)) { args->str_storage[0] = 0; pr_info("'f_sched_prog_exec' drop, mm=NULL\n"); return PPM_FAILURE_BUG; } - if(unlikely(!mm->arg_end)) - { + if(unlikely(!mm->arg_end)) { args->str_storage[0] = 0; pr_info("'f_sched_prog_exec' drop, mm->arg_end=NULL\n"); return PPM_FAILURE_BUG; @@ -7389,26 +7125,22 @@ int f_sched_prog_exec(struct event_filler_arguments *args) /* the combined length of the arguments string + executable string. */ args_len = mm->arg_end - mm->arg_start; - if(args_len > STR_STORAGE_SIZE) - { + if(args_len > STR_STORAGE_SIZE) { args_len = STR_STORAGE_SIZE; } - correctly_read = ppm_copy_from_user(args->str_storage, (const void __user *)mm->arg_start, args_len); + correctly_read = + ppm_copy_from_user(args->str_storage, (const void __user *)mm->arg_start, args_len); - if(args_len && correctly_read == 0) - { + if(args_len && correctly_read == 0) { args->str_storage[args_len - 1] = 0; - } - else - { + } else { args_len = 0; *args->str_storage = 0; } exe_len = strnlen(args->str_storage, args_len); - if(exe_len < args_len) - { + if(exe_len < args_len) { ++exe_len; } @@ -7417,7 +7149,11 @@ int f_sched_prog_exec(struct event_filler_arguments *args) CHECK_RES(res); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ - res = val_to_ring(args, (int64_t)(long)args->str_storage + exe_len, args_len - exe_len, false, 0); + res = val_to_ring(args, + (int64_t)(long)args->str_storage + exe_len, + args_len - exe_len, + false, + 0); CHECK_RES(res); /* Parameter 4: tid (type: PT_PID) */ @@ -7429,8 +7165,7 @@ int f_sched_prog_exec(struct event_filler_arguments *args) CHECK_RES(res); /* Parameter 6: ptid (type: PT_PID) */ - if(current->real_parent) - { + if(current->real_parent) { ptid = current->real_parent->pid; } @@ -7456,8 +7191,7 @@ int f_sched_prog_exec(struct event_filler_arguments *args) res = val_to_ring(args, current->min_flt, 0, false, 0); CHECK_RES(res); - if(mm) - { + if(mm) { total_vm = mm->total_vm << (PAGE_SHIFT - 10); total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT - 10); swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT - 10); @@ -7488,23 +7222,24 @@ int f_sched_prog_exec(struct event_filler_arguments *args) #endif /* Parameter 15: cgroups (type: PT_CHARBUFARRAY) */ - res = val_to_ring(args, (int64_t)(long)args->str_storage, STR_STORAGE_SIZE - available, false, 0); + res = val_to_ring(args, + (int64_t)(long)args->str_storage, + STR_STORAGE_SIZE - available, + false, + 0); CHECK_RES(res); env_len = mm->env_end - mm->env_start; - if(env_len > STR_STORAGE_SIZE) - { + if(env_len > STR_STORAGE_SIZE) { env_len = STR_STORAGE_SIZE; } - correctly_read = ppm_copy_from_user(args->str_storage, (const void __user *)mm->env_start, env_len); + correctly_read = + ppm_copy_from_user(args->str_storage, (const void __user *)mm->env_start, env_len); - if(env_len && correctly_read == 0) - { + if(env_len && correctly_read == 0) { args->str_storage[env_len - 1] = 0; - } - else - { + } else { env_len = 0; *args->str_storage = 0; } @@ -7519,7 +7254,11 @@ int f_sched_prog_exec(struct event_filler_arguments *args) CHECK_RES(res); /* Parameter 18: pgid (type: PT_PID) */ - res = val_to_ring(args, (int64_t)task_pgrp_nr_ns(current, task_active_pid_ns(current)), 0, false, 0); + res = val_to_ring(args, + (int64_t)task_pgrp_nr_ns(current, task_active_pid_ns(current)), + 0, + false, + 0); CHECK_RES(res); /* Parameter 19: loginuid (type: PT_UID) */ @@ -7533,28 +7272,30 @@ int f_sched_prog_exec(struct event_filler_arguments *args) /* `exe_writable`, `exe_upper_layer` and `exe_lower_layer` flag logic */ exe_file = ppm_get_mm_exe_file(mm); - if(exe_file != NULL) - { - if(file_inode(exe_file) != NULL) - { + if(exe_file != NULL) { + if(file_inode(exe_file) != NULL) { /* Support exe_writable */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) exe_writable |= (file_permission(exe_file, MAY_WRITE | MAY_NOT_BLOCK) == 0); exe_writable |= inode_owner_or_capable(file_mnt_idmap(exe_file), file_inode(exe_file)); #elif LINUX_VERSION_CODE >= KERNEL_VERSION(5, 12, 0) - exe_writable |= (inode_permission(current_user_ns(), file_inode(exe_file), MAY_WRITE | MAY_NOT_BLOCK) == 0); + exe_writable |= (inode_permission(current_user_ns(), + file_inode(exe_file), + MAY_WRITE | MAY_NOT_BLOCK) == 0); exe_writable |= inode_owner_or_capable(current_user_ns(), file_inode(exe_file)); #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 1, 0) - exe_writable |= (inode_permission(file_inode(exe_file), MAY_WRITE | MAY_NOT_BLOCK) == 0); + exe_writable |= + (inode_permission(file_inode(exe_file), MAY_WRITE | MAY_NOT_BLOCK) == 0); exe_writable |= inode_owner_or_capable(file_inode(exe_file)); #endif /* - * Kernels < 3.1.0 doesn't support the exe_writable flags due to the MAY_NOT_BLOCK not being - * available. This limitation is related to the fact that this function (f_sched_prog_exec) - * is in a RCU critical section: this means that this function (and its callee) MUST NOT - * call functions that can yield the processor (e.g. inode_permission that deep down in its - * call stack calls a down_read()). This is addressed after the Kernel 3.1.0 where the - * MAY_OT_BLOCK flag is introduced and avoids the processor to being yield. + * Kernels < 3.1.0 doesn't support the exe_writable flags due to the MAY_NOT_BLOCK not + * being available. This limitation is related to the fact that this function + * (f_sched_prog_exec) is in a RCU critical section: this means that this function (and + * its callee) MUST NOT call functions that can yield the processor (e.g. + * inode_permission that deep down in its call stack calls a down_read()). This is + * addressed after the Kernel 3.1.0 where the MAY_OT_BLOCK flag is introduced and avoids + * the processor to being yield. */ /* Support exe_upper_layer and exe_lower_layer */ @@ -7567,22 +7308,23 @@ int f_sched_prog_exec(struct event_filler_arguments *args) i_ino = file_inode(exe_file)->i_ino; /* Support exe_file ctime - * During kernel versions `i_ctime` changed from `struct timespec` to `struct timespec64` - * but fields names should be always the same. + * During kernel versions `i_ctime` changed from `struct timespec` to `struct + * timespec64` but fields names should be always the same. */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 6, 0) { struct timespec64 inode_ctime; inode_ctime = inode_get_ctime(file_inode(exe_file)); - ctime = inode_ctime.tv_sec * (uint64_t) 1000000000 + inode_ctime.tv_nsec; + ctime = inode_ctime.tv_sec * (uint64_t)1000000000 + inode_ctime.tv_nsec; } #else - ctime = file_inode(exe_file)->i_ctime.tv_sec * (uint64_t) 1000000000 + file_inode(exe_file)->i_ctime.tv_nsec; + ctime = file_inode(exe_file)->i_ctime.tv_sec * (uint64_t)1000000000 + + file_inode(exe_file)->i_ctime.tv_nsec; #endif /* Support exe_file mtime - * During kernel versions `i_mtime` changed from `struct timespec` to `struct timespec64` - * but fields names should be always the same. + * During kernel versions `i_mtime` changed from `struct timespec` to `struct + * timespec64` but fields names should be always the same. */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 7, 0) { @@ -7591,7 +7333,8 @@ int f_sched_prog_exec(struct event_filler_arguments *args) mtime = inode_mtime.tv_sec * (uint64_t)1000000000 + inode_mtime.tv_nsec; } #else - mtime = file_inode(exe_file)->i_mtime.tv_sec * (uint64_t) 1000000000 + file_inode(exe_file)->i_mtime.tv_nsec; + mtime = file_inode(exe_file)->i_mtime.tv_sec * (uint64_t)1000000000 + + file_inode(exe_file)->i_mtime.tv_nsec; #endif } /* Before free the exefile we catch the resolved path for symlink resolution */ @@ -7603,28 +7346,22 @@ int f_sched_prog_exec(struct event_filler_arguments *args) * https://github.com/torvalds/linux/blob/2dde18cd1d8fac735875f2e4987f11817cc0bc2c/fs/d_path.c#L255 * This is unhandy to manage in userspace, for this reason, we can remove it here */ - if(trusted_exepath != NULL) - { + if(trusted_exepath != NULL) { char deleted_suffix[] = " (deleted)"; int diff_len = strlen(trusted_exepath) - strlen(deleted_suffix); if(diff_len > 0 && - (strncmp(&trusted_exepath[diff_len], deleted_suffix, sizeof(deleted_suffix)) == 0)) - { + (strncmp(&trusted_exepath[diff_len], deleted_suffix, sizeof(deleted_suffix)) == 0)) { trusted_exepath[diff_len] = '\0'; } } - if(exe_writable) - { + if(exe_writable) { flags |= PPM_EXE_WRITABLE; } - if(exe_layer == PPM_OVERLAY_UPPER) - { + if(exe_layer == PPM_OVERLAY_UPPER) { flags |= PPM_EXE_UPPER_LAYER; - } - else if(exe_layer == PPM_OVERLAY_LOWER) - { + } else if(exe_layer == PPM_OVERLAY_LOWER) { flags |= PPM_EXE_LOWER_LAYER; } @@ -7670,11 +7407,13 @@ int f_sched_prog_exec(struct event_filler_arguments *args) res = val_to_ring(args, i_ino, 0, false, 0); CHECK_RES(res); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ res = val_to_ring(args, ctime, 0, false, 0); CHECK_RES(res); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ res = val_to_ring(args, mtime, 0, false, 0); CHECK_RES(res); @@ -7697,10 +7436,8 @@ int f_sched_prog_exec(struct event_filler_arguments *args) } #endif - #ifdef CAPTURE_SCHED_PROC_FORK -int f_sched_prog_fork(struct event_filler_arguments *args) -{ +int f_sched_prog_fork(struct event_filler_arguments *args) { int res = 0; struct task_struct *child = args->child; struct mm_struct *mm = child->mm; @@ -7726,19 +7463,17 @@ int f_sched_prog_fork(struct event_filler_arguments *args) CHECK_RES(res); /* - * The call always succeed so get `exe`, `args` from the child - * process; put one \0-separated exe-args string into - * str_storage - */ - if(unlikely(!mm)) - { + * The call always succeed so get `exe`, `args` from the child + * process; put one \0-separated exe-args string into + * str_storage + */ + if(unlikely(!mm)) { args->str_storage[0] = 0; pr_info("'f_sched_prog_fork' drop, mm=NULL\n"); return PPM_FAILURE_BUG; } - if(unlikely(!mm->arg_end)) - { + if(unlikely(!mm->arg_end)) { args->str_storage[0] = 0; pr_info("'f_sched_prog_fork' drop, mm->arg_end=NULL\n"); return PPM_FAILURE_BUG; @@ -7747,27 +7482,23 @@ int f_sched_prog_fork(struct event_filler_arguments *args) /* the combined length of the arguments string + executable string. */ args_len = mm->arg_end - mm->arg_start; - if(args_len > STR_STORAGE_SIZE) - { + if(args_len > STR_STORAGE_SIZE) { args_len = STR_STORAGE_SIZE; } - correctly_read = ppm_copy_from_user(args->str_storage, (const void __user *)mm->arg_start, args_len); + correctly_read = + ppm_copy_from_user(args->str_storage, (const void __user *)mm->arg_start, args_len); - if(args_len && correctly_read == 0) - { + if(args_len && correctly_read == 0) { args->str_storage[args_len - 1] = 0; - } - else - { + } else { args_len = 0; *args->str_storage = 0; } exe_len = strnlen(args->str_storage, args_len); // we add the `\0` terminator - if(exe_len < args_len) - { + if(exe_len < args_len) { ++exe_len; } @@ -7776,7 +7507,11 @@ int f_sched_prog_fork(struct event_filler_arguments *args) CHECK_RES(res); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ - res = val_to_ring(args, (int64_t)(long)args->str_storage + exe_len, args_len - exe_len, false, 0); + res = val_to_ring(args, + (int64_t)(long)args->str_storage + exe_len, + args_len - exe_len, + false, + 0); CHECK_RES(res); /* Parameter 4: tid (type: PT_PID) */ @@ -7788,8 +7523,7 @@ int f_sched_prog_fork(struct event_filler_arguments *args) CHECK_RES(res); /* Parameter 6: ptid (type: PT_PID) */ - if(child->real_parent) - { + if(child->real_parent) { ptid = child->real_parent->pid; } @@ -7815,8 +7549,7 @@ int f_sched_prog_fork(struct event_filler_arguments *args) res = val_to_ring(args, child->min_flt, 0, false, 0); CHECK_RES(res); - if(mm) - { + if(mm) { total_vm = mm->total_vm << (PAGE_SHIFT - 10); total_rss = ppm_get_mm_rss(mm) << (PAGE_SHIFT - 10); swap = ppm_get_mm_swap(mm) << (PAGE_SHIFT - 10); @@ -7847,7 +7580,11 @@ int f_sched_prog_fork(struct event_filler_arguments *args) #endif /* Parameter 15: cgroups (type: PT_CHARBUFARRAY) */ - res = val_to_ring(args, (int64_t)(long)args->str_storage, STR_STORAGE_SIZE - available, false, 0); + res = val_to_ring(args, + (int64_t)(long)args->str_storage, + STR_STORAGE_SIZE - available, + false, + 0); CHECK_RES(res); /* Since Linux 2.5.35, the flags mask must also include @@ -7856,8 +7593,7 @@ int f_sched_prog_fork(struct event_filler_arguments *args) * be included). * Taken from https://man7.org/linux/man-pages/man2/clone.2.html */ - if(child->pid != child->tgid) - { + if(child->pid != child->tgid) { flags |= PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM; } @@ -7865,8 +7601,7 @@ int f_sched_prog_fork(struct event_filler_arguments *args) * process share the same file descriptor table. * Taken from https://man7.org/linux/man-pages/man2/clone.2.html */ - if(child->files == current->files) - { + if(child->files == current->files) { flags |= PPM_CL_CLONE_FILES; } @@ -7874,8 +7609,7 @@ int f_sched_prog_fork(struct event_filler_arguments *args) * nevertheless has tid == vtid, so we need to generate this * custom flag `PPM_CL_CHILD_IN_PIDNS`. */ - if(pidns != &init_pid_ns) - { + if(pidns != &init_pid_ns) { flags |= PPM_CL_CHILD_IN_PIDNS; } @@ -7911,8 +7645,7 @@ int f_sched_prog_fork(struct event_filler_arguments *args) /* Here the father collects this info for the child. * Remember that this is the clone child event. */ - if(pidns && pidns->child_reaper) - { + if(pidns && pidns->child_reaper) { pidns_init_start_time = pidns->child_reaper->start_time; } res = val_to_ring(args, pidns_init_start_time, 0, false, 0); @@ -7926,8 +7659,7 @@ int f_sched_prog_fork(struct event_filler_arguments *args) } #endif -int f_sys_prctl_x(struct event_filler_arguments *args) -{ +int f_sys_prctl_x(struct event_filler_arguments *args) { int res; int retval; unsigned long option; @@ -7951,55 +7683,51 @@ int f_sys_prctl_x(struct event_filler_arguments *args) */ syscall_get_arguments_deprecated(args, 1, 1, &arg2); - switch(option){ - case PPM_PR_GET_NAME: - case PPM_PR_SET_NAME: - /* - * arg2_str - */ - res = val_to_ring(args, arg2, 0, true, 0); - CHECK_RES(res); - /* - * arg2_int - */ - res = val_to_ring(args, 0, 0, false, 0); - CHECK_RES(res); - break; - case PPM_PR_GET_CHILD_SUBREAPER: - { - int reaper_attr = 0; - /* Parameter 3: arg2_str (type: PT_CHARBUF) */ - res = push_empty_param(args); - CHECK_RES(res); - /* Parameter 4: arg2_int (type: PT_INT64) */ - if(unlikely(ppm_copy_from_user(&reaper_attr, (void *)arg2, sizeof(reaper_attr)))) - { - reaper_attr = 0; - } - res = val_to_ring(args, (int64_t)reaper_attr, 0, false, 0); - CHECK_RES(res); - } - break; - case PPM_PR_SET_CHILD_SUBREAPER: - default: - /* - * arg2_str - */ - res = push_empty_param(args); - CHECK_RES(res); - /* - * arg2_int - */ - res = val_to_ring(args, arg2, 0, false, 0); - CHECK_RES(res); - break; + switch(option) { + case PPM_PR_GET_NAME: + case PPM_PR_SET_NAME: + /* + * arg2_str + */ + res = val_to_ring(args, arg2, 0, true, 0); + CHECK_RES(res); + /* + * arg2_int + */ + res = val_to_ring(args, 0, 0, false, 0); + CHECK_RES(res); + break; + case PPM_PR_GET_CHILD_SUBREAPER: { + int reaper_attr = 0; + /* Parameter 3: arg2_str (type: PT_CHARBUF) */ + res = push_empty_param(args); + CHECK_RES(res); + /* Parameter 4: arg2_int (type: PT_INT64) */ + if(unlikely(ppm_copy_from_user(&reaper_attr, (void *)arg2, sizeof(reaper_attr)))) { + reaper_attr = 0; + } + res = val_to_ring(args, (int64_t)reaper_attr, 0, false, 0); + CHECK_RES(res); + } break; + case PPM_PR_SET_CHILD_SUBREAPER: + default: + /* + * arg2_str + */ + res = push_empty_param(args); + CHECK_RES(res); + /* + * arg2_int + */ + res = val_to_ring(args, arg2, 0, false, 0); + CHECK_RES(res); + break; } return add_sentinel(args); } -int f_sys_memfd_create_x(struct event_filler_arguments *args) -{ +int f_sys_memfd_create_x(struct event_filler_arguments *args) { unsigned long val; int res; long retval; @@ -8009,13 +7737,11 @@ int f_sys_memfd_create_x(struct event_filler_arguments *args) res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); - /* Parameter 2: name (type: PT_CHARBUF) */ syscall_get_arguments_deprecated(args, 0, 1, &val); res = val_to_ring(args, val, 0, true, 0); CHECK_RES(res); - /* Parameter 3: flags (type: PT_UINT32) */ syscall_get_arguments_deprecated(args, 1, 1, &val); res = val_to_ring(args, memfd_create_flags_to_scap(val), 0, true, 0); @@ -8024,15 +7750,14 @@ int f_sys_memfd_create_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_pidfd_getfd_x(struct event_filler_arguments *args) -{ +int f_sys_pidfd_getfd_x(struct event_filler_arguments *args) { unsigned long val; int res; long retval; int32_t fd; /* Parameter 1: ret (type: PT_FD) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); @@ -8056,15 +7781,14 @@ int f_sys_pidfd_getfd_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_pidfd_open_x(struct event_filler_arguments *args) -{ +int f_sys_pidfd_open_x(struct event_filler_arguments *args) { unsigned long val; int res; long retval; int32_t fd; /* Parameter 1: ret (type: PT_FD) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); @@ -8082,15 +7806,14 @@ int f_sys_pidfd_open_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_init_module_x(struct event_filler_arguments *args) -{ +int f_sys_init_module_x(struct event_filler_arguments *args) { unsigned long val; int res; long retval; uint64_t len; /* Parameter 1: ret (type: PT_ERRNO) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); @@ -8114,15 +7837,14 @@ int f_sys_init_module_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_finit_module_x(struct event_filler_arguments *args) -{ +int f_sys_finit_module_x(struct event_filler_arguments *args) { unsigned long val; int res; long retval; int32_t fd; /* Parameter 1: ret (type: PT_ERRNO) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); @@ -8145,14 +7867,13 @@ int f_sys_finit_module_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mknod_x(struct event_filler_arguments *args) -{ +int f_sys_mknod_x(struct event_filler_arguments *args) { unsigned long val; int res; long retval; /* Parameter 1: ret (type: PT_ERRNO) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); @@ -8174,22 +7895,21 @@ int f_sys_mknod_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_mknodat_x(struct event_filler_arguments *args) -{ +int f_sys_mknodat_x(struct event_filler_arguments *args) { unsigned long val; int res; int32_t fd; long retval; /* Parameter 1: ret (type: PT_ERRNO) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); /* Parameter 2: dirfd (type: PT_FD) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, true, 0); CHECK_RES(res); @@ -8212,22 +7932,21 @@ int f_sys_mknodat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_newfstatat_x(struct event_filler_arguments *args) -{ +int f_sys_newfstatat_x(struct event_filler_arguments *args) { unsigned long val; int res; int32_t fd; long retval; /* Parameter 1: ret (type: PT_ERRNO) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, retval, 0, false, 0); CHECK_RES(res); /* Parameter 2: dirfd (type: PT_FD) */ syscall_get_arguments_deprecated(args, 0, 1, &val); fd = (int32_t)val; - if (fd == AT_FDCWD) + if(fd == AT_FDCWD) fd = PPM_AT_FDCWD; res = val_to_ring(args, (int64_t)fd, 0, true, 0); CHECK_RES(res); @@ -8245,8 +7964,7 @@ int f_sys_newfstatat_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_process_vm_readv_x(struct event_filler_arguments *args) -{ +int f_sys_process_vm_readv_x(struct event_filler_arguments *args) { unsigned long val; long retval; int res; @@ -8254,7 +7972,7 @@ int f_sys_process_vm_readv_x(struct event_filler_arguments *args) int32_t pid; /* Parameter 1: ret (type: PT_INT64) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, (int64_t)retval, 0, false, 0); CHECK_RES(res); @@ -8264,28 +7982,29 @@ int f_sys_process_vm_readv_x(struct event_filler_arguments *args) res = val_to_ring(args, (int64_t)pid, 0, false, 0); CHECK_RES(res); - - if(retval > 0) - { + if(retval > 0) { /* We only get the local iov */ syscall_get_arguments_deprecated(args, 1, 1, &val); syscall_get_arguments_deprecated(args, 2, 1, &iovcnt); - #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) { - const struct compat_iovec __user *compat_iov = (const struct compat_iovec __user *)compat_ptr(val); - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, retval, PRB_FLAG_PUSH_DATA); +#ifdef CONFIG_COMPAT + if(unlikely(args->compat)) { + const struct compat_iovec __user *compat_iov = + (const struct compat_iovec __user *)compat_ptr(val); + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + retval, + PRB_FLAG_PUSH_DATA); } else - #endif +#endif { const struct iovec __user *iov = (const struct iovec __user *)val; res = parse_readv_writev_bufs(args, iov, iovcnt, retval, PRB_FLAG_PUSH_DATA); } CHECK_RES(res); - } - else - { + } else { /* pushing empty data */ res = push_empty_param(args); CHECK_RES(res); @@ -8294,8 +8013,7 @@ int f_sys_process_vm_readv_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_process_vm_writev_x(struct event_filler_arguments *args) -{ +int f_sys_process_vm_writev_x(struct event_filler_arguments *args) { unsigned long val; long retval; int res; @@ -8303,7 +8021,7 @@ int f_sys_process_vm_writev_x(struct event_filler_arguments *args) int32_t pid; /* Parameter 1: ret (type: PT_INT64) */ - retval = (int64_t) syscall_get_return_value(current,args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, (int64_t)retval, 0, false, 0); CHECK_RES(res); @@ -8313,28 +8031,29 @@ int f_sys_process_vm_writev_x(struct event_filler_arguments *args) res = val_to_ring(args, (int64_t)pid, 0, false, 0); CHECK_RES(res); - - if(retval > 0) - { + if(retval > 0) { /* We only get the local iov */ syscall_get_arguments_deprecated(args, 1, 1, &val); syscall_get_arguments_deprecated(args, 2, 1, &iovcnt); - #ifdef CONFIG_COMPAT - if (unlikely(args->compat)) { - const struct compat_iovec __user *compat_iov = (const struct compat_iovec __user *)compat_ptr(val); - res = compat_parse_readv_writev_bufs(args, compat_iov, iovcnt, retval, PRB_FLAG_PUSH_DATA); +#ifdef CONFIG_COMPAT + if(unlikely(args->compat)) { + const struct compat_iovec __user *compat_iov = + (const struct compat_iovec __user *)compat_ptr(val); + res = compat_parse_readv_writev_bufs(args, + compat_iov, + iovcnt, + retval, + PRB_FLAG_PUSH_DATA); } else - #endif +#endif { const struct iovec __user *iov = (const struct iovec __user *)val; res = parse_readv_writev_bufs(args, iov, iovcnt, retval, PRB_FLAG_PUSH_DATA); } CHECK_RES(res); - } - else - { + } else { /* pushing empty data */ res = push_empty_param(args); CHECK_RES(res); @@ -8343,15 +8062,14 @@ int f_sys_process_vm_writev_x(struct event_filler_arguments *args) return add_sentinel(args); } -int f_sys_delete_module_x(struct event_filler_arguments *args) -{ +int f_sys_delete_module_x(struct event_filler_arguments *args) { int64_t retval = 0; int64_t res = 0; uint32_t flags = 0; unsigned long val = 0; /* Parameter 1: res (type: PT_ERRNO) */ - retval = (int64_t) syscall_get_return_value(current, args->regs); + retval = (int64_t)syscall_get_return_value(current, args->regs); res = val_to_ring(args, (int64_t)retval, 0, false, 0); CHECK_RES(res); diff --git a/driver/ppm_fillers.h b/driver/ppm_fillers.h index 08e0d969e8..32e55ac77e 100644 --- a/driver/ppm_fillers.h +++ b/driver/ppm_fillers.h @@ -11,193 +11,190 @@ or GPL2.txt for full copies of the license. #ifndef PPM_FILLERS_H_ #define PPM_FILLERS_H_ -#define FILLER_LIST_MAPPER(FN) \ - FN(sys_autofill) \ - FN(sys_generic) \ - FN(sys_empty) \ - FN(sys_getcwd_x) \ - FN(sys_getdents_e) \ - FN(sys_getdents64_e) \ - FN(sys_single) \ - FN(sys_single_x) \ - FN(sys_fstat_e) \ - FN(sys_open_e) \ - FN(sys_open_x) \ - FN(sys_read_e) \ - FN(sys_read_x) \ - FN(sys_write_e) \ - FN(sys_write_x) \ - FN(sys_execve_e) \ - FN(proc_startupdate) \ - FN(proc_startupdate_2) \ - FN(proc_startupdate_3) \ - FN(sys_socketpair_x) \ - FN(sys_setsockopt_x) \ - FN(sys_getsockopt_x) \ - FN(sys_connect_x) \ - FN(sys_accept4_e) \ - FN(sys_accept_x) \ - FN(sys_send_e) \ - FN(sys_send_x) \ - FN(sys_sendto_e) \ - FN(sys_sendmsg_e) \ - FN(sys_sendmsg_x) \ - FN(sys_recv_x) \ - FN(sys_recvfrom_x) \ - FN(sys_recvmsg_x) \ - FN(sys_recvmsg_x_2) \ - FN(sys_shutdown_e) \ - FN(sys_creat_e) \ - FN(sys_creat_x) \ - FN(sys_pipe_x) \ - FN(sys_eventfd_e) \ - FN(sys_futex_e) \ - FN(sys_lseek_e) \ - FN(sys_llseek_e) \ - FN(sys_socket_bind_x) \ - FN(sys_poll_e) \ - FN(sys_poll_x) \ - FN(sys_pread64_e) \ - FN(sys_writev_e) \ - FN(sys_pwrite64_e) \ - FN(sys_readv_e) \ - FN(sys_preadv_e) \ - FN(sys_readv_preadv_x) \ - FN(sys_writev_pwritev_x) \ - FN(sys_pwritev_e) \ - FN(sys_nanosleep_e) \ - FN(sys_getrlimit_setrlimit_e) \ - FN(sys_getrlimit_x) \ - FN(sys_setrlimit_x) \ - FN(sys_prlimit_e) \ - FN(sys_prlimit_x) \ - FN(sched_switch_e) \ - FN(sched_drop) \ - FN(sys_fcntl_e) \ - FN(sys_fcntl_x) \ - FN(sys_ptrace_e) \ - FN(sys_ptrace_x) \ - FN(sys_mmap_e) \ - FN(sys_brk_munmap_mmap_x) \ - FN(sys_renameat_x) \ - FN(sys_renameat2_x) \ - FN(sys_symlinkat_x) \ - FN(sys_procexit_e) \ - FN(sys_sendfile_e) \ - FN(sys_sendfile_x) \ - FN(sys_quotactl_e) \ - FN(sys_quotactl_x) \ - FN(sys_scapevent_e) \ - FN(sys_getresuid_and_gid_x) \ - FN(sys_signaldeliver_e) \ - FN(sys_pagefault_e) \ - FN(sys_setns_e) \ - FN(sys_unshare_e) \ - FN(sys_flock_e) \ - FN(cpu_hotplug_e) \ - FN(sys_semop_x) \ - FN(sys_semget_e) \ - FN(sys_semctl_e) \ - FN(sys_ppoll_e) \ - FN(sys_mount_e) \ - FN(sys_access_e) \ - FN(sys_socket_x) \ - FN(sys_bpf_x) \ - FN(sys_unlinkat_x) \ - FN(sys_fchmodat_x) \ - FN(sys_chmod_x) \ - FN(sys_fchmod_x) \ - FN(sys_chown_x) \ - FN(sys_lchown_x) \ - FN(sys_fchown_x) \ - FN(sys_fchownat_x) \ - FN(sys_mkdirat_x) \ - FN(sys_openat_e) \ - FN(sys_openat_x) \ - FN(sys_openat2_e) \ - FN(sys_openat2_x) \ - FN(sys_linkat_x) \ - FN(sys_mprotect_e) \ - FN(sys_mprotect_x) \ - FN(sys_execveat_e) \ - FN(execve_extra_tail_1) \ - FN(execve_extra_tail_2) \ - FN(sys_copy_file_range_e) \ - FN(sys_copy_file_range_x) \ - FN(sys_connect_e) \ - FN(sys_open_by_handle_at_x) \ +#define FILLER_LIST_MAPPER(FN) \ + FN(sys_autofill) \ + FN(sys_generic) \ + FN(sys_empty) \ + FN(sys_getcwd_x) \ + FN(sys_getdents_e) \ + FN(sys_getdents64_e) \ + FN(sys_single) \ + FN(sys_single_x) \ + FN(sys_fstat_e) \ + FN(sys_open_e) \ + FN(sys_open_x) \ + FN(sys_read_e) \ + FN(sys_read_x) \ + FN(sys_write_e) \ + FN(sys_write_x) \ + FN(sys_execve_e) \ + FN(proc_startupdate) \ + FN(proc_startupdate_2) \ + FN(proc_startupdate_3) \ + FN(sys_socketpair_x) \ + FN(sys_setsockopt_x) \ + FN(sys_getsockopt_x) \ + FN(sys_connect_x) \ + FN(sys_accept4_e) \ + FN(sys_accept_x) \ + FN(sys_send_e) \ + FN(sys_send_x) \ + FN(sys_sendto_e) \ + FN(sys_sendmsg_e) \ + FN(sys_sendmsg_x) \ + FN(sys_recv_x) \ + FN(sys_recvfrom_x) \ + FN(sys_recvmsg_x) \ + FN(sys_recvmsg_x_2) \ + FN(sys_shutdown_e) \ + FN(sys_creat_e) \ + FN(sys_creat_x) \ + FN(sys_pipe_x) \ + FN(sys_eventfd_e) \ + FN(sys_futex_e) \ + FN(sys_lseek_e) \ + FN(sys_llseek_e) \ + FN(sys_socket_bind_x) \ + FN(sys_poll_e) \ + FN(sys_poll_x) \ + FN(sys_pread64_e) \ + FN(sys_writev_e) \ + FN(sys_pwrite64_e) \ + FN(sys_readv_e) \ + FN(sys_preadv_e) \ + FN(sys_readv_preadv_x) \ + FN(sys_writev_pwritev_x) \ + FN(sys_pwritev_e) \ + FN(sys_nanosleep_e) \ + FN(sys_getrlimit_setrlimit_e) \ + FN(sys_getrlimit_x) \ + FN(sys_setrlimit_x) \ + FN(sys_prlimit_e) \ + FN(sys_prlimit_x) \ + FN(sched_switch_e) \ + FN(sched_drop) \ + FN(sys_fcntl_e) \ + FN(sys_fcntl_x) \ + FN(sys_ptrace_e) \ + FN(sys_ptrace_x) \ + FN(sys_mmap_e) \ + FN(sys_brk_munmap_mmap_x) \ + FN(sys_renameat_x) \ + FN(sys_renameat2_x) \ + FN(sys_symlinkat_x) \ + FN(sys_procexit_e) \ + FN(sys_sendfile_e) \ + FN(sys_sendfile_x) \ + FN(sys_quotactl_e) \ + FN(sys_quotactl_x) \ + FN(sys_scapevent_e) \ + FN(sys_getresuid_and_gid_x) \ + FN(sys_signaldeliver_e) \ + FN(sys_pagefault_e) \ + FN(sys_setns_e) \ + FN(sys_unshare_e) \ + FN(sys_flock_e) \ + FN(cpu_hotplug_e) \ + FN(sys_semop_x) \ + FN(sys_semget_e) \ + FN(sys_semctl_e) \ + FN(sys_ppoll_e) \ + FN(sys_mount_e) \ + FN(sys_access_e) \ + FN(sys_socket_x) \ + FN(sys_bpf_x) \ + FN(sys_unlinkat_x) \ + FN(sys_fchmodat_x) \ + FN(sys_chmod_x) \ + FN(sys_fchmod_x) \ + FN(sys_chown_x) \ + FN(sys_lchown_x) \ + FN(sys_fchown_x) \ + FN(sys_fchownat_x) \ + FN(sys_mkdirat_x) \ + FN(sys_openat_e) \ + FN(sys_openat_x) \ + FN(sys_openat2_e) \ + FN(sys_openat2_x) \ + FN(sys_linkat_x) \ + FN(sys_mprotect_e) \ + FN(sys_mprotect_x) \ + FN(sys_execveat_e) \ + FN(execve_extra_tail_1) \ + FN(execve_extra_tail_2) \ + FN(sys_copy_file_range_e) \ + FN(sys_copy_file_range_x) \ + FN(sys_connect_e) \ + FN(sys_open_by_handle_at_x) \ FN(open_by_handle_at_x_extra_tail_1) \ - FN(sys_io_uring_setup_x) \ - FN(sys_io_uring_enter_x) \ - FN(sys_io_uring_register_x) \ - FN(sys_mlock_x) \ - FN(sys_munlock_x) \ - FN(sys_mlockall_x) \ - FN(sys_munlockall_x) \ - FN(sys_capset_x) \ - FN(sys_dup2_e) \ - FN(sys_dup2_x) \ - FN(sys_dup3_e) \ - FN(sys_dup3_x) \ - FN(sys_dup_e) \ - FN(sys_dup_x) \ - FN(sched_prog_exec) \ - FN(sched_prog_exec_2) \ - FN(sched_prog_exec_3) \ - FN(sched_prog_exec_4) \ - FN(sched_prog_exec_5) \ - FN(sched_prog_fork) \ - FN(sched_prog_fork_2) \ - FN(sched_prog_fork_3) \ - FN(sys_mlock2_x) \ - FN(sys_fsconfig_x) \ - FN(sys_epoll_create_e) \ - FN(sys_epoll_create_x) \ - FN(sys_epoll_create1_e) \ - FN(sys_epoll_create1_x) \ - FN(sys_socket_bind_e) \ - FN(sys_bpf_e) \ - FN(sys_close_e) \ - FN(sys_close_x) \ - FN(sys_fchdir_e) \ - FN(sys_fchdir_x) \ - FN(sys_ioctl_e) \ - FN(sys_mkdir_e) \ - FN(sys_setpgid_e) \ - FN(sys_recvfrom_e) \ - FN(sys_recvmsg_e) \ - FN(sys_listen_e) \ - FN(sys_signalfd_e) \ - FN(sys_splice_e) \ - FN(sys_umount_x) \ - FN(sys_umount2_e) \ - FN(sys_umount2_x) \ - FN(sys_pipe2_x) \ - FN(sys_inotify_init_e) \ - FN(sys_inotify_init1_x) \ - FN(sys_eventfd2_e) \ - FN(sys_eventfd2_x) \ - FN(sys_signalfd4_e) \ - FN(sys_signalfd4_x) \ - FN(sys_prctl_x) \ - FN(sys_memfd_create_x) \ - FN(sys_pidfd_getfd_x) \ - FN(sys_pidfd_open_x) \ - FN(sys_init_module_x) \ - FN(sys_finit_module_x) \ - FN(sys_mknod_x) \ - FN(sys_mknodat_x) \ - FN(sys_newfstatat_x) \ - FN(sys_process_vm_readv_x) \ - FN(sys_process_vm_writev_x) \ - FN(sys_delete_module_x) \ + FN(sys_io_uring_setup_x) \ + FN(sys_io_uring_enter_x) \ + FN(sys_io_uring_register_x) \ + FN(sys_mlock_x) \ + FN(sys_munlock_x) \ + FN(sys_mlockall_x) \ + FN(sys_munlockall_x) \ + FN(sys_capset_x) \ + FN(sys_dup2_e) \ + FN(sys_dup2_x) \ + FN(sys_dup3_e) \ + FN(sys_dup3_x) \ + FN(sys_dup_e) \ + FN(sys_dup_x) \ + FN(sched_prog_exec) \ + FN(sched_prog_exec_2) \ + FN(sched_prog_exec_3) \ + FN(sched_prog_exec_4) \ + FN(sched_prog_exec_5) \ + FN(sched_prog_fork) \ + FN(sched_prog_fork_2) \ + FN(sched_prog_fork_3) \ + FN(sys_mlock2_x) \ + FN(sys_fsconfig_x) \ + FN(sys_epoll_create_e) \ + FN(sys_epoll_create_x) \ + FN(sys_epoll_create1_e) \ + FN(sys_epoll_create1_x) \ + FN(sys_socket_bind_e) \ + FN(sys_bpf_e) \ + FN(sys_close_e) \ + FN(sys_close_x) \ + FN(sys_fchdir_e) \ + FN(sys_fchdir_x) \ + FN(sys_ioctl_e) \ + FN(sys_mkdir_e) \ + FN(sys_setpgid_e) \ + FN(sys_recvfrom_e) \ + FN(sys_recvmsg_e) \ + FN(sys_listen_e) \ + FN(sys_signalfd_e) \ + FN(sys_splice_e) \ + FN(sys_umount_x) \ + FN(sys_umount2_e) \ + FN(sys_umount2_x) \ + FN(sys_pipe2_x) \ + FN(sys_inotify_init_e) \ + FN(sys_inotify_init1_x) \ + FN(sys_eventfd2_e) \ + FN(sys_eventfd2_x) \ + FN(sys_signalfd4_e) \ + FN(sys_signalfd4_x) \ + FN(sys_prctl_x) \ + FN(sys_memfd_create_x) \ + FN(sys_pidfd_getfd_x) \ + FN(sys_pidfd_open_x) \ + FN(sys_init_module_x) \ + FN(sys_finit_module_x) \ + FN(sys_mknod_x) \ + FN(sys_mknodat_x) \ + FN(sys_newfstatat_x) \ + FN(sys_process_vm_readv_x) \ + FN(sys_process_vm_writev_x) \ + FN(sys_delete_module_x) \ FN(terminate_filler) #define FILLER_ENUM_FN(x) PPM_FILLER_##x, -enum ppm_filler_id { - FILLER_LIST_MAPPER(FILLER_ENUM_FN) - PPM_FILLER_MAX -}; +enum ppm_filler_id { FILLER_LIST_MAPPER(FILLER_ENUM_FN) PPM_FILLER_MAX }; #undef FILLER_ENUM_FN #define FILLER_PROTOTYPE_FN(x) int f_##x(struct event_filler_arguments *args); diff --git a/driver/ppm_flag_helpers.h b/driver/ppm_flag_helpers.h index 503dffb73f..d47ecc292d 100644 --- a/driver/ppm_flag_helpers.h +++ b/driver/ppm_flag_helpers.h @@ -11,11 +11,11 @@ or GPL2.txt for full copies of the license. #ifndef PPM_FLAG_HELPERS_H_ #define PPM_FLAG_HELPERS_H_ -/* The ASSERT is defined in other files that we don't +/* The ASSERT is defined in other files that we don't * want to inlcude with the modern probe. `ppm.h` */ #ifdef __USE_VMLINUX__ - #define ASSERT(expr) +#define ASSERT(expr) #endif #ifdef __KERNEL__ @@ -39,7 +39,7 @@ or GPL2.txt for full copies of the license. #ifdef __NR_umount2 #include #endif -#endif // ifndef __KERNEL__ +#endif // ifndef __KERNEL__ #ifndef __always_inline #define __always_inline inline @@ -47,25 +47,23 @@ or GPL2.txt for full copies of the license. // When this file is included in userspace #if !defined(__KERNEL__) && !defined(__USE_VMLINUX__) - #include - #include +#include +#include #endif #define PPM_MS_MGC_MSK 0xffff0000 #define PPM_MS_MGC_VAL 0xC0ED0000 /* Check if the res is different from `PPM_SUCCCES` */ -#define CHECK_RES(x) \ - if(unlikely(x != PPM_SUCCESS)) \ - { \ - return x; \ - } \ - -static __always_inline uint32_t open_flags_to_scap(uint32_t flags) -{ +#define CHECK_RES(x) \ + if(unlikely(x != PPM_SUCCESS)) { \ + return x; \ + } + +static __always_inline uint32_t open_flags_to_scap(uint32_t flags) { uint32_t res = 0; - switch (flags & (O_RDONLY | O_WRONLY | O_RDWR)) { + switch(flags & (O_RDONLY | O_WRONLY | O_RDWR)) { case O_WRONLY: res |= PPM_O_WRONLY; break; @@ -77,63 +75,61 @@ static __always_inline uint32_t open_flags_to_scap(uint32_t flags) break; } - if (flags & O_CREAT) + if(flags & O_CREAT) res |= PPM_O_CREAT; #ifdef O_TMPFILE - if (flags & O_TMPFILE) + if(flags & O_TMPFILE) res |= PPM_O_TMPFILE; #endif - if (flags & O_APPEND) + if(flags & O_APPEND) res |= PPM_O_APPEND; #ifdef O_DSYNC - if (flags & O_DSYNC) + if(flags & O_DSYNC) res |= PPM_O_DSYNC; #endif - if (flags & O_EXCL) + if(flags & O_EXCL) res |= PPM_O_EXCL; #ifdef O_NONBLOCK - if (flags & O_NONBLOCK) + if(flags & O_NONBLOCK) res |= PPM_O_NONBLOCK; #endif #ifdef O_SYNC - if (flags & O_SYNC) + if(flags & O_SYNC) res |= PPM_O_SYNC; #endif - if (flags & O_TRUNC) + if(flags & O_TRUNC) res |= PPM_O_TRUNC; #ifdef O_DIRECT - if (flags & O_DIRECT) + if(flags & O_DIRECT) res |= PPM_O_DIRECT; #endif #ifdef O_DIRECTORY - if (flags & O_DIRECTORY) + if(flags & O_DIRECTORY) res |= PPM_O_DIRECTORY; #endif #ifdef O_LARGEFILE - if (flags & O_LARGEFILE) + if(flags & O_LARGEFILE) res |= PPM_O_LARGEFILE; #endif #ifdef O_CLOEXEC - if (flags & O_CLOEXEC) + if(flags & O_CLOEXEC) res |= PPM_O_CLOEXEC; #endif return res; } -static __always_inline uint32_t open_modes_to_scap(unsigned long flags, - unsigned long modes) -{ +static __always_inline uint32_t open_modes_to_scap(unsigned long flags, unsigned long modes) { // This file is used also in userspace so we cannot use `KERNEL_VERSION` macro without an ifdef #ifdef __KERNEL__ #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0) @@ -147,229 +143,225 @@ static __always_inline uint32_t open_modes_to_scap(unsigned long flags, uint32_t res = 0; - if ((flags & flags_mask) == 0) + if((flags & flags_mask) == 0) return res; - if (modes & S_IRUSR) + if(modes & S_IRUSR) res |= PPM_S_IRUSR; - if (modes & S_IWUSR) + if(modes & S_IWUSR) res |= PPM_S_IWUSR; - if (modes & S_IXUSR) + if(modes & S_IXUSR) res |= PPM_S_IXUSR; /* - * PPM_S_IRWXU == S_IRUSR | S_IWUSR | S_IXUSR - */ + * PPM_S_IRWXU == S_IRUSR | S_IWUSR | S_IXUSR + */ - if (modes & S_IRGRP) + if(modes & S_IRGRP) res |= PPM_S_IRGRP; - if (modes & S_IWGRP) + if(modes & S_IWGRP) res |= PPM_S_IWGRP; - if (modes & S_IXGRP) + if(modes & S_IXGRP) res |= PPM_S_IXGRP; /* - * PPM_S_IRWXG == S_IRGRP | S_IWGRP | S_IXGRP - */ + * PPM_S_IRWXG == S_IRGRP | S_IWGRP | S_IXGRP + */ - if (modes & S_IROTH) + if(modes & S_IROTH) res |= PPM_S_IROTH; - if (modes & S_IWOTH) + if(modes & S_IWOTH) res |= PPM_S_IWOTH; - if (modes & S_IXOTH) + if(modes & S_IXOTH) res |= PPM_S_IXOTH; /* - * PPM_S_IRWXO == S_IROTH | S_IWOTH | S_IXOTH - */ + * PPM_S_IRWXO == S_IROTH | S_IWOTH | S_IXOTH + */ - if (modes & S_ISUID) + if(modes & S_ISUID) res |= PPM_S_ISUID; - if (modes & S_ISGID) + if(modes & S_ISGID) res |= PPM_S_ISGID; - if (modes & S_ISVTX) + if(modes & S_ISVTX) res |= PPM_S_ISVTX; return res; } -static __always_inline uint32_t openat2_resolve_to_scap(unsigned long flags) -{ +static __always_inline uint32_t openat2_resolve_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef RESOLVE_NO_XDEV - if (flags & RESOLVE_NO_XDEV) + if(flags & RESOLVE_NO_XDEV) res |= PPM_RESOLVE_NO_XDEV; #endif #ifdef RESOLVE_NO_MAGICLINKS - if (flags & RESOLVE_NO_MAGICLINKS) + if(flags & RESOLVE_NO_MAGICLINKS) res |= PPM_RESOLVE_NO_MAGICLINKS; #endif #ifdef RESOLVE_NO_SYMLINKS - if (flags & RESOLVE_NO_SYMLINKS) + if(flags & RESOLVE_NO_SYMLINKS) res |= PPM_RESOLVE_NO_SYMLINKS; #endif #ifdef RESOLVE_BENEATH - if (flags & RESOLVE_BENEATH) + if(flags & RESOLVE_BENEATH) res |= PPM_RESOLVE_BENEATH; #endif #ifdef RESOLVE_IN_ROOT - if (flags & RESOLVE_IN_ROOT) + if(flags & RESOLVE_IN_ROOT) res |= PPM_RESOLVE_IN_ROOT; #endif #ifdef RESOLVE_CACHED - if (flags & RESOLVE_CACHED) + if(flags & RESOLVE_CACHED) res |= PPM_RESOLVE_CACHED; #endif return res; } -static __always_inline uint32_t io_uring_setup_flags_to_scap(unsigned long flags){ +static __always_inline uint32_t io_uring_setup_flags_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef IORING_SETUP_IOPOLL - if (flags & IORING_SETUP_IOPOLL) + if(flags & IORING_SETUP_IOPOLL) res |= PPM_IORING_SETUP_IOPOLL; #endif #ifdef IORING_SETUP_SQPOLL - if (flags & IORING_SETUP_SQPOLL) + if(flags & IORING_SETUP_SQPOLL) res |= PPM_IORING_SETUP_SQPOLL; #endif #ifdef IORING_SQ_NEED_WAKEUP - if (flags & IORING_SQ_NEED_WAKEUP) + if(flags & IORING_SQ_NEED_WAKEUP) res |= PPM_IORING_SQ_NEED_WAKEUP; #endif #ifdef IORING_SETUP_SQ_AFF - if (flags & IORING_SETUP_SQ_AFF) + if(flags & IORING_SETUP_SQ_AFF) res |= PPM_IORING_SETUP_SQ_AFF; #endif #ifdef IORING_SETUP_CQSIZE - if (flags & IORING_SETUP_CQSIZE) + if(flags & IORING_SETUP_CQSIZE) res |= PPM_IORING_SETUP_CQSIZE; #endif #ifdef IORING_SETUP_CLAMP - if (flags & IORING_SETUP_CLAMP) + if(flags & IORING_SETUP_CLAMP) res |= PPM_IORING_SETUP_CLAMP; #endif #ifdef IORING_SETUP_ATTACH_WQ - if (flags & IORING_SETUP_ATTACH_WQ) + if(flags & IORING_SETUP_ATTACH_WQ) res |= PPM_IORING_SETUP_ATTACH_WQ; #endif #ifdef IORING_SETUP_R_DISABLED - if (flags & IORING_SETUP_R_DISABLED) + if(flags & IORING_SETUP_R_DISABLED) res |= PPM_IORING_SETUP_R_DISABLED; #endif return res; } -static __always_inline uint32_t io_uring_setup_feats_to_scap(unsigned long flags){ +static __always_inline uint32_t io_uring_setup_feats_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef IORING_FEAT_SINGLE_MMAP - if (flags & IORING_FEAT_SINGLE_MMAP) + if(flags & IORING_FEAT_SINGLE_MMAP) res |= PPM_IORING_FEAT_SINGLE_MMAP; #endif #ifdef IORING_FEAT_NODROP - if (flags & IORING_FEAT_NODROP) + if(flags & IORING_FEAT_NODROP) res |= PPM_IORING_FEAT_NODROP; #endif #ifdef IORING_FEAT_SUBMIT_STABLE - if (flags & IORING_FEAT_SUBMIT_STABLE) + if(flags & IORING_FEAT_SUBMIT_STABLE) res |= PPM_IORING_FEAT_SUBMIT_STABLE; #endif #ifdef IORING_FEAT_RW_CUR_POS - if (flags & IORING_FEAT_RW_CUR_POS) + if(flags & IORING_FEAT_RW_CUR_POS) res |= PPM_IORING_FEAT_RW_CUR_POS; #endif #ifdef IORING_FEAT_CUR_PERSONALITY - if (flags & IORING_FEAT_CUR_PERSONALITY) + if(flags & IORING_FEAT_CUR_PERSONALITY) res |= PPM_IORING_FEAT_CUR_PERSONALITY; #endif - #ifdef IORING_FEAT_FAST_POLL - if (flags & IORING_FEAT_FAST_POLL) + if(flags & IORING_FEAT_FAST_POLL) res |= PPM_IORING_FEAT_FAST_POLL; #endif #ifdef IORING_FEAT_POLL_32BITS - if (flags & IORING_FEAT_POLL_32BITS) + if(flags & IORING_FEAT_POLL_32BITS) res |= PPM_IORING_FEAT_POLL_32BITS; #endif #ifdef IORING_FEAT_SQPOLL_NONFIXED - if (flags & IORING_FEAT_SQPOLL_NONFIXED) + if(flags & IORING_FEAT_SQPOLL_NONFIXED) res |= PPM_IORING_FEAT_SQPOLL_NONFIXED; #endif #ifdef IORING_FEAT_ENTER_EXT_ARG - if (flags & IORING_FEAT_ENTER_EXT_ARG) + if(flags & IORING_FEAT_ENTER_EXT_ARG) res |= PPM_IORING_FEAT_ENTER_EXT_ARG; #endif #ifdef IORING_FEAT_NATIVE_WORKERS - if (flags & IORING_FEAT_NATIVE_WORKERS) + if(flags & IORING_FEAT_NATIVE_WORKERS) res |= PPM_IORING_FEAT_NATIVE_WORKERS; #endif #ifdef IORING_FEAT_RSRC_TAGS - if (flags & IORING_FEAT_RSRC_TAGS) + if(flags & IORING_FEAT_RSRC_TAGS) res |= PPM_IORING_FEAT_RSRC_TAGS; #endif return res; } -static __always_inline uint32_t io_uring_enter_flags_to_scap(unsigned long flags) -{ +static __always_inline uint32_t io_uring_enter_flags_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef IORING_ENTER_GETEVENTS - if (flags & IORING_ENTER_GETEVENTS) + if(flags & IORING_ENTER_GETEVENTS) res |= PPM_IORING_ENTER_GETEVENTS; #endif #ifdef IORING_ENTER_SQ_WAKEUP - if (flags & IORING_ENTER_SQ_WAKEUP) + if(flags & IORING_ENTER_SQ_WAKEUP) res |= PPM_IORING_ENTER_SQ_WAKEUP; #endif #ifdef IORING_ENTER_SQ_WAIT - if (flags & IORING_ENTER_SQ_WAIT) + if(flags & IORING_ENTER_SQ_WAIT) res |= PPM_IORING_ENTER_SQ_WAIT; #endif #ifdef IORING_ENTER_EXT_ARG - if (flags & IORING_ENTER_EXT_ARG) + if(flags & IORING_ENTER_EXT_ARG) res |= PPM_IORING_ENTER_EXT_ARG; #endif return res; } -static __always_inline uint32_t io_uring_register_opcodes_to_scap(unsigned long flags) -{ +static __always_inline uint32_t io_uring_register_opcodes_to_scap(unsigned long flags) { /* * io_uring_register opcodes are defined via enum in io_uring.h. * It is userspace API (thus stable) and arch independent. @@ -387,23 +379,21 @@ static __always_inline uint32_t io_uring_register_opcodes_to_scap(unsigned long * #define IN_CLOEXEC O_CLOEXEC * #define IN_NONBLOCK O_NONBLOCK */ -static __always_inline uint16_t inotify_init1_flags_to_scap(int32_t flags) -{ +static __always_inline uint16_t inotify_init1_flags_to_scap(int32_t flags) { uint16_t res = 0; /* We need to explicitly handle the negative case otherwise `-1` will match all `flags & ...` */ - if(flags < 0) - { + if(flags < 0) { return res; } #ifdef O_NONBLOCK - if (flags & O_NONBLOCK) + if(flags & O_NONBLOCK) res |= PPM_O_NONBLOCK; #endif #ifdef O_CLOEXEC - if (flags & O_CLOEXEC) + if(flags & O_CLOEXEC) res |= PPM_O_CLOEXEC; #endif @@ -418,23 +408,21 @@ static __always_inline uint16_t inotify_init1_flags_to_scap(int32_t flags) * #define EFD_CLOEXEC O_CLOEXEC * #define EFD_NONBLOCK O_NONBLOCK */ -static __always_inline uint16_t eventfd2_flags_to_scap(int32_t flags) -{ +static __always_inline uint16_t eventfd2_flags_to_scap(int32_t flags) { uint16_t res = 0; /* We need to explicitly handle the negative case otherwise `-1` will match all `flags & ...` */ - if(flags < 0) - { + if(flags < 0) { return res; } #ifdef O_NONBLOCK - if (flags & O_NONBLOCK) + if(flags & O_NONBLOCK) res |= PPM_O_NONBLOCK; #endif #ifdef O_CLOEXEC - if (flags & O_CLOEXEC) + if(flags & O_CLOEXEC) res |= PPM_O_CLOEXEC; #endif @@ -448,273 +436,269 @@ static __always_inline uint16_t eventfd2_flags_to_scap(int32_t flags) * #define SFD_CLOEXEC O_CLOEXEC * #define SFD_NONBLOCK O_NONBLOCK */ -static __always_inline uint16_t signalfd4_flags_to_scap(int32_t flags) -{ +static __always_inline uint16_t signalfd4_flags_to_scap(int32_t flags) { uint16_t res = 0; /* We need to explicitly handle the negative case otherwise `-1` will match all `flags & ...` */ - if(flags < 0) - { + if(flags < 0) { return res; } #ifdef O_NONBLOCK - if (flags & O_NONBLOCK) + if(flags & O_NONBLOCK) res |= PPM_O_NONBLOCK; #endif #ifdef O_CLOEXEC - if (flags & O_CLOEXEC) + if(flags & O_CLOEXEC) res |= PPM_O_CLOEXEC; #endif return res; } -static __always_inline uint32_t clone_flags_to_scap(int flags) -{ +static __always_inline uint32_t clone_flags_to_scap(int flags) { uint32_t res = 0; - if (flags & CLONE_FILES) + if(flags & CLONE_FILES) res |= PPM_CL_CLONE_FILES; - if (flags & CLONE_FS) + if(flags & CLONE_FS) res |= PPM_CL_CLONE_FS; #ifdef CLONE_IO - if (flags & CLONE_IO) + if(flags & CLONE_IO) res |= PPM_CL_CLONE_IO; #endif #ifdef CLONE_NEWIPC - if (flags & CLONE_NEWIPC) + if(flags & CLONE_NEWIPC) res |= PPM_CL_CLONE_NEWIPC; #endif #ifdef CLONE_NEWNET - if (flags & CLONE_NEWNET) + if(flags & CLONE_NEWNET) res |= PPM_CL_CLONE_NEWNET; #endif #ifdef CLONE_NEWNS - if (flags & CLONE_NEWNS) + if(flags & CLONE_NEWNS) res |= PPM_CL_CLONE_NEWNS; #endif #ifdef CLONE_NEWPID - if (flags & CLONE_NEWPID) + if(flags & CLONE_NEWPID) res |= PPM_CL_CLONE_NEWPID; #endif #ifdef CLONE_NEWUTS - if (flags & CLONE_NEWUTS) + if(flags & CLONE_NEWUTS) res |= PPM_CL_CLONE_NEWUTS; #endif - if (flags & CLONE_PARENT_SETTID) + if(flags & CLONE_PARENT_SETTID) res |= PPM_CL_CLONE_PARENT_SETTID; - if (flags & CLONE_PARENT) + if(flags & CLONE_PARENT) res |= PPM_CL_CLONE_PARENT; - if (flags & CLONE_PTRACE) + if(flags & CLONE_PTRACE) res |= PPM_CL_CLONE_PTRACE; - if (flags & CLONE_SIGHAND) + if(flags & CLONE_SIGHAND) res |= PPM_CL_CLONE_SIGHAND; - if (flags & CLONE_SYSVSEM) + if(flags & CLONE_SYSVSEM) res |= PPM_CL_CLONE_SYSVSEM; - if (flags & CLONE_THREAD) + if(flags & CLONE_THREAD) res |= PPM_CL_CLONE_THREAD; - if (flags & CLONE_UNTRACED) + if(flags & CLONE_UNTRACED) res |= PPM_CL_CLONE_UNTRACED; - if (flags & CLONE_VM) + if(flags & CLONE_VM) res |= PPM_CL_CLONE_VM; #ifdef CLONE_NEWUSER - if (flags & CLONE_NEWUSER) + if(flags & CLONE_NEWUSER) res |= PPM_CL_CLONE_NEWUSER; #endif - if (flags & CLONE_CHILD_CLEARTID) + if(flags & CLONE_CHILD_CLEARTID) res |= PPM_CL_CLONE_CHILD_CLEARTID; - if (flags & CLONE_CHILD_SETTID) + if(flags & CLONE_CHILD_SETTID) res |= PPM_CL_CLONE_CHILD_SETTID; - if (flags & CLONE_SETTLS) + if(flags & CLONE_SETTLS) res |= PPM_CL_CLONE_SETTLS; #ifdef CLONE_STOPPED - if (flags & CLONE_STOPPED) + if(flags & CLONE_STOPPED) res |= PPM_CL_CLONE_STOPPED; #endif - if (flags & CLONE_VFORK) + if(flags & CLONE_VFORK) res |= PPM_CL_CLONE_VFORK; #ifdef CLONE_NEWCGROUP - if (flags & CLONE_NEWCGROUP) - res |= PPM_CL_CLONE_NEWCGROUP; + if(flags & CLONE_NEWCGROUP) + res |= PPM_CL_CLONE_NEWCGROUP; #endif return res; } -static __always_inline uint8_t socket_family_to_scap(uint8_t family) -{ - if (family == AF_INET) +static __always_inline uint8_t socket_family_to_scap(uint8_t family) { + if(family == AF_INET) return PPM_AF_INET; - else if (family == AF_INET6) + else if(family == AF_INET6) return PPM_AF_INET6; - else if (family == AF_UNIX) + else if(family == AF_UNIX) return PPM_AF_UNIX; #ifdef AF_NETLINK - else if (family == AF_NETLINK) + else if(family == AF_NETLINK) return PPM_AF_NETLINK; #endif #ifdef AF_PACKET - else if (family == AF_PACKET) + else if(family == AF_PACKET) return PPM_AF_PACKET; #endif #ifdef AF_UNSPEC - else if (family == AF_UNSPEC) + else if(family == AF_UNSPEC) return PPM_AF_UNSPEC; #endif #ifdef AF_AX25 - else if (family == AF_AX25) + else if(family == AF_AX25) return PPM_AF_AX25; #endif #ifdef AF_IPX - else if (family == AF_IPX) + else if(family == AF_IPX) return PPM_AF_IPX; #endif #ifdef AF_APPLETALK - else if (family == AF_APPLETALK) + else if(family == AF_APPLETALK) return PPM_AF_APPLETALK; #endif #ifdef AF_NETROM - else if (family == AF_NETROM) + else if(family == AF_NETROM) return PPM_AF_NETROM; #endif #ifdef AF_BRIDGE - else if (family == AF_BRIDGE) + else if(family == AF_BRIDGE) return PPM_AF_BRIDGE; #endif #ifdef AF_ATMPVC - else if (family == AF_ATMPVC) + else if(family == AF_ATMPVC) return PPM_AF_ATMPVC; #endif #ifdef AF_X25 - else if (family == AF_X25) + else if(family == AF_X25) return PPM_AF_X25; #endif #ifdef AF_ROSE - else if (family == AF_ROSE) + else if(family == AF_ROSE) return PPM_AF_ROSE; #endif #ifdef AF_DECnet - else if (family == AF_DECnet) + else if(family == AF_DECnet) return PPM_AF_DECnet; #endif #ifdef AF_NETBEUI - else if (family == AF_NETBEUI) + else if(family == AF_NETBEUI) return PPM_AF_NETBEUI; #endif #ifdef AF_SECURITY - else if (family == AF_SECURITY) + else if(family == AF_SECURITY) return PPM_AF_SECURITY; #endif #ifdef AF_KEY - else if (family == AF_KEY) + else if(family == AF_KEY) return PPM_AF_KEY; #endif #ifdef AF_ROUTE - else if (family == AF_ROUTE) + else if(family == AF_ROUTE) return PPM_AF_ROUTE; #endif #ifdef AF_ASH - else if (family == AF_ASH) + else if(family == AF_ASH) return PPM_AF_ASH; #endif #ifdef AF_ECONET - else if (family == AF_ECONET) + else if(family == AF_ECONET) return PPM_AF_ECONET; #endif #ifdef AF_ATMSVC - else if (family == AF_ATMSVC) + else if(family == AF_ATMSVC) return PPM_AF_ATMSVC; #endif #ifdef AF_RDS - else if (family == AF_RDS) + else if(family == AF_RDS) return PPM_AF_RDS; #endif #ifdef AF_SNA - else if (family == AF_SNA) + else if(family == AF_SNA) return PPM_AF_SNA; #endif #ifdef AF_IRDA - else if (family == AF_IRDA) + else if(family == AF_IRDA) return PPM_AF_IRDA; #endif #ifdef AF_PPPOX - else if (family == AF_PPPOX) + else if(family == AF_PPPOX) return PPM_AF_PPPOX; #endif #ifdef AF_WANPIPE - else if (family == AF_WANPIPE) + else if(family == AF_WANPIPE) return PPM_AF_WANPIPE; #endif #ifdef AF_LLC - else if (family == AF_LLC) + else if(family == AF_LLC) return PPM_AF_LLC; #endif #ifdef AF_CAN - else if (family == AF_CAN) + else if(family == AF_CAN) return PPM_AF_CAN; #endif #ifdef AF_TIPC - else if (family == AF_TIPC) + else if(family == AF_TIPC) return PPM_AF_TIPC; #endif #ifdef AF_BLUETOOTH - else if (family == AF_BLUETOOTH) + else if(family == AF_BLUETOOTH) return PPM_AF_BLUETOOTH; #endif #ifdef AF_IUCV - else if (family == AF_IUCV) + else if(family == AF_IUCV) return PPM_AF_IUCV; #endif #ifdef AF_RXRPC - else if (family == AF_RXRPC) + else if(family == AF_RXRPC) return PPM_AF_RXRPC; #endif #ifdef AF_ISDN - else if (family == AF_ISDN) + else if(family == AF_ISDN) return PPM_AF_ISDN; #endif #ifdef AF_PHONET - else if (family == AF_PHONET) + else if(family == AF_PHONET) return PPM_AF_PHONET; #endif #ifdef AF_IEEE802154 - else if (family == AF_IEEE802154) + else if(family == AF_IEEE802154) return PPM_AF_IEEE802154; #endif #ifdef AF_CAIF - else if (family == AF_CAIF) + else if(family == AF_CAIF) return PPM_AF_CAIF; #endif #ifdef AF_ALG - else if (family == AF_ALG) + else if(family == AF_ALG) return PPM_AF_ALG; #endif #ifdef AF_NFC - else if (family == AF_NFC) + else if(family == AF_NFC) return PPM_AF_NFC; #endif else { @@ -723,99 +707,96 @@ static __always_inline uint8_t socket_family_to_scap(uint8_t family) } } -static __always_inline uint32_t prot_flags_to_scap(int prot) -{ +static __always_inline uint32_t prot_flags_to_scap(int prot) { uint32_t res = 0; - if (prot & PROT_READ) + if(prot & PROT_READ) res |= PPM_PROT_READ; - if (prot & PROT_WRITE) + if(prot & PROT_WRITE) res |= PPM_PROT_WRITE; - if (prot & PROT_EXEC) + if(prot & PROT_EXEC) res |= PPM_PROT_EXEC; #ifdef PROT_SEM - if (prot & PROT_SEM) + if(prot & PROT_SEM) res |= PPM_PROT_SEM; #endif - if (prot & PROT_GROWSDOWN) + if(prot & PROT_GROWSDOWN) res |= PPM_PROT_GROWSDOWN; - if (prot & PROT_GROWSUP) + if(prot & PROT_GROWSUP) res |= PPM_PROT_GROWSUP; #ifdef PROT_SAO - if (prot & PROT_SAO) + if(prot & PROT_SAO) res |= PPM_PROT_SAO; #endif return res; } -static __always_inline uint32_t mmap_flags_to_scap(int flags) -{ +static __always_inline uint32_t mmap_flags_to_scap(int flags) { uint32_t res = 0; - if (flags & MAP_SHARED) + if(flags & MAP_SHARED) res |= PPM_MAP_SHARED; - if (flags & MAP_PRIVATE) + if(flags & MAP_PRIVATE) res |= PPM_MAP_PRIVATE; - if (flags & MAP_FIXED) + if(flags & MAP_FIXED) res |= PPM_MAP_FIXED; - if (flags & MAP_ANONYMOUS) + if(flags & MAP_ANONYMOUS) res |= PPM_MAP_ANONYMOUS; #ifdef MAP_32BIT - if (flags & MAP_32BIT) + if(flags & MAP_32BIT) res |= PPM_MAP_32BIT; #endif #ifdef MAP_RENAME - if (flags & MAP_RENAME) + if(flags & MAP_RENAME) res |= PPM_MAP_RENAME; #endif - if (flags & MAP_NORESERVE) + if(flags & MAP_NORESERVE) res |= PPM_MAP_NORESERVE; - if (flags & MAP_POPULATE) + if(flags & MAP_POPULATE) res |= PPM_MAP_POPULATE; - if (flags & MAP_NONBLOCK) + if(flags & MAP_NONBLOCK) res |= PPM_MAP_NONBLOCK; - if (flags & MAP_GROWSDOWN) + if(flags & MAP_GROWSDOWN) res |= PPM_MAP_GROWSDOWN; - if (flags & MAP_DENYWRITE) + if(flags & MAP_DENYWRITE) res |= PPM_MAP_DENYWRITE; - if (flags & MAP_EXECUTABLE) + if(flags & MAP_EXECUTABLE) res |= PPM_MAP_EXECUTABLE; #ifdef MAP_INHERIT - if (flags & MAP_INHERIT) + if(flags & MAP_INHERIT) res |= PPM_MAP_INHERIT; #endif - if (flags & MAP_FILE) + if(flags & MAP_FILE) res |= PPM_MAP_FILE; - if (flags & MAP_LOCKED) + if(flags & MAP_LOCKED) res |= PPM_MAP_LOCKED; return res; } -static __always_inline uint8_t fcntl_cmd_to_scap(unsigned long cmd) -{ - switch (cmd) { +static __always_inline uint8_t fcntl_cmd_to_scap(unsigned long cmd) { + switch(cmd) { case F_DUPFD: return PPM_FCNTL_F_DUPFD; case F_GETFD: @@ -894,398 +875,395 @@ static __always_inline uint8_t fcntl_cmd_to_scap(unsigned long cmd) } } - -static __always_inline uint8_t sockopt_level_to_scap(int level) -{ - switch (level) { - case SOL_SOCKET: - return PPM_SOCKOPT_LEVEL_SOL_SOCKET; +static __always_inline uint8_t sockopt_level_to_scap(int level) { + switch(level) { + case SOL_SOCKET: + return PPM_SOCKOPT_LEVEL_SOL_SOCKET; #ifdef SOL_TCP - case SOL_TCP: - return PPM_SOCKOPT_LEVEL_SOL_TCP; + case SOL_TCP: + return PPM_SOCKOPT_LEVEL_SOL_TCP; #endif - default: - /* no ASSERT as there are legitimate other levels we don't just support yet */ - return PPM_SOCKOPT_LEVEL_UNKNOWN; + default: + /* no ASSERT as there are legitimate other levels we don't just support yet */ + return PPM_SOCKOPT_LEVEL_UNKNOWN; } } -static __always_inline uint8_t sockopt_optname_to_scap(int level, int optname) -{ - if (level != SOL_SOCKET) - { +static __always_inline uint8_t sockopt_optname_to_scap(int level, int optname) { + if(level != SOL_SOCKET) { /* no ASSERT as there are legitimate other levels we don't just support yet */ return PPM_SOCKOPT_LEVEL_UNKNOWN; } - switch (optname) { + switch(optname) { #ifdef SO_DEBUG - case SO_DEBUG: - return PPM_SOCKOPT_SO_DEBUG; + case SO_DEBUG: + return PPM_SOCKOPT_SO_DEBUG; #endif #ifdef SO_REUSEADDR - case SO_REUSEADDR: - return PPM_SOCKOPT_SO_REUSEADDR; + case SO_REUSEADDR: + return PPM_SOCKOPT_SO_REUSEADDR; #endif #ifdef SO_TYPE - case SO_TYPE: - return PPM_SOCKOPT_SO_TYPE; + case SO_TYPE: + return PPM_SOCKOPT_SO_TYPE; #endif #ifdef SO_ERROR - case SO_ERROR: - return PPM_SOCKOPT_SO_ERROR; + case SO_ERROR: + return PPM_SOCKOPT_SO_ERROR; #endif #ifdef SO_DONTROUTE - case SO_DONTROUTE: - return PPM_SOCKOPT_SO_DONTROUTE; + case SO_DONTROUTE: + return PPM_SOCKOPT_SO_DONTROUTE; #endif #ifdef SO_BROADCAST - case SO_BROADCAST: - return PPM_SOCKOPT_SO_BROADCAST; + case SO_BROADCAST: + return PPM_SOCKOPT_SO_BROADCAST; #endif #ifdef SO_SNDBUF - case SO_SNDBUF: - return PPM_SOCKOPT_SO_SNDBUF; + case SO_SNDBUF: + return PPM_SOCKOPT_SO_SNDBUF; #endif #ifdef SO_RCVBUF - case SO_RCVBUF: - return PPM_SOCKOPT_SO_RCVBUF; + case SO_RCVBUF: + return PPM_SOCKOPT_SO_RCVBUF; #endif #ifdef SO_SNDBUFFORCE - case SO_SNDBUFFORCE: - return PPM_SOCKOPT_SO_SNDBUFFORCE; + case SO_SNDBUFFORCE: + return PPM_SOCKOPT_SO_SNDBUFFORCE; #endif #ifdef SO_RCVBUFFORCE - case SO_RCVBUFFORCE: - return PPM_SOCKOPT_SO_RCVBUFFORCE; + case SO_RCVBUFFORCE: + return PPM_SOCKOPT_SO_RCVBUFFORCE; #endif #ifdef SO_KEEPALIVE - case SO_KEEPALIVE: - return PPM_SOCKOPT_SO_KEEPALIVE; + case SO_KEEPALIVE: + return PPM_SOCKOPT_SO_KEEPALIVE; #endif #ifdef SO_OOBINLINE - case SO_OOBINLINE: - return PPM_SOCKOPT_SO_OOBINLINE; + case SO_OOBINLINE: + return PPM_SOCKOPT_SO_OOBINLINE; #endif #ifdef SO_NO_CHECK - case SO_NO_CHECK: - return PPM_SOCKOPT_SO_NO_CHECK; + case SO_NO_CHECK: + return PPM_SOCKOPT_SO_NO_CHECK; #endif #ifdef SO_PRIORITY - case SO_PRIORITY: - return PPM_SOCKOPT_SO_PRIORITY; + case SO_PRIORITY: + return PPM_SOCKOPT_SO_PRIORITY; #endif #ifdef SO_LINGER - case SO_LINGER: - return PPM_SOCKOPT_SO_LINGER; + case SO_LINGER: + return PPM_SOCKOPT_SO_LINGER; #endif #ifdef SO_BSDCOMPAT - case SO_BSDCOMPAT: - return PPM_SOCKOPT_SO_BSDCOMPAT; + case SO_BSDCOMPAT: + return PPM_SOCKOPT_SO_BSDCOMPAT; #endif #ifdef SO_REUSEPORT - case SO_REUSEPORT: - return PPM_SOCKOPT_SO_REUSEPORT; + case SO_REUSEPORT: + return PPM_SOCKOPT_SO_REUSEPORT; #endif #ifdef SO_PASSCRED - case SO_PASSCRED: - return PPM_SOCKOPT_SO_PASSCRED; + case SO_PASSCRED: + return PPM_SOCKOPT_SO_PASSCRED; #endif #ifdef SO_PEERCRED - case SO_PEERCRED: - return PPM_SOCKOPT_SO_PEERCRED; + case SO_PEERCRED: + return PPM_SOCKOPT_SO_PEERCRED; #endif #ifdef SO_RCVLOWAT - case SO_RCVLOWAT: - return PPM_SOCKOPT_SO_RCVLOWAT; + case SO_RCVLOWAT: + return PPM_SOCKOPT_SO_RCVLOWAT; #endif #ifdef SO_SNDLOWAT - case SO_SNDLOWAT: - return PPM_SOCKOPT_SO_SNDLOWAT; + case SO_SNDLOWAT: + return PPM_SOCKOPT_SO_SNDLOWAT; #endif /* We use this workaround to avoid 2 switch cases with the same value. * An `elif` approach is not enough if `SO_RCVTIMEO` is not defined. * In this case we have only `SO_RCVTIMEO_OLD` and `SO_RCVTIMEO_NEW` so - * we couldn't be able to detect the right flag value, for example: + * we couldn't be able to detect the right flag value, for example: * `SO_RCVTIMEO_OLD` is defined so we compile only this branch, but * actual value of `SO_RCVTIMEO` is `SO_RCVTIMEO_NEW`. * https://github.com/torvalds/linux/commit/a9beb86ae6e55bd92f38453c8623de60b8e5a308 */ #ifdef SO_RCVTIMEO - case SO_RCVTIMEO: - return PPM_SOCKOPT_SO_RCVTIMEO; + case SO_RCVTIMEO: + return PPM_SOCKOPT_SO_RCVTIMEO; +#endif +#if(defined(SO_RCVTIMEO_OLD) && !defined(SO_RCVTIMEO)) || \ + (defined(SO_RCVTIMEO_OLD) && (SO_RCVTIMEO_OLD != SO_RCVTIMEO)) + case SO_RCVTIMEO_OLD: + return PPM_SOCKOPT_SO_RCVTIMEO; #endif -#if (defined(SO_RCVTIMEO_OLD) && !defined(SO_RCVTIMEO)) || (defined(SO_RCVTIMEO_OLD) && (SO_RCVTIMEO_OLD != SO_RCVTIMEO)) - case SO_RCVTIMEO_OLD: - return PPM_SOCKOPT_SO_RCVTIMEO; -#endif -#if (defined(SO_RCVTIMEO_NEW) && !defined(SO_RCVTIMEO)) || (defined(SO_RCVTIMEO_NEW) && (SO_RCVTIMEO_NEW != SO_RCVTIMEO)) - case SO_RCVTIMEO_NEW: - return PPM_SOCKOPT_SO_RCVTIMEO; +#if(defined(SO_RCVTIMEO_NEW) && !defined(SO_RCVTIMEO)) || \ + (defined(SO_RCVTIMEO_NEW) && (SO_RCVTIMEO_NEW != SO_RCVTIMEO)) + case SO_RCVTIMEO_NEW: + return PPM_SOCKOPT_SO_RCVTIMEO; #endif /* Look at `SO_RCVTIMEO` */ #ifdef SO_SNDTIMEO - case SO_SNDTIMEO: - return PPM_SOCKOPT_SO_SNDTIMEO; + case SO_SNDTIMEO: + return PPM_SOCKOPT_SO_SNDTIMEO; #endif -#if (defined(SO_SNDTIMEO_OLD) && !defined(SO_SNDTIMEO)) || (defined(SO_SNDTIMEO_OLD) && (SO_SNDTIMEO_OLD != SO_SNDTIMEO)) - case SO_SNDTIMEO_OLD: - return PPM_SOCKOPT_SO_SNDTIMEO; +#if(defined(SO_SNDTIMEO_OLD) && !defined(SO_SNDTIMEO)) || \ + (defined(SO_SNDTIMEO_OLD) && (SO_SNDTIMEO_OLD != SO_SNDTIMEO)) + case SO_SNDTIMEO_OLD: + return PPM_SOCKOPT_SO_SNDTIMEO; #endif -#if (defined(SO_SNDTIMEO_NEW) && !defined(SO_SNDTIMEO)) || (defined(SO_SNDTIMEO_NEW) && (SO_SNDTIMEO_NEW != SO_SNDTIMEO)) - case SO_SNDTIMEO_NEW: - return PPM_SOCKOPT_SO_SNDTIMEO; +#if(defined(SO_SNDTIMEO_NEW) && !defined(SO_SNDTIMEO)) || \ + (defined(SO_SNDTIMEO_NEW) && (SO_SNDTIMEO_NEW != SO_SNDTIMEO)) + case SO_SNDTIMEO_NEW: + return PPM_SOCKOPT_SO_SNDTIMEO; #endif #ifdef SO_SECURITY_AUTHENTICATION - case SO_SECURITY_AUTHENTICATION: - return PPM_SOCKOPT_SO_SECURITY_AUTHENTICATION; + case SO_SECURITY_AUTHENTICATION: + return PPM_SOCKOPT_SO_SECURITY_AUTHENTICATION; #endif #ifdef SO_SECURITY_ENCRYPTION_TRANSPORT - case SO_SECURITY_ENCRYPTION_TRANSPORT: - return PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_TRANSPORT; + case SO_SECURITY_ENCRYPTION_TRANSPORT: + return PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_TRANSPORT; #endif #ifdef SO_SECURITY_ENCRYPTION_NETWORK - case SO_SECURITY_ENCRYPTION_NETWORK: - return PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_NETWORK; + case SO_SECURITY_ENCRYPTION_NETWORK: + return PPM_SOCKOPT_SO_SECURITY_ENCRYPTION_NETWORK; #endif #ifdef SO_BINDTODEVICE - case SO_BINDTODEVICE: - return PPM_SOCKOPT_SO_BINDTODEVICE; + case SO_BINDTODEVICE: + return PPM_SOCKOPT_SO_BINDTODEVICE; #endif #ifdef SO_ATTACH_FILTER - case SO_ATTACH_FILTER: - return PPM_SOCKOPT_SO_ATTACH_FILTER; + case SO_ATTACH_FILTER: + return PPM_SOCKOPT_SO_ATTACH_FILTER; #endif #ifdef SO_DETACH_FILTER - case SO_DETACH_FILTER: - return PPM_SOCKOPT_SO_DETACH_FILTER; + case SO_DETACH_FILTER: + return PPM_SOCKOPT_SO_DETACH_FILTER; #endif #ifdef SO_PEERNAME - case SO_PEERNAME: - return PPM_SOCKOPT_SO_PEERNAME; + case SO_PEERNAME: + return PPM_SOCKOPT_SO_PEERNAME; #endif #ifdef SO_TIMESTAMP - case SO_TIMESTAMP: - return PPM_SOCKOPT_SO_TIMESTAMP; + case SO_TIMESTAMP: + return PPM_SOCKOPT_SO_TIMESTAMP; #endif #ifdef SO_ACCEPTCONN - case SO_ACCEPTCONN: - return PPM_SOCKOPT_SO_ACCEPTCONN; + case SO_ACCEPTCONN: + return PPM_SOCKOPT_SO_ACCEPTCONN; #endif #ifdef SO_PEERSEC - case SO_PEERSEC: - return PPM_SOCKOPT_SO_PEERSEC; + case SO_PEERSEC: + return PPM_SOCKOPT_SO_PEERSEC; #endif #ifdef SO_PASSSEC - case SO_PASSSEC: - return PPM_SOCKOPT_SO_PASSSEC; + case SO_PASSSEC: + return PPM_SOCKOPT_SO_PASSSEC; #endif #ifdef SO_TIMESTAMPNS - case SO_TIMESTAMPNS: - return PPM_SOCKOPT_SO_TIMESTAMPNS; + case SO_TIMESTAMPNS: + return PPM_SOCKOPT_SO_TIMESTAMPNS; #endif #ifdef SO_MARK - case SO_MARK: - return PPM_SOCKOPT_SO_MARK; + case SO_MARK: + return PPM_SOCKOPT_SO_MARK; #endif #ifdef SO_TIMESTAMPING - case SO_TIMESTAMPING: - return PPM_SOCKOPT_SO_TIMESTAMPING; + case SO_TIMESTAMPING: + return PPM_SOCKOPT_SO_TIMESTAMPING; #endif #ifdef SO_PROTOCOL - case SO_PROTOCOL: - return PPM_SOCKOPT_SO_PROTOCOL; + case SO_PROTOCOL: + return PPM_SOCKOPT_SO_PROTOCOL; #endif #ifdef SO_DOMAIN - case SO_DOMAIN: - return PPM_SOCKOPT_SO_DOMAIN; + case SO_DOMAIN: + return PPM_SOCKOPT_SO_DOMAIN; #endif #ifdef SO_RXQ_OVFL - case SO_RXQ_OVFL: - return PPM_SOCKOPT_SO_RXQ_OVFL; + case SO_RXQ_OVFL: + return PPM_SOCKOPT_SO_RXQ_OVFL; #endif #ifdef SO_WIFI_STATUS - case SO_WIFI_STATUS: - return PPM_SOCKOPT_SO_WIFI_STATUS; + case SO_WIFI_STATUS: + return PPM_SOCKOPT_SO_WIFI_STATUS; #endif #ifdef SO_PEEK_OFF - case SO_PEEK_OFF: - return PPM_SOCKOPT_SO_PEEK_OFF; + case SO_PEEK_OFF: + return PPM_SOCKOPT_SO_PEEK_OFF; #endif #ifdef SO_NOFCS - case SO_NOFCS: - return PPM_SOCKOPT_SO_NOFCS; + case SO_NOFCS: + return PPM_SOCKOPT_SO_NOFCS; #endif #ifdef SO_LOCK_FILTER - case SO_LOCK_FILTER: - return PPM_SOCKOPT_SO_LOCK_FILTER; + case SO_LOCK_FILTER: + return PPM_SOCKOPT_SO_LOCK_FILTER; #endif #ifdef SO_SELECT_ERR_QUEUE - case SO_SELECT_ERR_QUEUE: - return PPM_SOCKOPT_SO_SELECT_ERR_QUEUE; + case SO_SELECT_ERR_QUEUE: + return PPM_SOCKOPT_SO_SELECT_ERR_QUEUE; #endif #ifdef SO_BUSY_POLL - case SO_BUSY_POLL: - return PPM_SOCKOPT_SO_BUSY_POLL; + case SO_BUSY_POLL: + return PPM_SOCKOPT_SO_BUSY_POLL; #endif #ifdef SO_MAX_PACING_RATE - case SO_MAX_PACING_RATE: - return PPM_SOCKOPT_SO_MAX_PACING_RATE; + case SO_MAX_PACING_RATE: + return PPM_SOCKOPT_SO_MAX_PACING_RATE; #endif #ifdef SO_BPF_EXTENSIONS - case SO_BPF_EXTENSIONS: - return PPM_SOCKOPT_SO_BPF_EXTENSIONS; + case SO_BPF_EXTENSIONS: + return PPM_SOCKOPT_SO_BPF_EXTENSIONS; #endif #ifdef SO_INCOMING_CPU - case SO_INCOMING_CPU: - return PPM_SOCKOPT_SO_INCOMING_CPU; + case SO_INCOMING_CPU: + return PPM_SOCKOPT_SO_INCOMING_CPU; #endif #ifdef SO_ATTACH_BPF - case SO_ATTACH_BPF: - return PPM_SOCKOPT_SO_ATTACH_BPF; + case SO_ATTACH_BPF: + return PPM_SOCKOPT_SO_ATTACH_BPF; #endif #ifdef SO_PEERGROUPS - case SO_PEERGROUPS: - return PPM_SOCKOPT_SO_PEERGROUPS; + case SO_PEERGROUPS: + return PPM_SOCKOPT_SO_PEERGROUPS; #endif #ifdef SO_MEMINFO - case SO_MEMINFO: - return PPM_SOCKOPT_SO_MEMINFO; + case SO_MEMINFO: + return PPM_SOCKOPT_SO_MEMINFO; #endif #ifdef SO_COOKIE - case SO_COOKIE: - return PPM_SOCKOPT_SO_COOKIE; + case SO_COOKIE: + return PPM_SOCKOPT_SO_COOKIE; #endif #ifdef __BPF_TRACING__ - case INT_MAX: - // forcefully disable switch jump table (clang-5 bug?) - // Basically, when labels values are similar AND the switch has many labels, - // compiler tends to build a jump table as optimization. - // This breaks with eBPF, and in our Makefile we already have the -fno-jump-tables; - // most probably clang5 had some kind of bug that caused -O2 mode to still use jump tables. - // Let's add a "very distant" label value to forcefully disable jump table. - // - // DO NOT merge with below default case - // otherwise this label will be skipped by compiler. - ASSERT(false); - return PPM_SOCKOPT_UNKNOWN; -#endif - default: - ASSERT(false); - return PPM_SOCKOPT_UNKNOWN; + case INT_MAX: + // forcefully disable switch jump table (clang-5 bug?) + // Basically, when labels values are similar AND the switch has many labels, + // compiler tends to build a jump table as optimization. + // This breaks with eBPF, and in our Makefile we already have the -fno-jump-tables; + // most probably clang5 had some kind of bug that caused -O2 mode to still use jump tables. + // Let's add a "very distant" label value to forcefully disable jump table. + // + // DO NOT merge with below default case + // otherwise this label will be skipped by compiler. + ASSERT(false); + return PPM_SOCKOPT_UNKNOWN; +#endif + default: + ASSERT(false); + return PPM_SOCKOPT_UNKNOWN; } } /* XXX this is very basic for the moment, we'll need to improve it */ -static __always_inline uint16_t poll_events_to_scap(short revents) -{ +static __always_inline uint16_t poll_events_to_scap(short revents) { uint16_t res = 0; - if (revents & POLLIN) + if(revents & POLLIN) res |= PPM_POLLIN; - if (revents & POLLPRI) + if(revents & POLLPRI) res |= PPM_POLLPRI; - if (revents & POLLOUT) + if(revents & POLLOUT) res |= PPM_POLLOUT; - if (revents & POLLRDHUP) + if(revents & POLLRDHUP) res |= PPM_POLLRDHUP; - if (revents & POLLERR) + if(revents & POLLERR) res |= PPM_POLLERR; - if (revents & POLLHUP) + if(revents & POLLHUP) res |= PPM_POLLHUP; - if (revents & POLLNVAL) + if(revents & POLLNVAL) res |= PPM_POLLNVAL; - if (revents & POLLRDNORM) + if(revents & POLLRDNORM) res |= PPM_POLLRDNORM; - if (revents & POLLRDBAND) + if(revents & POLLRDBAND) res |= PPM_POLLRDBAND; - if (revents & POLLWRNORM) + if(revents & POLLWRNORM) res |= PPM_POLLWRNORM; - if (revents & POLLWRBAND) + if(revents & POLLWRBAND) res |= PPM_POLLWRBAND; return res; } -static __always_inline uint16_t futex_op_to_scap(unsigned long op) -{ +static __always_inline uint16_t futex_op_to_scap(unsigned long op) { uint16_t res = 0; unsigned long flt_op = op & 127; - if (flt_op == FUTEX_WAIT) + if(flt_op == FUTEX_WAIT) res = PPM_FU_FUTEX_WAIT; - else if (flt_op == FUTEX_WAKE) + else if(flt_op == FUTEX_WAKE) res = PPM_FU_FUTEX_WAKE; - else if (flt_op == FUTEX_FD) + else if(flt_op == FUTEX_FD) res = PPM_FU_FUTEX_FD; - else if (flt_op == FUTEX_REQUEUE) + else if(flt_op == FUTEX_REQUEUE) res = PPM_FU_FUTEX_REQUEUE; - else if (flt_op == FUTEX_CMP_REQUEUE) + else if(flt_op == FUTEX_CMP_REQUEUE) res = PPM_FU_FUTEX_CMP_REQUEUE; - else if (flt_op == FUTEX_WAKE_OP) + else if(flt_op == FUTEX_WAKE_OP) res = PPM_FU_FUTEX_WAKE_OP; - else if (flt_op == FUTEX_LOCK_PI) + else if(flt_op == FUTEX_LOCK_PI) res = PPM_FU_FUTEX_LOCK_PI; - else if (flt_op == FUTEX_UNLOCK_PI) + else if(flt_op == FUTEX_UNLOCK_PI) res = PPM_FU_FUTEX_UNLOCK_PI; - else if (flt_op == FUTEX_TRYLOCK_PI) + else if(flt_op == FUTEX_TRYLOCK_PI) res = PPM_FU_FUTEX_TRYLOCK_PI; #ifdef FUTEX_WAIT_BITSET - else if (flt_op == FUTEX_WAIT_BITSET) + else if(flt_op == FUTEX_WAIT_BITSET) res = PPM_FU_FUTEX_WAIT_BITSET; #endif #ifdef FUTEX_WAKE_BITSET - else if (flt_op == FUTEX_WAKE_BITSET) + else if(flt_op == FUTEX_WAKE_BITSET) res = PPM_FU_FUTEX_WAKE_BITSET; #endif #ifdef FUTEX_WAIT_REQUEUE_PI - else if (flt_op == FUTEX_WAIT_REQUEUE_PI) + else if(flt_op == FUTEX_WAIT_REQUEUE_PI) res = PPM_FU_FUTEX_WAIT_REQUEUE_PI; #endif #ifdef FUTEX_CMP_REQUEUE_PI - else if (flt_op == FUTEX_CMP_REQUEUE_PI) + else if(flt_op == FUTEX_CMP_REQUEUE_PI) res = PPM_FU_FUTEX_CMP_REQUEUE_PI; #endif - if (op & FUTEX_PRIVATE_FLAG) + if(op & FUTEX_PRIVATE_FLAG) res |= PPM_FU_FUTEX_PRIVATE_FLAG; #ifdef FUTEX_CLOCK_REALTIME - if (op & FUTEX_CLOCK_REALTIME) + if(op & FUTEX_CLOCK_REALTIME) res |= PPM_FU_FUTEX_CLOCK_REALTIME; #endif return res; } -static __always_inline uint32_t access_flags_to_scap(unsigned flags) -{ +static __always_inline uint32_t access_flags_to_scap(unsigned flags) { uint32_t res = 0; - if (flags == 0/*F_OK*/) { + if(flags == 0 /*F_OK*/) { res = PPM_F_OK; } else { #if defined(__KERNEL__) || defined(__USE_VMLINUX__) - if (flags & MAY_EXEC) + if(flags & MAY_EXEC) res |= PPM_X_OK; - if (flags & MAY_READ) + if(flags & MAY_READ) res |= PPM_R_OK; - if (flags & MAY_WRITE) + if(flags & MAY_WRITE) res |= PPM_W_OK; -#else // in userspace - if (flags & X_OK) +#else // in userspace + if(flags & X_OK) res |= PPM_X_OK; - if (flags & R_OK) + if(flags & R_OK) res |= PPM_R_OK; - if (flags & W_OK) + if(flags & W_OK) res |= PPM_W_OK; #endif } @@ -1293,9 +1271,8 @@ static __always_inline uint32_t access_flags_to_scap(unsigned flags) return res; } -static __always_inline u8 rlimit_resource_to_scap(uint32_t resource) -{ - switch (resource) { +static __always_inline u8 rlimit_resource_to_scap(uint32_t resource) { + switch(resource) { case RLIMIT_CPU: return PPM_RLIMIT_CPU; case RLIMIT_FSIZE: @@ -1335,46 +1312,42 @@ static __always_inline u8 rlimit_resource_to_scap(uint32_t resource) } } -static __always_inline uint16_t shutdown_how_to_scap(unsigned long how) -{ - if (how == SHUT_RD) +static __always_inline uint16_t shutdown_how_to_scap(unsigned long how) { + if(how == SHUT_RD) return PPM_SHUT_RD; - else if (how == SHUT_WR) + else if(how == SHUT_WR) return PPM_SHUT_WR; - else if (how == SHUT_RDWR) + else if(how == SHUT_RDWR) return PPM_SHUT_RDWR; return PPM_SHUT_UNKNOWN; } -static __always_inline uint64_t lseek_whence_to_scap(unsigned long whence) -{ +static __always_inline uint64_t lseek_whence_to_scap(unsigned long whence) { uint64_t res = 0; - if (whence == SEEK_SET) + if(whence == SEEK_SET) res = PPM_SEEK_SET; - else if (whence == SEEK_CUR) + else if(whence == SEEK_CUR) res = PPM_SEEK_CUR; - else if (whence == SEEK_END) + else if(whence == SEEK_END) res = PPM_SEEK_END; return res; } -static __always_inline uint16_t semop_flags_to_scap(short flags) -{ +static __always_inline uint16_t semop_flags_to_scap(short flags) { uint16_t res = 0; - if (flags & IPC_NOWAIT) + if(flags & IPC_NOWAIT) res |= PPM_IPC_NOWAIT; - if (flags & SEM_UNDO) + if(flags & SEM_UNDO) res |= PPM_SEM_UNDO; return res; } -static __always_inline uint32_t pf_flags_to_scap(unsigned long flags) -{ +static __always_inline uint32_t pf_flags_to_scap(unsigned long flags) { uint32_t res = 0; /* Page fault error codes don't seem to be clearly defined in header @@ -1383,52 +1356,50 @@ static __always_inline uint32_t pf_flags_to_scap(unsigned long flags) * the x86 manual. If we end up supporting another arch for page faults, * refactor this. */ - if (flags & 0x1) + if(flags & 0x1) res |= PPM_PF_PROTECTION_VIOLATION; else res |= PPM_PF_PAGE_NOT_PRESENT; - if (flags & 0x2) + if(flags & 0x2) res |= PPM_PF_WRITE_ACCESS; else res |= PPM_PF_READ_ACCESS; - if (flags & 0x4) + if(flags & 0x4) res |= PPM_PF_USER_FAULT; else res |= PPM_PF_SUPERVISOR_FAULT; - if (flags & 0x8) + if(flags & 0x8) res |= PPM_PF_RESERVED_PAGE; - if (flags & 0x10) + if(flags & 0x10) res |= PPM_PF_INSTRUCTION_FETCH; return res; } -static __always_inline uint32_t flock_flags_to_scap(int flags) -{ +static __always_inline uint32_t flock_flags_to_scap(int flags) { uint32_t res = 0; - if (flags & LOCK_EX) + if(flags & LOCK_EX) res |= PPM_LOCK_EX; - if (flags & LOCK_SH) + if(flags & LOCK_SH) res |= PPM_LOCK_SH; - if (flags & LOCK_UN) + if(flags & LOCK_UN) res |= PPM_LOCK_UN; - if (flags & LOCK_NB) + if(flags & LOCK_NB) res |= PPM_LOCK_NB; return res; } -static __always_inline uint8_t quotactl_type_to_scap(unsigned long cmd) -{ - switch (cmd & SUBCMDMASK) { +static __always_inline uint8_t quotactl_type_to_scap(unsigned long cmd) { + switch(cmd & SUBCMDMASK) { case USRQUOTA: return PPM_USRQUOTA; case GRPQUOTA: @@ -1437,11 +1408,10 @@ static __always_inline uint8_t quotactl_type_to_scap(unsigned long cmd) return 0; } -static __always_inline uint16_t quotactl_cmd_to_scap(unsigned long cmd) -{ +static __always_inline uint16_t quotactl_cmd_to_scap(unsigned long cmd) { uint16_t res; - switch (cmd >> SUBCMDSHIFT) { + switch(cmd >> SUBCMDSHIFT) { case Q_SYNC: res = PPM_Q_SYNC; break; @@ -1496,9 +1466,8 @@ static __always_inline uint16_t quotactl_cmd_to_scap(unsigned long cmd) return res; } -static __always_inline uint8_t quotactl_fmt_to_scap(unsigned long fmt) -{ - switch (fmt) { +static __always_inline uint8_t quotactl_fmt_to_scap(unsigned long fmt) { + switch(fmt) { case QFMT_VFS_OLD: return PPM_QFMT_VFS_OLD; case QFMT_VFS_V0: @@ -1512,46 +1481,57 @@ static __always_inline uint8_t quotactl_fmt_to_scap(unsigned long fmt) } } -static __always_inline uint32_t semget_flags_to_scap(unsigned flags) -{ +static __always_inline uint32_t semget_flags_to_scap(unsigned flags) { uint32_t res = 0; - if (flags & IPC_CREAT) + if(flags & IPC_CREAT) res |= PPM_IPC_CREAT; - if (flags & IPC_EXCL) + if(flags & IPC_EXCL) res |= PPM_IPC_EXCL; return res; } -static __always_inline uint32_t semctl_cmd_to_scap(unsigned cmd) -{ - switch (cmd) { - case IPC_STAT: return PPM_IPC_STAT; - case IPC_SET: return PPM_IPC_SET; - case IPC_RMID: return PPM_IPC_RMID; - case IPC_INFO: return PPM_IPC_INFO; - case SEM_INFO: return PPM_SEM_INFO; - case SEM_STAT: return PPM_SEM_STAT; - case GETALL: return PPM_GETALL; - case GETNCNT: return PPM_GETNCNT; - case GETPID: return PPM_GETPID; - case GETVAL: return PPM_GETVAL; - case GETZCNT: return PPM_GETZCNT; - case SETALL: return PPM_SETALL; - case SETVAL: return PPM_SETVAL; +static __always_inline uint32_t semctl_cmd_to_scap(unsigned cmd) { + switch(cmd) { + case IPC_STAT: + return PPM_IPC_STAT; + case IPC_SET: + return PPM_IPC_SET; + case IPC_RMID: + return PPM_IPC_RMID; + case IPC_INFO: + return PPM_IPC_INFO; + case SEM_INFO: + return PPM_SEM_INFO; + case SEM_STAT: + return PPM_SEM_STAT; + case GETALL: + return PPM_GETALL; + case GETNCNT: + return PPM_GETNCNT; + case GETPID: + return PPM_GETPID; + case GETVAL: + return PPM_GETVAL; + case GETZCNT: + return PPM_GETZCNT; + case SETALL: + return PPM_SETALL; + case SETVAL: + return PPM_SETVAL; #ifdef __BPF_TRACING__ // forcefully disable switch jump table, see sockopt_optname_to_scap() for more info - case INT_MAX: return 0; + case INT_MAX: + return 0; #endif } return 0; } -static __always_inline uint16_t ptrace_requests_to_scap(unsigned long req) -{ - switch (req) { +static __always_inline uint16_t ptrace_requests_to_scap(unsigned long req) { + switch(req) { #ifdef PTRACE_SINGLEBLOCK case PTRACE_SINGLEBLOCK: return PPM_PTRACE_SINGLEBLOCK; @@ -1660,7 +1640,7 @@ static __always_inline uint16_t ptrace_requests_to_scap(unsigned long req) #ifdef PTRACE_POKEUSR case PTRACE_POKEUSR: return PPM_PTRACE_POKEUSR; -#endif +#endif case PTRACE_POKEDATA: return PPM_PTRACE_POKEDATA; case PTRACE_POKETEXT: @@ -1680,25 +1660,23 @@ static __always_inline uint16_t ptrace_requests_to_scap(unsigned long req) } } -static __always_inline uint32_t execveat_flags_to_scap(unsigned long flags) -{ +static __always_inline uint32_t execveat_flags_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef AT_EMPTY_PATH - if (flags & AT_EMPTY_PATH) + if(flags & AT_EMPTY_PATH) res |= PPM_EXVAT_AT_EMPTY_PATH; #endif #ifdef AT_SYMLINK_NOFOLLOW - if (flags & AT_SYMLINK_NOFOLLOW) + if(flags & AT_SYMLINK_NOFOLLOW) res |= PPM_EXVAT_AT_SYMLINK_NOFOLLOW; #endif return res; } -static __always_inline uint32_t fsconfig_cmds_to_scap(uint32_t cmd) -{ +static __always_inline uint32_t fsconfig_cmds_to_scap(uint32_t cmd) { /* * fsconfig opcodes are defined via enum in uapi/linux/mount.h. * It is userspace API (thus stable) and arch-independent. @@ -1709,193 +1687,187 @@ static __always_inline uint32_t fsconfig_cmds_to_scap(uint32_t cmd) return cmd; } -static __always_inline uint32_t mlockall_flags_to_scap(unsigned long flags) -{ +static __always_inline uint32_t mlockall_flags_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef MCL_CURRENT - if (flags & MCL_CURRENT) + if(flags & MCL_CURRENT) res |= PPM_MLOCKALL_MCL_CURRENT; #endif #ifdef MCL_FUTURE - if (flags & MCL_FUTURE) + if(flags & MCL_FUTURE) res |= PPM_MLOCKALL_MCL_FUTURE; #endif #ifdef MCL_ONFAULT - if (flags & MCL_ONFAULT) + if(flags & MCL_ONFAULT) res |= PPM_MLOCKALL_MCL_ONFAULT; #endif return res; } -static __always_inline uint32_t mlock2_flags_to_scap(unsigned long flags) -{ +static __always_inline uint32_t mlock2_flags_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef MLOCK_ONFAULT - if (flags & MLOCK_ONFAULT) + if(flags & MLOCK_ONFAULT) res |= PPM_MLOCK_ONFAULT; #endif return res; } -static __always_inline uint32_t memfd_create_flags_to_scap(uint32_t flags) -{ +static __always_inline uint32_t memfd_create_flags_to_scap(uint32_t flags) { uint32_t res = 0; #ifdef MFD_CLOEXEC - if(flags & MFD_CLOEXEC) res |= PPM_MFD_CLOEXEC; + if(flags & MFD_CLOEXEC) + res |= PPM_MFD_CLOEXEC; #endif #ifdef MFD_ALLOW_SEALING - if(flags & MFD_ALLOW_SEALING) res |= PPM_MFD_ALLOW_SEALING; + if(flags & MFD_ALLOW_SEALING) + res |= PPM_MFD_ALLOW_SEALING; #endif #ifdef MFD_HUGETLB - if(flags & MFD_HUGETLB) res |= PPM_MFD_HUGETLB; + if(flags & MFD_HUGETLB) + res |= PPM_MFD_HUGETLB; #endif -return res; + return res; } -static __always_inline uint32_t unlinkat_flags_to_scap(int32_t flags) -{ +static __always_inline uint32_t unlinkat_flags_to_scap(int32_t flags) { uint32_t res = 0; - if (flags & AT_REMOVEDIR) + if(flags & AT_REMOVEDIR) res |= PPM_AT_REMOVEDIR; return res; } -static __always_inline uint32_t linkat_flags_to_scap(int32_t flags) -{ +static __always_inline uint32_t linkat_flags_to_scap(int32_t flags) { uint32_t res = 0; - if (flags & AT_SYMLINK_FOLLOW) + if(flags & AT_SYMLINK_FOLLOW) res |= PPM_AT_SYMLINK_FOLLOW; #ifdef AT_EMPTY_PATH - if (flags & AT_EMPTY_PATH) + if(flags & AT_EMPTY_PATH) res |= PPM_AT_EMPTY_PATH; #endif return res; } -static __always_inline uint32_t newfstatat_flags_to_scap(int32_t flags) -{ +static __always_inline uint32_t newfstatat_flags_to_scap(int32_t flags) { uint32_t res = 0; - /* AT_SYMLINK_NOFOLLOW was introduced in kernel 2.6.16, we don't need to check if it's defined */ - if (flags & AT_SYMLINK_NOFOLLOW) + /* AT_SYMLINK_NOFOLLOW was introduced in kernel 2.6.16, we don't need to check if it's defined + */ + if(flags & AT_SYMLINK_NOFOLLOW) res |= PPM_AT_SYMLINK_NOFOLLOW; #ifdef AT_EMPTY_PATH - if (flags & AT_EMPTY_PATH) + if(flags & AT_EMPTY_PATH) res |= PPM_AT_EMPTY_PATH; #endif #ifdef AT_NO_AUTOMOUNT - if (flags & AT_NO_AUTOMOUNT) + if(flags & AT_NO_AUTOMOUNT) res |= PPM_AT_NO_AUTOMOUNT; #endif return res; } -static __always_inline uint32_t chmod_mode_to_scap(unsigned long modes) -{ +static __always_inline uint32_t chmod_mode_to_scap(unsigned long modes) { uint32_t res = 0; - if (modes & S_IRUSR) + if(modes & S_IRUSR) res |= PPM_S_IRUSR; - if (modes & S_IWUSR) + if(modes & S_IWUSR) res |= PPM_S_IWUSR; - if (modes & S_IXUSR) + if(modes & S_IXUSR) res |= PPM_S_IXUSR; /* * PPM_S_IRWXU == S_IRUSR | S_IWUSR | S_IXUSR */ - if (modes & S_IRGRP) + if(modes & S_IRGRP) res |= PPM_S_IRGRP; - if (modes & S_IWGRP) + if(modes & S_IWGRP) res |= PPM_S_IWGRP; - if (modes & S_IXGRP) + if(modes & S_IXGRP) res |= PPM_S_IXGRP; /* * PPM_S_IRWXG == S_IRGRP | S_IWGRP | S_IXGRP */ - if (modes & S_IROTH) + if(modes & S_IROTH) res |= PPM_S_IROTH; - if (modes & S_IWOTH) + if(modes & S_IWOTH) res |= PPM_S_IWOTH; - if (modes & S_IXOTH) + if(modes & S_IXOTH) res |= PPM_S_IXOTH; /* * PPM_S_IRWXO == S_IROTH | S_IWOTH | S_IXOTH */ - if (modes & S_ISUID) + if(modes & S_ISUID) res |= PPM_S_ISUID; - if (modes & S_ISGID) + if(modes & S_ISGID) res |= PPM_S_ISGID; - if (modes & S_ISVTX) + if(modes & S_ISVTX) res |= PPM_S_ISVTX; return res; } -static __always_inline uint32_t umount2_flags_to_scap(int flags) -{ +static __always_inline uint32_t umount2_flags_to_scap(int flags) { uint32_t res = 0; #ifdef MNT_FORCE - if (flags & MNT_FORCE) + if(flags & MNT_FORCE) res |= PPM_MNT_FORCE; #endif #ifdef MNT_DETACH - if (flags & MNT_DETACH) + if(flags & MNT_DETACH) res |= PPM_MNT_DETACH; #endif #ifdef MNT_EXPIRE - if (flags & MNT_EXPIRE) + if(flags & MNT_EXPIRE) res |= PPM_MNT_EXPIRE; #endif #ifdef UMOUNT_NOFOLLOW - if (flags & UMOUNT_NOFOLLOW) + if(flags & UMOUNT_NOFOLLOW) res |= PPM_UMOUNT_NOFOLLOW; #endif return res; } -static __always_inline uint32_t fchownat_flags_to_scap(unsigned long flags) -{ +static __always_inline uint32_t fchownat_flags_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef AT_SYMLINK_FOLLOW - if (flags & AT_SYMLINK_FOLLOW) + if(flags & AT_SYMLINK_FOLLOW) res |= PPM_AT_SYMLINK_FOLLOW; #endif #ifdef AT_EMPTY_PATH - if (flags & AT_EMPTY_PATH) + if(flags & AT_EMPTY_PATH) res |= PPM_AT_EMPTY_PATH; #endif return res; } -static __always_inline uint64_t capabilities_to_scap(unsigned long caps) -{ +static __always_inline uint64_t capabilities_to_scap(unsigned long caps) { uint64_t res = 0; - + #ifdef CAP_CHOWN if(caps & (1UL << CAP_CHOWN)) res |= PPM_CAP_CHOWN; @@ -2064,79 +2036,74 @@ static __always_inline uint64_t capabilities_to_scap(unsigned long caps) return res; } -static __always_inline uint32_t dup3_flags_to_scap(int flags) -{ +static __always_inline uint32_t dup3_flags_to_scap(int flags) { uint32_t res = 0; #ifdef O_CLOEXEC - if (flags & O_CLOEXEC) + if(flags & O_CLOEXEC) res |= PPM_O_CLOEXEC; #endif return res; } -static __always_inline uint32_t pipe2_flags_to_scap(int32_t flags) -{ +static __always_inline uint32_t pipe2_flags_to_scap(int32_t flags) { uint32_t res = 0; /* We need to explicitly handle the negative case otherwise `-1` will match all `flags & ...` */ - if(flags < 0) - { + if(flags < 0) { return res; } #ifdef O_CLOEXEC - if (flags & O_CLOEXEC) + if(flags & O_CLOEXEC) res |= PPM_O_CLOEXEC; #endif #ifdef O_DIRECT - if (flags & O_DIRECT) + if(flags & O_DIRECT) res |= PPM_O_DIRECT; #endif #ifdef O_NONBLOCK - if (flags & O_NONBLOCK) + if(flags & O_NONBLOCK) res |= PPM_O_NONBLOCK; #endif return res; } -static __always_inline uint32_t epoll_create1_flags_to_scap(uint32_t flags) -{ +static __always_inline uint32_t epoll_create1_flags_to_scap(uint32_t flags) { uint32_t res = 0; #ifdef EPOLL_CLOEXEC - if (flags & EPOLL_CLOEXEC) + if(flags & EPOLL_CLOEXEC) res |= PPM_EPOLL_CLOEXEC; #endif return res; } -static __always_inline uint32_t splice_flags_to_scap(uint32_t flags) -{ +static __always_inline uint32_t splice_flags_to_scap(uint32_t flags) { uint32_t res = 0; #ifdef SPLICE_F_MOVE - if (flags & SPLICE_F_MOVE) + if(flags & SPLICE_F_MOVE) res |= PPM_SPLICE_F_MOVE; #endif #ifdef SPLICE_F_NONBLOCK - if (flags & SPLICE_F_NONBLOCK) + if(flags & SPLICE_F_NONBLOCK) res |= PPM_SPLICE_F_NONBLOCK; #endif #ifdef SPLICE_F_MORE - if (flags & SPLICE_F_MORE) + if(flags & SPLICE_F_MORE) res |= PPM_SPLICE_F_MORE; #endif #ifdef SPLICE_F_GIFT - if (flags & SPLICE_F_GIFT) + if(flags & SPLICE_F_GIFT) res |= PPM_SPLICE_F_GIFT; #endif return res; } -static __always_inline uint32_t pidfd_open_flags_to_scap(uint32_t flags) -{ +static __always_inline uint32_t pidfd_open_flags_to_scap(uint32_t flags) { uint32_t res = 0; // See https://elixir.bootlin.com/linux/v5.10.185/source/include/uapi/linux/pidfd.h#L10 #ifdef O_NONBLOCK - if(flags & O_NONBLOCK) res |= PPM_PIDFD_NONBLOCK; + if(flags & O_NONBLOCK) + res |= PPM_PIDFD_NONBLOCK; #endif return res; } @@ -2147,13 +2114,11 @@ static __always_inline uint32_t pidfd_open_flags_to_scap(uint32_t flags) #define PPM_OVERLAYFS_SUPER_MAGIC 0x794c7630 #endif -static __always_inline uint32_t prctl_options_to_scap(int options) -{ +static __always_inline uint32_t prctl_options_to_scap(int options) { return (uint32_t)options; } -static __always_inline uint32_t finit_module_flags_to_scap(int32_t flags) -{ +static __always_inline uint32_t finit_module_flags_to_scap(int32_t flags) { int32_t res = 0; #ifdef MODULE_INIT_IGNORE_MODVERSIONS if(flags & MODULE_INIT_IGNORE_MODVERSIONS) @@ -2173,8 +2138,7 @@ static __always_inline uint32_t finit_module_flags_to_scap(int32_t flags) return res; } -static __always_inline uint32_t mknod_mode_to_scap(uint32_t modes) -{ +static __always_inline uint32_t mknod_mode_to_scap(uint32_t modes) { uint32_t res = chmod_mode_to_scap(modes); /* @@ -2182,43 +2146,43 @@ static __always_inline uint32_t mknod_mode_to_scap(uint32_t modes) */ #ifdef S_IFMT - switch(modes & S_IFMT){ + switch(modes & S_IFMT) { #ifdef S_IFSOCK - case S_IFSOCK: - res |= PPM_S_IFSOCK; - break; + case S_IFSOCK: + res |= PPM_S_IFSOCK; + break; #endif #ifdef S_IFREG - // Zero file type is equivalent to type S_IFREG. - case 0: - case S_IFREG: - res |= PPM_S_IFREG; - break; + // Zero file type is equivalent to type S_IFREG. + case 0: + case S_IFREG: + res |= PPM_S_IFREG; + break; #endif #ifdef S_IFBLK - case S_IFBLK: - res |= PPM_S_IFBLK; - break; + case S_IFBLK: + res |= PPM_S_IFBLK; + break; #endif #ifdef S_IFCHR - case S_IFCHR: - res |= PPM_S_IFCHR; - break; + case S_IFCHR: + res |= PPM_S_IFCHR; + break; #endif #ifdef S_IFIFO - case S_IFIFO: - res |= PPM_S_IFIFO; - break; + case S_IFIFO: + res |= PPM_S_IFIFO; + break; #endif - default: - break; + default: + break; } #endif return res; } -static __always_inline uint32_t bpf_cmd_to_scap (unsigned long cmd){ +static __always_inline uint32_t bpf_cmd_to_scap(unsigned long cmd) { /* * bpf opcodes are defined via enum in uapi/linux/bpf.h. * It is userspace API (thus stable) and arch-independent. @@ -2230,18 +2194,17 @@ static __always_inline uint32_t bpf_cmd_to_scap (unsigned long cmd){ return cmd; } -static __always_inline uint32_t delete_module_flags_to_scap(unsigned long flags) -{ +static __always_inline uint32_t delete_module_flags_to_scap(unsigned long flags) { uint32_t res = 0; #ifdef O_NONBLOCK - if (flags & O_NONBLOCK) + if(flags & O_NONBLOCK) res |= PPM_DELETE_MODULE_O_NONBLOCK; #endif #ifdef O_TRUNC - if (flags & O_TRUNC) + if(flags & O_TRUNC) res |= PPM_DELETE_MODULE_O_TRUNC; #endif return res; } -#endif /* PPM_FLAG_HELPERS_H_ */ \ No newline at end of file +#endif /* PPM_FLAG_HELPERS_H_ */ diff --git a/driver/ppm_ringbuffer.h b/driver/ppm_ringbuffer.h index 92eae38ed9..f8e427fe0e 100644 --- a/driver/ppm_ringbuffer.h +++ b/driver/ppm_ringbuffer.h @@ -23,12 +23,12 @@ or GPL2.txt for full copies of the license. * - greater than `2 * PAGE_SIZE`. * - a multiple of the system PAGE_SIZE. * - a power of 2. - * + * * Returns true if the buffer has a valid dimension. */ -static inline bool validate_buffer_bytes_dim(unsigned long buf_bytes_dim, unsigned long page_size) -{ - return ((buf_bytes_dim > (2 * page_size)) && ((buf_bytes_dim % page_size) == 0) && ((buf_bytes_dim & (buf_bytes_dim - 1)) == 0)); +static inline bool validate_buffer_bytes_dim(unsigned long buf_bytes_dim, unsigned long page_size) { + return ((buf_bytes_dim > (2 * page_size)) && ((buf_bytes_dim % page_size) == 0) && + ((buf_bytes_dim & (buf_bytes_dim - 1)) == 0)); } /* @@ -37,9 +37,12 @@ static inline bool validate_buffer_bytes_dim(unsigned long buf_bytes_dim, unsign struct ppm_ring_buffer_info { volatile uint32_t head; volatile uint32_t tail; - volatile uint64_t n_evts; /* Total number of events that were received by the driver. */ - volatile uint64_t n_drops_buffer; /* Total number of kernel side drops due to full buffer, includes all categories below, likely higher than sum of syscall categories. */ - /* Kernel side drops due to full buffer for categories of system calls. Not all system calls of interest are mapped into one of the categories. */ + volatile uint64_t n_evts; /* Total number of events that were received by the driver. */ + volatile uint64_t + n_drops_buffer; /* Total number of kernel side drops due to full buffer, includes all + categories below, likely higher than sum of syscall categories. */ + /* Kernel side drops due to full buffer for categories of system calls. Not all system calls of + * interest are mapped into one of the categories. */ volatile uint64_t n_drops_buffer_clone_fork_enter; volatile uint64_t n_drops_buffer_clone_fork_exit; volatile uint64_t n_drops_buffer_execve_enter; @@ -50,13 +53,16 @@ struct ppm_ring_buffer_info { volatile uint64_t n_drops_buffer_open_exit; volatile uint64_t n_drops_buffer_dir_file_enter; volatile uint64_t n_drops_buffer_dir_file_exit; - volatile uint64_t n_drops_buffer_other_interest_enter; /* Category of other system calls of interest, not all other system calls that did not match a category from above. */ + volatile uint64_t + n_drops_buffer_other_interest_enter; /* Category of other system calls of interest, not + all other system calls that did not match a + category from above. */ volatile uint64_t n_drops_buffer_other_interest_exit; volatile uint64_t n_drops_buffer_close_exit; volatile uint64_t n_drops_buffer_proc_exit; - volatile uint64_t n_drops_pf; /* Number of dropped events (page faults). */ - volatile uint64_t n_preemptions; /* Number of preemptions. */ - volatile uint64_t n_context_switches; /* Number of received context switch events. */ + volatile uint64_t n_drops_pf; /* Number of dropped events (page faults). */ + volatile uint64_t n_preemptions; /* Number of preemptions. */ + volatile uint64_t n_context_switches; /* Number of received context switch events. */ }; #endif /* PPM_RINGBUFFER_H_ */ diff --git a/driver/ppm_tp.c b/driver/ppm_tp.c index 46f5ab87df..e426aabc29 100644 --- a/driver/ppm_tp.c +++ b/driver/ppm_tp.c @@ -10,6 +10,6 @@ const char *kmod_prog_names[] = { #define X(name, path) path, - KMOD_PROGS + KMOD_PROGS #undef X }; diff --git a/driver/ppm_tp.h b/driver/ppm_tp.h index a38e9d0c45..5e8e92cf7a 100644 --- a/driver/ppm_tp.h +++ b/driver/ppm_tp.h @@ -9,7 +9,7 @@ #pragma once /* | name | path | */ -#define KMOD_PROGS \ +#define KMOD_PROGS \ X(KMOD_PROG_SYS_ENTER, "sys_enter") \ X(KMOD_PROG_SYS_EXIT, "sys_exit") \ X(KMOD_PROG_SCHED_PROC_EXIT, "sched_process_exit") \ @@ -20,12 +20,11 @@ X(KMOD_PROG_SCHED_PROC_FORK, "sched_process_fork") \ X(KMOD_PROG_SCHED_PROC_EXEC, "sched_process_exec") -typedef enum -{ +typedef enum { #define X(name, path) name, KMOD_PROGS #undef X - KMOD_PROG_ATTACHED_MAX, + KMOD_PROG_ATTACHED_MAX, } kmod_prog_codes; extern const char *kmod_prog_names[]; diff --git a/driver/ppm_version.h b/driver/ppm_version.h index 2aca02cf9f..8bbad2a813 100644 --- a/driver/ppm_version.h +++ b/driver/ppm_version.h @@ -22,10 +22,10 @@ */ #ifdef RHEL_RELEASE_CODE #define PPM_RHEL_RELEASE_CODE RHEL_RELEASE_CODE -#define PPM_RHEL_RELEASE_VERSION(x,y) RHEL_RELEASE_VERSION(x,y) +#define PPM_RHEL_RELEASE_VERSION(x, y) RHEL_RELEASE_VERSION(x, y) #else #define PPM_RHEL_RELEASE_CODE 0 -#define PPM_RHEL_RELEASE_VERSION(x,y) 0 +#define PPM_RHEL_RELEASE_VERSION(x, y) 0 #endif #endif /* PPM_VERSION_H_ */ diff --git a/driver/socketcall_to_syscall.h b/driver/socketcall_to_syscall.h index 2200cc1d87..d0f1eeba03 100644 --- a/driver/socketcall_to_syscall.h +++ b/driver/socketcall_to_syscall.h @@ -18,13 +18,11 @@ or GPL2.txt for full copies of the license. */ #include -static inline int socketcall_code_to_syscall_code(int socketcall_code, bool* is_syscall_return) -{ +static inline int socketcall_code_to_syscall_code(int socketcall_code, bool* is_syscall_return) { /* First we check if we can convert a valid syscall code */ *is_syscall_return = true; - switch(socketcall_code) - { + switch(socketcall_code) { #ifdef __NR_socket case SYS_SOCKET: return __NR_socket; @@ -149,8 +147,7 @@ static inline int socketcall_code_to_syscall_code(int socketcall_code, bool* is_ */ *is_syscall_return = false; - switch(socketcall_code) - { + switch(socketcall_code) { #ifdef SYS_SOCKET case SYS_SOCKET: return PPME_SOCKET_SOCKET_E; diff --git a/driver/systype_compat.h b/driver/systype_compat.h index 1606f76c74..5adc8391da 100644 --- a/driver/systype_compat.h +++ b/driver/systype_compat.h @@ -10,17 +10,16 @@ #define __SYSTYPE_COMPACT_H__ /* If WIFEXITED(STATUS), the low-order 8 bits of the status. */ -#define __WEXITSTATUS(status) (((status)&0xff00) >> 8) +#define __WEXITSTATUS(status) (((status) & 0xff00) >> 8) /* If WIFSIGNALED(STATUS), the terminating signal. */ -#define __WTERMSIG(status) ((status)&0x7f) +#define __WTERMSIG(status) ((status) & 0x7f) /* Nonzero if STATUS indicates termination by a signal. */ -#define __WIFSIGNALED(status) \ - (((signed char)(((status)&0x7f) + 1) >> 1) > 0) +#define __WIFSIGNALED(status) (((signed char)(((status) & 0x7f) + 1) >> 1) > 0) /* Nonzero if STATUS indicates the child dumped core. */ -#define __WCOREDUMP(status) ((status)&__WCOREFLAG) +#define __WCOREDUMP(status) ((status) & __WCOREFLAG) #define __WCOREFLAG 0x80 diff --git a/test/drivers/CMakeLists.txt b/test/drivers/CMakeLists.txt index a8ae4ad41a..e1dae126e7 100644 --- a/test/drivers/CMakeLists.txt +++ b/test/drivers/CMakeLists.txt @@ -1,64 +1,58 @@ message(STATUS "Drivers tests build enabled") -## Configure ia32 action test +# Configure ia32 action test option(ENABLE_IA32_TESTS "Enable ia32 tests. Require ia32 glibc and gcc." ON) if(ENABLE_IA32_TESTS) - configure_file(${CMAKE_CURRENT_SOURCE_DIR}/test_suites/actions_suite/ia32.cpp.in ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/actions_suite/ia32.cpp) + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/actions_suite/ia32.cpp.in + ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/actions_suite/ia32.cpp + ) endif() -## Syscall_exit suite files. -file(GLOB_RECURSE SYSCALL_EXIT_TEST_SUITE ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/syscall_exit_suite/*.cpp) +# Syscall_exit suite files. +file(GLOB_RECURSE SYSCALL_EXIT_TEST_SUITE + ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/syscall_exit_suite/*.cpp +) -## Syscall_enter suite files. -file(GLOB_RECURSE SYSCALL_ENTER_TEST_SUITE ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/syscall_enter_suite/*.cpp) +# Syscall_enter suite files. +file(GLOB_RECURSE SYSCALL_ENTER_TEST_SUITE + ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/syscall_enter_suite/*.cpp +) -## Generic tracepoints suite files. -file(GLOB_RECURSE GENERIC_TRACEPOINTS_TEST_SUITE ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/generic_tracepoints_suite/*.cpp) +# Generic tracepoints suite files. +file(GLOB_RECURSE GENERIC_TRACEPOINTS_TEST_SUITE + ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/generic_tracepoints_suite/*.cpp +) -## Actions suite files +# Actions suite files file(GLOB_RECURSE ACTIONS_TEST_SUITE ${CMAKE_CURRENT_SOURCE_DIR}/test_suites/actions_suite/*.cpp) include(libscap) set(DRIVERS_TEST_SOURCES - ./start_tests.cpp - ./event_class/event_class.cpp - ./flags/capabilities.cpp - ./helpers/proc_parsing.cpp - ./helpers/file_opener.cpp - "${SYSCALL_EXIT_TEST_SUITE}" - "${SYSCALL_ENTER_TEST_SUITE}" - "${GENERIC_TRACEPOINTS_TEST_SUITE}" - "${ACTIONS_TEST_SUITE}" + ./start_tests.cpp + ./event_class/event_class.cpp + ./flags/capabilities.cpp + ./helpers/proc_parsing.cpp + ./helpers/file_opener.cpp + "${SYSCALL_EXIT_TEST_SUITE}" + "${SYSCALL_ENTER_TEST_SUITE}" + "${GENERIC_TRACEPOINTS_TEST_SUITE}" + "${ACTIONS_TEST_SUITE}" ) -set(DRIVERS_TEST_INCLUDE - PRIVATE - "${GTEST_INCLUDE}" - "${LIBS_DIR}/driver/" - "${LIBSCAP_INCLUDE_DIRS}" -) +set(DRIVERS_TEST_INCLUDE PRIVATE "${GTEST_INCLUDE}" "${LIBS_DIR}/driver/" "${LIBSCAP_INCLUDE_DIRS}") -set(DRIVERS_TEST_LINK_LIBRARIES - scap - "${GTEST_LIB}" - "${GTEST_MAIN_LIB}" -) +set(DRIVERS_TEST_LINK_LIBRARIES scap "${GTEST_LIB}" "${GTEST_MAIN_LIB}") -set(DRIVERS_TEST_DEPENDECIES - scap - gtest -) +set(DRIVERS_TEST_DEPENDECIES scap gtest) -## IA32 tests are only available on x86_64 +# IA32 tests are only available on x86_64 if(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64" AND ENABLE_IA32_TESTS) - add_executable(ia32 ./helpers/ia32.c) + add_executable(ia32 ./helpers/ia32.c) target_include_directories(ia32 PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") - set_target_properties(ia32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") - set(DRIVERS_TEST_DEPENDECIES - ${DRIVERS_TEST_DEPENDECIES} - ia32 - ) + set_target_properties(ia32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") + set(DRIVERS_TEST_DEPENDECIES ${DRIVERS_TEST_DEPENDECIES} ia32) endif() add_compile_options(${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS}) diff --git a/test/drivers/event_class/event_class.cpp b/test/drivers/event_class/event_class.cpp index f251d894f7..d1b732d89b 100644 --- a/test/drivers/event_class/event_class.cpp +++ b/test/drivers/event_class/event_class.cpp @@ -1,7 +1,7 @@ #include #include "event_class.h" #include -#include /* or */ +#include /* or */ #include #define MAX_CHARBUF_NUM 16 @@ -11,14 +11,15 @@ /* This array must follow the same order we use in BPF. */ const char* cgroup_prefix_array[] = { - "cpuset=/", - "cpu=/", - "cpuacct=/", - "io=/", - "memory=/", + "cpuset=/", + "cpu=/", + "cpuacct=/", + "io=/", + "memory=/", }; -static_assert(sizeof(cgroup_prefix_array) / sizeof(*cgroup_prefix_array) == CGROUP_NUMBER, "Wrong number of cgroup_prefix_array."); +static_assert(sizeof(cgroup_prefix_array) / sizeof(*cgroup_prefix_array) == CGROUP_NUMBER, + "Wrong number of cgroup_prefix_array."); /* Messages. */ #define VALUE_NOT_CORRECT ">>>>> value of the param is not correct. Param id = " @@ -31,18 +32,15 @@ extern const syscall_evt_pair g_syscall_table[SYSCALL_TABLE_SIZE]; // RETRIEVE EVENT CLASS ///////////////////////////////// -std::unique_ptr get_generic_event_test(ppm_sc_code sc_code) -{ +std::unique_ptr get_generic_event_test(ppm_sc_code sc_code) { return (std::unique_ptr)new event_test(sc_code); } -std::unique_ptr get_syscall_event_test(int syscall_id, int event_direction) -{ +std::unique_ptr get_syscall_event_test(int syscall_id, int event_direction) { return (std::unique_ptr)new event_test(syscall_id, event_direction); } -std::unique_ptr get_syscall_event_test() -{ +std::unique_ptr get_syscall_event_test() { return (std::unique_ptr)new event_test(); } @@ -50,18 +48,19 @@ std::unique_ptr get_syscall_event_test() // SYSCALL RESULT ASSERTIONS ///////////////////////////////// -void _assert_syscall_state(int syscall_state, const char* syscall_name, long syscall_rc, assertion_operators op, long expected_rc) -{ +void _assert_syscall_state(int syscall_state, + const char* syscall_name, + long syscall_rc, + assertion_operators op, + long expected_rc) { bool match = false; - if (errno == ENOSYS) - { + if(errno == ENOSYS) { // it is managed upward by assert_syscall_state macro. return; } - switch(op) - { + switch(op) { case EQUAL: match = syscall_rc == expected_rc; break; @@ -75,14 +74,12 @@ void _assert_syscall_state(int syscall_state, const char* syscall_name, long sys return; } - if(!match) - { - if(syscall_state == SYSCALL_SUCCESS) - { - FAIL() << ">>>>> The syscall '" << syscall_name << "' must be successful. Errno: " << errno << " err_message: " << strerror(errno) << std::endl; - } - else - { + if(!match) { + if(syscall_state == SYSCALL_SUCCESS) { + FAIL() << ">>>>> The syscall '" << syscall_name + << "' must be successful. Errno: " << errno + << " err_message: " << strerror(errno) << std::endl; + } else { FAIL() << ">>>>> The syscall '" << syscall_name << "' must fail." << std::endl; } } @@ -92,8 +89,7 @@ void _assert_syscall_state(int syscall_state, const char* syscall_name, long sys // CONFIGURATION ///////////////////////////////// -event_test::~event_test() -{ +event_test::~event_test() { /* Stop the capture just to be sure and clean ring buffers */ scap_stop_capture(s_scap_handle); clear_ring_buffers(); @@ -102,13 +98,10 @@ event_test::~event_test() /* This constructor must be used with generic tracepoints * that must attach a dedicated BPF program into the kernel. */ -event_test::event_test(ppm_sc_code sc_code): - m_sc_set(PPM_SC_MAX, 0) -{ +event_test::event_test(ppm_sc_code sc_code): m_sc_set(PPM_SC_MAX, 0) { m_current_param = 0; - switch(sc_code) - { + switch(sc_code) { case PPM_SC_SCHED_PROCESS_EXIT: m_event_type = PPME_PROCEXIT_1_E; break; @@ -138,21 +131,15 @@ event_test::event_test(ppm_sc_code sc_code): } /* This constructor must be used with syscalls events */ -event_test::event_test(int syscall_id, int event_direction): - m_sc_set(PPM_SC_MAX, 0) -{ - if(event_direction == ENTER_EVENT) - { +event_test::event_test(int syscall_id, int event_direction): m_sc_set(PPM_SC_MAX, 0) { + if(event_direction == ENTER_EVENT) { m_event_type = g_syscall_table[syscall_id].enter_event_type; - } - else - { + } else { m_event_type = g_syscall_table[syscall_id].exit_event_type; /* We need this patch to set the right event, the syscall table will * always return `PPME_GENERIC_E`. */ - if(m_event_type == PPME_GENERIC_E) - { + if(m_event_type == PPME_GENERIC_E) { m_event_type = PPME_GENERIC_X; } } @@ -164,33 +151,24 @@ event_test::event_test(int syscall_id, int event_direction): /* This constructor must be used with syscalls events when you * want to enable all syscalls. */ -event_test::event_test(): - m_sc_set(PPM_SC_MAX, 0) -{ +event_test::event_test(): m_sc_set(PPM_SC_MAX, 0) { m_current_param = 0; /* Enable all the syscalls and tracepoints */ - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { m_sc_set[ppm_sc] = 1; } } -void event_test::set_event_type(ppm_event_code evt_type) -{ +void event_test::set_event_type(ppm_event_code evt_type) { m_event_type = evt_type; } -void event_test::enable_capture() -{ - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if(m_sc_set[ppm_sc]) - { +void event_test::enable_capture() { + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(m_sc_set[ppm_sc]) { scap_set_ppm_sc(s_scap_handle, (ppm_sc_code)ppm_sc, true); - } - else - { + } else { scap_set_ppm_sc(s_scap_handle, (ppm_sc_code)ppm_sc, false); } } @@ -199,82 +177,64 @@ void event_test::enable_capture() scap_start_capture(s_scap_handle); } -void event_test::enable_sampling_logic(uint32_t sampling_ratio) -{ +void event_test::enable_sampling_logic(uint32_t sampling_ratio) { scap_start_dropping_mode(s_scap_handle, sampling_ratio); } -void event_test::disable_sampling_logic() -{ +void event_test::disable_sampling_logic() { scap_stop_dropping_mode(s_scap_handle); } -void event_test::enable_drop_failed() -{ +void event_test::enable_drop_failed() { scap_set_dropfailed(s_scap_handle, true); } -void event_test::disable_drop_failed() -{ +void event_test::disable_drop_failed() { scap_set_dropfailed(s_scap_handle, false); } -void event_test::set_do_dynamic_snaplen(bool enable) -{ - if(enable) - { +void event_test::set_do_dynamic_snaplen(bool enable) { + if(enable) { scap_enable_dynamic_snaplen(s_scap_handle); - } - else - { + } else { scap_disable_dynamic_snaplen(s_scap_handle); } } -void event_test::set_statsd_port(uint16_t port) -{ +void event_test::set_statsd_port(uint16_t port) { scap_set_statsd_port(s_scap_handle, port); } -void event_test::set_fullcapture_port_range(uint16_t start, uint16_t end) -{ +void event_test::set_fullcapture_port_range(uint16_t start, uint16_t end) { scap_set_fullcapture_port_range(s_scap_handle, start, end); } -void event_test::disable_capture() -{ +void event_test::disable_capture() { scap_stop_capture(s_scap_handle); } -void event_test::clear_ring_buffers() -{ +void event_test::clear_ring_buffers() { uint16_t cpu_id = 0; uint32_t flags = 0; /* First timeout means that all the buffers are empty. If the capture is not * stopped it is possible that we will never receive a `SCAP_TIMEOUT`. */ - while(scap_next(s_scap_handle, (scap_evt**)&m_event_header, &cpu_id, &flags) != SCAP_TIMEOUT) - { + while(scap_next(s_scap_handle, (scap_evt**)&m_event_header, &cpu_id, &flags) != SCAP_TIMEOUT) { } } -ppm_evt_hdr* event_test::get_event_from_ringbuffer(uint16_t* cpu_id) -{ +ppm_evt_hdr* event_test::get_event_from_ringbuffer(uint16_t* cpu_id) { ppm_evt_hdr* hdr = NULL; uint16_t attempts = 0; int32_t res = 0; uint32_t flags = 0; /* Try 2 times just to be sure that all the buffers are empty. */ - while(attempts <= 1) - { + while(attempts <= 1) { res = scap_next(s_scap_handle, (scap_evt**)&hdr, cpu_id, &flags); - if(res == SCAP_SUCCESS && hdr != NULL) - { + if(res == SCAP_SUCCESS && hdr != NULL) { break; - } - else if(res != SCAP_TIMEOUT && res != SCAP_SUCCESS) - { + } else if(res != SCAP_TIMEOUT && res != SCAP_SUCCESS) { return NULL; } attempts++; @@ -282,8 +242,7 @@ ppm_evt_hdr* event_test::get_event_from_ringbuffer(uint16_t* cpu_id) return hdr; } -void event_test::parse_event() -{ +void event_test::parse_event() { uint8_t nparams = m_event_header->nparams; uint16_t* lens16 = (uint16_t*)((char*)m_event_header + sizeof(ppm_evt_hdr)); char* valptr = (char*)lens16 + nparams * sizeof(uint16_t); @@ -295,8 +254,7 @@ void event_test::parse_event() par.valptr = NULL; m_event_params.push_back(par); - for(int j = 0; j < nparams; j++) - { + for(int j = 0; j < nparams; j++) { par.valptr = valptr; par.len = lens16[j]; valptr += lens16[j]; @@ -305,7 +263,8 @@ void event_test::parse_event() } /* This event len is the overall len of the event (header + len_vector + data). - * Note: we compute this length according to the number of params written in the header by the bpf program. + * Note: we compute this length according to the number of params written in the header by the + * bpf program. */ m_event_len = total_len; } @@ -314,72 +273,128 @@ void event_test::parse_event() // NETWORK SCAFFOLDING ///////////////////////////////// -void event_test::client_reuse_address_port(int32_t socketfd) -{ +void event_test::client_reuse_address_port(int32_t socketfd) { /* Allow the socket to reuse the port and address. */ int option_value = 1; - assert_syscall_state(SYSCALL_SUCCESS, "setsockopt (client address)", syscall(__NR_setsockopt, socketfd, SOL_SOCKET, SO_REUSEADDR, &option_value, sizeof(option_value)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "setsockopt (client port)", syscall(__NR_setsockopt, socketfd, SOL_SOCKET, SO_REUSEPORT, &option_value, sizeof(option_value)), NOT_EQUAL, -1); -} - -void event_test::server_reuse_address_port(int32_t socketfd) -{ + assert_syscall_state(SYSCALL_SUCCESS, + "setsockopt (client address)", + syscall(__NR_setsockopt, + socketfd, + SOL_SOCKET, + SO_REUSEADDR, + &option_value, + sizeof(option_value)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setsockopt (client port)", + syscall(__NR_setsockopt, + socketfd, + SOL_SOCKET, + SO_REUSEPORT, + &option_value, + sizeof(option_value)), + NOT_EQUAL, + -1); +} + +void event_test::server_reuse_address_port(int32_t socketfd) { /* Allow the socket to reuse the port and address. */ int option_value = 1; - assert_syscall_state(SYSCALL_SUCCESS, "setsockopt (server address)", syscall(__NR_setsockopt, socketfd, SOL_SOCKET, SO_REUSEADDR, &option_value, sizeof(option_value)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "setsockopt (server port)", syscall(__NR_setsockopt, socketfd, SOL_SOCKET, SO_REUSEPORT, &option_value, sizeof(option_value)), NOT_EQUAL, -1); -} - -void event_test::client_fill_sockaddr_in(sockaddr_in* sockaddr, int32_t ipv4_port, const char* ipv4_string) -{ + assert_syscall_state(SYSCALL_SUCCESS, + "setsockopt (server address)", + syscall(__NR_setsockopt, + socketfd, + SOL_SOCKET, + SO_REUSEADDR, + &option_value, + sizeof(option_value)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setsockopt (server port)", + syscall(__NR_setsockopt, + socketfd, + SOL_SOCKET, + SO_REUSEPORT, + &option_value, + sizeof(option_value)), + NOT_EQUAL, + -1); +} + +void event_test::client_fill_sockaddr_in(sockaddr_in* sockaddr, + int32_t ipv4_port, + const char* ipv4_string) { memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sin_family = AF_INET; sockaddr->sin_port = htons(ipv4_port); - assert_syscall_state(SYSCALL_SUCCESS, "inet_pton (client)", inet_pton(AF_INET, ipv4_string, &(sockaddr->sin_addr)), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "inet_pton (client)", + inet_pton(AF_INET, ipv4_string, &(sockaddr->sin_addr)), + NOT_EQUAL, + -1); } -void event_test::server_fill_sockaddr_in(sockaddr_in* sockaddr, int32_t ipv4_port, const char* ipv4_string) -{ +void event_test::server_fill_sockaddr_in(sockaddr_in* sockaddr, + int32_t ipv4_port, + const char* ipv4_string) { memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sin_family = AF_INET; sockaddr->sin_port = htons(ipv4_port); - assert_syscall_state(SYSCALL_SUCCESS, "inet_pton (server)", inet_pton(AF_INET, ipv4_string, &(sockaddr->sin_addr)), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "inet_pton (server)", + inet_pton(AF_INET, ipv4_string, &(sockaddr->sin_addr)), + NOT_EQUAL, + -1); } -void event_test::client_fill_sockaddr_in6(sockaddr_in6* sockaddr, int32_t ipv6_port, const char* ipv6_string) -{ +void event_test::client_fill_sockaddr_in6(sockaddr_in6* sockaddr, + int32_t ipv6_port, + const char* ipv6_string) { memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sin6_family = AF_INET6; sockaddr->sin6_port = htons(ipv6_port); - assert_syscall_state(SYSCALL_SUCCESS, "inet_pton (client)", inet_pton(AF_INET6, ipv6_string, &(sockaddr->sin6_addr)), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "inet_pton (client)", + inet_pton(AF_INET6, ipv6_string, &(sockaddr->sin6_addr)), + NOT_EQUAL, + -1); } -void event_test::server_fill_sockaddr_in6(sockaddr_in6* sockaddr, int32_t ipv6_port, const char* ipv6_string) -{ +void event_test::server_fill_sockaddr_in6(sockaddr_in6* sockaddr, + int32_t ipv6_port, + const char* ipv6_string) { memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sin6_family = AF_INET6; sockaddr->sin6_port = htons(ipv6_port); - assert_syscall_state(SYSCALL_SUCCESS, "inet_pton (server)", inet_pton(AF_INET6, ipv6_string, &(sockaddr->sin6_addr)), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "inet_pton (server)", + inet_pton(AF_INET6, ipv6_string, &(sockaddr->sin6_addr)), + NOT_EQUAL, + -1); } -void event_test::client_fill_sockaddr_un(sockaddr_un* sockaddr, const char* unix_path) -{ +void event_test::client_fill_sockaddr_un(sockaddr_un* sockaddr, const char* unix_path) { memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sun_family = AF_UNIX; strlcpy(sockaddr->sun_path, unix_path, MAX_SUN_PATH); } -void event_test::server_fill_sockaddr_un(sockaddr_un* sockaddr, const char* unix_path) -{ +void event_test::server_fill_sockaddr_un(sockaddr_un* sockaddr, const char* unix_path) { memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sun_family = AF_UNIX; strlcpy(sockaddr->sun_path, unix_path, MAX_SUN_PATH); } -void event_test::connect_ipv4_client_to_server(int32_t* client_socket, sockaddr_in* client_sockaddr, int32_t* server_socket, sockaddr_in* server_sockaddr, int32_t port_client, int32_t port_server) -{ +void event_test::connect_ipv4_client_to_server(int32_t* client_socket, + sockaddr_in* client_sockaddr, + int32_t* server_socket, + sockaddr_in* server_sockaddr, + int32_t port_client, + int32_t port_server) { /* Create the server socket. */ *server_socket = syscall(__NR_socket, AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); assert_syscall_state(SYSCALL_SUCCESS, "socket (server)", *server_socket, NOT_EQUAL, -1); @@ -389,8 +404,19 @@ void event_test::connect_ipv4_client_to_server(int32_t* client_socket, sockaddr_ server_fill_sockaddr_in(server_sockaddr, port_server); /* Now we bind the server socket with the server address. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (server)", syscall(__NR_bind, *server_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "listen (server)", syscall(__NR_listen, *server_socket, QUEUE_LENGTH), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "bind (server)", + syscall(__NR_bind, + *server_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "listen (server)", + syscall(__NR_listen, *server_socket, QUEUE_LENGTH), + NOT_EQUAL, + -1); /* The server now is ready, we need to create at least one connection from the client. */ @@ -402,12 +428,27 @@ void event_test::connect_ipv4_client_to_server(int32_t* client_socket, sockaddr_ client_fill_sockaddr_in(client_sockaddr, port_client); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, *client_socket, (sockaddr*)client_sockaddr, sizeof(*client_sockaddr)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "connect (client)", syscall(__NR_connect, *client_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); -} - -void event_test::client_to_server(send_data send_d, recv_data receive_d, network_config net_config) -{ + assert_syscall_state(SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, + *client_socket, + (sockaddr*)client_sockaddr, + sizeof(*client_sockaddr)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "connect (client)", + syscall(__NR_connect, + *client_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); +} + +void event_test::client_to_server(send_data send_d, + recv_data receive_d, + network_config net_config) { int32_t client_socket_fd = 0; int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; @@ -421,34 +462,43 @@ void event_test::client_to_server(send_data send_d, recv_data receive_d, network // Setup Connection ////////////////////// - switch(net_config.proto_L3) - { + switch(net_config.proto_L3) { case protocol_L3::IPv4: - if(net_config.proto_L4 == protocol_L4::TCP) - { - this->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, - &server_addr, net_config.client_port, net_config.server_port); - } - else - { - this->connect_ipv4_udp_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, - &server_addr, net_config.client_port, net_config.server_port); + if(net_config.proto_L4 == protocol_L4::TCP) { + this->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr, + net_config.client_port, + net_config.server_port); + } else { + this->connect_ipv4_udp_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr, + net_config.client_port, + net_config.server_port); } - // for the `recv*` syscalls we will use the memory of the server sockaddr but this will be overwritten - // by the kernel so it shouldn't be an issue. + // for the `recv*` syscalls we will use the memory of the server sockaddr but this will be + // overwritten by the kernel so it shouldn't be an issue. addr = (sockaddr*)&server_addr; addrlen = sizeof(server_addr); break; case protocol_L3::IPv6: - if(net_config.proto_L4 == protocol_L4::TCP) - { - this->connect_ipv6_client_to_server(&client_socket_fd, &client_addr6, &server_socket_fd, - &server_addr6, net_config.client_port, net_config.server_port); - } - else - { - this->connect_ipv6_udp_client_to_server(&client_socket_fd, &client_addr6, &server_socket_fd, - &server_addr6, net_config.client_port, net_config.server_port); + if(net_config.proto_L4 == protocol_L4::TCP) { + this->connect_ipv6_client_to_server(&client_socket_fd, + &client_addr6, + &server_socket_fd, + &server_addr6, + net_config.client_port, + net_config.server_port); + } else { + this->connect_ipv6_udp_client_to_server(&client_socket_fd, + &client_addr6, + &server_socket_fd, + &server_addr6, + net_config.client_port, + net_config.server_port); } addr = (sockaddr*)&server_addr6; addrlen = sizeof(server_addr6); @@ -462,37 +512,36 @@ void event_test::client_to_server(send_data send_d, recv_data receive_d, network // Send message ////////////////////// - switch(send_d.syscall_num) - { - case __NR_sendto: - { + switch(send_d.syscall_num) { + case __NR_sendto: { const void* sent_data = NULL; size_t sent_data_len = 0; uint32_t sendto_flags = 0; sent_data = (const void*)SHORT_MESSAGE; sent_data_len = SHORT_MESSAGE_LEN; - if(send_d.greater_snaplen) - { + if(send_d.greater_snaplen) { sent_data = (const void*)LONG_MESSAGE; sent_data_len = LONG_MESSAGE_LEN; } - if(send_d.null_sockaddr) - { + if(send_d.null_sockaddr) { addr = NULL; addrlen = 0; } /* Send a message to the server */ - int64_t sent_bytes = - syscall(__NR_sendto, client_socket_fd, sent_data, sent_data_len, sendto_flags, addr, addrlen); + int64_t sent_bytes = syscall(__NR_sendto, + client_socket_fd, + sent_data, + sent_data_len, + sendto_flags, + addr, + addrlen); assert_syscall_state(SYSCALL_SUCCESS, "sendto (client)", sent_bytes, NOT_EQUAL, -1); - } - break; + } break; - case __NR_sendmsg: - { + case __NR_sendmsg: { struct msghdr send_msg = {}; struct iovec iov[1] = {}; memset(&send_msg, 0, sizeof(send_msg)); @@ -505,46 +554,42 @@ void event_test::client_to_server(send_data send_d, recv_data receive_d, network iov[0].iov_base = (void*)SHORT_MESSAGE; iov[0].iov_len = SHORT_MESSAGE_LEN; - if(send_d.greater_snaplen) - { + if(send_d.greater_snaplen) { iov[0].iov_base = (void*)LONG_MESSAGE; iov[0].iov_len = LONG_MESSAGE_LEN; } - if(send_d.null_sockaddr) - { + if(send_d.null_sockaddr) { send_msg.msg_name = NULL; send_msg.msg_namelen = 0; } - assert_syscall_state(SYSCALL_SUCCESS, "sendmsg (client)", - syscall(__NR_sendmsg, client_socket_fd, &send_msg, sendmsg_flags), NOT_EQUAL, -1); - } - break; + assert_syscall_state(SYSCALL_SUCCESS, + "sendmsg (client)", + syscall(__NR_sendmsg, client_socket_fd, &send_msg, sendmsg_flags), + NOT_EQUAL, + -1); + } break; - case __NR_write: - { + case __NR_write: { const void* sent_data = (const void*)SHORT_MESSAGE; size_t sent_data_len = SHORT_MESSAGE_LEN; - if(send_d.greater_snaplen) - { + if(send_d.greater_snaplen) { sent_data = (const void*)LONG_MESSAGE; sent_data_len = LONG_MESSAGE_LEN; } ssize_t write_bytes = syscall(__NR_write, client_socket_fd, sent_data, sent_data_len); assert_syscall_state(SYSCALL_SUCCESS, "write (client)", write_bytes, NOT_EQUAL, -1); - } - break; + } break; default: FAIL() << "Invalid send syscall" << std::endl; break; } - if(receive_d.skip_recv_phase) - { + if(receive_d.skip_recv_phase) { // Cleanup and return immediately syscall(__NR_shutdown, server_socket_fd, 2); syscall(__NR_shutdown, client_socket_fd, 2); @@ -557,42 +602,40 @@ void event_test::client_to_server(send_data send_d, recv_data receive_d, network // Receive message ////////////////////// int receive_socket_fd = server_socket_fd; - if(net_config.proto_L4 == protocol_L4::TCP) - { + if(net_config.proto_L4 == protocol_L4::TCP) { // In case of TCP we need to accept the connection. receive_socket_fd = syscall(__NR_accept4, server_socket_fd, NULL, NULL, 0); assert_syscall_state(SYSCALL_SUCCESS, "accept4 (server)", receive_socket_fd, NOT_EQUAL, -1); } - switch(receive_d.syscall_num) - { - case __NR_recvfrom: - { + switch(receive_d.syscall_num) { + case __NR_recvfrom: { char received_data[MAX_RECV_BUF_SIZE]; uint32_t recvfrom_flags = 0; char* received_data_ptr = &received_data[0]; socklen_t received_data_len = MAX_RECV_BUF_SIZE; - if(receive_d.null_sockaddr) - { + if(receive_d.null_sockaddr) { addr = NULL; addrlen = 0; } - if(receive_d.null_receiver_buffer) - { + if(receive_d.null_receiver_buffer) { received_data_ptr = NULL; received_data_len = 0; } - int64_t received_bytes = syscall(__NR_recvfrom, receive_socket_fd, received_data_ptr, received_data_len, - recvfrom_flags, addr, &addrlen); + int64_t received_bytes = syscall(__NR_recvfrom, + receive_socket_fd, + received_data_ptr, + received_data_len, + recvfrom_flags, + addr, + &addrlen); assert_syscall_state(SYSCALL_SUCCESS, "recvfrom (server)", received_bytes, NOT_EQUAL, -1); - } - break; + } break; - case __NR_recvmsg: - { + case __NR_recvmsg: { struct msghdr recv_msg = {}; struct iovec iov[1] = {}; memset(&recv_msg, 0, sizeof(recv_msg)); @@ -606,39 +649,34 @@ void event_test::client_to_server(send_data send_d, recv_data receive_d, network recv_msg.msg_iov = iov; recv_msg.msg_iovlen = 1; - if(receive_d.null_sockaddr) - { + if(receive_d.null_sockaddr) { recv_msg.msg_name = NULL; recv_msg.msg_namelen = 0; } - if(receive_d.null_receiver_buffer) - { + if(receive_d.null_receiver_buffer) { recv_msg.msg_iov = NULL; recv_msg.msg_iovlen = 0; } int64_t received_bytes = syscall(__NR_recvmsg, receive_socket_fd, &recv_msg, recvmsg_flags); assert_syscall_state(SYSCALL_SUCCESS, "recvmsg (server)", received_bytes, NOT_EQUAL, -1); - } - break; + } break; - case __NR_read: - { + case __NR_read: { char buf[MAX_RECV_BUF_SIZE]; char* received_data_ptr = &buf[0]; size_t received_data_len = MAX_RECV_BUF_SIZE; - if(receive_d.null_receiver_buffer) - { + if(receive_d.null_receiver_buffer) { received_data_ptr = NULL; received_data_len = 0; } - ssize_t read_bytes = syscall(__NR_read, receive_socket_fd, (void*)received_data_ptr, received_data_len); + ssize_t read_bytes = + syscall(__NR_read, receive_socket_fd, (void*)received_data_ptr, received_data_len); assert_syscall_state(SYSCALL_SUCCESS, "read (server)", read_bytes, NOT_EQUAL, -1); - } - break; + } break; default: FAIL() << "Invalid recv syscall" << std::endl; @@ -648,8 +686,7 @@ void event_test::client_to_server(send_data send_d, recv_data receive_d, network ////////////////////// // Cleaning phase ////////////////////// - if(net_config.proto_L4 == protocol_L4::TCP) - { + if(net_config.proto_L4 == protocol_L4::TCP) { syscall(__NR_shutdown, receive_socket_fd, 2); syscall(__NR_close, receive_socket_fd); } @@ -659,28 +696,60 @@ void event_test::client_to_server(send_data send_d, recv_data receive_d, network syscall(__NR_close, client_socket_fd); } -void event_test::client_to_server_ipv4_tcp(send_data send_d, recv_data receive_d, int32_t client_port, int32_t server_port) -{ - this->client_to_server(send_d, receive_d, network_config{.proto_L3 = protocol_L3::IPv4, .proto_L4 = protocol_L4::TCP, .client_port = client_port, .server_port = server_port}); -} - -void event_test::client_to_server_ipv4_udp(send_data send_d, recv_data receive_d, int32_t client_port, int32_t server_port) -{ - this->client_to_server(send_d, receive_d, network_config{.proto_L3 = protocol_L3::IPv4, .proto_L4 = protocol_L4::UDP, .client_port = client_port, .server_port = server_port}); -} - -void event_test::client_to_server_ipv6_tcp(send_data send_d, recv_data receive_d, int32_t client_port, int32_t server_port) -{ - this->client_to_server(send_d, receive_d, network_config{.proto_L3 = protocol_L3::IPv6, .proto_L4 = protocol_L4::TCP, .client_port = client_port, .server_port = server_port}); -} - -void event_test::client_to_server_ipv6_udp(send_data send_d, recv_data receive_d, int32_t client_port, int32_t server_port) -{ - this->client_to_server(send_d, receive_d, network_config{.proto_L3 = protocol_L3::IPv6, .proto_L4 = protocol_L4::UDP, .client_port = client_port, .server_port = server_port}); -} - -void event_test::connect_ipv4_udp_client_to_server(int32_t* client_socket, sockaddr_in* client_sockaddr, int32_t* server_socket, sockaddr_in* server_sockaddr, int32_t port_client, int32_t port_server) -{ +void event_test::client_to_server_ipv4_tcp(send_data send_d, + recv_data receive_d, + int32_t client_port, + int32_t server_port) { + this->client_to_server(send_d, + receive_d, + network_config{.proto_L3 = protocol_L3::IPv4, + .proto_L4 = protocol_L4::TCP, + .client_port = client_port, + .server_port = server_port}); +} + +void event_test::client_to_server_ipv4_udp(send_data send_d, + recv_data receive_d, + int32_t client_port, + int32_t server_port) { + this->client_to_server(send_d, + receive_d, + network_config{.proto_L3 = protocol_L3::IPv4, + .proto_L4 = protocol_L4::UDP, + .client_port = client_port, + .server_port = server_port}); +} + +void event_test::client_to_server_ipv6_tcp(send_data send_d, + recv_data receive_d, + int32_t client_port, + int32_t server_port) { + this->client_to_server(send_d, + receive_d, + network_config{.proto_L3 = protocol_L3::IPv6, + .proto_L4 = protocol_L4::TCP, + .client_port = client_port, + .server_port = server_port}); +} + +void event_test::client_to_server_ipv6_udp(send_data send_d, + recv_data receive_d, + int32_t client_port, + int32_t server_port) { + this->client_to_server(send_d, + receive_d, + network_config{.proto_L3 = protocol_L3::IPv6, + .proto_L4 = protocol_L4::UDP, + .client_port = client_port, + .server_port = server_port}); +} + +void event_test::connect_ipv4_udp_client_to_server(int32_t* client_socket, + sockaddr_in* client_sockaddr, + int32_t* server_socket, + sockaddr_in* server_sockaddr, + int32_t port_client, + int32_t port_server) { /* Create the server socket. */ *server_socket = syscall(__NR_socket, AF_INET, SOCK_DGRAM, 0); assert_syscall_state(SYSCALL_SUCCESS, "socket (server)", *server_socket, NOT_EQUAL, -1); @@ -690,7 +759,14 @@ void event_test::connect_ipv4_udp_client_to_server(int32_t* client_socket, socka server_fill_sockaddr_in(server_sockaddr, port_server); /* Now we bind the server socket with the server address. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (server)", syscall(__NR_bind, *server_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "bind (server)", + syscall(__NR_bind, + *server_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); /* The server now is ready, we need to create at least one connection from the client. */ @@ -702,11 +778,22 @@ void event_test::connect_ipv4_udp_client_to_server(int32_t* client_socket, socka client_fill_sockaddr_in(client_sockaddr, port_client); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, *client_socket, (sockaddr*)client_sockaddr, sizeof(*client_sockaddr)), NOT_EQUAL, -1); -} - -void event_test::connect_ipv6_client_to_server(int32_t* client_socket, sockaddr_in6* client_sockaddr, int32_t* server_socket, sockaddr_in6* server_sockaddr, int32_t port_client, int32_t port_server) -{ + assert_syscall_state(SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, + *client_socket, + (sockaddr*)client_sockaddr, + sizeof(*client_sockaddr)), + NOT_EQUAL, + -1); +} + +void event_test::connect_ipv6_client_to_server(int32_t* client_socket, + sockaddr_in6* client_sockaddr, + int32_t* server_socket, + sockaddr_in6* server_sockaddr, + int32_t port_client, + int32_t port_server) { /* Create the server socket. */ *server_socket = syscall(__NR_socket, AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, 0); assert_syscall_state(SYSCALL_SUCCESS, "socket (server)", *server_socket, NOT_EQUAL, -1); @@ -716,8 +803,19 @@ void event_test::connect_ipv6_client_to_server(int32_t* client_socket, sockaddr_ server_fill_sockaddr_in6(server_sockaddr, port_server); /* Now we bind the server socket with the server address. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (server)", syscall(__NR_bind, *server_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "listen (server)", syscall(__NR_listen, *server_socket, QUEUE_LENGTH), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "bind (server)", + syscall(__NR_bind, + *server_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "listen (server)", + syscall(__NR_listen, *server_socket, QUEUE_LENGTH), + NOT_EQUAL, + -1); /* The server now is ready, we need to create at least one connection from the client. */ @@ -729,12 +827,30 @@ void event_test::connect_ipv6_client_to_server(int32_t* client_socket, sockaddr_ client_fill_sockaddr_in6(client_sockaddr, port_client); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, *client_socket, (sockaddr*)client_sockaddr, sizeof(*client_sockaddr)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "connect (client)", syscall(__NR_connect, *client_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); -} - -void event_test::connect_ipv6_udp_client_to_server(int32_t* client_socket, sockaddr_in6* client_sockaddr, int32_t* server_socket, sockaddr_in6* server_sockaddr, int32_t port_client, int32_t port_server) -{ + assert_syscall_state(SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, + *client_socket, + (sockaddr*)client_sockaddr, + sizeof(*client_sockaddr)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "connect (client)", + syscall(__NR_connect, + *client_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); +} + +void event_test::connect_ipv6_udp_client_to_server(int32_t* client_socket, + sockaddr_in6* client_sockaddr, + int32_t* server_socket, + sockaddr_in6* server_sockaddr, + int32_t port_client, + int32_t port_server) { /* Create the server socket. */ *server_socket = syscall(__NR_socket, AF_INET6, SOCK_DGRAM, 0); assert_syscall_state(SYSCALL_SUCCESS, "socket (server)", *server_socket, NOT_EQUAL, -1); @@ -744,7 +860,14 @@ void event_test::connect_ipv6_udp_client_to_server(int32_t* client_socket, socka server_fill_sockaddr_in6(server_sockaddr, port_server); /* Now we bind the server socket with the server address. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (server)", syscall(__NR_bind, *server_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "bind (server)", + syscall(__NR_bind, + *server_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); /* The server now is ready, we need to create at least one connection from the client. */ @@ -756,11 +879,20 @@ void event_test::connect_ipv6_udp_client_to_server(int32_t* client_socket, socka client_fill_sockaddr_in6(client_sockaddr, port_client); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, *client_socket, (sockaddr*)client_sockaddr, sizeof(*client_sockaddr)), NOT_EQUAL, -1); -} - -void event_test::connect_unix_client_to_server(int32_t* client_socket, sockaddr_un* client_sockaddr, int32_t* server_socket, sockaddr_un* server_sockaddr) -{ + assert_syscall_state(SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, + *client_socket, + (sockaddr*)client_sockaddr, + sizeof(*client_sockaddr)), + NOT_EQUAL, + -1); +} + +void event_test::connect_unix_client_to_server(int32_t* client_socket, + sockaddr_un* client_sockaddr, + int32_t* server_socket, + sockaddr_un* server_sockaddr) { /* Create the server socket. */ *server_socket = syscall(__NR_socket, AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0); assert_syscall_state(SYSCALL_SUCCESS, "socket (server)", *server_socket, NOT_EQUAL, -1); @@ -769,8 +901,19 @@ void event_test::connect_unix_client_to_server(int32_t* client_socket, sockaddr_ server_fill_sockaddr_un(server_sockaddr); /* Now we bind the server socket with the server address. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (server)", syscall(__NR_bind, *server_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "listen (server)", syscall(__NR_listen, *server_socket, QUEUE_LENGTH), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "bind (server)", + syscall(__NR_bind, + *server_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "listen (server)", + syscall(__NR_listen, *server_socket, QUEUE_LENGTH), + NOT_EQUAL, + -1); /* The server now is ready, we need to create at least one connection from the client. */ @@ -781,81 +924,96 @@ void event_test::connect_unix_client_to_server(int32_t* client_socket, sockaddr_ client_fill_sockaddr_un(client_sockaddr); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, *client_socket, (sockaddr*)client_sockaddr, sizeof(*client_sockaddr)), NOT_EQUAL, -1); - assert_syscall_state(SYSCALL_SUCCESS, "connect (client)", syscall(__NR_connect, *client_socket, (sockaddr*)server_sockaddr, sizeof(*server_sockaddr)), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, + *client_socket, + (sockaddr*)client_sockaddr, + sizeof(*client_sockaddr)), + NOT_EQUAL, + -1); + assert_syscall_state(SYSCALL_SUCCESS, + "connect (client)", + syscall(__NR_connect, + *client_socket, + (sockaddr*)server_sockaddr, + sizeof(*server_sockaddr)), + NOT_EQUAL, + -1); } ///////////////////////////////// // GENERIC EVENT ASSERTIONS ///////////////////////////////// -void event_test::assert_event_presence(pid_t pid_to_search, int event_to_search) -{ +void event_test::assert_event_presence(pid_t pid_to_search, int event_to_search) { assert_event_in_buffers(pid_to_search, event_to_search, true); } -void event_test::assert_event_absence(pid_t pid_to_search, int event_to_search) -{ +void event_test::assert_event_absence(pid_t pid_to_search, int event_to_search) { assert_event_in_buffers(pid_to_search, event_to_search, false); } -void event_test::assert_header() -{ - /* TODO: Here we need a `scap` function that exposes some fields of the table and not all the table!! */ +void event_test::assert_header() { + /* TODO: Here we need a `scap` function that exposes some fields of the table and not all the + * table!! */ int num_params_from_bpf_table = scap_get_event_info_table()[m_event_type].nparams; /* the bpf event gets the correct number of parameters from the param table. */ - ASSERT_EQ(m_event_header->nparams, num_params_from_bpf_table) << "'nparams' in the header is not correct." << std::endl; + ASSERT_EQ(m_event_header->nparams, num_params_from_bpf_table) + << "'nparams' in the header is not correct." << std::endl; /* the len specified in the header matches the real event len. */ - ASSERT_EQ(m_event_header->len, m_event_len) << "'event_len' in the header is not correct." << std::endl; + ASSERT_EQ(m_event_header->len, m_event_len) + << "'event_len' in the header is not correct." << std::endl; } -void event_test::assert_num_params_pushed(int total_params) -{ - /* TODO: Here we need a `scap` function that exposes some fields of the table and not all the table!! */ +void event_test::assert_num_params_pushed(int total_params) { + /* TODO: Here we need a `scap` function that exposes some fields of the table and not all the + * table!! */ int num_params_from_bpf_table = scap_get_event_info_table()[m_event_type].nparams; - ASSERT_EQ(total_params, num_params_from_bpf_table) << "for this event we have not pushed the right number of parameters." << std::endl; + ASSERT_EQ(total_params, num_params_from_bpf_table) + << "for this event we have not pushed the right number of parameters." << std::endl; } ///////////////////////////////// // PARAM ASSERTIONS ///////////////////////////////// -void event_test::assert_empty_param(int param_num) -{ +void event_test::assert_empty_param(int param_num) { assert_param_boundaries(param_num); /* The param length must be 0. */ assert_param_len(0); } -void event_test::assert_only_param_len(int param_num, uint16_t expected_size) -{ +void event_test::assert_only_param_len(int param_num, uint16_t expected_size) { assert_param_boundaries(param_num); assert_param_len(expected_size); } template -void event_test::assert_numeric_param(int param_num, T param, assertion_operators op) -{ +void event_test::assert_numeric_param(int param_num, T param, assertion_operators op) { assert_param_boundaries(param_num); assert_param_len(sizeof(T)); - switch(op) - { + switch(op) { case EQUAL: - ASSERT_EQ(*(T*)(m_event_params[m_current_param].valptr), param) << VALUE_NOT_CORRECT << m_current_param << std::endl; + ASSERT_EQ(*(T*)(m_event_params[m_current_param].valptr), param) + << VALUE_NOT_CORRECT << m_current_param << std::endl; break; case NOT_EQUAL: - ASSERT_NE(*(T*)(m_event_params[m_current_param].valptr), param) << VALUE_NOT_CORRECT << m_current_param << std::endl; + ASSERT_NE(*(T*)(m_event_params[m_current_param].valptr), param) + << VALUE_NOT_CORRECT << m_current_param << std::endl; break; case GREATER_EQUAL: - ASSERT_GE(*(T*)(m_event_params[m_current_param].valptr), param) << VALUE_NOT_CORRECT << m_current_param << std::endl; + ASSERT_GE(*(T*)(m_event_params[m_current_param].valptr), param) + << VALUE_NOT_CORRECT << m_current_param << std::endl; break; case LESS_EQUAL: - ASSERT_LE(*(T*)(m_event_params[m_current_param].valptr), param) << VALUE_NOT_CORRECT << m_current_param << std::endl; + ASSERT_LE(*(T*)(m_event_params[m_current_param].valptr), param) + << VALUE_NOT_CORRECT << m_current_param << std::endl; break; default: @@ -873,36 +1031,34 @@ template void event_test::assert_numeric_param(int, int16_t, assertion_ template void event_test::assert_numeric_param(int, int32_t, assertion_operators); template void event_test::assert_numeric_param(int, int64_t, assertion_operators); -void event_test::assert_charbuf_param(int param_num, const char* param) -{ +void event_test::assert_charbuf_param(int param_num, const char* param) { assert_param_boundaries(param_num); /* 'strlen()' does not include the terminating null byte while bpf adds it. */ assert_param_len(strlen(param) + 1); /* The following assertion compares two C strings, not std::string */ - ASSERT_STREQ(m_event_params[m_current_param].valptr, param) << VALUE_NOT_CORRECT << m_current_param << std::endl; + ASSERT_STREQ(m_event_params[m_current_param].valptr, param) + << VALUE_NOT_CORRECT << m_current_param << std::endl; } -void event_test::assert_charbuf_array_param(int param_num, const char** param) -{ +void event_test::assert_charbuf_array_param(int param_num, const char** param) { assert_param_boundaries(param_num); uint16_t total_len = 0; - for(int index = 0; index < MAX_CHARBUF_NUM; index++) - { - if(param[index] == NULL) - { + for(int index = 0; index < MAX_CHARBUF_NUM; index++) { + if(param[index] == NULL) { break; } /* We can use `STREQ` because every `charbuf` is `\0` terminated. */ - ASSERT_EQ(strlen(m_event_params[m_current_param].valptr + total_len), strlen(param[index])) << LEN_NOT_CORRECT << m_current_param << std::endl; - ASSERT_STREQ(m_event_params[m_current_param].valptr + total_len, param[index]) << VALUE_NOT_CORRECT << m_current_param << std::endl; + ASSERT_EQ(strlen(m_event_params[m_current_param].valptr + total_len), strlen(param[index])) + << LEN_NOT_CORRECT << m_current_param << std::endl; + ASSERT_STREQ(m_event_params[m_current_param].valptr + total_len, param[index]) + << VALUE_NOT_CORRECT << m_current_param << std::endl; total_len += strlen(param[index]) + 1; } assert_param_len(total_len); } -void event_test::assert_cgroup_param(int param_num) -{ +void event_test::assert_cgroup_param(int param_num) { assert_param_boundaries(param_num); uint16_t total_len = 0; /* 'cgroup_string' is composed by 'cgroup_subsytem_name' + 'cgroup_path'. @@ -913,51 +1069,50 @@ void event_test::assert_cgroup_param(int param_num) char cgroup_prefix[MAX_CGROUP_PREFIX_LEN]; int prefix_len = 0; - for(int index = 0; index < CGROUP_NUMBER; index++) - { - strlcpy(cgroup_string, m_event_params[m_current_param].valptr + total_len, MAX_CGROUP_STRING_LEN); + for(int index = 0; index < CGROUP_NUMBER; index++) { + strlcpy(cgroup_string, + m_event_params[m_current_param].valptr + total_len, + MAX_CGROUP_STRING_LEN); total_len += strlen(cgroup_string) + 1; prefix_len = strlen(cgroup_prefix_array[index]); strlcpy(cgroup_prefix, cgroup_string, prefix_len + 1); - ASSERT_STREQ(cgroup_prefix, cgroup_prefix_array[index]) << VALUE_NOT_CORRECT << m_current_param; + ASSERT_STREQ(cgroup_prefix, cgroup_prefix_array[index]) + << VALUE_NOT_CORRECT << m_current_param; } /* With the kmod we send more cgroups than the 5 we send in bpf and modern bpf */ - if(is_kmod_engine()) - { + if(is_kmod_engine()) { assert_param_len_ge(total_len); - } - else - { + } else { assert_param_len(total_len); } } -void event_test::assert_bytebuf_param(int param_num, const char* param, int buf_dimension) -{ +void event_test::assert_bytebuf_param(int param_num, const char* param, int buf_dimension) { assert_param_boundaries(param_num); assert_param_len(buf_dimension); std::string msg = "\nparam: "; - for (int i =0; i>>>> The param id '" << m_current_param << "' is to low." << std::endl; - ASSERT_LE(m_current_param, m_event_header->nparams) << ">>>>> The param id '" << m_current_param << "' is to big." << std::endl; + ASSERT_GE(m_current_param, 1) << ">>>>> The param id '" << m_current_param << "' is to low." + << std::endl; + ASSERT_LE(m_current_param, m_event_header->nparams) + << ">>>>> The param id '" << m_current_param << "' is to big." << std::endl; } -void event_test::assert_param_len(uint16_t expected_size) -{ +void event_test::assert_param_len(uint16_t expected_size) { uint16_t size = m_event_params[m_current_param].len; - ASSERT_EQ(size, expected_size) << ">>>>> length of the param is not correct. Param id = " << m_current_param << std::endl; + ASSERT_EQ(size, expected_size) + << ">>>>> length of the param is not correct. Param id = " << m_current_param + << std::endl; } -void event_test::assert_param_len_ge(uint16_t expected_size) -{ +void event_test::assert_param_len_ge(uint16_t expected_size) { uint16_t size = m_event_params[m_current_param].len; - ASSERT_GE(size, expected_size) << ">>>>> length of the param is not correct. Param id = " << m_current_param << std::endl; + ASSERT_GE(size, expected_size) + << ">>>>> length of the param is not correct. Param id = " << m_current_param + << std::endl; } -void event_test::assert_address_family(uint8_t desired_family, int starting_index) -{ +void event_test::assert_address_family(uint8_t desired_family, int starting_index) { uint8_t family = (uint8_t)(m_event_params[m_current_param].valptr[starting_index]); ASSERT_EQ(family, desired_family) << VALUE_NOT_CORRECT << m_current_param << std::endl; } -void event_test::assert_ipv4_string(const char* desired_ipv4, int starting_index, direction dir) -{ +void event_test::assert_ipv4_string(const char* desired_ipv4, int starting_index, direction dir) { char ipv4_string[ADDRESS_LENGTH]; - if(inet_ntop(AF_INET, (uint8_t*)(m_event_params[m_current_param].valptr + starting_index), ipv4_string, ADDRESS_LENGTH) == NULL) - { + if(inet_ntop(AF_INET, + (uint8_t*)(m_event_params[m_current_param].valptr + starting_index), + ipv4_string, + ADDRESS_LENGTH) == NULL) { FAIL() << "'inet_ntop' must not fail. Param id = " << m_current_param << std::endl; } - if(dir == DEST) - { - ASSERT_STREQ(ipv4_string, desired_ipv4) << VALUE_NOT_CORRECT << m_current_param << " (dest ipv4)" << std::endl; - } - else - { - ASSERT_STREQ(ipv4_string, desired_ipv4) << VALUE_NOT_CORRECT << m_current_param << " (source ipv4)" << std::endl; + if(dir == DEST) { + ASSERT_STREQ(ipv4_string, desired_ipv4) + << VALUE_NOT_CORRECT << m_current_param << " (dest ipv4)" << std::endl; + } else { + ASSERT_STREQ(ipv4_string, desired_ipv4) + << VALUE_NOT_CORRECT << m_current_param << " (source ipv4)" << std::endl; } } -void event_test::assert_port_string(const char* desired_port, int starting_index, direction dir) -{ +void event_test::assert_port_string(const char* desired_port, int starting_index, direction dir) { uint16_t port = *(uint16_t*)(m_event_params[m_current_param].valptr + starting_index); const char* port_string = std::to_string(port).c_str(); - if(dir == DEST) - { - ASSERT_STREQ(port_string, desired_port) << VALUE_NOT_CORRECT << m_current_param << "(dest port)" << std::endl; - } - else - { - ASSERT_STREQ(port_string, desired_port) << VALUE_NOT_CORRECT << m_current_param << "(source port)" << std::endl; + if(dir == DEST) { + ASSERT_STREQ(port_string, desired_port) + << VALUE_NOT_CORRECT << m_current_param << "(dest port)" << std::endl; + } else { + ASSERT_STREQ(port_string, desired_port) + << VALUE_NOT_CORRECT << m_current_param << "(source port)" << std::endl; } } -void event_test::assert_ipv6_string(const char* desired_ipv6, int starting_index, direction dir) -{ +void event_test::assert_ipv6_string(const char* desired_ipv6, int starting_index, direction dir) { char ipv6_string[ADDRESS_LENGTH]; - if(inet_ntop(AF_INET6, (uint32_t*)(m_event_params[m_current_param].valptr + starting_index), ipv6_string, ADDRESS_LENGTH) == NULL) - { + if(inet_ntop(AF_INET6, + (uint32_t*)(m_event_params[m_current_param].valptr + starting_index), + ipv6_string, + ADDRESS_LENGTH) == NULL) { FAIL() << "'inet_ntop' must not fail. Param id = " << m_current_param << std::endl; } - if(dir == DEST) - { - ASSERT_STREQ(ipv6_string, desired_ipv6) << VALUE_NOT_CORRECT << m_current_param << "(dest ipv6)" << std::endl; - } - else - { - ASSERT_STREQ(ipv6_string, desired_ipv6) << VALUE_NOT_CORRECT << m_current_param << "(source ipv6)" << std::endl; + if(dir == DEST) { + ASSERT_STREQ(ipv6_string, desired_ipv6) + << VALUE_NOT_CORRECT << m_current_param << "(dest ipv6)" << std::endl; + } else { + ASSERT_STREQ(ipv6_string, desired_ipv6) + << VALUE_NOT_CORRECT << m_current_param << "(source ipv6)" << std::endl; } } -void event_test::assert_unix_path(const char* desired_path, int starting_index) -{ +void event_test::assert_unix_path(const char* desired_path, int starting_index) { const char* unix_path = m_event_params[m_current_param].valptr + starting_index; ASSERT_STREQ(unix_path, desired_path) << VALUE_NOT_CORRECT << m_current_param; } -void event_test::assert_event_in_buffers(pid_t pid_to_search, int event_to_search, bool presence) -{ +void event_test::assert_event_in_buffers(pid_t pid_to_search, int event_to_search, bool presence) { uint16_t cpu_id = 0; pid_t pid = 0; - if(pid_to_search == CURRENT_PID) - { + if(pid_to_search == CURRENT_PID) { pid = ::getpid(); - } - else - { + } else { pid = pid_to_search; } - if(event_to_search != CURRENT_EVENT_TYPE) - { + if(event_to_search != CURRENT_EVENT_TYPE) { m_event_type = (ppm_event_code)event_to_search; } @@ -1275,42 +1451,33 @@ void event_test::assert_event_in_buffers(pid_t pid_to_search, int event_to_searc * with the type we are searching for. Even if we explicitly create only one event * of this type, the system could create other events of the same type during the test! */ - while(true) - { + while(true) { m_event_header = get_event_from_ringbuffer(&cpu_id); - if(m_event_header == NULL) - { - if(presence) - { + if(m_event_header == NULL) { + if(presence) { FAIL() << "There is no event '" << m_event_type << "' in the buffers." << std::endl; - } - else - { + } else { break; } } - if(m_event_header->tid == (uint64_t)pid && m_event_header->type == m_event_type) - { - if(presence) - { + if(m_event_header->tid == (uint64_t)pid && m_event_header->type == m_event_type) { + if(presence) { break; - } - else - { - FAIL() << "There is an event '" << m_event_type << "' in the buffers, but it shouldn't be there" << std::endl; + } else { + FAIL() << "There is an event '" << m_event_type + << "' in the buffers, but it shouldn't be there" << std::endl; } } } } -bool event_test::is_ext4_fs(int fd) -{ +bool event_test::is_ext4_fs(int fd) { #ifdef __NR_fstatfs struct statfs buf; - if (fstatfs(fd, &buf) != 0) { + if(fstatfs(fd, &buf) != 0) { return false; } - if (buf.f_type == EXT4_SUPER_MAGIC) { + if(buf.f_type == EXT4_SUPER_MAGIC) { return true; } #endif diff --git a/test/drivers/event_class/event_class.h b/test/drivers/event_class/event_class.h index ad6678f6f3..46e2597ea8 100644 --- a/test/drivers/event_class/event_class.h +++ b/test/drivers/event_class/event_class.h @@ -18,21 +18,18 @@ #define CURRENT_EVENT_TYPE -1 #define PPM_MAX_PATH_SIZE 1024 -extern "C" -{ +extern "C" { #include #include } -struct param -{ +struct param { char* valptr; uint16_t len; }; /* This is the struct we send to userspace in `poll` and `ppoll` syscalls */ -struct fd_poll -{ +struct fd_poll { int64_t fd; int16_t flags; }; @@ -50,20 +47,17 @@ struct recv_data { bool skip_recv_phase; }; -enum protocol_L4 -{ +enum protocol_L4 { TCP = 0, UDP = 1, }; -enum protocol_L3 -{ +enum protocol_L3 { IPv4 = 0, IPv6 = 1, }; -struct network_config -{ +struct network_config { protocol_L3 proto_L3; protocol_L4 proto_L4; int32_t client_port; @@ -71,8 +65,7 @@ struct network_config }; /* Assertion operators */ -enum assertion_operators -{ +enum assertion_operators { EQUAL = 0, NOT_EQUAL = 1, GREATER = 2, @@ -81,8 +74,7 @@ enum assertion_operators LESS_EQUAL = 5, }; -enum direction -{ +enum direction { SOURCE = 0, DEST = 1, }; @@ -108,10 +100,10 @@ enum direction * dealing with ENOSYS syscalls, ie: syscalls that are defined but unimplemented, * skipping the test. */ -#define assert_syscall_state(syscall_state, syscall_name, ...) \ - do { \ - _assert_syscall_state(syscall_state, syscall_name, __VA_ARGS__); \ - if(errno == ENOSYS) \ +#define assert_syscall_state(syscall_state, syscall_name, ...) \ + do { \ + _assert_syscall_state(syscall_state, syscall_name, __VA_ARGS__); \ + if(errno == ENOSYS) \ GTEST_SKIP() << "Syscall " << syscall_name << " not implemented" << std::endl; \ } while(0) @@ -135,17 +127,18 @@ enum direction * @param op the operation we want to perform in the assertion. * @param expected_rc the return code we expect. */ -void _assert_syscall_state(int syscall_state, const char* syscall_name, long syscall_rc, enum assertion_operators op = EQUAL, long expected_rc = -1); +void _assert_syscall_state(int syscall_state, + const char* syscall_name, + long syscall_rc, + enum assertion_operators op = EQUAL, + long expected_rc = -1); -class event_test -{ +class event_test { public: static scap_t* s_scap_handle; - static void clear_ppm_sc_mask() - { - for(int i = 0; i < PPM_SC_MAX; i++) - { + static void clear_ppm_sc_mask() { + for(int i = 0; i < PPM_SC_MAX; i++) { scap_set_ppm_sc(s_scap_handle, (ppm_sc_code)i, false); } } @@ -279,18 +272,14 @@ class event_test * * @return true if the current engine is bpf */ - bool is_bpf_engine() - { - return scap_check_current_engine(s_scap_handle, BPF_ENGINE); - } + bool is_bpf_engine() { return scap_check_current_engine(s_scap_handle, BPF_ENGINE); } /** * @brief Check the current engine type * * @return true if the current engine is modern-bpf */ - bool is_modern_bpf_engine() - { + bool is_modern_bpf_engine() { return scap_check_current_engine(s_scap_handle, MODERN_BPF_ENGINE); } @@ -299,10 +288,7 @@ class event_test * * @return true if the current engine is kmod */ - bool is_kmod_engine() - { - return scap_check_current_engine(s_scap_handle, KMOD_ENGINE); - } + bool is_kmod_engine() { return scap_check_current_engine(s_scap_handle, KMOD_ENGINE); } ///////////////////////////////// // NETWORK SCAFFOLDING @@ -324,8 +310,12 @@ class event_test * @param ipv4_port port as an integer value. * @param ipv4_string ipv4 as a string. */ - void client_fill_sockaddr_in(struct sockaddr_in* sockaddr, int32_t ipv4_port = IPV4_PORT_CLIENT, const char* ipv4_string = IPV4_CLIENT); - void server_fill_sockaddr_in(struct sockaddr_in* sockaddr, int32_t ipv4_port = IPV4_PORT_SERVER, const char* ipv4_string = IPV4_SERVER); + void client_fill_sockaddr_in(struct sockaddr_in* sockaddr, + int32_t ipv4_port = IPV4_PORT_CLIENT, + const char* ipv4_string = IPV4_CLIENT); + void server_fill_sockaddr_in(struct sockaddr_in* sockaddr, + int32_t ipv4_port = IPV4_PORT_SERVER, + const char* ipv4_string = IPV4_SERVER); /** * @brief Fill a `sockaddr_in6` struct. It uses default values defined @@ -335,8 +325,12 @@ class event_test * @param ipv6_port port as an integer value. * @param ipv6_string ipv6 as a string. */ - void client_fill_sockaddr_in6(struct sockaddr_in6* sockaddr, int32_t ipv6_port = IPV6_PORT_CLIENT, const char* ipv6_string = IPV6_CLIENT); - void server_fill_sockaddr_in6(struct sockaddr_in6* sockaddr, int32_t ipv6_port = IPV6_PORT_SERVER, const char* ipv6_string = IPV6_SERVER); + void client_fill_sockaddr_in6(struct sockaddr_in6* sockaddr, + int32_t ipv6_port = IPV6_PORT_CLIENT, + const char* ipv6_string = IPV6_CLIENT); + void server_fill_sockaddr_in6(struct sockaddr_in6* sockaddr, + int32_t ipv6_port = IPV6_PORT_SERVER, + const char* ipv6_string = IPV6_SERVER); /** * @brief Fill a `sockaddr_un` struct. It uses default values defined @@ -353,27 +347,62 @@ class event_test * and accept new connections. * * todo!: we should rename it into `connect_ipv4_tcp_client_to_server` - * + * * @param client_socket client socket file descriptor. * @param client_sockaddr client `sockaddr` struct to fill. * @param server_socket server socket file descriptor. * @param server_sockaddr server `sockaddr` struct to fill. */ - void connect_ipv4_client_to_server(int32_t* client_socket, struct sockaddr_in* client_sockaddr, int32_t* server_socket, struct sockaddr_in* server_sockaddr, int32_t client_port = IPV4_PORT_CLIENT, int32_t server_port = IPV4_PORT_SERVER); - void connect_ipv4_udp_client_to_server(int32_t* client_socket, struct sockaddr_in* client_sockaddr, int32_t* server_socket, struct sockaddr_in* server_sockaddr, int32_t client_port = IPV4_PORT_CLIENT, int32_t server_port = IPV4_PORT_SERVER); + void connect_ipv4_client_to_server(int32_t* client_socket, + struct sockaddr_in* client_sockaddr, + int32_t* server_socket, + struct sockaddr_in* server_sockaddr, + int32_t client_port = IPV4_PORT_CLIENT, + int32_t server_port = IPV4_PORT_SERVER); + void connect_ipv4_udp_client_to_server(int32_t* client_socket, + struct sockaddr_in* client_sockaddr, + int32_t* server_socket, + struct sockaddr_in* server_sockaddr, + int32_t client_port = IPV4_PORT_CLIENT, + int32_t server_port = IPV4_PORT_SERVER); // todo!: we should rename it into `connect_ipv6_client_to_server` - void connect_ipv6_client_to_server(int32_t* client_socket, struct sockaddr_in6* client_sockaddr, int32_t* server_socket, struct sockaddr_in6* server_sockaddr, int32_t client_port = IPV6_PORT_CLIENT, int32_t server_port = IPV6_PORT_SERVER); - void connect_ipv6_udp_client_to_server(int32_t* client_socket, sockaddr_in6* client_sockaddr, int32_t* server_socket, sockaddr_in6* server_sockaddr, int32_t client_port = IPV6_PORT_CLIENT, int32_t server_port = IPV6_PORT_SERVER); - - void connect_unix_client_to_server(int32_t* client_socket, struct sockaddr_un* client_sockaddr, int32_t* server_socket, struct sockaddr_un* server_sockaddr); + void connect_ipv6_client_to_server(int32_t* client_socket, + struct sockaddr_in6* client_sockaddr, + int32_t* server_socket, + struct sockaddr_in6* server_sockaddr, + int32_t client_port = IPV6_PORT_CLIENT, + int32_t server_port = IPV6_PORT_SERVER); + void connect_ipv6_udp_client_to_server(int32_t* client_socket, + sockaddr_in6* client_sockaddr, + int32_t* server_socket, + sockaddr_in6* server_sockaddr, + int32_t client_port = IPV6_PORT_CLIENT, + int32_t server_port = IPV6_PORT_SERVER); + + void connect_unix_client_to_server(int32_t* client_socket, + struct sockaddr_un* client_sockaddr, + int32_t* server_socket, + struct sockaddr_un* server_sockaddr); void client_to_server(send_data send_d, recv_data receive_d, network_config net_config); - void client_to_server_ipv4_tcp(send_data send_d, recv_data receive_d = {.skip_recv_phase = true}, int32_t client_port = IP_PORT_CLIENT, int32_t server_port = IP_PORT_SERVER); - void client_to_server_ipv4_udp(send_data send_d, recv_data receive_d = {.skip_recv_phase = true}, int32_t client_port = IP_PORT_CLIENT, int32_t server_port = IP_PORT_SERVER); - void client_to_server_ipv6_tcp(send_data send_d, recv_data receive_d = {.skip_recv_phase = true}, int32_t client_port = IP_PORT_CLIENT, int32_t server_port = IP_PORT_SERVER); - void client_to_server_ipv6_udp(send_data send_d, recv_data receive_d = {.skip_recv_phase = true}, int32_t client_port = IP_PORT_CLIENT, int32_t server_port = IP_PORT_SERVER); - + void client_to_server_ipv4_tcp(send_data send_d, + recv_data receive_d = {.skip_recv_phase = true}, + int32_t client_port = IP_PORT_CLIENT, + int32_t server_port = IP_PORT_SERVER); + void client_to_server_ipv4_udp(send_data send_d, + recv_data receive_d = {.skip_recv_phase = true}, + int32_t client_port = IP_PORT_CLIENT, + int32_t server_port = IP_PORT_SERVER); + void client_to_server_ipv6_tcp(send_data send_d, + recv_data receive_d = {.skip_recv_phase = true}, + int32_t client_port = IP_PORT_CLIENT, + int32_t server_port = IP_PORT_SERVER); + void client_to_server_ipv6_udp(send_data send_d, + recv_data receive_d = {.skip_recv_phase = true}, + int32_t client_port = IP_PORT_CLIENT, + int32_t server_port = IP_PORT_SERVER); + ///////////////////////////////// // GENERIC EVENT ASSERTIONS ///////////////////////////////// @@ -395,7 +424,8 @@ class event_test * @param pid_to_search pid that generated the event we are looking for. * @param event_to_search event type we are looking for. */ - void assert_event_presence(pid_t pid_to_search = CURRENT_PID, int event_to_search = CURRENT_EVENT_TYPE); + void assert_event_presence(pid_t pid_to_search = CURRENT_PID, + int event_to_search = CURRENT_EVENT_TYPE); /** * @brief Assert if our buffers *don't* contain an event: @@ -414,7 +444,8 @@ class event_test * @param pid_to_search pid that generated the event we are looking for. * @param event_to_search event type we are looking for. */ - void assert_event_absence(pid_t pid_to_search = CURRENT_PID, int event_to_search = CURRENT_EVENT_TYPE); + void assert_event_absence(pid_t pid_to_search = CURRENT_PID, + int event_to_search = CURRENT_EVENT_TYPE); /** * @brief Assert some fields of the event header: @@ -560,7 +591,10 @@ class event_test * @param desired_ipv4 expected ipv4. * @param desired_port expected port. */ - void assert_addr_info_inet_param(int param_num, uint8_t desired_family, const char* desired_ipv4, const char* desired_port); + void assert_addr_info_inet_param(int param_num, + uint8_t desired_family, + const char* desired_ipv4, + const char* desired_port); /** * @brief Assert the values extracted from an INET6 `sockaddr`: @@ -573,7 +607,10 @@ class event_test * @param desired_ipv6 expected ipv6. * @param desired_port expected port. */ - void assert_addr_info_inet6_param(int param_num, uint8_t desired_family, const char* desired_ipv6, const char* desired_port); + void assert_addr_info_inet6_param(int param_num, + uint8_t desired_family, + const char* desired_ipv6, + const char* desired_port); /** * @brief Assert the values extracted from a UNIX `sockaddr`: @@ -584,7 +621,9 @@ class event_test * @param desired_family expected socket family. * @param desired_path expected unix path. */ - void assert_addr_info_unix_param(int param_num, uint8_t desired_family, const char* desired_path); + void assert_addr_info_unix_param(int param_num, + uint8_t desired_family, + const char* desired_path); /** * @brief Assert the tuple extracted from a kernel INET socket: @@ -601,8 +640,12 @@ class event_test * @param desired_src_port expected source port. * @param desired_dest_port expected dest port. */ - void assert_tuple_inet_param(int param_num, uint8_t desired_family, const char* desired_src_ipv4, - const char* desired_dest_ipv4, const char* desired_src_port, const char* desired_dest_port); + void assert_tuple_inet_param(int param_num, + uint8_t desired_family, + const char* desired_src_ipv4, + const char* desired_dest_ipv4, + const char* desired_src_port, + const char* desired_dest_port); /** * @brief Assert the tuple extracted from a kernel INET6 socket: @@ -619,8 +662,12 @@ class event_test * @param desired_src_port expected source port. * @param desired_dest_port expected dest port. */ - void assert_tuple_inet6_param(int param_num, uint8_t desired_family, const char* desired_src_ipv6, const char* desired_dest_ipv6, - const char* desired_src_port, const char* desired_dest_port); + void assert_tuple_inet6_param(int param_num, + uint8_t desired_family, + const char* desired_src_ipv6, + const char* desired_dest_ipv6, + const char* desired_src_port, + const char* desired_dest_port); /** * @brief Assert the tuple extracted from a kernel UNIX socket: @@ -686,12 +733,13 @@ class event_test static bool is_ext4_fs(int fd); private: - ppm_event_code m_event_type; /* type of the event we want to assert in this test. */ + ppm_event_code m_event_type; /* type of the event we want to assert in this test. */ std::vector m_event_params; /* all the params of the event (len+value). */ - struct ppm_evt_hdr* m_event_header; /* header of the event. */ - uint32_t m_event_len; /* total event length. */ - uint32_t m_current_param; /* current param that we are analyzing in a single assert method. */ - std::vector m_sc_set; /* Set of scap codes that must be enabled for the specific test. */ + struct ppm_evt_hdr* m_event_header; /* header of the event. */ + uint32_t m_event_len; /* total event length. */ + uint32_t m_current_param; /* current param that we are analyzing in a single assert method. */ + std::vector + m_sc_set; /* Set of scap codes that must be enabled for the specific test. */ /** * @brief Performs two main actions: @@ -738,7 +786,9 @@ class event_test * @param desired_ipv4 expected ipv4 address as a string. * @param starting_index index inside the param where we can find the ipv4 address. */ - void assert_ipv4_string(const char* desired_ipv4, int starting_index, enum direction dir = DEST); + void assert_ipv4_string(const char* desired_ipv4, + int starting_index, + enum direction dir = DEST); /** * @brief Assert the port number as part of a `sockaddr` or a `tuple`. @@ -749,7 +799,9 @@ class event_test * @param desired_port expected port number as a string. * @param starting_index index inside the param where we can find the port number. */ - void assert_port_string(const char* desired_port, int starting_index, enum direction dir = DEST); + void assert_port_string(const char* desired_port, + int starting_index, + enum direction dir = DEST); /** * @brief Assert an ipv6 address as part of a `sockaddr` or a `tuple`. @@ -760,7 +812,9 @@ class event_test * @param desired_ipv6 expected ipv6 address. * @param starting_index index inside the param where we can find the ipv6 address. */ - void assert_ipv6_string(const char* desired_ipv6, int starting_index, enum direction dir = DEST); + void assert_ipv6_string(const char* desired_ipv6, + int starting_index, + enum direction dir = DEST); /** * @brief Assert an unix socket path as part of a `sockaddr` or a `tuple`. diff --git a/test/drivers/event_class/network_utils.h b/test/drivers/event_class/network_utils.h index cc848daded..2c1d503a08 100644 --- a/test/drivers/event_class/network_utils.h +++ b/test/drivers/event_class/network_utils.h @@ -16,7 +16,7 @@ /* Server queue length. */ #define QUEUE_LENGTH 2 -/* IP ports +/* IP ports * todo!: The distinction between ipv4 and ipv6 ports is not necessary. * at the moment we keep them just too avoid to touch many files. */ @@ -76,15 +76,16 @@ /*=============================== SEND/RECEIVE ===========================*/ - #define SHORT_MESSAGE "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS" #define SHORT_MESSAGE_LEN 61 -#define LONG_MESSAGE "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" +#define LONG_MESSAGE \ + "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" \ + "LLLLLLLLLLLLLLLLLLLLLLLLLLLL" #define LONG_MESSAGE_LEN 121 - -// todo!: These macro are used in legacy network tests. They should be removed when we cleanup all nwtwork tests. +// todo!: These macro are used in legacy network tests. They should be removed when we cleanup all +// nwtwork tests. /* we have also the null terminator because in all our messages * (first, second, third) we have left the last byte for the * null terminator. @@ -98,9 +99,12 @@ #define SECOND_MESSAGE_LEN 38 #define THIRD_MESSAGE_LEN 55 #define FULL_MESSAGE_LEN FIRST_MESSAGE_LEN + SECOND_MESSAGE_LEN + THIRD_MESSAGE_LEN -#define FULL_MESSAGE "hey! there is a first message here.\0hey! there is a second message here.\0\0hey! there is a third message here." +#define FULL_MESSAGE \ + "hey! there is a first message here.\0hey! there is a second message here.\0\0hey! there is " \ + "a third message here." #define NO_SNAPLEN_MESSAGE_LEN FIRST_MESSAGE_LEN + SECOND_MESSAGE_LEN -#define NO_SNAPLEN_MESSAGE "hey! there is a first message here.\0hey! there is a second message here.\0" +#define NO_SNAPLEN_MESSAGE \ + "hey! there is a first message here.\0hey! there is a second message here.\0" #define MAX_RECV_BUF_SIZE 100 /*=============================== SEND/RECEIVE ===========================*/ diff --git a/test/drivers/flags/capabilities.cpp b/test/drivers/flags/capabilities.cpp index 8a6c79f949..781d7b306e 100644 --- a/test/drivers/flags/capabilities.cpp +++ b/test/drivers/flags/capabilities.cpp @@ -19,8 +19,7 @@ * Right now we cannot directly include it, let's see if we need other helpers * from this file, in that case, we can think of splitting it. */ -uint64_t capabilities_to_scap(unsigned long caps) -{ +uint64_t capabilities_to_scap(unsigned long caps) { uint64_t res = 0; #ifdef CAP_CHOWN diff --git a/test/drivers/helpers/file_opener.cpp b/test/drivers/helpers/file_opener.cpp index 446e10273c..48a1398c63 100644 --- a/test/drivers/helpers/file_opener.cpp +++ b/test/drivers/helpers/file_opener.cpp @@ -1,61 +1,50 @@ #include "file_opener.h" #include -file_opener::file_opener(const char* filename, int flags, int dirfd) -{ - errno = 0; - m_fd = syscall(__NR_openat, dirfd, filename, flags, 0); - // Using the macro that deals with ENOSYS produces a build issue since GTEST_SKIP returns value in a ctor. - _assert_syscall_state(SYSCALL_SUCCESS, "openat", m_fd, NOT_EQUAL, -1); - m_tmpfile_supported = (errno == EOPNOTSUPP); - if(flags & O_DIRECTORY && strcmp(filename, ".") == 0) - { - m_pathname = m_tmpfile_supported? std::string(".tmpfile") : std::string("."); - } - else - { - m_pathname = std::string(filename); - } - - m_flags = flags; - - if(!m_tmpfile_supported && m_flags & O_TMPFILE) - { - m_flags ^= O_TMPFILE; - m_flags |= O_CREAT; - } +file_opener::file_opener(const char* filename, int flags, int dirfd) { + errno = 0; + m_fd = syscall(__NR_openat, dirfd, filename, flags, 0); + // Using the macro that deals with ENOSYS produces a build issue since GTEST_SKIP returns value + // in a ctor. + _assert_syscall_state(SYSCALL_SUCCESS, "openat", m_fd, NOT_EQUAL, -1); + m_tmpfile_supported = (errno == EOPNOTSUPP); + if(flags & O_DIRECTORY && strcmp(filename, ".") == 0) { + m_pathname = m_tmpfile_supported ? std::string(".tmpfile") : std::string("."); + } else { + m_pathname = std::string(filename); + } + + m_flags = flags; + + if(!m_tmpfile_supported && m_flags & O_TMPFILE) { + m_flags ^= O_TMPFILE; + m_flags |= O_CREAT; + } } -file_opener::~file_opener() -{ - close(); +file_opener::~file_opener() { + close(); } -void file_opener::close() -{ - syscall(__NR_close, m_fd); - if(m_tmpfile_supported) - { - unlink(m_pathname.c_str()); - } +void file_opener::close() { + syscall(__NR_close, m_fd); + if(m_tmpfile_supported) { + unlink(m_pathname.c_str()); + } } - bool file_opener::is_tmpfile_supported() const -{ - return m_tmpfile_supported; +bool file_opener::is_tmpfile_supported() const { + return m_tmpfile_supported; } - int file_opener::get_fd() const -{ - return m_fd; +int file_opener::get_fd() const { + return m_fd; } - int file_opener::get_flags() const -{ - return m_flags; +int file_opener::get_flags() const { + return m_flags; } -const char* file_opener::get_pathname() const -{ - return m_pathname.c_str(); +const char* file_opener::get_pathname() const { + return m_pathname.c_str(); } diff --git a/test/drivers/helpers/file_opener.h b/test/drivers/helpers/file_opener.h index 1501291c8f..8932a7c3ef 100644 --- a/test/drivers/helpers/file_opener.h +++ b/test/drivers/helpers/file_opener.h @@ -8,23 +8,20 @@ #include #include -class file_opener -{ - +class file_opener { public: - file_opener(const char* filename, int flags, int dirfd = AT_FDCWD); - ~file_opener(); + file_opener(const char* filename, int flags, int dirfd = AT_FDCWD); + ~file_opener(); - void close(); - bool is_tmpfile_supported() const; - int get_fd() const; - int get_flags() const; - const char* get_pathname() const; + void close(); + bool is_tmpfile_supported() const; + int get_fd() const; + int get_flags() const; + const char* get_pathname() const; private: - bool m_tmpfile_supported; - std::string m_pathname; - int m_flags; - int m_fd; - + bool m_tmpfile_supported; + std::string m_pathname; + int m_flags; + int m_fd; }; diff --git a/test/drivers/helpers/ia32.c b/test/drivers/helpers/ia32.c index 113d08fae4..04b3fdea78 100644 --- a/test/drivers/helpers/ia32.c +++ b/test/drivers/helpers/ia32.c @@ -21,20 +21,17 @@ #include /* Definition of RESOLVE_* constants */ #endif -#define TRY_SYSCALL(x, ...) \ - if(strncmp(#x, argv[1], sizeof(#x)) == 0) \ - { \ - syscall(x, ##__VA_ARGS__); \ - printf("--> Test_ia32 called '%s'\n", #x); \ - return 0; \ +#define TRY_SYSCALL(x, ...) \ + if(strncmp(#x, argv[1], sizeof(#x)) == 0) { \ + syscall(x, ##__VA_ARGS__); \ + printf("--> Test_ia32 called '%s'\n", #x); \ + return 0; \ } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { // Throw some generic syscalls if we just pass the name of the executable // todo!: we need to convert it to single `if` like the other cases. - if(argc == 1) - { + if(argc == 1) { #ifdef __NR_openat2 struct open_how how; how.flags = O_RDWR; @@ -49,10 +46,21 @@ int main(int argc, char** argv) syscall(__NR_umount, "mock_path"); - long int p = - syscall(__NR_mmap, NULL, 1003520, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + long int p = syscall(__NR_mmap, + NULL, + 1003520, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0); syscall(__NR_munmap, p, 1003520); - p = syscall(__NR_mmap2, NULL, 1003520, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + p = syscall(__NR_mmap2, + NULL, + 1003520, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0); syscall(__NR_munmap, p, 1003520); unsigned long args[3] = {0}; @@ -65,9 +73,7 @@ int main(int argc, char** argv) syscall(__NR_socketcall, SYS_ACCEPT, args); syscall(__NR_socketcall, -1, args); return 0; - } - else if(argc == 2) - { + } else if(argc == 2) { #ifdef __NR_write TRY_SYSCALL(__NR_write, 17, NULL, 1013) #endif @@ -87,48 +93,56 @@ int main(int argc, char** argv) #ifdef __NR_time TRY_SYSCALL(__NR_time, NULL) #endif - } - else if(argc == 3) - { + } else if(argc == 3) { /* This if case is used to manage socketcall, we look at argv[2] in this case */ // Create sockets int32_t server_socket_fd = syscall(__NR_socket, AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); - if(server_socket_fd == -1) - { + if(server_socket_fd == -1) { fprintf(stderr, "socket server failed\n"); return -1; } int32_t client_socket_fd = syscall(__NR_socket, AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); - if(client_socket_fd == -1) - { + if(client_socket_fd == -1) { fprintf(stderr, "socket client failed\n"); return -1; } // Reuse address and port int option_value = 1; - if(syscall(__NR_setsockopt, server_socket_fd, SOL_SOCKET, SO_REUSEADDR, &option_value, - sizeof(option_value)) == -1) - { + if(syscall(__NR_setsockopt, + server_socket_fd, + SOL_SOCKET, + SO_REUSEADDR, + &option_value, + sizeof(option_value)) == -1) { fprintf(stderr, "setsockopt (server addr) failed\n"); return -1; } - if(syscall(__NR_setsockopt, server_socket_fd, SOL_SOCKET, SO_REUSEPORT, &option_value, - sizeof(option_value)) == -1) - { + if(syscall(__NR_setsockopt, + server_socket_fd, + SOL_SOCKET, + SO_REUSEPORT, + &option_value, + sizeof(option_value)) == -1) { fprintf(stderr, "setsockopt (server port) failed\n"); return -1; } - if(syscall(__NR_setsockopt, client_socket_fd, SOL_SOCKET, SO_REUSEADDR, &option_value, - sizeof(option_value)) == -1) - { + if(syscall(__NR_setsockopt, + client_socket_fd, + SOL_SOCKET, + SO_REUSEADDR, + &option_value, + sizeof(option_value)) == -1) { fprintf(stderr, "setsockopt (client addr) failed\n"); return -1; } - if(syscall(__NR_setsockopt, client_socket_fd, SOL_SOCKET, SO_REUSEPORT, &option_value, - sizeof(option_value)) == -1) - { + if(syscall(__NR_setsockopt, + client_socket_fd, + SOL_SOCKET, + SO_REUSEPORT, + &option_value, + sizeof(option_value)) == -1) { fprintf(stderr, "setsockopt (client port) failed\n"); return -1; } @@ -139,54 +153,56 @@ int main(int argc, char** argv) server_addr.sin_family = AF_INET; server_addr.sin_port = htons(IPV4_PORT_SERVER); - if(inet_pton(AF_INET, IPV4_SERVER, &(server_addr.sin_addr)) == -1) - { + if(inet_pton(AF_INET, IPV4_SERVER, &(server_addr.sin_addr)) == -1) { fprintf(stderr, "inet_pton server failed\n"); return -1; } client_addr.sin_family = AF_INET; client_addr.sin_port = htons(IPV4_PORT_CLIENT); - if(inet_pton(AF_INET, IPV4_CLIENT, &(client_addr.sin_addr)) == -1) - { + if(inet_pton(AF_INET, IPV4_CLIENT, &(client_addr.sin_addr)) == -1) { fprintf(stderr, "inet_pton client failed\n"); return -1; } // Now we bind the server socket with the server address. - if(syscall(__NR_bind, server_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_bind, + server_socket_fd, + (struct sockaddr*)&server_addr, + sizeof(server_addr)) == -1) { fprintf(stderr, "bind (server) failed\n"); return -1; } - if(syscall(__NR_listen, server_socket_fd, QUEUE_LENGTH) == -1) - { + if(syscall(__NR_listen, server_socket_fd, QUEUE_LENGTH) == -1) { fprintf(stderr, "listen failed\n"); return -1; } // We need to bind the client socket with an address otherwise we cannot assert against it. - if(syscall(__NR_bind, client_socket_fd, (struct sockaddr*)&client_addr, sizeof(client_addr)) == -1) - { + if(syscall(__NR_bind, + client_socket_fd, + (struct sockaddr*)&client_addr, + sizeof(client_addr)) == -1) { fprintf(stderr, "bind (client) failed\n"); return -1; } // The connection will be inprogress so we don't check the errno. - syscall(__NR_connect, client_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)); + syscall(__NR_connect, + client_socket_fd, + (struct sockaddr*)&server_addr, + sizeof(server_addr)); #ifdef __NR_socketcall - if(strncmp("__NR_accept", argv[2], sizeof("__NR_accept")) == 0) - { + if(strncmp("__NR_accept", argv[2], sizeof("__NR_accept")) == 0) { uint32_t args[3] = {0}; args[0] = server_socket_fd; args[1] = 0; args[2] = 0; int connected_socket_fd = syscall(__NR_socketcall, SYS_ACCEPT, (uint32_t*)args); - if(connected_socket_fd == -1) - { + if(connected_socket_fd == -1) { fprintf(stderr, "accept (server) failed\n"); return -1; } @@ -194,8 +210,7 @@ int main(int argc, char** argv) syscall(__NR_close, connected_socket_fd); } - if(strncmp("__NR_sendto", argv[2], sizeof("__NR_sendto")) == 0) - { + if(strncmp("__NR_sendto", argv[2], sizeof("__NR_sendto")) == 0) { char sent_data[NO_SNAPLEN_MESSAGE_LEN] = NO_SNAPLEN_MESSAGE; uint32_t sendto_flags = 0; @@ -207,8 +222,7 @@ int main(int argc, char** argv) args[4] = (unsigned long)&server_addr; args[5] = sizeof(server_addr); int64_t sent_bytes = syscall(__NR_socketcall, SYS_SENDTO, args); - if(sent_bytes == -1) - { + if(sent_bytes == -1) { fprintf(stderr, "sendto failed\n"); return -1; } @@ -219,9 +233,7 @@ int main(int argc, char** argv) syscall(__NR_close, server_socket_fd); syscall(__NR_close, client_socket_fd); return 0; - } - else - { + } else { fprintf(stderr, "wrong number of args\n"); return -1; } diff --git a/test/drivers/helpers/proc_parsing.cpp b/test/drivers/helpers/proc_parsing.cpp index 36ec9b1446..3272cf8596 100644 --- a/test/drivers/helpers/proc_parsing.cpp +++ b/test/drivers/helpers/proc_parsing.cpp @@ -4,8 +4,7 @@ #include #include -bool get_proc_info(pid_t pid, proc_info* info) -{ +bool get_proc_info(pid_t pid, proc_info* info) { char path_to_read[MAX_PATH]; /* @@ -13,18 +12,19 @@ bool get_proc_info(pid_t pid, proc_info* info) */ snprintf(path_to_read, sizeof(path_to_read), "/proc/%d/stat", pid); FILE* stat = fopen(path_to_read, "r"); - if(stat == NULL) - { - std::cerr << "'fopen /proc/[pid]/stat' must not fail: (" << errno << "), " << strerror(errno) << std::endl; + if(stat == NULL) { + std::cerr << "'fopen /proc/[pid]/stat' must not fail: (" << errno << "), " + << strerror(errno) << std::endl; return false; } /* we could get the filename of the executable (`comm`) from proc, but it is returned - * in parentheses, so for example "(bpf_test)", so we prefer to use our macro `TEST_EXECUTABLE_NAME` + * in parentheses, so for example "(bpf_test)", so we prefer to use our macro + * `TEST_EXECUTABLE_NAME` */ - if(fscanf(stat, "%*d %*s %*c %d %d %*d %d", &info->ppid, &info->pgid, &info->tty) < 0) - { - std::cerr << "'fscanf /proc/[pid]/stat' must not fail: (" << errno << "), " << strerror(errno) << std::endl; + if(fscanf(stat, "%*d %*s %*c %d %d %*d %d", &info->ppid, &info->pgid, &info->tty) < 0) { + std::cerr << "'fscanf /proc/[pid]/stat' must not fail: (" << errno << "), " + << strerror(errno) << std::endl; fclose(stat); return false; } @@ -35,29 +35,26 @@ bool get_proc_info(pid_t pid, proc_info* info) */ snprintf(path_to_read, sizeof(path_to_read), "/proc/%d/cmdline", pid); FILE* cmdline = fopen(path_to_read, "r"); - if(cmdline == NULL) - { - std::cerr << "'fopen /proc/[pid]/cmdline' must not fail: (" << errno << "), " << strerror(errno) << std::endl; + if(cmdline == NULL) { + std::cerr << "'fopen /proc/[pid]/cmdline' must not fail: (" << errno << "), " + << strerror(errno) << std::endl; return false; } int c; int i = 0; int j = 0; - while((c = fgetc(cmdline)) != EOF && i < MAX_NUM_ARGS) - { + while((c = fgetc(cmdline)) != EOF && i < MAX_NUM_ARGS) { info->raw_args[i][j] = (char)c; j++; - if(c == '\0') - { + if(c == '\0') { info->args[i] = info->raw_args[i]; i++; j = 0; } } - if(i < MAX_NUM_ARGS) - { + if(i < MAX_NUM_ARGS) { info->args[i] = NULL; } fclose(cmdline); @@ -67,9 +64,9 @@ bool get_proc_info(pid_t pid, proc_info* info) */ snprintf(path_to_read, sizeof(path_to_read), "/proc/%d/status", pid); FILE* status = fopen(path_to_read, "r"); - if(status == NULL) - { - std::cerr << "'fopen /proc/[pid]/status' must not fail: (" << errno << "), " << strerror(errno) << std::endl; + if(status == NULL) { + std::cerr << "'fopen /proc/[pid]/status' must not fail: (" << errno << "), " + << strerror(errno) << std::endl; return false; } @@ -79,35 +76,29 @@ bool get_proc_info(pid_t pid, proc_info* info) uint32_t temp = 0; int found = 0; - while(fgets(line, MAX_PATH, status) != NULL) - { + while(fgets(line, MAX_PATH, status) != NULL) { sscanf(line, "%s %d %*s\n", prefix, &temp); - if(strncmp(prefix, "Uid:", 5) == 0) - { + if(strncmp(prefix, "Uid:", 5) == 0) { info->uid = temp; found++; } - if(strncmp(prefix, "Gid:", 5) == 0) - { + if(strncmp(prefix, "Gid:", 5) == 0) { info->gid = temp; found++; } - if(strncmp(prefix, "NStgid:", 8) == 0) - { + if(strncmp(prefix, "NStgid:", 8) == 0) { info->vpid = temp; found++; } - if(strncmp(prefix, "NSpid:", 7) == 0) - { + if(strncmp(prefix, "NSpid:", 7) == 0) { info->vtid = temp; found++; } - if(found == 4) - { + if(found == 4) { break; } } @@ -117,9 +108,9 @@ bool get_proc_info(pid_t pid, proc_info* info) * Get rlimit */ - if(getrlimit(RLIMIT_NOFILE, &info->file_rlimit) == -1) - { - std::cerr << "'getrlimit' must not fail: (" << errno << "), " << strerror(errno) << std::endl; + if(getrlimit(RLIMIT_NOFILE, &info->file_rlimit) == -1) { + std::cerr << "'getrlimit' must not fail: (" << errno << "), " << strerror(errno) + << std::endl; return false; } @@ -128,14 +119,14 @@ bool get_proc_info(pid_t pid, proc_info* info) */ snprintf(path_to_read, sizeof(path_to_read), "/proc/%d/loginuid", pid); FILE* login = fopen(path_to_read, "r"); - if(login == NULL) - { - std::cerr << "'fopen /proc/[pid]/loginuid' must not fail: (" << errno << "), " << strerror(errno) << std::endl; + if(login == NULL) { + std::cerr << "'fopen /proc/[pid]/loginuid' must not fail: (" << errno << "), " + << strerror(errno) << std::endl; return false; } - if(fscanf(login, "%d", &info->loginuid) != 1) - { - std::cerr << "'fscanf /proc/[pid]/loginuid' must not fail: (" << errno << "), " << strerror(errno) << std::endl; + if(fscanf(login, "%d", &info->loginuid) != 1) { + std::cerr << "'fscanf /proc/[pid]/loginuid' must not fail: (" << errno << "), " + << strerror(errno) << std::endl; fclose(login); return false; } @@ -144,13 +135,13 @@ bool get_proc_info(pid_t pid, proc_info* info) snprintf(path_to_read, sizeof(path_to_read), "/proc/%u/exe", ::getpid()); /* - * Gather the executable full name + * Gather the executable full name */ int res = readlink(path_to_read, info->exepath, sizeof(info->exepath) - 1); - if(res <= 0) - { - std::cerr << "'unable to readlink /proc/pid/exe: (" << errno << "), " << strerror(errno) << std::endl; + if(res <= 0) { + std::cerr << "'unable to readlink /proc/pid/exe: (" << errno << "), " << strerror(errno) + << std::endl; return false; } /* Null termination */ diff --git a/test/drivers/helpers/proc_parsing.h b/test/drivers/helpers/proc_parsing.h index 8194b964f6..6c398cf375 100644 --- a/test/drivers/helpers/proc_parsing.h +++ b/test/drivers/helpers/proc_parsing.h @@ -11,8 +11,7 @@ /* Params that we need to catch from proc. There are cases * in which we don't need them all. */ -struct proc_info -{ +struct proc_info { uint32_t tty; pid_t ppid; /* The PID of the parent of this process. */ pid_t pgid; /* The process group ID of the process. */ @@ -24,7 +23,7 @@ struct proc_info uint32_t vtid; struct rlimit file_rlimit; uint32_t loginuid; - char exepath [MAX_PATH]; + char exepath[MAX_PATH]; }; bool get_proc_info(pid_t pid, proc_info* info); diff --git a/test/drivers/start_tests.cpp b/test/drivers/start_tests.cpp index 9f4ea2c492..cce7219bba 100644 --- a/test/drivers/start_tests.cpp +++ b/test/drivers/start_tests.cpp @@ -22,12 +22,9 @@ scap_t* event_test::s_scap_handle = NULL; static falcosecurity_log_severity severity_level = FALCOSECURITY_LOG_SEV_WARNING; -int remove_kmod() -{ - if(syscall(__NR_delete_module, KMOD_NAME, O_NONBLOCK)) - { - switch(errno) - { +int remove_kmod() { + if(syscall(__NR_delete_module, KMOD_NAME, O_NONBLOCK)) { + switch(errno) { case ENOENT: return EXIT_SUCCESS; @@ -36,11 +33,9 @@ int remove_kmod() * case we wait until the module is detached. */ case EWOULDBLOCK: - for(int i = 0; i < 4; i++) - { + for(int i = 0; i < 4; i++) { int ret = syscall(__NR_delete_module, KMOD_NAME, O_NONBLOCK); - if(ret == 0 || errno == ENOENT) - { + if(ret == 0 || errno == ENOENT) { return EXIT_SUCCESS; } sleep(1); @@ -50,62 +45,56 @@ int remove_kmod() case EBUSY: case EFAULT: case EPERM: - std::cerr << "Unable to remove kernel module. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + std::cerr << "Unable to remove kernel module. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; default: - std::cerr << "Unexpected error code. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + std::cerr << "Unexpected error code. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } -int insert_kmod(const std::string& kmod_path) -{ +int insert_kmod(const std::string& kmod_path) { /* Here we want to insert the module if we fail we need to abort the program. */ int fd = open(kmod_path.c_str(), O_RDONLY); - if(fd < 0) - { - std::cout << "Unable to open the kmod file. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + if(fd < 0) { + std::cout << "Unable to open the kmod file. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; } - if(syscall(__NR_finit_module, fd, "", 0)) - { - std::cerr << "Unable to inject the kmod. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + if(syscall(__NR_finit_module, fd, "", 0)) { + std::cerr << "Unable to inject the kmod. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } -void abort_if_already_configured(const scap_vtable* vtable) -{ - if(vtable != nullptr) - { - std::cerr << "* '" << vtable->name << "' engine is already configured. Please specify just one engine!" << std::endl; +void abort_if_already_configured(const scap_vtable* vtable) { + if(vtable != nullptr) { + std::cerr << "* '" << vtable->name + << "' engine is already configured. Please specify just one engine!" << std::endl; exit(EXIT_FAILURE); } } -void test_open_log_fn(const char* component, const char* msg, falcosecurity_log_severity sev) -{ - if(sev <= severity_level) - { - if(component!= NULL) - { +void test_open_log_fn(const char* component, const char* msg, falcosecurity_log_severity sev) { + if(sev <= severity_level) { + if(component != NULL) { printf("%s: %s", component, msg); - } - else - { + } else { // libbpf logs have no components printf("%s", msg); } } } -void print_message(std::string msg) -{ +void print_message(std::string msg) { std::cout << std::endl; std::cout << "-----------------------------------------------------" << std::endl; std::cout << "- " << msg << std::endl; @@ -113,8 +102,7 @@ void print_message(std::string msg) std::cout << std::endl; } -void print_menu_and_exit() -{ +void print_menu_and_exit() { std::string usage = R"(Usage: drivers_test [options] Overview: The goal of this binary is to run tests against one of our drivers. @@ -131,16 +119,14 @@ Overview: The goal of this binary is to run tests against one of our drivers. exit(EXIT_SUCCESS); } -int open_engine(int argc, char** argv) -{ - static struct option long_options[] = { - {BPF_OPTION, optional_argument, 0, 'b'}, - {MODERN_BPF_OPTION, no_argument, 0, 'm'}, - {KMOD_OPTION, optional_argument, 0, 'k'}, - {BUFFER_OPTION, required_argument, 0, 'd'}, - {HELP_OPTION, no_argument, 0, 'h'}, - {VERBOSE_OPTION, required_argument, 0, 'v'}, - {0, 0, 0, 0}}; +int open_engine(int argc, char** argv) { + static struct option long_options[] = {{BPF_OPTION, optional_argument, 0, 'b'}, + {MODERN_BPF_OPTION, no_argument, 0, 'm'}, + {KMOD_OPTION, optional_argument, 0, 'k'}, + {BUFFER_OPTION, required_argument, 0, 'd'}, + {HELP_OPTION, no_argument, 0, 'h'}, + {VERBOSE_OPTION, required_argument, 0, 'v'}, + {0, 0, 0, 0}}; // They should live until we call 'scap_open' scap_modern_bpf_engine_params modern_bpf_params = {}; @@ -156,15 +142,13 @@ int open_engine(int argc, char** argv) /* Remove kmod if injected, we remove it always even if we use another engine * in this way we are sure the unique driver in the system is the one we will use. */ - if(remove_kmod()) - { + if(remove_kmod()) { return EXIT_FAILURE; } /* Get current cwd as a base directory for the driver path */ char driver_path[FILENAME_MAX]; - if(!getcwd(driver_path, FILENAME_MAX)) - { + if(!getcwd(driver_path, FILENAME_MAX)) { std::cerr << "Unable to get current dir" << std::endl; return EXIT_FAILURE; } @@ -172,12 +156,8 @@ int open_engine(int argc, char** argv) /* Parse CLI options */ int op = 0; int long_index = 0; - while((op = getopt_long(argc, argv, - "b::mk::d:hv:", - long_options, &long_index)) != -1) - { - switch(op) - { + while((op = getopt_long(argc, argv, "b::mk::d:hv:", long_options, &long_index)) != -1) { + switch(op) { case 'b': #ifdef HAS_ENGINE_BPF { @@ -188,28 +168,24 @@ int open_engine(int argc, char** argv) * `-b ./path/to/probe`. Without this `if` case we can accept arguments * only in this format `-b./path/to/probe` */ - if(optarg == NULL && optind < argc && argv[optind][0] != '-') - { + if(optarg == NULL && optind < argc && argv[optind][0] != '-') { bpf_params.bpf_probe = argv[optind++]; - } - else if(optarg == NULL) - { + } else if(optarg == NULL) { strlcat(driver_path, BPF_PROBE_DEFAULT_PATH, FILENAME_MAX); bpf_params.bpf_probe = driver_path; - } - else - { + } else { bpf_params.bpf_probe = optarg; } oargs.engine_params = &bpf_params; - std::cout << "* Configure BPF probe tests! Probe path: " << bpf_params.bpf_probe << std::endl; + std::cout << "* Configure BPF probe tests! Probe path: " << bpf_params.bpf_probe + << std::endl; } #else std::cerr << "BPF engine is not supported in this build" << std::endl; return EXIT_FAILURE; #endif - break; + break; case 'm': #ifdef HAS_ENGINE_MODERN_BPF @@ -224,7 +200,7 @@ int open_engine(int argc, char** argv) std::cerr << "Modern BPF engine is not supported in this build" << std::endl; return EXIT_FAILURE; #endif - break; + break; case 'k': #ifdef HAS_ENGINE_KMOD @@ -232,36 +208,31 @@ int open_engine(int argc, char** argv) abort_if_already_configured(vtable); vtable = &scap_kmod_engine; kmod_params.buffer_bytes_dim = buffer_bytes_dim; - if(optarg == NULL && optind < argc && argv[optind][0] != '-') - { + if(optarg == NULL && optind < argc && argv[optind][0] != '-') { kmod_path = argv[optind++]; - } - else if(optarg == NULL) - { + } else if(optarg == NULL) { strlcat(driver_path, KMOD_DEFAULT_PATH, FILENAME_MAX); kmod_path = driver_path; - } - else - { + } else { kmod_path = optarg; } oargs.engine_params = &kmod_params; - if(insert_kmod(kmod_path)) - { + if(insert_kmod(kmod_path)) { return EXIT_FAILURE; } - std::cout << "* Configure kernel module tests! Kernel module path: " << kmod_path << std::endl; + std::cout << "* Configure kernel module tests! Kernel module path: " << kmod_path + << std::endl; } #else std::cerr << "Kernel module engine is not supported in this build" << std::endl; return EXIT_FAILURE; #endif - break; + break; case 'd': - if(vtable != nullptr) - { - std::cerr << "The buffer dim '" << BUFFER_OPTION << "' must be chosen before opening the engine" << std::endl; + if(vtable != nullptr) { + std::cerr << "The buffer dim '" << BUFFER_OPTION + << "' must be chosen before opening the engine" << std::endl; return EXIT_FAILURE; } buffer_bytes_dim = strtoul(optarg, NULL, 10); @@ -271,17 +242,16 @@ int open_engine(int argc, char** argv) print_menu_and_exit(); break; - case 'v': - { - unsigned long level = strtoul(optarg, NULL, 10); - if(level < FALCOSECURITY_LOG_SEV_FATAL || level > FALCOSECURITY_LOG_SEV_TRACE) - { - std::cerr << "Invalid logging level. Valid range is '" << std::to_string(FALCOSECURITY_LOG_SEV_FATAL) <<"' <= lev <= '" << std::to_string(FALCOSECURITY_LOG_SEV_TRACE) << "'" << std::endl; - return EXIT_FAILURE; - } - severity_level = (falcosecurity_log_severity)level; + case 'v': { + unsigned long level = strtoul(optarg, NULL, 10); + if(level < FALCOSECURITY_LOG_SEV_FATAL || level > FALCOSECURITY_LOG_SEV_TRACE) { + std::cerr << "Invalid logging level. Valid range is '" + << std::to_string(FALCOSECURITY_LOG_SEV_FATAL) << "' <= lev <= '" + << std::to_string(FALCOSECURITY_LOG_SEV_TRACE) << "'" << std::endl; + return EXIT_FAILURE; } - break; + severity_level = (falcosecurity_log_severity)level; + } break; default: return EXIT_FAILURE; @@ -289,24 +259,21 @@ int open_engine(int argc, char** argv) } std::cout << "* Using buffer dim: " << buffer_bytes_dim << std::endl; - if(vtable == nullptr) - { + if(vtable == nullptr) { std::cerr << "Unsupported engine! Choose between: m, b, k" << std::endl; return EXIT_FAILURE; } char error_buffer[FILENAME_MAX] = {0}; event_test::s_scap_handle = scap_open(&oargs, vtable, error_buffer, &ret); - if(!event_test::s_scap_handle) - { + if(!event_test::s_scap_handle) { std::cerr << "Unable to open the engine: " << error_buffer << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { int res = EXIT_SUCCESS; print_message("Setup phase"); @@ -314,8 +281,7 @@ int main(int argc, char** argv) ::testing::InitGoogleTest(&argc, argv); /* Open the requested engine */ - if(open_engine(argc, argv)) - { + if(open_engine(argc, argv)) { return EXIT_FAILURE; } diff --git a/test/drivers/test_suites/actions_suite/drop_failed.cpp b/test/drivers/test_suites/actions_suite/drop_failed.cpp index 94395806cc..87869a62cd 100644 --- a/test/drivers/test_suites/actions_suite/drop_failed.cpp +++ b/test/drivers/test_suites/actions_suite/drop_failed.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_unshare) -TEST(Actions, drop_failed_enter) -{ +TEST(Actions, drop_failed_enter) { auto evt_test = get_syscall_event_test(__NR_unshare, ENTER_EVENT); /* Enable drop failed feature */ @@ -21,8 +20,7 @@ TEST(Actions, drop_failed_enter) evt_test->disable_capture(); } -TEST(Actions, drop_failed_exit) -{ +TEST(Actions, drop_failed_exit) { auto evt_test = get_syscall_event_test(__NR_unshare, EXIT_EVENT); /* Enable drop failed feature */ @@ -41,8 +39,7 @@ TEST(Actions, drop_failed_exit) evt_test->disable_capture(); } -TEST(Actions, drop_failed_successful) -{ +TEST(Actions, drop_failed_successful) { auto evt_test = get_syscall_event_test(__NR_unshare, EXIT_EVENT); /* Enable drop failed feature */ @@ -59,4 +56,4 @@ TEST(Actions, drop_failed_successful) evt_test->disable_capture(); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/actions_suite/dynamic_snaplen.cpp b/test/drivers/test_suites/actions_suite/dynamic_snaplen.cpp index eb44406256..7cac3d73e3 100644 --- a/test/drivers/test_suites/actions_suite/dynamic_snaplen.cpp +++ b/test/drivers/test_suites/actions_suite/dynamic_snaplen.cpp @@ -3,8 +3,7 @@ #if defined(__NR_write) && defined(__NR_clone3) && defined(__NR_wait4) #include -TEST(Actions, dynamic_snaplen_negative_fd) -{ +TEST(Actions, dynamic_snaplen_negative_fd) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -25,18 +24,14 @@ TEST(Actions, dynamic_snaplen_negative_fd) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Ensure that buf is not paged out by the kernel on some archs, like riscv */ char buf_child[data_len] = "HTTP/\0"; /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_write, fd, (void *)buf_child, data_len) == -1) - { + if(syscall(__NR_write, fd, (void *)buf_child, data_len) == -1) { /* SUCCESS because we want the call to fail */ exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -45,10 +40,13 @@ TEST(Actions, dynamic_snaplen_negative_fd) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The write call is successful while it should fail..." << std::endl; } @@ -62,8 +60,7 @@ TEST(Actions, dynamic_snaplen_negative_fd) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -85,8 +82,7 @@ TEST(Actions, dynamic_snaplen_negative_fd) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_no_socket) -{ +TEST(Actions, dynamic_snaplen_no_socket) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -107,18 +103,14 @@ TEST(Actions, dynamic_snaplen_no_socket) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Ensure that buf is not paged out by the kernel on some archs, like riscv */ char buf_child[data_len] = "HTTP/\0"; /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_write, fd, (void *)buf_child, data_len) == -1) - { + if(syscall(__NR_write, fd, (void *)buf_child, data_len) == -1) { /* SUCCESS because we want the call to fail */ exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -127,10 +119,13 @@ TEST(Actions, dynamic_snaplen_no_socket) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The write call is successful while it should fail..." << std::endl; } @@ -144,8 +139,7 @@ TEST(Actions, dynamic_snaplen_no_socket) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -167,9 +161,9 @@ TEST(Actions, dynamic_snaplen_no_socket) evt_test->assert_num_params_pushed(2); } -#if defined(__NR_sendto) && defined(__NR_socket) && defined(__NR_shutdown) && defined(__NR_close) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_connect) -TEST(Actions, dynamic_snaplen_HTTP) -{ +#if defined(__NR_sendto) && defined(__NR_socket) && defined(__NR_shutdown) && \ + defined(__NR_close) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_connect) +TEST(Actions, dynamic_snaplen_HTTP) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -182,7 +176,10 @@ TEST(Actions, dynamic_snaplen_HTTP) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -193,15 +190,17 @@ TEST(Actions, dynamic_snaplen_HTTP) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -210,10 +209,13 @@ TEST(Actions, dynamic_snaplen_HTTP) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -231,8 +233,7 @@ TEST(Actions, dynamic_snaplen_HTTP) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -253,8 +254,7 @@ TEST(Actions, dynamic_snaplen_HTTP) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_partial_HTTP_OPT) -{ +TEST(Actions, dynamic_snaplen_partial_HTTP_OPT) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -267,7 +267,10 @@ TEST(Actions, dynamic_snaplen_partial_HTTP_OPT) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -279,15 +282,17 @@ TEST(Actions, dynamic_snaplen_partial_HTTP_OPT) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -296,10 +301,13 @@ TEST(Actions, dynamic_snaplen_partial_HTTP_OPT) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -317,8 +325,7 @@ TEST(Actions, dynamic_snaplen_partial_HTTP_OPT) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -339,8 +346,7 @@ TEST(Actions, dynamic_snaplen_partial_HTTP_OPT) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_HTTP_TRACE) -{ +TEST(Actions, dynamic_snaplen_HTTP_TRACE) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -353,7 +359,10 @@ TEST(Actions, dynamic_snaplen_HTTP_TRACE) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -364,15 +373,17 @@ TEST(Actions, dynamic_snaplen_HTTP_TRACE) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -381,10 +392,13 @@ TEST(Actions, dynamic_snaplen_HTTP_TRACE) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -402,8 +416,7 @@ TEST(Actions, dynamic_snaplen_HTTP_TRACE) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -424,8 +437,7 @@ TEST(Actions, dynamic_snaplen_HTTP_TRACE) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_MYSQL) -{ +TEST(Actions, dynamic_snaplen_MYSQL) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -438,7 +450,11 @@ TEST(Actions, dynamic_snaplen_MYSQL) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr, PPM_PORT_MYSQL); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr, + PPM_PORT_MYSQL); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -451,15 +467,17 @@ TEST(Actions, dynamic_snaplen_MYSQL) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -468,10 +486,13 @@ TEST(Actions, dynamic_snaplen_MYSQL) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -489,8 +510,7 @@ TEST(Actions, dynamic_snaplen_MYSQL) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -511,8 +531,7 @@ TEST(Actions, dynamic_snaplen_MYSQL) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_not_MYSQL) -{ +TEST(Actions, dynamic_snaplen_not_MYSQL) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -525,7 +544,11 @@ TEST(Actions, dynamic_snaplen_not_MYSQL) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr, PPM_PORT_MYSQL); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr, + PPM_PORT_MYSQL); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -536,15 +559,17 @@ TEST(Actions, dynamic_snaplen_not_MYSQL) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -553,10 +578,13 @@ TEST(Actions, dynamic_snaplen_not_MYSQL) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -574,8 +602,7 @@ TEST(Actions, dynamic_snaplen_not_MYSQL) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -596,8 +623,7 @@ TEST(Actions, dynamic_snaplen_not_MYSQL) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_POSTGRES) -{ +TEST(Actions, dynamic_snaplen_POSTGRES) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -610,7 +636,11 @@ TEST(Actions, dynamic_snaplen_POSTGRES) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr, PPM_PORT_POSTGRES); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr, + PPM_PORT_POSTGRES); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -623,15 +653,17 @@ TEST(Actions, dynamic_snaplen_POSTGRES) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -640,10 +672,13 @@ TEST(Actions, dynamic_snaplen_POSTGRES) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -661,8 +696,7 @@ TEST(Actions, dynamic_snaplen_POSTGRES) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -683,8 +717,7 @@ TEST(Actions, dynamic_snaplen_POSTGRES) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_not_POSTGRES) -{ +TEST(Actions, dynamic_snaplen_not_POSTGRES) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -697,7 +730,11 @@ TEST(Actions, dynamic_snaplen_not_POSTGRES) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr, PPM_PORT_POSTGRES); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr, + PPM_PORT_POSTGRES); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -708,15 +745,17 @@ TEST(Actions, dynamic_snaplen_not_POSTGRES) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -725,10 +764,13 @@ TEST(Actions, dynamic_snaplen_not_POSTGRES) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -746,8 +788,7 @@ TEST(Actions, dynamic_snaplen_not_POSTGRES) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -768,8 +809,7 @@ TEST(Actions, dynamic_snaplen_not_POSTGRES) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_MONGO) -{ +TEST(Actions, dynamic_snaplen_MONGO) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -782,27 +822,32 @@ TEST(Actions, dynamic_snaplen_MONGO) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; char buf[data_len] = {0}; - *(int32_t *)(&buf[12]) = 0x01; // this 1 and it's ok + *(int32_t *)(&buf[12]) = 0x01; // this 1 and it's ok uint32_t sendto_flags = 0; clone_args cl_args = {}; cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -811,10 +856,13 @@ TEST(Actions, dynamic_snaplen_MONGO) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -832,8 +880,7 @@ TEST(Actions, dynamic_snaplen_MONGO) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -854,8 +901,7 @@ TEST(Actions, dynamic_snaplen_MONGO) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_not_MONGO) -{ +TEST(Actions, dynamic_snaplen_not_MONGO) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -868,7 +914,10 @@ TEST(Actions, dynamic_snaplen_not_MONGO) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -880,15 +929,17 @@ TEST(Actions, dynamic_snaplen_not_MONGO) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -897,10 +948,13 @@ TEST(Actions, dynamic_snaplen_not_MONGO) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -918,8 +972,7 @@ TEST(Actions, dynamic_snaplen_not_MONGO) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -940,8 +993,7 @@ TEST(Actions, dynamic_snaplen_not_MONGO) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_statsd_port) -{ +TEST(Actions, dynamic_snaplen_statsd_port) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -957,7 +1009,10 @@ TEST(Actions, dynamic_snaplen_statsd_port) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -968,15 +1023,17 @@ TEST(Actions, dynamic_snaplen_statsd_port) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -985,10 +1042,13 @@ TEST(Actions, dynamic_snaplen_statsd_port) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -1011,8 +1071,7 @@ TEST(Actions, dynamic_snaplen_statsd_port) */ evt_test->set_statsd_port(0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1033,8 +1092,7 @@ TEST(Actions, dynamic_snaplen_statsd_port) evt_test->assert_num_params_pushed(2); } -TEST(Actions, dynamic_snaplen_no_statsd_port) -{ +TEST(Actions, dynamic_snaplen_no_statsd_port) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -1050,7 +1108,10 @@ TEST(Actions, dynamic_snaplen_no_statsd_port) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ const unsigned data_len = DEFAULT_SNAPLEN * 2; @@ -1061,15 +1122,17 @@ TEST(Actions, dynamic_snaplen_no_statsd_port) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_sendto, client_socket_fd, buf, data_len, sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) - { + if(syscall(__NR_sendto, + client_socket_fd, + buf, + data_len, + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -1078,10 +1141,13 @@ TEST(Actions, dynamic_snaplen_no_statsd_port) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The sendto call shouldn't fail..." << std::endl; } @@ -1104,8 +1170,7 @@ TEST(Actions, dynamic_snaplen_no_statsd_port) */ evt_test->set_statsd_port(0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/actions_suite/ring_buffer.cpp b/test/drivers/test_suites/actions_suite/ring_buffer.cpp index f93d5afea8..c94a4f4b7a 100644 --- a/test/drivers/test_suites/actions_suite/ring_buffer.cpp +++ b/test/drivers/test_suites/actions_suite/ring_buffer.cpp @@ -4,8 +4,7 @@ #include #if defined(__NR_close) && defined(__NR_openat) && defined(__NR_ioctl) -TEST(Actions, read_in_order_from_buffer) -{ +TEST(Actions, read_in_order_from_buffer) { /* Here we capture all syscalls... this process will send some * specific syscalls and we have to check that they are extracted in order * from the buffers. @@ -18,7 +17,9 @@ TEST(Actions, read_in_order_from_buffer) assert_syscall_state(SYSCALL_FAILURE, "close", syscall(__NR_close, -1)); /* 2. Generate an `openat` event pair */ - assert_syscall_state(SYSCALL_FAILURE, "openat", syscall(__NR_openat, AT_FDCWD, "mock_path", 0, 0)); + assert_syscall_state(SYSCALL_FAILURE, + "openat", + syscall(__NR_openat, AT_FDCWD, "mock_path", 0, 0)); /* 3. Generate an `ioctl` event pair */ assert_syscall_state(SYSCALL_FAILURE, "ioctl", syscall(__NR_ioctl, -1, 0, NULL)); diff --git a/test/drivers/test_suites/actions_suite/sampling_ratio.cpp b/test/drivers/test_suites/actions_suite/sampling_ratio.cpp index f25305bdce..6e916b1937 100644 --- a/test/drivers/test_suites/actions_suite/sampling_ratio.cpp +++ b/test/drivers/test_suites/actions_suite/sampling_ratio.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_unshare) -TEST(Actions, sampling_ratio_UF_ALWAYS_DROP) -{ +TEST(Actions, sampling_ratio_UF_ALWAYS_DROP) { /* Here we set just one `UF_ALWAYS_DROP` syscall as interesting... this process will send * only this specific syscall and we have to check that the corresponding event is dropped when * the sampling logic is enabled and not dropped when the logic is disabled. @@ -32,8 +31,7 @@ TEST(Actions, sampling_ratio_UF_ALWAYS_DROP) #endif #if defined(__NR_eventfd) && defined(__NR_close) -TEST(Actions, sampling_ratio_UF_NEVER_DROP) -{ +TEST(Actions, sampling_ratio_UF_NEVER_DROP) { /* Here we set just one `UF_NEVER_DROP` syscall as interesting... this process will send * only this specific syscall and we have to check that the corresponding event is * not dropped when the sampling logic is enabled. @@ -59,8 +57,7 @@ TEST(Actions, sampling_ratio_UF_NEVER_DROP) #endif #if defined(__NR_capset) -TEST(Actions, sampling_ratio_NO_FLAGS) -{ +TEST(Actions, sampling_ratio_NO_FLAGS) { /* Here we set just one syscall with no flags (UF_ALWAYS_DROP/UF_NEVER_DROP) * as interesting... this process will send only this specific syscall and * we have to check that the corresponding event is not dropped when the @@ -87,15 +84,15 @@ TEST(Actions, sampling_ratio_NO_FLAGS) #ifdef __NR_fcntl #include -TEST(Actions, sampling_ratio_dropping_FCNTL_E) -{ +TEST(Actions, sampling_ratio_dropping_FCNTL_E) { auto evt_test = get_syscall_event_test(__NR_fcntl, ENTER_EVENT); evt_test->enable_sampling_logic(1); evt_test->enable_capture(); - /* If called with `F_DUPFD_CLOEXEC` flag the fcntl event shouldn't be dropped by the dropping logic */ + /* If called with `F_DUPFD_CLOEXEC` flag the fcntl event shouldn't be dropped by the dropping + * logic */ int32_t invalid_fd = -1; int cmd = F_DUPFD_CLOEXEC; assert_syscall_state(SYSCALL_FAILURE, "fcntl", syscall(__NR_fcntl, invalid_fd, cmd)); @@ -118,15 +115,15 @@ TEST(Actions, sampling_ratio_dropping_FCNTL_E) evt_test->disable_capture(); } -TEST(Actions, sampling_ratio_dropping_FCNTL_X) -{ +TEST(Actions, sampling_ratio_dropping_FCNTL_X) { auto evt_test = get_syscall_event_test(__NR_fcntl, EXIT_EVENT); evt_test->enable_sampling_logic(1); evt_test->enable_capture(); - /* If called with `F_DUPFD_CLOEXEC` flag the fcntl event shouldn't be dropped by the dropping logic */ + /* If called with `F_DUPFD_CLOEXEC` flag the fcntl event shouldn't be dropped by the dropping + * logic */ int32_t invalid_fd = -1; int cmd = F_DUPFD_CLOEXEC; assert_syscall_state(SYSCALL_FAILURE, "fcntl", syscall(__NR_fcntl, invalid_fd, cmd)); @@ -151,8 +148,7 @@ TEST(Actions, sampling_ratio_dropping_FCNTL_X) #endif #if defined(__NR_close) && defined(__NR_socket) -TEST(Actions, sampling_ratio_dropping_CLOSE_E_invalid_fd) -{ +TEST(Actions, sampling_ratio_dropping_CLOSE_E_invalid_fd) { auto evt_test = get_syscall_event_test(__NR_close, ENTER_EVENT); evt_test->enable_sampling_logic(1); @@ -175,8 +171,7 @@ TEST(Actions, sampling_ratio_dropping_CLOSE_E_invalid_fd) evt_test->disable_capture(); } -TEST(Actions, sampling_ratio_dropping_CLOSE_E_max_fds) -{ +TEST(Actions, sampling_ratio_dropping_CLOSE_E_max_fds) { auto evt_test = get_syscall_event_test(__NR_close, ENTER_EVENT); evt_test->enable_sampling_logic(1); @@ -197,8 +192,7 @@ TEST(Actions, sampling_ratio_dropping_CLOSE_E_max_fds) evt_test->disable_capture(); } -TEST(Actions, sampling_ratio_dropping_CLOSE_E_already_closed_fd) -{ +TEST(Actions, sampling_ratio_dropping_CLOSE_E_already_closed_fd) { auto evt_test = get_syscall_event_test(__NR_close, ENTER_EVENT); evt_test->enable_sampling_logic(1); @@ -213,7 +207,8 @@ TEST(Actions, sampling_ratio_dropping_CLOSE_E_already_closed_fd) evt_test->assert_event_presence(); - /* Now we call again the close on the already close fd and we shouldn't be able to catch the close enter event */ + /* Now we call again the close on the already close fd and we shouldn't be able to catch the + * close enter event */ assert_syscall_state(SYSCALL_FAILURE, "close", syscall(__NR_close, socket_fd)); evt_test->disable_sampling_logic(); @@ -228,8 +223,7 @@ TEST(Actions, sampling_ratio_dropping_CLOSE_E_already_closed_fd) evt_test->disable_capture(); } -TEST(Actions, sampling_ratio_dropping_CLOSE_X) -{ +TEST(Actions, sampling_ratio_dropping_CLOSE_X) { auto evt_test = get_syscall_event_test(__NR_close, EXIT_EVENT); evt_test->enable_sampling_logic(1); @@ -254,8 +248,7 @@ TEST(Actions, sampling_ratio_dropping_CLOSE_X) #endif #ifdef __NR_bind -TEST(Actions, sampling_ratio_dropping_BIND_X) -{ +TEST(Actions, sampling_ratio_dropping_BIND_X) { auto evt_test = get_syscall_event_test(__NR_bind, EXIT_EVENT); evt_test->enable_sampling_logic(1); @@ -279,8 +272,7 @@ TEST(Actions, sampling_ratio_dropping_BIND_X) } #endif -TEST(Actions, sampling_ratio_check_DROP_E_DROP_X) -{ +TEST(Actions, sampling_ratio_check_DROP_E_DROP_X) { /* Enable all syscalls */ auto evt_test = get_syscall_event_test(); @@ -295,31 +287,25 @@ TEST(Actions, sampling_ratio_check_DROP_E_DROP_X) bool drop_x = false; struct ppm_evt_hdr* evt = NULL; - while(events_processed < max_events_to_process) - { + while(events_processed < max_events_to_process) { evt = evt_test->get_event_from_ringbuffer(&cpu_id); events_processed++; - if(evt != NULL) - { - if(evt->type == PPME_DROP_E) - { + if(evt != NULL) { + if(evt->type == PPME_DROP_E) { drop_e = true; } - if(evt->type == PPME_DROP_X) - { + if(evt->type == PPME_DROP_X) { drop_x = true; } - if(drop_e && drop_x) - { + if(drop_e && drop_x) { break; } } } - if(events_processed >= max_events_to_process) - { + if(events_processed >= max_events_to_process) { FAIL() << "Found 'drop_e' = " << drop_e << ", found 'drop_x' = " << drop_x << std::endl; } diff --git a/test/drivers/test_suites/generic_tracepoints_suite/page_fault_kernel.cpp b/test/drivers/test_suites/generic_tracepoints_suite/page_fault_kernel.cpp index f89db7348f..e5c9126b4f 100644 --- a/test/drivers/test_suites/generic_tracepoints_suite/page_fault_kernel.cpp +++ b/test/drivers/test_suites/generic_tracepoints_suite/page_fault_kernel.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(CAPTURE_PAGE_FAULTS) && defined(__NR_fork) && defined(__NR_wait4) -TEST(GenericTracepoints, page_fault_kernel) -{ +TEST(GenericTracepoints, page_fault_kernel) { auto evt_test = get_generic_event_test(PPM_SC_PAGE_FAULT_KERNEL); evt_test->enable_capture(); @@ -10,17 +9,19 @@ TEST(GenericTracepoints, page_fault_kernel) /*=============================== TRIGGER SYSCALL ===========================*/ pid_t ret_pid = syscall(__NR_fork); - if(ret_pid == 0) - { + if(ret_pid == 0) { exit(EXIT_SUCCESS); } assert_syscall_state(SYSCALL_SUCCESS, "fork", ret_pid, NOT_EQUAL, -1); int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Fork failed..." << std::endl; } @@ -30,8 +31,7 @@ TEST(GenericTracepoints, page_fault_kernel) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/generic_tracepoints_suite/page_fault_user.cpp b/test/drivers/test_suites/generic_tracepoints_suite/page_fault_user.cpp index 9327e02177..dcd94b30ef 100644 --- a/test/drivers/test_suites/generic_tracepoints_suite/page_fault_user.cpp +++ b/test/drivers/test_suites/generic_tracepoints_suite/page_fault_user.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(CAPTURE_PAGE_FAULTS) && defined(__NR_fork) && defined(__NR_wait4) -TEST(GenericTracepoints, page_fault_user) -{ +TEST(GenericTracepoints, page_fault_user) { auto evt_test = get_generic_event_test(PPM_SC_PAGE_FAULT_USER); evt_test->enable_capture(); @@ -10,17 +9,19 @@ TEST(GenericTracepoints, page_fault_user) /*=============================== TRIGGER SYSCALL ===========================*/ pid_t ret_pid = syscall(__NR_fork); - if(ret_pid == 0) - { + if(ret_pid == 0) { exit(EXIT_SUCCESS); } assert_syscall_state(SYSCALL_SUCCESS, "fork", ret_pid, NOT_EQUAL, -1); int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Fork failed..." << std::endl; } @@ -30,8 +31,7 @@ TEST(GenericTracepoints, page_fault_user) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exec.cpp b/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exec.cpp index e95dab99b6..a050340333 100644 --- a/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exec.cpp +++ b/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exec.cpp @@ -1,12 +1,12 @@ #include "../../event_class/event_class.h" #include "../../helpers/proc_parsing.h" -#if defined(CAPTURE_SCHED_PROC_EXEC) && defined(__NR_clone3) && defined(__NR_wait4) && defined(__NR_execve) +#if defined(CAPTURE_SCHED_PROC_EXEC) && defined(__NR_clone3) && defined(__NR_wait4) && \ + defined(__NR_execve) #include -TEST(GenericTracepoints, sched_proc_exec) -{ +TEST(GenericTracepoints, sched_proc_exec) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -17,15 +17,27 @@ TEST(GenericTracepoints, sched_proc_exec) const char *pathname = "/usr/bin/true"; const char *comm = "true"; - std::string too_long_arg (4096, 'x'); - const char *newargv[] = {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; - std::string truncated_too_long_arg (4096 - (strlen(pathname)+1) - (strlen("first_argv")+1) - 2*(strlen("")+1) - 1, 'x'); - const char *expected_newargv[] = {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; - - const char *newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", too_long_arg.c_str(), "2_ARGUMENT=no", NULL}; - std::string truncated_too_long_env (4096 - (strlen("IN_TEST=yes")+1) - (strlen("3_ARGUMENT=yes")+1) - 1, 'x'); - const char *expected_newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", truncated_too_long_env.c_str(), NULL}; - + std::string too_long_arg(4096, 'x'); + const char *newargv[] = + {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; + std::string truncated_too_long_arg( + 4096 - (strlen(pathname) + 1) - (strlen("first_argv") + 1) - 2 * (strlen("") + 1) - 1, + 'x'); + const char *expected_newargv[] = + {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; + + const char *newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + too_long_arg.c_str(), + "2_ARGUMENT=no", + NULL}; + std::string truncated_too_long_env( + 4096 - (strlen("IN_TEST=yes") + 1) - (strlen("3_ARGUMENT=yes") + 1) - 1, + 'x'); + const char *expected_newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + truncated_too_long_env.c_str(), + NULL}; /* We need to use `SIGCHLD` otherwise the parent won't receive any signal * when the child terminates. @@ -34,8 +46,7 @@ TEST(GenericTracepoints, sched_proc_exec) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execve, pathname, newargv, newenviron); exit(EXIT_FAILURE); } @@ -45,10 +56,13 @@ TEST(GenericTracepoints, sched_proc_exec) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } @@ -59,8 +73,7 @@ TEST(GenericTracepoints, sched_proc_exec) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -102,18 +115,20 @@ TEST(GenericTracepoints, sched_proc_exec) /* Parameter 16: env (type: PT_CHARBUFARRAY) */ evt_test->assert_charbuf_array_param(16, &expected_newenviron[0]); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ @@ -129,8 +144,7 @@ TEST(GenericTracepoints, sched_proc_exec) #if defined(__NR_memfd_create) && defined(__NR_openat) && defined(__NR_read) && defined(__NR_write) #include -TEST(GenericTracepoints, sched_proc_exec_success_memfd) -{ +TEST(GenericTracepoints, sched_proc_exec_success_memfd) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -142,26 +156,22 @@ TEST(GenericTracepoints, sched_proc_exec_success_memfd) /* Open the executable to copy */ int fd_to_read = syscall(__NR_openat, 0, "/usr/bin/echo", O_RDWR); - if(fd_to_read < 0) - { + if(fd_to_read < 0) { FAIL() << "failed to open the file to read\n"; } char buf[200]; ssize_t bytes_read = 200; - while(bytes_read != 0) - { + while(bytes_read != 0) { bytes_read = syscall(__NR_read, fd_to_read, buf, sizeof(buf)); - if(bytes_read < 0) - { + if(bytes_read < 0) { syscall(__NR_close, fd_to_read); syscall(__NR_close, mem_fd); FAIL() << "unable to read from file\n"; } bytes_read = syscall(__NR_write, mem_fd, buf, bytes_read); - if(bytes_read < 0) - { + if(bytes_read < 0) { syscall(__NR_close, fd_to_read); syscall(__NR_close, mem_fd); FAIL() << "unable to write to file\n"; @@ -176,8 +186,7 @@ TEST(GenericTracepoints, sched_proc_exec_success_memfd) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { char pathname[200]; snprintf(pathname, sizeof(pathname), "/proc/%d/fd/%d", getpid(), mem_fd); const char *newargv[] = {pathname, "[OUTPUT] SyscallExit.execveX_success_memfd", NULL}; @@ -192,11 +201,13 @@ TEST(GenericTracepoints, sched_proc_exec_success_memfd) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } @@ -207,8 +218,7 @@ TEST(GenericTracepoints, sched_proc_exec_success_memfd) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -223,8 +233,8 @@ TEST(GenericTracepoints, sched_proc_exec_success_memfd) /* Parameter 1: res (type: PT_ERRNO)*/ evt_test->assert_numeric_param(1, (int64_t)0); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE | PPM_EXE_FROM_MEMFD); @@ -234,12 +244,9 @@ TEST(GenericTracepoints, sched_proc_exec_success_memfd) * Please note that in the kernel module, we remove the " (deleted)" suffix while * in BPF we don't add it at all. */ - if(evt_test->is_kmod_engine()) - { + if(evt_test->is_kmod_engine()) { evt_test->assert_charbuf_param(28, "/memfd:malware"); - } - else - { + } else { /* In BPF drivers we don't have the correct result but we can reconstruct part of it */ evt_test->assert_charbuf_param(28, "memfd:malware"); } diff --git a/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exit.cpp b/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exit.cpp index 81b6fa59df..6d86442f24 100644 --- a/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exit.cpp +++ b/test/drivers/test_suites/generic_tracepoints_suite/sched_process_exit.cpp @@ -8,8 +8,7 @@ #include -TEST(GenericTracepoints, sched_proc_exit_no_children) -{ +TEST(GenericTracepoints, sched_proc_exit_no_children) { auto evt_test = get_generic_event_test(PPM_SC_SCHED_PROCESS_EXIT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(GenericTracepoints, sched_proc_exit_no_children) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(5); } @@ -34,12 +32,14 @@ TEST(GenericTracepoints, sched_proc_exit_no_children) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); uint8_t sig = 0; - if(__WIFSIGNALED(status) != 0) - { + if(__WIFSIGNALED(status) != 0) { sig = __WTERMSIG(status); } @@ -52,8 +52,7 @@ TEST(GenericTracepoints, sched_proc_exit_no_children) */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -90,8 +89,7 @@ TEST(GenericTracepoints, sched_proc_exit_no_children) #if defined(__NR_prctl) && defined(CLONE_CLEAR_SIGHAND) #include -TEST(GenericTracepoints, sched_proc_exit_prctl_subreaper) -{ +TEST(GenericTracepoints, sched_proc_exit_prctl_subreaper) { auto evt_test = get_generic_event_test(PPM_SC_SCHED_PROCESS_EXIT); evt_test->enable_capture(); @@ -114,11 +112,9 @@ TEST(GenericTracepoints, sched_proc_exit_prctl_subreaper) cl_args_parent.exit_signal = SIGCHLD; pid_t p1_t1_pid = syscall(__NR_clone3, &cl_args_parent, sizeof(cl_args_parent)); - if(p1_t1_pid == 0) - { + if(p1_t1_pid == 0) { /* p1_t1 calls prctl */ - if(syscall(__NR_prctl, PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) == -1) - { + if(syscall(__NR_prctl, PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) == -1) { exit(EXIT_FAILURE); } @@ -127,37 +123,31 @@ TEST(GenericTracepoints, sched_proc_exit_prctl_subreaper) cl_args_child.set_tid_size = 1; cl_args_child.exit_signal = SIGCHLD; pid_t p2_t1_pid = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(p2_t1_pid == 0) - { + if(p2_t1_pid == 0) { cl_args_child.set_tid = (uint64_t)&p3_t1; cl_args_child.set_tid_size = 1; cl_args_child.exit_signal = SIGCHLD; pid_t p3_t1_pid = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(p3_t1_pid == 0) - { + if(p3_t1_pid == 0) { sleep(1); exit(EXIT_SUCCESS); } - if(p3_t1_pid == -1) - { + if(p3_t1_pid == -1) { exit(EXIT_FAILURE); } /* p2_t1 dies we should reparent p3_t1 to p1_t1 since it is a reaper */ exit(EXIT_SUCCESS); } - if(p2_t1_pid == -1) - { + if(p2_t1_pid == -1) { exit(EXIT_FAILURE); } int status = 0; int options = 0; - if(syscall(__NR_wait4, p2_t1, &status, options, NULL) == -1) - { + if(syscall(__NR_wait4, p2_t1, &status, options, NULL) == -1) { exit(EXIT_FAILURE); } - if(syscall(__NR_wait4, p3_t1, &status, options, NULL) == -1) - { + if(syscall(__NR_wait4, p3_t1, &status, options, NULL) == -1) { exit(EXIT_FAILURE); } @@ -170,11 +160,13 @@ TEST(GenericTracepoints, sched_proc_exit_prctl_subreaper) int options = 0; /* Wait for the first child */ - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, p1_t1_pid, &status, options, NULL), - NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, p1_t1_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the first child failed." << std::endl; } @@ -184,8 +176,7 @@ TEST(GenericTracepoints, sched_proc_exit_prctl_subreaper) evt_test->assert_event_presence(p2_t1); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -203,8 +194,7 @@ TEST(GenericTracepoints, sched_proc_exit_prctl_subreaper) evt_test->assert_num_params_pushed(5); } -TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper) -{ +TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper) { auto evt_test = get_generic_event_test(PPM_SC_SCHED_PROCESS_EXIT); evt_test->enable_capture(); @@ -231,45 +221,38 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper) cl_args_parent.exit_signal = SIGCHLD; pid_t p1_t1_pid = syscall(__NR_clone3, &cl_args_parent, sizeof(cl_args_parent)); - if(p1_t1_pid == 0) - { + if(p1_t1_pid == 0) { clone_args cl_args_child = {}; cl_args_child.set_tid = (uint64_t)&p2_t1; cl_args_child.set_tid_size = 2; cl_args_child.exit_signal = SIGCHLD; pid_t p2_t1_pid = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(p2_t1_pid == 0) - { + if(p2_t1_pid == 0) { cl_args_child.set_tid = (uint64_t)&p3_t1; cl_args_child.set_tid_size = 2; cl_args_child.exit_signal = SIGCHLD; pid_t p3_t1_pid = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(p3_t1_pid == 0) - { + if(p3_t1_pid == 0) { sleep(1); exit(EXIT_SUCCESS); } - if(p3_t1_pid == -1) - { + if(p3_t1_pid == -1) { exit(EXIT_FAILURE); } /* p2_t1 dies we should reparent p3_t1 to p1_t1 since it is a reaper */ exit(EXIT_SUCCESS); } - if(p2_t1_pid == -1) - { + if(p2_t1_pid == -1) { exit(EXIT_FAILURE); } int status = 0; int options = 0; /* we are inside the namespace we need to use the right pids */ - if(syscall(__NR_wait4, p2_t1[0], &status, options, NULL) == -1) - { + if(syscall(__NR_wait4, p2_t1[0], &status, options, NULL) == -1) { exit(EXIT_FAILURE); } - if(syscall(__NR_wait4, p3_t1[0], &status, options, NULL) == -1) - { + if(syscall(__NR_wait4, p3_t1[0], &status, options, NULL) == -1) { exit(EXIT_FAILURE); } @@ -282,11 +265,13 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper) int options = 0; /* Wait for the first child */ - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, p1_t1_pid, &status, options, NULL), - NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, p1_t1_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the first child failed." << std::endl; } @@ -296,8 +281,7 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper) evt_test->assert_event_presence(p2_t1[1]); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -315,8 +299,7 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper) evt_test->assert_num_params_pushed(5); } -TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper_die) -{ +TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper_die) { auto evt_test = get_generic_event_test(PPM_SC_SCHED_PROCESS_EXIT); evt_test->enable_capture(); @@ -342,20 +325,17 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper_die) cl_args_parent.exit_signal = SIGCHLD; pid_t p1_t1_pid = syscall(__NR_clone3, &cl_args_parent, sizeof(cl_args_parent)); - if(p1_t1_pid == 0) - { + if(p1_t1_pid == 0) { clone_args cl_args_child = {}; cl_args_child.set_tid = (uint64_t)&p2_t1; cl_args_child.set_tid_size = 2; cl_args_parent.exit_signal = SIGCHLD; pid_t p2_t1_pid = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(p2_t1_pid == 0) - { + if(p2_t1_pid == 0) { sleep(20); exit(EXIT_SUCCESS); } - if(p2_t1_pid == -1) - { + if(p2_t1_pid == -1) { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); @@ -367,11 +347,13 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper_die) int options = 0; /* Wait for the first child */ - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, p1_t1_pid, &status, options, NULL), - NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, p1_t1_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the first child failed." << std::endl; } @@ -381,8 +363,7 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper_die) evt_test->assert_event_presence(p1_t1[1]); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -402,27 +383,23 @@ TEST(GenericTracepoints, sched_proc_exit_child_namespace_reaper_die) } #ifdef __NR_kill -static int child_func(void* arg) -{ +static int child_func(void* arg) { pid_t p2_t1 = 57006; clone_args cl_args_child = {}; cl_args_child.set_tid = (uint64_t)&p2_t1; cl_args_child.set_tid_size = 1; pid_t p2_t1_pid = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(p2_t1_pid == 0) - { + if(p2_t1_pid == 0) { sleep(1); return 0; } - if(p2_t1_pid == -1) - { + if(p2_t1_pid == -1) { exit(EXIT_FAILURE); } return 0; } -TEST(GenericTracepoints, sched_proc_exit_reaper_in_the_same_group) -{ +TEST(GenericTracepoints, sched_proc_exit_reaper_in_the_same_group) { auto evt_test = get_generic_event_test(PPM_SC_SCHED_PROCESS_EXIT); evt_test->enable_capture(); @@ -438,14 +415,13 @@ TEST(GenericTracepoints, sched_proc_exit_reaper_in_the_same_group) const int STACK_SIZE = 65536; char* stack = (char*)malloc(STACK_SIZE); - if(!stack) - { + if(!stack) { exit(EXIT_FAILURE); } /* Create a new thread */ - unsigned long flags = - CLONE_THREAD | CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_SIGHAND | SIGCHLD; + unsigned long flags = CLONE_THREAD | CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | + CLONE_SIGHAND | SIGCHLD; pid_t p1_t2_tid = clone(child_func, stack + STACK_SIZE, flags, NULL); assert_syscall_state(SYSCALL_SUCCESS, "clone", p1_t2_tid, NOT_EQUAL, -1); @@ -460,8 +436,7 @@ TEST(GenericTracepoints, sched_proc_exit_reaper_in_the_same_group) evt_test->assert_event_presence(p1_t2_tid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/generic_tracepoints_suite/sched_process_fork.cpp b/test/drivers/test_suites/generic_tracepoints_suite/sched_process_fork.cpp index e827521571..ceae169b82 100644 --- a/test/drivers/test_suites/generic_tracepoints_suite/sched_process_fork.cpp +++ b/test/drivers/test_suites/generic_tracepoints_suite/sched_process_fork.cpp @@ -6,8 +6,7 @@ #include #ifdef __NR_clone3 -TEST(GenericTracepoints, sched_proc_fork_case_clone3) -{ +TEST(GenericTracepoints, sched_proc_fork_case_clone3) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3) /* Here we scan the parent just to obtain some info for the child */ struct proc_info info = {0}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -31,8 +29,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3) pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); /* Child performs assertions on itself. */ - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -41,10 +38,12 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -54,8 +53,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -110,8 +108,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3) * we should also have the `set_tid` field in struct `clone_args` */ #ifdef CLONE_CLEAR_SIGHAND -TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads) -{ +TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -132,8 +129,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads pid_t ret_pid = syscall(__NR_clone3, &cl_args_parent, sizeof(cl_args_parent)); /* Create a child process that will spawn a new thread */ - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Spawn a new thread */ clone_args cl_args_child = {0}; cl_args_child.set_tid = (uint64_t)&p1_t2; @@ -144,8 +140,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads */ cl_args_child.flags = CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_VFORK | CLONE_PARENT; pid_t child_thread = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(child_thread == 0) - { + if(child_thread == 0) { exit(EXIT_SUCCESS); } exit(EXIT_SUCCESS); @@ -155,11 +150,13 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } /*=============================== TRIGGER SYSCALL ===========================*/ @@ -168,8 +165,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads evt_test->assert_event_presence(p1_t2); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { FAIL() << "There is a fatal failure in the child"; } @@ -198,7 +194,9 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads /* Parameter 16: flags (type: PT_FLAGS32) */ /* Right now we cannot send `PPM_CL_CLONE_PARENT` in our `sched_proc_fork` hook */ - evt_test->assert_numeric_param(16, (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM); + evt_test->assert_numeric_param( + 16, + (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM); /* Parameter 19: vtid (type: PT_PID) */ evt_test->assert_numeric_param(19, (int64_t)p1_t2); @@ -211,8 +209,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_create_child_with_2_threads evt_test->assert_num_params_pushed(21); } -TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_clone_parent_flag) -{ +TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_clone_parent_flag) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -232,20 +229,17 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_clone_parent_flag) cl_args_parent.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args_parent, sizeof(cl_args_parent)); - if(ret_pid == 0) - { + if(ret_pid == 0) { clone_args cl_args_child = {0}; cl_args_child.set_tid = (uint64_t)&p2_t1; cl_args_child.set_tid_size = 1; cl_args_child.flags = CLONE_PARENT; cl_args_parent.exit_signal = SIGCHLD; pid_t second_child = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(second_child == 0) - { + if(second_child == 0) { exit(EXIT_SUCCESS); } - if(second_child == -1) - { + if(second_child == -1) { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); @@ -257,20 +251,25 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_clone_parent_flag) int options = 0; /* Wait for the first child */ - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the first child failed." << std::endl; } - /* Since we are using the `CLONE_PARENT` flag the currect process is signaled also for the second child */ - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, p2_t1, &status, options, NULL), NOT_EQUAL, - -1); + /* Since we are using the `CLONE_PARENT` flag the currect process is signaled also for the + * second child */ + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, p2_t1, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the second child failed." << std::endl; } @@ -280,8 +279,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_clone_parent_flag) evt_test->assert_event_presence(p2_t1); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -320,8 +318,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_clone_parent_flag) } /* here we test only the child case because the caller won't use this tracepoint */ -TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_from_child) -{ +TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_from_child) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -337,8 +334,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_from_ch cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -347,11 +343,13 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_from_ch int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -361,8 +359,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_from_ch evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -399,8 +396,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_from_ch evt_test->assert_num_params_pushed(21); } -TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_create_thread) -{ +TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_create_thread) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -422,16 +418,14 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_create_ cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Spawn a new thread */ clone_args cl_args_child = {0}; cl_args_child.set_tid = (uint64_t)&p1_t2; cl_args_child.set_tid_size = 2; cl_args_child.flags = CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_VFORK; pid_t child_thread = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(child_thread == 0) - { + if(child_thread == 0) { exit(EXIT_SUCCESS); } exit(EXIT_SUCCESS); @@ -441,11 +435,13 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_create_ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -455,8 +451,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_create_ evt_test->assert_event_presence(p1_t2[1]); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -480,8 +475,9 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_create_ /* Parameter 16: flags (type: PT_FLAGS32) */ /* we cannot get the `PPM_CL_CLONE_VFORK` flag here */ - evt_test->assert_numeric_param(16, (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM | - PPM_CL_CHILD_IN_PIDNS); + evt_test->assert_numeric_param(16, + (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | + PPM_CL_CLONE_VM | PPM_CL_CHILD_IN_PIDNS); /* Parameter 19: vtid (type: PT_PID) */ evt_test->assert_numeric_param(19, (int64_t)p1_t2[0]); @@ -498,8 +494,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone3_child_new_namespace_create_ #endif /* __NR_clone3 */ #ifdef __NR_clone -TEST(GenericTracepoints, sched_proc_fork_case_clone) -{ +TEST(GenericTracepoints, sched_proc_fork_case_clone) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -509,8 +504,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone) /* Here we scan the parent just to obtain some info for the child */ struct proc_info info = {0}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -532,8 +526,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone) ret_pid = syscall(__NR_clone, clone_flags, newsp, &parent_tid, &child_tid, tls); #endif - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -542,10 +535,12 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -555,8 +550,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -609,8 +603,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_clone) #endif /* __NR_clone */ #ifdef __NR_fork -TEST(GenericTracepoints, sched_proc_fork_case_fork) -{ +TEST(GenericTracepoints, sched_proc_fork_case_fork) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -620,15 +613,13 @@ TEST(GenericTracepoints, sched_proc_fork_case_fork) /* Here we scan the parent just to obtain some info for the child */ struct proc_info info = {0}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } pid_t ret_pid = syscall(__NR_fork); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -637,11 +628,13 @@ TEST(GenericTracepoints, sched_proc_fork_case_fork) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -651,8 +644,7 @@ TEST(GenericTracepoints, sched_proc_fork_case_fork) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/generic_tracepoints_suite/sched_switch.cpp b/test/drivers/test_suites/generic_tracepoints_suite/sched_switch.cpp index 48f2372657..7997dca258 100644 --- a/test/drivers/test_suites/generic_tracepoints_suite/sched_switch.cpp +++ b/test/drivers/test_suites/generic_tracepoints_suite/sched_switch.cpp @@ -5,8 +5,7 @@ #include -TEST(GenericTracepoints, sched_switch) -{ +TEST(GenericTracepoints, sched_switch) { auto evt_test = get_generic_event_test(PPM_SC_SCHED_SWITCH); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(GenericTracepoints, sched_switch) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -30,7 +28,11 @@ TEST(GenericTracepoints, sched_switch) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -39,8 +41,7 @@ TEST(GenericTracepoints, sched_switch) /* We search for a father event. */ evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/generic_tracepoints_suite/signal_deliver.cpp b/test/drivers/test_suites/generic_tracepoints_suite/signal_deliver.cpp index 199635cb18..b5242c146c 100644 --- a/test/drivers/test_suites/generic_tracepoints_suite/signal_deliver.cpp +++ b/test/drivers/test_suites/generic_tracepoints_suite/signal_deliver.cpp @@ -4,25 +4,25 @@ #include -static void signal_deliver_callback(int signal) -{ -} +static void signal_deliver_callback(int signal) {} -TEST(GenericTracepoints, signal_deliver) -{ +TEST(GenericTracepoints, signal_deliver) { auto evt_test = get_generic_event_test(PPM_SC_SIGNAL_DELIVER); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - if(signal(SIGUSR1, signal_deliver_callback) == SIG_ERR) - { + if(signal(SIGUSR1, signal_deliver_callback) == SIG_ERR) { FAIL() << "An error occurred while setting SIGUSR1 signal handler.\n"; } /* Send a signal to the caller */ - assert_syscall_state(SYSCALL_SUCCESS, "kill", syscall(__NR_kill, getpid(), SIGUSR1), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "kill", + syscall(__NR_kill, getpid(), SIGUSR1), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -30,8 +30,7 @@ TEST(GenericTracepoints, signal_deliver) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/accept4_e.cpp b/test/drivers/test_suites/syscall_enter_suite/accept4_e.cpp index aefe292d4a..26c7e2c48d 100644 --- a/test/drivers/test_suites/syscall_enter_suite/accept4_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/accept4_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_accept4 -TEST(SyscallEnter, accept4E) -{ +TEST(SyscallEnter, accept4E) { auto evt_test = get_syscall_event_test(__NR_accept4, ENTER_EVENT); evt_test->enable_capture(); @@ -12,9 +11,11 @@ TEST(SyscallEnter, accept4E) int32_t mock_fd = -1; sockaddr* addr = NULL; - socklen_t *addrlen = NULL; + socklen_t* addrlen = NULL; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "accept4", syscall(__NR_accept4, mock_fd, addr, addrlen, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "accept4", + syscall(__NR_accept4, mock_fd, addr, addrlen, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, accept4E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/accept_e.cpp b/test/drivers/test_suites/syscall_enter_suite/accept_e.cpp index 6c5ec9ab45..1e87548f99 100644 --- a/test/drivers/test_suites/syscall_enter_suite/accept_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/accept_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_accept -TEST(SyscallEnter, acceptE) -{ +TEST(SyscallEnter, acceptE) { auto evt_test = get_syscall_event_test(__NR_accept, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,7 @@ TEST(SyscallEnter, acceptE) int32_t mock_fd = -1; sockaddr* addr = NULL; - socklen_t *addrlen = NULL; + socklen_t* addrlen = NULL; assert_syscall_state(SYSCALL_FAILURE, "accept", syscall(__NR_accept, mock_fd, addr, addrlen)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +20,7 @@ TEST(SyscallEnter, acceptE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/access_e.cpp b/test/drivers/test_suites/syscall_enter_suite/access_e.cpp index 4e4b9fad60..458403bdcd 100644 --- a/test/drivers/test_suites/syscall_enter_suite/access_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/access_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_access -TEST(SyscallEnter, accessE) -{ +TEST(SyscallEnter, accessE) { auto evt_test = get_syscall_event_test(__NR_access, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, accessE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/bind_e.cpp b/test/drivers/test_suites/syscall_enter_suite/bind_e.cpp index 67ca6c6d4e..985247b6ee 100644 --- a/test/drivers/test_suites/syscall_enter_suite/bind_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/bind_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_bind -TEST(SyscallEnter, bindE) -{ +TEST(SyscallEnter, bindE) { auto evt_test = get_syscall_event_test(__NR_bind, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, bindE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/bpf_e.cpp b/test/drivers/test_suites/syscall_enter_suite/bpf_e.cpp index f6e246488a..3df9c873b2 100644 --- a/test/drivers/test_suites/syscall_enter_suite/bpf_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/bpf_e.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallEnter, bpfE) -{ +TEST(SyscallEnter, bpfE) { auto evt_test = get_syscall_event_test(__NR_bpf, ENTER_EVENT); evt_test->enable_capture(); @@ -24,16 +23,12 @@ TEST(SyscallEnter, bpfE) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if (ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_bpf, cmd, attr, size) == -1) - { + if(syscall(__NR_bpf, cmd, attr, size) == -1) { /* SUCCESS because we want the call to fail */ exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -42,10 +37,13 @@ TEST(SyscallEnter, bpfE) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The bpf call is successful while it should fail..." << std::endl; } @@ -55,8 +53,7 @@ TEST(SyscallEnter, bpfE) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/brk_e.cpp b/test/drivers/test_suites/syscall_enter_suite/brk_e.cpp index 30b8e95348..c851ad153a 100644 --- a/test/drivers/test_suites/syscall_enter_suite/brk_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/brk_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_brk -TEST(SyscallEnter, brkE) -{ +TEST(SyscallEnter, brkE) { auto evt_test = get_syscall_event_test(__NR_brk, ENTER_EVENT); evt_test->enable_capture(); @@ -11,8 +10,8 @@ TEST(SyscallEnter, brkE) /*=============================== TRIGGER SYSCALL ===========================*/ unsigned long addr = 0; - /* brk returns the new program break on success. On failure, the system call returns the current break, - * so we cannot assert its failure + /* brk returns the new program break on success. On failure, the system call returns the + * current break, so we cannot assert its failure */ syscall(__NR_brk, addr); @@ -22,8 +21,7 @@ TEST(SyscallEnter, brkE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/capset_e.cpp b/test/drivers/test_suites/syscall_enter_suite/capset_e.cpp index 05564c9988..f6a1aa4b5f 100644 --- a/test/drivers/test_suites/syscall_enter_suite/capset_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/capset_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, capsetE) -{ +TEST(SyscallEnter, capsetE) { auto evt_test = get_syscall_event_test(__NR_capset, ENTER_EVENT); evt_test->enable_capture(); @@ -25,8 +24,7 @@ TEST(SyscallEnter, capsetE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/chdir_e.cpp b/test/drivers/test_suites/syscall_enter_suite/chdir_e.cpp index f311faf417..3365ef0223 100644 --- a/test/drivers/test_suites/syscall_enter_suite/chdir_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/chdir_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chdir -TEST(SyscallEnter, chdirE) -{ +TEST(SyscallEnter, chdirE) { auto evt_test = get_syscall_event_test(__NR_chdir, ENTER_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallEnter, chdirE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/chmod_e.cpp b/test/drivers/test_suites/syscall_enter_suite/chmod_e.cpp index c45ab93f52..54a7684418 100644 --- a/test/drivers/test_suites/syscall_enter_suite/chmod_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/chmod_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chmod -TEST(SyscallEnter, chmodE) -{ +TEST(SyscallEnter, chmodE) { auto evt_test = get_syscall_event_test(__NR_chmod, ENTER_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(SyscallEnter, chmodE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/chown_e.cpp b/test/drivers/test_suites/syscall_enter_suite/chown_e.cpp index 59e35b5add..56ecbafa75 100644 --- a/test/drivers/test_suites/syscall_enter_suite/chown_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/chown_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chown -TEST(SyscallEnter, chownE) -{ +TEST(SyscallEnter, chownE) { auto evt_test = get_syscall_event_test(__NR_chown, ENTER_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(SyscallEnter, chownE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/chroot_e.cpp b/test/drivers/test_suites/syscall_enter_suite/chroot_e.cpp index cff50bd859..41fc9cbfc1 100644 --- a/test/drivers/test_suites/syscall_enter_suite/chroot_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/chroot_e.cpp @@ -1,9 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chroot -TEST(SyscallEnter, chrootE) -{ - +TEST(SyscallEnter, chrootE) { auto evt_test = get_syscall_event_test(__NR_chroot, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +16,7 @@ TEST(SyscallEnter, chrootE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/clone3_e.cpp b/test/drivers/test_suites/syscall_enter_suite/clone3_e.cpp index 1a913a143f..cab872d453 100644 --- a/test/drivers/test_suites/syscall_enter_suite/clone3_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/clone3_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, clone3E) -{ +TEST(SyscallEnter, clone3E) { auto evt_test = get_syscall_event_test(__NR_clone3, ENTER_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallEnter, clone3E) /* flags are invalid so the syscall will fail. */ clone_args cl_args = {}; cl_args.flags = (unsigned long)-1; - assert_syscall_state(SYSCALL_FAILURE, "clone3", syscall(__NR_clone3, &cl_args, sizeof(cl_args))); + assert_syscall_state(SYSCALL_FAILURE, + "clone3", + syscall(__NR_clone3, &cl_args, sizeof(cl_args))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallEnter, clone3E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/clone_e.cpp b/test/drivers/test_suites/syscall_enter_suite/clone_e.cpp index 17ac50a964..f69c3b43e9 100644 --- a/test/drivers/test_suites/syscall_enter_suite/clone_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/clone_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_clone -TEST(SyscallEnter, cloneE) -{ +TEST(SyscallEnter, cloneE) { auto evt_test = get_syscall_event_test(__NR_clone, ENTER_EVENT); evt_test->enable_capture(); @@ -16,19 +15,16 @@ TEST(SyscallEnter, cloneE) int child_tid = -1; unsigned long tls = 0; - /* Please note: Some systems are compiled with kernel config like `CONFIG_CLONE_BACKWARDS2`, so the order of clone params - * is not the same as for all architectures. `/kernel/fork.c` from kernel source tree. + /* Please note: Some systems are compiled with kernel config like `CONFIG_CLONE_BACKWARDS2`, so + *the order of clone params is not the same as for all architectures. `/kernel/fork.c` from + *kernel source tree. * * #ifdef CONFIG_CLONE_BACKWARDS - * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `aarch64` systems use this. - * int __user *, parent_tidptr, - * unsigned long, tls, - * int __user *, child_tidptr) + * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `aarch64` + *systems use this. int __user *, parent_tidptr, unsigned long, tls, int __user *, child_tidptr) * #elif defined(CONFIG_CLONE_BACKWARDS2) - * SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags, <-- `s390x` systems use this. - * int __user *, parent_tidptr, - * int __user *, child_tidptr, - * unsigned long, tls) + * SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags, <-- `s390x` + *systems use this. int __user *, parent_tidptr, int __user *, child_tidptr, unsigned long, tls) * #elif defined(CONFIG_CLONE_BACKWARDS3) * SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp, * int, stack_size, @@ -36,19 +32,23 @@ TEST(SyscallEnter, cloneE) * int __user *, child_tidptr, * unsigned long, tls) * #else - * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `x86_64` systems use this. - * int __user *, parent_tidptr, - * int __user *, child_tidptr, - * unsigned long, tls) + * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `x86_64` + *systems use this. int __user *, parent_tidptr, int __user *, child_tidptr, unsigned long, tls) * #endif * */ #ifdef __s390x__ - assert_syscall_state(SYSCALL_FAILURE, "clone", syscall(__NR_clone, newsp, clone_flags, &parent_tid, &child_tid, tls)); + assert_syscall_state(SYSCALL_FAILURE, + "clone", + syscall(__NR_clone, newsp, clone_flags, &parent_tid, &child_tid, tls)); #elif defined(__aarch64__) || defined(__riscv) || defined(__loongarch64) - assert_syscall_state(SYSCALL_FAILURE, "clone", syscall(__NR_clone, clone_flags, newsp, &parent_tid, tls, &child_tid)); + assert_syscall_state(SYSCALL_FAILURE, + "clone", + syscall(__NR_clone, clone_flags, newsp, &parent_tid, tls, &child_tid)); #else - assert_syscall_state(SYSCALL_FAILURE, "clone", syscall(__NR_clone, clone_flags, newsp, &parent_tid, &child_tid, tls)); + assert_syscall_state(SYSCALL_FAILURE, + "clone", + syscall(__NR_clone, clone_flags, newsp, &parent_tid, &child_tid, tls)); #endif /*=============================== TRIGGER SYSCALL ===========================*/ @@ -57,8 +57,7 @@ TEST(SyscallEnter, cloneE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/close_e.cpp b/test/drivers/test_suites/syscall_enter_suite/close_e.cpp index 214149a589..ff8095f36b 100644 --- a/test/drivers/test_suites/syscall_enter_suite/close_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/close_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_close -TEST(SyscallEnter, closeE) -{ +TEST(SyscallEnter, closeE) { auto evt_test = get_syscall_event_test(__NR_close, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallEnter, closeE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/connect_e.cpp b/test/drivers/test_suites/syscall_enter_suite/connect_e.cpp index ed39a62391..c5225e5313 100644 --- a/test/drivers/test_suites/syscall_enter_suite/connect_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/connect_e.cpp @@ -2,8 +2,7 @@ #if defined(__NR_connect) -TEST(SyscallEnter, connectE_INET_failure) -{ +TEST(SyscallEnter, connectE_INET_failure) { auto evt_test = get_syscall_event_test(__NR_connect, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,10 @@ TEST(SyscallEnter, connectE_INET_failure) int32_t mock_fd = -1; sockaddr_in server_addr; evt_test->server_fill_sockaddr_in(&server_addr); - assert_syscall_state(SYSCALL_FAILURE, "connect", syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); + assert_syscall_state( + SYSCALL_FAILURE, + "connect", + syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +23,7 @@ TEST(SyscallEnter, connectE_INET_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -36,16 +37,16 @@ TEST(SyscallEnter, connectE_INET_failure) evt_test->assert_numeric_param(1, (int64_t)mock_fd); /* Parameter 2: addr (type: PT_SOCKADDR)*/ - /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. */ - if(evt_test->is_modern_bpf_engine()) - { + /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. + */ + if(evt_test->is_modern_bpf_engine()) { evt_test->assert_addr_info_inet_param(2, PPM_AF_INET, IPV4_SERVER, IPV4_PORT_SERVER_STRING); - } - else - { + } else { evt_test->assert_empty_param(2); evt_test->assert_num_params_pushed(2); - GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } /*=============================== ASSERT PARAMETERS ===========================*/ @@ -53,8 +54,7 @@ TEST(SyscallEnter, connectE_INET_failure) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, connectE_INET6_failure) -{ +TEST(SyscallEnter, connectE_INET6_failure) { auto evt_test = get_syscall_event_test(__NR_connect, ENTER_EVENT); evt_test->enable_capture(); @@ -64,7 +64,10 @@ TEST(SyscallEnter, connectE_INET6_failure) int32_t mock_fd = -1; sockaddr_in6 server_addr; evt_test->server_fill_sockaddr_in6(&server_addr); - assert_syscall_state(SYSCALL_FAILURE, "connect", syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); + assert_syscall_state( + SYSCALL_FAILURE, + "connect", + syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -72,8 +75,7 @@ TEST(SyscallEnter, connectE_INET6_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -87,16 +89,19 @@ TEST(SyscallEnter, connectE_INET6_failure) evt_test->assert_numeric_param(1, (int64_t)mock_fd); /* Parameter 2: addr (type: PT_SOCKADDR)*/ - /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. */ - if(evt_test->is_modern_bpf_engine()) - { - evt_test->assert_addr_info_inet6_param(2, PPM_AF_INET6, IPV6_SERVER, IPV6_PORT_SERVER_STRING); - } - else - { + /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. + */ + if(evt_test->is_modern_bpf_engine()) { + evt_test->assert_addr_info_inet6_param(2, + PPM_AF_INET6, + IPV6_SERVER, + IPV6_PORT_SERVER_STRING); + } else { evt_test->assert_empty_param(2); evt_test->assert_num_params_pushed(2); - GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } /*=============================== ASSERT PARAMETERS ===========================*/ @@ -104,8 +109,7 @@ TEST(SyscallEnter, connectE_INET6_failure) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, connectE_UNIX_failure) -{ +TEST(SyscallEnter, connectE_UNIX_failure) { auto evt_test = get_syscall_event_test(__NR_connect, ENTER_EVENT); evt_test->enable_capture(); @@ -118,7 +122,10 @@ TEST(SyscallEnter, connectE_UNIX_failure) int32_t mock_fd = -1; sockaddr_un server_addr; evt_test->server_fill_sockaddr_un(&server_addr); - assert_syscall_state(SYSCALL_FAILURE, "connect", syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); + assert_syscall_state( + SYSCALL_FAILURE, + "connect", + syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -126,8 +133,7 @@ TEST(SyscallEnter, connectE_UNIX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -141,16 +147,16 @@ TEST(SyscallEnter, connectE_UNIX_failure) evt_test->assert_numeric_param(1, (int64_t)mock_fd); /* Parameter 2: addr (type: PT_SOCKADDR)*/ - /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. */ - if(evt_test->is_modern_bpf_engine()) - { + /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. + */ + if(evt_test->is_modern_bpf_engine()) { evt_test->assert_addr_info_unix_param(2, PPM_AF_UNIX, UNIX_SERVER); - } - else - { + } else { evt_test->assert_empty_param(2); evt_test->assert_num_params_pushed(2); - GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } /*=============================== ASSERT PARAMETERS ===========================*/ @@ -158,14 +164,17 @@ TEST(SyscallEnter, connectE_UNIX_failure) evt_test->assert_num_params_pushed(2); } -/* This is 109 chars long, so no null terminator will be put inside the `sun_path` during the socket call. - * The BPF prog can read at most `108` chars so instead of the `*`, it will put the `\0`. +/* This is 109 chars long, so no null terminator will be put inside the `sun_path` during the socket + * call. The BPF prog can read at most `108` chars so instead of the `*`, it will put the `\0`. */ -#define UNIX_LONG_PATH "/unix_socket/test/too_long/too_long/too_long/too_long/unix_socket/test/too_long/too_long/too_long/too_longgg*" -#define EXPECTED_UNIX_LONG_PATH "/unix_socket/test/too_long/too_long/too_long/too_long/unix_socket/test/too_long/too_long/too_long/too_longgg" - -TEST(SyscallEnter, connectE_UNIX_max_path_failure) -{ +#define UNIX_LONG_PATH \ + "/unix_socket/test/too_long/too_long/too_long/too_long/unix_socket/test/too_long/too_long/" \ + "too_long/too_longgg*" +#define EXPECTED_UNIX_LONG_PATH \ + "/unix_socket/test/too_long/too_long/too_long/too_long/unix_socket/test/too_long/too_long/" \ + "too_long/too_longgg" + +TEST(SyscallEnter, connectE_UNIX_max_path_failure) { auto evt_test = get_syscall_event_test(__NR_connect, ENTER_EVENT); evt_test->enable_capture(); @@ -180,7 +189,10 @@ TEST(SyscallEnter, connectE_UNIX_max_path_failure) int32_t mock_fd = -1; sockaddr_un server_addr; evt_test->server_fill_sockaddr_un(&server_addr, UNIX_LONG_PATH); - assert_syscall_state(SYSCALL_FAILURE, "connect", syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); + assert_syscall_state( + SYSCALL_FAILURE, + "connect", + syscall(__NR_connect, mock_fd, (sockaddr*)&server_addr, sizeof(server_addr))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -188,8 +200,7 @@ TEST(SyscallEnter, connectE_UNIX_max_path_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -203,16 +214,16 @@ TEST(SyscallEnter, connectE_UNIX_max_path_failure) evt_test->assert_numeric_param(1, (int64_t)mock_fd); /* Parameter 2: addr (type: PT_SOCKADDR)*/ - /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. */ - if(evt_test->is_modern_bpf_engine()) - { + /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. + */ + if(evt_test->is_modern_bpf_engine()) { evt_test->assert_addr_info_unix_param(2, PPM_AF_UNIX, EXPECTED_UNIX_LONG_PATH); - } - else - { + } else { evt_test->assert_empty_param(2); evt_test->assert_num_params_pushed(2); - GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } /*=============================== ASSERT PARAMETERS ===========================*/ @@ -220,8 +231,7 @@ TEST(SyscallEnter, connectE_UNIX_max_path_failure) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, connectE_null_sockaddr_failure) -{ +TEST(SyscallEnter, connectE_null_sockaddr_failure) { auto evt_test = get_syscall_event_test(__NR_connect, ENTER_EVENT); evt_test->enable_capture(); @@ -242,8 +252,7 @@ TEST(SyscallEnter, connectE_null_sockaddr_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/copy_file_range_e.cpp b/test/drivers/test_suites/syscall_enter_suite/copy_file_range_e.cpp index 3a4cf156c5..9b155ab100 100644 --- a/test/drivers/test_suites/syscall_enter_suite/copy_file_range_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/copy_file_range_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_copy_file_range -TEST(SyscallEnter, copy_file_rangeE) -{ +TEST(SyscallEnter, copy_file_rangeE) { auto evt_test = get_syscall_event_test(__NR_copy_file_range, ENTER_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallEnter, copy_file_rangeE) off64_t off_out = 300; size_t len = 20; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "copy_file_range", syscall(__NR_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "copy_file_range", + syscall(__NR_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallEnter, copy_file_rangeE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/creat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/creat_e.cpp index 2d68b8146d..a9694c2957 100644 --- a/test/drivers/test_suites/syscall_enter_suite/creat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/creat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_creat -TEST(SyscallEnter, creatE) -{ +TEST(SyscallEnter, creatE) { auto evt_test = get_syscall_event_test(__NR_creat, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, creatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -41,8 +39,7 @@ TEST(SyscallEnter, creatE) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, creatE_max_path) -{ +TEST(SyscallEnter, creatE_max_path) { auto evt_test = get_syscall_event_test(__NR_creat, ENTER_EVENT); evt_test->enable_capture(); @@ -60,8 +57,7 @@ TEST(SyscallEnter, creatE_max_path) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/dup2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/dup2_e.cpp index b2b7682b94..caf83382dc 100644 --- a/test/drivers/test_suites/syscall_enter_suite/dup2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/dup2_e.cpp @@ -2,8 +2,7 @@ #include "../../helpers/file_opener.h" #if defined(__NR_dup2) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallEnter, dup2E) -{ +TEST(SyscallEnter, dup2E) { auto evt_test = get_syscall_event_test(__NR_dup2, ENTER_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallEnter, dup2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/dup3_e.cpp b/test/drivers/test_suites/syscall_enter_suite/dup3_e.cpp index bfc2caeacc..a60982cef6 100644 --- a/test/drivers/test_suites/syscall_enter_suite/dup3_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/dup3_e.cpp @@ -2,8 +2,7 @@ #include "../../helpers/file_opener.h" #if defined(__NR_dup3) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallEnter, dup3E) -{ +TEST(SyscallEnter, dup3E) { auto evt_test = get_syscall_event_test(__NR_dup3, ENTER_EVENT); evt_test->enable_capture(); @@ -28,8 +27,7 @@ TEST(SyscallEnter, dup3E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/dup_e.cpp b/test/drivers/test_suites/syscall_enter_suite/dup_e.cpp index b918bf420a..7e1559fd78 100644 --- a/test/drivers/test_suites/syscall_enter_suite/dup_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/dup_e.cpp @@ -2,8 +2,7 @@ #include "../../helpers/file_opener.h" #if defined(__NR_dup) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallEnter, dupE) -{ +TEST(SyscallEnter, dupE) { auto evt_test = get_syscall_event_test(__NR_dup, ENTER_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallEnter, dupE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/epoll_create1_e.cpp b/test/drivers/test_suites/syscall_enter_suite/epoll_create1_e.cpp index 846d5c6373..3f999544ae 100644 --- a/test/drivers/test_suites/syscall_enter_suite/epoll_create1_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/epoll_create1_e.cpp @@ -2,8 +2,7 @@ #include #if defined(__NR_epoll_create1) && defined(__NR_close) -TEST(SyscallEnter, epoll_create1E) -{ +TEST(SyscallEnter, epoll_create1E) { auto evt_test = get_syscall_event_test(__NR_epoll_create1, ENTER_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallEnter, epoll_create1E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/epoll_create_e.cpp b/test/drivers/test_suites/syscall_enter_suite/epoll_create_e.cpp index cdd90bc87e..748f685ec4 100644 --- a/test/drivers/test_suites/syscall_enter_suite/epoll_create_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/epoll_create_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_epoll_create) && defined(__NR_close) -TEST(SyscallEnter, epoll_createE) -{ +TEST(SyscallEnter, epoll_createE) { auto evt_test = get_syscall_event_test(__NR_epoll_create, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, epoll_createE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/epoll_wait_e.cpp b/test/drivers/test_suites/syscall_enter_suite/epoll_wait_e.cpp index 61bd09dde7..4f22d1f742 100644 --- a/test/drivers/test_suites/syscall_enter_suite/epoll_wait_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/epoll_wait_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_epoll_wait -TEST(SyscallEnter, epoll_waitE) -{ +TEST(SyscallEnter, epoll_waitE) { auto evt_test = get_syscall_event_test(__NR_epoll_wait, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, epoll_waitE) void* events = NULL; int maxevents = 10; int timeout = 0; - assert_syscall_state(SYSCALL_FAILURE, "epoll_wait", syscall(__NR_epoll_wait, epfd, events, maxevents, timeout)); + assert_syscall_state(SYSCALL_FAILURE, + "epoll_wait", + syscall(__NR_epoll_wait, epfd, events, maxevents, timeout)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, epoll_waitE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/eventfd2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/eventfd2_e.cpp index b31703941d..bedad03569 100644 --- a/test/drivers/test_suites/syscall_enter_suite/eventfd2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/eventfd2_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_eventfd2) -TEST(SyscallEnter, eventfd2E) -{ +TEST(SyscallEnter, eventfd2E) { auto evt_test = get_syscall_event_test(__NR_eventfd2, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, eventfd2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/eventfd_e.cpp b/test/drivers/test_suites/syscall_enter_suite/eventfd_e.cpp index d0da725157..bc1b902de6 100644 --- a/test/drivers/test_suites/syscall_enter_suite/eventfd_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/eventfd_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_eventfd) && defined(__NR_close) -TEST(SyscallEnter, eventfdE) -{ +TEST(SyscallEnter, eventfdE) { auto evt_test = get_syscall_event_test(__NR_eventfd, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, eventfdE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/execve_e.cpp b/test/drivers/test_suites/syscall_enter_suite/execve_e.cpp index c7d4c0e164..8effc67072 100644 --- a/test/drivers/test_suites/syscall_enter_suite/execve_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/execve_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_execve -TEST(SyscallEnter, execveE) -{ +TEST(SyscallEnter, execveE) { auto evt_test = get_syscall_event_test(__NR_execve, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, execveE) char pathname[] = "//**null-file-path**//"; const char *newargv = NULL; const char *newenviron = NULL; - assert_syscall_state(SYSCALL_FAILURE, "execve", syscall(__NR_execve, pathname, newargv, newenviron)); + assert_syscall_state(SYSCALL_FAILURE, + "execve", + syscall(__NR_execve, pathname, newargv, newenviron)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, execveE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/execveat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/execveat_e.cpp index ce48e96c4e..164b179cd7 100644 --- a/test/drivers/test_suites/syscall_enter_suite/execveat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/execveat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_execveat -TEST(SyscallEnter, execveatE) -{ +TEST(SyscallEnter, execveatE) { auto evt_test = get_syscall_event_test(__NR_execveat, ENTER_EVENT); evt_test->enable_capture(); @@ -20,7 +19,9 @@ TEST(SyscallEnter, execveatE) const char* newargv = NULL; const char* newenviron = NULL; int flags = AT_SYMLINK_NOFOLLOW; - assert_syscall_state(SYSCALL_FAILURE, "execveat", syscall(__NR_execveat, dirfd, pathname, newargv, newenviron, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "execveat", + syscall(__NR_execveat, dirfd, pathname, newargv, newenviron, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +29,7 @@ TEST(SyscallEnter, execveatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fchdir_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fchdir_e.cpp index c61e067bed..6465c7a812 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fchdir_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fchdir_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchdir -TEST(SyscallEnter, fchdirE) -{ +TEST(SyscallEnter, fchdirE) { auto evt_test = get_syscall_event_test(__NR_fchdir, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallEnter, fchdirE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fchmod_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fchmod_e.cpp index 4e9da8633d..de9d1a05f0 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fchmod_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fchmod_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchmod -TEST(SyscallEnter, fchmodE) -{ +TEST(SyscallEnter, fchmodE) { auto evt_test = get_syscall_event_test(__NR_fchmod, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, fchmodE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fchmodat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fchmodat_e.cpp index d232671548..06a8d11afa 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fchmodat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fchmodat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchmodat -TEST(SyscallEnter, fchmodatE) -{ +TEST(SyscallEnter, fchmodatE) { auto evt_test = get_syscall_event_test(__NR_fchmodat, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, fchmodatE) const char* pathname = NULL; uint32_t mode = 0; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "fchmodat", syscall(__NR_fchmodat, mock_dirfd, pathname, mode, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "fchmodat", + syscall(__NR_fchmodat, mock_dirfd, pathname, mode, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, fchmodatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fchown_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fchown_e.cpp index d5c93a42a5..e4a1cde270 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fchown_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fchown_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchown -TEST(SyscallEnter, fchownE) -{ +TEST(SyscallEnter, fchownE) { auto evt_test = get_syscall_event_test(__NR_fchown, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, fchownE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fchownat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fchownat_e.cpp index 5e877cdaa0..23c5e0ed89 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fchownat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fchownat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchownat -TEST(SyscallEnter, fchownatE) -{ +TEST(SyscallEnter, fchownatE) { auto evt_test = get_syscall_event_test(__NR_fchownat, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, fchownatE) uint32_t uid = 0; uint32_t gid = 0; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "fchownat", syscall(__NR_fchownat, mock_dirfd, pathname, uid, gid, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "fchownat", + syscall(__NR_fchownat, mock_dirfd, pathname, uid, gid, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, fchownatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fcntl_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fcntl_e.cpp index 2e03f66e0c..d228feea4e 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fcntl_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fcntl_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, fcntlE) -{ +TEST(SyscallEnter, fcntlE) { auto evt_test = get_syscall_event_test(__NR_fcntl, ENTER_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallEnter, fcntlE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/finit_module_e.cpp b/test/drivers/test_suites/syscall_enter_suite/finit_module_e.cpp index 16ae41a5c0..5169d68052 100644 --- a/test/drivers/test_suites/syscall_enter_suite/finit_module_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/finit_module_e.cpp @@ -1,7 +1,6 @@ #include "../../event_class/event_class.h" #if defined(__NR_finit_module) -TEST(SyscallEnter, finit_moduleE) -{ +TEST(SyscallEnter, finit_moduleE) { auto evt_test = get_syscall_event_test(__NR_finit_module, ENTER_EVENT); evt_test->enable_capture(); @@ -11,8 +10,9 @@ TEST(SyscallEnter, finit_moduleE) char mock_buf[8]; int mock_flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "finit_module", syscall(__NR_finit_module, mock_fd, (void *)(mock_buf), mock_flags)); - + assert_syscall_state(SYSCALL_FAILURE, + "finit_module", + syscall(__NR_finit_module, mock_fd, (void *)(mock_buf), mock_flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +20,7 @@ TEST(SyscallEnter, finit_moduleE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -36,6 +35,5 @@ TEST(SyscallEnter, finit_moduleE) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); - } #endif diff --git a/test/drivers/test_suites/syscall_enter_suite/flock_e.cpp b/test/drivers/test_suites/syscall_enter_suite/flock_e.cpp index d63c11983b..56e3d5b062 100644 --- a/test/drivers/test_suites/syscall_enter_suite/flock_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/flock_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_flock -TEST(SyscallEnter, flockE) -{ +TEST(SyscallEnter, flockE) { auto evt_test = get_syscall_event_test(__NR_flock, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, flockE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fork_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fork_e.cpp index c48fb9c90b..95cc11b61e 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fork_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fork_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_fork) && defined(__NR_wait4) -TEST(SyscallEnter, forkE) -{ +TEST(SyscallEnter, forkE) { auto evt_test = get_syscall_event_test(__NR_fork, ENTER_EVENT); evt_test->enable_capture(); @@ -10,8 +9,7 @@ TEST(SyscallEnter, forkE) /*=============================== TRIGGER SYSCALL ===========================*/ pid_t ret_pid = syscall(__NR_fork); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -20,7 +18,11 @@ TEST(SyscallEnter, forkE) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +30,7 @@ TEST(SyscallEnter, forkE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fsconfig_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fsconfig_e.cpp index f19f583200..a55c4ef971 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fsconfig_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fsconfig_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_fsconfig) -TEST(SyscallEnter, fsconfigE) -{ +TEST(SyscallEnter, fsconfigE) { auto evt_test = get_syscall_event_test(__NR_fsconfig, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, fsconfigE) const char* key = NULL; const char* value = NULL; int aux = 0; - assert_syscall_state(SYSCALL_FAILURE, "fsconfig", syscall(__NR_fsconfig, fd, cmd, key, value, aux)); + assert_syscall_state(SYSCALL_FAILURE, + "fsconfig", + syscall(__NR_fsconfig, fd, cmd, key, value, aux)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, fsconfigE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/fstat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/fstat_e.cpp index c876693f81..6f3c5b2b59 100644 --- a/test/drivers/test_suites/syscall_enter_suite/fstat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/fstat_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_fstat -TEST(SyscallEnter, fstatE) -{ +TEST(SyscallEnter, fstatE) { auto evt_test = get_syscall_event_test(__NR_fstat, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, fstatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/futex_e.cpp b/test/drivers/test_suites/syscall_enter_suite/futex_e.cpp index 585ce12f2d..f20497e0fd 100644 --- a/test/drivers/test_suites/syscall_enter_suite/futex_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/futex_e.cpp @@ -5,8 +5,7 @@ #include #ifdef __NR_futex -TEST(SyscallEnter, futexE) -{ +TEST(SyscallEnter, futexE) { auto evt_test = get_syscall_event_test(__NR_futex, ENTER_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallEnter, futexE) uint32_t futex_word; int futex_op = FUTEX_PRIVATE_FLAG; uint32_t val = 7; - assert_syscall_state(SYSCALL_FAILURE, "futex", syscall(__NR_futex, &futex_word, futex_op, val, NULL, NULL, 0)); + assert_syscall_state(SYSCALL_FAILURE, + "futex", + syscall(__NR_futex, &futex_word, futex_op, val, NULL, NULL, 0)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallEnter, futexE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/generic_e.cpp b/test/drivers/test_suites/syscall_enter_suite/generic_e.cpp index dee9b70191..e85b0e26e1 100644 --- a/test/drivers/test_suites/syscall_enter_suite/generic_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/generic_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_uname -TEST(SyscallEnter, genericE) -{ +TEST(SyscallEnter, genericE) { /* We use `uname` syscall because it is defined on all architectures * and is a very simple syscall. */ @@ -20,8 +19,7 @@ TEST(SyscallEnter, genericE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getcwd_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getcwd_e.cpp index 5ea623b95e..c7384e0da4 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getcwd_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getcwd_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getcwd -TEST(SyscallEnter, getcwdE) -{ +TEST(SyscallEnter, getcwdE) { auto evt_test = get_syscall_event_test(__NR_getcwd, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, getcwdE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getdents64_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getdents64_e.cpp index 1b92dcb0b8..b9a538b1a9 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getdents64_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getdents64_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getdents64 -TEST(SyscallEnter, getdents64E) -{ +TEST(SyscallEnter, getdents64E) { auto evt_test = get_syscall_event_test(__NR_getdents64, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, getdents64E) int32_t invalid_fd = -1; void* dirp = NULL; int count = 0; - assert_syscall_state(SYSCALL_FAILURE, "getdents64", syscall(__NR_getdents64, invalid_fd, dirp, count)); + assert_syscall_state(SYSCALL_FAILURE, + "getdents64", + syscall(__NR_getdents64, invalid_fd, dirp, count)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, getdents64E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getdents_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getdents_e.cpp index b3571a0ff5..d94cd945d7 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getdents_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getdents_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getdents -TEST(SyscallEnter, getdentsE) -{ +TEST(SyscallEnter, getdentsE) { auto evt_test = get_syscall_event_test(__NR_getdents, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, getdentsE) int32_t invalid_fd = -1; void* dirp = NULL; int count = 0; - assert_syscall_state(SYSCALL_FAILURE, "getdents", syscall(__NR_getdents, invalid_fd, dirp, count)); + assert_syscall_state(SYSCALL_FAILURE, + "getdents", + syscall(__NR_getdents, invalid_fd, dirp, count)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, getdentsE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getegid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getegid_e.cpp index 454949215e..5c7d115c36 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getegid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getegid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getegid -TEST(SyscallEnter, getegidE) -{ +TEST(SyscallEnter, getegidE) { auto evt_test = get_syscall_event_test(__NR_getegid, ENTER_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(SyscallEnter, getegidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/geteuid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/geteuid_e.cpp index 37de5161ae..478b34c82c 100644 --- a/test/drivers/test_suites/syscall_enter_suite/geteuid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/geteuid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_geteuid -TEST(SyscallEnter, geteuidE) -{ +TEST(SyscallEnter, geteuidE) { auto evt_test = get_syscall_event_test(__NR_geteuid, ENTER_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(SyscallEnter, geteuidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getgid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getgid_e.cpp index 2fdbd5a4bc..a178c4ec6c 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getgid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getgid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getgid -TEST(SyscallEnter, getgidE) -{ +TEST(SyscallEnter, getgidE) { auto evt_test = get_syscall_event_test(__NR_getgid, ENTER_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(SyscallEnter, getgidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getpeername_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getpeername_e.cpp index 5f085b6fd9..1f92b23d0b 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getpeername_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getpeername_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getpeername -TEST(SyscallEnter, getpeernameE) -{ +TEST(SyscallEnter, getpeernameE) { auto evt_test = get_syscall_event_test(__NR_getpeername, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, getpeernameE) int32_t mock_fd = -1; void* usockaddr = NULL; int* usockaddr_len = NULL; - assert_syscall_state(SYSCALL_FAILURE, "getpeername", syscall(__NR_getpeername, mock_fd, usockaddr, usockaddr_len)); + assert_syscall_state(SYSCALL_FAILURE, + "getpeername", + syscall(__NR_getpeername, mock_fd, usockaddr, usockaddr_len)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, getpeernameE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getresgid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getresgid_e.cpp index 65bf5c8c00..961a9ed6b7 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getresgid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getresgid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getresgid -TEST(SyscallEnter, getresgidE) -{ +TEST(SyscallEnter, getresgidE) { auto evt_test = get_syscall_event_test(__NR_getresgid, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,11 @@ TEST(SyscallEnter, getresgidE) gid_t rgid; gid_t egid; gid_t sgid; - assert_syscall_state(SYSCALL_SUCCESS, "getresgid", syscall(__NR_getresgid, &rgid, &egid, &sgid), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "getresgid", + syscall(__NR_getresgid, &rgid, &egid, &sgid), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +23,7 @@ TEST(SyscallEnter, getresgidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getresuid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getresuid_e.cpp index f7c1404b6b..1980027597 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getresuid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getresuid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getresuid -TEST(SyscallEnter, getresuidE) -{ +TEST(SyscallEnter, getresuidE) { auto evt_test = get_syscall_event_test(__NR_getresuid, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,11 @@ TEST(SyscallEnter, getresuidE) uid_t ruid; uid_t euid; uid_t suid; - assert_syscall_state(SYSCALL_SUCCESS, "getresuid", syscall(__NR_getresuid, &ruid, &euid, &suid), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "getresuid", + syscall(__NR_getresuid, &ruid, &euid, &suid), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +23,7 @@ TEST(SyscallEnter, getresuidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getrlimit_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getrlimit_e.cpp index 40440deec3..8aed1831e7 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getrlimit_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getrlimit_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, getrlimitE) -{ +TEST(SyscallEnter, getrlimitE) { auto evt_test = get_syscall_event_test(__NR_getrlimit, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, getrlimitE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getsockname_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getsockname_e.cpp index 279b08b1a7..92fef15bcc 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getsockname_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getsockname_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getsockname -TEST(SyscallEnter, getsocknameE) -{ +TEST(SyscallEnter, getsocknameE) { auto evt_test = get_syscall_event_test(__NR_getsockname, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, getsocknameE) int32_t mock_fd = -1; void* usockaddr = NULL; int* usockaddr_len = NULL; - assert_syscall_state(SYSCALL_FAILURE, "getsockname", syscall(__NR_getsockname, mock_fd, usockaddr, usockaddr_len)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockname", + syscall(__NR_getsockname, mock_fd, usockaddr, usockaddr_len)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, getsocknameE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getsockopt_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getsockopt_e.cpp index 185a3346de..f714752de7 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getsockopt_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getsockopt_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, getsockoptE) -{ +TEST(SyscallEnter, getsockoptE) { auto evt_test = get_syscall_event_test(__NR_getsockopt, ENTER_EVENT); evt_test->enable_capture(); @@ -17,7 +16,10 @@ TEST(SyscallEnter, getsockoptE) int option_name = 0; int option_value = 0; socklen_t option_len = 0; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_getsockopt, socket_fd, level, option_name, &option_value, &option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_getsockopt, socket_fd, level, option_name, &option_value, &option_len)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +27,7 @@ TEST(SyscallEnter, getsockoptE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/getuid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/getuid_e.cpp index 3d910d09d1..928dc4fa3a 100644 --- a/test/drivers/test_suites/syscall_enter_suite/getuid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/getuid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getuid -TEST(SyscallEnter, getuidE) -{ +TEST(SyscallEnter, getuidE) { auto evt_test = get_syscall_event_test(__NR_getuid, ENTER_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(SyscallEnter, getuidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/init_module_e.cpp b/test/drivers/test_suites/syscall_enter_suite/init_module_e.cpp index a9ea5f6757..b22b8025ff 100644 --- a/test/drivers/test_suites/syscall_enter_suite/init_module_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/init_module_e.cpp @@ -1,7 +1,6 @@ #include "../../event_class/event_class.h" #if defined(__NR_init_module) -TEST(SyscallEnter, init_moduleE) -{ +TEST(SyscallEnter, init_moduleE) { auto evt_test = get_syscall_event_test(__NR_init_module, ENTER_EVENT); evt_test->enable_capture(); @@ -11,8 +10,9 @@ TEST(SyscallEnter, init_moduleE) unsigned long len = 100; char mock_buf[8]; - assert_syscall_state(SYSCALL_FAILURE, "init_module", syscall(__NR_init_module, (void *)(mock_img), len, (void *)(mock_buf))); - + assert_syscall_state(SYSCALL_FAILURE, + "init_module", + syscall(__NR_init_module, (void *)(mock_img), len, (void *)(mock_buf))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +20,7 @@ TEST(SyscallEnter, init_moduleE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -36,6 +35,5 @@ TEST(SyscallEnter, init_moduleE) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); - } #endif diff --git a/test/drivers/test_suites/syscall_enter_suite/inotify_init1_e.cpp b/test/drivers/test_suites/syscall_enter_suite/inotify_init1_e.cpp index 1fec3e504e..4df2d26938 100644 --- a/test/drivers/test_suites/syscall_enter_suite/inotify_init1_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/inotify_init1_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_inotify_init1) -TEST(SyscallEnter, inotify_init1E_failure) -{ +TEST(SyscallEnter, inotify_init1E_failure) { auto evt_test = get_syscall_event_test(__NR_inotify_init1, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, inotify_init1E_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/inotify_init_e.cpp b/test/drivers/test_suites/syscall_enter_suite/inotify_init_e.cpp index 80215d33d4..51a90baee8 100644 --- a/test/drivers/test_suites/syscall_enter_suite/inotify_init_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/inotify_init_e.cpp @@ -1,9 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_inotify_init) && defined(__NR_close) -TEST(SyscallEnter, inotify_initE) -{ - +TEST(SyscallEnter, inotify_initE) { auto evt_test = get_syscall_event_test(__NR_inotify_init, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +18,7 @@ TEST(SyscallEnter, inotify_initE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/io_uring_enter_e.cpp b/test/drivers/test_suites/syscall_enter_suite/io_uring_enter_e.cpp index 6e9f686807..063d6170d8 100644 --- a/test/drivers/test_suites/syscall_enter_suite/io_uring_enter_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/io_uring_enter_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, io_uring_enterE) -{ +TEST(SyscallEnter, io_uring_enterE) { auto evt_test = get_syscall_event_test(__NR_io_uring_enter, ENTER_EVENT); evt_test->enable_capture(); @@ -18,7 +17,10 @@ TEST(SyscallEnter, io_uring_enterE) uint32_t flags = 0; const void* argp = NULL; size_t argsz = 7; - assert_syscall_state(SYSCALL_FAILURE, "io_uring_enter", syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, argp, argsz)); + assert_syscall_state( + SYSCALL_FAILURE, + "io_uring_enter", + syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, argp, argsz)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -26,8 +28,7 @@ TEST(SyscallEnter, io_uring_enterE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/io_uring_register_e.cpp b/test/drivers/test_suites/syscall_enter_suite/io_uring_register_e.cpp index 0687b8757a..315298960e 100644 --- a/test/drivers/test_suites/syscall_enter_suite/io_uring_register_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/io_uring_register_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, io_uring_registerE) -{ +TEST(SyscallEnter, io_uring_registerE) { auto evt_test = get_syscall_event_test(__NR_io_uring_register, ENTER_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallEnter, io_uring_registerE) uint32_t opcode = 0; const void* arg = NULL; unsigned int nr_args = 7; - assert_syscall_state(SYSCALL_FAILURE, "io_uring_register", syscall(__NR_io_uring_register, fd, opcode, arg, nr_args)); + assert_syscall_state(SYSCALL_FAILURE, + "io_uring_register", + syscall(__NR_io_uring_register, fd, opcode, arg, nr_args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallEnter, io_uring_registerE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/io_uring_setup_e.cpp b/test/drivers/test_suites/syscall_enter_suite/io_uring_setup_e.cpp index d3aca19179..652af409fb 100644 --- a/test/drivers/test_suites/syscall_enter_suite/io_uring_setup_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/io_uring_setup_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, io_uring_setupE) -{ +TEST(SyscallEnter, io_uring_setupE) { auto evt_test = get_syscall_event_test(__NR_io_uring_setup, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, io_uring_setupE) uint32_t entries = 4; struct io_uring_params* params_pointer = NULL; - assert_syscall_state(SYSCALL_FAILURE, "io_uring_setup", syscall(__NR_io_uring_setup, entries, params_pointer)); + assert_syscall_state(SYSCALL_FAILURE, + "io_uring_setup", + syscall(__NR_io_uring_setup, entries, params_pointer)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, io_uring_setupE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/ioctl_e.cpp b/test/drivers/test_suites/syscall_enter_suite/ioctl_e.cpp index 7ddfc41b8e..8d1bc11d81 100644 --- a/test/drivers/test_suites/syscall_enter_suite/ioctl_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/ioctl_e.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallEnter, ioctlE) -{ +TEST(SyscallEnter, ioctlE) { auto evt_test = get_syscall_event_test(__NR_ioctl, ENTER_EVENT); evt_test->enable_capture(); @@ -28,16 +27,12 @@ TEST(SyscallEnter, ioctlE) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_ioctl, mock_fd, request, argp) == -1) - { + if(syscall(__NR_ioctl, mock_fd, request, argp) == -1) { /* SUCCESS because we want the call to fail */ exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -46,10 +41,13 @@ TEST(SyscallEnter, ioctlE) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The ioctl call is successful while it should fail..." << std::endl; } @@ -59,8 +57,7 @@ TEST(SyscallEnter, ioctlE) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/kill_e.cpp b/test/drivers/test_suites/syscall_enter_suite/kill_e.cpp index 454c0807df..f79fabf675 100644 --- a/test/drivers/test_suites/syscall_enter_suite/kill_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/kill_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_kill -TEST(SyscallEnter, killE) -{ +TEST(SyscallEnter, killE) { auto evt_test = get_syscall_event_test(__NR_kill, ENTER_EVENT); evt_test->enable_capture(); @@ -17,7 +16,11 @@ TEST(SyscallEnter, killE) */ int32_t mock_pid = 0; int32_t signal = 0; - assert_syscall_state(SYSCALL_SUCCESS, "kill", syscall(__NR_kill, mock_pid, signal), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "kill", + syscall(__NR_kill, mock_pid, signal), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +28,7 @@ TEST(SyscallEnter, killE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/lchown_e.cpp b/test/drivers/test_suites/syscall_enter_suite/lchown_e.cpp index a354517496..7caae67809 100644 --- a/test/drivers/test_suites/syscall_enter_suite/lchown_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/lchown_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_lchown -TEST(SyscallEnter, lchownE) -{ +TEST(SyscallEnter, lchownE) { auto evt_test = get_syscall_event_test(__NR_lchown, ENTER_EVENT); evt_test->enable_capture(); @@ -17,8 +16,7 @@ TEST(SyscallEnter, lchownE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/link_e.cpp b/test/drivers/test_suites/syscall_enter_suite/link_e.cpp index 146bbb4f36..30964d4a58 100644 --- a/test/drivers/test_suites/syscall_enter_suite/link_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/link_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_link -TEST(SyscallEnter, linkE) -{ +TEST(SyscallEnter, linkE) { auto evt_test = get_syscall_event_test(__NR_link, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, linkE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/linkat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/linkat_e.cpp index 4277d62098..154a97a07a 100644 --- a/test/drivers/test_suites/syscall_enter_suite/linkat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/linkat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_linkat -TEST(SyscallEnter, linkatE) -{ +TEST(SyscallEnter, linkatE) { auto evt_test = get_syscall_event_test(__NR_linkat, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, linkatE) const char* old_path = NULL; const char* new_path = NULL; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "linkat", syscall(__NR_linkat, old_fd, old_path, new_fd, new_path, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "linkat", + syscall(__NR_linkat, old_fd, old_path, new_fd, new_path, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, linkatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/listen_e.cpp b/test/drivers/test_suites/syscall_enter_suite/listen_e.cpp index cf697d6611..56067fe271 100644 --- a/test/drivers/test_suites/syscall_enter_suite/listen_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/listen_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_listen -TEST(SyscallEnter, listenE) -{ +TEST(SyscallEnter, listenE) { auto evt_test = get_syscall_event_test(__NR_listen, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, listenE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/llseek_e.cpp b/test/drivers/test_suites/syscall_enter_suite/llseek_e.cpp index 550d87f831..14676793d9 100644 --- a/test/drivers/test_suites/syscall_enter_suite/llseek_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/llseek_e.cpp @@ -3,8 +3,7 @@ #include #ifdef __NR_llseek -TEST(SyscallEnter, llseekE) -{ +TEST(SyscallEnter, llseekE) { auto evt_test = get_syscall_event_test(__NR_llseek, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, llseekE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/lseek_e.cpp b/test/drivers/test_suites/syscall_enter_suite/lseek_e.cpp index be800c4ce2..5cff7009d4 100644 --- a/test/drivers/test_suites/syscall_enter_suite/lseek_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/lseek_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_lseek -TEST(SyscallEnter, lseekE) -{ +TEST(SyscallEnter, lseekE) { auto evt_test = get_syscall_event_test(__NR_lseek, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, lseekE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/lstat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/lstat_e.cpp index ddb4acfccb..e53c1dc196 100644 --- a/test/drivers/test_suites/syscall_enter_suite/lstat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/lstat_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_lstat -TEST(SyscallEnter, lstatE) -{ +TEST(SyscallEnter, lstatE) { auto evt_test = get_syscall_event_test(__NR_lstat, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, lstatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -31,7 +29,6 @@ TEST(SyscallEnter, lstatE) /*=============================== ASSERT PARAMETERS ===========================*/ - /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); diff --git a/test/drivers/test_suites/syscall_enter_suite/memfd_create_e.cpp b/test/drivers/test_suites/syscall_enter_suite/memfd_create_e.cpp index 7c8aefe63b..1a63969509 100644 --- a/test/drivers/test_suites/syscall_enter_suite/memfd_create_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/memfd_create_e.cpp @@ -4,38 +4,35 @@ #ifdef __NR_memfd_create -TEST(SyscallEnter, memfd_createE) -{ - auto evt_test = get_syscall_event_test(__NR_memfd_create,ENTER_EVENT); +TEST(SyscallEnter, memfd_createE) { + auto evt_test = get_syscall_event_test(__NR_memfd_create, ENTER_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - const char* name = NULL; - unsigned int flags = 0; - assert_syscall_state(SYSCALL_FAILURE,"memfd_create",syscall(__NR_memfd_create,name,flags)); + const char* name = NULL; + unsigned int flags = 0; + assert_syscall_state(SYSCALL_FAILURE, "memfd_create", syscall(__NR_memfd_create, name, flags)); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_enter_suite/mkdir_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mkdir_e.cpp index a6ea75ccf4..a922928c54 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mkdir_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mkdir_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_mkdir -TEST(SyscallEnter, mkdirE) -{ +TEST(SyscallEnter, mkdirE) { auto evt_test = get_syscall_event_test(__NR_mkdir, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, mkdirE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/mkdirat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mkdirat_e.cpp index a3940658f4..b5725d7c91 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mkdirat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mkdirat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_mkdirat -TEST(SyscallEnter, mkdiratE) -{ +TEST(SyscallEnter, mkdiratE) { auto evt_test = get_syscall_event_test(__NR_mkdirat, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, mkdiratE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/mlock2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mlock2_e.cpp index a60b6aaa2a..c3bdb7b627 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mlock2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mlock2_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, mlock2E) -{ +TEST(SyscallEnter, mlock2E) { auto evt_test = get_syscall_event_test(__NR_mlock2, ENTER_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallEnter, mlock2E) void *mock_addr = (void *)0; size_t mock_len = 4096; int mock_flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "mlock2", syscall(__NR_mlock2, mock_addr, mock_len, mock_flags)); + assert_syscall_state(SYSCALL_FAILURE, + "mlock2", + syscall(__NR_mlock2, mock_addr, mock_len, mock_flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallEnter, mlock2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/mlock_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mlock_e.cpp index e865b10fab..811db8ca91 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mlock_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mlock_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, mlockE) -{ +TEST(SyscallEnter, mlockE) { auto evt_test = get_syscall_event_test(__NR_mlock, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, mlockE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/mlockall_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mlockall_e.cpp index bfddde5f15..682219f22d 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mlockall_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mlockall_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, mlockallE) -{ +TEST(SyscallEnter, mlockallE) { auto evt_test = get_syscall_event_test(__NR_mlockall, ENTER_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallEnter, mlockallE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/mmap2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mmap2_e.cpp index 0801e88630..251add5181 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mmap2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mmap2_e.cpp @@ -5,8 +5,7 @@ #include -TEST(SyscallEnter, mmap2E) -{ +TEST(SyscallEnter, mmap2E) { auto evt_test = get_syscall_event_test(__NR_mmap2, ENTER_EVENT); evt_test->enable_capture(); @@ -20,7 +19,15 @@ TEST(SyscallEnter, mmap2E) int mock_fd = -1; off_t mock_offset = 1023; - assert_syscall_state(SYSCALL_FAILURE, "mmap2", syscall(__NR_mmap2, mock_addr, mock_length, mock_prot, mock_flags, mock_fd, mock_offset)); + assert_syscall_state(SYSCALL_FAILURE, + "mmap2", + syscall(__NR_mmap2, + mock_addr, + mock_length, + mock_prot, + mock_flags, + mock_fd, + mock_offset)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +35,7 @@ TEST(SyscallEnter, mmap2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/mmap_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mmap_e.cpp index 27f974a992..70e726ad8b 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mmap_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mmap_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, mmapE) -{ +TEST(SyscallEnter, mmapE) { auto evt_test = get_syscall_event_test(__NR_mmap, ENTER_EVENT); evt_test->enable_capture(); @@ -19,7 +18,15 @@ TEST(SyscallEnter, mmapE) int mock_fd = -1; off_t mock_offset = 1023; - assert_syscall_state(SYSCALL_FAILURE, "mmap", syscall(__NR_mmap, mock_addr, mock_length, mock_prot, mock_flags, mock_fd, mock_offset)); + assert_syscall_state(SYSCALL_FAILURE, + "mmap", + syscall(__NR_mmap, + mock_addr, + mock_length, + mock_prot, + mock_flags, + mock_fd, + mock_offset)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -27,8 +34,7 @@ TEST(SyscallEnter, mmapE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -52,7 +58,7 @@ TEST(SyscallEnter, mmapE) /* Parameter 5: fd (type: PT_FD) */ evt_test->assert_numeric_param(5, (int64_t)mock_fd); - + /* Parameter 6: offset (type: PT_UINT64) */ evt_test->assert_numeric_param(6, (uint64_t)mock_offset); diff --git a/test/drivers/test_suites/syscall_enter_suite/mount_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mount_e.cpp index 15746d6850..40d8d90a50 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mount_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mount_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, mountE) -{ +TEST(SyscallEnter, mountE) { auto evt_test = get_syscall_event_test(__NR_mount, ENTER_EVENT); evt_test->enable_capture(); @@ -17,7 +16,9 @@ TEST(SyscallEnter, mountE) const char* filesystemtype = "not_supported"; unsigned long flags = MS_MGC_VAL | MS_RDONLY; const void* data = NULL; - assert_syscall_state(SYSCALL_FAILURE, "mount", syscall(__NR_mount, source, target, filesystemtype, flags, data)); + assert_syscall_state(SYSCALL_FAILURE, + "mount", + syscall(__NR_mount, source, target, filesystemtype, flags, data)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallEnter, mountE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/mprotect_e.cpp b/test/drivers/test_suites/syscall_enter_suite/mprotect_e.cpp index f133fa99cd..487cf1f039 100644 --- a/test/drivers/test_suites/syscall_enter_suite/mprotect_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/mprotect_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, mprotectE) -{ +TEST(SyscallEnter, mprotectE) { auto evt_test = get_syscall_event_test(__NR_mprotect, ENTER_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallEnter, mprotectE) void *mock_addr = (void *)0; size_t mock_size = 4096; int mock_prot = PROT_READ | PROT_EXEC; - assert_syscall_state(SYSCALL_FAILURE, "mprotect", syscall(__NR_mprotect, mock_addr, mock_size, mock_prot)); + assert_syscall_state(SYSCALL_FAILURE, + "mprotect", + syscall(__NR_mprotect, mock_addr, mock_size, mock_prot)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallEnter, mprotectE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/munlock_e.cpp b/test/drivers/test_suites/syscall_enter_suite/munlock_e.cpp index 7e9b9c2df4..486e3c0aac 100644 --- a/test/drivers/test_suites/syscall_enter_suite/munlock_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/munlock_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, munlockE) -{ +TEST(SyscallEnter, munlockE) { auto evt_test = get_syscall_event_test(__NR_munlock, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, munlockE) unsigned long mock_addr = 1; size_t mock_len{1024}; - assert_syscall_state(SYSCALL_FAILURE, "munlock", syscall(__NR_munlock, (void *)mock_addr, mock_len)); + assert_syscall_state(SYSCALL_FAILURE, + "munlock", + syscall(__NR_munlock, (void *)mock_addr, mock_len)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, munlockE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/munlockall_e.cpp b/test/drivers/test_suites/syscall_enter_suite/munlockall_e.cpp index 81f7a45483..524e30dc22 100644 --- a/test/drivers/test_suites/syscall_enter_suite/munlockall_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/munlockall_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, munlockallE) -{ +TEST(SyscallEnter, munlockallE) { auto evt_test = get_syscall_event_test(__NR_munlockall, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, munlockallE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/munmap_e.cpp b/test/drivers/test_suites/syscall_enter_suite/munmap_e.cpp index 9663184ad0..ff6424eeb2 100644 --- a/test/drivers/test_suites/syscall_enter_suite/munmap_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/munmap_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, munmapE) -{ +TEST(SyscallEnter, munmapE) { auto evt_test = get_syscall_event_test(__NR_munmap, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, munmapE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/nanosleep_e.cpp b/test/drivers/test_suites/syscall_enter_suite/nanosleep_e.cpp index 9f37302a7a..68347c0c7d 100644 --- a/test/drivers/test_suites/syscall_enter_suite/nanosleep_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/nanosleep_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_nanosleep -TEST(SyscallEnter, nanosleepE) -{ +TEST(SyscallEnter, nanosleepE) { auto evt_test = get_syscall_event_test(__NR_nanosleep, ENTER_EVENT); evt_test->enable_capture(); @@ -10,7 +9,11 @@ TEST(SyscallEnter, nanosleepE) /*=============================== TRIGGER SYSCALL ===========================*/ const struct timespec req = {.tv_sec = 0, .tv_nsec = 3}; - assert_syscall_state(SYSCALL_SUCCESS, "nanosleep", syscall(__NR_nanosleep, &req, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "nanosleep", + syscall(__NR_nanosleep, &req, NULL), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -18,8 +21,7 @@ TEST(SyscallEnter, nanosleepE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -37,8 +39,7 @@ TEST(SyscallEnter, nanosleepE) evt_test->assert_num_params_pushed(1); } -TEST(SyscallEnter, nanosleepE_fail) -{ +TEST(SyscallEnter, nanosleepE_fail) { auto evt_test = get_syscall_event_test(__NR_nanosleep, ENTER_EVENT); evt_test->enable_capture(); @@ -53,8 +54,7 @@ TEST(SyscallEnter, nanosleepE_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/newfstatat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/newfstatat_e.cpp index 4e5c285998..b347592b84 100644 --- a/test/drivers/test_suites/syscall_enter_suite/newfstatat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/newfstatat_e.cpp @@ -1,21 +1,21 @@ #include "../../event_class/event_class.h" #ifdef __NR_newfstatat -TEST(SyscallEnter, newfstatatE) -{ +TEST(SyscallEnter, newfstatatE) { auto evt_test = get_syscall_event_test(__NR_newfstatat, ENTER_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - //int dirfd = AT_FDCWD; + // int dirfd = AT_FDCWD; int dirfd = -1; const char* pathname = "mock_path"; struct stat buffer; int flags = AT_EMPTY_PATH | AT_NO_AUTOMOUNT | AT_SYMLINK_NOFOLLOW; - assert_syscall_state(SYSCALL_FAILURE, "newfstatat", syscall(__NR_newfstatat, dirfd, pathname, &buffer, flags)); - + assert_syscall_state(SYSCALL_FAILURE, + "newfstatat", + syscall(__NR_newfstatat, dirfd, pathname, &buffer, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +23,7 @@ TEST(SyscallEnter, newfstatatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -39,6 +38,5 @@ TEST(SyscallEnter, newfstatatE) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); - } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_enter_suite/open_by_handle_at_e.cpp b/test/drivers/test_suites/syscall_enter_suite/open_by_handle_at_e.cpp index 41076aea5b..3b83d879bc 100644 --- a/test/drivers/test_suites/syscall_enter_suite/open_by_handle_at_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/open_by_handle_at_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_open_by_handle_at -TEST(SyscallEnter, open_by_handle_atE) -{ +TEST(SyscallEnter, open_by_handle_atE) { auto evt_test = get_syscall_event_test(__NR_open_by_handle_at, ENTER_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallEnter, open_by_handle_atE) int mount_fd = -1; struct file_handle *fhp = NULL; int flags = O_RDWR; - assert_syscall_state(SYSCALL_FAILURE, "open_by_handle_at", syscall(__NR_open_by_handle_at, mount_fd, fhp, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "open_by_handle_at", + syscall(__NR_open_by_handle_at, mount_fd, fhp, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallEnter, open_by_handle_atE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { /* This could happen if: * - the syscall result state is different from the expected one. * - we are not able to find the event in the ring buffers. diff --git a/test/drivers/test_suites/syscall_enter_suite/open_e.cpp b/test/drivers/test_suites/syscall_enter_suite/open_e.cpp index 28362a167b..03a48f9059 100644 --- a/test/drivers/test_suites/syscall_enter_suite/open_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/open_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_open -TEST(SyscallEnter, openE) -{ +TEST(SyscallEnter, openE) { auto evt_test = get_syscall_event_test(__NR_open, ENTER_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallEnter, openE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -49,8 +47,7 @@ TEST(SyscallEnter, openE) evt_test->assert_num_params_pushed(3); } -TEST(SyscallEnter, openE_max_path) -{ +TEST(SyscallEnter, openE_max_path) { auto evt_test = get_syscall_event_test(__NR_open, ENTER_EVENT); evt_test->enable_capture(); @@ -65,7 +62,9 @@ TEST(SyscallEnter, openE_max_path) pathname.insert(0, PPM_MAX_PATH_SIZE - 1, 'A'); int flags = O_RDWR | O_TMPFILE | O_DIRECTORY; mode_t mode = 0; - assert_syscall_state(SYSCALL_FAILURE, "open", syscall(__NR_open, pathname.c_str(), flags, mode)); + assert_syscall_state(SYSCALL_FAILURE, + "open", + syscall(__NR_open, pathname.c_str(), flags, mode)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -73,8 +72,7 @@ TEST(SyscallEnter, openE_max_path) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/openat2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/openat2_e.cpp index 1045cb14e1..a1adf0b8b5 100644 --- a/test/drivers/test_suites/syscall_enter_suite/openat2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/openat2_e.cpp @@ -4,8 +4,7 @@ #include /* Definition of RESOLVE_* constants */ -TEST(SyscallEnter, openat2E) -{ +TEST(SyscallEnter, openat2E) { auto evt_test = get_syscall_event_test(__NR_openat2, ENTER_EVENT); evt_test->enable_capture(); @@ -23,7 +22,9 @@ TEST(SyscallEnter, openat2E) how.flags = O_RDWR | O_TMPFILE | O_DIRECTORY; how.mode = 0; how.resolve = RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS; - assert_syscall_state(SYSCALL_FAILURE, "openat2", syscall(__NR_openat2, dirfd, pathname, &how, sizeof(struct open_how))); + assert_syscall_state(SYSCALL_FAILURE, + "openat2", + syscall(__NR_openat2, dirfd, pathname, &how, sizeof(struct open_how))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -31,8 +32,7 @@ TEST(SyscallEnter, openat2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -62,8 +62,7 @@ TEST(SyscallEnter, openat2E) evt_test->assert_num_params_pushed(5); } -TEST(SyscallEnter, openat2E_max_path) -{ +TEST(SyscallEnter, openat2E_max_path) { auto evt_test = get_syscall_event_test(__NR_openat2, ENTER_EVENT); evt_test->enable_capture(); @@ -82,7 +81,10 @@ TEST(SyscallEnter, openat2E_max_path) how.flags = O_RDWR | O_TMPFILE | O_DIRECTORY; how.mode = 0; how.resolve = RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS; - assert_syscall_state(SYSCALL_FAILURE, "openat2", syscall(__NR_openat2, dirfd, pathname.c_str(), &how, sizeof(struct open_how))); + assert_syscall_state( + SYSCALL_FAILURE, + "openat2", + syscall(__NR_openat2, dirfd, pathname.c_str(), &how, sizeof(struct open_how))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -90,8 +92,7 @@ TEST(SyscallEnter, openat2E_max_path) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/openat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/openat_e.cpp index cc8a7fa734..02bc9e2e24 100644 --- a/test/drivers/test_suites/syscall_enter_suite/openat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/openat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_openat -TEST(SyscallEnter, openatE) -{ +TEST(SyscallEnter, openatE) { auto evt_test = get_syscall_event_test(__NR_openat, ENTER_EVENT); evt_test->enable_capture(); @@ -18,7 +17,9 @@ TEST(SyscallEnter, openatE) const char* pathname = "mock_path"; int flags = O_RDWR | O_TMPFILE | O_DIRECTORY; mode_t mode = 0; - assert_syscall_state(SYSCALL_FAILURE, "openat", syscall(__NR_openat, dirfd, pathname, flags, mode)); + assert_syscall_state(SYSCALL_FAILURE, + "openat", + syscall(__NR_openat, dirfd, pathname, flags, mode)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -26,8 +27,7 @@ TEST(SyscallEnter, openatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -54,8 +54,7 @@ TEST(SyscallEnter, openatE) evt_test->assert_num_params_pushed(4); } -TEST(SyscallEnter, openatE_max_path) -{ +TEST(SyscallEnter, openatE_max_path) { auto evt_test = get_syscall_event_test(__NR_openat, ENTER_EVENT); evt_test->enable_capture(); @@ -72,7 +71,9 @@ TEST(SyscallEnter, openatE_max_path) pathname.insert(0, PPM_MAX_PATH_SIZE - 1, 'A'); int flags = O_RDWR | O_TMPFILE | O_DIRECTORY; mode_t mode = 0; - assert_syscall_state(SYSCALL_FAILURE, "openat", syscall(__NR_openat, dirfd, pathname.c_str(), flags, mode)); + assert_syscall_state(SYSCALL_FAILURE, + "openat", + syscall(__NR_openat, dirfd, pathname.c_str(), flags, mode)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -80,8 +81,7 @@ TEST(SyscallEnter, openatE_max_path) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/pidfd_getfd_e.cpp b/test/drivers/test_suites/syscall_enter_suite/pidfd_getfd_e.cpp index 969330fdee..265d940404 100644 --- a/test/drivers/test_suites/syscall_enter_suite/pidfd_getfd_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/pidfd_getfd_e.cpp @@ -2,38 +2,38 @@ #ifdef __NR_pidfd_getfd -TEST(SyscallEnter, pidfd_getfdE) -{ - auto evt_test = get_syscall_event_test(__NR_pidfd_getfd, ENTER_EVENT); +TEST(SyscallEnter, pidfd_getfdE) { + auto evt_test = get_syscall_event_test(__NR_pidfd_getfd, ENTER_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - int pidfd = 0; - int targetfd = 0; - int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "pidfd_getfd", syscall(__NR_pidfd_getfd, pidfd, targetfd, flags)); + int pidfd = 0; + int targetfd = 0; + int flags = 0; + assert_syscall_state(SYSCALL_FAILURE, + "pidfd_getfd", + syscall(__NR_pidfd_getfd, pidfd, targetfd, flags)); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_enter_suite/pidfd_open_e.cpp b/test/drivers/test_suites/syscall_enter_suite/pidfd_open_e.cpp index 9712a8f844..f6098d5320 100644 --- a/test/drivers/test_suites/syscall_enter_suite/pidfd_open_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/pidfd_open_e.cpp @@ -3,37 +3,35 @@ #ifdef __NR_pidfd_open -TEST(SyscallEnter, pidfd_openE) -{ - auto evt_test = get_syscall_event_test(__NR_pidfd_open, ENTER_EVENT); +TEST(SyscallEnter, pidfd_openE) { + auto evt_test = get_syscall_event_test(__NR_pidfd_open, ENTER_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - int pid = 0; - int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "pidfd_open", syscall(__NR_pidfd_open, pid, flags)); + int pid = 0; + int flags = 0; + assert_syscall_state(SYSCALL_FAILURE, "pidfd_open", syscall(__NR_pidfd_open, pid, flags)); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_enter_suite/pipe2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/pipe2_e.cpp index 1db9d58515..9483e581fa 100644 --- a/test/drivers/test_suites/syscall_enter_suite/pipe2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/pipe2_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_pipe2 -TEST(SyscallEnter, pipe2E) -{ +TEST(SyscallEnter, pipe2E) { auto evt_test = get_syscall_event_test(__NR_pipe2, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, pipe2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/pipe_e.cpp b/test/drivers/test_suites/syscall_enter_suite/pipe_e.cpp index 28ec74ba8c..5ded2086f9 100644 --- a/test/drivers/test_suites/syscall_enter_suite/pipe_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/pipe_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_pipe -TEST(SyscallEnter, pipeE) -{ +TEST(SyscallEnter, pipeE) { auto evt_test = get_syscall_event_test(__NR_pipe, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallEnter, pipeE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/poll_e.cpp b/test/drivers/test_suites/syscall_enter_suite/poll_e.cpp index b2af37f331..4277d962b9 100644 --- a/test/drivers/test_suites/syscall_enter_suite/poll_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/poll_e.cpp @@ -6,8 +6,7 @@ /* Right now this is our limit in the drivers */ #define MAX_FDS 16 -TEST(SyscallEnter, pollE_null_pointer) -{ +TEST(SyscallEnter, pollE_null_pointer) { auto evt_test = get_syscall_event_test(__NR_poll, ENTER_EVENT); evt_test->enable_capture(); @@ -25,8 +24,7 @@ TEST(SyscallEnter, pollE_null_pointer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -48,8 +46,7 @@ TEST(SyscallEnter, pollE_null_pointer) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, pollE_empty_nfds) -{ +TEST(SyscallEnter, pollE_empty_nfds) { auto evt_test = get_syscall_event_test(__NR_poll, ENTER_EVENT); evt_test->enable_capture(); @@ -69,7 +66,11 @@ TEST(SyscallEnter, pollE_empty_nfds) /* We send it empty so expect no fd in the structs to be collected */ uint32_t nfds = 0; int timeout = 0; - assert_syscall_state(SYSCALL_SUCCESS, "poll", syscall(__NR_poll, fds, nfds, timeout), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "poll", + syscall(__NR_poll, fds, nfds, timeout), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -77,8 +78,7 @@ TEST(SyscallEnter, pollE_empty_nfds) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -100,8 +100,7 @@ TEST(SyscallEnter, pollE_empty_nfds) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, pollE_not_truncated) -{ +TEST(SyscallEnter, pollE_not_truncated) { auto evt_test = get_syscall_event_test(__NR_poll, ENTER_EVENT); evt_test->enable_capture(); @@ -111,7 +110,8 @@ TEST(SyscallEnter, pollE_not_truncated) struct pollfd fds[2]; fds[0].fd = -1; - fds[0].events = POLLIN | POLLPRI | POLLOUT | POLLRDHUP | POLLERR | POLLHUP | POLLNVAL | POLLRDNORM | POLLRDBAND | POLLWRNORM | POLLWRBAND; + fds[0].events = POLLIN | POLLPRI | POLLOUT | POLLRDHUP | POLLERR | POLLHUP | POLLNVAL | + POLLRDNORM | POLLRDBAND | POLLWRNORM | POLLWRBAND; fds[0].revents = 0; fds[1].fd = -10; @@ -125,12 +125,18 @@ TEST(SyscallEnter, pollE_not_truncated) struct fd_poll expected[2]; expected[0].fd = fds[0].fd; - expected[0].flags = PPM_POLLIN | PPM_POLLPRI | PPM_POLLOUT | PPM_POLLRDHUP | PPM_POLLERR | PPM_POLLHUP | PPM_POLLNVAL | PPM_POLLRDNORM | PPM_POLLRDBAND | PPM_POLLWRNORM | PPM_POLLWRBAND; + expected[0].flags = PPM_POLLIN | PPM_POLLPRI | PPM_POLLOUT | PPM_POLLRDHUP | PPM_POLLERR | + PPM_POLLHUP | PPM_POLLNVAL | PPM_POLLRDNORM | PPM_POLLRDBAND | + PPM_POLLWRNORM | PPM_POLLWRBAND; expected[1].fd = fds[1].fd; expected[1].flags = PPM_POLLWRBAND; - assert_syscall_state(SYSCALL_SUCCESS, "poll", syscall(__NR_poll, fds, nfds, timeout), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "poll", + syscall(__NR_poll, fds, nfds, timeout), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -138,8 +144,7 @@ TEST(SyscallEnter, pollE_not_truncated) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -160,13 +165,12 @@ TEST(SyscallEnter, pollE_not_truncated) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, pollE_truncated) -{ +TEST(SyscallEnter, pollE_truncated) { auto evt_test = get_syscall_event_test(__NR_poll, ENTER_EVENT); - if(evt_test->is_kmod_engine()) - { - GTEST_SKIP() << "[POLL_E]: the kmod is not subject to params truncation like BPF drivers" << std::endl; + if(evt_test->is_kmod_engine()) { + GTEST_SKIP() << "[POLL_E]: the kmod is not subject to params truncation like BPF drivers" + << std::endl; } evt_test->enable_capture(); @@ -181,7 +185,11 @@ TEST(SyscallEnter, pollE_truncated) /* We expect only `MAX_FDS` structs */ struct fd_poll expected[MAX_FDS] = {}; - assert_syscall_state(SYSCALL_SUCCESS, "poll", syscall(__NR_poll, fds, nfds, timeout), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "poll", + syscall(__NR_poll, fds, nfds, timeout), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -189,8 +197,7 @@ TEST(SyscallEnter, pollE_truncated) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/ppoll_e.cpp b/test/drivers/test_suites/syscall_enter_suite/ppoll_e.cpp index 45f48089c0..572326b8e6 100644 --- a/test/drivers/test_suites/syscall_enter_suite/ppoll_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/ppoll_e.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallEnter, ppollE_null_pointers) -{ +TEST(SyscallEnter, ppollE_null_pointers) { auto evt_test = get_syscall_event_test(__NR_ppoll, ENTER_EVENT); evt_test->enable_capture(); @@ -20,7 +19,9 @@ TEST(SyscallEnter, ppollE_null_pointers) struct timespec* timestamp = NULL; sigset_t* sigmask = NULL; uint32_t nfds = 5; - assert_syscall_state(SYSCALL_FAILURE, "ppoll", syscall(__NR_ppoll, fds, nfds, timestamp, sigmask)); + assert_syscall_state(SYSCALL_FAILURE, + "ppoll", + syscall(__NR_ppoll, fds, nfds, timestamp, sigmask)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +29,7 @@ TEST(SyscallEnter, ppollE_null_pointers) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -56,8 +56,7 @@ TEST(SyscallEnter, ppollE_null_pointers) evt_test->assert_num_params_pushed(3); } -TEST(SyscallEnter, ppollE_valid_pointers) -{ +TEST(SyscallEnter, ppollE_valid_pointers) { auto evt_test = get_syscall_event_test(__NR_ppoll, ENTER_EVENT); evt_test->enable_capture(); @@ -75,7 +74,9 @@ TEST(SyscallEnter, ppollE_valid_pointers) sigmask.__val[0] = SIGIO; sigmask.__val[1] = SIGTERM; uint32_t nfds = 5; - assert_syscall_state(SYSCALL_FAILURE, "ppoll", syscall(__NR_ppoll, fds, nfds, ×tamp, &sigmask)); + assert_syscall_state(SYSCALL_FAILURE, + "ppoll", + syscall(__NR_ppoll, fds, nfds, ×tamp, &sigmask)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -83,8 +84,7 @@ TEST(SyscallEnter, ppollE_valid_pointers) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -100,7 +100,8 @@ TEST(SyscallEnter, ppollE_valid_pointers) /* Parameter 2: timeout (type: PT_RELTIME) */ /* The pointer is NULL so we should have UINT64_MAX */ - evt_test->assert_numeric_param(2, ((uint64_t)timestamp.tv_sec * SEC_FACTOR) + timestamp.tv_nsec); + evt_test->assert_numeric_param(2, + ((uint64_t)timestamp.tv_sec * SEC_FACTOR) + timestamp.tv_nsec); /* Parameter 3: sigmask (type: PT_SIGSET) */ evt_test->assert_numeric_param(3, (uint32_t)SIGIO); diff --git a/test/drivers/test_suites/syscall_enter_suite/prctl_e.cpp b/test/drivers/test_suites/syscall_enter_suite/prctl_e.cpp index 3deb44b83e..3413d57ba4 100644 --- a/test/drivers/test_suites/syscall_enter_suite/prctl_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/prctl_e.cpp @@ -1,7 +1,6 @@ #include "../../event_class/event_class.h" #if defined(__NR_prctl) -TEST(SyscallEnter, prctlE) -{ +TEST(SyscallEnter, prctlE) { auto evt_test = get_syscall_event_test(__NR_prctl, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, prctlE) unsigned long arg4 = 0; unsigned long arg5 = 0; - assert_syscall_state(SYSCALL_SUCCESS, "prctl", syscall(__NR_prctl, option, arg2, arg3, arg4, arg5)); + assert_syscall_state(SYSCALL_SUCCESS, + "prctl", + syscall(__NR_prctl, option, arg2, arg3, arg4, arg5)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, prctlE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -37,6 +37,5 @@ TEST(SyscallEnter, prctlE) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); - } #endif diff --git a/test/drivers/test_suites/syscall_enter_suite/pread64_e.cpp b/test/drivers/test_suites/syscall_enter_suite/pread64_e.cpp index 6914f34a42..d722a60740 100644 --- a/test/drivers/test_suites/syscall_enter_suite/pread64_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/pread64_e.cpp @@ -3,8 +3,7 @@ #ifdef __NR_pread64 -TEST(SyscallEnter, preadE) -{ +TEST(SyscallEnter, preadE) { auto evt_test = get_syscall_event_test(__NR_pread64, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, preadE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/preadv_e.cpp b/test/drivers/test_suites/syscall_enter_suite/preadv_e.cpp index 24e757f478..7ae2024e76 100644 --- a/test/drivers/test_suites/syscall_enter_suite/preadv_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/preadv_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_preadv -TEST(SyscallEnter, preadvE) -{ +TEST(SyscallEnter, preadvE) { auto evt_test = get_syscall_event_test(__NR_preadv, ENTER_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallEnter, preadvE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/prlimit64_e.cpp b/test/drivers/test_suites/syscall_enter_suite/prlimit64_e.cpp index 174843839c..f2680438d9 100644 --- a/test/drivers/test_suites/syscall_enter_suite/prlimit64_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/prlimit64_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, prlimit64E) -{ +TEST(SyscallEnter, prlimit64E) { auto evt_test = get_syscall_event_test(__NR_prlimit64, ENTER_EVENT); evt_test->enable_capture(); @@ -17,7 +16,9 @@ TEST(SyscallEnter, prlimit64E) /* We need to put the pid to `-1` otherwise the syscall won't fail on some machines. */ pid_t pid = -1; int resource = RLIMIT_NOFILE; - assert_syscall_state(SYSCALL_FAILURE, "prlimit64", syscall(__NR_prlimit64, pid, resource, &new_rlimit, &old_rlimit)); + assert_syscall_state(SYSCALL_FAILURE, + "prlimit64", + syscall(__NR_prlimit64, pid, resource, &new_rlimit, &old_rlimit)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallEnter, prlimit64E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/ptrace_e.cpp b/test/drivers/test_suites/syscall_enter_suite/ptrace_e.cpp index a7f0edaf6c..942a00c9ce 100644 --- a/test/drivers/test_suites/syscall_enter_suite/ptrace_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/ptrace_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, ptraceE) -{ +TEST(SyscallEnter, ptraceE) { auto evt_test = get_syscall_event_test(__NR_ptrace, ENTER_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallEnter, ptraceE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/pwrite64_e.cpp b/test/drivers/test_suites/syscall_enter_suite/pwrite64_e.cpp index 8079da2d32..e11c5777b0 100644 --- a/test/drivers/test_suites/syscall_enter_suite/pwrite64_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/pwrite64_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_pwrite64 -TEST(SyscallEnter, pwrite64E) -{ +TEST(SyscallEnter, pwrite64E) { auto evt_test = get_syscall_event_test(__NR_pwrite64, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, pwrite64E) char* mock_buf = NULL; size_t mock_count = 4096; off_t off = 16; - assert_syscall_state(SYSCALL_FAILURE, "pwrite64", syscall(__NR_pwrite64, mock_fd, (void*)(mock_buf), mock_count, off)); + assert_syscall_state(SYSCALL_FAILURE, + "pwrite64", + syscall(__NR_pwrite64, mock_fd, (void*)(mock_buf), mock_count, off)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, pwrite64E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/pwritev_e.cpp b/test/drivers/test_suites/syscall_enter_suite/pwritev_e.cpp index d23cdc2959..bdfa94da8a 100644 --- a/test/drivers/test_suites/syscall_enter_suite/pwritev_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/pwritev_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_pwritev -TEST(SyscallEnter, pwritevE_empty_iovec) -{ +TEST(SyscallEnter, pwritevE_empty_iovec) { auto evt_test = get_syscall_event_test(__NR_pwritev, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, pwritevE_empty_iovec) iovec* iov = NULL; int32_t iovcnt = 7; off_t off = 29; - assert_syscall_state(SYSCALL_FAILURE, "pwritev", syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); + assert_syscall_state(SYSCALL_FAILURE, + "pwritev", + syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, pwritevE_empty_iovec) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -47,8 +47,7 @@ TEST(SyscallEnter, pwritevE_empty_iovec) evt_test->assert_num_params_pushed(3); } -TEST(SyscallEnter, pwritevE_full_iovec) -{ +TEST(SyscallEnter, pwritevE_full_iovec) { auto evt_test = get_syscall_event_test(__NR_pwritev, ENTER_EVENT); evt_test->enable_capture(); @@ -62,7 +61,9 @@ TEST(SyscallEnter, pwritevE_full_iovec) iov[1].iov_len = DEFAULT_SNAPLEN + 1; int32_t iovcnt = 2; off_t off = 0; - assert_syscall_state(SYSCALL_FAILURE, "pwritev", syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); + assert_syscall_state(SYSCALL_FAILURE, + "pwritev", + syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -70,8 +71,7 @@ TEST(SyscallEnter, pwritevE_full_iovec) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/quotactl_e.cpp b/test/drivers/test_suites/syscall_enter_suite/quotactl_e.cpp index c618034a93..7c325f8c4a 100644 --- a/test/drivers/test_suites/syscall_enter_suite/quotactl_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/quotactl_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, quotactlE) -{ +TEST(SyscallEnter, quotactlE) { auto evt_test = get_syscall_event_test(__NR_quotactl, ENTER_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallEnter, quotactlE) const char* special = "/dev//*null"; int id = 1; struct if_dqblk addr = {}; - assert_syscall_state(SYSCALL_FAILURE, "quotactl", syscall(__NR_quotactl, cmd, special, id, &addr)); + assert_syscall_state(SYSCALL_FAILURE, + "quotactl", + syscall(__NR_quotactl, cmd, special, id, &addr)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallEnter, quotactlE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/read_e.cpp b/test/drivers/test_suites/syscall_enter_suite/read_e.cpp index e80e71d850..3f34974858 100644 --- a/test/drivers/test_suites/syscall_enter_suite/read_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/read_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_read -TEST(SyscallEnter, readE) -{ +TEST(SyscallEnter, readE) { auto evt_test = get_syscall_event_test(__NR_read, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, readE) int32_t mock_fd = -1; char mock_buf[8]; size_t mock_count = 4096; - assert_syscall_state(SYSCALL_FAILURE, "read", syscall(__NR_read, mock_fd, (void *)(mock_buf), mock_count)); + assert_syscall_state(SYSCALL_FAILURE, + "read", + syscall(__NR_read, mock_fd, (void *)(mock_buf), mock_count)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, readE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/readv_e.cpp b/test/drivers/test_suites/syscall_enter_suite/readv_e.cpp index 2fb450aa54..ef3571c3bd 100644 --- a/test/drivers/test_suites/syscall_enter_suite/readv_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/readv_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_readv -TEST(SyscallEnter, readvE) -{ +TEST(SyscallEnter, readvE) { auto evt_test = get_syscall_event_test(__NR_readv, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, readvE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/recv_e.cpp b/test/drivers/test_suites/syscall_enter_suite/recv_e.cpp index 9c3b92f57e..a451d77925 100644 --- a/test/drivers/test_suites/syscall_enter_suite/recv_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/recv_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_recv -TEST(SyscallEnter, recvE) -{ +TEST(SyscallEnter, recvE) { auto evt_test = get_syscall_event_test(__NR_recv, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, recvE) char* mock_buf = NULL; size_t mock_count = DEFAULT_SNAPLEN; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "recv", syscall(__NR_recv, mock_fd, (void*)(mock_buf), mock_count, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "recv", + syscall(__NR_recv, mock_fd, (void*)(mock_buf), mock_count, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, recvE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/recvfrom_e.cpp b/test/drivers/test_suites/syscall_enter_suite/recvfrom_e.cpp index 34ba56ae67..f795bac4df 100644 --- a/test/drivers/test_suites/syscall_enter_suite/recvfrom_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/recvfrom_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_recvfrom -TEST(SyscallEnter, recvfromE) -{ +TEST(SyscallEnter, recvfromE) { auto evt_test = get_syscall_event_test(__NR_recvfrom, ENTER_EVENT); evt_test->enable_capture(); @@ -15,8 +14,16 @@ TEST(SyscallEnter, recvfromE) socklen_t received_data_len = MAX_RECV_BUF_SIZE; uint32_t flags = 0; sockaddr* src_addr = NULL; - socklen_t *addrlen = NULL; - assert_syscall_state(SYSCALL_FAILURE, "recvfrom", syscall(__NR_recvfrom, mock_fd, received_data, received_data_len, flags, src_addr, addrlen)); + socklen_t* addrlen = NULL; + assert_syscall_state(SYSCALL_FAILURE, + "recvfrom", + syscall(__NR_recvfrom, + mock_fd, + received_data, + received_data_len, + flags, + src_addr, + addrlen)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +31,7 @@ TEST(SyscallEnter, recvfromE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/recvmmsg_e.cpp b/test/drivers/test_suites/syscall_enter_suite/recvmmsg_e.cpp index 2d8f3f3be6..5c04af96fb 100644 --- a/test/drivers/test_suites/syscall_enter_suite/recvmmsg_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/recvmmsg_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_recvmmsg -TEST(SyscallEnter, recvmmsgE) -{ +TEST(SyscallEnter, recvmmsgE) { auto evt_test = get_syscall_event_test(__NR_recvmmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, recvmmsgE) uint32_t vlen = 0; int flags = 0; struct timespec *timeout = NULL; - assert_syscall_state(SYSCALL_FAILURE, "recvmmsg", syscall(__NR_recvmmsg, mock_fd, msg, vlen, flags, timeout)); + assert_syscall_state(SYSCALL_FAILURE, + "recvmmsg", + syscall(__NR_recvmmsg, mock_fd, msg, vlen, flags, timeout)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, recvmmsgE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/recvmsg_e.cpp b/test/drivers/test_suites/syscall_enter_suite/recvmsg_e.cpp index c364a73518..a367860203 100644 --- a/test/drivers/test_suites/syscall_enter_suite/recvmsg_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/recvmsg_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_recvmsg -TEST(SyscallEnter, recvmsgE) -{ +TEST(SyscallEnter, recvmsgE) { auto evt_test = get_syscall_event_test(__NR_recvmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, recvmsgE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/rename_e.cpp b/test/drivers/test_suites/syscall_enter_suite/rename_e.cpp index 618a131a03..008f507101 100644 --- a/test/drivers/test_suites/syscall_enter_suite/rename_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/rename_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_rename -TEST(SyscallEnter, renameE) -{ +TEST(SyscallEnter, renameE) { auto evt_test = get_syscall_event_test(__NR_rename, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, renameE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/renameat2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/renameat2_e.cpp index bd5087c87c..c902cd8f56 100644 --- a/test/drivers/test_suites/syscall_enter_suite/renameat2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/renameat2_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_renameat2 -TEST(SyscallEnter, renameat2E) -{ +TEST(SyscallEnter, renameat2E) { auto evt_test = get_syscall_event_test(__NR_renameat2, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, renameat2E) const char* old_path = NULL; const char* new_path = NULL; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "renameat2", syscall(__NR_renameat2, old_fd, old_path, new_fd, new_path, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "renameat2", + syscall(__NR_renameat2, old_fd, old_path, new_fd, new_path, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, renameat2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/renameat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/renameat_e.cpp index 66754b34d3..860495fe77 100644 --- a/test/drivers/test_suites/syscall_enter_suite/renameat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/renameat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_renameat -TEST(SyscallEnter, renameatE) -{ +TEST(SyscallEnter, renameatE) { auto evt_test = get_syscall_event_test(__NR_renameat, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, renameatE) int32_t new_fd = 0; const char* old_path = NULL; const char* new_path = NULL; - assert_syscall_state(SYSCALL_FAILURE, "renameat", syscall(__NR_renameat, old_fd, old_path, new_fd, new_path)); + assert_syscall_state(SYSCALL_FAILURE, + "renameat", + syscall(__NR_renameat, old_fd, old_path, new_fd, new_path)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, renameatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/rmdir_e.cpp b/test/drivers/test_suites/syscall_enter_suite/rmdir_e.cpp index 2d5ab470b8..a1fbf8226b 100644 --- a/test/drivers/test_suites/syscall_enter_suite/rmdir_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/rmdir_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_rmdir -TEST(SyscallEnter, rmdirE) -{ +TEST(SyscallEnter, rmdirE) { auto evt_test = get_syscall_event_test(__NR_rmdir, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallEnter, rmdirE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/seccomp_e.cpp b/test/drivers/test_suites/syscall_enter_suite/seccomp_e.cpp index 7293cc2aea..c5246f5eed 100644 --- a/test/drivers/test_suites/syscall_enter_suite/seccomp_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/seccomp_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, seccompE) -{ +TEST(SyscallEnter, seccompE) { auto evt_test = get_syscall_event_test(__NR_seccomp, ENTER_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallEnter, seccompE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/select_e.cpp b/test/drivers/test_suites/syscall_enter_suite/select_e.cpp index 9de212f2d5..f46590e649 100644 --- a/test/drivers/test_suites/syscall_enter_suite/select_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/select_e.cpp @@ -1,15 +1,16 @@ #include "../../event_class/event_class.h" #ifdef __NR_select -TEST(SyscallEnter, selectE) -{ +TEST(SyscallEnter, selectE) { auto evt_test = get_syscall_event_test(__NR_select, ENTER_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - assert_syscall_state(SYSCALL_FAILURE, "select", syscall(__NR_select, -1, nullptr, nullptr, nullptr, nullptr)); + assert_syscall_state(SYSCALL_FAILURE, + "select", + syscall(__NR_select, -1, nullptr, nullptr, nullptr, nullptr)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -17,8 +18,7 @@ TEST(SyscallEnter, selectE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/semctl_e.cpp b/test/drivers/test_suites/syscall_enter_suite/semctl_e.cpp index 9e6be7c5a1..f9efc68a90 100644 --- a/test/drivers/test_suites/syscall_enter_suite/semctl_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/semctl_e.cpp @@ -6,8 +6,7 @@ #include #include -TEST(SyscallEnter, semctlE) -{ +TEST(SyscallEnter, semctlE) { auto evt_test = get_syscall_event_test(__NR_semctl, ENTER_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallEnter, semctlE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -53,4 +51,4 @@ TEST(SyscallEnter, semctlE) evt_test->assert_num_params_pushed(4); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_enter_suite/semget_e.cpp b/test/drivers/test_suites/syscall_enter_suite/semget_e.cpp index 19d4223ba5..facc63296f 100644 --- a/test/drivers/test_suites/syscall_enter_suite/semget_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/semget_e.cpp @@ -6,8 +6,7 @@ #include #include -TEST(SyscallEnter, semgetE) -{ +TEST(SyscallEnter, semgetE) { auto evt_test = get_syscall_event_test(__NR_semget, ENTER_EVENT); evt_test->enable_capture(); @@ -25,8 +24,7 @@ TEST(SyscallEnter, semgetE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -49,4 +47,4 @@ TEST(SyscallEnter, semgetE) evt_test->assert_num_params_pushed(3); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_enter_suite/semop_e.cpp b/test/drivers/test_suites/syscall_enter_suite/semop_e.cpp index ef49c20ab3..c6aab5edfa 100644 --- a/test/drivers/test_suites/syscall_enter_suite/semop_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/semop_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, semopE) -{ +TEST(SyscallEnter, semopE) { auto evt_test = get_syscall_event_test(__NR_semop, ENTER_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallEnter, semopE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/send_e.cpp b/test/drivers/test_suites/syscall_enter_suite/send_e.cpp index 603d71bf46..321975b0c4 100644 --- a/test/drivers/test_suites/syscall_enter_suite/send_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/send_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_send -TEST(SyscallEnter, sendE) -{ +TEST(SyscallEnter, sendE) { auto evt_test = get_syscall_event_test(__NR_send, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, sendE) char mock_buf[8]; size_t mock_count = 4096; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "send", syscall(__NR_send, mock_fd, (void *)(mock_buf), mock_count, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "send", + syscall(__NR_send, mock_fd, (void *)(mock_buf), mock_count, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, sendE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/sendfile_e.cpp b/test/drivers/test_suites/syscall_enter_suite/sendfile_e.cpp index 120e0ad89f..3a439033e8 100644 --- a/test/drivers/test_suites/syscall_enter_suite/sendfile_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/sendfile_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_sendfile -TEST(SyscallEnter, sendfileE_null_pointer) -{ +TEST(SyscallEnter, sendfileE_null_pointer) { auto evt_test = get_syscall_event_test(__NR_sendfile, ENTER_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallEnter, sendfileE_null_pointer) int in_fd = -2; void* offsite = NULL; unsigned long size = 37; - assert_syscall_state(SYSCALL_FAILURE, "sendfile", syscall(__NR_sendfile, out_fd, in_fd, offsite, size)); + assert_syscall_state(SYSCALL_FAILURE, + "sendfile", + syscall(__NR_sendfile, out_fd, in_fd, offsite, size)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallEnter, sendfileE_null_pointer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -51,8 +51,7 @@ TEST(SyscallEnter, sendfileE_null_pointer) evt_test->assert_num_params_pushed(4); } -TEST(SyscallEnter, sendfileE) -{ +TEST(SyscallEnter, sendfileE) { auto evt_test = get_syscall_event_test(__NR_sendfile, ENTER_EVENT); evt_test->enable_capture(); @@ -63,7 +62,9 @@ TEST(SyscallEnter, sendfileE) int in_fd = -2; unsigned long offsite = 24; unsigned long size = 37; - assert_syscall_state(SYSCALL_FAILURE, "sendfile", syscall(__NR_sendfile, out_fd, in_fd, &offsite, size)); + assert_syscall_state(SYSCALL_FAILURE, + "sendfile", + syscall(__NR_sendfile, out_fd, in_fd, &offsite, size)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -71,8 +72,7 @@ TEST(SyscallEnter, sendfileE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/sendmmsg_e.cpp b/test/drivers/test_suites/syscall_enter_suite/sendmmsg_e.cpp index cbf4b9f8b8..1b1456c524 100644 --- a/test/drivers/test_suites/syscall_enter_suite/sendmmsg_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/sendmmsg_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_sendmmsg -TEST(SyscallEnter, sendmmsgE) -{ +TEST(SyscallEnter, sendmmsgE) { auto evt_test = get_syscall_event_test(__NR_sendmmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, sendmmsgE) struct msghdr *msg = NULL; uint32_t vlen = 0; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendmmsg", syscall(__NR_sendmmsg, mock_fd, msg, vlen, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "sendmmsg", + syscall(__NR_sendmmsg, mock_fd, msg, vlen, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, sendmmsgE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/sendmsg_e.cpp b/test/drivers/test_suites/syscall_enter_suite/sendmsg_e.cpp index a4f65e5958..4bbb648f0c 100644 --- a/test/drivers/test_suites/syscall_enter_suite/sendmsg_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/sendmsg_e.cpp @@ -1,12 +1,12 @@ #include "../../event_class/event_class.h" -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ - defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendmsg) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && \ + defined(__NR_sendmsg) /*=============================== TCP ===========================*/ -TEST(SyscallEnter, sendmsgE_ipv4_tcp) -{ +TEST(SyscallEnter, sendmsgE_ipv4_tcp) { auto evt_test = get_syscall_event_test(__NR_sendmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -21,8 +21,7 @@ TEST(SyscallEnter, sendmsgE_ipv4_tcp) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -36,23 +35,27 @@ TEST(SyscallEnter, sendmsgE_ipv4_tcp) evt_test->assert_numeric_param(2, (uint32_t)SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE)*/ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallEnter, sendmsgE_ipv4_tcp_NULL_sockaddr) -{ +TEST(SyscallEnter, sendmsgE_ipv4_tcp_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_sendmsg, ENTER_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendmsg, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendmsg, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -60,8 +63,7 @@ TEST(SyscallEnter, sendmsgE_ipv4_tcp_NULL_sockaddr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -75,14 +77,15 @@ TEST(SyscallEnter, sendmsgE_ipv4_tcp_NULL_sockaddr) evt_test->assert_numeric_param(2, (uint32_t)SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE)*/ - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { // We can recover the tuple even without the userspace socaddr - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); - } - else - { + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); + } else { // todo!: We are reading some random stuff, because we don't use kernel info GTEST_SKIP() << "We obtain a wrong tuple because we don't use the kernel info"; } @@ -94,8 +97,7 @@ TEST(SyscallEnter, sendmsgE_ipv4_tcp_NULL_sockaddr) /*=============================== UDP ===========================*/ -TEST(SyscallEnter, sendmsgE_ipv4_udp) -{ +TEST(SyscallEnter, sendmsgE_ipv4_udp) { auto evt_test = get_syscall_event_test(__NR_sendmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -110,8 +112,7 @@ TEST(SyscallEnter, sendmsgE_ipv4_udp) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -125,19 +126,22 @@ TEST(SyscallEnter, sendmsgE_ipv4_udp) evt_test->assert_numeric_param(2, (uint32_t)SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE)*/ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -// We cannot call a sendmsg without a destination address in UDP. Errno: 89 err_message: Destination address required -// TEST(SyscallEnter, sendmsgE_ipv4_udp_NULL_sockaddr) +// We cannot call a sendmsg without a destination address in UDP. Errno: 89 err_message: Destination +// address required TEST(SyscallEnter, sendmsgE_ipv4_udp_NULL_sockaddr) -TEST(SyscallEnter, sendmsgE_fail) -{ +TEST(SyscallEnter, sendmsgE_fail) { auto evt_test = get_syscall_event_test(__NR_sendmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -156,7 +160,9 @@ TEST(SyscallEnter, sendmsgE_fail) send_msg.msg_iovlen = 1; uint32_t sendmsg_flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendmsg", syscall(__NR_sendmsg, mock_fd, &send_msg, sendmsg_flags)); + assert_syscall_state(SYSCALL_FAILURE, + "sendmsg", + syscall(__NR_sendmsg, mock_fd, &send_msg, sendmsg_flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -164,8 +170,7 @@ TEST(SyscallEnter, sendmsgE_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/sendto_e.cpp b/test/drivers/test_suites/syscall_enter_suite/sendto_e.cpp index 86a2c4b8a6..97d1397f91 100644 --- a/test/drivers/test_suites/syscall_enter_suite/sendto_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/sendto_e.cpp @@ -1,12 +1,12 @@ #include "../../event_class/event_class.h" -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ - defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && \ + defined(__NR_sendto) /*=============================== TCP ===========================*/ -TEST(SyscallEnter, sendtoE_ipv4_tcp) -{ +TEST(SyscallEnter, sendtoE_ipv4_tcp) { auto evt_test = get_syscall_event_test(__NR_sendto, ENTER_EVENT); evt_test->enable_capture(); @@ -21,8 +21,7 @@ TEST(SyscallEnter, sendtoE_ipv4_tcp) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -36,23 +35,27 @@ TEST(SyscallEnter, sendtoE_ipv4_tcp) evt_test->assert_numeric_param(2, (uint32_t)SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE)*/ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallEnter, sendtoE_ipv4_tcp_NULL_sockaddr) -{ +TEST(SyscallEnter, sendtoE_ipv4_tcp_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_sendto, ENTER_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -60,8 +63,7 @@ TEST(SyscallEnter, sendtoE_ipv4_tcp_NULL_sockaddr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -75,14 +77,15 @@ TEST(SyscallEnter, sendtoE_ipv4_tcp_NULL_sockaddr) evt_test->assert_numeric_param(2, (uint32_t)SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE)*/ - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { // We can recover the tuple even without the userspace socaddr - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); - } - else - { + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); + } else { // todo!: We are reading some random stuff, because we don't use kernel info GTEST_SKIP() << "We obtain a wrong tuple because we don't use the kernel info"; } @@ -94,8 +97,7 @@ TEST(SyscallEnter, sendtoE_ipv4_tcp_NULL_sockaddr) /*=============================== UDP ===========================*/ -TEST(SyscallEnter, sendtoE_ipv4_udp) -{ +TEST(SyscallEnter, sendtoE_ipv4_udp) { auto evt_test = get_syscall_event_test(__NR_sendto, ENTER_EVENT); evt_test->enable_capture(); @@ -110,8 +112,7 @@ TEST(SyscallEnter, sendtoE_ipv4_udp) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -125,19 +126,22 @@ TEST(SyscallEnter, sendtoE_ipv4_udp) evt_test->assert_numeric_param(2, (uint32_t)SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE)*/ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -// We cannot call a sendto without a destination address in UDP. Errno: 89 err_message: Destination address required -// TEST(SyscallEnter, sendtoE_ipv4_udp_NULL_sockaddr) +// We cannot call a sendto without a destination address in UDP. Errno: 89 err_message: Destination +// address required TEST(SyscallEnter, sendtoE_ipv4_udp_NULL_sockaddr) -TEST(SyscallEnter, sendtoE_fail) -{ +TEST(SyscallEnter, sendtoE_fail) { auto evt_test = get_syscall_event_test(__NR_sendto, ENTER_EVENT); evt_test->enable_capture(); @@ -145,13 +149,15 @@ TEST(SyscallEnter, sendtoE_fail) /*=============================== TRIGGER SYSCALL ===========================*/ int32_t mock_fd = -12; - size_t len = DEFAULT_SNAPLEN / 2; // random value + size_t len = DEFAULT_SNAPLEN / 2; // random value uint32_t sendto_flags = 0; struct sockaddr* dest_addr = NULL; socklen_t addrlen = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendto", - syscall(__NR_sendto, mock_fd, NULL, len, sendto_flags, dest_addr, addrlen)); + assert_syscall_state( + SYSCALL_FAILURE, + "sendto", + syscall(__NR_sendto, mock_fd, NULL, len, sendto_flags, dest_addr, addrlen)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -159,8 +165,7 @@ TEST(SyscallEnter, sendtoE_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setgid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setgid_e.cpp index 7901b6e887..49eb63be41 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setgid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setgid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setgid -TEST(SyscallEnter, setgidE) -{ +TEST(SyscallEnter, setgidE) { auto evt_test = get_syscall_event_test(__NR_setgid, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallEnter, setgidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setns_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setns_e.cpp index 92f0dacc33..ddb1daed35 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setns_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setns_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setns -TEST(SyscallEnter, setnsE) -{ +TEST(SyscallEnter, setnsE) { auto evt_test = get_syscall_event_test(__NR_setns, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, setnsE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setpgid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setpgid_e.cpp index fa8f1d3a3b..cb840bec46 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setpgid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setpgid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setpgid -TEST(SyscallEnter, setpgidE) -{ +TEST(SyscallEnter, setpgidE) { auto evt_test = get_syscall_event_test(__NR_setpgid, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, setpgidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setregid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setregid_e.cpp index 3ee8f1eec3..d0737fe59d 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setregid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setregid_e.cpp @@ -1,40 +1,42 @@ #include "../../event_class/event_class.h" #ifdef __NR_setregid -TEST(SyscallEnter, setregidE) -{ - auto evt_test = get_syscall_event_test(__NR_setregid, ENTER_EVENT); +TEST(SyscallEnter, setregidE) { + auto evt_test = get_syscall_event_test(__NR_setregid, ENTER_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - gid_t rgid = (uint32_t)-1; - gid_t egid = (uint32_t)-1; - /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setregid", syscall(__NR_setregid, rgid, egid), NOT_EQUAL, -1); + gid_t rgid = (uint32_t)-1; + gid_t egid = (uint32_t)-1; + /* If one of the arguments equals -1, the corresponding value is not changed. */ + assert_syscall_state(SYSCALL_SUCCESS, + "setregid", + syscall(__NR_setregid, rgid, egid), + NOT_EQUAL, + -1); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ // Here we have no parameters to assert. - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(0); + evt_test->assert_num_params_pushed(0); } #endif diff --git a/test/drivers/test_suites/syscall_enter_suite/setresgid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setresgid_e.cpp index f1378d0f4a..4305f2422c 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setresgid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setresgid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setresgid -TEST(SyscallEnter, setresgidE) -{ +TEST(SyscallEnter, setresgidE) { auto evt_test = get_syscall_event_test(__NR_setresgid, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,11 @@ TEST(SyscallEnter, setresgidE) gid_t egid = (uint32_t)-1; gid_t sgid = (uint32_t)-1; /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setresgid", syscall(__NR_setresgid, rgid, egid, sgid), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setresgid", + syscall(__NR_setresgid, rgid, egid, sgid), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +24,7 @@ TEST(SyscallEnter, setresgidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setresuid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setresuid_e.cpp index 4ed2226597..68e8f6c770 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setresuid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setresuid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setresuid -TEST(SyscallEnter, setresuidE) -{ +TEST(SyscallEnter, setresuidE) { auto evt_test = get_syscall_event_test(__NR_setresuid, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,11 @@ TEST(SyscallEnter, setresuidE) uid_t euid = (uint32_t)-1; uid_t suid = (uint32_t)-1; /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setresuid", syscall(__NR_setresuid, ruid, euid, suid), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setresuid", + syscall(__NR_setresuid, ruid, euid, suid), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +24,7 @@ TEST(SyscallEnter, setresuidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setreuid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setreuid_e.cpp index 6c18ac3b51..b628aa0529 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setreuid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setreuid_e.cpp @@ -1,40 +1,42 @@ #include "../../event_class/event_class.h" #ifdef __NR_setreuid -TEST(SyscallEnter, setreuidE) -{ - auto evt_test = get_syscall_event_test(__NR_setreuid, ENTER_EVENT); +TEST(SyscallEnter, setreuidE) { + auto evt_test = get_syscall_event_test(__NR_setreuid, ENTER_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - uid_t ruid = (uint32_t)-1; - uid_t euid = (uint32_t)-1; - /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setreuid", syscall(__NR_setreuid, ruid, euid), NOT_EQUAL, -1); + uid_t ruid = (uint32_t)-1; + uid_t euid = (uint32_t)-1; + /* If one of the arguments equals -1, the corresponding value is not changed. */ + assert_syscall_state(SYSCALL_SUCCESS, + "setreuid", + syscall(__NR_setreuid, ruid, euid), + NOT_EQUAL, + -1); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ // Here we have no parameters to assert. - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(0); + evt_test->assert_num_params_pushed(0); } #endif diff --git a/test/drivers/test_suites/syscall_enter_suite/setrlimit_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setrlimit_e.cpp index 3faa032d33..c8f798ed9a 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setrlimit_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setrlimit_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, setrlimitE) -{ +TEST(SyscallEnter, setrlimitE) { auto evt_test = get_syscall_event_test(__NR_setrlimit, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, setrlimitE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setsid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setsid_e.cpp index 0e00c68cc0..a61801fbb3 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setsid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setsid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setsid -TEST(SyscallEnter, setsidE) -{ +TEST(SyscallEnter, setsidE) { auto evt_test = get_syscall_event_test(__NR_setsid, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, setsidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setsockopt_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setsockopt_e.cpp index a388b7eceb..4e96b03d85 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setsockopt_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setsockopt_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, setsockoptE) -{ +TEST(SyscallEnter, setsockoptE) { auto evt_test = get_syscall_event_test(__NR_setsockopt, ENTER_EVENT); evt_test->enable_capture(); @@ -17,7 +16,10 @@ TEST(SyscallEnter, setsockoptE) int option_name = 0; const void* option_value = NULL; socklen_t option_len = 0; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, socket_fd, level, option_name, option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, socket_fd, level, option_name, option_value, option_len)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +27,7 @@ TEST(SyscallEnter, setsockoptE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/setuid_e.cpp b/test/drivers/test_suites/syscall_enter_suite/setuid_e.cpp index b722388cb5..f551a4fdfd 100644 --- a/test/drivers/test_suites/syscall_enter_suite/setuid_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/setuid_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setuid -TEST(SyscallEnter, setuidE) -{ +TEST(SyscallEnter, setuidE) { auto evt_test = get_syscall_event_test(__NR_setuid, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallEnter, setuidE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/shutdown_e.cpp b/test/drivers/test_suites/syscall_enter_suite/shutdown_e.cpp index 15ea38d9f5..aa6c11bf1b 100644 --- a/test/drivers/test_suites/syscall_enter_suite/shutdown_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/shutdown_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, shutdownE) -{ +TEST(SyscallEnter, shutdownE) { auto evt_test = get_syscall_event_test(__NR_shutdown, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, shutdownE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/signalfd4_e.cpp b/test/drivers/test_suites/syscall_enter_suite/signalfd4_e.cpp index 3b9b2926ef..17138b0817 100644 --- a/test/drivers/test_suites/syscall_enter_suite/signalfd4_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/signalfd4_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, signalfd4E) -{ +TEST(SyscallEnter, signalfd4E) { auto evt_test = get_syscall_event_test(__NR_signalfd4, ENTER_EVENT); evt_test->enable_capture(); @@ -17,7 +16,9 @@ TEST(SyscallEnter, signalfd4E) sigset_t mask = {0}; size_t sizemask = 0; int flags = 7; - assert_syscall_state(SYSCALL_FAILURE, "signalfd4", syscall(__NR_signalfd4, mock_fd, &mask, sizemask, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "signalfd4", + syscall(__NR_signalfd4, mock_fd, &mask, sizemask, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallEnter, signalfd4E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/signalfd_e.cpp b/test/drivers/test_suites/syscall_enter_suite/signalfd_e.cpp index 56b6ea21eb..5b5a359bd6 100644 --- a/test/drivers/test_suites/syscall_enter_suite/signalfd_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/signalfd_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, signalfdE) -{ +TEST(SyscallEnter, signalfdE) { auto evt_test = get_syscall_event_test(__NR_signalfd, ENTER_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallEnter, signalfdE) int32_t mock_fd = -1; sigset_t mask = {0}; size_t sizemask = 0; - assert_syscall_state(SYSCALL_FAILURE, "signalfd", syscall(__NR_signalfd, mock_fd, &mask, sizemask)); + assert_syscall_state(SYSCALL_FAILURE, + "signalfd", + syscall(__NR_signalfd, mock_fd, &mask, sizemask)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallEnter, signalfdE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/socket_e.cpp b/test/drivers/test_suites/syscall_enter_suite/socket_e.cpp index 2020e1fe84..8ecbbc2a34 100644 --- a/test/drivers/test_suites/syscall_enter_suite/socket_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/socket_e.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallEnter, socketE) -{ +TEST(SyscallEnter, socketE) { auto evt_test = get_syscall_event_test(__NR_socket, ENTER_EVENT); evt_test->enable_capture(); @@ -25,15 +24,11 @@ TEST(SyscallEnter, socketE) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_socket, domain, type, protocol) == -1) - { + if(syscall(__NR_socket, domain, type, protocol) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -42,10 +37,13 @@ TEST(SyscallEnter, socketE) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The socket call failed while it should be successful..." << std::endl; } @@ -55,8 +53,7 @@ TEST(SyscallEnter, socketE) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/socketcall_e.cpp b/test/drivers/test_suites/syscall_enter_suite/socketcall_e.cpp index 5ce7a90b8a..7f2b05e9cb 100644 --- a/test/drivers/test_suites/syscall_enter_suite/socketcall_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/socketcall_e.cpp @@ -10,8 +10,7 @@ #if defined(__NR_clone3) && defined(__NR_wait4) #include -TEST(SyscallEnter, socketcall_socketE) -{ +TEST(SyscallEnter, socketcall_socketE) { auto evt_test = get_syscall_event_test(__NR_socket, ENTER_EVENT); evt_test->enable_capture(); @@ -31,15 +30,11 @@ TEST(SyscallEnter, socketcall_socketE) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_socketcall, SYS_SOCKET, args) == -1) - { + if(syscall(__NR_socketcall, SYS_SOCKET, args) == -1) { exit(EXIT_FAILURE); - } - else - { + } else { exit(EXIT_SUCCESS); } } @@ -48,10 +43,13 @@ TEST(SyscallEnter, socketcall_socketE) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The 'socketcall socket' failed while it should be successful..." << std::endl; } @@ -61,8 +59,7 @@ TEST(SyscallEnter, socketcall_socketE) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -87,8 +84,7 @@ TEST(SyscallEnter, socketcall_socketE) } #endif -TEST(SyscallEnter, socketcall_bindE) -{ +TEST(SyscallEnter, socketcall_bindE) { auto evt_test = get_syscall_event_test(__NR_bind, ENTER_EVENT); evt_test->enable_capture(); @@ -100,7 +96,9 @@ TEST(SyscallEnter, socketcall_bindE) args[1] = 0; args[2] = 0; - assert_syscall_state(SYSCALL_FAILURE, "socketcall bind", syscall(__NR_socketcall, SYS_BIND, args)); + assert_syscall_state(SYSCALL_FAILURE, + "socketcall bind", + syscall(__NR_socketcall, SYS_BIND, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -108,8 +106,7 @@ TEST(SyscallEnter, socketcall_bindE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -127,8 +124,7 @@ TEST(SyscallEnter, socketcall_bindE) evt_test->assert_num_params_pushed(1); } -TEST(SyscallEnter, socketcall_connectE) -{ +TEST(SyscallEnter, socketcall_connectE) { auto evt_test = get_syscall_event_test(__NR_connect, ENTER_EVENT); evt_test->enable_capture(); @@ -142,7 +138,9 @@ TEST(SyscallEnter, socketcall_connectE) args[0] = mock_fd; args[1] = (unsigned long)&server_addr; args[2] = sizeof(server_addr); - assert_syscall_state(SYSCALL_FAILURE, "socketcall connect", syscall(__NR_socketcall, SYS_CONNECT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "socketcall connect", + syscall(__NR_socketcall, SYS_CONNECT, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -150,8 +148,7 @@ TEST(SyscallEnter, socketcall_connectE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -165,16 +162,16 @@ TEST(SyscallEnter, socketcall_connectE) evt_test->assert_numeric_param(1, (int64_t)mock_fd); /* Parameter 2: addr (type: PT_SOCKADDR)*/ - /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. */ - if(evt_test->is_modern_bpf_engine()) - { + /* Modern BPF returns addr_info even if the syscall fails other drivers return an empty param. + */ + if(evt_test->is_modern_bpf_engine()) { evt_test->assert_addr_info_inet_param(2, PPM_AF_INET, IPV4_SERVER, IPV4_PORT_SERVER_STRING); - } - else - { + } else { evt_test->assert_empty_param(2); evt_test->assert_num_params_pushed(2); - GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[CONNECT_E]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } /*=============================== ASSERT PARAMETERS ===========================*/ @@ -184,8 +181,7 @@ TEST(SyscallEnter, socketcall_connectE) #endif #ifdef __NR_recvmmsg -TEST(SyscallEnter, socketcall_recvmmsgE) -{ +TEST(SyscallEnter, socketcall_recvmmsgE) { auto evt_test = get_syscall_event_test(__NR_recvmmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -212,8 +208,7 @@ TEST(SyscallEnter, socketcall_recvmmsgE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -232,8 +227,7 @@ TEST(SyscallEnter, socketcall_recvmmsgE) #endif #ifdef __NR_sendmmsg -TEST(SyscallEnter, socketcall_sendmmsgE) -{ +TEST(SyscallEnter, socketcall_sendmmsgE) { auto evt_test = get_syscall_event_test(__NR_sendmmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -258,8 +252,7 @@ TEST(SyscallEnter, socketcall_sendmmsgE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -277,8 +270,7 @@ TEST(SyscallEnter, socketcall_sendmmsgE) } #endif -TEST(SyscallEnter, socketcall_shutdownE) -{ +TEST(SyscallEnter, socketcall_shutdownE) { auto evt_test = get_syscall_event_test(__NR_shutdown, ENTER_EVENT); evt_test->enable_capture(); @@ -299,8 +291,7 @@ TEST(SyscallEnter, socketcall_shutdownE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -323,13 +314,11 @@ TEST(SyscallEnter, socketcall_shutdownE) #if defined(__NR_accept) || defined(__s390x__) -TEST(SyscallEnter, socketcall_acceptE) -{ +TEST(SyscallEnter, socketcall_acceptE) { #ifdef __s390x__ auto evt_test = get_syscall_event_test(__NR_accept4, ENTER_EVENT); /* The kmod/bpf can correctly handle accept also on s390x */ - if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) - { + if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) { /* we cannot set `__NR_accept` explicitly since it is not defined on s390x * we activate all syscalls. */ @@ -345,7 +334,7 @@ TEST(SyscallEnter, socketcall_acceptE) /*=============================== TRIGGER SYSCALL ===========================*/ int32_t mock_fd = -1; - sockaddr* addr = NULL; + sockaddr *addr = NULL; socklen_t *addrlen = NULL; unsigned long args[3] = {0}; @@ -360,8 +349,7 @@ TEST(SyscallEnter, socketcall_acceptE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -370,8 +358,7 @@ TEST(SyscallEnter, socketcall_acceptE) evt_test->assert_header(); #ifdef __s390x__ - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { /* socketcall uses accept4 event for SYS_ACCEPT for modern BPF */ /*=============================== ASSERT PARAMETERS ===========================*/ @@ -400,8 +387,7 @@ TEST(SyscallEnter, socketcall_acceptE) #ifdef __NR_accept4 -TEST(SyscallEnter, socketcall_accept4E) -{ +TEST(SyscallEnter, socketcall_accept4E) { auto evt_test = get_syscall_event_test(__NR_accept4, ENTER_EVENT); evt_test->enable_capture(); @@ -409,7 +395,7 @@ TEST(SyscallEnter, socketcall_accept4E) /*=============================== TRIGGER SYSCALL ===========================*/ int32_t mock_fd = -1; - sockaddr* addr = NULL; + sockaddr *addr = NULL; socklen_t *addrlen = NULL; int flags = 0; @@ -426,8 +412,7 @@ TEST(SyscallEnter, socketcall_accept4E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -448,8 +433,7 @@ TEST(SyscallEnter, socketcall_accept4E) #endif #ifdef __NR_listen -TEST(SyscallEnter, socketcall_listenE) -{ +TEST(SyscallEnter, socketcall_listenE) { auto evt_test = get_syscall_event_test(__NR_listen, ENTER_EVENT); evt_test->enable_capture(); @@ -470,8 +454,7 @@ TEST(SyscallEnter, socketcall_listenE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -495,8 +478,7 @@ TEST(SyscallEnter, socketcall_listenE) #ifdef __NR_recvfrom -TEST(SyscallEnter, socketcall_recvfromE) -{ +TEST(SyscallEnter, socketcall_recvfromE) { auto evt_test = get_syscall_event_test(__NR_recvfrom, ENTER_EVENT); evt_test->enable_capture(); @@ -507,7 +489,7 @@ TEST(SyscallEnter, socketcall_recvfromE) char received_data[MAX_RECV_BUF_SIZE]; socklen_t received_data_len = MAX_RECV_BUF_SIZE; uint32_t flags = 0; - sockaddr* src_addr = NULL; + sockaddr *src_addr = NULL; socklen_t *addrlen = NULL; unsigned long args[6] = {0}; @@ -526,8 +508,7 @@ TEST(SyscallEnter, socketcall_recvfromE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -553,8 +534,7 @@ TEST(SyscallEnter, socketcall_recvfromE) #include -TEST(SyscallEnter, socketcall_socketpairE) -{ +TEST(SyscallEnter, socketcall_socketpairE) { auto evt_test = get_syscall_event_test(__NR_socketpair, ENTER_EVENT); evt_test->enable_capture(); @@ -571,7 +551,9 @@ TEST(SyscallEnter, socketcall_socketpairE) args[1] = type; args[2] = protocol; args[3] = (unsigned long)fds; - assert_syscall_state(SYSCALL_FAILURE, "socketpair", syscall(__NR_socketcall, SYS_SOCKETPAIR, args)); + assert_syscall_state(SYSCALL_FAILURE, + "socketpair", + syscall(__NR_socketcall, SYS_SOCKETPAIR, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -579,8 +561,7 @@ TEST(SyscallEnter, socketcall_socketpairE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -605,10 +586,11 @@ TEST(SyscallEnter, socketcall_socketpairE) } #endif -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && \ + defined(__NR_sendto) -TEST(SyscallEnter, socketcall_sendtoE) -{ +TEST(SyscallEnter, socketcall_sendtoE) { auto evt_test = get_syscall_event_test(__NR_sendto, ENTER_EVENT); evt_test->enable_capture(); @@ -619,7 +601,10 @@ TEST(SyscallEnter, socketcall_sendtoE) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ char sent_data[FULL_MESSAGE_LEN] = FULL_MESSAGE; @@ -632,7 +617,11 @@ TEST(SyscallEnter, socketcall_sendtoE) args[3] = sendto_flags; args[4] = (unsigned long)&server_addr; args[5] = sizeof(server_addr); - assert_syscall_state(SYSCALL_SUCCESS, "sendto (client)", syscall(__NR_socketcall, SYS_SENDTO, args), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "sendto (client)", + syscall(__NR_socketcall, SYS_SENDTO, args), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_shutdown, server_socket_fd, 2); @@ -646,8 +635,7 @@ TEST(SyscallEnter, socketcall_sendtoE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -665,7 +653,12 @@ TEST(SyscallEnter, socketcall_sendtoE) /* Parameter 3: addr (type: PT_SOCKADDR)*/ /* The client performs a `sendto` to the server so the src_ipv4 is the client one. */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -673,10 +666,11 @@ TEST(SyscallEnter, socketcall_sendtoE) } #endif -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendmsg) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && \ + defined(__NR_sendmsg) -TEST(SyscallEnter, socketcall_sendmsgE) -{ +TEST(SyscallEnter, socketcall_sendmsgE) { auto evt_test = get_syscall_event_test(__NR_sendmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -687,14 +681,17 @@ TEST(SyscallEnter, socketcall_sendmsgE) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ struct msghdr send_msg; struct iovec iov[3]; memset(&send_msg, 0, sizeof(send_msg)); memset(iov, 0, sizeof(iov)); - send_msg.msg_name = (sockaddr*)&server_addr; + send_msg.msg_name = (sockaddr *)&server_addr; send_msg.msg_namelen = sizeof(server_addr); char sent_data_1[FIRST_MESSAGE_LEN] = "hey! there is a first message here."; char sent_data_2[SECOND_MESSAGE_LEN] = "hey! there is a second message here."; @@ -713,7 +710,11 @@ TEST(SyscallEnter, socketcall_sendmsgE) args[0] = client_socket_fd; args[1] = (unsigned long)&send_msg; args[2] = sendmsg_flags; - assert_syscall_state(SYSCALL_SUCCESS, "sendmsg (client)", syscall(__NR_socketcall, SYS_SENDMSG, args), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "sendmsg (client)", + syscall(__NR_socketcall, SYS_SENDMSG, args), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_shutdown, server_socket_fd, 2); @@ -727,8 +728,7 @@ TEST(SyscallEnter, socketcall_sendmsgE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -746,7 +746,12 @@ TEST(SyscallEnter, socketcall_sendmsgE) /* Parameter 3: addr (type: PT_SOCKADDR)*/ /* The client performs a `sendmsg` to the server so the src_ipv4 is the client one. */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -755,8 +760,7 @@ TEST(SyscallEnter, socketcall_sendmsgE) #endif #ifdef __NR_recvmsg -TEST(SyscallEnter, socketcall_recvmsgE) -{ +TEST(SyscallEnter, socketcall_recvmsgE) { auto evt_test = get_syscall_event_test(__NR_recvmsg, ENTER_EVENT); evt_test->enable_capture(); @@ -779,8 +783,7 @@ TEST(SyscallEnter, socketcall_recvmsgE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -803,8 +806,7 @@ TEST(SyscallEnter, socketcall_recvmsgE) #include -TEST(SyscallEnter, socketcall_getsockoptE) -{ +TEST(SyscallEnter, socketcall_getsockoptE) { auto evt_test = get_syscall_event_test(__NR_getsockopt, ENTER_EVENT); evt_test->enable_capture(); @@ -823,7 +825,9 @@ TEST(SyscallEnter, socketcall_getsockoptE) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -831,8 +835,7 @@ TEST(SyscallEnter, socketcall_getsockoptE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -854,8 +857,7 @@ TEST(SyscallEnter, socketcall_getsockoptE) #include -TEST(SyscallEnter, socketcall_setsockoptE) -{ +TEST(SyscallEnter, socketcall_setsockoptE) { auto evt_test = get_syscall_event_test(__NR_setsockopt, ENTER_EVENT); evt_test->enable_capture(); @@ -874,7 +876,9 @@ TEST(SyscallEnter, socketcall_setsockoptE) args[2] = option_name; args[3] = (unsigned long)option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -882,8 +886,7 @@ TEST(SyscallEnter, socketcall_setsockoptE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -903,8 +906,7 @@ TEST(SyscallEnter, socketcall_setsockoptE) #ifdef __NR_send -TEST(SyscallEnter, socketcall_sendE) -{ +TEST(SyscallEnter, socketcall_sendE) { auto evt_test = get_syscall_event_test(__NR_send, ENTER_EVENT); evt_test->enable_capture(); @@ -929,8 +931,7 @@ TEST(SyscallEnter, socketcall_sendE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -954,8 +955,7 @@ TEST(SyscallEnter, socketcall_sendE) #ifdef __NR_recv -TEST(SyscallEnter, socketcall_recvE) -{ +TEST(SyscallEnter, socketcall_recvE) { auto evt_test = get_syscall_event_test(__NR_recv, ENTER_EVENT); evt_test->enable_capture(); @@ -980,8 +980,7 @@ TEST(SyscallEnter, socketcall_recvE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1004,8 +1003,7 @@ TEST(SyscallEnter, socketcall_recvE) #endif #ifdef __NR_getpeername -TEST(SyscallEnter, socketcall_getpeernameE) -{ +TEST(SyscallEnter, socketcall_getpeernameE) { auto evt_test = get_syscall_event_test(__NR_getpeername, ENTER_EVENT); evt_test->enable_capture(); @@ -1020,7 +1018,9 @@ TEST(SyscallEnter, socketcall_getpeernameE) args[0] = mock_fd; args[1] = (unsigned long)usockaddr; args[2] = (unsigned long)usockaddr_len; - assert_syscall_state(SYSCALL_FAILURE, "getpeername", syscall(__NR_socketcall, SYS_GETPEERNAME, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getpeername", + syscall(__NR_socketcall, SYS_GETPEERNAME, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -1028,8 +1028,7 @@ TEST(SyscallEnter, socketcall_getpeernameE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1048,8 +1047,7 @@ TEST(SyscallEnter, socketcall_getpeernameE) #endif #ifdef __NR_getsockname -TEST(SyscallEnter, socketcall_getsocknameE) -{ +TEST(SyscallEnter, socketcall_getsocknameE) { auto evt_test = get_syscall_event_test(__NR_getsockname, ENTER_EVENT); evt_test->enable_capture(); @@ -1064,7 +1062,9 @@ TEST(SyscallEnter, socketcall_getsocknameE) args[0] = mock_fd; args[1] = (unsigned long)usockaddr; args[2] = (unsigned long)usockaddr_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockname", syscall(__NR_socketcall, SYS_GETSOCKNAME, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockname", + syscall(__NR_socketcall, SYS_GETSOCKNAME, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -1072,8 +1072,7 @@ TEST(SyscallEnter, socketcall_getsocknameE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1091,8 +1090,7 @@ TEST(SyscallEnter, socketcall_getsocknameE) } #endif -TEST(SyscallEnter, socketcall_wrong_code_socketcall_interesting) -{ +TEST(SyscallEnter, socketcall_wrong_code_socketcall_interesting) { // We send a wrong code so the event will be dropped auto evt_test = get_syscall_event_test(__NR_socketcall, ENTER_EVENT); @@ -1115,8 +1113,7 @@ TEST(SyscallEnter, socketcall_wrong_code_socketcall_interesting) evt_test->assert_event_absence(CURRENT_PID, PPME_GENERIC_E); } -TEST(SyscallEnter, socketcall_wrong_code_socketcall_not_interesting) -{ +TEST(SyscallEnter, socketcall_wrong_code_socketcall_not_interesting) { // Same as the previous test auto evt_test = get_syscall_event_test(__NR_setsockopt, ENTER_EVENT); @@ -1139,23 +1136,24 @@ TEST(SyscallEnter, socketcall_wrong_code_socketcall_not_interesting) evt_test->assert_event_absence(CURRENT_PID, PPME_GENERIC_E); } -TEST(SyscallEnter, socketcall_null_pointer) -{ +TEST(SyscallEnter, socketcall_null_pointer) { auto evt_test = get_syscall_event_test(__NR_shutdown, ENTER_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - assert_syscall_state(SYSCALL_FAILURE, "socketcall", syscall(__NR_socketcall, SYS_SHUTDOWN, NULL)); + assert_syscall_state(SYSCALL_FAILURE, + "socketcall", + syscall(__NR_socketcall, SYS_SHUTDOWN, NULL)); /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); - if(evt_test->is_kmod_engine()) - { - /* with a null pointer we are not able to correctly obtain the event so right now we drop it. */ + if(evt_test->is_kmod_engine()) { + /* with a null pointer we are not able to correctly obtain the event so right now we drop + * it. */ evt_test->assert_event_absence(); SUCCEED(); return; @@ -1166,8 +1164,7 @@ TEST(SyscallEnter, socketcall_null_pointer) */ evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1188,8 +1185,7 @@ TEST(SyscallEnter, socketcall_null_pointer) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, socketcall_null_pointer_and_wrong_code_socketcall_interesting) -{ +TEST(SyscallEnter, socketcall_null_pointer_and_wrong_code_socketcall_interesting) { // We send a wrong code so the event will be dropped auto evt_test = get_syscall_event_test(__NR_socketcall, ENTER_EVENT); diff --git a/test/drivers/test_suites/syscall_enter_suite/socketpair_e.cpp b/test/drivers/test_suites/syscall_enter_suite/socketpair_e.cpp index b305597d85..51e8abf60a 100644 --- a/test/drivers/test_suites/syscall_enter_suite/socketpair_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/socketpair_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, socketpairE) -{ +TEST(SyscallEnter, socketpairE) { auto evt_test = get_syscall_event_test(__NR_socketpair, ENTER_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallEnter, socketpairE) int type = SOCK_STREAM; int protocol = 0; int32_t* fds = NULL; - assert_syscall_state(SYSCALL_FAILURE, "socketpair", syscall(__NR_socketpair, domain, type, protocol, fds)); + assert_syscall_state(SYSCALL_FAILURE, + "socketpair", + syscall(__NR_socketpair, domain, type, protocol, fds)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallEnter, socketpairE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/splice_e.cpp b/test/drivers/test_suites/syscall_enter_suite/splice_e.cpp index 75c1d6bcd9..adecb31bd5 100644 --- a/test/drivers/test_suites/syscall_enter_suite/splice_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/splice_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_splice -TEST(SyscallEnter, spliceE) -{ +TEST(SyscallEnter, spliceE) { auto evt_test = get_syscall_event_test(__NR_splice, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, spliceE) int fd_out = 1; uint64_t size = 0x123; unsigned int flags = SPLICE_F_MOVE; - assert_syscall_state(SYSCALL_FAILURE, "splice", syscall(__NR_splice, fd_in, 0, fd_out, 0, size, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "splice", + syscall(__NR_splice, fd_in, 0, fd_out, 0, size, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, spliceE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/stat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/stat_e.cpp index 89d7432f3d..2aceda8b47 100644 --- a/test/drivers/test_suites/syscall_enter_suite/stat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/stat_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_stat -TEST(SyscallEnter, statE) -{ +TEST(SyscallEnter, statE) { auto evt_test = get_syscall_event_test(__NR_stat, ENTER_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallEnter, statE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -31,7 +29,6 @@ TEST(SyscallEnter, statE) /*=============================== ASSERT PARAMETERS ===========================*/ - /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); diff --git a/test/drivers/test_suites/syscall_enter_suite/symlink_e.cpp b/test/drivers/test_suites/syscall_enter_suite/symlink_e.cpp index a60190ba64..767dae7cb6 100644 --- a/test/drivers/test_suites/syscall_enter_suite/symlink_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/symlink_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_symlink -TEST(SyscallEnter, symlinkE) -{ +TEST(SyscallEnter, symlinkE) { auto evt_test = get_syscall_event_test(__NR_symlink, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, symlinkE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/symlinkat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/symlinkat_e.cpp index ecf225be87..1596d9ee3c 100644 --- a/test/drivers/test_suites/syscall_enter_suite/symlinkat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/symlinkat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_symlinkat -TEST(SyscallEnter, symlinkatE) -{ +TEST(SyscallEnter, symlinkatE) { auto evt_test = get_syscall_event_test(__NR_symlinkat, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, symlinkatE) const char* target = NULL; int32_t mock_dirfd = 0; const char* path = NULL; - assert_syscall_state(SYSCALL_FAILURE, "symlinkat", syscall(__NR_symlinkat, target, mock_dirfd, path)); + assert_syscall_state(SYSCALL_FAILURE, + "symlinkat", + syscall(__NR_symlinkat, target, mock_dirfd, path)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, symlinkatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/tgkill_e.cpp b/test/drivers/test_suites/syscall_enter_suite/tgkill_e.cpp index ff810f5ba6..5b28b5a540 100644 --- a/test/drivers/test_suites/syscall_enter_suite/tgkill_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/tgkill_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_tgkill -TEST(SyscallEnter, tgkillE) -{ +TEST(SyscallEnter, tgkillE) { auto evt_test = get_syscall_event_test(__NR_tgkill, ENTER_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallEnter, tgkillE) int32_t mock_tgid = 0; int32_t mock_tid = 0; int32_t signal = 0; - assert_syscall_state(SYSCALL_FAILURE, "tgkill", syscall(__NR_tgkill, mock_tgid, mock_tid, signal)); + assert_syscall_state(SYSCALL_FAILURE, + "tgkill", + syscall(__NR_tgkill, mock_tgid, mock_tid, signal)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallEnter, tgkillE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/timerfd_create_e.cpp b/test/drivers/test_suites/syscall_enter_suite/timerfd_create_e.cpp index 74553b8fb5..58bc437b3b 100644 --- a/test/drivers/test_suites/syscall_enter_suite/timerfd_create_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/timerfd_create_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_timerfd_create -TEST(SyscallEnter, timerfd_createE) -{ +TEST(SyscallEnter, timerfd_createE) { auto evt_test = get_syscall_event_test(__NR_timerfd_create, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, timerfd_createE) /* `clockid` and `flags` are not caught BPF side, we always send `0` */ int clockid = -1; int flags = -1; - assert_syscall_state(SYSCALL_FAILURE,"timerfd_create", syscall(__NR_timerfd_create, clockid, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "timerfd_create", + syscall(__NR_timerfd_create, clockid, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, timerfd_createE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/tkill_e.cpp b/test/drivers/test_suites/syscall_enter_suite/tkill_e.cpp index f940d5c07b..22c70736cf 100644 --- a/test/drivers/test_suites/syscall_enter_suite/tkill_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/tkill_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_tkill -TEST(SyscallEnter, tkillE) -{ +TEST(SyscallEnter, tkillE) { auto evt_test = get_syscall_event_test(__NR_tkill, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, tkillE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/ugetrlimit_e.cpp b/test/drivers/test_suites/syscall_enter_suite/ugetrlimit_e.cpp index be2ac58c41..26871e7e0c 100644 --- a/test/drivers/test_suites/syscall_enter_suite/ugetrlimit_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/ugetrlimit_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, ugetrlimitE) -{ +TEST(SyscallEnter, ugetrlimitE) { /* Please note: * the syscall `ugetrlimit` is mapped to `PPME_SYSCALL_GETRLIMIT_E` event * like `getrlimit`. The same BPF program will be used for both the syscalls. @@ -27,8 +26,7 @@ TEST(SyscallEnter, ugetrlimitE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/umount2_e.cpp b/test/drivers/test_suites/syscall_enter_suite/umount2_e.cpp index 94032cab38..8d2a9caf02 100644 --- a/test/drivers/test_suites/syscall_enter_suite/umount2_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/umount2_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, umount2E) -{ +TEST(SyscallEnter, umount2E) { auto evt_test = get_syscall_event_test(__NR_umount2, ENTER_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallEnter, umount2E) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -34,7 +32,9 @@ TEST(SyscallEnter, umount2E) /*=============================== ASSERT PARAMETERS ===========================*/ /* Parameter 1: flags (type: PT_FLAGS32) */ - evt_test->assert_numeric_param(1, (uint32_t)(PPM_MNT_FORCE | PPM_MNT_DETACH | PPM_MNT_EXPIRE | PPM_UMOUNT_NOFOLLOW)); + evt_test->assert_numeric_param( + 1, + (uint32_t)(PPM_MNT_FORCE | PPM_MNT_DETACH | PPM_MNT_EXPIRE | PPM_UMOUNT_NOFOLLOW)); /*=============================== ASSERT PARAMETERS ===========================*/ diff --git a/test/drivers/test_suites/syscall_enter_suite/umount_e.cpp b/test/drivers/test_suites/syscall_enter_suite/umount_e.cpp index 2b92b1ae1d..587cf64325 100644 --- a/test/drivers/test_suites/syscall_enter_suite/umount_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/umount_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_umount -TEST(SyscallEnter, umountE) -{ +TEST(SyscallEnter, umountE) { auto evt_test = get_syscall_event_test(__NR_umount, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, umountE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/unlink_e.cpp b/test/drivers/test_suites/syscall_enter_suite/unlink_e.cpp index 6e16848f7c..ee3385bfac 100644 --- a/test/drivers/test_suites/syscall_enter_suite/unlink_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/unlink_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_unlink -TEST(SyscallEnter, unlinkE) -{ +TEST(SyscallEnter, unlinkE) { auto evt_test = get_syscall_event_test(__NR_unlink, ENTER_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallEnter, unlinkE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/unlinkat_e.cpp b/test/drivers/test_suites/syscall_enter_suite/unlinkat_e.cpp index 11eec417d5..4e280865ad 100644 --- a/test/drivers/test_suites/syscall_enter_suite/unlinkat_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/unlinkat_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_unlinkat -TEST(SyscallEnter, unlinkatE) -{ +TEST(SyscallEnter, unlinkatE) { auto evt_test = get_syscall_event_test(__NR_unlinkat, ENTER_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallEnter, unlinkatE) int32_t mock_dirfd = 0; const char* path = NULL; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "unlinkat", syscall(__NR_unlinkat, mock_dirfd, path, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "unlinkat", + syscall(__NR_unlinkat, mock_dirfd, path, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallEnter, unlinkatE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/unshare_e.cpp b/test/drivers/test_suites/syscall_enter_suite/unshare_e.cpp index d59a9dcee7..d993fc1db1 100644 --- a/test/drivers/test_suites/syscall_enter_suite/unshare_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/unshare_e.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallEnter, unshareE) -{ +TEST(SyscallEnter, unshareE) { auto evt_test = get_syscall_event_test(__NR_unshare, ENTER_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallEnter, unshareE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/userfaultfd_e.cpp b/test/drivers/test_suites/syscall_enter_suite/userfaultfd_e.cpp index e7cd7dbda3..3ce022e191 100644 --- a/test/drivers/test_suites/syscall_enter_suite/userfaultfd_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/userfaultfd_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_userfaultfd -TEST(SyscallEnter, userfaultfdE) -{ +TEST(SyscallEnter, userfaultfdE) { auto evt_test = get_syscall_event_test(__NR_userfaultfd, ENTER_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallEnter, userfaultfdE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/vfork_e.cpp b/test/drivers/test_suites/syscall_enter_suite/vfork_e.cpp index 696fe736a9..5bae4e3697 100644 --- a/test/drivers/test_suites/syscall_enter_suite/vfork_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/vfork_e.cpp @@ -31,7 +31,8 @@ // assert_syscall_state(SYSCALL_SUCCESS, "vfork", ret_pid, NOT_EQUAL, -1); // int status = 0; // int options = 0; -// assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); +// assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, +// NULL), NOT_EQUAL, -1); // /*=============================== TRIGGER SYSCALL ===========================*/ diff --git a/test/drivers/test_suites/syscall_enter_suite/write_e.cpp b/test/drivers/test_suites/syscall_enter_suite/write_e.cpp index 1b4cfc3d5c..8eba62fc5e 100644 --- a/test/drivers/test_suites/syscall_enter_suite/write_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/write_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_write -TEST(SyscallEnter, writeE) -{ +TEST(SyscallEnter, writeE) { auto evt_test = get_syscall_event_test(__NR_write, ENTER_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallEnter, writeE) int mock_fd = -1; char mock_buf[8]; size_t mock_count = 4096; - assert_syscall_state(SYSCALL_FAILURE, "write", syscall(__NR_write, mock_fd, (void *)(mock_buf), mock_count)); + assert_syscall_state(SYSCALL_FAILURE, + "write", + syscall(__NR_write, mock_fd, (void *)(mock_buf), mock_count)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallEnter, writeE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_enter_suite/writev_e.cpp b/test/drivers/test_suites/syscall_enter_suite/writev_e.cpp index 0ba53133bd..d27399741c 100644 --- a/test/drivers/test_suites/syscall_enter_suite/writev_e.cpp +++ b/test/drivers/test_suites/syscall_enter_suite/writev_e.cpp @@ -2,8 +2,7 @@ #ifdef __NR_writev -TEST(SyscallEnter, writevE_empty_iovec) -{ +TEST(SyscallEnter, writevE_empty_iovec) { auto evt_test = get_syscall_event_test(__NR_writev, ENTER_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallEnter, writevE_empty_iovec) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -43,8 +41,7 @@ TEST(SyscallEnter, writevE_empty_iovec) evt_test->assert_num_params_pushed(2); } -TEST(SyscallEnter, writevE_full_iovec) -{ +TEST(SyscallEnter, writevE_full_iovec) { auto evt_test = get_syscall_event_test(__NR_writev, ENTER_EVENT); evt_test->enable_capture(); @@ -65,8 +62,7 @@ TEST(SyscallEnter, writevE_full_iovec) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/accept4_x.cpp b/test/drivers/test_suites/syscall_exit_suite/accept4_x.cpp index 3424e247bf..08eed51f36 100644 --- a/test/drivers/test_suites/syscall_exit_suite/accept4_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/accept4_x.cpp @@ -1,11 +1,13 @@ #include "../../event_class/event_class.h" -#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && \ + defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && \ + defined(__NR_setsockopt) && defined(__NR_shutdown) -/* On `s390x` architectures only `accept4` (`accept` is not defined) is used so we need to test all the cases also here. */ +/* On `s390x` architectures only `accept4` (`accept` is not defined) is used so we need to test all + * the cases also here. */ -TEST(SyscallExit, accept4X_INET) -{ +TEST(SyscallExit, accept4X_INET) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -16,11 +18,14 @@ TEST(SyscallExit, accept4X_INET) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ sockaddr* addr = NULL; - socklen_t *addrlen = NULL; + socklen_t* addrlen = NULL; int flags = 0; int connected_socket_fd = syscall(__NR_accept4, server_socket_fd, addr, addrlen, flags); assert_syscall_state(SYSCALL_SUCCESS, "accept4 (server)", connected_socket_fd, NOT_EQUAL, -1); @@ -39,8 +44,7 @@ TEST(SyscallExit, accept4X_INET) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -55,7 +59,12 @@ TEST(SyscallExit, accept4X_INET) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -73,8 +82,7 @@ TEST(SyscallExit, accept4X_INET) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, accept4X_INET6) -{ +TEST(SyscallExit, accept4X_INET6) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -85,11 +93,14 @@ TEST(SyscallExit, accept4X_INET6) int32_t server_socket_fd = 0; sockaddr_in6 client_addr = {}; sockaddr_in6 server_addr = {}; - evt_test->connect_ipv6_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv6_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ sockaddr* addr = NULL; - socklen_t *addrlen = NULL; + socklen_t* addrlen = NULL; int flags = 0; int connected_socket_fd = syscall(__NR_accept4, server_socket_fd, addr, addrlen, flags); assert_syscall_state(SYSCALL_SUCCESS, "accept4 (server)", connected_socket_fd, NOT_EQUAL, -1); @@ -108,8 +119,7 @@ TEST(SyscallExit, accept4X_INET6) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -124,7 +134,12 @@ TEST(SyscallExit, accept4X_INET6) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet6_param(2, PPM_AF_INET6, IPV6_CLIENT, IPV6_SERVER, IPV6_PORT_CLIENT_STRING, IPV6_PORT_SERVER_STRING); + evt_test->assert_tuple_inet6_param(2, + PPM_AF_INET6, + IPV6_CLIENT, + IPV6_SERVER, + IPV6_PORT_CLIENT_STRING, + IPV6_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -143,8 +158,7 @@ TEST(SyscallExit, accept4X_INET6) } #ifdef __NR_unlinkat -TEST(SyscallExit, accept4X_UNIX) -{ +TEST(SyscallExit, accept4X_UNIX) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -155,11 +169,14 @@ TEST(SyscallExit, accept4X_UNIX) int32_t server_socket_fd = 0; struct sockaddr_un client_addr = {}; struct sockaddr_un server_addr = {}; - evt_test->connect_unix_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_unix_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ sockaddr* addr = NULL; - socklen_t *addrlen = NULL; + socklen_t* addrlen = NULL; int flags = 0; int connected_socket_fd = syscall(__NR_accept4, server_socket_fd, addr, addrlen, flags); assert_syscall_state(SYSCALL_SUCCESS, "accept4 (server)", connected_socket_fd, NOT_EQUAL, -1); @@ -180,8 +197,7 @@ TEST(SyscallExit, accept4X_UNIX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -215,8 +231,7 @@ TEST(SyscallExit, accept4X_UNIX) } #endif /* __NR_unlinkat */ -TEST(SyscallExit, accept4X_failure) -{ +TEST(SyscallExit, accept4X_failure) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -225,9 +240,11 @@ TEST(SyscallExit, accept4X_failure) int32_t mock_fd = -1; sockaddr* addr = NULL; - socklen_t *addrlen = NULL; + socklen_t* addrlen = NULL; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "accept4", syscall(__NR_accept4, mock_fd, addr, addrlen, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "accept4", + syscall(__NR_accept4, mock_fd, addr, addrlen, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -236,8 +253,7 @@ TEST(SyscallExit, accept4X_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/accept_x.cpp b/test/drivers/test_suites/syscall_exit_suite/accept_x.cpp index 91ff785e38..7d829b2d67 100644 --- a/test/drivers/test_suites/syscall_exit_suite/accept_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/accept_x.cpp @@ -1,9 +1,10 @@ #include "../../event_class/event_class.h" -#if defined(__NR_accept) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_accept) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && \ + defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && \ + defined(__NR_shutdown) -TEST(SyscallExit, acceptX_INET) -{ +TEST(SyscallExit, acceptX_INET) { auto evt_test = get_syscall_event_test(__NR_accept, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +15,10 @@ TEST(SyscallExit, acceptX_INET) int32_t server_socket_fd = 0; sockaddr_in client_addr = {}; sockaddr_in server_addr = {}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ int connected_socket_fd = syscall(__NR_accept, server_socket_fd, NULL, NULL); @@ -34,8 +38,7 @@ TEST(SyscallExit, acceptX_INET) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -50,7 +53,12 @@ TEST(SyscallExit, acceptX_INET) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -68,8 +76,7 @@ TEST(SyscallExit, acceptX_INET) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, acceptX_INET6) -{ +TEST(SyscallExit, acceptX_INET6) { auto evt_test = get_syscall_event_test(__NR_accept, EXIT_EVENT); evt_test->enable_capture(); @@ -80,7 +87,10 @@ TEST(SyscallExit, acceptX_INET6) int32_t server_socket_fd = 0; sockaddr_in6 client_addr = {}; sockaddr_in6 server_addr = {}; - evt_test->connect_ipv6_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv6_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ int connected_socket_fd = syscall(__NR_accept, server_socket_fd, NULL, NULL); @@ -100,8 +110,7 @@ TEST(SyscallExit, acceptX_INET6) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -116,7 +125,12 @@ TEST(SyscallExit, acceptX_INET6) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet6_param(2, PPM_AF_INET6, IPV6_CLIENT, IPV6_SERVER, IPV6_PORT_CLIENT_STRING, IPV6_PORT_SERVER_STRING); + evt_test->assert_tuple_inet6_param(2, + PPM_AF_INET6, + IPV6_CLIENT, + IPV6_SERVER, + IPV6_PORT_CLIENT_STRING, + IPV6_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -135,8 +149,7 @@ TEST(SyscallExit, acceptX_INET6) } #ifdef __NR_unlinkat -TEST(SyscallExit, acceptX_UNIX) -{ +TEST(SyscallExit, acceptX_UNIX) { auto evt_test = get_syscall_event_test(__NR_accept, EXIT_EVENT); evt_test->enable_capture(); @@ -147,7 +160,10 @@ TEST(SyscallExit, acceptX_UNIX) int32_t server_socket_fd = 0; struct sockaddr_un client_addr = {}; struct sockaddr_un server_addr = {}; - evt_test->connect_unix_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_unix_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ int connected_socket_fd = syscall(__NR_accept, server_socket_fd, NULL, NULL); @@ -169,8 +185,7 @@ TEST(SyscallExit, acceptX_UNIX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -204,8 +219,7 @@ TEST(SyscallExit, acceptX_UNIX) } #endif /* __NR_unlinkat */ -TEST(SyscallExit, acceptX_failure) -{ +TEST(SyscallExit, acceptX_failure) { auto evt_test = get_syscall_event_test(__NR_accept, EXIT_EVENT); evt_test->enable_capture(); @@ -214,7 +228,7 @@ TEST(SyscallExit, acceptX_failure) int mock_fd = -1; sockaddr* addr = NULL; - socklen_t *addrlen = NULL; + socklen_t* addrlen = NULL; assert_syscall_state(SYSCALL_FAILURE, "accept", syscall(__NR_accept, mock_fd, addr, addrlen)); int64_t errno_value = -errno; @@ -224,8 +238,7 @@ TEST(SyscallExit, acceptX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/access_x.cpp b/test/drivers/test_suites/syscall_exit_suite/access_x.cpp index af7a92388e..2491a94e91 100644 --- a/test/drivers/test_suites/syscall_exit_suite/access_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/access_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_access -TEST(SyscallExit, accessX) -{ +TEST(SyscallExit, accessX) { auto evt_test = get_syscall_event_test(__NR_access, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, accessX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/bind_x.cpp b/test/drivers/test_suites/syscall_exit_suite/bind_x.cpp index 7aa2e6b88e..1c11e23ac0 100644 --- a/test/drivers/test_suites/syscall_exit_suite/bind_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/bind_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, bindX_INET) -{ +TEST(SyscallExit, bindX_INET) { auto evt_test = get_syscall_event_test(__NR_bind, EXIT_EVENT); evt_test->enable_capture(); @@ -19,7 +18,12 @@ TEST(SyscallExit, bindX_INET) sockaddr_in server_addr; evt_test->server_fill_sockaddr_in(&server_addr); - assert_syscall_state(SYSCALL_SUCCESS, "bind", syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind", + syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, server_socket_fd); @@ -30,8 +34,7 @@ TEST(SyscallExit, bindX_INET) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -52,8 +55,7 @@ TEST(SyscallExit, bindX_INET) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, bindX_INET6) -{ +TEST(SyscallExit, bindX_INET6) { auto evt_test = get_syscall_event_test(__NR_bind, EXIT_EVENT); evt_test->enable_capture(); @@ -67,7 +69,12 @@ TEST(SyscallExit, bindX_INET6) sockaddr_in6 server_addr; evt_test->server_fill_sockaddr_in6(&server_addr); - assert_syscall_state(SYSCALL_SUCCESS, "bind", syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind", + syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, server_socket_fd); @@ -78,8 +85,7 @@ TEST(SyscallExit, bindX_INET6) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -101,8 +107,7 @@ TEST(SyscallExit, bindX_INET6) } #ifdef __NR_unlinkat -TEST(SyscallExit, bindX_UNIX) -{ +TEST(SyscallExit, bindX_UNIX) { auto evt_test = get_syscall_event_test(__NR_bind, EXIT_EVENT); evt_test->enable_capture(); @@ -115,7 +120,12 @@ TEST(SyscallExit, bindX_UNIX) struct sockaddr_un server_addr; evt_test->server_fill_sockaddr_un(&server_addr); - assert_syscall_state(SYSCALL_SUCCESS, "bind", syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind", + syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, server_socket_fd); @@ -127,8 +137,7 @@ TEST(SyscallExit, bindX_UNIX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -150,8 +159,7 @@ TEST(SyscallExit, bindX_UNIX) } #endif /* __NR_unlinkat */ -TEST(SyscallExit, bindX_failure) -{ +TEST(SyscallExit, bindX_failure) { auto evt_test = get_syscall_event_test(__NR_bind, EXIT_EVENT); evt_test->enable_capture(); @@ -170,8 +178,7 @@ TEST(SyscallExit, bindX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/bpf_x.cpp b/test/drivers/test_suites/syscall_exit_suite/bpf_x.cpp index 6e6e3091bb..85196bd18d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/bpf_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/bpf_x.cpp @@ -6,8 +6,7 @@ #include #include -TEST(SyscallExit, bpfX_invalid_cmd) -{ +TEST(SyscallExit, bpfX_invalid_cmd) { auto evt_test = get_syscall_event_test(__NR_bpf, EXIT_EVENT); evt_test->enable_capture(); @@ -25,16 +24,12 @@ TEST(SyscallExit, bpfX_invalid_cmd) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_bpf, cmd, attr, size) == -1) - { + if(syscall(__NR_bpf, cmd, attr, size) == -1) { /* SUCCESS because we want the call to fail */ exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -43,10 +38,13 @@ TEST(SyscallExit, bpfX_invalid_cmd) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The bpf call is successful while it should fail..." << std::endl; } @@ -59,8 +57,7 @@ TEST(SyscallExit, bpfX_invalid_cmd) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -81,9 +78,7 @@ TEST(SyscallExit, bpfX_invalid_cmd) evt_test->assert_num_params_pushed(2); } - -TEST(SyscallExit, bpfX_MAP_CREATE) -{ +TEST(SyscallExit, bpfX_MAP_CREATE) { auto evt_test = get_syscall_event_test(__NR_bpf, EXIT_EVENT); evt_test->enable_capture(); @@ -91,8 +86,7 @@ TEST(SyscallExit, bpfX_MAP_CREATE) /*=============================== TRIGGER SYSCALL ===========================*/ int32_t cmd = BPF_MAP_CREATE; - union bpf_attr *attr = NULL; - + union bpf_attr *attr = NULL; /* Here we need to call the `bpf` from a child because the main process throws lots of * `bpf` syscalls to manage the bpf drivers. @@ -101,16 +95,12 @@ TEST(SyscallExit, bpfX_MAP_CREATE) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_bpf, cmd, attr, sizeof(attr) == -1)) - { + if(syscall(__NR_bpf, cmd, attr, sizeof(attr) == -1)) { /* SUCCESS because we want the call to fail */ exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -119,10 +109,13 @@ TEST(SyscallExit, bpfX_MAP_CREATE) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The bpf call is successful while it should fail..." << std::endl; } @@ -134,8 +127,7 @@ TEST(SyscallExit, bpfX_MAP_CREATE) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/brk_x.cpp b/test/drivers/test_suites/syscall_exit_suite/brk_x.cpp index b9f6df8b65..25e9061f2f 100644 --- a/test/drivers/test_suites/syscall_exit_suite/brk_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/brk_x.cpp @@ -2,8 +2,7 @@ #ifdef __NR_brk -TEST(SyscallExit, brkX) -{ +TEST(SyscallExit, brkX) { auto evt_test = get_syscall_event_test(__NR_brk, EXIT_EVENT); evt_test->enable_capture(); @@ -11,8 +10,8 @@ TEST(SyscallExit, brkX) /*=============================== TRIGGER SYSCALL ===========================*/ unsigned long addr = 0; - /* brk returns the new program break on success. On failure, the system call returns the current break, - * so we cannot assert its failure + /* brk returns the new program break on success. On failure, the system call returns the + * current break, so we cannot assert its failure */ syscall(__NR_brk, addr); @@ -22,8 +21,7 @@ TEST(SyscallExit, brkX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/capset_x.cpp b/test/drivers/test_suites/syscall_exit_suite/capset_x.cpp index 721bd90e2e..813edd9bda 100644 --- a/test/drivers/test_suites/syscall_exit_suite/capset_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/capset_x.cpp @@ -2,8 +2,7 @@ #include "../../flags/flags_definitions.h" #ifdef __NR_capset -TEST(SyscallExit, capsetX) -{ +TEST(SyscallExit, capsetX) { auto evt_test = get_syscall_event_test(__NR_capset, EXIT_EVENT); evt_test->enable_capture(); @@ -39,8 +38,7 @@ TEST(SyscallExit, capsetX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -54,13 +52,22 @@ TEST(SyscallExit, capsetX) evt_test->assert_numeric_param(1, (int64_t)errno_value); /* Parameter 2: cap_inheritable (type: PT_UINT64) */ - evt_test->assert_numeric_param(2, (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | data[0].inheritable)); + evt_test->assert_numeric_param( + 2, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | + data[0].inheritable)); /* Parameter 3: cap_permitted (type: PT_UINT64) */ - evt_test->assert_numeric_param(3, (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | data[0].permitted)); + evt_test->assert_numeric_param( + 3, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | + data[0].permitted)); /* Parameter 4: cap_effective (type: PT_UINT64) */ - evt_test->assert_numeric_param(4, (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | data[0].effective)); + evt_test->assert_numeric_param( + 4, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | + data[0].effective)); /*=============================== ASSERT PARAMETERS ===========================*/ diff --git a/test/drivers/test_suites/syscall_exit_suite/chdir_x.cpp b/test/drivers/test_suites/syscall_exit_suite/chdir_x.cpp index 2ffb6bf12a..9f274e2a3b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/chdir_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/chdir_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chdir -TEST(SyscallExit, chdirX) -{ +TEST(SyscallExit, chdirX) { auto evt_test = get_syscall_event_test(__NR_chdir, EXIT_EVENT); evt_test->enable_capture(); @@ -25,8 +24,7 @@ TEST(SyscallExit, chdirX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/chmod_x.cpp b/test/drivers/test_suites/syscall_exit_suite/chmod_x.cpp index 523239ccd3..705ce171a3 100644 --- a/test/drivers/test_suites/syscall_exit_suite/chmod_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/chmod_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chmod -TEST(SyscallExit, chmodX) -{ +TEST(SyscallExit, chmodX) { auto evt_test = get_syscall_event_test(__NR_chmod, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, chmodX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/chown_x.cpp b/test/drivers/test_suites/syscall_exit_suite/chown_x.cpp index 0683eaf705..36a9c053e5 100644 --- a/test/drivers/test_suites/syscall_exit_suite/chown_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/chown_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chown -TEST(SyscallExit, chownX) -{ +TEST(SyscallExit, chownX) { auto evt_test = get_syscall_event_test(__NR_chown, EXIT_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallExit, chownX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/chroot_x.cpp b/test/drivers/test_suites/syscall_exit_suite/chroot_x.cpp index df8c301c9d..35ea7328ec 100644 --- a/test/drivers/test_suites/syscall_exit_suite/chroot_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/chroot_x.cpp @@ -1,9 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_chroot -TEST(SyscallExit, chrootX) -{ - +TEST(SyscallExit, chrootX) { auto evt_test = get_syscall_event_test(__NR_chroot, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +18,7 @@ TEST(SyscallExit, chrootX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/clock_gettime_x.cpp b/test/drivers/test_suites/syscall_exit_suite/clock_gettime_x.cpp index ae1e2d1e11..2abdcf0ef6 100644 --- a/test/drivers/test_suites/syscall_exit_suite/clock_gettime_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/clock_gettime_x.cpp @@ -2,8 +2,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_clock_gettime -TEST(SyscallExit, clock_gettime_X) -{ +TEST(SyscallExit, clock_gettime_X) { auto evt_test = get_syscall_event_test(__NR_clock_gettime, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, clock_gettime_X) /* Retrieve events in order. */ evt_test->assert_event_presence(CURRENT_PID, PPME_GENERIC_X); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/clone3_x.cpp b/test/drivers/test_suites/syscall_exit_suite/clone3_x.cpp index 97fc52dbcc..52bb7a4b5c 100644 --- a/test/drivers/test_suites/syscall_exit_suite/clone3_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/clone3_x.cpp @@ -5,8 +5,7 @@ #include -TEST(SyscallExit, clone3X_father) -{ +TEST(SyscallExit, clone3X_father) { auto evt_test = get_syscall_event_test(__NR_clone3, EXIT_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallExit, clone3X_father) */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -31,8 +29,7 @@ TEST(SyscallExit, clone3X_father) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -41,8 +38,11 @@ TEST(SyscallExit, clone3X_father) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -50,8 +50,7 @@ TEST(SyscallExit, clone3X_father) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -134,8 +133,7 @@ TEST(SyscallExit, clone3X_father) evt_test->assert_num_params_pushed(21); } -TEST(SyscallExit, clone3X_child) -{ +TEST(SyscallExit, clone3X_child) { auto evt_test = get_syscall_event_test(__NR_clone3, EXIT_EVENT); evt_test->enable_capture(); @@ -145,8 +143,7 @@ TEST(SyscallExit, clone3X_child) /* Here we scan the parent just to obtain some info for the child */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -159,8 +156,7 @@ TEST(SyscallExit, clone3X_child) pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); /* Child performs assertions on itself. */ - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -169,11 +165,13 @@ TEST(SyscallExit, clone3X_child) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -193,8 +191,7 @@ TEST(SyscallExit, clone3X_child) #else evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -208,7 +205,7 @@ TEST(SyscallExit, clone3X_child) evt_test->assert_numeric_param(1, (int64_t)0); /* Parameter 2: exe (type: PT_CHARBUF) */ -#ifndef __powerpc64__ // Page faults +#ifndef __powerpc64__ // Page faults evt_test->assert_charbuf_param(2, info.args[0]); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ @@ -237,7 +234,7 @@ TEST(SyscallExit, clone3X_child) evt_test->assert_cgroup_param(15); /* Parameter 16: flags (type: PT_FLAGS32) */ -#ifndef __powerpc64__ // Page faults +#ifndef __powerpc64__ // Page faults evt_test->assert_numeric_param(16, (uint32_t)PPM_CL_CLONE_FILES); #endif @@ -254,8 +251,7 @@ TEST(SyscallExit, clone3X_child) * we should also have the `set_tid` field in struct `clone_args` */ #ifdef CLONE_CLEAR_SIGHAND -TEST(SyscallExit, clone3X_create_child_with_2_threads) -{ +TEST(SyscallExit, clone3X_create_child_with_2_threads) { auto evt_test = get_syscall_event_test(__NR_clone3, EXIT_EVENT); evt_test->enable_capture(); @@ -276,8 +272,7 @@ TEST(SyscallExit, clone3X_create_child_with_2_threads) pid_t ret_pid = syscall(__NR_clone3, &cl_args_parent, sizeof(cl_args_parent)); /* Create a child process that will spawn a new thread */ - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Spawn a new thread */ clone_args cl_args_child = {}; cl_args_child.set_tid = (uint64_t)&p1_t2; @@ -288,8 +283,7 @@ TEST(SyscallExit, clone3X_create_child_with_2_threads) */ cl_args_child.flags = CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_VFORK | CLONE_PARENT; pid_t child_thread = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(child_thread == 0) - { + if(child_thread == 0) { exit(EXIT_SUCCESS); } exit(EXIT_SUCCESS); @@ -299,11 +293,13 @@ TEST(SyscallExit, clone3X_create_child_with_2_threads) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } /*=============================== TRIGGER SYSCALL ===========================*/ @@ -315,8 +311,7 @@ TEST(SyscallExit, clone3X_create_child_with_2_threads) #else evt_test->assert_event_presence(p1_t2); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { FAIL() << "There is a fatal failure in the child"; } @@ -344,8 +339,10 @@ TEST(SyscallExit, clone3X_create_child_with_2_threads) evt_test->assert_numeric_param(6, (int64_t)::gettid()); /* Parameter 16: flags (type: PT_FLAGS32) */ - evt_test->assert_numeric_param(16, (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM | - PPM_CL_CLONE_VFORK | PPM_CL_CLONE_PARENT); + evt_test->assert_numeric_param(16, + (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | + PPM_CL_CLONE_VM | PPM_CL_CLONE_VFORK | + PPM_CL_CLONE_PARENT); /* Parameter 19: vtid (type: PT_PID) */ evt_test->assert_numeric_param(19, (int64_t)p1_t2); @@ -359,8 +356,7 @@ TEST(SyscallExit, clone3X_create_child_with_2_threads) #endif } -TEST(SyscallExit, clone3X_child_clone_parent_flag) -{ +TEST(SyscallExit, clone3X_child_clone_parent_flag) { auto evt_test = get_syscall_event_test(__NR_clone3, EXIT_EVENT); evt_test->enable_capture(); @@ -380,20 +376,17 @@ TEST(SyscallExit, clone3X_child_clone_parent_flag) cl_args_parent.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args_parent, sizeof(cl_args_parent)); - if(ret_pid == 0) - { + if(ret_pid == 0) { clone_args cl_args_child = {}; cl_args_child.set_tid = (uint64_t)&p2_t1; cl_args_child.set_tid_size = 1; cl_args_child.flags = CLONE_PARENT; cl_args_parent.exit_signal = SIGCHLD; pid_t second_child = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(second_child == 0) - { + if(second_child == 0) { exit(EXIT_SUCCESS); } - if(second_child == -1) - { + if(second_child == -1) { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); @@ -405,20 +398,25 @@ TEST(SyscallExit, clone3X_child_clone_parent_flag) int options = 0; /* Wait for the first child */ - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the first child failed." << std::endl; } - /* Since we are using the `CLONE_PARENT` flag the currect process is signaled also for the second child */ - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, p2_t1, &status, options, NULL), NOT_EQUAL, - -1); + /* Since we are using the `CLONE_PARENT` flag the currect process is signaled also for the + * second child */ + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, p2_t1, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the second child failed." << std::endl; } @@ -431,8 +429,7 @@ TEST(SyscallExit, clone3X_child_clone_parent_flag) #else evt_test->assert_event_presence(p2_t1); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -456,7 +453,7 @@ TEST(SyscallExit, clone3X_child_clone_parent_flag) evt_test->assert_numeric_param(6, (int64_t)::gettid()); /* Parameter 16: flags (type: PT_FLAGS32) */ -#ifndef __powerpc64__ // Page fault +#ifndef __powerpc64__ // Page fault evt_test->assert_numeric_param(16, (uint32_t)PPM_CL_CLONE_PARENT); #endif /* Parameter 19: vtid (type: PT_PID) */ @@ -471,8 +468,7 @@ TEST(SyscallExit, clone3X_child_clone_parent_flag) #endif } -TEST(SyscallExit, clone3X_child_new_namespace_from_child) -{ +TEST(SyscallExit, clone3X_child_new_namespace_from_child) { auto evt_test = get_syscall_event_test(__NR_clone3, EXIT_EVENT); evt_test->enable_capture(); @@ -489,8 +485,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_child) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -499,11 +494,13 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_child) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -516,8 +513,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_child) #else evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -540,7 +536,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_child) evt_test->assert_numeric_param(6, (int64_t)::gettid()); /* Parameter 16: flags (type: PT_FLAGS32) */ -#ifndef __powerpc64__ // Page fault +#ifndef __powerpc64__ // Page fault evt_test->assert_numeric_param(16, (uint32_t)PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS); #endif /* Parameter 19: vtid (type: PT_PID) */ @@ -555,8 +551,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_child) #endif } -TEST(SyscallExit, clone3X_child_new_namespace_from_caller) -{ +TEST(SyscallExit, clone3X_child_new_namespace_from_caller) { auto evt_test = get_syscall_event_test(__NR_clone3, EXIT_EVENT); evt_test->enable_capture(); @@ -573,8 +568,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_caller) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -583,11 +577,13 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_caller) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -597,8 +593,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_caller) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -632,8 +627,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_from_caller) evt_test->assert_num_params_pushed(21); } -TEST(SyscallExit, clone3X_child_new_namespace_create_thread) -{ +TEST(SyscallExit, clone3X_child_new_namespace_create_thread) { auto evt_test = get_syscall_event_test(__NR_clone3, EXIT_EVENT); evt_test->enable_capture(); @@ -655,16 +649,14 @@ TEST(SyscallExit, clone3X_child_new_namespace_create_thread) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Spawn a new thread */ clone_args cl_args_child = {}; cl_args_child.set_tid = (uint64_t)&p1_t2; cl_args_child.set_tid_size = 2; cl_args_child.flags = CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_VFORK; pid_t child_thread = syscall(__NR_clone3, &cl_args_child, sizeof(cl_args_child)); - if(child_thread == 0) - { + if(child_thread == 0) { exit(EXIT_SUCCESS); } exit(EXIT_SUCCESS); @@ -674,11 +666,13 @@ TEST(SyscallExit, clone3X_child_new_namespace_create_thread) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -691,8 +685,7 @@ TEST(SyscallExit, clone3X_child_new_namespace_create_thread) #else evt_test->assert_event_presence(p1_t2[1]); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -715,8 +708,10 @@ TEST(SyscallExit, clone3X_child_new_namespace_create_thread) evt_test->assert_numeric_param(6, (int64_t)::gettid()); /* Parameter 16: flags (type: PT_FLAGS32) */ - evt_test->assert_numeric_param(16, (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | PPM_CL_CLONE_VM | - PPM_CL_CLONE_VFORK | PPM_CL_CHILD_IN_PIDNS); + evt_test->assert_numeric_param(16, + (uint32_t)PPM_CL_CLONE_THREAD | PPM_CL_CLONE_SIGHAND | + PPM_CL_CLONE_VM | PPM_CL_CLONE_VFORK | + PPM_CL_CHILD_IN_PIDNS); /* Parameter 19: vtid (type: PT_PID) */ evt_test->assert_numeric_param(19, (int64_t)p1_t2[0]); diff --git a/test/drivers/test_suites/syscall_exit_suite/clone_x.cpp b/test/drivers/test_suites/syscall_exit_suite/clone_x.cpp index 3b7f9e8027..cd61c08018 100644 --- a/test/drivers/test_suites/syscall_exit_suite/clone_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/clone_x.cpp @@ -3,8 +3,7 @@ #if defined(__NR_clone) && defined(__NR_wait4) -TEST(SyscallExit, cloneX_father) -{ +TEST(SyscallExit, cloneX_father) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -16,8 +15,7 @@ TEST(SyscallExit, cloneX_father) */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -31,30 +29,22 @@ TEST(SyscallExit, cloneX_father) unsigned long tls = 0; pid_t ret_pid = 0; - /* Please note: Some systems are compiled with kernel config like `CONFIG_CLONE_BACKWARDS2`, so the order of clone params - * is not the same as for all architectures. `/kernel/fork.c` from kernel source tree. + /* Please note: Some systems are compiled with kernel config like `CONFIG_CLONE_BACKWARDS2`, so + *the order of clone params is not the same as for all architectures. `/kernel/fork.c` from + *kernel source tree. * * #ifdef CONFIG_CLONE_BACKWARDS - * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `aarch64` and `riscv` systems use this. - * int __user *, parent_tidptr, - * unsigned long, tls, - * int __user *, child_tidptr) - * #elif defined(CONFIG_CLONE_BACKWARDS2) - * SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags, <-- `s390x` systems use this. - * int __user *, parent_tidptr, - * int __user *, child_tidptr, - * unsigned long, tls) - * #elif defined(CONFIG_CLONE_BACKWARDS3) - * SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp, - * int, stack_size, - * int __user *, parent_tidptr, - * int __user *, child_tidptr, + * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `aarch64` + *and `riscv` systems use this. int __user *, parent_tidptr, unsigned long, tls, int __user *, + *child_tidptr) #elif defined(CONFIG_CLONE_BACKWARDS2) SYSCALL_DEFINE5(clone, unsigned long, + *newsp, unsigned long, clone_flags, <-- `s390x` systems use this. int __user *, + *parent_tidptr, int __user *, child_tidptr, unsigned long, tls) #elif + *defined(CONFIG_CLONE_BACKWARDS3) SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned + *long, newsp, int, stack_size, int __user *, parent_tidptr, int __user *, child_tidptr, * unsigned long, tls) * #else - * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `x86_64` systems use this. - * int __user *, parent_tidptr, - * int __user *, child_tidptr, - * unsigned long, tls) + * SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, <-- `x86_64` + *systems use this. int __user *, parent_tidptr, int __user *, child_tidptr, unsigned long, tls) * #endif * */ @@ -66,8 +56,7 @@ TEST(SyscallExit, cloneX_father) ret_pid = syscall(__NR_clone, test_clone_flags, newsp, &parent_tid, &child_tid, tls); #endif - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -77,7 +66,11 @@ TEST(SyscallExit, cloneX_father) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -85,8 +78,7 @@ TEST(SyscallExit, cloneX_father) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -169,8 +161,7 @@ TEST(SyscallExit, cloneX_father) evt_test->assert_num_params_pushed(21); } -TEST(SyscallExit, cloneX_child) -{ +TEST(SyscallExit, cloneX_child) { auto evt_test = get_syscall_event_test(__NR_clone, EXIT_EVENT); evt_test->enable_capture(); @@ -180,8 +171,7 @@ TEST(SyscallExit, cloneX_child) /* Here we scan the parent just to obtain some info for the child */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -203,8 +193,7 @@ TEST(SyscallExit, cloneX_child) ret_pid = syscall(__NR_clone, test_clone_flags, newsp, &parent_tid, &child_tid, tls); #endif - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -213,9 +202,12 @@ TEST(SyscallExit, cloneX_child) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -225,8 +217,7 @@ TEST(SyscallExit, cloneX_child) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -240,7 +231,7 @@ TEST(SyscallExit, cloneX_child) evt_test->assert_numeric_param(1, (int64_t)0); /* Parameter 2: exe (type: PT_CHARBUF) */ -#ifndef __powerpc64__ // Page fault +#ifndef __powerpc64__ // Page fault evt_test->assert_charbuf_param(2, info.args[0]); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ diff --git a/test/drivers/test_suites/syscall_exit_suite/close_x.cpp b/test/drivers/test_suites/syscall_exit_suite/close_x.cpp index 36b5869bf2..cabfa77584 100644 --- a/test/drivers/test_suites/syscall_exit_suite/close_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/close_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_close -TEST(SyscallExit, closeX) -{ +TEST(SyscallExit, closeX) { auto evt_test = get_syscall_event_test(__NR_close, EXIT_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallExit, closeX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/connect_x.cpp b/test/drivers/test_suites/syscall_exit_suite/connect_x.cpp index d7f81fd045..1526e16776 100644 --- a/test/drivers/test_suites/syscall_exit_suite/connect_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/connect_x.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallExit, connectX_INET) -{ +TEST(SyscallExit, connectX_INET) { auto evt_test = get_syscall_event_test(__NR_connect, EXIT_EVENT); evt_test->enable_capture(); @@ -21,14 +20,25 @@ TEST(SyscallExit, connectX_INET) evt_test->client_fill_sockaddr_in(&client_addr); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), + NOT_EQUAL, + -1); /* Now we associate the client socket with the server address. */ sockaddr_in server_addr; evt_test->server_fill_sockaddr_in(&server_addr); - /* With `SOCK_DGRAM` the `connect` will not perform a connection this is why the syscall doesn't fail. */ - assert_syscall_state(SYSCALL_SUCCESS, "connect (client)", syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + /* With `SOCK_DGRAM` the `connect` will not perform a connection this is why the syscall doesn't + * fail. */ + assert_syscall_state( + SYSCALL_SUCCESS, + "connect (client)", + syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, client_socket_fd); @@ -39,8 +49,7 @@ TEST(SyscallExit, connectX_INET) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -55,7 +64,12 @@ TEST(SyscallExit, connectX_INET) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The client performs a `connect` so the client is the src. */ - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 3: fd (type: PT_FD) */ evt_test->assert_numeric_param(3, (int64_t)client_socket_fd); @@ -65,8 +79,7 @@ TEST(SyscallExit, connectX_INET) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, connectX_INET6) -{ +TEST(SyscallExit, connectX_INET6) { auto evt_test = get_syscall_event_test(__NR_connect, EXIT_EVENT); evt_test->enable_capture(); @@ -81,13 +94,23 @@ TEST(SyscallExit, connectX_INET6) evt_test->client_fill_sockaddr_in6(&client_addr); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), + NOT_EQUAL, + -1); sockaddr_in6 server_addr; evt_test->server_fill_sockaddr_in6(&server_addr); /* Now we associate the client socket with the server address. */ - assert_syscall_state(SYSCALL_SUCCESS, "connect (client)", syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "connect (client)", + syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, client_socket_fd); @@ -98,8 +121,7 @@ TEST(SyscallExit, connectX_INET6) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -114,7 +136,12 @@ TEST(SyscallExit, connectX_INET6) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The client performs a `connect` so the client is the src. */ - evt_test->assert_tuple_inet6_param(2, PPM_AF_INET6, IPV6_CLIENT, IPV6_SERVER, IPV6_PORT_CLIENT_STRING, IPV6_PORT_SERVER_STRING); + evt_test->assert_tuple_inet6_param(2, + PPM_AF_INET6, + IPV6_CLIENT, + IPV6_SERVER, + IPV6_PORT_CLIENT_STRING, + IPV6_PORT_SERVER_STRING); /* Parameter 3: fd (type: PT_FD) */ evt_test->assert_numeric_param(3, (int64_t)client_socket_fd); @@ -125,8 +152,7 @@ TEST(SyscallExit, connectX_INET6) } #ifdef __NR_unlinkat -TEST(SyscallExit, connectX_UNIX) -{ +TEST(SyscallExit, connectX_UNIX) { auto evt_test = get_syscall_event_test(__NR_connect, EXIT_EVENT); evt_test->enable_capture(); @@ -140,7 +166,12 @@ TEST(SyscallExit, connectX_UNIX) evt_test->client_fill_sockaddr_un(&client_addr); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), + NOT_EQUAL, + -1); /* We need to create a server socket. */ int32_t server_socket_fd = syscall(__NR_socket, AF_UNIX, SOCK_DGRAM, 0); @@ -149,9 +180,19 @@ TEST(SyscallExit, connectX_UNIX) struct sockaddr_un server_addr; evt_test->server_fill_sockaddr_un(&server_addr); - assert_syscall_state(SYSCALL_SUCCESS, "bind (server)", syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (server)", + syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); - assert_syscall_state(SYSCALL_SUCCESS, "connect (client)", syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "connect (client)", + syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, client_socket_fd); @@ -165,8 +206,7 @@ TEST(SyscallExit, connectX_UNIX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -192,8 +232,7 @@ TEST(SyscallExit, connectX_UNIX) } #endif /* __NR_unlinkat */ -TEST(SyscallExit, connectX_failure) -{ +TEST(SyscallExit, connectX_failure) { auto evt_test = get_syscall_event_test(__NR_connect, EXIT_EVENT); evt_test->enable_capture(); @@ -212,8 +251,7 @@ TEST(SyscallExit, connectX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -237,8 +275,7 @@ TEST(SyscallExit, connectX_failure) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, connectX_failure_ECONNREFUSED) -{ +TEST(SyscallExit, connectX_failure_ECONNREFUSED) { auto evt_test = get_syscall_event_test(__NR_connect, EXIT_EVENT); evt_test->enable_capture(); @@ -253,13 +290,21 @@ TEST(SyscallExit, connectX_failure_ECONNREFUSED) evt_test->client_fill_sockaddr_in(&client_addr); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), + NOT_EQUAL, + -1); /* We try to reach this server that doesn't exist */ sockaddr_in server_addr; evt_test->server_fill_sockaddr_in(&server_addr); - assert_syscall_state(SYSCALL_FAILURE, "connect (client)", syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr))); + assert_syscall_state( + SYSCALL_FAILURE, + "connect (client)", + syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -267,8 +312,7 @@ TEST(SyscallExit, connectX_failure_ECONNREFUSED) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -283,13 +327,15 @@ TEST(SyscallExit, connectX_failure_ECONNREFUSED) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* Modern BPF doesn't return the tuple in case of failure */ - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { evt_test->assert_empty_param(2); - } - else - { - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + } else { + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); } /* Parameter 3: fd (type: PT_FD) */ @@ -300,8 +346,7 @@ TEST(SyscallExit, connectX_failure_ECONNREFUSED) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, connectX_failure_EINPROGRESS) -{ +TEST(SyscallExit, connectX_failure_EINPROGRESS) { auto evt_test = get_syscall_event_test(__NR_connect, EXIT_EVENT); evt_test->enable_capture(); @@ -316,7 +361,12 @@ TEST(SyscallExit, connectX_failure_EINPROGRESS) sockaddr_in client_addr; evt_test->client_fill_sockaddr_in(&client_addr); - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), + NOT_EQUAL, + -1); int32_t server_socket_fd = syscall(__NR_socket, AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); assert_syscall_state(SYSCALL_SUCCESS, "socket (server)", server_socket_fd, NOT_EQUAL, -1); @@ -326,13 +376,21 @@ TEST(SyscallExit, connectX_failure_EINPROGRESS) evt_test->server_fill_sockaddr_in(&server_addr); /* Now we bind the server socket with the server address. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (server)", syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (server)", + syscall(__NR_bind, server_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr)), + NOT_EQUAL, + -1); /* Here we don't call listen so the connection from the client should be * in progress. */ - assert_syscall_state(SYSCALL_FAILURE, "connect (client)", syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr))); + assert_syscall_state( + SYSCALL_FAILURE, + "connect (client)", + syscall(__NR_connect, client_socket_fd, (sockaddr*)&server_addr, sizeof(server_addr))); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -340,8 +398,7 @@ TEST(SyscallExit, connectX_failure_EINPROGRESS) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -358,7 +415,12 @@ TEST(SyscallExit, connectX_failure_EINPROGRESS) /* `EINPROGRESS` is the unique failure case that the modern bpf probe * can catch. */ - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 3: fd (type: PT_FD) */ evt_test->assert_numeric_param(3, (int64_t)client_socket_fd); diff --git a/test/drivers/test_suites/syscall_exit_suite/copy_file_range_x.cpp b/test/drivers/test_suites/syscall_exit_suite/copy_file_range_x.cpp index 369cbd5d27..078a9e81e6 100644 --- a/test/drivers/test_suites/syscall_exit_suite/copy_file_range_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/copy_file_range_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_copy_file_range -TEST(SyscallExit, copy_file_rangeX) -{ +TEST(SyscallExit, copy_file_rangeX) { auto evt_test = get_syscall_event_test(__NR_copy_file_range, EXIT_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallExit, copy_file_rangeX) off64_t off_out = 300; size_t len = 20; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "copy_file_range", syscall(__NR_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "copy_file_range", + syscall(__NR_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallExit, copy_file_rangeX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/creat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/creat_x.cpp index 2334aeab87..535ca1643b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/creat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/creat_x.cpp @@ -3,8 +3,7 @@ #ifdef __NR_creat #if defined(__NR_fstat) && defined(__NR_unlinkat) && defined(__NR_close) -TEST(SyscallExit, creatX_success) -{ +TEST(SyscallExit, creatX_success) { auto evt_test = get_syscall_event_test(__NR_creat, EXIT_EVENT); evt_test->enable_capture(); @@ -18,7 +17,11 @@ TEST(SyscallExit, creatX_success) /* Call `fstat` to retrieve the `dev` and `ino`. */ struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, fd, &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, fd, &file_stat), + NOT_EQUAL, + -1); uint32_t dev = (uint32_t)file_stat.st_dev; uint64_t inode = file_stat.st_ino; const bool is_ext4 = event_test::is_ext4_fs(fd); @@ -34,8 +37,7 @@ TEST(SyscallExit, creatX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -55,8 +57,7 @@ TEST(SyscallExit, creatX_success) evt_test->assert_numeric_param(3, (uint32_t)(PPM_S_IRUSR | PPM_S_IWUSR | PPM_S_IXUSR)); /* Parameter 4: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(4, (uint32_t)dev); } @@ -72,8 +73,7 @@ TEST(SyscallExit, creatX_success) } #endif /* defined(__NR_fstat) && defined(__NR_unlinkat) && defined(__NR_close) */ -TEST(SyscallExit, creatX_failure) -{ +TEST(SyscallExit, creatX_failure) { auto evt_test = get_syscall_event_test(__NR_creat, EXIT_EVENT); evt_test->enable_capture(); @@ -91,8 +91,7 @@ TEST(SyscallExit, creatX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/delete_module_x.cpp b/test/drivers/test_suites/syscall_exit_suite/delete_module_x.cpp index c31a6c36f8..bd2429e706 100644 --- a/test/drivers/test_suites/syscall_exit_suite/delete_module_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/delete_module_x.cpp @@ -3,8 +3,7 @@ #if defined(__NR_delete_module) #include -TEST(SyscallExit, delete_moduleX_failure) -{ +TEST(SyscallExit, delete_moduleX_failure) { const char* module_name = "test_module"; auto evt_test = get_syscall_event_test(__NR_delete_module, EXIT_EVENT); @@ -15,7 +14,9 @@ TEST(SyscallExit, delete_moduleX_failure) /* * Call the `delete_module` syscall */ - assert_syscall_state(SYSCALL_FAILURE, "delete_module", syscall(__NR_delete_module, module_name, O_TRUNC | O_NONBLOCK)); + assert_syscall_state(SYSCALL_FAILURE, + "delete_module", + syscall(__NR_delete_module, module_name, O_TRUNC | O_NONBLOCK)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallExit, delete_moduleX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -49,4 +49,4 @@ TEST(SyscallExit, delete_moduleX_failure) evt_test->assert_num_params_pushed(3); } -#endif /* __NR_delete_module */ \ No newline at end of file +#endif /* __NR_delete_module */ diff --git a/test/drivers/test_suites/syscall_exit_suite/dup2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/dup2_x.cpp index 84495aeafe..1d625f72e1 100644 --- a/test/drivers/test_suites/syscall_exit_suite/dup2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/dup2_x.cpp @@ -3,8 +3,7 @@ #include #if defined(__NR_dup2) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallExit, dup2X) -{ +TEST(SyscallExit, dup2X) { auto evt_test = get_syscall_event_test(__NR_dup2, EXIT_EVENT); evt_test->enable_capture(); @@ -27,8 +26,7 @@ TEST(SyscallExit, dup2X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/dup3_x.cpp b/test/drivers/test_suites/syscall_exit_suite/dup3_x.cpp index bbefe514b8..30279f59d9 100644 --- a/test/drivers/test_suites/syscall_exit_suite/dup3_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/dup3_x.cpp @@ -2,8 +2,7 @@ #include "../../helpers/file_opener.h" #if defined(__NR_dup3) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallExit, dup3X) -{ +TEST(SyscallExit, dup3X) { auto evt_test = get_syscall_event_test(__NR_dup3, EXIT_EVENT); evt_test->enable_capture(); @@ -29,8 +28,7 @@ TEST(SyscallExit, dup3X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/dup_x.cpp b/test/drivers/test_suites/syscall_exit_suite/dup_x.cpp index 71fc00bcbd..38ef09e54c 100644 --- a/test/drivers/test_suites/syscall_exit_suite/dup_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/dup_x.cpp @@ -2,8 +2,7 @@ #include "../../helpers/file_opener.h" #if defined(__NR_dup) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallExit, dupX) -{ +TEST(SyscallExit, dupX) { auto evt_test = get_syscall_event_test(__NR_dup, EXIT_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallExit, dupX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/epoll_create1_x.cpp b/test/drivers/test_suites/syscall_exit_suite/epoll_create1_x.cpp index e3051a2e81..c7d1275f8e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/epoll_create1_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/epoll_create1_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_epoll_create1) && defined(__NR_close) -TEST(SyscallExit, epoll_create1X) -{ +TEST(SyscallExit, epoll_create1X) { auto evt_test = get_syscall_event_test(__NR_epoll_create1, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, epoll_create1X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/epoll_create_x.cpp b/test/drivers/test_suites/syscall_exit_suite/epoll_create_x.cpp index f9856ae40a..c5f85b08c6 100644 --- a/test/drivers/test_suites/syscall_exit_suite/epoll_create_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/epoll_create_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_epoll_create) && defined(__NR_close) -TEST(SyscallExit, epoll_createX) -{ +TEST(SyscallExit, epoll_createX) { auto evt_test = get_syscall_event_test(__NR_epoll_create, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, epoll_createX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/epoll_wait_x.cpp b/test/drivers/test_suites/syscall_exit_suite/epoll_wait_x.cpp index fa001c5cb6..6f88c4a50f 100644 --- a/test/drivers/test_suites/syscall_exit_suite/epoll_wait_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/epoll_wait_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_epoll_wait -TEST(SyscallExit, epoll_waitX) -{ +TEST(SyscallExit, epoll_waitX) { auto evt_test = get_syscall_event_test(__NR_epoll_wait, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallExit, epoll_waitX) void* events = NULL; int maxevents = -1; int timeout = 0; - assert_syscall_state(SYSCALL_FAILURE, "epoll_wait", syscall(__NR_epoll_wait, epfd, events, maxevents, timeout)); + assert_syscall_state(SYSCALL_FAILURE, + "epoll_wait", + syscall(__NR_epoll_wait, epfd, events, maxevents, timeout)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallExit, epoll_waitX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/eventfd2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/eventfd2_x.cpp index 76f6f12be1..414756146c 100644 --- a/test/drivers/test_suites/syscall_exit_suite/eventfd2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/eventfd2_x.cpp @@ -2,8 +2,7 @@ #if defined(__NR_eventfd2) && defined(__NR_close) #include -TEST(SyscallExit, eventfd2X_success) -{ +TEST(SyscallExit, eventfd2X_success) { auto evt_test = get_syscall_event_test(__NR_eventfd2, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, eventfd2X_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -45,8 +43,7 @@ TEST(SyscallExit, eventfd2X_success) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, eventfd2X_failure) -{ +TEST(SyscallExit, eventfd2X_failure) { auto evt_test = get_syscall_event_test(__NR_eventfd2, EXIT_EVENT); evt_test->enable_capture(); @@ -64,8 +61,7 @@ TEST(SyscallExit, eventfd2X_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/eventfd_x.cpp b/test/drivers/test_suites/syscall_exit_suite/eventfd_x.cpp index b08b6c3bd9..5878afa3a0 100644 --- a/test/drivers/test_suites/syscall_exit_suite/eventfd_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/eventfd_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_eventfd) && defined(__NR_close) -TEST(SyscallExit, eventfdX) -{ +TEST(SyscallExit, eventfdX) { auto evt_test = get_syscall_event_test(__NR_eventfd, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, eventfdX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/execve_x.cpp b/test/drivers/test_suites/syscall_exit_suite/execve_x.cpp index e3e07adb96..49ef28a5c4 100644 --- a/test/drivers/test_suites/syscall_exit_suite/execve_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/execve_x.cpp @@ -7,119 +7,106 @@ #include -#define CREATE_OVERLAY_FS \ - \ - /* Create temp directories */ \ - char work[] = "/tmp/work.XXXXXX"; \ - char lower[] = "/tmp/lower.XXXXXX"; \ - char upper[] = "/tmp/upper.XXXXXX"; \ - char merge[] = "/tmp/overlay.XXXXXX"; \ - \ - char *workdir = mkdtemp(work); \ - char *lowerdir = mkdtemp(lower); \ - char *upperdir = mkdtemp(upper); \ - char *mergedir = mkdtemp(merge); \ - \ - if(workdir == NULL || lowerdir == NULL || upperdir == NULL || mergedir == NULL) \ - { \ - FAIL() << "Cannot create temporary directories." << std::endl; \ - } \ - \ - /* 1. We create the lower layer file before mounting the overlayfs */ \ - \ - /* Copy local bin/true to lower layer */ \ - int true_fd = open("/bin/true", O_RDONLY); \ - if(true_fd == -1) \ - { \ - FAIL() << "Cannot open /bin/true." << std::endl; \ - } \ - \ - char lower_exe_path[1024]; \ - snprintf(lower_exe_path, 1024, "%s/lowertrue", lowerdir); \ - int lower_exe_fd = open(lower_exe_path, O_WRONLY | O_CREAT, 0777); \ - if(lower_exe_fd < 0) \ - { \ - FAIL() << "Cannot open /tmp/merged/lowertrue." << std::endl; \ - } \ - \ - char buf[1024]; \ - ssize_t bytes_read; \ - while((bytes_read = read(true_fd, buf, sizeof(buf))) > 0) \ - { \ - if(write(lower_exe_fd, buf, bytes_read) != bytes_read) \ - { \ - FAIL() << "Cannot write /tmp/merged/lowertrue." << std::endl; \ - } \ - } \ - \ - if(bytes_read == -1) \ - { \ - FAIL() << "Error copying /bin/true" << std::endl; \ - } \ - \ - if(close(lower_exe_fd) == -1) \ - { \ - FAIL() << "Error closing /tmp/merged/lowertrue" << std::endl; \ - } \ - if(close(true_fd) == -1) \ - { \ - FAIL() << "Error closing /bin/true" << std::endl; \ - } \ - \ - /* 2. We mount the overlayfs */ \ - \ - /* Construct the mount options string */ \ - char mntopts[1024]; \ - snprintf(mntopts, 1024, "lowerdir=%s,upperdir=%s,workdir=%s", lowerdir, upperdir, \ - workdir); /* Mount the overlayfs */ \ - if(mount("overlay", mergedir, "overlay", MS_MGC_VAL, mntopts) != 0) \ - { \ - FAIL() << "Cannot mount overlay." << std::endl; \ - } /* 3. We create a file in the upper layer */ \ - char upper_exe_path[1024]; \ - sprintf(upper_exe_path, "%s/uppertrue", mergedir); \ - int upper_exe_fd = open(upper_exe_path, O_WRONLY | O_CREAT, 0777); \ - if(upper_exe_fd == -1) \ - { \ - FAIL() << "Cannot open /tmp/merged/uppertrue." << std::endl; \ - } \ - true_fd = open("/bin/true", O_RDONLY); \ - if(true_fd == -1) \ - { \ - FAIL() << "Cannot open /bin/true." << std::endl; \ - } \ - while((bytes_read = read(true_fd, buf, sizeof(buf))) > 0) \ - { \ - if(write(upper_exe_fd, buf, bytes_read) != bytes_read) \ - { \ - FAIL() << "Cannot write /tmp/merged/uppertrue." << std::endl; \ - } \ - } \ - if(bytes_read == -1) \ - { \ - FAIL() << "Error copying /bin/true" << std::endl; \ - } \ - if(close(true_fd) == -1) \ - { \ - FAIL() << "Error closing /bin/true" << std::endl; \ - } \ - if(close(upper_exe_fd) == -1) \ - { \ - FAIL() << "Error closing /tmp/merged/uppertrue" << std::endl; \ +#define CREATE_OVERLAY_FS \ + \ + /* Create temp directories */ \ + char work[] = "/tmp/work.XXXXXX"; \ + char lower[] = "/tmp/lower.XXXXXX"; \ + char upper[] = "/tmp/upper.XXXXXX"; \ + char merge[] = "/tmp/overlay.XXXXXX"; \ + \ + char *workdir = mkdtemp(work); \ + char *lowerdir = mkdtemp(lower); \ + char *upperdir = mkdtemp(upper); \ + char *mergedir = mkdtemp(merge); \ + \ + if(workdir == NULL || lowerdir == NULL || upperdir == NULL || mergedir == NULL) { \ + FAIL() << "Cannot create temporary directories." << std::endl; \ + } \ + \ + /* 1. We create the lower layer file before mounting the overlayfs */ \ + \ + /* Copy local bin/true to lower layer */ \ + int true_fd = open("/bin/true", O_RDONLY); \ + if(true_fd == -1) { \ + FAIL() << "Cannot open /bin/true." << std::endl; \ + } \ + \ + char lower_exe_path[1024]; \ + snprintf(lower_exe_path, 1024, "%s/lowertrue", lowerdir); \ + int lower_exe_fd = open(lower_exe_path, O_WRONLY | O_CREAT, 0777); \ + if(lower_exe_fd < 0) { \ + FAIL() << "Cannot open /tmp/merged/lowertrue." << std::endl; \ + } \ + \ + char buf[1024]; \ + ssize_t bytes_read; \ + while((bytes_read = read(true_fd, buf, sizeof(buf))) > 0) { \ + if(write(lower_exe_fd, buf, bytes_read) != bytes_read) { \ + FAIL() << "Cannot write /tmp/merged/lowertrue." << std::endl; \ + } \ + } \ + \ + if(bytes_read == -1) { \ + FAIL() << "Error copying /bin/true" << std::endl; \ + } \ + \ + if(close(lower_exe_fd) == -1) { \ + FAIL() << "Error closing /tmp/merged/lowertrue" << std::endl; \ + } \ + if(close(true_fd) == -1) { \ + FAIL() << "Error closing /bin/true" << std::endl; \ + } \ + \ + /* 2. We mount the overlayfs */ \ + \ + /* Construct the mount options string */ \ + char mntopts[1024]; \ + snprintf(mntopts, \ + 1024, \ + "lowerdir=%s,upperdir=%s,workdir=%s", \ + lowerdir, \ + upperdir, \ + workdir); /* Mount the overlayfs */ \ + if(mount("overlay", mergedir, "overlay", MS_MGC_VAL, mntopts) != 0) { \ + FAIL() << "Cannot mount overlay." << std::endl; \ + } /* 3. We create a file in the upper layer */ \ + char upper_exe_path[1024]; \ + sprintf(upper_exe_path, "%s/uppertrue", mergedir); \ + int upper_exe_fd = open(upper_exe_path, O_WRONLY | O_CREAT, 0777); \ + if(upper_exe_fd == -1) { \ + FAIL() << "Cannot open /tmp/merged/uppertrue." << std::endl; \ + } \ + true_fd = open("/bin/true", O_RDONLY); \ + if(true_fd == -1) { \ + FAIL() << "Cannot open /bin/true." << std::endl; \ + } \ + while((bytes_read = read(true_fd, buf, sizeof(buf))) > 0) { \ + if(write(upper_exe_fd, buf, bytes_read) != bytes_read) { \ + FAIL() << "Cannot write /tmp/merged/uppertrue." << std::endl; \ + } \ + } \ + if(bytes_read == -1) { \ + FAIL() << "Error copying /bin/true" << std::endl; \ + } \ + if(close(true_fd) == -1) { \ + FAIL() << "Error closing /bin/true" << std::endl; \ + } \ + if(close(upper_exe_fd) == -1) { \ + FAIL() << "Error closing /tmp/merged/uppertrue" << std::endl; \ } -#define DESTROY_OVERLAY_FS \ - /* Unmount the overlay file system */ \ - unlink(upper_exe_path); \ - unlink(lower_exe_path); \ - rmdir(upperdir); \ - rmdir(workdir); \ - rmdir(lowerdir); \ - umount2(mergedir, MNT_FORCE); \ +#define DESTROY_OVERLAY_FS \ + /* Unmount the overlay file system */ \ + unlink(upper_exe_path); \ + unlink(lower_exe_path); \ + rmdir(upperdir); \ + rmdir(workdir); \ + rmdir(lowerdir); \ + umount2(mergedir, MNT_FORCE); \ rmdir(mergedir); -TEST(SyscallExit, execveX_failure) -{ +TEST(SyscallExit, execveX_failure) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -129,8 +116,7 @@ TEST(SyscallExit, execveX_failure) /* Get all the info from proc. */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -152,26 +138,40 @@ TEST(SyscallExit, execveX_failure) * Call the `execve` */ char pathname[] = "//**null-file-path**//"; - - std::string too_long_arg (4096, 'x'); - const char *newargv[] = {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; - std::string truncated_too_long_arg (4096 - (strlen(pathname)+1) - (strlen("first_argv")+1) - 2*(strlen("")+1) - 1, 'x'); - const char *expected_newargv[] = {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; - const char *newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", too_long_arg.c_str(), "2_ARGUMENT=no", NULL}; - std::string truncated_too_long_env (4096 - (strlen("IN_TEST=yes")+1) - (strlen("3_ARGUMENT=yes")+1) - 1, 'x'); - const char *expected_newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", truncated_too_long_env.c_str(), NULL}; + std::string too_long_arg(4096, 'x'); + const char *newargv[] = + {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; + std::string truncated_too_long_arg( + 4096 - (strlen(pathname) + 1) - (strlen("first_argv") + 1) - 2 * (strlen("") + 1) - 1, + 'x'); + const char *expected_newargv[] = + {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; + + const char *newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + too_long_arg.c_str(), + "2_ARGUMENT=no", + NULL}; + std::string truncated_too_long_env( + 4096 - (strlen("IN_TEST=yes") + 1) - (strlen("3_ARGUMENT=yes") + 1) - 1, + 'x'); + const char *expected_newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + truncated_too_long_env.c_str(), + NULL}; bool expect_truncated = true; - if(evt_test->is_kmod_engine() && getpagesize() > 4096) - { + if(evt_test->is_kmod_engine() && getpagesize() > 4096) { // for kmod, the size limit is actually PAGE_SIZE; // see STR_STORAGE_SIZE macro definition in driver/capture_macro.h. // In case PAGE_SIZE is < 4096, expect NON-truncated args/envs expect_truncated = false; } - assert_syscall_state(SYSCALL_FAILURE, "execve", syscall(__NR_execve, pathname, newargv, newenviron)); + assert_syscall_state(SYSCALL_FAILURE, + "execve", + syscall(__NR_execve, pathname, newargv, newenviron)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -180,8 +180,7 @@ TEST(SyscallExit, execveX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -199,12 +198,9 @@ TEST(SyscallExit, execveX_failure) /* Parameter 3: args (type: PT_CHARBUFARRAY) */ /* Starting from `1` because the first is `exe`. */ - if (expect_truncated) - { + if(expect_truncated) { evt_test->assert_charbuf_array_param(3, &expected_newargv[1]); - } - else - { + } else { evt_test->assert_charbuf_array_param(3, &newargv[1]); } @@ -249,12 +245,9 @@ TEST(SyscallExit, execveX_failure) evt_test->assert_cgroup_param(15); /* Parameter 16: env (type: PT_CHARBUFARRAY) */ - if (expect_truncated) - { + if(expect_truncated) { evt_test->assert_charbuf_array_param(16, &expected_newenviron[0]); - } - else - { + } else { evt_test->assert_charbuf_array_param(16, &newenviron[0]); } @@ -267,44 +260,54 @@ TEST(SyscallExit, execveX_failure) /* Parameter 19: loginuid (type: PT_UID) */ evt_test->assert_numeric_param(19, (uint32_t)info.loginuid); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE); /* Parameter 21: cap_inheritable (type: PT_UINT64) */ - evt_test->assert_numeric_param(21, (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | data[0].inheritable)); + evt_test->assert_numeric_param( + 21, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | + data[0].inheritable)); /* Parameter 22: cap_permitted (type: PT_UINT64) */ - evt_test->assert_numeric_param(22, (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | data[0].permitted)); + evt_test->assert_numeric_param( + 22, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | + data[0].permitted)); /* Parameter 23: cap_effective (type: PT_UINT64) */ - evt_test->assert_numeric_param(23, (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | data[0].effective)); + evt_test->assert_numeric_param( + 23, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | + data[0].effective)); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ evt_test->assert_numeric_param(27, (uint32_t)geteuid(), EQUAL); /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ - /* Here we don't call the execve so the result should be the full path to the drivers test executable */ + /* Here we don't call the execve so the result should be the full path to the drivers test + * executable */ evt_test->assert_charbuf_param(28, info.exepath); - /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(28); } -TEST(SyscallExit, execveX_failure_args_env_NULL) -{ +TEST(SyscallExit, execveX_failure_args_env_NULL) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -321,8 +324,7 @@ TEST(SyscallExit, execveX_failure_args_env_NULL) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -342,7 +344,7 @@ TEST(SyscallExit, execveX_failure_args_env_NULL) /* Parameter 3: args (type: PT_CHARBUFARRAY) */ evt_test->assert_empty_param(3); - /* Parameter 16: env (type: PT_CHARBUFARRAY) */ + /* Parameter 16: env (type: PT_CHARBUFARRAY) */ evt_test->assert_empty_param(16); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -350,8 +352,7 @@ TEST(SyscallExit, execveX_failure_args_env_NULL) evt_test->assert_num_params_pushed(28); } -TEST(SyscallExit, execveX_failure_path_NULL_but_not_args) -{ +TEST(SyscallExit, execveX_failure_path_NULL_but_not_args) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -361,7 +362,9 @@ TEST(SyscallExit, execveX_failure_path_NULL_but_not_args) char pathname[] = "//path_NULL_but_not_args//"; const char *newargv[] = {"", NULL}; const char *newenviron[] = {"", NULL}; - assert_syscall_state(SYSCALL_FAILURE, "execve", syscall(__NR_execve, pathname, newargv, newenviron)); + assert_syscall_state(SYSCALL_FAILURE, + "execve", + syscall(__NR_execve, pathname, newargv, newenviron)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -370,8 +373,7 @@ TEST(SyscallExit, execveX_failure_path_NULL_but_not_args) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -390,7 +392,7 @@ TEST(SyscallExit, execveX_failure_path_NULL_but_not_args) /* Parameter 3: args (type: PT_CHARBUFARRAY) */ evt_test->assert_empty_param(3); - /* Parameter 16: env (type: PT_CHARBUFARRAY) */ + /* Parameter 16: env (type: PT_CHARBUFARRAY) */ evt_test->assert_charbuf_array_param(16, &newenviron[0]); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -398,8 +400,7 @@ TEST(SyscallExit, execveX_failure_path_NULL_but_not_args) evt_test->assert_num_params_pushed(28); } -TEST(SyscallExit, execveX_success) -{ +TEST(SyscallExit, execveX_success) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -410,18 +411,30 @@ TEST(SyscallExit, execveX_success) const char *pathname = "/usr/bin/true"; const char *comm = "true"; - std::string too_long_arg (4096, 'x'); - const char *newargv[] = {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; - std::string truncated_too_long_arg (4096 - (strlen(pathname)+1) - (strlen("first_argv")+1) - 2*(strlen("")+1) - 1, 'x'); - const char *expected_newargv[] = {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; - - const char *newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", too_long_arg.c_str(), "2_ARGUMENT=no", NULL}; - std::string truncated_too_long_env (4096 - (strlen("IN_TEST=yes")+1) - (strlen("3_ARGUMENT=yes")+1) - 1, 'x'); - const char *expected_newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", truncated_too_long_env.c_str(), NULL}; + std::string too_long_arg(4096, 'x'); + const char *newargv[] = + {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; + std::string truncated_too_long_arg( + 4096 - (strlen(pathname) + 1) - (strlen("first_argv") + 1) - 2 * (strlen("") + 1) - 1, + 'x'); + const char *expected_newargv[] = + {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; + + const char *newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + too_long_arg.c_str(), + "2_ARGUMENT=no", + NULL}; + std::string truncated_too_long_env( + 4096 - (strlen("IN_TEST=yes") + 1) - (strlen("3_ARGUMENT=yes") + 1) - 1, + 'x'); + const char *expected_newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + truncated_too_long_env.c_str(), + NULL}; bool expect_truncated = true; - if(evt_test->is_kmod_engine() && getpagesize() > 4096) - { + if(evt_test->is_kmod_engine() && getpagesize() > 4096) { // for kmod, the size limit is actually PAGE_SIZE; // see STR_STORAGE_SIZE macro definition in driver/capture_macro.h. // In case PAGE_SIZE is < 4096, expect NON-truncated args/envs @@ -435,8 +448,7 @@ TEST(SyscallExit, execveX_success) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execve, pathname, newargv, newenviron); exit(EXIT_FAILURE); } @@ -446,10 +458,13 @@ TEST(SyscallExit, execveX_success) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } @@ -460,8 +475,7 @@ TEST(SyscallExit, execveX_success) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -481,12 +495,9 @@ TEST(SyscallExit, execveX_success) /* Parameter 3: args (type: PT_CHARBUFARRAY) */ /* Starting from `1` because the first is `exe`. */ - if (expect_truncated) - { + if(expect_truncated) { evt_test->assert_charbuf_array_param(3, &expected_newargv[1]); - } - else - { + } else { evt_test->assert_charbuf_array_param(3, &newargv[1]); } @@ -511,27 +522,26 @@ TEST(SyscallExit, execveX_success) evt_test->assert_cgroup_param(15); /* Parameter 16: env (type: PT_CHARBUFARRAY) */ - if (expect_truncated) - { + if(expect_truncated) { evt_test->assert_charbuf_array_param(16, &expected_newenviron[0]); - } - else - { + } else { evt_test->assert_charbuf_array_param(16, &newenviron[0]); } - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ @@ -545,8 +555,7 @@ TEST(SyscallExit, execveX_success) evt_test->assert_num_params_pushed(28); } -TEST(SyscallExit, execveX_not_upperlayer) -{ +TEST(SyscallExit, execveX_not_upperlayer) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -572,8 +581,7 @@ TEST(SyscallExit, execveX_not_upperlayer) /* * Call the `execve` */ - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execve, merged_exe_path, argv, envp); printf("execve failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); @@ -584,10 +592,13 @@ TEST(SyscallExit, execveX_not_upperlayer) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } @@ -600,8 +611,7 @@ TEST(SyscallExit, execveX_not_upperlayer) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -646,18 +656,20 @@ TEST(SyscallExit, execveX_not_upperlayer) /* Parameter 16: env (type: PT_CHARBUFARRAY) */ evt_test->assert_charbuf_array_param(16, &envp[0]); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE | PPM_EXE_LOWER_LAYER, EQUAL); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modifitrueion time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modifitrueion time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ @@ -671,8 +683,7 @@ TEST(SyscallExit, execveX_not_upperlayer) evt_test->assert_num_params_pushed(28); } -TEST(SyscallExit, execveX_upperlayer_success) -{ +TEST(SyscallExit, execveX_upperlayer_success) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -697,8 +708,7 @@ TEST(SyscallExit, execveX_upperlayer_success) /* * Call the `execve` */ - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execve, pathname, argv, envp); printf("execve failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); @@ -709,10 +719,13 @@ TEST(SyscallExit, execveX_upperlayer_success) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } @@ -725,8 +738,7 @@ TEST(SyscallExit, execveX_upperlayer_success) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -771,18 +783,20 @@ TEST(SyscallExit, execveX_upperlayer_success) /* Parameter 16: env (type: PT_CHARBUFARRAY) */ evt_test->assert_charbuf_array_param(16, &envp[0]); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ - evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE|PPM_EXE_UPPER_LAYER); + evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE | PPM_EXE_UPPER_LAYER); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modifitrueion time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modifitrueion time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ @@ -798,8 +812,7 @@ TEST(SyscallExit, execveX_upperlayer_success) #if defined(__NR_memfd_create) && defined(__NR_openat) && defined(__NR_read) && defined(__NR_write) #include -TEST(SyscallExit, execveX_success_memfd) -{ +TEST(SyscallExit, execveX_success_memfd) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -811,26 +824,22 @@ TEST(SyscallExit, execveX_success_memfd) /* Open the executable to copy */ int fd_to_read = syscall(__NR_openat, 0, "/usr/bin/echo", O_RDWR); - if(fd_to_read < 0) - { + if(fd_to_read < 0) { FAIL() << "failed to open the file to read\n"; } char buf[200]; ssize_t bytes_read = 200; - while(bytes_read != 0) - { + while(bytes_read != 0) { bytes_read = syscall(__NR_read, fd_to_read, buf, sizeof(buf)); - if(bytes_read < 0) - { + if(bytes_read < 0) { syscall(__NR_close, fd_to_read); syscall(__NR_close, mem_fd); FAIL() << "unable to read from file\n"; } bytes_read = syscall(__NR_write, mem_fd, buf, bytes_read); - if(bytes_read < 0) - { + if(bytes_read < 0) { syscall(__NR_close, fd_to_read); syscall(__NR_close, mem_fd); FAIL() << "unable to write to file\n"; @@ -845,8 +854,7 @@ TEST(SyscallExit, execveX_success_memfd) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { char pathname[200]; snprintf(pathname, sizeof(pathname), "/proc/%d/fd/%d", getpid(), mem_fd); const char *newargv[] = {pathname, "[OUTPUT] SyscallExit.execveX_success_memfd", NULL}; @@ -861,11 +869,13 @@ TEST(SyscallExit, execveX_success_memfd) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } @@ -876,8 +886,7 @@ TEST(SyscallExit, execveX_success_memfd) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -892,8 +901,8 @@ TEST(SyscallExit, execveX_success_memfd) /* Parameter 1: res (type: PT_ERRNO)*/ evt_test->assert_numeric_param(1, (int64_t)0); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE | PPM_EXE_FROM_MEMFD); @@ -903,12 +912,9 @@ TEST(SyscallExit, execveX_success_memfd) * Please note that in the kernel module, we remove the " (deleted)" suffix while * in BPF we don't add it at all. */ - if(evt_test->is_kmod_engine()) - { + if(evt_test->is_kmod_engine()) { evt_test->assert_charbuf_param(28, "/memfd:malware"); - } - else - { + } else { /* In BPF drivers we don't have the correct result but we can reconstruct part of it */ evt_test->assert_charbuf_param(28, "memfd:malware"); } @@ -920,8 +926,7 @@ TEST(SyscallExit, execveX_success_memfd) #endif #if defined(__NR_symlinkat) && defined(__NR_unlinkat) -TEST(SyscallExit, execveX_symlink) -{ +TEST(SyscallExit, execveX_symlink) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -933,7 +938,11 @@ TEST(SyscallExit, execveX_symlink) const char *linkpath = "target3"; /* Create symlink */ - assert_syscall_state(SYSCALL_SUCCESS, "symlinkat", syscall(__NR_symlinkat, pathname, AT_FDCWD, linkpath), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "symlinkat", + syscall(__NR_symlinkat, pathname, AT_FDCWD, linkpath), + NOT_EQUAL, + -1); const char *comm = "target3"; const char *argv[] = {linkpath, "[OUTPUT] SyscallExit.execveX_success test", NULL}; @@ -946,8 +955,7 @@ TEST(SyscallExit, execveX_symlink) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execve, linkpath, argv, envp); exit(EXIT_FAILURE); } @@ -957,14 +965,21 @@ TEST(SyscallExit, execveX_symlink) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } - assert_syscall_state(SYSCALL_SUCCESS, "unlinkat", syscall(__NR_unlinkat, AT_FDCWD, linkpath, 0), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "unlinkat", + syscall(__NR_unlinkat, AT_FDCWD, linkpath, 0), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -973,8 +988,7 @@ TEST(SyscallExit, execveX_symlink) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1004,8 +1018,7 @@ TEST(SyscallExit, execveX_symlink) } #endif -TEST(SyscallExit, execveX_failure_empty_arg) -{ +TEST(SyscallExit, execveX_failure_empty_arg) { auto evt_test = get_syscall_event_test(__NR_execve, EXIT_EVENT); evt_test->enable_capture(); @@ -1015,8 +1028,7 @@ TEST(SyscallExit, execveX_failure_empty_arg) /* Get all the info from proc. */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -1039,8 +1051,11 @@ TEST(SyscallExit, execveX_failure_empty_arg) */ char pathname[] = ""; const char *newargv[] = {pathname, "first_argv", "second_argv", "", "fourth_argv", NULL}; - const char *newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", "2_ARGUMENT=no", "", "0_ARGUMENT=no", NULL}; - assert_syscall_state(SYSCALL_FAILURE, "execve", syscall(__NR_execve, pathname, newargv, newenviron)); + const char *newenviron[] = + {"IN_TEST=yes", "3_ARGUMENT=yes", "2_ARGUMENT=no", "", "0_ARGUMENT=no", NULL}; + assert_syscall_state(SYSCALL_FAILURE, + "execve", + syscall(__NR_execve, pathname, newargv, newenviron)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -1049,8 +1064,7 @@ TEST(SyscallExit, execveX_failure_empty_arg) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1122,37 +1136,48 @@ TEST(SyscallExit, execveX_failure_empty_arg) /* Parameter 19: loginuid (type: PT_UID) */ evt_test->assert_numeric_param(19, (uint32_t)info.loginuid); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE); /* Parameter 21: cap_inheritable (type: PT_UINT64) */ - evt_test->assert_numeric_param(21, (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | data[0].inheritable)); + evt_test->assert_numeric_param( + 21, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | + data[0].inheritable)); /* Parameter 22: cap_permitted (type: PT_UINT64) */ - evt_test->assert_numeric_param(22, (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | data[0].permitted)); + evt_test->assert_numeric_param( + 22, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | + data[0].permitted)); /* Parameter 23: cap_effective (type: PT_UINT64) */ - evt_test->assert_numeric_param(23, (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | data[0].effective)); + evt_test->assert_numeric_param( + 23, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | + data[0].effective)); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ evt_test->assert_numeric_param(27, (uint32_t)geteuid(), EQUAL); /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ - /* Here we don't call the execve so the result should be the full path to the drivers test executable */ + /* Here we don't call the execve so the result should be the full path to the drivers test + * executable */ evt_test->assert_charbuf_param(28, info.exepath); - /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(28); diff --git a/test/drivers/test_suites/syscall_exit_suite/execveat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/execveat_x.cpp index ffbb5053b4..dab08a408e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/execveat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/execveat_x.cpp @@ -2,12 +2,12 @@ #include "../../flags/flags_definitions.h" #include "../../helpers/proc_parsing.h" -#if defined(__NR_execveat) && defined(__NR_capget) && defined(__NR_clone3) && defined(__NR_wait4) && defined(__NR_execve) +#if defined(__NR_execveat) && defined(__NR_capget) && defined(__NR_clone3) && \ + defined(__NR_wait4) && defined(__NR_execve) #include -TEST(SyscallExit, execveatX_failure) -{ +TEST(SyscallExit, execveatX_failure) { auto evt_test = get_syscall_event_test(__NR_execveat, EXIT_EVENT); evt_test->enable_capture(); @@ -17,8 +17,7 @@ TEST(SyscallExit, execveatX_failure) /* Get all the info from proc. */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } @@ -42,18 +41,30 @@ TEST(SyscallExit, execveatX_failure) */ int dirfd = AT_FDCWD; char pathname[] = "//**null-file-path**//"; - std::string too_long_arg (4096, 'x'); - const char *newargv[] = {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; - std::string truncated_too_long_arg (4096 - (strlen(pathname)+1) - (strlen("first_argv")+1) - 2*(strlen("")+1) - 1, 'x'); - const char *expected_newargv[] = {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; - - const char *newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", too_long_arg.c_str(), "2_ARGUMENT=no", NULL}; - std::string truncated_too_long_env (4096 - (strlen("IN_TEST=yes")+1) - (strlen("3_ARGUMENT=yes")+1) - 1, 'x'); - const char *expected_newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", truncated_too_long_env.c_str(), NULL}; + std::string too_long_arg(4096, 'x'); + const char *newargv[] = + {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; + std::string truncated_too_long_arg( + 4096 - (strlen(pathname) + 1) - (strlen("first_argv") + 1) - 2 * (strlen("") + 1) - 1, + 'x'); + const char *expected_newargv[] = + {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; + + const char *newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + too_long_arg.c_str(), + "2_ARGUMENT=no", + NULL}; + std::string truncated_too_long_env( + 4096 - (strlen("IN_TEST=yes") + 1) - (strlen("3_ARGUMENT=yes") + 1) - 1, + 'x'); + const char *expected_newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + truncated_too_long_env.c_str(), + NULL}; bool expect_truncated = true; - if(evt_test->is_kmod_engine() && getpagesize() > 4096) - { + if(evt_test->is_kmod_engine() && getpagesize() > 4096) { // for kmod, the size limit is actually PAGE_SIZE; // see STR_STORAGE_SIZE macro definition in driver/capture_macro.h. // In case PAGE_SIZE is < 4096, expect NON-truncated args/envs @@ -61,7 +72,9 @@ TEST(SyscallExit, execveatX_failure) } int flags = AT_SYMLINK_NOFOLLOW; - assert_syscall_state(SYSCALL_FAILURE, "execveat", syscall(__NR_execveat, dirfd, pathname, newargv, newenviron, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "execveat", + syscall(__NR_execveat, dirfd, pathname, newargv, newenviron, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -70,8 +83,7 @@ TEST(SyscallExit, execveatX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -89,12 +101,9 @@ TEST(SyscallExit, execveatX_failure) /* Parameter 3: args (type: PT_CHARBUFARRAY) */ /* Starting from `1` because the first is `exe`. */ - if (expect_truncated) - { + if(expect_truncated) { evt_test->assert_charbuf_array_param(3, &expected_newargv[1]); - } - else - { + } else { evt_test->assert_charbuf_array_param(3, &newargv[1]); } @@ -139,12 +148,9 @@ TEST(SyscallExit, execveatX_failure) evt_test->assert_cgroup_param(15); /* Parameter 16: env (type: PT_CHARBUFARRAY) */ - if (expect_truncated) - { + if(expect_truncated) { evt_test->assert_charbuf_array_param(16, &expected_newenviron[0]); - } - else - { + } else { evt_test->assert_charbuf_array_param(16, &newenviron[0]); } @@ -158,34 +164,46 @@ TEST(SyscallExit, execveatX_failure) /* Parameter 19: loginuid (type: PT_UID) */ evt_test->assert_numeric_param(19, (uint32_t)info.loginuid); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE); /* Parameter 21: cap_inheritable (type: PT_UINT64) */ - evt_test->assert_numeric_param(21, (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | data[0].inheritable)); + evt_test->assert_numeric_param( + 21, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].inheritable << 32) | + data[0].inheritable)); /* Parameter 22: cap_permitted (type: PT_UINT64) */ - evt_test->assert_numeric_param(22, (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | data[0].permitted)); + evt_test->assert_numeric_param( + 22, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].permitted << 32) | + data[0].permitted)); /* Parameter 23: cap_effective (type: PT_UINT64) */ - evt_test->assert_numeric_param(23, (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | data[0].effective)); + evt_test->assert_numeric_param( + 23, + (uint64_t)capabilities_to_scap(((unsigned long)data[1].effective << 32) | + data[0].effective)); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ evt_test->assert_numeric_param(27, (uint32_t)geteuid(), EQUAL); /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ - /* Here we don't call the execveat so the result should be the full path to the drivers test executable */ + /* Here we don't call the execveat so the result should be the full path to the drivers test + * executable */ evt_test->assert_charbuf_param(28, info.exepath); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -197,8 +215,7 @@ TEST(SyscallExit, execveatX_failure) * `s390x` seems to return an `EXECVEAT_X` event also when the syscall succeeds, other * architectures like `x86_64` return an `EXECVE_X` event. */ -TEST(SyscallExit, execveatX_correct_exit) -{ +TEST(SyscallExit, execveatX_correct_exit) { auto evt_test = get_syscall_event_test(__NR_execveat, EXIT_EVENT); evt_test->enable_capture(); @@ -209,13 +226,17 @@ TEST(SyscallExit, execveatX_correct_exit) int dirfd = 0; const char *pathname = "/usr/bin/test"; - std::string too_long_arg (4096, 'x'); - const char *newargv[] = {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; - const char *newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", too_long_arg.c_str(), "2_ARGUMENT=no", NULL}; + std::string too_long_arg(4096, 'x'); + const char *newargv[] = + {pathname, "", "first_argv", "", too_long_arg.c_str(), "second_argv", NULL}; + const char *newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + too_long_arg.c_str(), + "2_ARGUMENT=no", + NULL}; bool expect_truncated = true; - if(evt_test->is_kmod_engine() && getpagesize() > 4096) - { + if(evt_test->is_kmod_engine() && getpagesize() > 4096) { // for kmod, the size limit is actually PAGE_SIZE; // see STR_STORAGE_SIZE macro definition in driver/capture_macro.h. // In case PAGE_SIZE is < 4096, expect NON-truncated args/envs @@ -231,8 +252,7 @@ TEST(SyscallExit, execveatX_correct_exit) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execveat, dirfd, pathname, newargv, newenviron, flags); exit(EXIT_FAILURE); } @@ -242,10 +262,13 @@ TEST(SyscallExit, execveatX_correct_exit) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execveat failed." << std::endl; } @@ -257,8 +280,7 @@ TEST(SyscallExit, execveatX_correct_exit) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -280,15 +302,15 @@ TEST(SyscallExit, execveatX_correct_exit) /* Parameter 3: args (type: PT_CHARBUFARRAY) */ /* Starting from `1` because the first is `exe`. */ - if (expect_truncated) - { - std::string truncated_too_long_arg( - 4096 - (strlen(pathname) + 1) - (strlen("first_argv") + 1) - 2 * (strlen("") + 1) - 1, 'x'); - const char *expected_newargv[] = {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; + if(expect_truncated) { + std::string truncated_too_long_arg(4096 - (strlen(pathname) + 1) - + (strlen("first_argv") + 1) - + 2 * (strlen("") + 1) - 1, + 'x'); + const char *expected_newargv[] = + {pathname, "", "first_argv", "", truncated_too_long_arg.c_str(), NULL}; evt_test->assert_charbuf_array_param(3, &expected_newargv[1]); - } - else - { + } else { evt_test->assert_charbuf_array_param(3, &newargv[1]); } @@ -313,31 +335,33 @@ TEST(SyscallExit, execveatX_correct_exit) evt_test->assert_cgroup_param(15); /* Parameter 16: env (type: PT_CHARBUFARRAY) */ - if (expect_truncated) - { + if(expect_truncated) { std::string truncated_too_long_env( - 4096 - (strlen("IN_TEST=yes") + 1) - (strlen("3_ARGUMENT=yes") + 1) - 1, 'x'); - const char *expected_newenviron[] = {"IN_TEST=yes", "3_ARGUMENT=yes", truncated_too_long_env.c_str(), - NULL}; + 4096 - (strlen("IN_TEST=yes") + 1) - (strlen("3_ARGUMENT=yes") + 1) - 1, + 'x'); + const char *expected_newenviron[] = {"IN_TEST=yes", + "3_ARGUMENT=yes", + truncated_too_long_env.c_str(), + NULL}; evt_test->assert_charbuf_array_param(16, &expected_newenviron[0]); - } - else - { + } else { evt_test->assert_charbuf_array_param(16, &newenviron[0]); } - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ @@ -355,8 +379,7 @@ TEST(SyscallExit, execveatX_correct_exit) #endif } -TEST(SyscallExit, execveatX_execve_exit) -{ +TEST(SyscallExit, execveatX_execve_exit) { auto evt_test = get_syscall_event_test(); evt_test->enable_capture(); @@ -378,8 +401,7 @@ TEST(SyscallExit, execveatX_execve_exit) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execveat, dirfd, pathname, argv, envp, flags); exit(EXIT_FAILURE); } @@ -389,10 +411,13 @@ TEST(SyscallExit, execveatX_execve_exit) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execveat failed." << std::endl; } @@ -408,8 +433,7 @@ TEST(SyscallExit, execveatX_execve_exit) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid, PPME_SYSCALL_EXECVE_19_X); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -454,18 +478,20 @@ TEST(SyscallExit, execveatX_execve_exit) /* Parameter 16: env (type: PT_CHARBUFARRAY) */ evt_test->assert_charbuf_array_param(16, &envp[0]); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE); /* Parameter 24: exe_file ino (type: PT_UINT64) */ evt_test->assert_numeric_param(24, (uint64_t)1, GREATER_EQUAL); - /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 25: exe_file ctime (last status change time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(25, (uint64_t)1000000000000000000, GREATER_EQUAL); - /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: PT_ABSTIME) */ + /* Parameter 26: exe_file mtime (last modification time, epoch value in nanoseconds) (type: + * PT_ABSTIME) */ evt_test->assert_numeric_param(26, (uint64_t)1000000000000000000, GREATER_EQUAL); /* Parameter 27: euid (type: PT_UID) */ @@ -480,8 +506,7 @@ TEST(SyscallExit, execveatX_execve_exit) #endif } -TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) -{ +TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) { auto evt_test = get_syscall_event_test(); evt_test->enable_capture(); @@ -489,16 +514,17 @@ TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) /*=============================== TRIGGER SYSCALL ===========================*/ /* Prepare the execve args */ - const char* exe_path = "/usr/bin/echo"; + const char *exe_path = "/usr/bin/echo"; int dirfd = open(exe_path, O_RDONLY); - if(dirfd < 0) - { + if(dirfd < 0) { FAIL() << "failed to open the file\n"; } // We will use the `AT_EMPTY_PATH` strategy const char *pathname = ""; - const char *argv[] = {pathname, "[OUTPUT] SyscallExit.execveatX_execve_exit_comm_equal_to_fd", NULL}; + const char *argv[] = {pathname, + "[OUTPUT] SyscallExit.execveatX_execve_exit_comm_equal_to_fd", + NULL}; const char *envp[] = {"IN_TEST=yes", "3_ARGUMENT=yes", "2_ARGUMENT=no", NULL}; int flags = AT_EMPTY_PATH; @@ -506,8 +532,7 @@ TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { syscall(__NR_execveat, dirfd, pathname, argv, envp, flags); exit(EXIT_FAILURE); } @@ -517,10 +542,13 @@ TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execveat failed." << std::endl; } @@ -536,8 +564,7 @@ TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid, PPME_SYSCALL_EXECVE_19_X); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -563,7 +590,7 @@ TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) // This is exactly the behavior that we obtain using the `AT_EMPTY_PATH` flag // https://github.com/torvalds/linux/blob/master/fs/exec.c#L1600 // https://github.com/torvalds/linux/blob/master/fs/exec.c#L1425 - std::string comm = std::to_string(dirfd); + std::string comm = std::to_string(dirfd); evt_test->assert_charbuf_param(14, comm.c_str()); /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ @@ -575,11 +602,9 @@ TEST(SyscallExit, execveatX_execve_exit_comm_equal_to_fd) #endif } - #if defined(__NR_memfd_create) && defined(__NR_openat) && defined(__NR_read) && defined(__NR_write) #include -TEST(SyscallExit, execveatX_success_memfd) -{ +TEST(SyscallExit, execveatX_success_memfd) { auto evt_test = get_syscall_event_test(__NR_execveat, EXIT_EVENT); evt_test->enable_capture(); @@ -591,26 +616,22 @@ TEST(SyscallExit, execveatX_success_memfd) /* Open the executable to copy */ int fd_to_read = syscall(__NR_openat, 0, "/usr/bin/echo", O_RDWR); - if(fd_to_read < 0) - { + if(fd_to_read < 0) { FAIL() << "failed to open the file to read\n"; } char buf[200]; ssize_t bytes_read = 200; - while(bytes_read != 0) - { + while(bytes_read != 0) { bytes_read = syscall(__NR_read, fd_to_read, buf, sizeof(buf)); - if(bytes_read < 0) - { + if(bytes_read < 0) { syscall(__NR_close, fd_to_read); syscall(__NR_close, mem_fd); FAIL() << "unable to read from file\n"; } bytes_read = syscall(__NR_write, mem_fd, buf, bytes_read); - if(bytes_read < 0) - { + if(bytes_read < 0) { syscall(__NR_close, fd_to_read); syscall(__NR_close, mem_fd); FAIL() << "unable to write to file\n"; @@ -625,8 +646,7 @@ TEST(SyscallExit, execveatX_success_memfd) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { char pathname[200]; snprintf(pathname, sizeof(pathname), "/proc/%d/fd/%d", getpid(), mem_fd); const char *newargv[] = {pathname, "[OUTPUT] SyscallExit.execveX_success_memfd", NULL}; @@ -641,11 +661,13 @@ TEST(SyscallExit, execveatX_success_memfd) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, - -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The child execve failed." << std::endl; } @@ -657,8 +679,7 @@ TEST(SyscallExit, execveatX_success_memfd) /* We search for a child event. */ evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -673,8 +694,8 @@ TEST(SyscallExit, execveatX_success_memfd) /* Parameter 1: res (type: PT_ERRNO)*/ evt_test->assert_numeric_param(1, (int64_t)0); - /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the executable - * file that is used to spawn it or is its owner or otherwise capable. + /* PPM_EXE_WRITABLE is set when the user that executed a process can also write to the + * executable file that is used to spawn it or is its owner or otherwise capable. */ evt_test->assert_numeric_param(20, (uint32_t)PPM_EXE_WRITABLE | PPM_EXE_FROM_MEMFD); @@ -684,12 +705,9 @@ TEST(SyscallExit, execveatX_success_memfd) * Please note that in the kernel module, we remove the " (deleted)" suffix while * in BPF we don't add it at all. */ - if(evt_test->is_kmod_engine()) - { + if(evt_test->is_kmod_engine()) { evt_test->assert_charbuf_param(28, "/memfd:malware"); - } - else - { + } else { /* In BPF drivers we don't have the correct result but we can reconstruct part of it */ evt_test->assert_charbuf_param(28, "memfd:malware"); } diff --git a/test/drivers/test_suites/syscall_exit_suite/fchdir_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fchdir_x.cpp index c98f69d6f3..13453fc08d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fchdir_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fchdir_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchdir -TEST(SyscallExit, fchdirX) -{ +TEST(SyscallExit, fchdirX) { auto evt_test = get_syscall_event_test(__NR_fchdir, EXIT_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallExit, fchdirX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/fchmod_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fchmod_x.cpp index f75d44286a..21553b5b82 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fchmod_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fchmod_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchmod -TEST(SyscallExit, fchmodX) -{ +TEST(SyscallExit, fchmodX) { auto evt_test = get_syscall_event_test(__NR_fchmod, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, fchmodX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/fchmodat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fchmodat_x.cpp index 7860ac3c94..c59c42f9f7 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fchmodat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fchmodat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchmodat -TEST(SyscallExit, fchmodatX) -{ +TEST(SyscallExit, fchmodatX) { auto evt_test = get_syscall_event_test(__NR_fchmodat, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallExit, fchmodatX) const char* pathname = "*//null"; uint32_t mode = S_IXUSR; uint32_t flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "fchmodat", syscall(__NR_fchmodat, mock_dirfd, pathname, mode, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "fchmodat", + syscall(__NR_fchmodat, mock_dirfd, pathname, mode, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallExit, fchmodatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/fchown_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fchown_x.cpp index 7a4ce20148..51303ff3dc 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fchown_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fchown_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchown -TEST(SyscallExit, fchownX) -{ +TEST(SyscallExit, fchownX) { auto evt_test = get_syscall_event_test(__NR_fchown, EXIT_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallExit, fchownX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/fchownat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fchownat_x.cpp index 3f16a74d22..3f3c3e4240 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fchownat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fchownat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fchownat -TEST(SyscallExit, fchownatX) -{ +TEST(SyscallExit, fchownatX) { auto evt_test = get_syscall_event_test(__NR_fchownat, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallExit, fchownatX) uint32_t uid = 0; uint32_t gid = 0; uint32_t flags = AT_SYMLINK_FOLLOW | AT_EMPTY_PATH; - assert_syscall_state(SYSCALL_FAILURE, "fchownat", syscall(__NR_fchownat, mock_dirfd, pathname, uid, gid, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "fchownat", + syscall(__NR_fchownat, mock_dirfd, pathname, uid, gid, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallExit, fchownatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/fcntl_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fcntl_x.cpp index 9e988193f6..537a072c75 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fcntl_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fcntl_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, fcntlX) -{ +TEST(SyscallExit, fcntlX) { auto evt_test = get_syscall_event_test(__NR_fcntl, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, fcntlX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/finit_module_x.cpp b/test/drivers/test_suites/syscall_exit_suite/finit_module_x.cpp index dab8e756c1..3dc453078e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/finit_module_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/finit_module_x.cpp @@ -3,8 +3,7 @@ #if defined(__NR_finit_module) #include -TEST(SyscallExit, finit_moduleX_failure) -{ +TEST(SyscallExit, finit_moduleX_failure) { auto evt_test = get_syscall_event_test(__NR_finit_module, EXIT_EVENT); evt_test->enable_capture(); @@ -18,19 +17,18 @@ TEST(SyscallExit, finit_moduleX_failure) */ int64_t kmod_fd = -1; - assert_syscall_state(SYSCALL_FAILURE, "finit_module", syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "finit_module", + syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); int64_t errno_value = -errno; - - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -58,8 +56,7 @@ TEST(SyscallExit, finit_moduleX_failure) } #ifdef MODULE_INIT_IGNORE_MODVERSIONS -TEST(SyscallExit, finit_moduleX_failure_IGNORE_MODVERSIONS) -{ +TEST(SyscallExit, finit_moduleX_failure_IGNORE_MODVERSIONS) { auto evt_test = get_syscall_event_test(__NR_finit_module, EXIT_EVENT); evt_test->enable_capture(); @@ -73,18 +70,18 @@ TEST(SyscallExit, finit_moduleX_failure_IGNORE_MODVERSIONS) */ int64_t kmod_fd = 99; - assert_syscall_state(SYSCALL_FAILURE, "finit_module", syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "finit_module", + syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -113,8 +110,7 @@ TEST(SyscallExit, finit_moduleX_failure_IGNORE_MODVERSIONS) #endif #ifdef MODULE_INIT_IGNORE_VERMAGIC -TEST(SyscallExit, finit_moduleX_failure_IGNORE_VERMAGIC) -{ +TEST(SyscallExit, finit_moduleX_failure_IGNORE_VERMAGIC) { auto evt_test = get_syscall_event_test(__NR_finit_module, EXIT_EVENT); evt_test->enable_capture(); @@ -128,18 +124,18 @@ TEST(SyscallExit, finit_moduleX_failure_IGNORE_VERMAGIC) */ int64_t kmod_fd = 99; - assert_syscall_state(SYSCALL_FAILURE, "finit_module", syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "finit_module", + syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -168,8 +164,7 @@ TEST(SyscallExit, finit_moduleX_failure_IGNORE_VERMAGIC) #endif #ifdef MODULE_INIT_COMPRESSED_FILE -TEST(SyscallExit, finit_moduleX_failure_COMPRESSED_FILE) -{ +TEST(SyscallExit, finit_moduleX_failure_COMPRESSED_FILE) { auto evt_test = get_syscall_event_test(__NR_finit_module, EXIT_EVENT); evt_test->enable_capture(); @@ -183,18 +178,18 @@ TEST(SyscallExit, finit_moduleX_failure_COMPRESSED_FILE) */ int64_t kmod_fd = 99; - assert_syscall_state(SYSCALL_FAILURE, "finit_module", syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "finit_module", + syscall(__NR_finit_module, kmod_fd, (void*)mock_buf, flags)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/flock_x.cpp b/test/drivers/test_suites/syscall_exit_suite/flock_x.cpp index 974e17c3fd..0b6f5aadcf 100644 --- a/test/drivers/test_suites/syscall_exit_suite/flock_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/flock_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_flock -TEST(SyscallExit, flockX) -{ +TEST(SyscallExit, flockX) { auto evt_test = get_syscall_event_test(__NR_flock, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, flockX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/fork_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fork_x.cpp index 5f5c328925..9cbc3a35c0 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fork_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fork_x.cpp @@ -3,8 +3,7 @@ #if defined(__NR_fork) && defined(__NR_wait4) -TEST(SyscallExit, forkX_father) -{ +TEST(SyscallExit, forkX_father) { auto evt_test = get_syscall_event_test(__NR_fork, EXIT_EVENT); evt_test->enable_capture(); @@ -16,15 +15,13 @@ TEST(SyscallExit, forkX_father) */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } pid_t ret_pid = syscall(__NR_fork); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -34,9 +31,12 @@ TEST(SyscallExit, forkX_father) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -46,8 +46,7 @@ TEST(SyscallExit, forkX_father) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -130,8 +129,7 @@ TEST(SyscallExit, forkX_father) evt_test->assert_num_params_pushed(21); } -TEST(SyscallExit, forkX_child) -{ +TEST(SyscallExit, forkX_child) { event_test evt_test(__NR_fork, EXIT_EVENT); evt_test.enable_capture(); @@ -141,15 +139,13 @@ TEST(SyscallExit, forkX_child) /* Here we scan the parent just to obtain some info for the child */ struct proc_info info = {}; pid_t pid = ::getpid(); - if(!get_proc_info(pid, &info)) - { + if(!get_proc_info(pid, &info)) { FAIL() << "Unable to get all the info from proc" << std::endl; } pid_t ret_pid = syscall(__NR_fork); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* Child terminates immediately. */ exit(EXIT_SUCCESS); } @@ -158,9 +154,12 @@ TEST(SyscallExit, forkX_child) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "Something in the child failed." << std::endl; } @@ -178,8 +177,7 @@ TEST(SyscallExit, forkX_child) #else evt_test.assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -193,7 +191,7 @@ TEST(SyscallExit, forkX_child) evt_test.assert_numeric_param(1, (int64_t)0); /* Parameter 2: exe (type: PT_CHARBUF) */ -#ifndef __powerpc64__ // Page fault +#ifndef __powerpc64__ // Page fault evt_test.assert_charbuf_param(2, info.args[0]); /* Parameter 3: args (type: PT_CHARBUFARRAY) */ diff --git a/test/drivers/test_suites/syscall_exit_suite/fsconfig_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fsconfig_x.cpp index 56f1847c5d..26a2d0de59 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fsconfig_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fsconfig_x.cpp @@ -3,8 +3,7 @@ #if defined(__NR_fsconfig) && defined(__NR_fspick) #include -TEST(SyscallExit, fsconfigX_FSCONFIG_SET_STRING) -{ +TEST(SyscallExit, fsconfigX_FSCONFIG_SET_STRING) { auto evt_test = get_syscall_event_test(__NR_fsconfig, EXIT_EVENT); evt_test->enable_capture(); @@ -29,8 +28,7 @@ TEST(SyscallExit, fsconfigX_FSCONFIG_SET_STRING) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -66,8 +64,7 @@ TEST(SyscallExit, fsconfigX_FSCONFIG_SET_STRING) evt_test->assert_num_params_pushed(7); } -TEST(SyscallExit, fsconfigX_failure) -{ +TEST(SyscallExit, fsconfigX_failure) { auto evt_test = get_syscall_event_test(__NR_fsconfig, EXIT_EVENT); evt_test->enable_capture(); @@ -79,7 +76,9 @@ TEST(SyscallExit, fsconfigX_failure) const char* key = "//**invalid-key**//"; const char* value = "//**invalid-value**//"; int aux = 100; - assert_syscall_state(SYSCALL_FAILURE, "fsconfig", syscall(__NR_fsconfig, fd, cmd, key, value, aux)); + assert_syscall_state(SYSCALL_FAILURE, + "fsconfig", + syscall(__NR_fsconfig, fd, cmd, key, value, aux)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -88,8 +87,7 @@ TEST(SyscallExit, fsconfigX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/fstat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/fstat_x.cpp index 4ef64b32df..aff44a28e8 100644 --- a/test/drivers/test_suites/syscall_exit_suite/fstat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/fstat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_fstat -TEST(SyscallExit, fstatX) -{ +TEST(SyscallExit, fstatX) { auto evt_test = get_syscall_event_test(__NR_fstat, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, fstatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/futex_x.cpp b/test/drivers/test_suites/syscall_exit_suite/futex_x.cpp index b998a9a22b..9fb6743ea1 100644 --- a/test/drivers/test_suites/syscall_exit_suite/futex_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/futex_x.cpp @@ -5,8 +5,7 @@ #include #ifdef __NR_futex -TEST(SyscallEnter, futexX) -{ +TEST(SyscallEnter, futexX) { auto evt_test = get_syscall_event_test(__NR_futex, EXIT_EVENT); evt_test->enable_capture(); @@ -16,8 +15,10 @@ TEST(SyscallEnter, futexX) uint32_t futex_word; int futex_op = FUTEX_PRIVATE_FLAG; uint32_t val = 7; - assert_syscall_state(SYSCALL_FAILURE, "futex", syscall(__NR_futex, &futex_word, futex_op, val, NULL, NULL, 0)); - int64_t errno_value = -errno; + assert_syscall_state(SYSCALL_FAILURE, + "futex", + syscall(__NR_futex, &futex_word, futex_op, val, NULL, NULL, 0)); + int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallEnter, futexX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/generic_x.cpp b/test/drivers/test_suites/syscall_exit_suite/generic_x.cpp index ff0281a1a2..196c99e97a 100644 --- a/test/drivers/test_suites/syscall_exit_suite/generic_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/generic_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_uname -TEST(SyscallExit, genericX) -{ +TEST(SyscallExit, genericX) { /* We use `uname` syscall because it is defined on all architectures * and is a very simple syscall. */ @@ -20,8 +19,7 @@ TEST(SyscallExit, genericX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getcpu_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getcpu_x.cpp index 2e545f7774..10e955e0fd 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getcpu_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getcpu_x.cpp @@ -2,8 +2,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getcpu -TEST(SyscallExit, getcpu_X) -{ +TEST(SyscallExit, getcpu_X) { auto evt_test = get_syscall_event_test(__NR_getcpu, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, getcpu_X) /* Retrieve events in order. */ evt_test->assert_event_presence(CURRENT_PID, PPME_GENERIC_X); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getcwd_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getcwd_x.cpp index 1a3a3b9517..808ff96825 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getcwd_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getcwd_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getcwd -TEST(SyscallExit, getcwdX_success) -{ +TEST(SyscallExit, getcwdX_success) { auto evt_test = get_syscall_event_test(__NR_getcwd, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, getcwdX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -44,8 +42,7 @@ TEST(SyscallExit, getcwdX_success) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, getcwdX_fail) -{ +TEST(SyscallExit, getcwdX_fail) { auto evt_test = get_syscall_event_test(__NR_getcwd, EXIT_EVENT); evt_test->enable_capture(); @@ -63,8 +60,7 @@ TEST(SyscallExit, getcwdX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getdents64_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getdents64_x.cpp index 477c596754..c86e9dfa57 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getdents64_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getdents64_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getdents64 -TEST(SyscallExit, getdents64X) -{ +TEST(SyscallExit, getdents64X) { auto evt_test = get_syscall_event_test(__NR_getdents64, EXIT_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallExit, getdents64X) int32_t invalid_fd = 10; void* dirp = NULL; int count = 0; - assert_syscall_state(SYSCALL_FAILURE, "getdents64", syscall(__NR_getdents64, invalid_fd, dirp, count)); + assert_syscall_state(SYSCALL_FAILURE, + "getdents64", + syscall(__NR_getdents64, invalid_fd, dirp, count)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallExit, getdents64X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getdents_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getdents_x.cpp index 9283f98f42..a911e802ce 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getdents_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getdents_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getdents -TEST(SyscallExit, getdentsX) -{ +TEST(SyscallExit, getdentsX) { auto evt_test = get_syscall_event_test(__NR_getdents, EXIT_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallExit, getdentsX) int32_t invalid_fd = 10; void* dirp = NULL; int count = 0; - assert_syscall_state(SYSCALL_FAILURE, "getdents", syscall(__NR_getdents, invalid_fd, dirp, count)); + assert_syscall_state(SYSCALL_FAILURE, + "getdents", + syscall(__NR_getdents, invalid_fd, dirp, count)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallExit, getdentsX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getegid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getegid_x.cpp index 8ce6354555..97a6760ccd 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getegid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getegid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getegid -TEST(SyscallExit, getegidX) -{ +TEST(SyscallExit, getegidX) { auto evt_test = get_syscall_event_test(__NR_getegid, EXIT_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallExit, getegidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/geteuid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/geteuid_x.cpp index 1a6f5860d6..eb59762911 100644 --- a/test/drivers/test_suites/syscall_exit_suite/geteuid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/geteuid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_geteuid -TEST(SyscallExit, geteuidX) -{ +TEST(SyscallExit, geteuidX) { auto evt_test = get_syscall_event_test(__NR_geteuid, EXIT_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallExit, geteuidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getgid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getgid_x.cpp index 70717efe19..7a5ad775cc 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getgid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getgid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getgid -TEST(SyscallExit, getgidX) -{ +TEST(SyscallExit, getgidX) { auto evt_test = get_syscall_event_test(__NR_getgid, EXIT_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallExit, getgidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getpeername_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getpeername_x.cpp index f94c17c1ac..e47afb071d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getpeername_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getpeername_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getpeername -TEST(SyscallExit, getpeernameX) -{ +TEST(SyscallExit, getpeernameX) { auto evt_test = get_syscall_event_test(__NR_getpeername, EXIT_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallExit, getpeernameX) int32_t mock_fd = -1; void* usockaddr = NULL; int* usockaddr_len = NULL; - assert_syscall_state(SYSCALL_FAILURE, "getpeername", syscall(__NR_getpeername, mock_fd, usockaddr, usockaddr_len)); + assert_syscall_state(SYSCALL_FAILURE, + "getpeername", + syscall(__NR_getpeername, mock_fd, usockaddr, usockaddr_len)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallExit, getpeernameX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getresgid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getresgid_x.cpp index dc91f6fc8c..7c8eb0d302 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getresgid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getresgid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getresgid -TEST(SyscallExit, getresgidX) -{ +TEST(SyscallExit, getresgidX) { auto evt_test = get_syscall_event_test(__NR_getresgid, EXIT_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallExit, getresgidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -33,8 +31,8 @@ TEST(SyscallExit, getresgidX) /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ - evt_test->assert_numeric_param(1, (int64_t)res); + /* Parameter 1: res (type: PT_ERRNO) */ + evt_test->assert_numeric_param(1, (int64_t)res); /* Parameter 2: ruid (type: PT_GID) */ evt_test->assert_numeric_param(2, (uint32_t)rgid); diff --git a/test/drivers/test_suites/syscall_exit_suite/getresuid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getresuid_x.cpp index 4ddd369bf9..41331de295 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getresuid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getresuid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getresuid -TEST(SyscallExit, getresuidX) -{ +TEST(SyscallExit, getresuidX) { auto evt_test = get_syscall_event_test(__NR_getresuid, EXIT_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallExit, getresuidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -33,8 +31,8 @@ TEST(SyscallExit, getresuidX) /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ - evt_test->assert_numeric_param(1, (int64_t)res); + /* Parameter 1: res (type: PT_ERRNO) */ + evt_test->assert_numeric_param(1, (int64_t)res); /* Parameter 2: ruid (type: PT_UID) */ evt_test->assert_numeric_param(2, (uint32_t)ruid); diff --git a/test/drivers/test_suites/syscall_exit_suite/getrlimit_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getrlimit_x.cpp index acd7ddc1a7..0dbb4fedcb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getrlimit_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getrlimit_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, getrlimitX_success) -{ +TEST(SyscallExit, getrlimitX_success) { auto evt_test = get_syscall_event_test(__NR_getrlimit, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,11 @@ TEST(SyscallExit, getrlimitX_success) int resource = RLIMIT_NPROC; struct rlimit rlim = {}; - assert_syscall_state(SYSCALL_SUCCESS, "getrlimit", syscall(__NR_getrlimit, resource, &rlim), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "getrlimit", + syscall(__NR_getrlimit, resource, &rlim), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +25,7 @@ TEST(SyscallExit, getrlimitX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -47,8 +49,7 @@ TEST(SyscallExit, getrlimitX_success) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, getrlimitX_wrong_resource) -{ +TEST(SyscallExit, getrlimitX_wrong_resource) { auto evt_test = get_syscall_event_test(__NR_getrlimit, EXIT_EVENT); evt_test->enable_capture(); @@ -66,8 +67,7 @@ TEST(SyscallExit, getrlimitX_wrong_resource) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -93,8 +93,7 @@ TEST(SyscallExit, getrlimitX_wrong_resource) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, getrlimitX_null_rlimit_pointer) -{ +TEST(SyscallExit, getrlimitX_null_rlimit_pointer) { auto evt_test = get_syscall_event_test(__NR_getrlimit, EXIT_EVENT); evt_test->enable_capture(); @@ -111,8 +110,7 @@ TEST(SyscallExit, getrlimitX_null_rlimit_pointer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getsockname_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getsockname_x.cpp index 9ee6f4d580..17d1c26491 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getsockname_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getsockname_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getsockname -TEST(SyscallExit, getsocknameX) -{ +TEST(SyscallExit, getsocknameX) { auto evt_test = get_syscall_event_test(__NR_getsockname, EXIT_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallExit, getsocknameX) int32_t mock_fd = -1; void* usockaddr = NULL; int* usockaddr_len = NULL; - assert_syscall_state(SYSCALL_FAILURE, "getsockname", syscall(__NR_getsockname, mock_fd, usockaddr, usockaddr_len)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockname", + syscall(__NR_getsockname, mock_fd, usockaddr, usockaddr_len)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +21,7 @@ TEST(SyscallExit, getsocknameX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getsockopt_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getsockopt_x.cpp index 9c0d1e5bf7..14c11f0c41 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getsockopt_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getsockopt_x.cpp @@ -6,8 +6,7 @@ #include #if defined(__NR_socket) && defined(__NR_setsockopt) && defined(__NR_close) -TEST(SyscallExit, getsockoptX_success) -{ +TEST(SyscallExit, getsockoptX_success) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -20,7 +19,16 @@ TEST(SyscallExit, getsockoptX_success) /* This option allow us to reuse the same address. */ int32_t setsockopt_option_value = 1; socklen_t setsockopt_option_len = sizeof(setsockopt_option_value); - assert_syscall_state(SYSCALL_SUCCESS, "setsockopt", syscall(__NR_setsockopt, socketfd, SOL_SOCKET, SO_REUSEADDR, &setsockopt_option_value, setsockopt_option_len), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setsockopt", + syscall(__NR_setsockopt, + socketfd, + SOL_SOCKET, + SO_REUSEADDR, + &setsockopt_option_value, + setsockopt_option_len), + NOT_EQUAL, + -1); /* Check if we are able to get the right option just set */ int32_t level = SOL_SOCKET; @@ -28,7 +36,12 @@ TEST(SyscallExit, getsockoptX_success) /* just a fake value that should be overwritten by the real value */ int32_t option_value = 14; socklen_t option_len = sizeof(int32_t); - assert_syscall_state(SYSCALL_SUCCESS, "getsockopt", syscall(__NR_getsockopt, socketfd, level, option_name, &option_value, &option_len), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "getsockopt", + syscall(__NR_getsockopt, socketfd, level, option_name, &option_value, &option_len), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, socketfd); @@ -39,8 +52,7 @@ TEST(SyscallExit, getsockoptX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -63,7 +75,10 @@ TEST(SyscallExit, getsockoptX_success) evt_test->assert_numeric_param(4, (uint8_t)PPM_SOCKOPT_SO_REUSEADDR); /* Parameter 5: optval (type: PT_DYN) */ - evt_test->assert_setsockopt_val(5, PPM_SOCKOPT_IDX_UINT32, &setsockopt_option_value, setsockopt_option_len); + evt_test->assert_setsockopt_val(5, + PPM_SOCKOPT_IDX_UINT32, + &setsockopt_option_value, + setsockopt_option_len); /* Parameter 6: optlen (type: PT_UINT32) */ evt_test->assert_numeric_param(6, (uint32_t)setsockopt_option_len); @@ -74,8 +89,7 @@ TEST(SyscallExit, getsockoptX_success) } #endif -TEST(SyscallExit, getsockoptX_SO_RCVTIMEO) -{ +TEST(SyscallExit, getsockoptX_SO_RCVTIMEO) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -89,7 +103,10 @@ TEST(SyscallExit, getsockoptX_SO_RCVTIMEO) option_value.tv_sec = 5; option_value.tv_usec = 10; socklen_t option_len = sizeof(struct timeval); - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -98,8 +115,7 @@ TEST(SyscallExit, getsockoptX_SO_RCVTIMEO) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -133,8 +149,7 @@ TEST(SyscallExit, getsockoptX_SO_RCVTIMEO) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, getsockoptX_SO_COOKIE) -{ +TEST(SyscallExit, getsockoptX_SO_COOKIE) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -146,7 +161,10 @@ TEST(SyscallExit, getsockoptX_SO_COOKIE) int32_t option_name = SO_COOKIE; uint64_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -155,8 +173,7 @@ TEST(SyscallExit, getsockoptX_SO_COOKIE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -189,8 +206,7 @@ TEST(SyscallExit, getsockoptX_SO_COOKIE) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, getsockoptX_SO_PASSCRED) -{ +TEST(SyscallExit, getsockoptX_SO_PASSCRED) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -202,7 +218,10 @@ TEST(SyscallExit, getsockoptX_SO_PASSCRED) int32_t option_name = SO_PASSCRED; uint32_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -211,8 +230,7 @@ TEST(SyscallExit, getsockoptX_SO_PASSCRED) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -245,8 +263,7 @@ TEST(SyscallExit, getsockoptX_SO_PASSCRED) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, getsockoptX_UNKNOWN_OPTION) -{ +TEST(SyscallExit, getsockoptX_UNKNOWN_OPTION) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -258,7 +275,10 @@ TEST(SyscallExit, getsockoptX_UNKNOWN_OPTION) int32_t option_name = -1; /* this is an unknown option. */ uint32_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -267,8 +287,7 @@ TEST(SyscallExit, getsockoptX_UNKNOWN_OPTION) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -301,8 +320,7 @@ TEST(SyscallExit, getsockoptX_UNKNOWN_OPTION) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, getsockoptX_SOL_UNKNOWN) -{ +TEST(SyscallExit, getsockoptX_SOL_UNKNOWN) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -314,7 +332,10 @@ TEST(SyscallExit, getsockoptX_SOL_UNKNOWN) int32_t option_name = SO_PASSCRED; uint32_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -323,8 +344,7 @@ TEST(SyscallExit, getsockoptX_SOL_UNKNOWN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -357,8 +377,7 @@ TEST(SyscallExit, getsockoptX_SOL_UNKNOWN) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, getsockoptX_ZERO_OPTLEN) -{ +TEST(SyscallExit, getsockoptX_ZERO_OPTLEN) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -370,7 +389,10 @@ TEST(SyscallExit, getsockoptX_ZERO_OPTLEN) int32_t option_name = SO_PASSCRED; uint32_t option_value = 0; socklen_t option_len = 0; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_getsockopt, mock_fd, level, option_name, &option_value, &option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -379,8 +401,7 @@ TEST(SyscallExit, getsockoptX_ZERO_OPTLEN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/gettimeofday_x.cpp b/test/drivers/test_suites/syscall_exit_suite/gettimeofday_x.cpp index d5efc0e32e..216eb08802 100644 --- a/test/drivers/test_suites/syscall_exit_suite/gettimeofday_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/gettimeofday_x.cpp @@ -2,8 +2,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_gettimeofday -TEST(SyscallExit, gettimeofday_X) -{ +TEST(SyscallExit, gettimeofday_X) { auto evt_test = get_syscall_event_test(__NR_gettimeofday, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, gettimeofday_X) /* Retrieve events in order. */ evt_test->assert_event_presence(CURRENT_PID, PPME_GENERIC_X); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/getuid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/getuid_x.cpp index 1591f9ece3..bbb03e6619 100644 --- a/test/drivers/test_suites/syscall_exit_suite/getuid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/getuid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_getuid -TEST(SyscallExit, getuidX) -{ +TEST(SyscallExit, getuidX) { auto evt_test = get_syscall_event_test(__NR_getuid, EXIT_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallExit, getuidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/init_module_x.cpp b/test/drivers/test_suites/syscall_exit_suite/init_module_x.cpp index 4cc014ad1a..3e9906b0bb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/init_module_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/init_module_x.cpp @@ -2,8 +2,7 @@ #if defined(__NR_init_module) -TEST(SyscallExit, init_moduleX_failure) -{ +TEST(SyscallExit, init_moduleX_failure) { auto evt_test = get_syscall_event_test(__NR_init_module, EXIT_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallExit, init_moduleX_failure) /* * Call the `init_module` */ - assert_syscall_state(SYSCALL_FAILURE, "init_module", syscall(__NR_init_module, (void*)mock_img, data_len, (void *)mock_buf)); + assert_syscall_state(SYSCALL_FAILURE, + "init_module", + syscall(__NR_init_module, (void *)mock_img, data_len, (void *)mock_buf)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallExit, init_moduleX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/inotify_init1_x.cpp b/test/drivers/test_suites/syscall_exit_suite/inotify_init1_x.cpp index 5275dd7925..30245e1ae5 100644 --- a/test/drivers/test_suites/syscall_exit_suite/inotify_init1_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/inotify_init1_x.cpp @@ -2,8 +2,7 @@ #if defined(__NR_inotify_init1) && defined(__NR_close) #include -TEST(SyscallExit, inotify_init1X_success) -{ +TEST(SyscallExit, inotify_init1X_success) { auto evt_test = get_syscall_event_test(__NR_inotify_init1, EXIT_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallExit, inotify_init1X_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -45,8 +43,7 @@ TEST(SyscallExit, inotify_init1X_success) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, inotify_init1X_failure) -{ +TEST(SyscallExit, inotify_init1X_failure) { auto evt_test = get_syscall_event_test(__NR_inotify_init1, EXIT_EVENT); evt_test->enable_capture(); @@ -64,8 +61,7 @@ TEST(SyscallExit, inotify_init1X_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/inotify_init_x.cpp b/test/drivers/test_suites/syscall_exit_suite/inotify_init_x.cpp index d9b603ffdb..66654d935d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/inotify_init_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/inotify_init_x.cpp @@ -1,9 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_inotify_init) && defined(__NR_close) -TEST(SyscallExit, inotify_initX) -{ - +TEST(SyscallExit, inotify_initX) { auto evt_test = get_syscall_event_test(__NR_inotify_init, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +18,7 @@ TEST(SyscallExit, inotify_initX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/io_uring_enter_x.cpp b/test/drivers/test_suites/syscall_exit_suite/io_uring_enter_x.cpp index 4cde909dae..8308bd8c4e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/io_uring_enter_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/io_uring_enter_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, io_uring_enterX) -{ +TEST(SyscallExit, io_uring_enterX) { auto evt_test = get_syscall_event_test(__NR_io_uring_enter, EXIT_EVENT); evt_test->enable_capture(); @@ -23,7 +22,10 @@ TEST(SyscallExit, io_uring_enterX) #endif const void* argp = NULL; size_t argsz = 7; - assert_syscall_state(SYSCALL_FAILURE, "io_uring_enter", syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, argp, argsz)); + assert_syscall_state( + SYSCALL_FAILURE, + "io_uring_enter", + syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, argp, argsz)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -32,8 +34,7 @@ TEST(SyscallExit, io_uring_enterX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/io_uring_register_x.cpp b/test/drivers/test_suites/syscall_exit_suite/io_uring_register_x.cpp index 9a4ad2c65a..22fbbe6602 100644 --- a/test/drivers/test_suites/syscall_exit_suite/io_uring_register_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/io_uring_register_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, io_uring_registerX) -{ +TEST(SyscallExit, io_uring_registerX) { auto evt_test = get_syscall_event_test(__NR_io_uring_register, EXIT_EVENT); evt_test->enable_capture(); @@ -19,7 +18,9 @@ TEST(SyscallExit, io_uring_registerX) #endif const void* arg = (const void*)0x7fff5694dc58; unsigned int nr_args = 34; - assert_syscall_state(SYSCALL_FAILURE, "io_uring_register", syscall(__NR_io_uring_register, fd, opcode, arg, nr_args)); + assert_syscall_state(SYSCALL_FAILURE, + "io_uring_register", + syscall(__NR_io_uring_register, fd, opcode, arg, nr_args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +29,7 @@ TEST(SyscallExit, io_uring_registerX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/io_uring_setup_x.cpp b/test/drivers/test_suites/syscall_exit_suite/io_uring_setup_x.cpp index 6c394a9a99..944c47f2af 100644 --- a/test/drivers/test_suites/syscall_exit_suite/io_uring_setup_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/io_uring_setup_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, io_uring_setupX) -{ +TEST(SyscallExit, io_uring_setupX) { auto evt_test = get_syscall_event_test(__NR_io_uring_setup, EXIT_EVENT); evt_test->enable_capture(); @@ -35,7 +34,9 @@ TEST(SyscallExit, io_uring_setupX) params.features = IORING_FEAT_NODROP; expected_features = PPM_IORING_FEAT_NODROP; #endif - assert_syscall_state(SYSCALL_FAILURE, "io_uring_setup", syscall(__NR_io_uring_setup, entries, ¶ms)); + assert_syscall_state(SYSCALL_FAILURE, + "io_uring_setup", + syscall(__NR_io_uring_setup, entries, ¶ms)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -44,8 +45,7 @@ TEST(SyscallExit, io_uring_setupX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -84,8 +84,7 @@ TEST(SyscallExit, io_uring_setupX) evt_test->assert_num_params_pushed(8); } -TEST(SyscallExit, io_uring_setupX_with_NULL_pointer) -{ +TEST(SyscallExit, io_uring_setupX_with_NULL_pointer) { auto evt_test = get_syscall_event_test(__NR_io_uring_setup, EXIT_EVENT); evt_test->enable_capture(); @@ -94,7 +93,9 @@ TEST(SyscallExit, io_uring_setupX_with_NULL_pointer) uint32_t entries = 4; struct io_uring_params* params_pointer = NULL; - assert_syscall_state(SYSCALL_FAILURE, "io_uring_setup", syscall(__NR_io_uring_setup, entries, params_pointer)); + assert_syscall_state(SYSCALL_FAILURE, + "io_uring_setup", + syscall(__NR_io_uring_setup, entries, params_pointer)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -103,8 +104,7 @@ TEST(SyscallExit, io_uring_setupX_with_NULL_pointer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/ioctl_x.cpp b/test/drivers/test_suites/syscall_exit_suite/ioctl_x.cpp index fb70425503..c73208cdd0 100644 --- a/test/drivers/test_suites/syscall_exit_suite/ioctl_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/ioctl_x.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallExit, ioctlX) -{ +TEST(SyscallExit, ioctlX) { auto evt_test = get_syscall_event_test(__NR_ioctl, EXIT_EVENT); evt_test->enable_capture(); @@ -28,16 +27,12 @@ TEST(SyscallExit, ioctlX) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_ioctl, mock_fd, request, argp) == -1) - { + if(syscall(__NR_ioctl, mock_fd, request, argp) == -1) { /* SUCCESS because we want the call to fail */ exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -46,10 +41,13 @@ TEST(SyscallExit, ioctlX) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The ioctl call is successful while it should fail..." << std::endl; } @@ -62,8 +60,7 @@ TEST(SyscallExit, ioctlX) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/kill_x.cpp b/test/drivers/test_suites/syscall_exit_suite/kill_x.cpp index 3e4a377644..e1aacf5175 100644 --- a/test/drivers/test_suites/syscall_exit_suite/kill_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/kill_x.cpp @@ -2,8 +2,7 @@ #ifdef __NR_kill -TEST(SyscallExit, killX) -{ +TEST(SyscallExit, killX) { auto evt_test = get_syscall_event_test(__NR_kill, EXIT_EVENT); evt_test->enable_capture(); @@ -17,7 +16,11 @@ TEST(SyscallExit, killX) */ int32_t mock_pid = 0; int32_t signal = 0; - assert_syscall_state(SYSCALL_SUCCESS, "kill", syscall(__NR_kill, mock_pid, signal), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "kill", + syscall(__NR_kill, mock_pid, signal), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +28,7 @@ TEST(SyscallExit, killX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/lchown_x.cpp b/test/drivers/test_suites/syscall_exit_suite/lchown_x.cpp index 6785f0a7d0..8b66b4cceb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/lchown_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/lchown_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_lchown -TEST(SyscallExit, lchownX) -{ +TEST(SyscallExit, lchownX) { auto evt_test = get_syscall_event_test(__NR_lchown, EXIT_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallExit, lchownX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/link_x.cpp b/test/drivers/test_suites/syscall_exit_suite/link_x.cpp index 9d9293c75c..f231c33b5b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/link_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/link_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_link -TEST(SyscallExit, linkX) -{ +TEST(SyscallExit, linkX) { auto evt_test = get_syscall_event_test(__NR_link, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, linkX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/linkat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/linkat_x.cpp index bd7a26a842..e3aa2700eb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/linkat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/linkat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_linkat -TEST(SyscallExit, linkatX) -{ +TEST(SyscallExit, linkatX) { auto evt_test = get_syscall_event_test(__NR_linkat, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallExit, linkatX) const char* old_path = "/xyzk-this/is/the/old/path"; const char* new_path = "/xyzk-this/is/the/new/path/"; uint32_t flags = AT_SYMLINK_FOLLOW; - assert_syscall_state(SYSCALL_FAILURE, "linkat", syscall(__NR_linkat, old_fd, old_path, new_fd, new_path, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "linkat", + syscall(__NR_linkat, old_fd, old_path, new_fd, new_path, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallExit, linkatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/listen_x.cpp b/test/drivers/test_suites/syscall_exit_suite/listen_x.cpp index 3c8dae28c4..661c50fdd7 100644 --- a/test/drivers/test_suites/syscall_exit_suite/listen_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/listen_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_listen -TEST(SyscallExit, listenX) -{ +TEST(SyscallExit, listenX) { auto evt_test = get_syscall_event_test(__NR_listen, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, listenX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/llseek_x.cpp b/test/drivers/test_suites/syscall_exit_suite/llseek_x.cpp index c3393afbe9..7efa8bc2dc 100644 --- a/test/drivers/test_suites/syscall_exit_suite/llseek_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/llseek_x.cpp @@ -3,8 +3,7 @@ #include #ifdef __NR_llseek -TEST(SyscallExit, llseekX) -{ +TEST(SyscallExit, llseekX) { auto evt_test = get_syscall_event_test(__NR_llseek, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, llseekX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/lseek_x.cpp b/test/drivers/test_suites/syscall_exit_suite/lseek_x.cpp index 6e9d645f26..1dde47c020 100644 --- a/test/drivers/test_suites/syscall_exit_suite/lseek_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/lseek_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_lseek -TEST(SyscallExit, lseekX) -{ +TEST(SyscallExit, lseekX) { auto evt_test = get_syscall_event_test(__NR_lseek, EXIT_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallExit, lseekX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/lstat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/lstat_x.cpp index f6a1f223e5..53f86e70b8 100644 --- a/test/drivers/test_suites/syscall_exit_suite/lstat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/lstat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_lstat -TEST(SyscallExit, lstatX) -{ +TEST(SyscallExit, lstatX) { auto evt_test = get_syscall_event_test(__NR_lstat, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, lstatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/memfd_create_x.cpp b/test/drivers/test_suites/syscall_exit_suite/memfd_create_x.cpp index b25bbe1600..e5b74bf18d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/memfd_create_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/memfd_create_x.cpp @@ -4,95 +4,91 @@ #if defined(__NR_memfd_create) && defined(MFD_ALLOW_SEALING) -TEST(SyscallExit, memfd_createX_success) -{ - auto evt_test = get_syscall_event_test(__NR_memfd_create, EXIT_EVENT); +TEST(SyscallExit, memfd_createX_success) { + auto evt_test = get_syscall_event_test(__NR_memfd_create, EXIT_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - const char* fileName = "test"; - int flags = MFD_ALLOW_SEALING | MFD_CLOEXEC; - int fd = syscall(__NR_memfd_create, fileName, flags); - assert_syscall_state(SYSCALL_SUCCESS, "memfd_create", fd, NOT_EQUAL, -1); - close(fd); + const char* fileName = "test"; + int flags = MFD_ALLOW_SEALING | MFD_CLOEXEC; + int fd = syscall(__NR_memfd_create, fileName, flags); + assert_syscall_state(SYSCALL_SUCCESS, "memfd_create", fd, NOT_EQUAL, -1); + close(fd); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: ret (type: PT_FD)*/ - evt_test->assert_numeric_param(1, (int64_t)fd); + /* Parameter 1: ret (type: PT_FD)*/ + evt_test->assert_numeric_param(1, (int64_t)fd); - /* Parameter 2: name (type: PT_CHARBUF) */ - evt_test->assert_charbuf_param(2, fileName); + /* Parameter 2: name (type: PT_CHARBUF) */ + evt_test->assert_charbuf_param(2, fileName); - /* Parameter 3: flags (type: PT_FLAGS32) */ - evt_test->assert_numeric_param(3, (uint32_t)PPM_MFD_ALLOW_SEALING | PPM_MFD_CLOEXEC); + /* Parameter 3: flags (type: PT_FLAGS32) */ + evt_test->assert_numeric_param(3, (uint32_t)PPM_MFD_ALLOW_SEALING | PPM_MFD_CLOEXEC); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(3); + evt_test->assert_num_params_pushed(3); } +TEST(SyscallExit, memfd_createX_failure) { + auto evt_test = get_syscall_event_test(__NR_memfd_create, EXIT_EVENT); -TEST(SyscallExit, memfd_createX_failure) -{ - auto evt_test = get_syscall_event_test(__NR_memfd_create, EXIT_EVENT); + evt_test->enable_capture(); - evt_test->enable_capture(); + /*=============================== TRIGGER SYSCALL ===========================*/ - /*=============================== TRIGGER SYSCALL ===========================*/ + const char* name = "test"; + int flags = -1; + assert_syscall_state(SYSCALL_FAILURE, "memfd_create", syscall(__NR_memfd_create, name, flags)); + int64_t errno_value = -errno; - const char* name = "test"; - int flags = -1; - assert_syscall_state(SYSCALL_FAILURE, "memfd_create",syscall(__NR_memfd_create,name,flags)); - int64_t errno_value = -errno; + /*=============================== TRIGGER SYSCALL ===========================*/ - /*=============================== TRIGGER SYSCALL ===========================*/ + evt_test->disable_capture(); - evt_test->disable_capture(); + evt_test->assert_event_presence(); - evt_test->assert_event_presence(); + if(HasFatalFailure()) { + return; + } - if(HasFatalFailure()){ - return; - } + evt_test->parse_event(); - evt_test->parse_event(); + evt_test->assert_header(); - evt_test->assert_header(); + /*=============================== ASSERT PARAMETERS ===========================*/ - /*=============================== ASSERT PARAMETERS ===========================*/ + /* Parameter 1: ret (type: PT_FD)*/ + evt_test->assert_numeric_param(1, (int64_t)errno_value); - /* Parameter 1: ret (type: PT_FD)*/ - evt_test->assert_numeric_param(1, (int64_t)errno_value); + /* Parameter 2: name (type: PT_CHARBUF) */ + evt_test->assert_charbuf_param(2, name); - /* Parameter 2: name (type: PT_CHARBUF) */ - evt_test->assert_charbuf_param(2, name); + /* Parameter 3: flags (type: PT_FLAGS32) */ + evt_test->assert_numeric_param( + 3, + (uint32_t)PPM_MFD_ALLOW_SEALING | PPM_MFD_CLOEXEC | PPM_MFD_HUGETLB); - /* Parameter 3: flags (type: PT_FLAGS32) */ - evt_test->assert_numeric_param(3, (uint32_t)PPM_MFD_ALLOW_SEALING | PPM_MFD_CLOEXEC | PPM_MFD_HUGETLB); - - - /*=============================== ASSERT PARAMETERS ===========================*/ - - evt_test->assert_num_params_pushed(3); + /*=============================== ASSERT PARAMETERS ===========================*/ + evt_test->assert_num_params_pushed(3); } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/mkdir_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mkdir_x.cpp index f3ba6440d4..50a02197e5 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mkdir_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mkdir_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_mkdir -TEST(SyscallExit, mkdirX) -{ +TEST(SyscallExit, mkdirX) { auto evt_test = get_syscall_event_test(__NR_mkdir, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, mkdirX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mkdirat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mkdirat_x.cpp index 8375840147..828e503b05 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mkdirat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mkdirat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_mkdirat -TEST(SyscallExit, mkdiratX) -{ +TEST(SyscallExit, mkdiratX) { auto evt_test = get_syscall_event_test(__NR_mkdirat, EXIT_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallExit, mkdiratX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mknod_e.cpp b/test/drivers/test_suites/syscall_exit_suite/mknod_e.cpp index 8665a4164a..37c34f42bb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mknod_e.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mknod_e.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_mknod) #include -TEST(SyscallEnter, mknodE_failure) -{ +TEST(SyscallEnter, mknodE_failure) { auto evt_test = get_syscall_event_test(__NR_mknod, ENTER_EVENT); evt_test->enable_capture(); @@ -12,8 +11,9 @@ TEST(SyscallEnter, mknodE_failure) uint32_t mode = 0060000 | 0666; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknod", syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); - + assert_syscall_state(SYSCALL_FAILURE, + "mknod", + syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +21,7 @@ TEST(SyscallEnter, mknodE_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -37,6 +36,5 @@ TEST(SyscallEnter, mknodE_failure) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); - } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/mknod_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mknod_x.cpp index ec3270ea60..dc47c9bf69 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mknod_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mknod_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_mknod) #include -TEST(SyscallExit, mknodX_failure) -{ +TEST(SyscallExit, mknodX_failure) { auto evt_test = get_syscall_event_test(__NR_mknod, EXIT_EVENT); evt_test->enable_capture(); @@ -12,18 +11,18 @@ TEST(SyscallExit, mknodX_failure) uint32_t mode = 0060000 | 0666; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknod", syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknod", + syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -48,11 +47,9 @@ TEST(SyscallExit, mknodX_failure) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(4); - } -TEST(SyscallExit, mknodX_failure_S_IFREG) -{ +TEST(SyscallExit, mknodX_failure_S_IFREG) { auto evt_test = get_syscall_event_test(__NR_mknod, EXIT_EVENT); evt_test->enable_capture(); @@ -62,18 +59,18 @@ TEST(SyscallExit, mknodX_failure_S_IFREG) mode_t mode = S_IXUSR | S_IFREG; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknod", syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknod", + syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -98,11 +95,9 @@ TEST(SyscallExit, mknodX_failure_S_IFREG) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(4); - } -TEST(SyscallExit, mknodX_failure_S_IFCHR) -{ +TEST(SyscallExit, mknodX_failure_S_IFCHR) { auto evt_test = get_syscall_event_test(__NR_mknod, EXIT_EVENT); evt_test->enable_capture(); @@ -112,18 +107,18 @@ TEST(SyscallExit, mknodX_failure_S_IFCHR) mode_t mode = S_IXUSR | S_IFCHR; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknod", syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknod", + syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -148,11 +143,9 @@ TEST(SyscallExit, mknodX_failure_S_IFCHR) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(4); - } -TEST(SyscallExit, mknodX_failure_S_IFBLK) -{ +TEST(SyscallExit, mknodX_failure_S_IFBLK) { auto evt_test = get_syscall_event_test(__NR_mknod, EXIT_EVENT); evt_test->enable_capture(); @@ -162,18 +155,18 @@ TEST(SyscallExit, mknodX_failure_S_IFBLK) mode_t mode = S_IXUSR | S_IFBLK; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknod", syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknod", + syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -198,11 +191,9 @@ TEST(SyscallExit, mknodX_failure_S_IFBLK) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(4); - } -TEST(SyscallExit, mknodX_failure_S_IFIFO) -{ +TEST(SyscallExit, mknodX_failure_S_IFIFO) { auto evt_test = get_syscall_event_test(__NR_mknod, EXIT_EVENT); evt_test->enable_capture(); @@ -212,18 +203,18 @@ TEST(SyscallExit, mknodX_failure_S_IFIFO) mode_t mode = S_IXUSR | S_IFIFO; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknod", syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknod", + syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -248,11 +239,9 @@ TEST(SyscallExit, mknodX_failure_S_IFIFO) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(4); - } -TEST(SyscallExit, mknodX_failure_S_IFSOCK) -{ +TEST(SyscallExit, mknodX_failure_S_IFSOCK) { auto evt_test = get_syscall_event_test(__NR_mknod, EXIT_EVENT); evt_test->enable_capture(); @@ -262,18 +251,18 @@ TEST(SyscallExit, mknodX_failure_S_IFSOCK) mode_t mode = S_IXUSR | S_IFSOCK; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknod", syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknod", + syscall(__NR_mknod, (void *)(path), (mode_t)mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -298,6 +287,5 @@ TEST(SyscallExit, mknodX_failure_S_IFSOCK) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(4); - } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/mknodat_e.cpp b/test/drivers/test_suites/syscall_exit_suite/mknodat_e.cpp index 93c8e0f33a..a73742b409 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mknodat_e.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mknodat_e.cpp @@ -1,7 +1,6 @@ #include "../../event_class/event_class.h" #if defined(__NR_mknodat) -TEST(SyscallEnter, mknodatE_failure) -{ +TEST(SyscallEnter, mknodatE_failure) { auto evt_test = get_syscall_event_test(__NR_mknodat, ENTER_EVENT); evt_test->enable_capture(); @@ -10,8 +9,9 @@ TEST(SyscallEnter, mknodatE_failure) int mock_fd = -1; char mock_buf[100]; - assert_syscall_state(SYSCALL_FAILURE, "mknodat", syscall(__NR_mknodat, mock_fd, (void *)(mock_buf), NULL, 0)); - + assert_syscall_state(SYSCALL_FAILURE, + "mknodat", + syscall(__NR_mknodat, mock_fd, (void *)(mock_buf), NULL, 0)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -19,8 +19,7 @@ TEST(SyscallEnter, mknodatE_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -35,6 +34,5 @@ TEST(SyscallEnter, mknodatE_failure) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(0); - } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/mknodat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mknodat_x.cpp index c13b442881..465df5ef65 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mknodat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mknodat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #if defined(__NR_mknodat) #include -TEST(SyscallExit, mknodatX_failure) -{ +TEST(SyscallExit, mknodatX_failure) { auto evt_test = get_syscall_event_test(__NR_mknodat, EXIT_EVENT); evt_test->enable_capture(); @@ -12,18 +11,18 @@ TEST(SyscallExit, mknodatX_failure) char path[] = "/tmp/"; uint32_t mode = 0060000 | 0666; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknodat", syscall(__NR_mknodat, fd, (void *)(path), (mode_t)mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknodat", + syscall(__NR_mknodat, fd, (void *)(path), (mode_t)mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -51,11 +50,9 @@ TEST(SyscallExit, mknodatX_failure) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(5); - } -TEST(SyscallExit, mknodatX_failure_S_IFREG) -{ +TEST(SyscallExit, mknodatX_failure_S_IFREG) { auto evt_test = get_syscall_event_test(__NR_mknodat, EXIT_EVENT); evt_test->enable_capture(); @@ -65,18 +62,18 @@ TEST(SyscallExit, mknodatX_failure_S_IFREG) char path[] = "/tmp/"; mode_t mode = S_IXUSR | S_IFREG; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknodat", syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknodat", + syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -104,11 +101,9 @@ TEST(SyscallExit, mknodatX_failure_S_IFREG) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(5); - } -TEST(SyscallExit, mknodatX_failure_S_IFCHR) -{ +TEST(SyscallExit, mknodatX_failure_S_IFCHR) { auto evt_test = get_syscall_event_test(__NR_mknodat, EXIT_EVENT); evt_test->enable_capture(); @@ -118,18 +113,18 @@ TEST(SyscallExit, mknodatX_failure_S_IFCHR) char path[] = "/tmp/"; mode_t mode = S_IXUSR | S_IFCHR; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknodat", syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknodat", + syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -157,11 +152,9 @@ TEST(SyscallExit, mknodatX_failure_S_IFCHR) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(5); - } -TEST(SyscallExit, mknodatX_failure_S_IFBLK) -{ +TEST(SyscallExit, mknodatX_failure_S_IFBLK) { auto evt_test = get_syscall_event_test(__NR_mknodat, EXIT_EVENT); evt_test->enable_capture(); @@ -171,18 +164,18 @@ TEST(SyscallExit, mknodatX_failure_S_IFBLK) char path[] = "/tmp/"; mode_t mode = S_IXUSR | S_IFBLK; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknodat", syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknodat", + syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -210,11 +203,9 @@ TEST(SyscallExit, mknodatX_failure_S_IFBLK) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(5); - } -TEST(SyscallExit, mknodatX_failure_S_IFIFO) -{ +TEST(SyscallExit, mknodatX_failure_S_IFIFO) { auto evt_test = get_syscall_event_test(__NR_mknodat, EXIT_EVENT); evt_test->enable_capture(); @@ -224,18 +215,18 @@ TEST(SyscallExit, mknodatX_failure_S_IFIFO) char path[] = "/tmp/"; mode_t mode = S_IXUSR | S_IFIFO; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknodat", syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknodat", + syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -263,11 +254,9 @@ TEST(SyscallExit, mknodatX_failure_S_IFIFO) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(5); - } -TEST(SyscallExit, mknodatX_failure_S_IFSOCK) -{ +TEST(SyscallExit, mknodatX_failure_S_IFSOCK) { auto evt_test = get_syscall_event_test(__NR_mknodat, EXIT_EVENT); evt_test->enable_capture(); @@ -277,18 +266,18 @@ TEST(SyscallExit, mknodatX_failure_S_IFSOCK) char path[] = "/tmp/"; mode_t mode = S_IXUSR | S_IFSOCK; uint32_t dev = 61440; - assert_syscall_state(SYSCALL_FAILURE, "mknodat", syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); + assert_syscall_state(SYSCALL_FAILURE, + "mknodat", + syscall(__NR_mknodat, fd, (void *)(path), mode, (dev_t)dev)); int64_t errno_value = -errno; - /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -316,6 +305,5 @@ TEST(SyscallExit, mknodatX_failure_S_IFSOCK) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(5); - } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/mlock2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mlock2_x.cpp index c00df97972..45be301ea9 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mlock2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mlock2_x.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallExit, mlock2X) -{ +TEST(SyscallExit, mlock2X) { auto evt_test = get_syscall_event_test(__NR_mlock2, EXIT_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallExit, mlock2X) void *mock_addr = (void *)0; size_t mock_len = 4; int mock_flags = MLOCK_ONFAULT; - assert_syscall_state(SYSCALL_FAILURE, "mlock2", syscall(__NR_mlock2, mock_addr, mock_len, mock_flags)); + assert_syscall_state(SYSCALL_FAILURE, + "mlock2", + syscall(__NR_mlock2, mock_addr, mock_len, mock_flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallExit, mlock2X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mlock_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mlock_x.cpp index a55d9d0138..aa04e0c9a7 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mlock_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mlock_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, mlockX) -{ +TEST(SyscallExit, mlockX) { auto evt_test = get_syscall_event_test(__NR_mlock, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, mlockX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mlockall_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mlockall_x.cpp index 0a3c7ae41d..5faa6528cb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mlockall_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mlockall_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, mlockallX) -{ +TEST(SyscallExit, mlockallX) { auto evt_test = get_syscall_event_test(__NR_mlockall, EXIT_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallExit, mlockallX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mmap2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mmap2_x.cpp index b9f8e67bad..0cf79aa68e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mmap2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mmap2_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, mmap2X) -{ +TEST(SyscallExit, mmap2X) { auto evt_test = get_syscall_event_test(__NR_mmap2, EXIT_EVENT); evt_test->enable_capture(); @@ -19,7 +18,15 @@ TEST(SyscallExit, mmap2X) int mock_fd = -1; off_t mock_offset = 0; - assert_syscall_state(SYSCALL_FAILURE, "mmap", syscall(__NR_mmap2, mock_addr, mock_length, mock_prot, mock_flags, mock_fd, mock_offset)); + assert_syscall_state(SYSCALL_FAILURE, + "mmap", + syscall(__NR_mmap2, + mock_addr, + mock_length, + mock_prot, + mock_flags, + mock_fd, + mock_offset)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +35,7 @@ TEST(SyscallExit, mmap2X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mmap_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mmap_x.cpp index 41afbdcc4d..ad90c57ba9 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mmap_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mmap_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, mmapX) -{ +TEST(SyscallExit, mmapX) { auto evt_test = get_syscall_event_test(__NR_mmap, EXIT_EVENT); evt_test->enable_capture(); @@ -19,7 +18,15 @@ TEST(SyscallExit, mmapX) int mock_fd = -1; off_t mock_offset = 1023; - assert_syscall_state(SYSCALL_FAILURE, "mmap", syscall(__NR_mmap, mock_addr, mock_length, mock_prot, mock_flags, mock_fd, mock_offset)); + assert_syscall_state(SYSCALL_FAILURE, + "mmap", + syscall(__NR_mmap, + mock_addr, + mock_length, + mock_prot, + mock_flags, + mock_fd, + mock_offset)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +35,7 @@ TEST(SyscallExit, mmapX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mount_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mount_x.cpp index 8ce22b8e53..c6ae2eaf4b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mount_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mount_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, mountX) -{ +TEST(SyscallExit, mountX) { auto evt_test = get_syscall_event_test(__NR_mount, EXIT_EVENT); evt_test->enable_capture(); @@ -17,7 +16,9 @@ TEST(SyscallExit, mountX) const char* filesystemtype = "not_supported"; unsigned long flags = MS_MGC_VAL | MS_RDONLY; const void* data = NULL; - assert_syscall_state(SYSCALL_FAILURE, "mount", syscall(__NR_mount, source, target, filesystemtype, flags, data)); + assert_syscall_state(SYSCALL_FAILURE, + "mount", + syscall(__NR_mount, source, target, filesystemtype, flags, data)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -26,8 +27,7 @@ TEST(SyscallExit, mountX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/mprotect_x.cpp b/test/drivers/test_suites/syscall_exit_suite/mprotect_x.cpp index c219745bba..640249a5b8 100644 --- a/test/drivers/test_suites/syscall_exit_suite/mprotect_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/mprotect_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, mprotectX) -{ +TEST(SyscallExit, mprotectX) { auto evt_test = get_syscall_event_test(__NR_mprotect, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallExit, mprotectX) void *mock_addr = (void *)1; size_t mock_len = 4096; int mock_prot = PROT_READ | PROT_EXEC; - assert_syscall_state(SYSCALL_FAILURE, "mprotect", syscall(__NR_mprotect, mock_addr, mock_len, mock_prot)); + assert_syscall_state(SYSCALL_FAILURE, + "mprotect", + syscall(__NR_mprotect, mock_addr, mock_len, mock_prot)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallExit, mprotectX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/munlock_x.cpp b/test/drivers/test_suites/syscall_exit_suite/munlock_x.cpp index 02e73cde10..0ace7ec11a 100644 --- a/test/drivers/test_suites/syscall_exit_suite/munlock_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/munlock_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, munlockX) -{ +TEST(SyscallExit, munlockX) { auto evt_test = get_syscall_event_test(__NR_munlock, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, munlockX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/munlockall_x.cpp b/test/drivers/test_suites/syscall_exit_suite/munlockall_x.cpp index 4af32b3264..fe409497ba 100644 --- a/test/drivers/test_suites/syscall_exit_suite/munlockall_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/munlockall_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, munlockallX) -{ +TEST(SyscallExit, munlockallX) { auto evt_test = get_syscall_event_test(__NR_munlockall, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, munlockallX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/munmap_x.cpp b/test/drivers/test_suites/syscall_exit_suite/munmap_x.cpp index 0b3c1a3526..e582014ce5 100644 --- a/test/drivers/test_suites/syscall_exit_suite/munmap_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/munmap_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, munmapX) -{ +TEST(SyscallExit, munmapX) { auto evt_test = get_syscall_event_test(__NR_munmap, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, munmapX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/nanosleep_x.cpp b/test/drivers/test_suites/syscall_exit_suite/nanosleep_x.cpp index 4f2f1c4568..ca3917b088 100644 --- a/test/drivers/test_suites/syscall_exit_suite/nanosleep_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/nanosleep_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_nanosleep -TEST(SyscallExit, nanosleepX) -{ +TEST(SyscallExit, nanosleepX) { auto evt_test = get_syscall_event_test(__NR_nanosleep, EXIT_EVENT); evt_test->enable_capture(); @@ -18,8 +17,7 @@ TEST(SyscallExit, nanosleepX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/newfstatat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/newfstatat_x.cpp index fcae5d44a3..baa51aa36e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/newfstatat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/newfstatat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_newfstatat -TEST(SyscallExit, newfstatatX_success) -{ +TEST(SyscallExit, newfstatatX_success) { auto evt_test = get_syscall_event_test(__NR_newfstatat, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, newfstatatX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -51,8 +49,7 @@ TEST(SyscallExit, newfstatatX_success) evt_test->assert_num_params_pushed(4); } -TEST(SyscallExit, newfstatatX_failure) -{ +TEST(SyscallExit, newfstatatX_failure) { auto evt_test = get_syscall_event_test(__NR_newfstatat, EXIT_EVENT); evt_test->enable_capture(); @@ -74,8 +71,7 @@ TEST(SyscallExit, newfstatatX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -102,4 +98,4 @@ TEST(SyscallExit, newfstatatX_failure) evt_test->assert_num_params_pushed(4); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/open_by_handle_at_x.cpp b/test/drivers/test_suites/syscall_exit_suite/open_by_handle_at_x.cpp index b4c7a75413..ea5bf14489 100644 --- a/test/drivers/test_suites/syscall_exit_suite/open_by_handle_at_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/open_by_handle_at_x.cpp @@ -6,23 +6,26 @@ #if defined(__NR_open_by_handle_at) && defined(__NR_name_to_handle_at) && defined(__NR_openat) -#define MAX_FSPATH_LEN 4096 - -void do___open_by_handle_atX_success(int *open_by_handle_fd, int *dirfd, char *fspath, uint32_t *dev, uint64_t *inode, bool *is_ext4, int use_mountpoint) -{ +#define MAX_FSPATH_LEN 4096 + +void do___open_by_handle_atX_success(int *open_by_handle_fd, + int *dirfd, + char *fspath, + uint32_t *dev, + uint64_t *inode, + bool *is_ext4, + int use_mountpoint) { /* * 0. Create (temporary) mount point (if use_mountpoint). */ char tmpdir[] = "/tmp/modern.bpf.open_by_handle_atX_success_mp.XXXXXX"; char *dir_name = NULL; *dirfd = AT_FDCWD; - if(use_mountpoint) - { + if(use_mountpoint) { int rc; dir_name = mkdtemp(tmpdir); - if (dir_name == NULL) - { + if(dir_name == NULL) { FAIL() << "Could not create temporary directory" << std::endl; } @@ -44,27 +47,29 @@ void do___open_by_handle_atX_success(int *open_by_handle_fd, int *dirfd, char *f struct file_handle *fhp; int fhsize = sizeof(*fhp); fhp = (struct file_handle *)malloc(fhsize); - if(fhp == NULL) - { + if(fhp == NULL) { FAIL() << "Error in allocating the `struct file_handle` with malloc" << std::endl; } - /* Make an initial call to name_to_handle_at() to discover the size required for the file handle. - * The caller can discover the required size for the file_handle structure by making a call in which handle->handle_bytes is zero; - * in this case, the call fails with the error EOVERFLOW and handle->handle_bytes is set to indicate the required size; + /* Make an initial call to name_to_handle_at() to discover the size required for the file + * handle. The caller can discover the required size for the file_handle structure by making a + * call in which handle->handle_bytes is zero; in this case, the call fails with the error + * EOVERFLOW and handle->handle_bytes is set to indicate the required size; */ int mount_id; int flags = 0; fhp->handle_bytes = 0; - assert_syscall_state(SYSCALL_FAILURE, "name_to_handle_at", syscall(__NR_name_to_handle_at, *dirfd, fo.get_pathname(), fhp, &mount_id, flags)); + assert_syscall_state( + SYSCALL_FAILURE, + "name_to_handle_at", + syscall(__NR_name_to_handle_at, *dirfd, fo.get_pathname(), fhp, &mount_id, flags)); /* * 2. Reallocate file_handle structure with the correct size. */ fhsize = sizeof(*fhp) + fhp->handle_bytes; struct file_handle *new_fhp = (struct file_handle *)realloc(fhp, fhsize); - if(new_fhp == NULL) - { + if(new_fhp == NULL) { free(fhp); FAIL() << "Error in allocating the `struct file_handle` with realloc" << std::endl; } @@ -73,7 +78,12 @@ void do___open_by_handle_atX_success(int *open_by_handle_fd, int *dirfd, char *f /* * 3. Get file handle. */ - assert_syscall_state(SYSCALL_SUCCESS, "name_to_handle_at", syscall(__NR_name_to_handle_at, *dirfd, fo.get_pathname(), fhp, &mount_id, flags), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "name_to_handle_at", + syscall(__NR_name_to_handle_at, *dirfd, fo.get_pathname(), fhp, &mount_id, flags), + NOT_EQUAL, + -1); /* * 4. Call `open_by_handle_at`. @@ -86,15 +96,11 @@ void do___open_by_handle_atX_success(int *open_by_handle_fd, int *dirfd, char *f /* * 5. Get the current working directory. */ - if(use_mountpoint) - { + if(use_mountpoint) { strlcpy(fspath, dir_name, MAX_FSPATH_LEN); - } - else - { + } else { char *err = getcwd(fspath, MAX_FSPATH_LEN); - if(!err) - { + if(!err) { FAIL() << "Could not get the current working directory" << std::endl; } } @@ -104,7 +110,11 @@ void do___open_by_handle_atX_success(int *open_by_handle_fd, int *dirfd, char *f * 6. Get dev and ino. */ struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, *open_by_handle_fd, &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, *open_by_handle_fd, &file_stat), + NOT_EQUAL, + -1); *dev = (uint32_t)file_stat.st_dev; *inode = file_stat.st_ino; *is_ext4 = event_test::is_ext4_fs(*open_by_handle_fd); @@ -115,39 +125,36 @@ void do___open_by_handle_atX_success(int *open_by_handle_fd, int *dirfd, char *f close(*open_by_handle_fd); free(fhp); - if(use_mountpoint) - { + if(use_mountpoint) { close(*dirfd); umount(dir_name); rmdir(dir_name); } - } -TEST(SyscallExit, open_by_handle_atX_success) -{ +TEST(SyscallExit, open_by_handle_atX_success) { auto evt_test = get_syscall_event_test(__NR_open_by_handle_at, EXIT_EVENT); auto fo = file_opener(".", (O_RDWR | O_TMPFILE | O_DIRECTORY)); - if(!fo.get_fd()) - { + if(!fo.get_fd()) { FAIL() << "Error opening current directory" << std::endl; } struct file_handle *fhp; fhp = (struct file_handle *)malloc(sizeof(*fhp) + sizeof(fhp->handle_bytes)); - if(fhp == NULL) - { + if(fhp == NULL) { FAIL() << "Error in allocating the `struct file_handle` with malloc" << std::endl; } int mount_id; fhp->handle_bytes = 0; - if(syscall(__NR_name_to_handle_at, AT_FDCWD, fo.get_pathname(), fhp, &mount_id, 0) != 0 && errno == EOPNOTSUPP) - { + if(syscall(__NR_name_to_handle_at, AT_FDCWD, fo.get_pathname(), fhp, &mount_id, 0) != 0 && + errno == EOPNOTSUPP) { /* * Run the test only if the filesystem supports name_to_handle_at. */ - GTEST_SKIP() << "[NAME_TO_HANDLE_AT]: the current filesystem doesn't support this operation." << std::endl; + GTEST_SKIP() + << "[NAME_TO_HANDLE_AT]: the current filesystem doesn't support this operation." + << std::endl; } evt_test->enable_capture(); @@ -161,15 +168,14 @@ TEST(SyscallExit, open_by_handle_atX_success) uint64_t inode; bool is_ext4; do___open_by_handle_atX_success(&open_by_handle_fd, &dirfd, fspath, &dev, &inode, &is_ext4, 0); - + /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -192,8 +198,7 @@ TEST(SyscallExit, open_by_handle_atX_success) #ifdef __NR_fstat /* Parameter 5: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(5, dev); } @@ -204,11 +209,9 @@ TEST(SyscallExit, open_by_handle_atX_success) /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(6); - } -TEST(SyscallExit, open_by_handle_atX_success_mp) -{ +TEST(SyscallExit, open_by_handle_atX_success_mp) { auto evt_test = get_syscall_event_test(__NR_open_by_handle_at, EXIT_EVENT); evt_test->enable_capture(); @@ -229,8 +232,7 @@ TEST(SyscallExit, open_by_handle_atX_success_mp) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -254,8 +256,7 @@ TEST(SyscallExit, open_by_handle_atX_success_mp) #ifdef __NR_fstat /* Parameter 5: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(5, dev); } @@ -268,8 +269,7 @@ TEST(SyscallExit, open_by_handle_atX_success_mp) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, open_by_handle_atX_failure) -{ +TEST(SyscallExit, open_by_handle_atX_failure) { auto evt_test = get_syscall_event_test(__NR_open_by_handle_at, EXIT_EVENT); evt_test->enable_capture(); @@ -283,7 +283,9 @@ TEST(SyscallExit, open_by_handle_atX_failure) int mount_fd = -1; struct file_handle *fhp = NULL; int flags = O_RDWR; - assert_syscall_state(SYSCALL_FAILURE, "open_by_handle_at", syscall(__NR_open_by_handle_at, mount_fd, fhp, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "open_by_handle_at", + syscall(__NR_open_by_handle_at, mount_fd, fhp, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -292,8 +294,7 @@ TEST(SyscallExit, open_by_handle_atX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { /* This could happen if: * - the syscall result state is different from the expected one. * - we are not able to find the event in the ring buffers. diff --git a/test/drivers/test_suites/syscall_exit_suite/open_x.cpp b/test/drivers/test_suites/syscall_exit_suite/open_x.cpp index 17f0b267d0..4a0f7f58e9 100644 --- a/test/drivers/test_suites/syscall_exit_suite/open_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/open_x.cpp @@ -5,8 +5,7 @@ #include /* Definitions for `fstat` syscall. */ -TEST(SyscallExit, openX_success) -{ +TEST(SyscallExit, openX_success) { auto evt_test = get_syscall_event_test(__NR_open, EXIT_EVENT); syscall(__NR_openat, AT_FDCWD, ".", O_RDWR | O_TMPFILE, 0); @@ -19,22 +18,25 @@ TEST(SyscallExit, openX_success) /* Syscall special notes: * With `O_TMPFILE` flag the pathname must be a directory. */ - const char* pathname = notmpfile? ".tmpfile" : "."; - int flags = notmpfile? (O_RDWR | O_CREAT | O_DIRECTORY) : (O_RDWR | O_TMPFILE | O_DIRECTORY); + const char* pathname = notmpfile ? ".tmpfile" : "."; + int flags = notmpfile ? (O_RDWR | O_CREAT | O_DIRECTORY) : (O_RDWR | O_TMPFILE | O_DIRECTORY); mode_t mode = 0; int fd = syscall(__NR_open, pathname, flags, mode); assert_syscall_state(SYSCALL_SUCCESS, "open", fd, NOT_EQUAL, -1); /* Call `fstat` to retrieve the `dev` and `ino`. */ struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, fd, &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, fd, &file_stat), + NOT_EQUAL, + -1); uint32_t dev = (uint32_t)file_stat.st_dev; uint64_t inode = file_stat.st_ino; const bool is_ext4 = event_test::is_ext4_fs(fd); close(fd); - if(notmpfile) - { + if(notmpfile) { unlink(pathname); } @@ -44,8 +46,7 @@ TEST(SyscallExit, openX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -62,7 +63,8 @@ TEST(SyscallExit, openX_success) evt_test->assert_charbuf_param(2, pathname); /* Parameter 3: flags (type: PT_FLAGS32) */ - uint32_t oflags = notmpfile ? (PPM_O_RDWR | PPM_O_CREAT | PPM_O_DIRECTORY) : (PPM_O_RDWR | PPM_O_TMPFILE | PPM_O_DIRECTORY); + uint32_t oflags = notmpfile ? (PPM_O_RDWR | PPM_O_CREAT | PPM_O_DIRECTORY) + : (PPM_O_RDWR | PPM_O_TMPFILE | PPM_O_DIRECTORY); evt_test->assert_numeric_param(3, oflags); /* Parameter 4: mode (type: PT_UINT32) */ @@ -70,8 +72,7 @@ TEST(SyscallExit, openX_success) evt_test->assert_numeric_param(4, (uint32_t)mode); /* Parameter 5: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(5, (uint32_t)dev); } @@ -83,8 +84,7 @@ TEST(SyscallExit, openX_success) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, openX_failure) -{ +TEST(SyscallExit, openX_failure) { auto evt_test = get_syscall_event_test(__NR_open, EXIT_EVENT); evt_test->enable_capture(); @@ -107,8 +107,7 @@ TEST(SyscallExit, openX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -144,8 +143,7 @@ TEST(SyscallExit, openX_failure) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, openX_create_success) -{ +TEST(SyscallExit, openX_create_success) { auto evt_test = get_syscall_event_test(__NR_open, EXIT_EVENT); evt_test->enable_capture(); @@ -167,8 +165,7 @@ TEST(SyscallExit, openX_create_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -188,7 +185,9 @@ TEST(SyscallExit, openX_create_success) evt_test->assert_numeric_param(3, (uint32_t)(PPM_O_RDWR | PPM_O_CREAT | PPM_O_F_CREATED)); /* Parameter 4: mode (type: PT_UINT32) */ - evt_test->assert_numeric_param(4, (uint32_t)(PPM_S_IRUSR | PPM_S_IWUSR | PPM_S_IXUSR | PPM_S_IRGRP | PPM_S_IXGRP)); + evt_test->assert_numeric_param( + 4, + (uint32_t)(PPM_S_IRUSR | PPM_S_IWUSR | PPM_S_IXUSR | PPM_S_IRGRP | PPM_S_IXGRP)); /* Parameter 5: dev (type: PT_UINT32) */ evt_test->assert_only_param_len(5, sizeof(uint32_t)); diff --git a/test/drivers/test_suites/syscall_exit_suite/openat2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/openat2_x.cpp index ea5eb40ffa..6fb6a59bc4 100644 --- a/test/drivers/test_suites/syscall_exit_suite/openat2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/openat2_x.cpp @@ -4,8 +4,7 @@ #include /* Definition of RESOLVE_* constants */ -TEST(SyscallExit, openat2X_success) -{ +TEST(SyscallExit, openat2X_success) { auto evt_test = get_syscall_event_test(__NR_openat2, EXIT_EVENT); evt_test->enable_capture(); @@ -27,7 +26,11 @@ TEST(SyscallExit, openat2X_success) #ifdef __NR_fstat /* Call `fstat` to retrieve the `dev` and `ino`. */ struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, fd, &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, fd, &file_stat), + NOT_EQUAL, + -1); uint32_t dev = (uint32_t)file_stat.st_dev; uint64_t inode = file_stat.st_ino; const bool is_ext4 = event_test::is_ext4_fs(fd); @@ -40,8 +43,7 @@ TEST(SyscallExit, openat2X_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -71,8 +73,7 @@ TEST(SyscallExit, openat2X_success) #ifdef __NR_fstat /* Parameter 7: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(7, dev); } @@ -85,8 +86,7 @@ TEST(SyscallExit, openat2X_success) evt_test->assert_num_params_pushed(8); } -TEST(SyscallExit, openat2X_failure) -{ +TEST(SyscallExit, openat2X_failure) { auto evt_test = get_syscall_event_test(__NR_openat2, EXIT_EVENT); evt_test->enable_capture(); @@ -104,7 +104,9 @@ TEST(SyscallExit, openat2X_failure) how.flags = O_RDWR | O_TMPFILE | O_DIRECTORY; how.mode = 0; how.resolve = RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS; - assert_syscall_state(SYSCALL_FAILURE, "openat2", syscall(__NR_openat2, dirfd, pathname, &how, sizeof(struct open_how))); + assert_syscall_state(SYSCALL_FAILURE, + "openat2", + syscall(__NR_openat2, dirfd, pathname, &how, sizeof(struct open_how))); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -113,8 +115,7 @@ TEST(SyscallExit, openat2X_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -149,14 +150,13 @@ TEST(SyscallExit, openat2X_failure) /* Parameter 8: ino (type: PT_UINT64) */ evt_test->assert_numeric_param(8, (uint64_t)0); - + /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(8); } -TEST(SyscallExit, openat2X_create_success) -{ +TEST(SyscallExit, openat2X_create_success) { auto evt_test = get_syscall_event_test(__NR_openat2, EXIT_EVENT); evt_test->enable_capture(); @@ -176,7 +176,11 @@ TEST(SyscallExit, openat2X_create_success) #ifdef __NR_fstat /* Call `fstat` to retrieve the `dev` and `ino`. */ struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, fd, &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, fd, &file_stat), + NOT_EQUAL, + -1); uint32_t dev = (uint32_t)file_stat.st_dev; uint64_t inode = file_stat.st_ino; const bool is_ext4 = event_test::is_ext4_fs(fd); @@ -189,8 +193,7 @@ TEST(SyscallExit, openat2X_create_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -220,8 +223,7 @@ TEST(SyscallExit, openat2X_create_success) #ifdef __NR_fstat /* Parameter 7: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(7, dev); } diff --git a/test/drivers/test_suites/syscall_exit_suite/openat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/openat_x.cpp index 891ac22a32..d01424715f 100644 --- a/test/drivers/test_suites/syscall_exit_suite/openat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/openat_x.cpp @@ -6,8 +6,7 @@ #include /* Definitions for `fstat` syscall. */ -TEST(SyscallExit, openatX_success) -{ +TEST(SyscallExit, openatX_success) { auto evt_test = get_syscall_event_test(__NR_openat, EXIT_EVENT); auto fo = file_opener(".", (O_RDWR | O_TMPFILE | O_DIRECTORY)); @@ -22,22 +21,25 @@ TEST(SyscallExit, openatX_success) * With `O_TMPFILE` flag the pathname must be a directory. */ int dirfd = AT_FDCWD; - const char* pathname = notmpfile? ".tmpfile" : "."; - int flags = notmpfile? (O_RDWR | O_CREAT | O_DIRECTORY) : (O_RDWR | O_TMPFILE | O_DIRECTORY); + const char* pathname = notmpfile ? ".tmpfile" : "."; + int flags = notmpfile ? (O_RDWR | O_CREAT | O_DIRECTORY) : (O_RDWR | O_TMPFILE | O_DIRECTORY); mode_t mode = 0; int fd = syscall(__NR_openat, dirfd, pathname, flags, mode); assert_syscall_state(SYSCALL_SUCCESS, "openat", fd, NOT_EQUAL, -1); /* Call `fstat` to retrieve the `dev` and `ino`. */ struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, fd, &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, fd, &file_stat), + NOT_EQUAL, + -1); uint32_t dev = (uint32_t)file_stat.st_dev; uint64_t inode = file_stat.st_ino; const bool is_ext4 = event_test::is_ext4_fs(fd); close(fd); - if(notmpfile) - { + if(notmpfile) { unlink(pathname); } @@ -47,8 +49,7 @@ TEST(SyscallExit, openatX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -68,15 +69,15 @@ TEST(SyscallExit, openatX_success) evt_test->assert_charbuf_param(3, pathname); /* Parameter 4: flags (type: PT_FLAGS32) */ - flags = notmpfile? (PPM_O_RDWR | PPM_O_CREAT | PPM_O_DIRECTORY) : (PPM_O_RDWR | PPM_O_TMPFILE | PPM_O_DIRECTORY); + flags = notmpfile ? (PPM_O_RDWR | PPM_O_CREAT | PPM_O_DIRECTORY) + : (PPM_O_RDWR | PPM_O_TMPFILE | PPM_O_DIRECTORY); evt_test->assert_numeric_param(4, (uint32_t)flags); /* Parameter 5: mode (type: PT_UINT32) */ evt_test->assert_numeric_param(5, (uint32_t)mode); /* Parameter 6: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(6, (uint32_t)dev); } @@ -88,8 +89,7 @@ TEST(SyscallExit, openatX_success) evt_test->assert_num_params_pushed(7); } -TEST(SyscallExit, openatX_failure) -{ +TEST(SyscallExit, openatX_failure) { auto evt_test = get_syscall_event_test(__NR_openat, EXIT_EVENT); evt_test->enable_capture(); @@ -105,7 +105,9 @@ TEST(SyscallExit, openatX_failure) const char* pathname = "mock_path"; int flags = O_RDWR | O_TMPFILE | O_DIRECTORY; mode_t mode = 0; - assert_syscall_state(SYSCALL_FAILURE, "openat", syscall(__NR_openat, dirfd, pathname, flags, mode)); + assert_syscall_state(SYSCALL_FAILURE, + "openat", + syscall(__NR_openat, dirfd, pathname, flags, mode)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -114,8 +116,7 @@ TEST(SyscallExit, openatX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -153,8 +154,7 @@ TEST(SyscallExit, openatX_failure) evt_test->assert_num_params_pushed(7); } -TEST(SyscallExit, openatX_create_success) -{ +TEST(SyscallExit, openatX_create_success) { auto evt_test = get_syscall_event_test(__NR_openat, EXIT_EVENT); evt_test->enable_capture(); @@ -171,7 +171,11 @@ TEST(SyscallExit, openatX_create_success) /* Call `fstat` to retrieve the `dev` and `ino`. */ struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, fd, &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, fd, &file_stat), + NOT_EQUAL, + -1); uint32_t dev = (uint32_t)file_stat.st_dev; uint64_t inode = file_stat.st_ino; const bool is_ext4 = event_test::is_ext4_fs(fd); @@ -183,8 +187,7 @@ TEST(SyscallExit, openatX_create_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -210,8 +213,7 @@ TEST(SyscallExit, openatX_create_success) evt_test->assert_numeric_param(5, (uint32_t)mode); /* Parameter 6: dev (type: PT_UINT32) */ - if (is_ext4) - { + if(is_ext4) { evt_test->assert_numeric_param(6, (uint32_t)dev); } diff --git a/test/drivers/test_suites/syscall_exit_suite/pidfd_getfd_x.cpp b/test/drivers/test_suites/syscall_exit_suite/pidfd_getfd_x.cpp index 2ff47e4f2d..94b69610eb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/pidfd_getfd_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/pidfd_getfd_x.cpp @@ -2,59 +2,57 @@ #ifdef __NR_pidfd_getfd -TEST(SyscallExit, pidfd_getfdX) -{ - auto evt_test = get_syscall_event_test(__NR_pidfd_getfd, EXIT_EVENT); +TEST(SyscallExit, pidfd_getfdX) { + auto evt_test = get_syscall_event_test(__NR_pidfd_getfd, EXIT_EVENT); - evt_test->enable_capture(); - + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - int pid_fd = -1; - int target_fd = -1; - uint32_t flags = 1; - int64_t errno_value = -EINVAL; + int pid_fd = -1; + int target_fd = -1; + uint32_t flags = 1; + int64_t errno_value = -EINVAL; - /* - The syscall should fail when flag is not equal to zero - See https://elixir.bootlin.com/linux/latest/source/kernel/pid.c#L731 - */ + /* + The syscall should fail when flag is not equal to zero + See https://elixir.bootlin.com/linux/latest/source/kernel/pid.c#L731 + */ - assert_syscall_state(SYSCALL_FAILURE, "pidfd_getfd", syscall(__NR_pidfd_getfd, pid_fd, target_fd, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "pidfd_getfd", + syscall(__NR_pidfd_getfd, pid_fd, target_fd, flags)); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO)*/ - evt_test->assert_numeric_param(1, (int64_t)errno_value); + /* Parameter 1: res (type: PT_ERRNO)*/ + evt_test->assert_numeric_param(1, (int64_t)errno_value); - /* Parameter 2: pidfd (type: PT_FD)*/ - evt_test->assert_numeric_param(2, (int64_t)pid_fd); + /* Parameter 2: pidfd (type: PT_FD)*/ + evt_test->assert_numeric_param(2, (int64_t)pid_fd); - /* Parameter 3: targetfd (type: PT_FD)*/ - evt_test->assert_numeric_param(3, (int64_t)target_fd); + /* Parameter 3: targetfd (type: PT_FD)*/ + evt_test->assert_numeric_param(3, (int64_t)target_fd); - /* Parameter 4: flags (type: PT_FLAGS32)*/ - evt_test->assert_numeric_param(4, flags); + /* Parameter 4: flags (type: PT_FLAGS32)*/ + evt_test->assert_numeric_param(4, flags); /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(4); - + evt_test->assert_num_params_pushed(4); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/pidfd_open_x.cpp b/test/drivers/test_suites/syscall_exit_suite/pidfd_open_x.cpp index a34754a1bb..edc181dca2 100644 --- a/test/drivers/test_suites/syscall_exit_suite/pidfd_open_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/pidfd_open_x.cpp @@ -2,110 +2,104 @@ #include - #ifdef __NR_pidfd_open #ifdef __NR_fork -TEST(SyscallExit, pidfd_openX_success) -{ - auto evt_test = get_syscall_event_test(__NR_pidfd_open, EXIT_EVENT); +TEST(SyscallExit, pidfd_openX_success) { + auto evt_test = get_syscall_event_test(__NR_pidfd_open, EXIT_EVENT); + + evt_test->enable_capture(); - evt_test->enable_capture(); + /*=============================== TRIGGER SYSCALL ===========================*/ + /* + PIDFD_NONBLOCK is available only on kernal versions > 5.10.0. No other flags are supported + See https://elixir.bootlin.com/linux/v5.10.185/source/include/uapi/linux/pidfd.h#L10 + */ - /*=============================== TRIGGER SYSCALL ===========================*/ - /* - PIDFD_NONBLOCK is available only on kernal versions > 5.10.0. No other flags are supported - See https://elixir.bootlin.com/linux/v5.10.185/source/include/uapi/linux/pidfd.h#L10 - */ - - int flags = 0; - pid_t pid = syscall(__NR_fork); - if(pid == 0) - { - exit(EXIT_SUCCESS); - } - assert_syscall_state(SYSCALL_SUCCESS, "fork", pid, NOT_EQUAL, -1); + int flags = 0; + pid_t pid = syscall(__NR_fork); + if(pid == 0) { + exit(EXIT_SUCCESS); + } + assert_syscall_state(SYSCALL_SUCCESS, "fork", pid, NOT_EQUAL, -1); - int pidfd = syscall(__NR_pidfd_open, pid, flags); - assert_syscall_state(SYSCALL_SUCCESS, "pidfd_open", pidfd, NOT_EQUAL, -1); - syscall(__NR_close); + int pidfd = syscall(__NR_pidfd_open, pid, flags); + assert_syscall_state(SYSCALL_SUCCESS, "pidfd_open", pidfd, NOT_EQUAL, -1); + syscall(__NR_close); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: ret (type: PT_FD)*/ - evt_test->assert_numeric_param(1, (int64_t)pidfd); + /* Parameter 1: ret (type: PT_FD)*/ + evt_test->assert_numeric_param(1, (int64_t)pidfd); - /* Parameter 2: pid (type: PT_PID)*/ - evt_test->assert_numeric_param(2, (int64_t)pid); + /* Parameter 2: pid (type: PT_PID)*/ + evt_test->assert_numeric_param(2, (int64_t)pid); - /* Parameter 3: flags (type: PT_FLAGS32) */ - evt_test->assert_numeric_param(3, (uint32_t)0); + /* Parameter 3: flags (type: PT_FLAGS32) */ + evt_test->assert_numeric_param(3, (uint32_t)0); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(3); + evt_test->assert_num_params_pushed(3); } #endif -TEST(SyscallExit, pidfd_openX_failure) -{ - auto evt_test = get_syscall_event_test(__NR_pidfd_open, EXIT_EVENT); +TEST(SyscallExit, pidfd_openX_failure) { + auto evt_test = get_syscall_event_test(__NR_pidfd_open, EXIT_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - int flags = O_NONBLOCK; + int flags = O_NONBLOCK; #ifdef PIDFD_NONBLOCK - flags = PIDFD_NONBLOCK; + flags = PIDFD_NONBLOCK; #endif - pid_t pid = 0; - int64_t errno_value = -EINVAL; - assert_syscall_state(SYSCALL_FAILURE, "pidfd_open", syscall(__NR_pidfd_open, pid, flags)); + pid_t pid = 0; + int64_t errno_value = -EINVAL; + assert_syscall_state(SYSCALL_FAILURE, "pidfd_open", syscall(__NR_pidfd_open, pid, flags)); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: ret (type: PT_FD)*/ - evt_test->assert_numeric_param(1, (int64_t)errno_value); + /* Parameter 1: ret (type: PT_FD)*/ + evt_test->assert_numeric_param(1, (int64_t)errno_value); - /* Parameter 2: pid (type: PT_PID)*/ - evt_test->assert_numeric_param(2, (int64_t)pid); + /* Parameter 2: pid (type: PT_PID)*/ + evt_test->assert_numeric_param(2, (int64_t)pid); - /* Parameter 3: flags (type: PT_FLAGS32) */ - evt_test->assert_numeric_param(3, (uint32_t)PPM_PIDFD_NONBLOCK); + /* Parameter 3: flags (type: PT_FLAGS32) */ + evt_test->assert_numeric_param(3, (uint32_t)PPM_PIDFD_NONBLOCK); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(3); + evt_test->assert_num_params_pushed(3); } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/pipe2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/pipe2_x.cpp index 012222139d..191eb9a7ac 100644 --- a/test/drivers/test_suites/syscall_exit_suite/pipe2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/pipe2_x.cpp @@ -7,8 +7,7 @@ * is enough. */ -TEST(SyscallExit, pipe2X_failure) -{ +TEST(SyscallExit, pipe2X_failure) { auto evt_test = get_syscall_event_test(__NR_pipe2, EXIT_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallExit, pipe2X_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/pipe_x.cpp b/test/drivers/test_suites/syscall_exit_suite/pipe_x.cpp index 92b5f2bb10..3cdaab196d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/pipe_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/pipe_x.cpp @@ -4,8 +4,7 @@ #if defined(__NR_fstat) && defined(__NR_close) -TEST(SyscallExit, pipeX_success) -{ +TEST(SyscallExit, pipeX_success) { auto evt_test = get_syscall_event_test(__NR_pipe, EXIT_EVENT); evt_test->enable_capture(); @@ -16,7 +15,11 @@ TEST(SyscallExit, pipeX_success) assert_syscall_state(SYSCALL_SUCCESS, "pipe", syscall(__NR_pipe, pipefd), NOT_EQUAL, -1); struct stat file_stat; - assert_syscall_state(SYSCALL_SUCCESS, "fstat", syscall(__NR_fstat, pipefd[0], &file_stat), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "fstat", + syscall(__NR_fstat, pipefd[0], &file_stat), + NOT_EQUAL, + -1); uint64_t inode = file_stat.st_ino; syscall(__NR_close, pipefd[0]); @@ -28,8 +31,7 @@ TEST(SyscallExit, pipeX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -58,8 +60,7 @@ TEST(SyscallExit, pipeX_success) #endif /* defined(__NR_fstat) && defined(__NR_close) */ -TEST(SyscallExit, pipeX_failure) -{ +TEST(SyscallExit, pipeX_failure) { auto evt_test = get_syscall_event_test(__NR_pipe, EXIT_EVENT); evt_test->enable_capture(); @@ -76,8 +77,7 @@ TEST(SyscallExit, pipeX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/poll_x.cpp b/test/drivers/test_suites/syscall_exit_suite/poll_x.cpp index 6ef4ae23f0..3b5672eef1 100644 --- a/test/drivers/test_suites/syscall_exit_suite/poll_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/poll_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, pollX_success) -{ +TEST(SyscallExit, pollX_success) { auto evt_test = get_syscall_event_test(__NR_poll, EXIT_EVENT); evt_test->enable_capture(); @@ -37,7 +36,11 @@ TEST(SyscallExit, pollX_success) expected[1].fd = fds[1].fd; expected[1].flags = 0; - assert_syscall_state(SYSCALL_SUCCESS, "poll", syscall(__NR_poll, fds, nfds, timeout), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "poll", + syscall(__NR_poll, fds, nfds, timeout), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -45,8 +48,7 @@ TEST(SyscallExit, pollX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/ppoll_x.cpp b/test/drivers/test_suites/syscall_exit_suite/ppoll_x.cpp index 383ca16c99..0c7d8ab566 100644 --- a/test/drivers/test_suites/syscall_exit_suite/ppoll_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/ppoll_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, ppollX) -{ +TEST(SyscallExit, ppollX) { auto evt_test = get_syscall_event_test(__NR_ppoll, EXIT_EVENT); evt_test->enable_capture(); @@ -19,7 +18,9 @@ TEST(SyscallExit, ppollX) struct timespec* timestamp = NULL; sigset_t* sigmask = NULL; uint32_t nfds = 5; - assert_syscall_state(SYSCALL_FAILURE, "ppoll", syscall(__NR_ppoll, fds, nfds, timestamp, sigmask)); + assert_syscall_state(SYSCALL_FAILURE, + "ppoll", + syscall(__NR_ppoll, fds, nfds, timestamp, sigmask)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -28,8 +29,7 @@ TEST(SyscallExit, ppollX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/prctl_x.cpp b/test/drivers/test_suites/syscall_exit_suite/prctl_x.cpp index 8efde04316..77af6bd12b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/prctl_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/prctl_x.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallExit, prctlX_failure) -{ +TEST(SyscallExit, prctlX_failure) { auto evt_test = get_syscall_event_test(__NR_prctl, EXIT_EVENT); evt_test->enable_capture(); @@ -22,7 +21,9 @@ TEST(SyscallExit, prctlX_failure) * Call the `prctl` */ - assert_syscall_state(SYSCALL_FAILURE, "prctl", syscall(__NR_prctl, option, arg2, arg3, arg4, arg5)); + assert_syscall_state(SYSCALL_FAILURE, + "prctl", + syscall(__NR_prctl, option, arg2, arg3, arg4, arg5)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -31,8 +32,7 @@ TEST(SyscallExit, prctlX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -59,12 +59,15 @@ TEST(SyscallExit, prctlX_failure) evt_test->assert_num_params_pushed(4); } -TEST(SyscallExit, prctlX_get_child_subreaper) -{ +TEST(SyscallExit, prctlX_get_child_subreaper) { auto evt_test = get_syscall_event_test(__NR_prctl, EXIT_EVENT); // set the subreaper attribute - assert_syscall_state(SYSCALL_SUCCESS, "prctl", syscall(__NR_prctl, PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0), EQUAL, 0); + assert_syscall_state(SYSCALL_SUCCESS, + "prctl", + syscall(__NR_prctl, PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0), + EQUAL, + 0); evt_test->enable_capture(); @@ -76,20 +79,26 @@ TEST(SyscallExit, prctlX_get_child_subreaper) unsigned long arg4 = 0; unsigned long arg5 = 0; - assert_syscall_state(SYSCALL_SUCCESS, "prctl", syscall(__NR_prctl, option, &arg2, arg3, arg4, arg5), EQUAL, 0); - + assert_syscall_state(SYSCALL_SUCCESS, + "prctl", + syscall(__NR_prctl, option, &arg2, arg3, arg4, arg5), + EQUAL, + 0); /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); // unset the subreaper attribute - assert_syscall_state(SYSCALL_SUCCESS, "prctl", syscall(__NR_prctl, PR_SET_CHILD_SUBREAPER, 0, 0, 0, 0), EQUAL, 0); + assert_syscall_state(SYSCALL_SUCCESS, + "prctl", + syscall(__NR_prctl, PR_SET_CHILD_SUBREAPER, 0, 0, 0, 0), + EQUAL, + 0); evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -116,8 +125,7 @@ TEST(SyscallExit, prctlX_get_child_subreaper) evt_test->assert_num_params_pushed(4); } -TEST(SyscallExit, prctlX_set_child_subreaper) -{ +TEST(SyscallExit, prctlX_set_child_subreaper) { auto evt_test = get_syscall_event_test(__NR_prctl, EXIT_EVENT); evt_test->enable_capture(); @@ -137,12 +145,15 @@ TEST(SyscallExit, prctlX_set_child_subreaper) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* * Call the `prctl` */ - assert_syscall_state(SYSCALL_SUCCESS, "prctl", syscall(__NR_prctl, option, arg2, arg3, arg4, arg5), EQUAL, 0); + assert_syscall_state(SYSCALL_SUCCESS, + "prctl", + syscall(__NR_prctl, option, arg2, arg3, arg4, arg5), + EQUAL, + 0); exit(EXIT_SUCCESS); } @@ -152,9 +163,12 @@ TEST(SyscallExit, prctlX_set_child_subreaper) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The prctl call is successful while it should fail..." << std::endl; } @@ -164,8 +178,7 @@ TEST(SyscallExit, prctlX_set_child_subreaper) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -192,8 +205,7 @@ TEST(SyscallExit, prctlX_set_child_subreaper) evt_test->assert_num_params_pushed(4); } -TEST(SyscallExit, prctlX_set_name) -{ +TEST(SyscallExit, prctlX_set_name) { auto evt_test = get_syscall_event_test(__NR_prctl, EXIT_EVENT); evt_test->enable_capture(); @@ -201,7 +213,10 @@ TEST(SyscallExit, prctlX_set_name) /*=============================== TRIGGER SYSCALL ===========================*/ int option = PR_SET_NAME; - const char arg2[] = "AAABAACAADAAEAAFAAGAAHAAIAAJAAKAALAAMAANAAOAAPAAQAARAASAATAAUAAVAAWAAXAAYAAZAAaAAbAAcAAdAAeAAfAAgAAhAAiAAjAAkAAlAAmAAnAAoAApAAqAArAAsAAtAAuAAvAAwAAxAAyAAzAA1AA2AA3AA4AA5AA6AA7AA8AA9AA0ABBABCABDABEABFABGABHABIABJABKABLABMABNABOABPABQABRABSABTABUABVABWABXAB"; + const char arg2[] = + "AAABAACAADAAEAAFAAGAAHAAIAAJAAKAALAAMAANAAOAAPAAQAARAASAATAAUAAVAAWAAXAAYAAZAAaAAbAAcA" + "AdAAeAAfAAgAAhAAiAAjAAkAAlAAmAAnAAoAApAAqAArAAsAAtAAuAAvAAwAAxAAyAAzAA1AA2AA3AA4AA5AA6" + "AA7AA8AA9AA0ABBABCABDABEABFABGABHABIABJABKABLABMABNABOABPABQABRABSABTABUABVABWABXAB"; unsigned long arg3 = 0; unsigned long arg4 = 0; unsigned long arg5 = 0; @@ -213,12 +228,15 @@ TEST(SyscallExit, prctlX_set_name) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* * Call the `prctl` */ - assert_syscall_state(SYSCALL_SUCCESS, "prctl", syscall(__NR_prctl, option, arg2, arg3, arg4, arg5), EQUAL, 0); + assert_syscall_state(SYSCALL_SUCCESS, + "prctl", + syscall(__NR_prctl, option, arg2, arg3, arg4, arg5), + EQUAL, + 0); exit(EXIT_SUCCESS); } @@ -229,9 +247,12 @@ TEST(SyscallExit, prctlX_set_name) int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The prctl call is successful while it should fail..." << std::endl; } @@ -241,8 +262,7 @@ TEST(SyscallExit, prctlX_set_name) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/pread64_x.cpp b/test/drivers/test_suites/syscall_exit_suite/pread64_x.cpp index 1f152e358d..612df847aa 100644 --- a/test/drivers/test_suites/syscall_exit_suite/pread64_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/pread64_x.cpp @@ -5,8 +5,7 @@ #ifdef __NR_pread64 -TEST(SyscallExit, preadX_fail) -{ +TEST(SyscallExit, preadX_fail) { auto evt_test = get_syscall_event_test(__NR_pread64, EXIT_EVENT); evt_test->enable_capture(); @@ -25,8 +24,7 @@ TEST(SyscallExit, preadX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -47,4 +45,4 @@ TEST(SyscallExit, preadX_fail) evt_test->assert_num_params_pushed(2); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/preadv_x.cpp b/test/drivers/test_suites/syscall_exit_suite/preadv_x.cpp index fdccf8cbee..2a8aa24580 100644 --- a/test/drivers/test_suites/syscall_exit_suite/preadv_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/preadv_x.cpp @@ -5,8 +5,7 @@ #ifdef __NR_preadv -TEST(SyscallExit, preadvX_fail) -{ +TEST(SyscallExit, preadvX_fail) { auto evt_test = get_syscall_event_test(__NR_preadv, EXIT_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallExit, preadvX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -51,4 +49,4 @@ TEST(SyscallExit, preadvX_fail) evt_test->assert_num_params_pushed(3); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/prlimit64_x.cpp b/test/drivers/test_suites/syscall_exit_suite/prlimit64_x.cpp index 45e11a1d7c..86ac470ca9 100644 --- a/test/drivers/test_suites/syscall_exit_suite/prlimit64_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/prlimit64_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, prlimit64X_success) -{ +TEST(SyscallExit, prlimit64X_success) { auto evt_test = get_syscall_event_test(__NR_prlimit64, EXIT_EVENT); evt_test->enable_capture(); @@ -17,14 +16,22 @@ TEST(SyscallExit, prlimit64X_success) * 2. Set them as new limits so nothing will change. */ struct rlimit file_rlimit; - assert_syscall_state(SYSCALL_SUCCESS, "getrlimit", syscall(__NR_getrlimit, RLIMIT_NOFILE, &file_rlimit), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "getrlimit", + syscall(__NR_getrlimit, RLIMIT_NOFILE, &file_rlimit), + NOT_EQUAL, + -1); struct rlimit old_rlimit; struct rlimit new_rlimit; new_rlimit.rlim_cur = file_rlimit.rlim_cur; new_rlimit.rlim_max = file_rlimit.rlim_max; pid_t pid = ::getpid(); - assert_syscall_state(SYSCALL_SUCCESS, "prlimit64", syscall(__NR_prlimit64, pid, RLIMIT_NOFILE, &new_rlimit, &old_rlimit), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "prlimit64", + syscall(__NR_prlimit64, pid, RLIMIT_NOFILE, &new_rlimit, &old_rlimit), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -32,8 +39,7 @@ TEST(SyscallExit, prlimit64X_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -69,8 +75,7 @@ TEST(SyscallExit, prlimit64X_success) evt_test->assert_num_params_pushed(7); } -TEST(SyscallExit, prlimit64X_failure) -{ +TEST(SyscallExit, prlimit64X_failure) { auto evt_test = get_syscall_event_test(__NR_prlimit64, EXIT_EVENT); evt_test->enable_capture(); @@ -78,7 +83,9 @@ TEST(SyscallExit, prlimit64X_failure) /*=============================== TRIGGER SYSCALL ===========================*/ pid_t pid = -1; - assert_syscall_state(SYSCALL_FAILURE, "prlimit64", syscall(__NR_prlimit64, pid, RLIMIT_RSS, NULL, NULL)); + assert_syscall_state(SYSCALL_FAILURE, + "prlimit64", + syscall(__NR_prlimit64, pid, RLIMIT_RSS, NULL, NULL)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -87,8 +94,7 @@ TEST(SyscallExit, prlimit64X_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/process_vm_readv_x.cpp b/test/drivers/test_suites/syscall_exit_suite/process_vm_readv_x.cpp index c2ee918477..222ad2e30c 100644 --- a/test/drivers/test_suites/syscall_exit_suite/process_vm_readv_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/process_vm_readv_x.cpp @@ -3,12 +3,10 @@ #ifdef __NR_process_vm_readv void signal_handler(int signum) { - // Do nothing + // Do nothing } - -TEST(SyscallExit, process_vm_readvX_failure) -{ +TEST(SyscallExit, process_vm_readvX_failure) { auto evt_test = get_syscall_event_test(__NR_process_vm_readv, EXIT_EVENT); evt_test->enable_capture(); @@ -16,7 +14,7 @@ TEST(SyscallExit, process_vm_readvX_failure) /*=============================== TRIGGER SYSCALL ===========================*/ // Setting the iov to NULL will cause the failure of the syscall. - iovec *iov = NULL; + iovec* iov = NULL; int32_t iovcnt = 7; size_t res = syscall(__NR_process_vm_readv, getpid(), iov, iovcnt, iov, iovcnt, 0); @@ -28,8 +26,7 @@ TEST(SyscallExit, process_vm_readvX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -53,8 +50,7 @@ TEST(SyscallExit, process_vm_readvX_failure) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, process_vm_readvX_success) -{ +TEST(SyscallExit, process_vm_readvX_success) { auto evt_test = get_syscall_event_test(__NR_process_vm_readv, EXIT_EVENT); evt_test->enable_capture(); @@ -67,9 +63,7 @@ TEST(SyscallExit, process_vm_readvX_success) pid_t child_pid = fork(); - if(child_pid == 0) - { - + if(child_pid == 0) { char buf[10] = "QWERTYUIO"; struct iovec remote[1]; remote[0].iov_base = (void*)buf; @@ -92,10 +86,7 @@ TEST(SyscallExit, process_vm_readvX_success) pause(); exit(EXIT_SUCCESS); - } - else - { - + } else { char buffer[10]; struct iovec local[1]; local[0].iov_base = buffer; @@ -124,8 +115,7 @@ TEST(SyscallExit, process_vm_readvX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/process_vm_writev_x.cpp b/test/drivers/test_suites/syscall_exit_suite/process_vm_writev_x.cpp index 3c7aa55666..da85f25e5e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/process_vm_writev_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/process_vm_writev_x.cpp @@ -3,15 +3,20 @@ #ifdef __NR_process_vm_writev -TEST(SyscallExit, process_vm_writevX_failure) -{ +TEST(SyscallExit, process_vm_writevX_failure) { auto evt_test = get_syscall_event_test(__NR_process_vm_writev, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - size_t res = syscall(__NR_process_vm_writev, getpid(), (void*)(0x41414141), 0, (void*)(0x42424242), 0, 0); + size_t res = syscall(__NR_process_vm_writev, + getpid(), + (void*)(0x41414141), + 0, + (void*)(0x42424242), + 0, + 0); assert_syscall_state(SYSCALL_FAILURE, "process_vm_writev", res, EQUAL, 0); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +25,7 @@ TEST(SyscallExit, process_vm_writevX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -45,8 +49,7 @@ TEST(SyscallExit, process_vm_writevX_failure) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, process_vm_writevX_success) -{ +TEST(SyscallExit, process_vm_writevX_success) { auto evt_test = get_syscall_event_test(__NR_process_vm_writev, EXIT_EVENT); evt_test->enable_capture(); @@ -60,9 +63,7 @@ TEST(SyscallExit, process_vm_writevX_success) pid_t parent_pid = getpid(); pid_t child_pid = fork(); - if(child_pid == 0) - { - + if(child_pid == 0) { char buf[10] = "QWERTYUIO"; struct iovec local[1]; local[0].iov_base = buf; @@ -80,10 +81,7 @@ TEST(SyscallExit, process_vm_writevX_success) close(pipe_fd[0]); exit(EXIT_SUCCESS); - } - else - { - + } else { char buf[10]; struct iovec local[1]; local[0].iov_base = (void*)buf; @@ -107,8 +105,7 @@ TEST(SyscallExit, process_vm_writevX_success) evt_test->assert_event_presence(child_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/ptrace_x.cpp b/test/drivers/test_suites/syscall_exit_suite/ptrace_x.cpp index cd1996f6ae..c9f82e7c9a 100644 --- a/test/drivers/test_suites/syscall_exit_suite/ptrace_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/ptrace_x.cpp @@ -6,8 +6,7 @@ /// TODO: we need a test to assert the behavior in case of success. -TEST(SyscallExit, ptraceX_failure) -{ +TEST(SyscallExit, ptraceX_failure) { auto evt_test = get_syscall_event_test(__NR_ptrace, EXIT_EVENT); evt_test->enable_capture(); @@ -27,8 +26,7 @@ TEST(SyscallExit, ptraceX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/pwrite64_x.cpp b/test/drivers/test_suites/syscall_exit_suite/pwrite64_x.cpp index 222c1aef4d..288f8d37e6 100644 --- a/test/drivers/test_suites/syscall_exit_suite/pwrite64_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/pwrite64_x.cpp @@ -5,8 +5,7 @@ #if defined(__NR_close) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallExit, pwrite64X_no_snaplen) -{ +TEST(SyscallExit, pwrite64X_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_pwrite64, EXIT_EVENT); evt_test->enable_capture(); @@ -21,7 +20,11 @@ TEST(SyscallExit, pwrite64X_no_snaplen) const unsigned data_len = DEFAULT_SNAPLEN / 2; char buf[data_len] = "hello\0"; off_t off = 0; - assert_syscall_state(SYSCALL_SUCCESS, "pwrite64", syscall(__NR_pwrite64, fd, (void *)buf, data_len, off), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "pwrite64", + syscall(__NR_pwrite64, fd, (void *)buf, data_len, off), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -29,8 +32,7 @@ TEST(SyscallExit, pwrite64X_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -51,8 +53,7 @@ TEST(SyscallExit, pwrite64X_no_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, pwrite64X_snaplen) -{ +TEST(SyscallExit, pwrite64X_snaplen) { auto evt_test = get_syscall_event_test(__NR_pwrite64, EXIT_EVENT); evt_test->enable_capture(); @@ -62,7 +63,9 @@ TEST(SyscallExit, pwrite64X_snaplen) const unsigned data_len = DEFAULT_SNAPLEN * 2; char buf[data_len] = "some-data"; off_t off = 0; - assert_syscall_state(SYSCALL_FAILURE, "pwrite64", syscall(__NR_pwrite64, -1, (void *)buf, data_len, off)); + assert_syscall_state(SYSCALL_FAILURE, + "pwrite64", + syscall(__NR_pwrite64, -1, (void *)buf, data_len, off)); int errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -71,8 +74,7 @@ TEST(SyscallExit, pwrite64X_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -93,8 +95,7 @@ TEST(SyscallExit, pwrite64X_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, pwrite64X_fail) -{ +TEST(SyscallExit, pwrite64X_fail) { auto evt_test = get_syscall_event_test(__NR_pwrite64, EXIT_EVENT); evt_test->enable_capture(); @@ -105,7 +106,9 @@ TEST(SyscallExit, pwrite64X_fail) const unsigned data_len = 64; char *buf = NULL; off_t off = 0; - assert_syscall_state(SYSCALL_FAILURE, "pwrite64", syscall(__NR_pwrite64, -1, (void *)buf, data_len, off)); + assert_syscall_state(SYSCALL_FAILURE, + "pwrite64", + syscall(__NR_pwrite64, -1, (void *)buf, data_len, off)); int errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -114,8 +117,7 @@ TEST(SyscallExit, pwrite64X_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/pwritev_x.cpp b/test/drivers/test_suites/syscall_exit_suite/pwritev_x.cpp index 44283bf2d8..dfd601269c 100644 --- a/test/drivers/test_suites/syscall_exit_suite/pwritev_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/pwritev_x.cpp @@ -5,8 +5,7 @@ #if defined(__NR_close) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallExit, pwritevX_no_snaplen) -{ +TEST(SyscallExit, pwritevX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_pwritev, EXIT_EVENT); evt_test->enable_capture(); @@ -21,7 +20,9 @@ TEST(SyscallExit, pwritevX_no_snaplen) iov[0].iov_len = sizeof(sent_data_1); int32_t iovcnt = 1; off_t off = 1; - assert_syscall_state(SYSCALL_FAILURE, "pwritev", syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); + assert_syscall_state(SYSCALL_FAILURE, + "pwritev", + syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -30,8 +31,7 @@ TEST(SyscallExit, pwritevX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -53,8 +53,7 @@ TEST(SyscallExit, pwritevX_no_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, pwritevX_snaplen) -{ +TEST(SyscallExit, pwritevX_snaplen) { auto evt_test = get_syscall_event_test(__NR_pwritev, EXIT_EVENT); evt_test->enable_capture(); @@ -76,7 +75,11 @@ TEST(SyscallExit, pwritevX_snaplen) iov[1].iov_len = sizeof(sent_data_2); int32_t iovcnt = 2; off_t off = 0; - assert_syscall_state(SYSCALL_SUCCESS, "pwritev", syscall(__NR_pwritev, fd, iov, iovcnt, off), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "pwritev", + syscall(__NR_pwritev, fd, iov, iovcnt, off), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -84,8 +87,7 @@ TEST(SyscallExit, pwritevX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -106,8 +108,7 @@ TEST(SyscallExit, pwritevX_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, pwritevX_empty) -{ +TEST(SyscallExit, pwritevX_empty) { auto evt_test = get_syscall_event_test(__NR_pwritev, EXIT_EVENT); evt_test->enable_capture(); @@ -118,7 +119,9 @@ TEST(SyscallExit, pwritevX_empty) iovec* iov = NULL; int32_t iovcnt = 7; off_t off = 0; - assert_syscall_state(SYSCALL_FAILURE, "pwritev", syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); + assert_syscall_state(SYSCALL_FAILURE, + "pwritev", + syscall(__NR_pwritev, mock_fd, iov, iovcnt, off)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -127,8 +130,7 @@ TEST(SyscallExit, pwritevX_empty) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/quotactl_x.cpp b/test/drivers/test_suites/syscall_exit_suite/quotactl_x.cpp index 8e49487fb2..485d53119b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/quotactl_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/quotactl_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, quotactlX) -{ +TEST(SyscallExit, quotactlX) { auto evt_test = get_syscall_event_test(__NR_quotactl, EXIT_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallExit, quotactlX) const char* special = "/dev//*null"; int id = 1; struct if_dqblk addr = {}; - assert_syscall_state(SYSCALL_FAILURE, "quotactl", syscall(__NR_quotactl, cmd, special, id, &addr)); + assert_syscall_state(SYSCALL_FAILURE, + "quotactl", + syscall(__NR_quotactl, cmd, special, id, &addr)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallExit, quotactlX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/read_x.cpp b/test/drivers/test_suites/syscall_exit_suite/read_x.cpp index b7e8b7d025..9193859422 100644 --- a/test/drivers/test_suites/syscall_exit_suite/read_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/read_x.cpp @@ -4,8 +4,7 @@ #if defined(__NR_close) && defined(__NR_open) -TEST(SyscallExit, readX_no_snaplen) -{ +TEST(SyscallExit, readX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->enable_capture(); @@ -31,8 +30,7 @@ TEST(SyscallExit, readX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -53,8 +51,7 @@ TEST(SyscallExit, readX_no_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, readX_snaplen) -{ +TEST(SyscallExit, readX_snaplen) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->enable_capture(); @@ -80,8 +77,7 @@ TEST(SyscallExit, readX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -102,8 +98,7 @@ TEST(SyscallExit, readX_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, readXfail) -{ +TEST(SyscallExit, readXfail) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->enable_capture(); @@ -123,8 +118,7 @@ TEST(SyscallExit, readXfail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -145,16 +139,16 @@ TEST(SyscallExit, readXfail) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, readX_ipv4_tcp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, readX_ipv4_tcp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_read}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_read}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -162,8 +156,7 @@ TEST(SyscallExit, readX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -178,28 +171,28 @@ TEST(SyscallExit, readX_ipv4_tcp_message_truncated_by_snaplen) /* Parameter 2: data (type: PT_BYTEBUF) */ evt_test->assert_bytebuf_param(2, LONG_MESSAGE, DEFAULT_SNAPLEN); - /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, readX_ipv4_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, readX_ipv4_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_read}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_read}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -214,8 +207,7 @@ TEST(SyscallExit, readX_ipv4_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -230,22 +222,22 @@ TEST(SyscallExit, readX_ipv4_tcp_message_not_truncated_fullcapture_port) /* Parameter 2: data (type: PT_BYTEBUF) */ evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); - + /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, readX_ipv4_udp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, readX_ipv4_udp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_read}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_read}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -253,8 +245,7 @@ TEST(SyscallExit, readX_ipv4_udp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -269,14 +260,13 @@ TEST(SyscallExit, readX_ipv4_udp_message_truncated_by_snaplen) /* Parameter 2: data (type: PT_BYTEBUF) */ evt_test->assert_bytebuf_param(2, LONG_MESSAGE, DEFAULT_SNAPLEN); - + /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, readX_ipv4_udp_message_truncated_fullcapture_client_port) -{ +TEST(SyscallExit, readX_ipv4_udp_message_truncated_fullcapture_client_port) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -287,8 +277,9 @@ TEST(SyscallExit, readX_ipv4_udp_message_truncated_fullcapture_client_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_read}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_read}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -303,8 +294,7 @@ TEST(SyscallExit, readX_ipv4_udp_message_truncated_fullcapture_client_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -318,30 +308,31 @@ TEST(SyscallExit, readX_ipv4_udp_message_truncated_fullcapture_client_port) evt_test->assert_numeric_param(1, (int64_t)MAX_RECV_BUF_SIZE); /* Parameter 2: data (type: PT_BYTEBUF) */ - // We cannot retrieve the client port and so the FULLCAPTURE_PORT_RANGE logic doesn't increase the snaplen. + // We cannot retrieve the client port and so the FULLCAPTURE_PORT_RANGE logic doesn't increase + // the snaplen. evt_test->assert_bytebuf_param(2, LONG_MESSAGE, DEFAULT_SNAPLEN); - + /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, readX_ipv4_udp_message_not_truncated_fullcapture_server_port) -{ +TEST(SyscallExit, readX_ipv4_udp_message_not_truncated_fullcapture_server_port) { auto evt_test = get_syscall_event_test(__NR_read, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // In this case we should be able to retrieve the server port from the kernel socket because it is the local - // port We are receiving on the server. + // In this case we should be able to retrieve the server port from the kernel socket because it + // is the local port We are receiving on the server. evt_test->set_fullcapture_port_range(IPV4_PORT_SERVER, IPV4_PORT_SERVER); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_read}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_read}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -356,8 +347,7 @@ TEST(SyscallExit, readX_ipv4_udp_message_not_truncated_fullcapture_server_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -372,7 +362,7 @@ TEST(SyscallExit, readX_ipv4_udp_message_not_truncated_fullcapture_server_port) /* Parameter 2: data (type: PT_BYTEBUF) */ evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); - + /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(2); diff --git a/test/drivers/test_suites/syscall_exit_suite/readv_x.cpp b/test/drivers/test_suites/syscall_exit_suite/readv_x.cpp index d7db563cca..5a8ec5788c 100644 --- a/test/drivers/test_suites/syscall_exit_suite/readv_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/readv_x.cpp @@ -2,8 +2,7 @@ #ifdef __NR_readv -TEST(SyscallExit, readvX_fail) -{ +TEST(SyscallExit, readvX_fail) { auto evt_test = get_syscall_event_test(__NR_readv, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, readvX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -48,21 +46,22 @@ TEST(SyscallExit, readvX_fail) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, readvX_success) -{ +TEST(SyscallExit, readvX_success) { auto evt_test = get_syscall_event_test(__NR_readv, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - /* Create a non blocking pipe, so that we can read and write from and to it without touching the filesystem */ + /* Create a non blocking pipe, so that we can read and write from and to it without touching the + * filesystem */ int pipefds[2]; ASSERT_EQ(pipe2(pipefds, O_NONBLOCK), 0); /* Write a string into it */ const char *test_string = "this is a string used for testing purposes"; - ASSERT_EQ(write(pipefds[1], (void *)test_string, strlen(test_string) + 1), strlen(test_string) + 1); + ASSERT_EQ(write(pipefds[1], (void *)test_string, strlen(test_string) + 1), + strlen(test_string) + 1); /* Try to read the string with readv using three buffers */ int32_t iovcnt = 3; @@ -70,16 +69,18 @@ TEST(SyscallExit, readvX_success) size_t buf_size = 15; ASSERT_GT(iovcnt * buf_size, strlen(test_string) + 1); - for(int i = 0; i < iovcnt; i++) - { + for(int i = 0; i < iovcnt; i++) { iov[i].iov_base = (void *)new char[buf_size]; iov[i].iov_len = buf_size; } - assert_syscall_state(SYSCALL_SUCCESS, "readv", syscall(__NR_readv, pipefds[0], iov, iovcnt), EQUAL, strlen(test_string) + 1); + assert_syscall_state(SYSCALL_SUCCESS, + "readv", + syscall(__NR_readv, pipefds[0], iov, iovcnt), + EQUAL, + strlen(test_string) + 1); - for(int i = 0; i < iovcnt; i++) - { + for(int i = 0; i < iovcnt; i++) { delete(char *)iov[i].iov_base; } @@ -89,8 +90,7 @@ TEST(SyscallExit, readvX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/recv_x.cpp b/test/drivers/test_suites/syscall_exit_suite/recv_x.cpp index 670e5b9c82..7ec7ecf16c 100644 --- a/test/drivers/test_suites/syscall_exit_suite/recv_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/recv_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_recv -TEST(SyscallExit, recvX_fail) -{ +TEST(SyscallExit, recvX_fail) { auto evt_test = get_syscall_event_test(__NR_recv, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallExit, recvX_fail) char* mock_buf = NULL; size_t mock_count = DEFAULT_SNAPLEN; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "recv", syscall(__NR_recv, mock_fd, (void*)(mock_buf), mock_count, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "recv", + syscall(__NR_recv, mock_fd, (void*)(mock_buf), mock_count, flags)); int errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallExit, recvX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/recvfrom_x.cpp b/test/drivers/test_suites/syscall_exit_suite/recvfrom_x.cpp index c51ff69b00..1b220d58d8 100644 --- a/test/drivers/test_suites/syscall_exit_suite/recvfrom_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/recvfrom_x.cpp @@ -2,14 +2,13 @@ #ifdef __NR_recvfrom -#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && \ - defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && \ - defined(__NR_sendto) +#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && \ + defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && \ + defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) /*=============================== TCP ===========================*/ -TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_by_snaplen) -{ +TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); @@ -17,7 +16,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_by_snaplen) /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto}, - recv_data{.syscall_num = __NR_recvfrom}); + recv_data{.syscall_num = __NR_recvfrom}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +24,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -43,26 +41,30 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_by_snaplen) evt_test->assert_bytebuf_param(2, SHORT_MESSAGE, SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - /* The server performs a 'recvfrom` so the server is the final destination of the packet while the client is the - * src. */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + /* The server performs a 'recvfrom` so the server is the final destination of the packet while + * the client is the src. */ + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_tcp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, recvfromX_ipv4_tcp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -70,8 +72,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -88,29 +89,34 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_bytebuf_param(2, LONG_MESSAGE, DEFAULT_SNAPLEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -125,8 +131,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -144,73 +149,79 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port) evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_DNS_snaplen) -{ - auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); +TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_DNS_snaplen) { + auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); - evt_test->set_do_dynamic_snaplen(true); + evt_test->set_do_dynamic_snaplen(true); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom}, IP_PORT_DNS, IP_PORT_SERVER); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom}, + IP_PORT_DNS, + IP_PORT_SERVER); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->set_do_dynamic_snaplen(false); + evt_test->set_do_dynamic_snaplen(false); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ - evt_test->assert_numeric_param(1, (int64_t)MAX_RECV_BUF_SIZE); + /* Parameter 1: res (type: PT_ERRNO) */ + evt_test->assert_numeric_param(1, (int64_t)MAX_RECV_BUF_SIZE); - /* Parameter 2: data (type: PT_BYTEBUF) */ - // Since the client port matches the fullcapture port range we should see the full message. - evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); + /* Parameter 2: data (type: PT_BYTEBUF) */ + // Since the client port matches the fullcapture port range we should see the full message. + evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(3); + evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv6_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, recvfromX_ipv6_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV6_PORT_CLIENT, IPV6_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv6_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom}); + evt_test->client_to_server_ipv6_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -225,8 +236,7 @@ TEST(SyscallExit, recvfromX_ipv6_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -244,24 +254,28 @@ TEST(SyscallExit, recvfromX_ipv6_tcp_message_not_truncated_fullcapture_port) evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet6_param(3, PPM_AF_INET6, IPV6_CLIENT, IPV6_SERVER, IPV6_PORT_CLIENT_STRING, - IPV6_PORT_SERVER_STRING); + evt_test->assert_tuple_inet6_param(3, + PPM_AF_INET6, + IPV6_CLIENT, + IPV6_SERVER, + IPV6_PORT_CLIENT_STRING, + IPV6_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_sockaddr) -{ +TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -269,8 +283,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_sockaddr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -287,34 +300,39 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_sockaddr) evt_test->assert_bytebuf_param(2, LONG_MESSAGE, DEFAULT_SNAPLEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - /* We have a connected socket so the kernel can retrieve the source address and port even if the userspace does - * not provide it. + /* We have a connected socket so the kernel can retrieve the source address and port even if the + * userspace does not provide it. */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -// Even if the sockaddr is NULL we can retrieve the information from the kernel socket because we have a connection -// between client and server. -TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_sockaddr) -{ +// Even if the sockaddr is NULL we can retrieve the information from the kernel socket because we +// have a connection between client and server. +TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -329,8 +347,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -348,24 +365,28 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_buffer) -{ +TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_buffer) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom, .null_receiver_buffer = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom, .null_receiver_buffer = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -373,8 +394,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_buffer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -392,8 +412,12 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_buffer) evt_test->assert_empty_param(2); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -402,8 +426,7 @@ TEST(SyscallExit, recvfromX_ipv4_tcp_NULL_buffer) /*=============================== UDP ===========================*/ -TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_by_snaplen) -{ +TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); @@ -411,7 +434,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_by_snaplen) /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto}, - recv_data{.syscall_num = __NR_recvfrom}); + recv_data{.syscall_num = __NR_recvfrom}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -419,8 +442,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -437,24 +459,28 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_by_snaplen) evt_test->assert_bytebuf_param(2, SHORT_MESSAGE, SHORT_MESSAGE_LEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -462,8 +488,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -480,29 +505,34 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_by_snaplen) evt_test->assert_bytebuf_param(2, LONG_MESSAGE, DEFAULT_SNAPLEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -517,8 +547,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -536,24 +565,28 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_not_truncated_fullcapture_port) evt_test->assert_bytebuf_param(2, LONG_MESSAGE, MAX_RECV_BUF_SIZE); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_udp_NULL_sockaddr) -{ +TEST(SyscallExit, recvfromX_ipv4_udp_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -561,8 +594,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_NULL_sockaddr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -582,31 +614,36 @@ TEST(SyscallExit, recvfromX_ipv4_udp_NULL_sockaddr) /* If the `sockaddr` is `NULL` we cannot extract the sender ip and port. * This is not a common case in real applications, it means we are ignoring the sender. */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_EMPTY, IPV4_SERVER, IPV4_PORT_EMPTY_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_EMPTY, + IPV4_SERVER, + IPV4_PORT_EMPTY_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -// If the `sockaddr` is `NULL` we cannot extract the sender ip and port. For this reason, the fullcapture port range -// logic won't work. -TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_fullcapture_port_NULL_sockaddr) -{ +// If the `sockaddr` is `NULL` we cannot extract the sender ip and port. For this reason, the +// fullcapture port range logic won't work. +TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_fullcapture_port_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -621,8 +658,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_fullcapture_port_NULL_soc */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -640,24 +676,28 @@ TEST(SyscallExit, recvfromX_ipv4_udp_message_truncated_fullcapture_port_NULL_soc evt_test->assert_bytebuf_param(2, LONG_MESSAGE, DEFAULT_SNAPLEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_EMPTY, IPV4_SERVER, IPV4_PORT_EMPTY_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_EMPTY, + IPV4_SERVER, + IPV4_PORT_EMPTY_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, recvfromX_ipv4_udp_NULL_buffer) -{ +TEST(SyscallExit, recvfromX_ipv4_udp_NULL_buffer) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvfrom, .null_receiver_buffer = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvfrom, .null_receiver_buffer = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -665,8 +705,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_NULL_buffer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -684,8 +723,12 @@ TEST(SyscallExit, recvfromX_ipv4_udp_NULL_buffer) evt_test->assert_empty_param(2); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -693,8 +736,7 @@ TEST(SyscallExit, recvfromX_ipv4_udp_NULL_buffer) } #endif -TEST(SyscallExit, recvfromX_fail) -{ +TEST(SyscallExit, recvfromX_fail) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); @@ -707,9 +749,15 @@ TEST(SyscallExit, recvfromX_fail) uint32_t flags = 0; sockaddr* src_addr = NULL; socklen_t* addrlen = NULL; - assert_syscall_state( - SYSCALL_FAILURE, "recvfrom", - syscall(__NR_recvfrom, mock_fd, received_data, received_data_len, flags, src_addr, addrlen)); + assert_syscall_state(SYSCALL_FAILURE, + "recvfrom", + syscall(__NR_recvfrom, + mock_fd, + received_data, + received_data_len, + flags, + src_addr, + addrlen)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -718,8 +766,7 @@ TEST(SyscallExit, recvfromX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/recvmmsg_x.cpp b/test/drivers/test_suites/syscall_exit_suite/recvmmsg_x.cpp index 70b8d1ff8e..821376266f 100644 --- a/test/drivers/test_suites/syscall_exit_suite/recvmmsg_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/recvmmsg_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_recvmmsg -TEST(SyscallExit, recvmmsgX) -{ +TEST(SyscallExit, recvmmsgX) { auto evt_test = get_syscall_event_test(__NR_recvmmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallExit, recvmmsgX) uint32_t vlen = 0; int flags = 0; struct timespec *timeout = NULL; - assert_syscall_state(SYSCALL_FAILURE, "recvmmsg", syscall(__NR_recvmmsg, mock_fd, msg, vlen, flags, timeout)); + assert_syscall_state(SYSCALL_FAILURE, + "recvmmsg", + syscall(__NR_recvmmsg, mock_fd, msg, vlen, flags, timeout)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallExit, recvmmsgX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/recvmsg_x.cpp b/test/drivers/test_suites/syscall_exit_suite/recvmsg_x.cpp index 9334d852c5..6f407686dc 100644 --- a/test/drivers/test_suites/syscall_exit_suite/recvmsg_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/recvmsg_x.cpp @@ -2,14 +2,14 @@ #ifdef __NR_recvmsg -#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && \ - defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && \ - defined(__NR_sendto) && defined(__NR_sendmsg) +#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && \ + defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && \ + defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) && \ + defined(__NR_sendmsg) /*=============================== TCP ===========================*/ -TEST(SyscallExit, recvmsgX_ipv4_tcp_message_shorter_than_snaplen) -{ +TEST(SyscallExit, recvmsgX_ipv4_tcp_message_shorter_than_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -17,7 +17,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_shorter_than_snaplen) /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto}, - recv_data{.syscall_num = __NR_recvmsg}); + recv_data{.syscall_num = __NR_recvmsg}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +25,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_shorter_than_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -46,22 +45,25 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_shorter_than_snaplen) evt_test->assert_bytebuf_param(3, SHORT_MESSAGE, SHORT_MESSAGE_LEN); /* Parameter 4: tuple (type: PT_SOCKTUPLE) */ - if(evt_test->is_modern_bpf_engine()) - { - /* The server performs a 'recvmsg` so the server is the final destination of the packet while the client - * is the src. */ - evt_test->assert_tuple_inet_param(4, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); - } - else - { - /// todo!: If the socket is connected, the msg_name and msg_namelen members shall be ignored, but - /// right now we use them to send data also in TCP connections so we need to change this behavior! + if(evt_test->is_modern_bpf_engine()) { + /* The server performs a 'recvmsg` so the server is the final destination of the packet + * while the client is the src. */ + evt_test->assert_tuple_inet_param(4, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); + } else { + /// todo!: If the socket is connected, the msg_name and msg_namelen members shall be + /// ignored, but right now we use them to send data also in TCP connections so we need to + /// change this behavior! evt_test->assert_empty_param(4); evt_test->assert_num_params_pushed(5); - GTEST_SKIP() << "[RECVMSG_X]: we receive an empty tuple but we have all the data in the kernel to " - "obtain the correct tuple" - << std::endl; + GTEST_SKIP() << "[RECVMSG_X]: we receive an empty tuple but we have all the data in the " + "kernel to " + "obtain the correct tuple" + << std::endl; } /* Parameter 5: msg_control (type: PT_BYTEBUF) */ @@ -72,16 +74,16 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_shorter_than_snaplen) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_truncated) -{ +TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_truncated) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -89,8 +91,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_truncated) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -114,21 +115,22 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_truncated) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -143,8 +145,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fu */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -168,21 +169,22 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fu evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, recvmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV6_PORT_CLIENT, IPV6_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv6_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg}); + evt_test->client_to_server_ipv6_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -197,8 +199,7 @@ TEST(SyscallExit, recvmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -222,16 +223,16 @@ TEST(SyscallExit, recvmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_sockaddr) -{ +TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -239,8 +240,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_sockaddr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -259,18 +259,19 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_sockaddr) /* Parameter 3: data (type: PT_BYTEBUF) */ evt_test->assert_bytebuf_param(3, LONG_MESSAGE, DEFAULT_SNAPLEN); - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { /* Parameter 4: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(4, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); - } - else - { + evt_test->assert_tuple_inet_param(4, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); + } else { evt_test->assert_empty_param(4); - GTEST_SKIP() << "[RECVMSG_X]: we rely on the addrlen provided by the kernel but this seems to be always 0." - << "we should rely on kernel structs" - << std::endl; + GTEST_SKIP() << "[RECVMSG_X]: we rely on the addrlen provided by the kernel but this seems " + "to be always 0." + << "we should rely on kernel structs" << std::endl; } /*=============================== ASSERT PARAMETERS ===========================*/ @@ -278,23 +279,25 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_sockaddr) evt_test->assert_num_params_pushed(5); } -// Even if the sockaddr is NULL we can retrieve the information from the kernel socket because we have a connection -// between client and server. -TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fullcapture_port_NULL_sockaddr) -{ +// Even if the sockaddr is NULL we can retrieve the information from the kernel socket because we +// have a connection between client and server. +TEST(SyscallExit, + recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fullcapture_port_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -309,8 +312,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fu */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -334,16 +336,16 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_message_longer_than_snaplen_not_truncated_fu evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_buffer) -{ +TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_buffer) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg, .null_receiver_buffer = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg, .null_receiver_buffer = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -351,8 +353,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_buffer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -378,8 +379,7 @@ TEST(SyscallExit, recvmsgX_ipv4_tcp_NULL_buffer) /*=============================== UDP ===========================*/ -TEST(SyscallExit, recvmsgX_ipv4_udp_message_shorter_than_snaplen) -{ +TEST(SyscallExit, recvmsgX_ipv4_udp_message_shorter_than_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -387,7 +387,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_shorter_than_snaplen) /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto}, - recv_data{.syscall_num = __NR_recvmsg}); + recv_data{.syscall_num = __NR_recvmsg}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -395,8 +395,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_shorter_than_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -416,8 +415,12 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_shorter_than_snaplen) evt_test->assert_bytebuf_param(3, SHORT_MESSAGE, SHORT_MESSAGE_LEN); /* Parameter 4: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(4, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, - IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(4, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 5: msg_control (type: PT_BYTEBUF) */ evt_test->assert_empty_param(5); @@ -427,16 +430,16 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_shorter_than_snaplen) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated) -{ +TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -444,8 +447,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -469,21 +471,22 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -495,8 +498,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_not_truncated_fu evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -520,16 +522,16 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_not_truncated_fu evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_sockaddr) -{ +TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -537,8 +539,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_sockaddr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -557,19 +558,20 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_sockaddr) /* Parameter 3: data (type: PT_BYTEBUF) */ evt_test->assert_bytebuf_param(3, LONG_MESSAGE, DEFAULT_SNAPLEN); - if(evt_test->is_modern_bpf_engine()) - { - + if(evt_test->is_modern_bpf_engine()) { /* Parameter 4: tuple (type: PT_SOCKTUPLE) */ - evt_test->assert_tuple_inet_param(4, PPM_AF_INET, IPV4_EMPTY, IPV4_SERVER, IPV4_PORT_EMPTY_STRING, - IPV4_PORT_SERVER_STRING); - } - else - { + evt_test->assert_tuple_inet_param(4, + PPM_AF_INET, + IPV4_EMPTY, + IPV4_SERVER, + IPV4_PORT_EMPTY_STRING, + IPV4_PORT_SERVER_STRING); + } else { evt_test->assert_empty_param(4); - GTEST_SKIP() << "[RECVMSG_X]: we receive an empty tuple because the pointer to sockaddr is NULL, but " - "we should rely on kernel structs" - << std::endl; + GTEST_SKIP() << "[RECVMSG_X]: we receive an empty tuple because the pointer to sockaddr is " + "NULL, but " + "we should rely on kernel structs" + << std::endl; } /*=============================== ASSERT PARAMETERS ===========================*/ @@ -577,23 +579,25 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_sockaddr) evt_test->assert_num_params_pushed(5); } -// Even if the sockaddr is NULL we can retrieve the information from the kernel socket because we have a connection -// between client and server. -TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated_fullcapture_port_NULL_sockaddr) -{ +// Even if the sockaddr is NULL we can retrieve the information from the kernel socket because we +// have a connection between client and server. +TEST(SyscallExit, + recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated_fullcapture_port_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); - // Now the client port is in the range so we should see the full message not truncated by the snaplen. + // Now the client port is in the range so we should see the full message not truncated by the + // snaplen. evt_test->set_fullcapture_port_range(IPV4_PORT_CLIENT, IPV4_PORT_CLIENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -605,8 +609,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated_fullca evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -630,16 +633,16 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_message_longer_than_snaplen_truncated_fullca evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_buffer) -{ +TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_buffer) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, - recv_data{.syscall_num = __NR_recvmsg, .null_receiver_buffer = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.syscall_num = __NR_recvmsg, .null_receiver_buffer = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -647,8 +650,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_buffer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -675,8 +677,7 @@ TEST(SyscallExit, recvmsgX_ipv4_udp_NULL_buffer) // todo!: we could add a test in which we receive a message on 2 different iovec structs #endif -TEST(SyscallExit, recvmsgX_fail) -{ +TEST(SyscallExit, recvmsgX_fail) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -695,8 +696,7 @@ TEST(SyscallExit, recvmsgX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -724,8 +724,7 @@ TEST(SyscallExit, recvmsgX_fail) /*=============================== ASSERT PARAMETERS ===========================*/ } -TEST(SyscallExit, recvmsg_ancillary_data) -{ +TEST(SyscallExit, recvmsg_ancillary_data) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -736,23 +735,26 @@ TEST(SyscallExit, recvmsg_ancillary_data) int32_t server_socket_fd = 0; struct sockaddr_un client_addr = {}; struct sockaddr_un server_addr = {}; - evt_test->connect_unix_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_unix_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); int64_t received_bytes, sent_bytes, msg_controllen; struct cmsghdr *cmsg; char cmsg_buf[CMSG_SPACE(sizeof(int))]; struct iovec iov = { - .iov_base = (void *)LONG_MESSAGE, - .iov_len = LONG_MESSAGE_LEN, + .iov_base = (void *)LONG_MESSAGE, + .iov_len = LONG_MESSAGE_LEN, }; /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ int connected_socket_fd = syscall(__NR_accept4, server_socket_fd, NULL, NULL, 0); assert_syscall_state(SYSCALL_SUCCESS, "accept (server)", connected_socket_fd, NOT_EQUAL, -1); - /* Now we can fork. We still maintain the connected_socket_fd in both parent and child processes */ + /* Now we can fork. We still maintain the connected_socket_fd in both parent and child processes + */ pid_t pid = fork(); - if(pid) - { + if(pid) { /* Create a socket. It is used to pass it to the child process, just for test purposes */ int sock = socket(AF_UNIX, SOCK_STREAM, 0); msghdr msg = {}; @@ -778,9 +780,7 @@ TEST(SyscallExit, recvmsg_ancillary_data) syscall(__NR_shutdown, sock); syscall(__NR_close, sock); - } - else - { + } else { char buf[LONG_MESSAGE_LEN]; iov = {iov.iov_base = (void *)buf, iov.iov_len = sizeof(buf)}; @@ -814,8 +814,7 @@ TEST(SyscallExit, recvmsg_ancillary_data) evt_test->assert_event_presence(pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/rename_x.cpp b/test/drivers/test_suites/syscall_exit_suite/rename_x.cpp index 579ad909f1..80361ca40b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/rename_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/rename_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_rename -TEST(SyscallExit, renameX) -{ +TEST(SyscallExit, renameX) { auto evt_test = get_syscall_event_test(__NR_rename, EXIT_EVENT); evt_test->enable_capture(); @@ -21,8 +20,7 @@ TEST(SyscallExit, renameX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/renameat2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/renameat2_x.cpp index 2a1a7339d9..0b304ceb35 100644 --- a/test/drivers/test_suites/syscall_exit_suite/renameat2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/renameat2_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_renameat2 -TEST(SyscallExit, renameat2X) -{ +TEST(SyscallExit, renameat2X) { auto evt_test = get_syscall_event_test(__NR_renameat2, EXIT_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallExit, renameat2X) const char* old_path = "**//this/is/the/old/path"; const char* new_path = "**//this/is/the/new/path/"; uint32_t flags = 7; - assert_syscall_state(SYSCALL_FAILURE, "renameat2", syscall(__NR_renameat2, old_fd, old_path, new_fd, new_path, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "renameat2", + syscall(__NR_renameat2, old_fd, old_path, new_fd, new_path, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallExit, renameat2X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/renameat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/renameat_x.cpp index cb03cdc491..ddbc594119 100644 --- a/test/drivers/test_suites/syscall_exit_suite/renameat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/renameat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_renameat -TEST(SyscallExit, renameatX) -{ +TEST(SyscallExit, renameatX) { auto evt_test = get_syscall_event_test(__NR_renameat, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallExit, renameatX) int32_t new_fd = AT_FDCWD; const char* old_path = "**//this/is/the/old/path"; const char* new_path = "**//this/is/the/new/path/"; - assert_syscall_state(SYSCALL_FAILURE, "renameat", syscall(__NR_renameat, old_fd, old_path, new_fd, new_path)); + assert_syscall_state(SYSCALL_FAILURE, + "renameat", + syscall(__NR_renameat, old_fd, old_path, new_fd, new_path)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallExit, renameatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/rmdir_x.cpp b/test/drivers/test_suites/syscall_exit_suite/rmdir_x.cpp index 137309cdfc..de6647e001 100644 --- a/test/drivers/test_suites/syscall_exit_suite/rmdir_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/rmdir_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_rmdir -TEST(SyscallExit, rmdirX) -{ +TEST(SyscallExit, rmdirX) { auto evt_test = get_syscall_event_test(__NR_rmdir, EXIT_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallExit, rmdirX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/seccomp_x.cpp b/test/drivers/test_suites/syscall_exit_suite/seccomp_x.cpp index 6959e2f2ed..96fd5f0237 100644 --- a/test/drivers/test_suites/syscall_exit_suite/seccomp_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/seccomp_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, seccompX) -{ +TEST(SyscallExit, seccompX) { auto evt_test = get_syscall_event_test(__NR_seccomp, EXIT_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallExit, seccompX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/select_x.cpp b/test/drivers/test_suites/syscall_exit_suite/select_x.cpp index 46c93662bc..8b4463806b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/select_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/select_x.cpp @@ -2,15 +2,16 @@ #ifdef __NR_select -TEST(SyscallExit, selectX) -{ +TEST(SyscallExit, selectX) { auto evt_test = get_syscall_event_test(__NR_select, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - assert_syscall_state(SYSCALL_FAILURE, "select", syscall(__NR_select, -1, nullptr, nullptr, nullptr, nullptr)); + assert_syscall_state(SYSCALL_FAILURE, + "select", + syscall(__NR_select, -1, nullptr, nullptr, nullptr, nullptr)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -19,8 +20,7 @@ TEST(SyscallExit, selectX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -37,4 +37,4 @@ TEST(SyscallExit, selectX) evt_test->assert_num_params_pushed(1); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/semctl_x.cpp b/test/drivers/test_suites/syscall_exit_suite/semctl_x.cpp index a0587a22fe..8e25809eb3 100644 --- a/test/drivers/test_suites/syscall_exit_suite/semctl_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/semctl_x.cpp @@ -6,8 +6,7 @@ #include #include -TEST(SyscallExit, semctlX) -{ +TEST(SyscallExit, semctlX) { auto evt_test = get_syscall_event_test(__NR_semctl, EXIT_EVENT); evt_test->enable_capture(); @@ -27,8 +26,7 @@ TEST(SyscallExit, semctlX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -45,4 +43,4 @@ TEST(SyscallExit, semctlX) evt_test->assert_num_params_pushed(1); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/semget_x.cpp b/test/drivers/test_suites/syscall_exit_suite/semget_x.cpp index db04ebbbad..430f395f1a 100644 --- a/test/drivers/test_suites/syscall_exit_suite/semget_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/semget_x.cpp @@ -6,8 +6,7 @@ #include #include -TEST(SyscallExit, semgetX) -{ +TEST(SyscallExit, semgetX) { auto evt_test = get_syscall_event_test(__NR_semget, EXIT_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallExit, semgetX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -44,4 +42,4 @@ TEST(SyscallExit, semgetX) evt_test->assert_num_params_pushed(1); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/semop_x.cpp b/test/drivers/test_suites/syscall_exit_suite/semop_x.cpp index b75a847036..f24a4acf22 100644 --- a/test/drivers/test_suites/syscall_exit_suite/semop_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/semop_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, semopX_null_pointer) -{ +TEST(SyscallExit, semopX_null_pointer) { auto evt_test = get_syscall_event_test(__NR_semop, EXIT_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallExit, semopX_null_pointer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -66,11 +64,10 @@ TEST(SyscallExit, semopX_null_pointer) #if defined(__NR_semget) && defined(__NR_semctl) -/* This case was not managed correctly by old drivers, if we don't check for the syscall return value - * there is the risk to send junk data to userspace when `nops` is wrong. +/* This case was not managed correctly by old drivers, if we don't check for the syscall return + * value there is the risk to send junk data to userspace when `nops` is wrong. */ -TEST(SyscallExit, semopX_wrong_nops) -{ +TEST(SyscallExit, semopX_wrong_nops) { auto evt_test = get_syscall_event_test(__NR_semop, EXIT_EVENT); evt_test->enable_capture(); @@ -102,8 +99,7 @@ TEST(SyscallExit, semopX_wrong_nops) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -142,8 +138,7 @@ TEST(SyscallExit, semopX_wrong_nops) evt_test->assert_num_params_pushed(8); } -TEST(SyscallExit, semopX_1_operation) -{ +TEST(SyscallExit, semopX_1_operation) { auto evt_test = get_syscall_event_test(__NR_semop, EXIT_EVENT); evt_test->enable_capture(); @@ -160,7 +155,11 @@ TEST(SyscallExit, semopX_1_operation) sops.sem_op = 3; sops.sem_flg = SEM_UNDO; size_t nsops = 1; - assert_syscall_state(SYSCALL_SUCCESS, "semop", syscall(__NR_semop, semid, &sops, nsops), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "semop", + syscall(__NR_semop, semid, &sops, nsops), + NOT_EQUAL, + -1); /* Close a semaphore */ syscall(__NR_semctl, semid, 0, IPC_RMID); @@ -171,8 +170,7 @@ TEST(SyscallExit, semopX_1_operation) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -213,8 +211,7 @@ TEST(SyscallExit, semopX_1_operation) evt_test->assert_num_params_pushed(8); } -TEST(SyscallExit, semopX_2_operation) -{ +TEST(SyscallExit, semopX_2_operation) { auto evt_test = get_syscall_event_test(__NR_semop, EXIT_EVENT); evt_test->enable_capture(); @@ -234,7 +231,11 @@ TEST(SyscallExit, semopX_2_operation) sops[1].sem_op = 7; sops[1].sem_flg = IPC_NOWAIT; size_t nsops = 2; - assert_syscall_state(SYSCALL_SUCCESS, "semop", syscall(__NR_semop, semid, sops, nsops), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "semop", + syscall(__NR_semop, semid, sops, nsops), + NOT_EQUAL, + -1); /* Close a semaphore */ syscall(__NR_semctl, semid, 0, IPC_RMID); @@ -245,8 +246,7 @@ TEST(SyscallExit, semopX_2_operation) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/send_x.cpp b/test/drivers/test_suites/syscall_exit_suite/send_x.cpp index 1cd4cf4759..fef1db7bab 100644 --- a/test/drivers/test_suites/syscall_exit_suite/send_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/send_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_send -TEST(SyscallExit, sendX_fail) -{ +TEST(SyscallExit, sendX_fail) { auto evt_test = get_syscall_event_test(__NR_send, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallExit, sendX_fail) const unsigned data_len = DEFAULT_SNAPLEN * 2; char buf[data_len] = "some-data"; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "send", syscall(__NR_send, mock_fd, (void *)buf, data_len, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "send", + syscall(__NR_send, mock_fd, (void *)buf, data_len, flags)); int errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -22,8 +23,7 @@ TEST(SyscallExit, sendX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/sendfile_x.cpp b/test/drivers/test_suites/syscall_exit_suite/sendfile_x.cpp index c30b182d61..d77aa141f8 100644 --- a/test/drivers/test_suites/syscall_exit_suite/sendfile_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/sendfile_x.cpp @@ -2,8 +2,7 @@ #ifdef __NR_sendfile -TEST(SyscallExit, sendfileX_null_pointer) -{ +TEST(SyscallExit, sendfileX_null_pointer) { auto evt_test = get_syscall_event_test(__NR_sendfile, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallExit, sendfileX_null_pointer) int in_fd = -2; void* offsite = NULL; unsigned long size = 37; - assert_syscall_state(SYSCALL_FAILURE, "sendfile", syscall(__NR_sendfile, out_fd, in_fd, offsite, size)); + assert_syscall_state(SYSCALL_FAILURE, + "sendfile", + syscall(__NR_sendfile, out_fd, in_fd, offsite, size)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallExit, sendfileX_null_pointer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -46,8 +46,7 @@ TEST(SyscallExit, sendfileX_null_pointer) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendfileX) -{ +TEST(SyscallExit, sendfileX) { auto evt_test = get_syscall_event_test(__NR_sendfile, EXIT_EVENT); evt_test->enable_capture(); @@ -58,7 +57,9 @@ TEST(SyscallExit, sendfileX) int in_fd = -2; unsigned long offsite = 24; unsigned long size = 37; - assert_syscall_state(SYSCALL_FAILURE, "sendfile", syscall(__NR_sendfile, out_fd, in_fd, &offsite, size)); + assert_syscall_state(SYSCALL_FAILURE, + "sendfile", + syscall(__NR_sendfile, out_fd, in_fd, &offsite, size)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -67,8 +68,7 @@ TEST(SyscallExit, sendfileX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/sendmmsg_x.cpp b/test/drivers/test_suites/syscall_exit_suite/sendmmsg_x.cpp index e6d3b4f14f..5af498a675 100644 --- a/test/drivers/test_suites/syscall_exit_suite/sendmmsg_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/sendmmsg_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_sendmmsg -TEST(SyscallExit, sendmmsgX) -{ +TEST(SyscallExit, sendmmsgX) { auto evt_test = get_syscall_event_test(__NR_sendmmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,9 @@ TEST(SyscallExit, sendmmsgX) struct msghdr *msg = NULL; uint32_t vlen = 0; int flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendmmsg", syscall(__NR_sendmmsg, mock_fd, msg, vlen, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "sendmmsg", + syscall(__NR_sendmmsg, mock_fd, msg, vlen, flags)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallExit, sendmmsgX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/sendmsg_x.cpp b/test/drivers/test_suites/syscall_exit_suite/sendmsg_x.cpp index 064ce8a6ca..443b938250 100644 --- a/test/drivers/test_suites/syscall_exit_suite/sendmsg_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/sendmsg_x.cpp @@ -2,13 +2,12 @@ #ifdef __NR_sendmsg -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ - defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) /*=============================== TCP ===========================*/ -TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_by_snaplen) -{ +TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -45,15 +43,15 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_ipv4_tcp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, sendmsgX_ipv4_tcp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -61,8 +59,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -83,8 +80,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -96,7 +92,8 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -111,8 +108,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -133,8 +129,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, sendmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -146,7 +141,8 @@ TEST(SyscallExit, sendmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv6_tcp(send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); + evt_test->client_to_server_ipv6_tcp( + send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -161,8 +157,7 @@ TEST(SyscallExit, sendmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -183,8 +178,7 @@ TEST(SyscallExit, sendmsgX_ipv6_tcp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_sockaddr) -{ +TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -196,7 +190,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_ /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->client_to_server_ipv4_tcp( - send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true, .null_sockaddr = true}); + send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -211,8 +205,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_ */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -235,8 +228,7 @@ TEST(SyscallExit, sendmsgX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_ /*=============================== UDP ===========================*/ -TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_by_snaplen) -{ +TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -251,8 +243,7 @@ TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -273,15 +264,15 @@ TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_ipv4_udp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, sendmsgX_ipv4_udp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -289,8 +280,7 @@ TEST(SyscallExit, sendmsgX_ipv4_udp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -311,8 +301,7 @@ TEST(SyscallExit, sendmsgX_ipv4_udp_message_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -323,7 +312,8 @@ TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_fullcapture_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendmsg, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -338,8 +328,7 @@ TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -360,13 +349,13 @@ TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(2); } -// We cannot call a sendmsg without a destination address in UDP. Errno: 89 err_message: Destination address required. -// TEST(SyscallExit, sendmsgX_ipv4_udp_message_not_truncated_fullcapture_port_NULL_sockaddr) +// We cannot call a sendmsg without a destination address in UDP. Errno: 89 err_message: Destination +// address required. TEST(SyscallExit, +// sendmsgX_ipv4_udp_message_not_truncated_fullcapture_port_NULL_sockaddr) #endif -TEST(SyscallExit, sendmsgX_fail) -{ +TEST(SyscallExit, sendmsgX_fail) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -385,7 +374,9 @@ TEST(SyscallExit, sendmsgX_fail) send_msg.msg_iovlen = 1; uint32_t sendmsg_flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendmsg", syscall(__NR_sendmsg, mock_fd, &send_msg, sendmsg_flags)); + assert_syscall_state(SYSCALL_FAILURE, + "sendmsg", + syscall(__NR_sendmsg, mock_fd, &send_msg, sendmsg_flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -394,8 +385,7 @@ TEST(SyscallExit, sendmsgX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -416,8 +406,7 @@ TEST(SyscallExit, sendmsgX_fail) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_null_iovec) -{ +TEST(SyscallExit, sendmsgX_null_iovec) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -432,29 +421,28 @@ TEST(SyscallExit, sendmsgX_null_iovec) send_msg.msg_iovlen = 3; uint32_t sendmsg_flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendmsg", syscall(__NR_sendmsg, mock_fd, &send_msg, sendmsg_flags)); + assert_syscall_state(SYSCALL_FAILURE, + "sendmsg", + syscall(__NR_sendmsg, mock_fd, &send_msg, sendmsg_flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { evt_test->assert_event_presence(); - } - else - { + } else { /* we need to rewrite the logic in old drivers to support this partial collection * right now we drop the entire event. */ evt_test->assert_event_absence(); - GTEST_SKIP() << "[SENDMSG_X]: what we receive is correct but we need to reimplement it, see the code" - << std::endl; + GTEST_SKIP() << "[SENDMSG_X]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -475,8 +463,7 @@ TEST(SyscallExit, sendmsgX_null_iovec) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendmsgX_null_msghdr) -{ +TEST(SyscallExit, sendmsgX_null_msghdr) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -487,7 +474,9 @@ TEST(SyscallExit, sendmsgX_null_msghdr) struct msghdr* send_msg = NULL; uint32_t sendmsg_flags = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendmsg", syscall(__NR_sendmsg, mock_fd, send_msg, sendmsg_flags)); + assert_syscall_state(SYSCALL_FAILURE, + "sendmsg", + syscall(__NR_sendmsg, mock_fd, send_msg, sendmsg_flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -496,8 +485,7 @@ TEST(SyscallExit, sendmsgX_null_msghdr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/sendto_x.cpp b/test/drivers/test_suites/syscall_exit_suite/sendto_x.cpp index b8a8f6bfa2..a4dc4c25ea 100644 --- a/test/drivers/test_suites/syscall_exit_suite/sendto_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/sendto_x.cpp @@ -2,13 +2,12 @@ #ifdef __NR_sendto -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ - defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) /*=============================== TCP ===========================*/ -TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_by_snaplen) -{ +TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -45,15 +43,15 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_ipv4_tcp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, sendtoX_ipv4_tcp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -61,8 +59,7 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -83,8 +80,7 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -96,7 +92,8 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -111,8 +108,7 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -133,51 +129,52 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_DNS_snaplen) -{ - auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); +TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_DNS_snaplen) { + auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); - evt_test->set_do_dynamic_snaplen(true); + evt_test->set_do_dynamic_snaplen(true); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - // The remote port is the DNS one so the snaplen should be increased. - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, recv_data{.skip_recv_phase = true}, IP_PORT_CLIENT, IP_PORT_DNS); + // The remote port is the DNS one so the snaplen should be increased. + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}, + recv_data{.skip_recv_phase = true}, + IP_PORT_CLIENT, + IP_PORT_DNS); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->set_do_dynamic_snaplen(false); + evt_test->set_do_dynamic_snaplen(false); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ - evt_test->assert_numeric_param(1, (int64_t)LONG_MESSAGE_LEN); + /* Parameter 1: res (type: PT_ERRNO) */ + evt_test->assert_numeric_param(1, (int64_t)LONG_MESSAGE_LEN); - /* Parameter 2: data (type: PT_BYTEBUF)*/ - evt_test->assert_bytebuf_param(2, LONG_MESSAGE, LONG_MESSAGE_LEN); + /* Parameter 2: data (type: PT_BYTEBUF)*/ + evt_test->assert_bytebuf_param(2, LONG_MESSAGE, LONG_MESSAGE_LEN); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(2); + evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_ipv6_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, sendtoX_ipv6_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -189,7 +186,8 @@ TEST(SyscallExit, sendtoX_ipv6_tcp_message_not_truncated_fullcapture_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -204,8 +202,7 @@ TEST(SyscallExit, sendtoX_ipv6_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -226,8 +223,7 @@ TEST(SyscallExit, sendtoX_ipv6_tcp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_sockaddr) -{ +TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_sockaddr) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -239,7 +235,7 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_s /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->client_to_server_ipv4_tcp( - send_data{.syscall_num = __NR_sendto, .greater_snaplen = true, .null_sockaddr = true}); + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true, .null_sockaddr = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -254,8 +250,7 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_s */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -278,8 +273,7 @@ TEST(SyscallExit, sendtoX_ipv4_tcp_message_not_truncated_fullcapture_port_NULL_s /*=============================== UDP ===========================*/ -TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_by_snaplen) -{ +TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -294,8 +288,7 @@ TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -316,15 +309,15 @@ TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_ipv4_udp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, sendtoX_ipv4_udp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -332,8 +325,7 @@ TEST(SyscallExit, sendtoX_ipv4_udp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -354,8 +346,7 @@ TEST(SyscallExit, sendtoX_ipv4_udp_message_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -366,7 +357,8 @@ TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_fullcapture_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_udp(send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_udp( + send_data{.syscall_num = __NR_sendto, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -381,8 +373,7 @@ TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -403,12 +394,12 @@ TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(2); } -// We cannot call a sendto without a destination address in UDP. Errno: 89 err_message: Destination address required. -// TEST(SyscallExit, sendtoX_ipv4_udp_message_not_truncated_fullcapture_port_NULL_sockaddr) +// We cannot call a sendto without a destination address in UDP. Errno: 89 err_message: Destination +// address required. TEST(SyscallExit, +// sendtoX_ipv4_udp_message_not_truncated_fullcapture_port_NULL_sockaddr) #endif -TEST(SyscallExit, sendtoX_fail) -{ +TEST(SyscallExit, sendtoX_fail) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -422,8 +413,10 @@ TEST(SyscallExit, sendtoX_fail) struct sockaddr* dest_addr = NULL; socklen_t addrlen = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendto", - syscall(__NR_sendto, mock_fd, sent_data, len, sendto_flags, dest_addr, addrlen)); + assert_syscall_state( + SYSCALL_FAILURE, + "sendto", + syscall(__NR_sendto, mock_fd, sent_data, len, sendto_flags, dest_addr, addrlen)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -432,8 +425,7 @@ TEST(SyscallExit, sendtoX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -454,8 +446,7 @@ TEST(SyscallExit, sendtoX_fail) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, sendtoX_empty) -{ +TEST(SyscallExit, sendtoX_empty) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -469,8 +460,10 @@ TEST(SyscallExit, sendtoX_empty) struct sockaddr* dest_addr = NULL; socklen_t addrlen = 0; - assert_syscall_state(SYSCALL_FAILURE, "sendto", - syscall(__NR_sendto, mock_fd, sent_data, len, sendto_flags, dest_addr, addrlen)); + assert_syscall_state( + SYSCALL_FAILURE, + "sendto", + syscall(__NR_sendto, mock_fd, sent_data, len, sendto_flags, dest_addr, addrlen)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -479,8 +472,7 @@ TEST(SyscallExit, sendtoX_empty) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setgid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setgid_x.cpp index 03563b3336..3d5d6e6490 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setgid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setgid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setgid -TEST(SyscallExit, setgidX) -{ +TEST(SyscallExit, setgidX) { auto evt_test = get_syscall_event_test(__NR_setgid, EXIT_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallExit, setgidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setns_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setns_x.cpp index 413a6a65ef..1ba93bf2c9 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setns_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setns_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setns -TEST(SyscallExit, setnsX) -{ +TEST(SyscallExit, setnsX) { auto evt_test = get_syscall_event_test(__NR_setns, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, setnsX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setpgid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setpgid_x.cpp index cfe350f78c..5b0653fec0 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setpgid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setpgid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setpgid -TEST(SyscallExit, setpgidX) -{ +TEST(SyscallExit, setpgidX) { auto evt_test = get_syscall_event_test(__NR_setpgid, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, setpgidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setregid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setregid_x.cpp index 5f5c8f99f8..13d6733f3a 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setregid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setregid_x.cpp @@ -1,47 +1,49 @@ #include "../../event_class/event_class.h" #ifdef __NR_setresgid -TEST(SyscallExit, setregidX) -{ - auto evt_test = get_syscall_event_test(__NR_setregid, EXIT_EVENT); +TEST(SyscallExit, setregidX) { + auto evt_test = get_syscall_event_test(__NR_setregid, EXIT_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - gid_t rgid = (uint32_t)-1; - gid_t egid = (uint32_t)-1; - /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setregid", syscall(__NR_setregid, rgid, egid), NOT_EQUAL, -1); + gid_t rgid = (uint32_t)-1; + gid_t egid = (uint32_t)-1; + /* If one of the arguments equals -1, the corresponding value is not changed. */ + assert_syscall_state(SYSCALL_SUCCESS, + "setregid", + syscall(__NR_setregid, rgid, egid), + NOT_EQUAL, + -1); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ - evt_test->assert_numeric_param(1, (int64_t)0); + /* Parameter 1: res (type: PT_ERRNO) */ + evt_test->assert_numeric_param(1, (int64_t)0); - /* Parameter 1: rgid (type: PT_GID) */ - evt_test->assert_numeric_param(2, (uint32_t)rgid); + /* Parameter 1: rgid (type: PT_GID) */ + evt_test->assert_numeric_param(2, (uint32_t)rgid); - /* Parameter 2: egid (type: PT_GID) */ - evt_test->assert_numeric_param(3, (uint32_t)egid); + /* Parameter 2: egid (type: PT_GID) */ + evt_test->assert_numeric_param(3, (uint32_t)egid); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(3); + evt_test->assert_num_params_pushed(3); } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/setresgid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setresgid_x.cpp index 9550630a11..a8f29cef78 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setresgid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setresgid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setresgid -TEST(SyscallExit, setresgidX) -{ +TEST(SyscallExit, setresgidX) { auto evt_test = get_syscall_event_test(__NR_setresgid, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,11 @@ TEST(SyscallExit, setresgidX) gid_t egid = (uint32_t)-1; gid_t sgid = (uint32_t)-1; /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setresgid", syscall(__NR_setresgid, rgid, egid, sgid), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setresgid", + syscall(__NR_setresgid, rgid, egid, sgid), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +24,7 @@ TEST(SyscallExit, setresgidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setresuid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setresuid_x.cpp index f0e821b08d..cb77e967d7 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setresuid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setresuid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setresuid -TEST(SyscallExit, setresuidX) -{ +TEST(SyscallExit, setresuidX) { auto evt_test = get_syscall_event_test(__NR_setresuid, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,11 @@ TEST(SyscallExit, setresuidX) uid_t euid = (uint32_t)-1; uid_t suid = (uint32_t)-1; /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setresuid", syscall(__NR_setresuid, ruid, euid, suid), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setresuid", + syscall(__NR_setresuid, ruid, euid, suid), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +24,7 @@ TEST(SyscallExit, setresuidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setreuid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setreuid_x.cpp index 26239e811d..2eef984c05 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setreuid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setreuid_x.cpp @@ -1,47 +1,49 @@ #include "../../event_class/event_class.h" #ifdef __NR_setresuid -TEST(SyscallExit, setreuidX) -{ - auto evt_test = get_syscall_event_test(__NR_setreuid, EXIT_EVENT); +TEST(SyscallExit, setreuidX) { + auto evt_test = get_syscall_event_test(__NR_setreuid, EXIT_EVENT); - evt_test->enable_capture(); + evt_test->enable_capture(); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - uid_t ruid = (uint32_t)-1; - uid_t euid = (uint32_t)-1; - /* If one of the arguments equals -1, the corresponding value is not changed. */ - assert_syscall_state(SYSCALL_SUCCESS, "setreuid", syscall(__NR_setreuid, ruid, euid), NOT_EQUAL, -1); + uid_t ruid = (uint32_t)-1; + uid_t euid = (uint32_t)-1; + /* If one of the arguments equals -1, the corresponding value is not changed. */ + assert_syscall_state(SYSCALL_SUCCESS, + "setreuid", + syscall(__NR_setreuid, ruid, euid), + NOT_EQUAL, + -1); - /*=============================== TRIGGER SYSCALL ===========================*/ + /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->disable_capture(); + evt_test->disable_capture(); - evt_test->assert_event_presence(); + evt_test->assert_event_presence(); - if(HasFatalFailure()) - { - return; - } + if(HasFatalFailure()) { + return; + } - evt_test->parse_event(); + evt_test->parse_event(); - evt_test->assert_header(); + evt_test->assert_header(); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - /* Parameter 1: res (type: PT_ERRNO) */ - evt_test->assert_numeric_param(1, (int64_t)0); + /* Parameter 1: res (type: PT_ERRNO) */ + evt_test->assert_numeric_param(1, (int64_t)0); - /* Parameter 2: ruid (type: PT_GID) */ - evt_test->assert_numeric_param(2, (uint32_t)ruid); + /* Parameter 2: ruid (type: PT_GID) */ + evt_test->assert_numeric_param(2, (uint32_t)ruid); - /* Parameter 3: euid (type: PT_GID) */ - evt_test->assert_numeric_param(3, (uint32_t)euid); + /* Parameter 3: euid (type: PT_GID) */ + evt_test->assert_numeric_param(3, (uint32_t)euid); - /*=============================== ASSERT PARAMETERS ===========================*/ + /*=============================== ASSERT PARAMETERS ===========================*/ - evt_test->assert_num_params_pushed(3); + evt_test->assert_num_params_pushed(3); } #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/setrlimit_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setrlimit_x.cpp index 6ae90107b1..0567c9e4eb 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setrlimit_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setrlimit_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, setrlimitX_null_rlimit_pointer) -{ +TEST(SyscallExit, setrlimitX_null_rlimit_pointer) { auto evt_test = get_syscall_event_test(__NR_setrlimit, EXIT_EVENT); evt_test->enable_capture(); @@ -24,8 +23,7 @@ TEST(SyscallExit, setrlimitX_null_rlimit_pointer) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -52,8 +50,7 @@ TEST(SyscallExit, setrlimitX_null_rlimit_pointer) evt_test->assert_num_params_pushed(4); } -TEST(SyscallExit, setrlimitX_wrong_resource) -{ +TEST(SyscallExit, setrlimitX_wrong_resource) { auto evt_test = get_syscall_event_test(__NR_setrlimit, EXIT_EVENT); evt_test->enable_capture(); @@ -75,8 +72,7 @@ TEST(SyscallExit, setrlimitX_wrong_resource) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -103,8 +99,7 @@ TEST(SyscallExit, setrlimitX_wrong_resource) evt_test->assert_num_params_pushed(4); } -TEST(SyscallExit, setrlimitX_success) -{ +TEST(SyscallExit, setrlimitX_success) { auto evt_test = get_syscall_event_test(__NR_setrlimit, EXIT_EVENT); evt_test->enable_capture(); @@ -126,8 +121,7 @@ TEST(SyscallExit, setrlimitX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setsid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setsid_x.cpp index ed4d6062d2..27c0a36ac4 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setsid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setsid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setsid -TEST(SyscallExit, setsidX) -{ +TEST(SyscallExit, setsidX) { auto evt_test = get_syscall_event_test(__NR_setsid, EXIT_EVENT); evt_test->enable_capture(); @@ -22,8 +21,7 @@ TEST(SyscallExit, setsidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setsockopt_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setsockopt_x.cpp index ea65e90eda..97be17feaa 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setsockopt_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setsockopt_x.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallExit, setsockoptX_SO_ERROR) -{ +TEST(SyscallExit, setsockoptX_SO_ERROR) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -18,7 +17,10 @@ TEST(SyscallExit, setsockoptX_SO_ERROR) int32_t option_name = SO_ERROR; int32_t option_value = 14; socklen_t option_len = sizeof(int32_t); - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -27,8 +29,7 @@ TEST(SyscallExit, setsockoptX_SO_ERROR) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -63,8 +64,7 @@ TEST(SyscallExit, setsockoptX_SO_ERROR) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, setsockoptX_SO_RCVTIMEO) -{ +TEST(SyscallExit, setsockoptX_SO_RCVTIMEO) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -78,7 +78,10 @@ TEST(SyscallExit, setsockoptX_SO_RCVTIMEO) option_value.tv_sec = 5; option_value.tv_usec = 10; socklen_t option_len = sizeof(struct timeval); - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -87,8 +90,7 @@ TEST(SyscallExit, setsockoptX_SO_RCVTIMEO) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -122,8 +124,7 @@ TEST(SyscallExit, setsockoptX_SO_RCVTIMEO) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, setsockoptX_SO_COOKIE) -{ +TEST(SyscallExit, setsockoptX_SO_COOKIE) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -135,7 +136,10 @@ TEST(SyscallExit, setsockoptX_SO_COOKIE) int32_t option_name = SO_COOKIE; uint64_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -144,8 +148,7 @@ TEST(SyscallExit, setsockoptX_SO_COOKIE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -178,8 +181,7 @@ TEST(SyscallExit, setsockoptX_SO_COOKIE) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, setsockoptX_SO_PASSCRED) -{ +TEST(SyscallExit, setsockoptX_SO_PASSCRED) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -191,7 +193,10 @@ TEST(SyscallExit, setsockoptX_SO_PASSCRED) int32_t option_name = SO_PASSCRED; uint32_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -200,8 +205,7 @@ TEST(SyscallExit, setsockoptX_SO_PASSCRED) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -234,8 +238,7 @@ TEST(SyscallExit, setsockoptX_SO_PASSCRED) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, setsockoptX_UNKNOWN_OPTION) -{ +TEST(SyscallExit, setsockoptX_UNKNOWN_OPTION) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -247,7 +250,10 @@ TEST(SyscallExit, setsockoptX_UNKNOWN_OPTION) int32_t option_name = -1; /* this is an unknown option. */ uint32_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -256,8 +262,7 @@ TEST(SyscallExit, setsockoptX_UNKNOWN_OPTION) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -290,8 +295,7 @@ TEST(SyscallExit, setsockoptX_UNKNOWN_OPTION) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, setsockoptX_SOL_UNKNOWN) -{ +TEST(SyscallExit, setsockoptX_SOL_UNKNOWN) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -303,7 +307,10 @@ TEST(SyscallExit, setsockoptX_SOL_UNKNOWN) int32_t option_name = SO_PASSCRED; uint32_t option_value = 16; socklen_t option_len = sizeof(option_value); - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -312,8 +319,7 @@ TEST(SyscallExit, setsockoptX_SOL_UNKNOWN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -346,8 +352,7 @@ TEST(SyscallExit, setsockoptX_SOL_UNKNOWN) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, setsockoptX_ZERO_OPTLEN) -{ +TEST(SyscallExit, setsockoptX_ZERO_OPTLEN) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -359,7 +364,10 @@ TEST(SyscallExit, setsockoptX_ZERO_OPTLEN) int32_t option_name = SO_PASSCRED; uint32_t option_value = 0; socklen_t option_len = 0; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); + assert_syscall_state( + SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_setsockopt, mock_fd, level, option_name, &option_value, option_len)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -368,8 +376,7 @@ TEST(SyscallExit, setsockoptX_ZERO_OPTLEN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/setuid_x.cpp b/test/drivers/test_suites/syscall_exit_suite/setuid_x.cpp index 688aae2146..78bde08f92 100644 --- a/test/drivers/test_suites/syscall_exit_suite/setuid_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/setuid_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_setuid -TEST(SyscallExit, setuidX) -{ +TEST(SyscallExit, setuidX) { auto evt_test = get_syscall_event_test(__NR_setuid, EXIT_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallExit, setuidX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/shutdown_x.cpp b/test/drivers/test_suites/syscall_exit_suite/shutdown_x.cpp index 769bf32a0d..99a992a6a1 100644 --- a/test/drivers/test_suites/syscall_exit_suite/shutdown_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/shutdown_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, shutdownX) -{ +TEST(SyscallExit, shutdownX) { auto evt_test = get_syscall_event_test(__NR_shutdown, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, shutdownX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/signalfd4_x.cpp b/test/drivers/test_suites/syscall_exit_suite/signalfd4_x.cpp index de47750f9e..7065efc8e9 100644 --- a/test/drivers/test_suites/syscall_exit_suite/signalfd4_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/signalfd4_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, signalfd4X) -{ +TEST(SyscallExit, signalfd4X) { auto evt_test = get_syscall_event_test(__NR_signalfd4, EXIT_EVENT); evt_test->enable_capture(); @@ -18,7 +17,9 @@ TEST(SyscallExit, signalfd4X) size_t sizemask = 0; /* Our instrumentation will convert these into `O_NONBLOCK | O_CLOEXEC` */ int flags = SFD_NONBLOCK | SFD_CLOEXEC; - assert_syscall_state(SYSCALL_FAILURE, "signalfd4", syscall(__NR_signalfd4, mock_fd, &mask, sizemask, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "signalfd4", + syscall(__NR_signalfd4, mock_fd, &mask, sizemask, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -27,8 +28,7 @@ TEST(SyscallExit, signalfd4X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/signalfd_x.cpp b/test/drivers/test_suites/syscall_exit_suite/signalfd_x.cpp index 59593c6be7..7bd009d170 100644 --- a/test/drivers/test_suites/syscall_exit_suite/signalfd_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/signalfd_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, signalfdX) -{ +TEST(SyscallExit, signalfdX) { auto evt_test = get_syscall_event_test(__NR_signalfd, EXIT_EVENT); evt_test->enable_capture(); @@ -16,7 +15,9 @@ TEST(SyscallExit, signalfdX) int32_t mock_fd = -1; sigset_t mask = {0}; size_t sizemask = 0; - assert_syscall_state(SYSCALL_FAILURE, "signalfd", syscall(__NR_signalfd, mock_fd, &mask, sizemask)); + assert_syscall_state(SYSCALL_FAILURE, + "signalfd", + syscall(__NR_signalfd, mock_fd, &mask, sizemask)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -25,8 +26,7 @@ TEST(SyscallExit, signalfdX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/socket_x.cpp b/test/drivers/test_suites/syscall_exit_suite/socket_x.cpp index 0b732b39b8..8be270264d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/socket_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/socket_x.cpp @@ -5,8 +5,7 @@ #include #include -TEST(SyscallExit, socketX) -{ +TEST(SyscallExit, socketX) { auto evt_test = get_syscall_event_test(__NR_socket, EXIT_EVENT); evt_test->enable_capture(); @@ -25,15 +24,11 @@ TEST(SyscallExit, socketX) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_socket, domain, type, protocol) == -1) - { + if(syscall(__NR_socket, domain, type, protocol) == -1) { exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -42,10 +37,13 @@ TEST(SyscallExit, socketX) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The socket call is successful while it should fail..." << std::endl; } @@ -58,8 +56,7 @@ TEST(SyscallExit, socketX) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/socketcall_x.cpp b/test/drivers/test_suites/syscall_exit_suite/socketcall_x.cpp index 2baa90e997..17e73c5089 100644 --- a/test/drivers/test_suites/syscall_exit_suite/socketcall_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/socketcall_x.cpp @@ -10,8 +10,7 @@ #if defined(__NR_clone3) && defined(__NR_wait4) #include -TEST(SyscallExit, socketcall_socketX) -{ +TEST(SyscallExit, socketcall_socketX) { auto evt_test = get_syscall_event_test(__NR_socket, EXIT_EVENT); evt_test->enable_capture(); @@ -31,15 +30,11 @@ TEST(SyscallExit, socketcall_socketX) cl_args.exit_signal = SIGCHLD; pid_t ret_pid = syscall(__NR_clone3, &cl_args, sizeof(cl_args)); - if(ret_pid == 0) - { + if(ret_pid == 0) { /* In this way in the father we know if the call was successful or not. */ - if(syscall(__NR_socketcall, SYS_SOCKET, args) == -1) - { + if(syscall(__NR_socketcall, SYS_SOCKET, args) == -1) { exit(EXIT_SUCCESS); - } - else - { + } else { exit(EXIT_FAILURE); } } @@ -48,10 +43,13 @@ TEST(SyscallExit, socketcall_socketX) /* Catch the child before doing anything else. */ int status = 0; int options = 0; - assert_syscall_state(SYSCALL_SUCCESS, "wait4", syscall(__NR_wait4, ret_pid, &status, options, NULL), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "wait4", + syscall(__NR_wait4, ret_pid, &status, options, NULL), + NOT_EQUAL, + -1); - if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) - { + if(__WEXITSTATUS(status) == EXIT_FAILURE || __WIFSIGNALED(status) != 0) { FAIL() << "The 'socketcall socket' is successful while it should fail..." << std::endl; } @@ -64,8 +62,7 @@ TEST(SyscallExit, socketcall_socketX) evt_test->assert_event_presence(ret_pid); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -84,8 +81,7 @@ TEST(SyscallExit, socketcall_socketX) } #endif -TEST(SyscallExit, socketcall_bindX) -{ +TEST(SyscallExit, socketcall_bindX) { auto evt_test = get_syscall_event_test(__NR_bind, EXIT_EVENT); evt_test->enable_capture(); @@ -104,7 +100,11 @@ TEST(SyscallExit, socketcall_bindX) args[1] = (unsigned long)&server_addr; args[2] = sizeof(server_addr); - assert_syscall_state(SYSCALL_SUCCESS, "bind", syscall(__NR_socketcall, SYS_BIND, args), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "bind", + syscall(__NR_socketcall, SYS_BIND, args), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, server_socket_fd); @@ -115,8 +115,7 @@ TEST(SyscallExit, socketcall_bindX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -137,8 +136,7 @@ TEST(SyscallExit, socketcall_bindX) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, socketcall_connectX) -{ +TEST(SyscallExit, socketcall_connectX) { auto evt_test = get_syscall_event_test(__NR_connect, EXIT_EVENT); evt_test->enable_capture(); @@ -153,18 +151,28 @@ TEST(SyscallExit, socketcall_connectX) evt_test->client_fill_sockaddr_in(&client_addr); /* We need to bind the client socket with an address otherwise we cannot assert against it. */ - assert_syscall_state(SYSCALL_SUCCESS, "bind (client)", syscall(__NR_bind, client_socket_fd, (sockaddr*)&client_addr, sizeof(client_addr)), NOT_EQUAL, -1); + assert_syscall_state( + SYSCALL_SUCCESS, + "bind (client)", + syscall(__NR_bind, client_socket_fd, (sockaddr *)&client_addr, sizeof(client_addr)), + NOT_EQUAL, + -1); /* Now we associate the client socket with the server address. */ sockaddr_in server_addr; evt_test->server_fill_sockaddr_in(&server_addr); - /* With `SOCK_DGRAM` the `connect` will not perform a connection this is why the syscall doesn't fail. */ + /* With `SOCK_DGRAM` the `connect` will not perform a connection this is why the syscall doesn't + * fail. */ unsigned long args[3] = {0}; args[0] = client_socket_fd; args[1] = (unsigned long)&server_addr; args[2] = sizeof(server_addr); - assert_syscall_state(SYSCALL_SUCCESS, "socketcall connect (client)", syscall(__NR_socketcall, SYS_CONNECT, args), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "socketcall connect (client)", + syscall(__NR_socketcall, SYS_CONNECT, args), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, client_socket_fd); @@ -175,8 +183,7 @@ TEST(SyscallExit, socketcall_connectX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -191,7 +198,12 @@ TEST(SyscallExit, socketcall_connectX) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The client performs a `connect` so the client is the src. */ - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 3: fd (type: PT_FD) */ evt_test->assert_numeric_param(3, (int64_t)client_socket_fd); @@ -203,8 +215,7 @@ TEST(SyscallExit, socketcall_connectX) #endif #ifdef __NR_recvmmsg -TEST(SyscallExit, socketcall_recvmmsgX) -{ +TEST(SyscallExit, socketcall_recvmmsgX) { auto evt_test = get_syscall_event_test(__NR_recvmmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -231,8 +242,7 @@ TEST(SyscallExit, socketcall_recvmmsgX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -251,8 +261,7 @@ TEST(SyscallExit, socketcall_recvmmsgX) #endif #ifdef __NR_sendmmsg -TEST(SyscallExit, socketcall_sendmmsgX) -{ +TEST(SyscallExit, socketcall_sendmmsgX) { auto evt_test = get_syscall_event_test(__NR_sendmmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -277,8 +286,7 @@ TEST(SyscallExit, socketcall_sendmmsgX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -296,8 +304,7 @@ TEST(SyscallExit, socketcall_sendmmsgX) } #endif -TEST(SyscallExit, socketcall_shutdownX) -{ +TEST(SyscallExit, socketcall_shutdownX) { auto evt_test = get_syscall_event_test(__NR_shutdown, EXIT_EVENT); evt_test->enable_capture(); @@ -319,8 +326,7 @@ TEST(SyscallExit, socketcall_shutdownX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -340,15 +346,14 @@ TEST(SyscallExit, socketcall_shutdownX) #if defined(__NR_accept) || defined(__s390x__) -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) -TEST(SyscallExit, socketcall_acceptX_INET) -{ +TEST(SyscallExit, socketcall_acceptX_INET) { #ifdef __s390x__ auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); /* The kmod/bpf can correctly handle accept also on s390x */ - if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) - { + if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) { /* we cannot set `__NR_accept` explicitly since it is not defined on s390x * we activate all syscalls. */ @@ -367,7 +372,10 @@ TEST(SyscallExit, socketcall_acceptX_INET) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ unsigned long args[3] = {0}; @@ -391,8 +399,7 @@ TEST(SyscallExit, socketcall_acceptX_INET) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -407,7 +414,12 @@ TEST(SyscallExit, socketcall_acceptX_INET) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -425,13 +437,11 @@ TEST(SyscallExit, socketcall_acceptX_INET) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, socketcall_acceptX_INET6) -{ +TEST(SyscallExit, socketcall_acceptX_INET6) { #ifdef __s390x__ auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); /* The kmod/bpf can correctly handle accept also on s390x */ - if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) - { + if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) { /* we cannot set `__NR_accept` explicitly since it is not defined on s390x * we activate all syscalls. */ @@ -450,7 +460,10 @@ TEST(SyscallExit, socketcall_acceptX_INET6) int32_t server_socket_fd = 0; sockaddr_in6 client_addr = {0}; sockaddr_in6 server_addr = {0}; - evt_test->connect_ipv6_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv6_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ unsigned long args[3] = {0}; @@ -474,8 +487,7 @@ TEST(SyscallExit, socketcall_acceptX_INET6) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -490,7 +502,12 @@ TEST(SyscallExit, socketcall_acceptX_INET6) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet6_param(2, PPM_AF_INET6, IPV6_CLIENT, IPV6_SERVER, IPV6_PORT_CLIENT_STRING, IPV6_PORT_SERVER_STRING); + evt_test->assert_tuple_inet6_param(2, + PPM_AF_INET6, + IPV6_CLIENT, + IPV6_SERVER, + IPV6_PORT_CLIENT_STRING, + IPV6_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -509,13 +526,11 @@ TEST(SyscallExit, socketcall_acceptX_INET6) } #ifdef __NR_unlinkat -TEST(SyscallExit, socketcall_acceptX_UNIX) -{ +TEST(SyscallExit, socketcall_acceptX_UNIX) { #ifdef __s390x__ auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); /* The kmod/bpf can correctly handle accept also on s390x */ - if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) - { + if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) { /* we cannot set `__NR_accept` explicitly since it is not defined on s390x * we activate all syscalls. */ @@ -534,7 +549,10 @@ TEST(SyscallExit, socketcall_acceptX_UNIX) int32_t server_socket_fd = 0; struct sockaddr_un client_addr = {0}; struct sockaddr_un server_addr = {0}; - evt_test->connect_unix_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_unix_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ unsigned long args[3] = {0}; @@ -560,8 +578,7 @@ TEST(SyscallExit, socketcall_acceptX_UNIX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -595,13 +612,11 @@ TEST(SyscallExit, socketcall_acceptX_UNIX) } #endif /* __NR_unlinkat */ -TEST(SyscallExit, socketcall_acceptX_failure) -{ +TEST(SyscallExit, socketcall_acceptX_failure) { #ifdef __s390x__ auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); /* The kmod/bpf can correctly handle accept also on s390x */ - if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) - { + if(evt_test->is_kmod_engine() || evt_test->is_bpf_engine()) { /* we cannot set `__NR_accept` explicitly since it is not defined on s390x * we activate all syscalls. */ @@ -617,7 +632,7 @@ TEST(SyscallExit, socketcall_acceptX_failure) /*=============================== TRIGGER SYSCALL ===========================*/ int mock_fd = -1; - sockaddr* addr = NULL; + sockaddr *addr = NULL; socklen_t *addrlen = NULL; unsigned long args[3] = {0}; @@ -633,8 +648,7 @@ TEST(SyscallExit, socketcall_acceptX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -666,10 +680,11 @@ TEST(SyscallExit, socketcall_acceptX_failure) #endif #endif /* __NR_accept || __s390x__ */ -#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && \ + defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && \ + defined(__NR_setsockopt) && defined(__NR_shutdown) -TEST(SyscallExit, socketcall_accept4X_INET) -{ +TEST(SyscallExit, socketcall_accept4X_INET) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -680,10 +695,13 @@ TEST(SyscallExit, socketcall_accept4X_INET) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ - sockaddr* addr = NULL; + sockaddr *addr = NULL; socklen_t *addrlen = NULL; int flags = 0; @@ -709,8 +727,7 @@ TEST(SyscallExit, socketcall_accept4X_INET) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -725,7 +742,12 @@ TEST(SyscallExit, socketcall_accept4X_INET) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet_param(2, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + evt_test->assert_tuple_inet_param(2, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -743,8 +765,7 @@ TEST(SyscallExit, socketcall_accept4X_INET) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, socketcall_accept4X_INET6) -{ +TEST(SyscallExit, socketcall_accept4X_INET6) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -755,10 +776,13 @@ TEST(SyscallExit, socketcall_accept4X_INET6) int32_t server_socket_fd = 0; sockaddr_in6 client_addr = {0}; sockaddr_in6 server_addr = {0}; - evt_test->connect_ipv6_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv6_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ - sockaddr* addr = NULL; + sockaddr *addr = NULL; socklen_t *addrlen = NULL; int flags = 0; @@ -784,8 +808,7 @@ TEST(SyscallExit, socketcall_accept4X_INET6) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -800,7 +823,12 @@ TEST(SyscallExit, socketcall_accept4X_INET6) /* Parameter 2: tuple (type: PT_SOCKTUPLE) */ /* The server performs an `accept` so the `client` is the src. */ - evt_test->assert_tuple_inet6_param(2, PPM_AF_INET6, IPV6_CLIENT, IPV6_SERVER, IPV6_PORT_CLIENT_STRING, IPV6_PORT_SERVER_STRING); + evt_test->assert_tuple_inet6_param(2, + PPM_AF_INET6, + IPV6_CLIENT, + IPV6_SERVER, + IPV6_PORT_CLIENT_STRING, + IPV6_PORT_SERVER_STRING); /* Parameter 3: queuepct (type: PT_UINT8) */ /* we expect 0 elements in the queue so 0%. */ @@ -819,8 +847,7 @@ TEST(SyscallExit, socketcall_accept4X_INET6) } #ifdef __NR_unlinkat -TEST(SyscallExit, socketcall_accept4X_UNIX) -{ +TEST(SyscallExit, socketcall_accept4X_UNIX) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -831,10 +858,13 @@ TEST(SyscallExit, socketcall_accept4X_UNIX) int32_t server_socket_fd = 0; struct sockaddr_un client_addr = {0}; struct sockaddr_un server_addr = {0}; - evt_test->connect_unix_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_unix_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* We don't want to get any info about the connected socket so `addr` and `addrlen` are NULL. */ - sockaddr* addr = NULL; + sockaddr *addr = NULL; socklen_t *addrlen = NULL; int flags = 0; @@ -862,8 +892,7 @@ TEST(SyscallExit, socketcall_accept4X_UNIX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -897,8 +926,7 @@ TEST(SyscallExit, socketcall_accept4X_UNIX) } #endif /* __NR_unlinkat */ -TEST(SyscallExit, socketcall_accept4X_failure) -{ +TEST(SyscallExit, socketcall_accept4X_failure) { auto evt_test = get_syscall_event_test(__NR_accept4, EXIT_EVENT); evt_test->enable_capture(); @@ -906,7 +934,7 @@ TEST(SyscallExit, socketcall_accept4X_failure) /*=============================== TRIGGER SYSCALL ===========================*/ int32_t mock_fd = -1; - sockaddr* addr = NULL; + sockaddr *addr = NULL; socklen_t *addrlen = NULL; int flags = 0; @@ -924,8 +952,7 @@ TEST(SyscallExit, socketcall_accept4X_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -957,8 +984,7 @@ TEST(SyscallExit, socketcall_accept4X_failure) #endif #ifdef __NR_listen -TEST(SyscallExit, socketcall_listenX) -{ +TEST(SyscallExit, socketcall_listenX) { auto evt_test = get_syscall_event_test(__NR_listen, EXIT_EVENT); evt_test->enable_capture(); @@ -980,8 +1006,7 @@ TEST(SyscallExit, socketcall_listenX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1002,10 +1027,11 @@ TEST(SyscallExit, socketcall_listenX) #ifdef __NR_recvfrom -#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) +#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && \ + defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && \ + defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) -TEST(SyscallExit, socketcall_recvfromX_no_snaplen) -{ +TEST(SyscallExit, socketcall_recvfromX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); @@ -1016,12 +1042,21 @@ TEST(SyscallExit, socketcall_recvfromX_no_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ char sent_data[NO_SNAPLEN_MESSAGE_LEN] = NO_SNAPLEN_MESSAGE; uint32_t sendto_flags = 0; - int64_t sent_bytes = syscall(__NR_sendto, client_socket_fd, sent_data, sizeof(sent_data), sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)); + int64_t sent_bytes = syscall(__NR_sendto, + client_socket_fd, + sent_data, + sizeof(sent_data), + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)); assert_syscall_state(SYSCALL_SUCCESS, "sendto (client)", sent_bytes, NOT_EQUAL, -1); /* The server accepts the connection and receives the message */ @@ -1031,8 +1066,9 @@ TEST(SyscallExit, socketcall_recvfromX_no_snaplen) char received_data[MAX_RECV_BUF_SIZE]; socklen_t received_data_len = MAX_RECV_BUF_SIZE; uint32_t recvfrom_flags = 0; - /// TODO: if we use `sockaddr_in* src_addr = NULL` kernel module and old bpf are not able to get correct data. - /// Fixing them means changing how we retrieve network data, so it would be quite a big change. + /// TODO: if we use `sockaddr_in* src_addr = NULL` kernel module and old bpf are not able to get + /// correct data. Fixing them means changing how we retrieve network data, so it would be quite + /// a big change. sockaddr_in src_addr = {0}; socklen_t addrlen = sizeof(src_addr); @@ -1061,8 +1097,7 @@ TEST(SyscallExit, socketcall_recvfromX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1079,16 +1114,21 @@ TEST(SyscallExit, socketcall_recvfromX_no_snaplen) evt_test->assert_bytebuf_param(2, NO_SNAPLEN_MESSAGE, received_bytes); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - /* The server performs a 'recvfrom` so the server is the final destination of the packet while the client is the src. */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + /* The server performs a 'recvfrom` so the server is the final destination of the packet while + * the client is the src. */ + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, socketcall_recvfromX_snaplen) -{ +TEST(SyscallExit, socketcall_recvfromX_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); @@ -1099,12 +1139,21 @@ TEST(SyscallExit, socketcall_recvfromX_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ char sent_data[FULL_MESSAGE_LEN] = FULL_MESSAGE; uint32_t sendto_flags = 0; - int64_t sent_bytes = syscall(__NR_sendto, client_socket_fd, sent_data, sizeof(sent_data), sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)); + int64_t sent_bytes = syscall(__NR_sendto, + client_socket_fd, + sent_data, + sizeof(sent_data), + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)); assert_syscall_state(SYSCALL_SUCCESS, "sendto (client)", sent_bytes, NOT_EQUAL, -1); /* The server accepts the connection and receives the message */ @@ -1142,8 +1191,7 @@ TEST(SyscallExit, socketcall_recvfromX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1160,8 +1208,14 @@ TEST(SyscallExit, socketcall_recvfromX_snaplen) evt_test->assert_bytebuf_param(2, FULL_MESSAGE, DEFAULT_SNAPLEN); /* Parameter 3: tuple (type: PT_SOCKTUPLE) */ - /* The server performs a 'recvfrom` so the server is the final destination of the packet while the client is the src. */ - evt_test->assert_tuple_inet_param(3, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); + /* The server performs a 'recvfrom` so the server is the final destination of the packet while + * the client is the src. */ + evt_test->assert_tuple_inet_param(3, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); /*=============================== ASSERT PARAMETERS ===========================*/ @@ -1169,8 +1223,7 @@ TEST(SyscallExit, socketcall_recvfromX_snaplen) } #endif -TEST(SyscallExit, socketcall_recvfromX_fail) -{ +TEST(SyscallExit, socketcall_recvfromX_fail) { auto evt_test = get_syscall_event_test(__NR_recvfrom, EXIT_EVENT); evt_test->enable_capture(); @@ -1181,7 +1234,7 @@ TEST(SyscallExit, socketcall_recvfromX_fail) char received_data[MAX_RECV_BUF_SIZE]; socklen_t received_data_len = MAX_RECV_BUF_SIZE; uint32_t flags = 0; - sockaddr* src_addr = NULL; + sockaddr *src_addr = NULL; socklen_t *addrlen = NULL; unsigned long args[6] = {0}; @@ -1201,8 +1254,7 @@ TEST(SyscallExit, socketcall_recvfromX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1232,8 +1284,7 @@ TEST(SyscallExit, socketcall_recvfromX_fail) #include -TEST(SyscallExit, socketcall_socketpairX_success) -{ +TEST(SyscallExit, socketcall_socketpairX_success) { auto evt_test = get_syscall_event_test(__NR_socketpair, EXIT_EVENT); evt_test->enable_capture(); @@ -1250,7 +1301,11 @@ TEST(SyscallExit, socketcall_socketpairX_success) args[1] = type; args[2] = protocol; args[3] = (unsigned long)fd; - assert_syscall_state(SYSCALL_SUCCESS, "socketpair", syscall(__NR_socketcall, SYS_SOCKETPAIR, args), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "socketpair", + syscall(__NR_socketcall, SYS_SOCKETPAIR, args), + NOT_EQUAL, + -1); syscall(__NR_close, fd[0]); syscall(__NR_close, fd[1]); @@ -1260,8 +1315,7 @@ TEST(SyscallExit, socketcall_socketpairX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1293,8 +1347,7 @@ TEST(SyscallExit, socketcall_socketpairX_success) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, socketcall_socketpairX_failure) -{ +TEST(SyscallExit, socketcall_socketpairX_failure) { auto evt_test = get_syscall_event_test(__NR_socketpair, EXIT_EVENT); evt_test->enable_capture(); @@ -1311,7 +1364,9 @@ TEST(SyscallExit, socketcall_socketpairX_failure) args[1] = type; args[2] = protocol; args[3] = (unsigned long)fd; - assert_syscall_state(SYSCALL_SUCCESS, "socketpair", syscall(__NR_socketcall, SYS_SOCKETPAIR, args)); + assert_syscall_state(SYSCALL_SUCCESS, + "socketpair", + syscall(__NR_socketcall, SYS_SOCKETPAIR, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -1320,8 +1375,7 @@ TEST(SyscallExit, socketcall_socketpairX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1355,13 +1409,13 @@ TEST(SyscallExit, socketcall_socketpairX_failure) #ifdef __NR_sendto -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) /* By default `snaplen` is 80 bytes. * No `snaplen` because here we don't hit the 80 bytes so we don't have to truncate the message. */ -TEST(SyscallExit, socketcall_sendtoX_no_snaplen) -{ +TEST(SyscallExit, socketcall_sendtoX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -1372,7 +1426,10 @@ TEST(SyscallExit, socketcall_sendtoX_no_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ char sent_data[NO_SNAPLEN_MESSAGE_LEN] = NO_SNAPLEN_MESSAGE; @@ -1400,8 +1457,7 @@ TEST(SyscallExit, socketcall_sendtoX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1423,8 +1479,7 @@ TEST(SyscallExit, socketcall_sendtoX_no_snaplen) } /* Here we need to truncate our message since it is greater than `snaplen` */ -TEST(SyscallExit, socketcall_sendtoX_snaplen) -{ +TEST(SyscallExit, socketcall_sendtoX_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -1435,7 +1490,10 @@ TEST(SyscallExit, socketcall_sendtoX_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ char sent_data[FULL_MESSAGE_LEN] = FULL_MESSAGE; @@ -1463,8 +1521,7 @@ TEST(SyscallExit, socketcall_sendtoX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1486,8 +1543,7 @@ TEST(SyscallExit, socketcall_sendtoX_snaplen) } #endif -TEST(SyscallExit, socketcall_sendtoX_fail) -{ +TEST(SyscallExit, socketcall_sendtoX_fail) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -1498,7 +1554,7 @@ TEST(SyscallExit, socketcall_sendtoX_fail) char sent_data[DEFAULT_SNAPLEN / 2] = "some-data"; size_t len = DEFAULT_SNAPLEN / 2; uint32_t sendto_flags = 0; - sockaddr* dest_addr = NULL; + sockaddr *dest_addr = NULL; socklen_t addrlen = 0; unsigned long args[6] = {0}; @@ -1517,8 +1573,7 @@ TEST(SyscallExit, socketcall_sendtoX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1539,8 +1594,7 @@ TEST(SyscallExit, socketcall_sendtoX_fail) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, socketcall_sendtoX_empty) -{ +TEST(SyscallExit, socketcall_sendtoX_empty) { auto evt_test = get_syscall_event_test(__NR_sendto, EXIT_EVENT); evt_test->enable_capture(); @@ -1551,7 +1605,7 @@ TEST(SyscallExit, socketcall_sendtoX_empty) char *sent_data = NULL; size_t len = 0; uint32_t sendto_flags = 0; - sockaddr* dest_addr = NULL; + sockaddr *dest_addr = NULL; socklen_t addrlen = 0; unsigned long args[6] = {0}; @@ -1570,8 +1624,7 @@ TEST(SyscallExit, socketcall_sendtoX_empty) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1596,13 +1649,13 @@ TEST(SyscallExit, socketcall_sendtoX_empty) #ifdef __NR_sendmsg -#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) +#if defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && \ + defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) /* By default `snaplen` is 80 bytes. * No `snaplen` because here we don't hit the 80 bytes so we don't have to truncate the message. */ -TEST(SyscallExit, socketcall_sendmsgX_no_snaplen) -{ +TEST(SyscallExit, socketcall_sendmsgX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -1613,14 +1666,17 @@ TEST(SyscallExit, socketcall_sendmsgX_no_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ struct msghdr send_msg; struct iovec iov[2]; memset(&send_msg, 0, sizeof(send_msg)); memset(iov, 0, sizeof(iov)); - send_msg.msg_name = (sockaddr*)&server_addr; + send_msg.msg_name = (sockaddr *)&server_addr; send_msg.msg_namelen = sizeof(server_addr); char sent_data_1[FIRST_MESSAGE_LEN] = "hey! there is a first message here."; char sent_data_2[SECOND_MESSAGE_LEN] = "hey! there is a second message here."; @@ -1651,8 +1707,7 @@ TEST(SyscallExit, socketcall_sendmsgX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1674,8 +1729,7 @@ TEST(SyscallExit, socketcall_sendmsgX_no_snaplen) } /* Here we need to truncate our message since it is greater than `snaplen` */ -TEST(SyscallExit, socketcall_sendmsgX_snaplen) -{ +TEST(SyscallExit, socketcall_sendmsgX_snaplen) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -1686,14 +1740,17 @@ TEST(SyscallExit, socketcall_sendmsgX_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ struct msghdr send_msg; struct iovec iov[3]; memset(&send_msg, 0, sizeof(send_msg)); memset(iov, 0, sizeof(iov)); - send_msg.msg_name = (sockaddr*)&server_addr; + send_msg.msg_name = (sockaddr *)&server_addr; send_msg.msg_namelen = sizeof(server_addr); char sent_data_1[FIRST_MESSAGE_LEN] = "hey! there is a first message here."; char sent_data_2[SECOND_MESSAGE_LEN] = "hey! there is a second message here."; @@ -1727,8 +1784,7 @@ TEST(SyscallExit, socketcall_sendmsgX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1750,8 +1806,7 @@ TEST(SyscallExit, socketcall_sendmsgX_snaplen) } #endif -TEST(SyscallExit, socketcall_sendmsgX_fail) -{ +TEST(SyscallExit, socketcall_sendmsgX_fail) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -1783,8 +1838,7 @@ TEST(SyscallExit, socketcall_sendmsgX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1805,8 +1859,7 @@ TEST(SyscallExit, socketcall_sendmsgX_fail) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, socketcall_sendmsgX_null_iovec) -{ +TEST(SyscallExit, socketcall_sendmsgX_null_iovec) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -1832,21 +1885,19 @@ TEST(SyscallExit, socketcall_sendmsgX_null_iovec) evt_test->disable_capture(); - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { evt_test->assert_event_presence(); - } - else - { + } else { /* we need to rewrite the logic in old drivers to support this partial collection * right now we drop the entire event. */ evt_test->assert_event_absence(); - GTEST_SKIP() << "[SENDMSG_X]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[SENDMSG_X]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1867,8 +1918,7 @@ TEST(SyscallExit, socketcall_sendmsgX_null_iovec) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, socketcall_sendmsgX_null_msghdr) -{ +TEST(SyscallExit, socketcall_sendmsgX_null_msghdr) { auto evt_test = get_syscall_event_test(__NR_sendmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -1892,8 +1942,7 @@ TEST(SyscallExit, socketcall_sendmsgX_null_msghdr) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -1918,10 +1967,11 @@ TEST(SyscallExit, socketcall_sendmsgX_null_msghdr) #ifdef __NR_recvmsg -#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) +#if defined(__NR_accept4) && defined(__NR_connect) && defined(__NR_socket) && \ + defined(__NR_bind) && defined(__NR_listen) && defined(__NR_close) && \ + defined(__NR_setsockopt) && defined(__NR_shutdown) && defined(__NR_sendto) -TEST(SyscallExit, socketcall_recvmsgX_no_snaplen) -{ +TEST(SyscallExit, socketcall_recvmsgX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -1932,12 +1982,21 @@ TEST(SyscallExit, socketcall_recvmsgX_no_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ char sent_data[NO_SNAPLEN_MESSAGE_LEN] = NO_SNAPLEN_MESSAGE; uint32_t sendto_flags = 0; - int64_t sent_bytes = syscall(__NR_sendto, client_socket_fd, sent_data, sizeof(sent_data), sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)); + int64_t sent_bytes = syscall(__NR_sendto, + client_socket_fd, + sent_data, + sizeof(sent_data), + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)); assert_syscall_state(SYSCALL_SUCCESS, "sendto (client)", sent_bytes, NOT_EQUAL, -1); /* The server accepts the connection and receives the message */ @@ -1948,7 +2007,7 @@ TEST(SyscallExit, socketcall_recvmsgX_no_snaplen) struct iovec iov[2]; memset(&recv_msg, 0, sizeof(recv_msg)); memset(iov, 0, sizeof(iov)); - recv_msg.msg_name = (sockaddr*)&client_addr; + recv_msg.msg_name = (sockaddr *)&client_addr; recv_msg.msg_namelen = sizeof(client_addr); char data_1[MAX_RECV_BUF_SIZE]; char data_2[MAX_RECV_BUF_SIZE]; @@ -1981,8 +2040,7 @@ TEST(SyscallExit, socketcall_recvmsgX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2003,19 +2061,24 @@ TEST(SyscallExit, socketcall_recvmsgX_no_snaplen) /* Parameter 4: tuple (type: PT_SOCKTUPLE) */ - if(evt_test->is_modern_bpf_engine()) - { - /* The server performs a 'recvmsg` so the server is the final destination of the packet while the client is the src. */ - evt_test->assert_tuple_inet_param(4, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); - } - else - { + if(evt_test->is_modern_bpf_engine()) { + /* The server performs a 'recvmsg` so the server is the final destination of the packet + * while the client is the src. */ + evt_test->assert_tuple_inet_param(4, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); + } else { /// TODO: same as `recvfrom` the kernel code tries to get information from userspace structs - /// but these could be empty so this is not the correct way to retrieve information we have to - /// change it. + /// but these could be empty so this is not the correct way to retrieve information we have + /// to change it. evt_test->assert_empty_param(4); evt_test->assert_num_params_pushed(5); - GTEST_SKIP() << "[RECVMSG_X]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[RECVMSG_X]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } /* Parameter 5: msg_control (type: PT_BYTEBUF) */ @@ -2026,8 +2089,7 @@ TEST(SyscallExit, socketcall_recvmsgX_no_snaplen) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, socketcall_recvmsgX_snaplen) -{ +TEST(SyscallExit, socketcall_recvmsgX_snaplen) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -2038,12 +2100,21 @@ TEST(SyscallExit, socketcall_recvmsgX_snaplen) int32_t server_socket_fd = 0; sockaddr_in client_addr = {0}; sockaddr_in server_addr = {0}; - evt_test->connect_ipv4_client_to_server(&client_socket_fd, &client_addr, &server_socket_fd, &server_addr); + evt_test->connect_ipv4_client_to_server(&client_socket_fd, + &client_addr, + &server_socket_fd, + &server_addr); /* Send a message to the server */ char sent_data[FULL_MESSAGE_LEN] = FULL_MESSAGE; uint32_t sendto_flags = 0; - int64_t sent_bytes = syscall(__NR_sendto, client_socket_fd, sent_data, sizeof(sent_data), sendto_flags, (sockaddr*)&server_addr, sizeof(server_addr)); + int64_t sent_bytes = syscall(__NR_sendto, + client_socket_fd, + sent_data, + sizeof(sent_data), + sendto_flags, + (sockaddr *)&server_addr, + sizeof(server_addr)); assert_syscall_state(SYSCALL_SUCCESS, "sendto (client)", sent_bytes, NOT_EQUAL, -1); /* The server accepts the connection and receives the message */ @@ -2054,7 +2125,7 @@ TEST(SyscallExit, socketcall_recvmsgX_snaplen) struct iovec iov[2]; memset(&recv_msg, 0, sizeof(recv_msg)); memset(iov, 0, sizeof(iov)); - recv_msg.msg_name = (sockaddr*)&client_addr; + recv_msg.msg_name = (sockaddr *)&client_addr; recv_msg.msg_namelen = sizeof(client_addr); char data_1[MAX_RECV_BUF_SIZE]; char data_2[MAX_RECV_BUF_SIZE]; @@ -2087,8 +2158,7 @@ TEST(SyscallExit, socketcall_recvmsgX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2107,20 +2177,25 @@ TEST(SyscallExit, socketcall_recvmsgX_snaplen) /* Parameter 3: data (type: PT_BYTEBUF) */ evt_test->assert_bytebuf_param(3, FULL_MESSAGE, DEFAULT_SNAPLEN); - if(evt_test->is_modern_bpf_engine()) - { + if(evt_test->is_modern_bpf_engine()) { /* Parameter 4: tuple (type: PT_SOCKTUPLE) */ - /* The server performs a 'recvmsg` so the server is the final destination of the packet while the client is the src. */ - evt_test->assert_tuple_inet_param(4, PPM_AF_INET, IPV4_CLIENT, IPV4_SERVER, IPV4_PORT_CLIENT_STRING, IPV4_PORT_SERVER_STRING); - } - else - { + /* The server performs a 'recvmsg` so the server is the final destination of the packet + * while the client is the src. */ + evt_test->assert_tuple_inet_param(4, + PPM_AF_INET, + IPV4_CLIENT, + IPV4_SERVER, + IPV4_PORT_CLIENT_STRING, + IPV4_PORT_SERVER_STRING); + } else { /// TODO: same as `recvfrom` the kernel code tries to get information from userspace structs - /// but these could be empty so this is not the correct way to retrieve information we have to - /// change it. + /// but these could be empty so this is not the correct way to retrieve information we have + /// to change it. evt_test->assert_empty_param(4); evt_test->assert_num_params_pushed(5); - GTEST_SKIP() << "[RECVMSG_X]: what we receive is correct but we need to reimplement it, see the code" << std::endl; + GTEST_SKIP() << "[RECVMSG_X]: what we receive is correct but we need to reimplement it, " + "see the code" + << std::endl; } /* Parameter 5: msg_control (type: PT_BYTEBUF) */ @@ -2132,8 +2207,7 @@ TEST(SyscallExit, socketcall_recvmsgX_snaplen) } #endif -TEST(SyscallExit, socketcall_recvmsgX_fail) -{ +TEST(SyscallExit, socketcall_recvmsgX_fail) { auto evt_test = get_syscall_event_test(__NR_recvmsg, EXIT_EVENT); evt_test->enable_capture(); @@ -2157,8 +2231,7 @@ TEST(SyscallExit, socketcall_recvmsgX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2196,8 +2269,7 @@ TEST(SyscallExit, socketcall_recvmsgX_fail) #include #if defined(__NR_socket) && defined(__NR_setsockopt) && defined(__NR_close) -TEST(SyscallExit, socketcall_getsockoptX_success) -{ +TEST(SyscallExit, socketcall_getsockoptX_success) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2217,7 +2289,11 @@ TEST(SyscallExit, socketcall_getsockoptX_success) args[2] = SO_REUSEADDR; args[3] = (unsigned long)&setsockopt_option_value; args[4] = setsockopt_option_len; - assert_syscall_state(SYSCALL_SUCCESS, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args), + NOT_EQUAL, + -1); /* Check if we are able to get the right option just set */ int32_t level = SOL_SOCKET; @@ -2231,7 +2307,11 @@ TEST(SyscallExit, socketcall_getsockoptX_success) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_SUCCESS, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args), + NOT_EQUAL, + -1); /* Cleaning phase */ syscall(__NR_close, socketfd); @@ -2242,8 +2322,7 @@ TEST(SyscallExit, socketcall_getsockoptX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2266,7 +2345,10 @@ TEST(SyscallExit, socketcall_getsockoptX_success) evt_test->assert_numeric_param(4, (uint8_t)PPM_SOCKOPT_SO_REUSEADDR); /* Parameter 5: optval (type: PT_DYN) */ - evt_test->assert_setsockopt_val(5, PPM_SOCKOPT_IDX_UINT32, &setsockopt_option_value, setsockopt_option_len); + evt_test->assert_setsockopt_val(5, + PPM_SOCKOPT_IDX_UINT32, + &setsockopt_option_value, + setsockopt_option_len); /* Parameter 6: optlen (type: PT_UINT32) */ evt_test->assert_numeric_param(6, (uint32_t)setsockopt_option_len); @@ -2277,8 +2359,7 @@ TEST(SyscallExit, socketcall_getsockoptX_success) } #endif -TEST(SyscallExit, socketcall_getsockoptX_SO_RCVTIMEO) -{ +TEST(SyscallExit, socketcall_getsockoptX_SO_RCVTIMEO) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2299,7 +2380,9 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_RCVTIMEO) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2308,8 +2391,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_RCVTIMEO) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2343,8 +2425,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_RCVTIMEO) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_getsockoptX_SO_COOKIE) -{ +TEST(SyscallExit, socketcall_getsockoptX_SO_COOKIE) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2363,7 +2444,9 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_COOKIE) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2372,8 +2455,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_COOKIE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2406,8 +2488,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_COOKIE) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_getsockoptX_SO_PASSCRED) -{ +TEST(SyscallExit, socketcall_getsockoptX_SO_PASSCRED) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2426,7 +2507,9 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_PASSCRED) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2435,8 +2518,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_PASSCRED) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2469,8 +2551,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SO_PASSCRED) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_getsockoptX_UNKNOWN_OPTION) -{ +TEST(SyscallExit, socketcall_getsockoptX_UNKNOWN_OPTION) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2489,7 +2570,9 @@ TEST(SyscallExit, socketcall_getsockoptX_UNKNOWN_OPTION) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2498,8 +2581,7 @@ TEST(SyscallExit, socketcall_getsockoptX_UNKNOWN_OPTION) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2532,8 +2614,7 @@ TEST(SyscallExit, socketcall_getsockoptX_UNKNOWN_OPTION) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_getsockoptX_SOL_UNKNOWN) -{ +TEST(SyscallExit, socketcall_getsockoptX_SOL_UNKNOWN) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2552,7 +2633,9 @@ TEST(SyscallExit, socketcall_getsockoptX_SOL_UNKNOWN) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2561,8 +2644,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SOL_UNKNOWN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2595,8 +2677,7 @@ TEST(SyscallExit, socketcall_getsockoptX_SOL_UNKNOWN) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_getsockoptX_ZERO_OPTLEN) -{ +TEST(SyscallExit, socketcall_getsockoptX_ZERO_OPTLEN) { auto evt_test = get_syscall_event_test(__NR_getsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2615,7 +2696,9 @@ TEST(SyscallExit, socketcall_getsockoptX_ZERO_OPTLEN) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = (unsigned long)&option_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockopt", syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockopt", + syscall(__NR_socketcall, SYS_GETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2624,8 +2707,7 @@ TEST(SyscallExit, socketcall_getsockoptX_ZERO_OPTLEN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2665,8 +2747,7 @@ TEST(SyscallExit, socketcall_getsockoptX_ZERO_OPTLEN) #include #include -TEST(SyscallExit, socketcall_setsockoptX_SO_ERROR) -{ +TEST(SyscallExit, socketcall_setsockoptX_SO_ERROR) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2685,7 +2766,9 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_ERROR) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2694,8 +2777,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_ERROR) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2730,8 +2812,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_ERROR) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_setsockoptX_SO_RCVTIMEO) -{ +TEST(SyscallExit, socketcall_setsockoptX_SO_RCVTIMEO) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2752,7 +2833,9 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_RCVTIMEO) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2761,8 +2844,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_RCVTIMEO) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2796,8 +2878,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_RCVTIMEO) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_setsockoptX_SO_COOKIE) -{ +TEST(SyscallExit, socketcall_setsockoptX_SO_COOKIE) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2816,7 +2897,9 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_COOKIE) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2825,8 +2908,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_COOKIE) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2859,8 +2941,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_COOKIE) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_setsockoptX_SO_PASSCRED) -{ +TEST(SyscallExit, socketcall_setsockoptX_SO_PASSCRED) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2879,7 +2960,9 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_PASSCRED) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2888,8 +2971,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_PASSCRED) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2922,8 +3004,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SO_PASSCRED) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_setsockoptX_UNKNOWN_OPTION) -{ +TEST(SyscallExit, socketcall_setsockoptX_UNKNOWN_OPTION) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -2942,7 +3023,9 @@ TEST(SyscallExit, socketcall_setsockoptX_UNKNOWN_OPTION) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -2951,8 +3034,7 @@ TEST(SyscallExit, socketcall_setsockoptX_UNKNOWN_OPTION) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -2985,8 +3067,7 @@ TEST(SyscallExit, socketcall_setsockoptX_UNKNOWN_OPTION) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_setsockoptX_SOL_UNKNOWN) -{ +TEST(SyscallExit, socketcall_setsockoptX_SOL_UNKNOWN) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -3005,7 +3086,9 @@ TEST(SyscallExit, socketcall_setsockoptX_SOL_UNKNOWN) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -3014,8 +3097,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SOL_UNKNOWN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -3048,8 +3130,7 @@ TEST(SyscallExit, socketcall_setsockoptX_SOL_UNKNOWN) evt_test->assert_num_params_pushed(6); } -TEST(SyscallExit, socketcall_setsockoptX_ZERO_OPTLEN) -{ +TEST(SyscallExit, socketcall_setsockoptX_ZERO_OPTLEN) { auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); evt_test->enable_capture(); @@ -3068,7 +3149,9 @@ TEST(SyscallExit, socketcall_setsockoptX_ZERO_OPTLEN) args[2] = option_name; args[3] = (unsigned long)&option_value; args[4] = option_len; - assert_syscall_state(SYSCALL_FAILURE, "setsockopt", syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); + assert_syscall_state(SYSCALL_FAILURE, + "setsockopt", + syscall(__NR_socketcall, SYS_SETSOCKOPT, args)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -3077,8 +3160,7 @@ TEST(SyscallExit, socketcall_setsockoptX_ZERO_OPTLEN) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -3115,8 +3197,7 @@ TEST(SyscallExit, socketcall_setsockoptX_ZERO_OPTLEN) #ifdef __NR_send -TEST(SyscallExit, socketcall_sendX) -{ +TEST(SyscallExit, socketcall_sendX) { auto evt_test = get_syscall_event_test(__NR_send, EXIT_EVENT); evt_test->enable_capture(); @@ -3141,8 +3222,7 @@ TEST(SyscallExit, socketcall_sendX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -3165,8 +3245,7 @@ TEST(SyscallExit, socketcall_sendX) #endif #ifdef __NR_recv -TEST(SyscallExit, socketcall_recvX_fail) -{ +TEST(SyscallExit, socketcall_recvX_fail) { auto evt_test = get_syscall_event_test(__NR_recv, EXIT_EVENT); evt_test->enable_capture(); @@ -3192,8 +3271,7 @@ TEST(SyscallExit, socketcall_recvX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -3216,8 +3294,7 @@ TEST(SyscallExit, socketcall_recvX_fail) #endif #ifdef __NR_getpeername -TEST(SyscallExit, socketcall_getpeernameX) -{ +TEST(SyscallExit, socketcall_getpeernameX) { auto evt_test = get_syscall_event_test(__NR_getpeername, EXIT_EVENT); evt_test->enable_capture(); @@ -3232,7 +3309,9 @@ TEST(SyscallExit, socketcall_getpeernameX) args[0] = mock_fd; args[1] = (unsigned long)usockaddr; args[2] = (unsigned long)usockaddr_len; - assert_syscall_state(SYSCALL_FAILURE, "getpeername", syscall(__NR_socketcall, SYS_GETPEERNAME, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getpeername", + syscall(__NR_socketcall, SYS_GETPEERNAME, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -3240,8 +3319,7 @@ TEST(SyscallExit, socketcall_getpeernameX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -3260,8 +3338,7 @@ TEST(SyscallExit, socketcall_getpeernameX) #endif #ifdef __NR_getsockname -TEST(SyscallExit, socketcall_getsocknameX) -{ +TEST(SyscallExit, socketcall_getsocknameX) { auto evt_test = get_syscall_event_test(__NR_getsockname, EXIT_EVENT); evt_test->enable_capture(); @@ -3276,7 +3353,9 @@ TEST(SyscallExit, socketcall_getsocknameX) args[0] = mock_fd; args[1] = (unsigned long)usockaddr; args[2] = (unsigned long)usockaddr_len; - assert_syscall_state(SYSCALL_FAILURE, "getsockname", syscall(__NR_socketcall, SYS_GETSOCKNAME, args)); + assert_syscall_state(SYSCALL_FAILURE, + "getsockname", + syscall(__NR_socketcall, SYS_GETSOCKNAME, args)); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -3284,8 +3363,7 @@ TEST(SyscallExit, socketcall_getsocknameX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -3303,8 +3381,7 @@ TEST(SyscallExit, socketcall_getsocknameX) } #endif -TEST(SyscallExit, socketcall_wrong_code_socketcall_interesting) -{ +TEST(SyscallExit, socketcall_wrong_code_socketcall_interesting) { // Even if the socketcall is marked as interesting we drop the event auto evt_test = get_syscall_event_test(__NR_socketcall, EXIT_EVENT); @@ -3327,8 +3404,7 @@ TEST(SyscallExit, socketcall_wrong_code_socketcall_interesting) evt_test->assert_event_absence(CURRENT_PID, PPME_GENERIC_X); } -TEST(SyscallExit, socketcall_wrong_code_socketcall_not_interesting) -{ +TEST(SyscallExit, socketcall_wrong_code_socketcall_not_interesting) { // Same as the previous test auto evt_test = get_syscall_event_test(__NR_setsockopt, EXIT_EVENT); @@ -3351,24 +3427,25 @@ TEST(SyscallExit, socketcall_wrong_code_socketcall_not_interesting) evt_test->assert_event_absence(CURRENT_PID, PPME_GENERIC_X); } -TEST(SyscallExit, socketcall_null_pointer) -{ +TEST(SyscallExit, socketcall_null_pointer) { auto evt_test = get_syscall_event_test(__NR_shutdown, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - assert_syscall_state(SYSCALL_FAILURE, "socketcall", syscall(__NR_socketcall, SYS_SHUTDOWN, NULL)); + assert_syscall_state(SYSCALL_FAILURE, + "socketcall", + syscall(__NR_socketcall, SYS_SHUTDOWN, NULL)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ evt_test->disable_capture(); - if(evt_test->is_kmod_engine()) - { - /* with a null pointer we are not able to correctly obtain the event so right now we drop it. */ + if(evt_test->is_kmod_engine()) { + /* with a null pointer we are not able to correctly obtain the event so right now we drop + * it. */ evt_test->assert_event_absence(); SUCCEED(); return; @@ -3377,8 +3454,7 @@ TEST(SyscallExit, socketcall_null_pointer) /* in bpf and modern bpf we can obtain an event even with a null pointer. */ evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -3399,8 +3475,7 @@ TEST(SyscallExit, socketcall_null_pointer) evt_test->assert_num_params_pushed(1); } -TEST(SyscallExit, socketcall_null_pointer_and_wrong_code_socketcall_interesting) -{ +TEST(SyscallExit, socketcall_null_pointer_and_wrong_code_socketcall_interesting) { // We send a wrong code so the event will be dropped auto evt_test = get_syscall_event_test(__NR_socketcall, EXIT_EVENT); diff --git a/test/drivers/test_suites/syscall_exit_suite/socketpair_x.cpp b/test/drivers/test_suites/syscall_exit_suite/socketpair_x.cpp index 4422957878..9d0479775f 100644 --- a/test/drivers/test_suites/syscall_exit_suite/socketpair_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/socketpair_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, socketpairX_success) -{ +TEST(SyscallExit, socketpairX_success) { auto evt_test = get_syscall_event_test(__NR_socketpair, EXIT_EVENT); evt_test->enable_capture(); @@ -16,7 +15,11 @@ TEST(SyscallExit, socketpairX_success) int type = SOCK_STREAM; int protocol = 0; int32_t fd[2]; - assert_syscall_state(SYSCALL_SUCCESS, "socketpair", syscall(__NR_socketpair, domain, type, protocol, fd), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "socketpair", + syscall(__NR_socketpair, domain, type, protocol, fd), + NOT_EQUAL, + -1); syscall(__NR_close, fd[0]); syscall(__NR_close, fd[1]); @@ -26,8 +29,7 @@ TEST(SyscallExit, socketpairX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -59,8 +61,7 @@ TEST(SyscallExit, socketpairX_success) evt_test->assert_num_params_pushed(5); } -TEST(SyscallExit, socketpairX_failure) -{ +TEST(SyscallExit, socketpairX_failure) { auto evt_test = get_syscall_event_test(__NR_socketpair, EXIT_EVENT); evt_test->enable_capture(); @@ -71,7 +72,9 @@ TEST(SyscallExit, socketpairX_failure) int type = SOCK_STREAM; int protocol = 0; int32_t* fd = NULL; - assert_syscall_state(SYSCALL_FAILURE, "socketpair", syscall(__NR_socketpair, domain, type, protocol, fd)); + assert_syscall_state(SYSCALL_FAILURE, + "socketpair", + syscall(__NR_socketpair, domain, type, protocol, fd)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -80,8 +83,7 @@ TEST(SyscallExit, socketpairX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/splice_x.cpp b/test/drivers/test_suites/syscall_exit_suite/splice_x.cpp index 47cc5afab0..c90e766d59 100644 --- a/test/drivers/test_suites/syscall_exit_suite/splice_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/splice_x.cpp @@ -2,8 +2,7 @@ #ifdef __NR_splice -TEST(SyscallExit, spliceX) -{ +TEST(SyscallExit, spliceX) { auto evt_test = get_syscall_event_test(__NR_splice, EXIT_EVENT); evt_test->enable_capture(); @@ -14,7 +13,9 @@ TEST(SyscallExit, spliceX) int fd_out = 1; uint64_t size = 0x123; unsigned int flags = SPLICE_F_MOVE; - assert_syscall_state(SYSCALL_FAILURE, "splice", syscall(__NR_splice, fd_in, 0, fd_out, 0, size, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "splice", + syscall(__NR_splice, fd_in, 0, fd_out, 0, size, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -23,8 +24,7 @@ TEST(SyscallExit, spliceX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -41,4 +41,4 @@ TEST(SyscallExit, spliceX) evt_test->assert_num_params_pushed(1); } -#endif \ No newline at end of file +#endif diff --git a/test/drivers/test_suites/syscall_exit_suite/stat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/stat_x.cpp index 95f1e54455..48f74b52d2 100644 --- a/test/drivers/test_suites/syscall_exit_suite/stat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/stat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_stat -TEST(SyscallExit, statX) -{ +TEST(SyscallExit, statX) { auto evt_test = get_syscall_event_test(__NR_stat, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, statX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/symlink_x.cpp b/test/drivers/test_suites/syscall_exit_suite/symlink_x.cpp index ba0c4315cb..e68ab96589 100644 --- a/test/drivers/test_suites/syscall_exit_suite/symlink_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/symlink_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_symlink -TEST(SyscallExit, symlinkX) -{ +TEST(SyscallExit, symlinkX) { auto evt_test = get_syscall_event_test(__NR_symlink, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, symlinkX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/symlinkat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/symlinkat_x.cpp index 1714be661e..f6c4075d55 100644 --- a/test/drivers/test_suites/syscall_exit_suite/symlinkat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/symlinkat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_symlinkat -TEST(SyscallExit, symlinkatX) -{ +TEST(SyscallExit, symlinkatX) { auto evt_test = get_syscall_event_test(__NR_symlinkat, EXIT_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallExit, symlinkatX) const char* target = "//**null-target**//"; int32_t mock_dirfd = AT_FDCWD; const char* path = "//**null-path**//"; - assert_syscall_state(SYSCALL_FAILURE, "symlinkat", syscall(__NR_symlinkat, target, mock_dirfd, path)); + assert_syscall_state(SYSCALL_FAILURE, + "symlinkat", + syscall(__NR_symlinkat, target, mock_dirfd, path)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallExit, symlinkatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/tgkill_x.cpp b/test/drivers/test_suites/syscall_exit_suite/tgkill_x.cpp index e146fd95e0..43527e5b9e 100644 --- a/test/drivers/test_suites/syscall_exit_suite/tgkill_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/tgkill_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_tgkill -TEST(SyscallExit, tgkillX) -{ +TEST(SyscallExit, tgkillX) { auto evt_test = get_syscall_event_test(__NR_tgkill, EXIT_EVENT); evt_test->enable_capture(); @@ -15,7 +14,9 @@ TEST(SyscallExit, tgkillX) int32_t mock_tgid = 0; int32_t mock_tid = 0; int32_t signal = 0; - assert_syscall_state(SYSCALL_FAILURE, "tgkill", syscall(__NR_tgkill, mock_tgid, mock_tid, signal)); + assert_syscall_state(SYSCALL_FAILURE, + "tgkill", + syscall(__NR_tgkill, mock_tgid, mock_tid, signal)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -24,8 +25,7 @@ TEST(SyscallExit, tgkillX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/time_x.cpp b/test/drivers/test_suites/syscall_exit_suite/time_x.cpp index d9e6ad596e..66da8a2e4d 100644 --- a/test/drivers/test_suites/syscall_exit_suite/time_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/time_x.cpp @@ -2,8 +2,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_time -TEST(SyscallExit, time_X) -{ +TEST(SyscallExit, time_X) { auto evt_test = get_syscall_event_test(__NR_time, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, time_X) /* Retrieve events in order. */ evt_test->assert_event_presence(CURRENT_PID, PPME_GENERIC_X); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/timerfd_create_x.cpp b/test/drivers/test_suites/syscall_exit_suite/timerfd_create_x.cpp index 9edf66e522..3d6617bdd3 100644 --- a/test/drivers/test_suites/syscall_exit_suite/timerfd_create_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/timerfd_create_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_timerfd_create -TEST(SyscallExit, timerfd_createX) -{ +TEST(SyscallExit, timerfd_createX) { auto evt_test = get_syscall_event_test(__NR_timerfd_create, EXIT_EVENT); evt_test->enable_capture(); @@ -12,8 +11,10 @@ TEST(SyscallExit, timerfd_createX) /* `clockid` and `flags` are not caught BPF side, we always send `0` */ int clockid = -1; int flags = -1; - assert_syscall_state(SYSCALL_FAILURE,"timerfd_create", syscall(__NR_timerfd_create, clockid, flags)); - int64_t errno_value = -errno; + assert_syscall_state(SYSCALL_FAILURE, + "timerfd_create", + syscall(__NR_timerfd_create, clockid, flags)); + int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallExit, timerfd_createX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/tkill_x.cpp b/test/drivers/test_suites/syscall_exit_suite/tkill_x.cpp index a785db3399..a0c7eaf930 100644 --- a/test/drivers/test_suites/syscall_exit_suite/tkill_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/tkill_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_tkill -TEST(SyscallExit, tkillX) -{ +TEST(SyscallExit, tkillX) { auto evt_test = get_syscall_event_test(__NR_tkill, EXIT_EVENT); evt_test->enable_capture(); @@ -13,7 +12,7 @@ TEST(SyscallExit, tkillX) int32_t mock_tid = 0; int32_t signal = 0; assert_syscall_state(SYSCALL_FAILURE, "tkill", syscall(__NR_tkill, mock_tid, signal)); - int64_t errno_value = -errno; + int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +20,7 @@ TEST(SyscallExit, tkillX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/ugetrlimit_x.cpp b/test/drivers/test_suites/syscall_exit_suite/ugetrlimit_x.cpp index 90b8ac8eac..69aaf70a85 100644 --- a/test/drivers/test_suites/syscall_exit_suite/ugetrlimit_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/ugetrlimit_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, ugetrlimitX_success) -{ +TEST(SyscallExit, ugetrlimitX_success) { /* Please note: * the syscall `ugetrlimit` is mapped to `PPME_SYSCALL_GETRLIMIT_E` event * like `getrlimit`. The same BPF program will be used for both the syscalls. @@ -19,7 +18,11 @@ TEST(SyscallExit, ugetrlimitX_success) int resource = RLIMIT_NPROC; struct rlimit rlim = {0}; - assert_syscall_state(SYSCALL_SUCCESS, "ugetrlimit", syscall(__NR_ugetrlimit, resource, &rlim), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "ugetrlimit", + syscall(__NR_ugetrlimit, resource, &rlim), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -27,8 +30,7 @@ TEST(SyscallExit, ugetrlimitX_success) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -52,8 +54,7 @@ TEST(SyscallExit, ugetrlimitX_success) evt_test->assert_num_params_pushed(3); } -TEST(SyscallExit, ugetrlimitX_failure) -{ +TEST(SyscallExit, ugetrlimitX_failure) { /* Please note: * the syscall `ugetrlimit` is mapped to `PPME_SYSCALL_GETRLIMIT_E` event * like `getrlimit`. The same BPF program will be used for both the syscalls. @@ -76,8 +77,7 @@ TEST(SyscallExit, ugetrlimitX_failure) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/umount2_x.cpp b/test/drivers/test_suites/syscall_exit_suite/umount2_x.cpp index eeac8af2a5..9fef7d3e1b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/umount2_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/umount2_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, umount2X) -{ +TEST(SyscallExit, umount2X) { auto evt_test = get_syscall_event_test(__NR_umount2, EXIT_EVENT); evt_test->enable_capture(); @@ -23,8 +22,7 @@ TEST(SyscallExit, umount2X) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/umount_x.cpp b/test/drivers/test_suites/syscall_exit_suite/umount_x.cpp index 02b232602b..1f9827f794 100644 --- a/test/drivers/test_suites/syscall_exit_suite/umount_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/umount_x.cpp @@ -2,8 +2,7 @@ #ifdef __NR_umount -TEST(SyscallExit, umountX) -{ +TEST(SyscallExit, umountX) { auto evt_test = get_syscall_event_test(__NR_umount, EXIT_EVENT); evt_test->enable_capture(); @@ -20,8 +19,7 @@ TEST(SyscallExit, umountX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/unlink_x.cpp b/test/drivers/test_suites/syscall_exit_suite/unlink_x.cpp index 8e7f13077a..488e32df54 100644 --- a/test/drivers/test_suites/syscall_exit_suite/unlink_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/unlink_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_unlink -TEST(SyscallExit, unlinkX) -{ +TEST(SyscallExit, unlinkX) { auto evt_test = get_syscall_event_test(__NR_unlink, EXIT_EVENT); evt_test->enable_capture(); @@ -19,8 +18,7 @@ TEST(SyscallExit, unlinkX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/unlinkat_x.cpp b/test/drivers/test_suites/syscall_exit_suite/unlinkat_x.cpp index fe8579ffcc..6497ab0396 100644 --- a/test/drivers/test_suites/syscall_exit_suite/unlinkat_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/unlinkat_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_unlinkat -TEST(SyscallExit, unlinkatX) -{ +TEST(SyscallExit, unlinkatX) { auto evt_test = get_syscall_event_test(__NR_unlinkat, EXIT_EVENT); evt_test->enable_capture(); @@ -12,7 +11,9 @@ TEST(SyscallExit, unlinkatX) int32_t mock_dirfd = -1; const char* path = "//**null**//"; uint32_t flags = AT_REMOVEDIR; - assert_syscall_state(SYSCALL_FAILURE, "unlinkat", syscall(__NR_unlinkat, mock_dirfd, path, flags)); + assert_syscall_state(SYSCALL_FAILURE, + "unlinkat", + syscall(__NR_unlinkat, mock_dirfd, path, flags)); int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -21,8 +22,7 @@ TEST(SyscallExit, unlinkatX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/unshare_x.cpp b/test/drivers/test_suites/syscall_exit_suite/unshare_x.cpp index 6101728087..34a2f63222 100644 --- a/test/drivers/test_suites/syscall_exit_suite/unshare_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/unshare_x.cpp @@ -4,8 +4,7 @@ #include -TEST(SyscallExit, unshareX) -{ +TEST(SyscallExit, unshareX) { auto evt_test = get_syscall_event_test(__NR_unshare, EXIT_EVENT); evt_test->enable_capture(); @@ -26,8 +25,7 @@ TEST(SyscallExit, unshareX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/userfaultfd_x.cpp b/test/drivers/test_suites/syscall_exit_suite/userfaultfd_x.cpp index 7aa06cd008..ed0fdcc584 100644 --- a/test/drivers/test_suites/syscall_exit_suite/userfaultfd_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/userfaultfd_x.cpp @@ -1,8 +1,7 @@ #include "../../event_class/event_class.h" #ifdef __NR_userfaultfd -TEST(SyscallExit, userfaultfdX) -{ +TEST(SyscallExit, userfaultfdX) { auto evt_test = get_syscall_event_test(__NR_userfaultfd, EXIT_EVENT); evt_test->enable_capture(); @@ -12,7 +11,7 @@ TEST(SyscallExit, userfaultfdX) /* `flags = 3` is an invalid flag value so the syscall will return `EINVAL` as errno. */ int flags = 3; assert_syscall_state(SYSCALL_FAILURE, "userfaultfd", syscall(__NR_userfaultfd, flags)); - int64_t errno_value = -errno; + int64_t errno_value = -errno; /*=============================== TRIGGER SYSCALL ===========================*/ @@ -20,8 +19,7 @@ TEST(SyscallExit, userfaultfdX) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/drivers/test_suites/syscall_exit_suite/write_x.cpp b/test/drivers/test_suites/syscall_exit_suite/write_x.cpp index b29e873e10..077d666e84 100644 --- a/test/drivers/test_suites/syscall_exit_suite/write_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/write_x.cpp @@ -5,8 +5,7 @@ #if defined(__NR_close) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallExit, writeX_no_snaplen) -{ +TEST(SyscallExit, writeX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->enable_capture(); @@ -29,8 +28,7 @@ TEST(SyscallExit, writeX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -51,8 +49,7 @@ TEST(SyscallExit, writeX_no_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, writeX_snaplen) -{ +TEST(SyscallExit, writeX_snaplen) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->enable_capture(); @@ -75,8 +72,7 @@ TEST(SyscallExit, writeX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -97,8 +93,7 @@ TEST(SyscallExit, writeX_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, writeX_fail) -{ +TEST(SyscallExit, writeX_fail) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->enable_capture(); @@ -117,8 +112,7 @@ TEST(SyscallExit, writeX_fail) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -139,8 +133,7 @@ TEST(SyscallExit, writeX_fail) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, writeX_empty) -{ +TEST(SyscallExit, writeX_empty) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->enable_capture(); @@ -158,8 +151,7 @@ TEST(SyscallExit, writeX_empty) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -180,15 +172,15 @@ TEST(SyscallExit, writeX_empty) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, writeX_ipv4_tcp_message_truncated_by_snaplen) -{ +TEST(SyscallExit, writeX_ipv4_tcp_message_truncated_by_snaplen) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->enable_capture(); /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_write, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_write, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -196,8 +188,7 @@ TEST(SyscallExit, writeX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -218,8 +209,7 @@ TEST(SyscallExit, writeX_ipv4_tcp_message_truncated_by_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, writeX_ipv4_tcp_message_not_truncated_fullcapture_port) -{ +TEST(SyscallExit, writeX_ipv4_tcp_message_not_truncated_fullcapture_port) { auto evt_test = get_syscall_event_test(__NR_write, EXIT_EVENT); evt_test->set_do_dynamic_snaplen(true); @@ -230,7 +220,8 @@ TEST(SyscallExit, writeX_ipv4_tcp_message_not_truncated_fullcapture_port) /*=============================== TRIGGER SYSCALL ===========================*/ - evt_test->client_to_server_ipv4_tcp(send_data{.syscall_num = __NR_write, .greater_snaplen = true}); + evt_test->client_to_server_ipv4_tcp( + send_data{.syscall_num = __NR_write, .greater_snaplen = true}); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -245,8 +236,7 @@ TEST(SyscallExit, writeX_ipv4_tcp_message_not_truncated_fullcapture_port) */ evt_test->set_fullcapture_port_range(0, 0); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -267,8 +257,9 @@ TEST(SyscallExit, writeX_ipv4_tcp_message_not_truncated_fullcapture_port) evt_test->assert_num_params_pushed(2); } -// We cannot call a write without a destination address in UDP. Errno: 89 err_message: Destination address required. -// To run this test we should use a UDP socket connected to the server, and so we should use the connect syscall. -// TEST(SyscallExit, writeX_ipv4_udp_message_not_truncated_fullcapture_port) +// We cannot call a write without a destination address in UDP. Errno: 89 err_message: Destination +// address required. To run this test we should use a UDP socket connected to the server, and so we +// should use the connect syscall. TEST(SyscallExit, +// writeX_ipv4_udp_message_not_truncated_fullcapture_port) #endif #endif diff --git a/test/drivers/test_suites/syscall_exit_suite/writev_x.cpp b/test/drivers/test_suites/syscall_exit_suite/writev_x.cpp index 67e2b3e925..a65b9f1c2b 100644 --- a/test/drivers/test_suites/syscall_exit_suite/writev_x.cpp +++ b/test/drivers/test_suites/syscall_exit_suite/writev_x.cpp @@ -5,8 +5,7 @@ #if defined(__NR_close) && defined(__NR_openat) && defined(__NR_close) -TEST(SyscallExit, writevX_no_snaplen) -{ +TEST(SyscallExit, writevX_no_snaplen) { auto evt_test = get_syscall_event_test(__NR_writev, EXIT_EVENT); evt_test->enable_capture(); @@ -30,8 +29,7 @@ TEST(SyscallExit, writevX_no_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -53,8 +51,7 @@ TEST(SyscallExit, writevX_no_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, writevX_snaplen) -{ +TEST(SyscallExit, writevX_snaplen) { auto evt_test = get_syscall_event_test(__NR_writev, EXIT_EVENT); evt_test->enable_capture(); @@ -74,7 +71,11 @@ TEST(SyscallExit, writevX_snaplen) iov[0].iov_len = sizeof(sent_data_1); iov[1].iov_len = sizeof(sent_data_2); int32_t iovcnt = 2; - assert_syscall_state(SYSCALL_SUCCESS, "writev", syscall(__NR_writev, fd, iov, iovcnt), NOT_EQUAL, -1); + assert_syscall_state(SYSCALL_SUCCESS, + "writev", + syscall(__NR_writev, fd, iov, iovcnt), + NOT_EQUAL, + -1); /*=============================== TRIGGER SYSCALL ===========================*/ @@ -82,8 +83,7 @@ TEST(SyscallExit, writevX_snaplen) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } @@ -104,8 +104,7 @@ TEST(SyscallExit, writevX_snaplen) evt_test->assert_num_params_pushed(2); } -TEST(SyscallExit, writevX_empty) -{ +TEST(SyscallExit, writevX_empty) { auto evt_test = get_syscall_event_test(__NR_writev, EXIT_EVENT); evt_test->enable_capture(); @@ -124,8 +123,7 @@ TEST(SyscallExit, writevX_empty) evt_test->assert_event_presence(); - if(HasFatalFailure()) - { + if(HasFatalFailure()) { return; } diff --git a/test/e2e/CMakeLists.txt b/test/e2e/CMakeLists.txt index 86934515eb..7d30915501 100644 --- a/test/e2e/CMakeLists.txt +++ b/test/e2e/CMakeLists.txt @@ -12,70 +12,61 @@ set(E2E_CONTEXT ${CMAKE_CURRENT_BINARY_DIR}/ctx) # When running in CI, dump the reports in /tmp/ if(DEFINED ENV{CI}) - set(E2E_REPORT /tmp/) + set(E2E_REPORT /tmp/) else() - set(E2E_REPORT ${CMAKE_CURRENT_BINARY_DIR}) + set(E2E_REPORT ${CMAKE_CURRENT_BINARY_DIR}) endif() add_compile_options(${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS}) add_link_options(${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS}) -add_custom_target(e2e-install-deps +add_custom_target( + e2e-install-deps COMMAND pip3 install -r ${CMAKE_CURRENT_SOURCE_DIR}/tests/requirements.txt COMMAND pip3 install ${CMAKE_CURRENT_SOURCE_DIR}/tests/commons/ ) -add_custom_target(e2e-context +add_custom_target( + e2e-context COMMAND mkdir -p ${E2E_CONTEXT} - COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_BINARY_DIR}/libsinsp/examples/sinsp-example ${E2E_CONTEXT} + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_BINARY_DIR}/libsinsp/examples/sinsp-example ${E2E_CONTEXT} COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_BINARY_DIR}/driver/scap.ko ${E2E_CONTEXT} - COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_BINARY_DIR}/driver/bpf/probe.o ${E2E_CONTEXT} + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_BINARY_DIR}/driver/bpf/probe.o + ${E2E_CONTEXT} DEPENDS sinsp-example driver bpf ) -add_custom_target(e2e-containers - COMMAND docker build - --tag sinsp-example:latest - -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/sinsp.Dockerfile - ${E2E_CONTEXT} - COMMAND docker build - --tag sinsp-e2e-tester:latest - -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/tests.Dockerfile - ${CMAKE_CURRENT_SOURCE_DIR} +add_custom_target( + e2e-containers + COMMAND docker build --tag sinsp-example:latest -f + ${CMAKE_CURRENT_SOURCE_DIR}/containers/sinsp.Dockerfile ${E2E_CONTEXT} + COMMAND docker build --tag sinsp-e2e-tester:latest -f + ${CMAKE_CURRENT_SOURCE_DIR}/containers/tests.Dockerfile ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS e2e-context ) -add_custom_target(e2e-tests-container +add_custom_target( + e2e-tests-container COMMAND mkdir -p ${CMAKE_CURRENT_BINARY_DIR}/report # Run e2e tests with the kernel module - COMMAND docker run --rm - --name sinsp-e2e-tester - -e KERNEL_MODULE=/driver/scap.ko - -e BPF_PROBE=/driver/probe.o - -v /var/run/docker.sock:/var/run/docker.sock - -v ${E2E_REPORT}/report:/report - sinsp-e2e-tester:latest + COMMAND + docker run --rm --name sinsp-e2e-tester -e KERNEL_MODULE=/driver/scap.ko -e + BPF_PROBE=/driver/probe.o -v /var/run/docker.sock:/var/run/docker.sock -v + ${E2E_REPORT}/report:/report sinsp-e2e-tester:latest DEPENDS e2e-containers ) -add_custom_target(e2e-tests +add_custom_target( + e2e-tests COMMAND mkdir -p ${E2E_REPORT}/report # Run e2e tests with the kernel module COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/scripts/run_tests.sh DEPENDS sinsp-example driver bpf ) -# This is a list of containers run by the e2e tests, if you add a different one -# please add it to the list -set(E2E_CONTAINERS - sinsp - nginx - sinsp-e2e-tester - curl - generator - http-hello -) +# This is a list of containers run by the e2e tests, if you add a different one please add it to the +# list +set(E2E_CONTAINERS sinsp nginx sinsp-e2e-tester curl generator http-hello) - add_custom_target(e2e-cleanup - COMMAND docker rm -f ${E2E_CONTAINERS} -) +add_custom_target(e2e-cleanup COMMAND docker rm -f ${E2E_CONTAINERS}) diff --git a/test/libscap/CMakeLists.txt b/test/libscap/CMakeLists.txt index e88603ebd0..cdcc76d182 100644 --- a/test/libscap/CMakeLists.txt +++ b/test/libscap/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # message(STATUS "Libscap unit tests build enabled") @@ -21,37 +19,29 @@ if(NOT DEFINED DRIVER_NAME) set(DRIVER_NAME "scap") endif() -# Create a libscap_test_var.h file with some variables used by our tests -# for example the kmod path or the bpf path. -configure_file ( - "${CMAKE_CURRENT_SOURCE_DIR}/libscap_test_var.h.in" - "${CMAKE_CURRENT_BINARY_DIR}/libscap_test_var.h" +# Create a libscap_test_var.h file with some variables used by our tests for example the kmod path +# or the bpf path. +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/libscap_test_var.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/libscap_test_var.h" ) set(LIBSCAP_TESTS_INCLUDE - PRIVATE - "${GTEST_INCLUDE}" - "${CMAKE_CURRENT_SOURCE_DIR}" # for test helpers - "${LIBS_DIR}" - "${LIBS_DIR}/userspace" - "${PROJECT_BINARY_DIR}" - "${CMAKE_CURRENT_BINARY_DIR}" # used to include `libscap_test_var.h` + PRIVATE + "${GTEST_INCLUDE}" + "${CMAKE_CURRENT_SOURCE_DIR}" # for test helpers + "${LIBS_DIR}" + "${LIBS_DIR}/userspace" + "${PROJECT_BINARY_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}" # used to include `libscap_test_var.h` ) # Needed by gtest find_package(Threads) -set(LIBSCAP_TESTS_LIBRARIES - "${GTEST_LIB}" - "${GTEST_MAIN_LIB}" - "${CMAKE_THREAD_LIBS_INIT}" - scap -) +set(LIBSCAP_TESTS_LIBRARIES "${GTEST_LIB}" "${GTEST_MAIN_LIB}" "${CMAKE_THREAD_LIBS_INIT}" scap) -set(LIBSCAP_TESTS_DEPENDENCIES - gtest - scap -) +set(LIBSCAP_TESTS_DEPENDENCIES gtest scap) # Test suite asserting against pure userspace components file(GLOB_RECURSE USERSPACE_TEST_SUITE "${CMAKE_CURRENT_SOURCE_DIR}/test_suites/userspace/*.cpp") @@ -62,8 +52,10 @@ file(GLOB_RECURSE LIBSCAP_TESTS_UTILS_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/helpe list(APPEND LIBSCAP_TESTS_SOURCES ${LIBSCAP_TESTS_UTILS_SOURCES}) # Linux specific tests -if (CMAKE_SYSTEM_NAME MATCHES "Linux") - file(GLOB_RECURSE LINUX_TEST_SUITE "${CMAKE_CURRENT_SOURCE_DIR}/test_suites/userspace/linux/*.cpp") +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + file(GLOB_RECURSE LINUX_TEST_SUITE + "${CMAKE_CURRENT_SOURCE_DIR}/test_suites/userspace/linux/*.cpp" + ) list(APPEND LIBSCAP_TEST_SOURCES ${LINUX_TEST_SUITE}) list(APPEND LIBSCAP_TESTS_LIBRARIES scap_engine_util) endif() @@ -84,15 +76,20 @@ if(BUILD_BPF) endif() if(BUILD_LIBSCAP_MODERN_BPF) - file(GLOB_RECURSE MODERN_BPF_TEST_SUITE "${CMAKE_CURRENT_SOURCE_DIR}/test_suites/engines/modern_bpf/*.cpp") + file(GLOB_RECURSE MODERN_BPF_TEST_SUITE + "${CMAKE_CURRENT_SOURCE_DIR}/test_suites/engines/modern_bpf/*.cpp" + ) list(APPEND LIBSCAP_TESTS_SOURCES ${MODERN_BPF_TEST_SUITE}) endif() if(BUILD_LIBSCAP_GVISOR) include(protobuf) - file(GLOB_RECURSE GVISOR_TEST_SUITE "${CMAKE_CURRENT_SOURCE_DIR}/test_suites/engines/gvisor/*.cpp") + file(GLOB_RECURSE GVISOR_TEST_SUITE + "${CMAKE_CURRENT_SOURCE_DIR}/test_suites/engines/gvisor/*.cpp" + ) list(APPEND LIBSCAP_TESTS_SOURCES ${GVISOR_TEST_SUITE}) - list(APPEND LIBSCAP_TESTS_INCLUDE "${CMAKE_BINARY_DIR}/libscap/engine/gvisor") # Used for includes + list(APPEND LIBSCAP_TESTS_INCLUDE "${CMAKE_BINARY_DIR}/libscap/engine/gvisor" + )# Used for includes endif() # Summary logs @@ -100,7 +97,9 @@ set(LIBSCAP_UNIT_TESTS_PREFIX "[LIBSCAP UNIT TESTS]") message(STATUS "${LIBSCAP_UNIT_TESTS_PREFIX} LIBSCAP_TESTS_SOURCES: ${LIBSCAP_TESTS_SOURCES}") message(STATUS "${LIBSCAP_UNIT_TESTS_PREFIX} LIBSCAP_TESTS_INCLUDE: ${LIBSCAP_TESTS_INCLUDE}") message(STATUS "${LIBSCAP_UNIT_TESTS_PREFIX} LIBSCAP_TESTS_LIBRARIES: ${LIBSCAP_TESTS_LIBRARIES}") -message(STATUS "${LIBSCAP_UNIT_TESTS_PREFIX} LIBSCAP_TESTS_DEPENDENCIES: ${LIBSCAP_TESTS_DEPENDENCIES}") +message( + STATUS "${LIBSCAP_UNIT_TESTS_PREFIX} LIBSCAP_TESTS_DEPENDENCIES: ${LIBSCAP_TESTS_DEPENDENCIES}" +) add_compile_options(${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS}) add_link_options(${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS}) diff --git a/test/libscap/helpers/engines.cpp b/test/libscap/helpers/engines.cpp index a430c74177..e68243524e 100644 --- a/test/libscap/helpers/engines.cpp +++ b/test/libscap/helpers/engines.cpp @@ -14,49 +14,50 @@ /* Number of events we want to assert */ #define EVENTS_TO_ASSERT 32 -void check_event_is_not_overwritten(scap_t *h) -{ +void check_event_is_not_overwritten(scap_t *h) { /* Start the capture */ - ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS) << "unable to start the capture: " << scap_getlasterr(h) << std::endl; + ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS) + << "unable to start the capture: " << scap_getlasterr(h) << std::endl; - /* When the number of events is fixed for `MAX_ITERATIONS` we consider all the buffers full, this is just an approximation */ + /* When the number of events is fixed for `MAX_ITERATIONS` we consider all the buffers full, + * this is just an approximation */ scap_stats stats = {}; uint64_t last_num_events = 0; uint16_t iterations = 0; - while(iterations < MAX_ITERATIONS || stats.n_drops == 0) - { - ASSERT_EQ(scap_get_stats(h, &stats), SCAP_SUCCESS) << "unable to get stats: " << scap_getlasterr(h) << std::endl; - if(last_num_events == (stats.n_evts - stats.n_drops)) - { + while(iterations < MAX_ITERATIONS || stats.n_drops == 0) { + ASSERT_EQ(scap_get_stats(h, &stats), SCAP_SUCCESS) + << "unable to get stats: " << scap_getlasterr(h) << std::endl; + if(last_num_events == (stats.n_evts - stats.n_drops)) { iterations++; - } - else - { + } else { iterations = 0; last_num_events = (stats.n_evts - stats.n_drops); } } /* Stop the capture */ - ASSERT_EQ(scap_stop_capture(h), SCAP_SUCCESS) << "unable to stop the capture: " << scap_getlasterr(h) << std::endl; + ASSERT_EQ(scap_stop_capture(h), SCAP_SUCCESS) + << "unable to stop the capture: " << scap_getlasterr(h) << std::endl; /* The idea here is to check if an event is overwritten while we still have a pointer to it. - * Again this is only an approximation, we don't know if new events will be written in the buffer - * under test... + * Again this is only an approximation, we don't know if new events will be written in the + * buffer under test... * * We call `scap_next` keeping the pointer to the event. - * An event pointer becomes invalid when we call another `scap_next`, but until that moment it should be valid! + * An event pointer becomes invalid when we call another `scap_next`, but until that moment it + * should be valid! */ scap_evt *evt = NULL; uint16_t buffer_id; uint32_t flags; - /* The first 'scap_next` could return a `SCAP_TIMEOUT` according to the chosen `buffer_mode` so we ignore it. */ + /* The first 'scap_next` could return a `SCAP_TIMEOUT` according to the chosen `buffer_mode` so + * we ignore it. */ scap_next(h, &evt, &buffer_id, &flags); ASSERT_EQ(scap_next(h, &evt, &buffer_id, &flags), SCAP_SUCCESS) - << "unable to get an event with `scap_next`: " << scap_getlasterr(h) << std::endl; + << "unable to get an event with `scap_next`: " << scap_getlasterr(h) << std::endl; last_num_events = 0; iterations = 0; @@ -69,18 +70,16 @@ void check_event_is_not_overwritten(scap_t *h) uint32_t prev_nparams = evt->nparams; /* Start again the capture */ - ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS) << "unable to restart the capture: " << scap_getlasterr(h) << std::endl; + ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS) + << "unable to restart the capture: " << scap_getlasterr(h) << std::endl; /* We use the same approximation as before */ - while(iterations < MAX_ITERATIONS) - { - ASSERT_EQ(scap_get_stats(h, &stats), SCAP_SUCCESS) << "unable to get stats: " << scap_getlasterr(h) << std::endl; - if(last_num_events == (stats.n_evts - stats.n_drops)) - { + while(iterations < MAX_ITERATIONS) { + ASSERT_EQ(scap_get_stats(h, &stats), SCAP_SUCCESS) + << "unable to get stats: " << scap_getlasterr(h) << std::endl; + if(last_num_events == (stats.n_evts - stats.n_drops)) { iterations++; - } - else - { + } else { iterations = 0; last_num_events = (stats.n_evts - stats.n_drops); } @@ -94,14 +93,30 @@ void check_event_is_not_overwritten(scap_t *h) ASSERT_EQ(prev_nparams, evt->nparams) << "different num params" << std::endl; } -#if defined(__NR_close) && defined(__NR_openat) && defined(__NR_listen) && defined(__NR_accept4) && defined(__NR_getegid) && defined(__NR_getgid) && defined(__NR_geteuid) && defined(__NR_getuid) && defined(__NR_bind) && defined(__NR_connect) && defined(__NR_sendto) && defined(__NR_getsockopt) && defined(__NR_recvmsg) && defined(__NR_recvfrom) && defined(__NR_socket) && defined(__NR_socketpair) - -void check_event_order(scap_t *h) -{ - uint32_t events_to_assert[EVENTS_TO_ASSERT] = {PPME_SYSCALL_CLOSE_E, PPME_SYSCALL_CLOSE_X, PPME_SYSCALL_OPENAT_2_E, PPME_SYSCALL_OPENAT_2_X, PPME_SOCKET_LISTEN_E, PPME_SOCKET_LISTEN_X, PPME_SOCKET_ACCEPT4_6_E, PPME_SOCKET_ACCEPT4_6_X, PPME_SYSCALL_GETEGID_E, PPME_SYSCALL_GETEGID_X, PPME_SYSCALL_GETGID_E, PPME_SYSCALL_GETGID_X, PPME_SYSCALL_GETEUID_E, PPME_SYSCALL_GETEUID_X, PPME_SYSCALL_GETUID_E, PPME_SYSCALL_GETUID_X, PPME_SOCKET_BIND_E, PPME_SOCKET_BIND_X, PPME_SOCKET_CONNECT_E, PPME_SOCKET_CONNECT_X, PPME_SOCKET_SENDTO_E, PPME_SOCKET_SENDTO_X, PPME_SOCKET_GETSOCKOPT_E, PPME_SOCKET_GETSOCKOPT_X, PPME_SOCKET_RECVMSG_E, PPME_SOCKET_RECVMSG_X, PPME_SOCKET_RECVFROM_E, PPME_SOCKET_RECVFROM_X, PPME_SOCKET_SOCKET_E, PPME_SOCKET_SOCKET_X, PPME_SOCKET_SOCKETPAIR_E, PPME_SOCKET_SOCKETPAIR_X}; +#if defined(__NR_close) && defined(__NR_openat) && defined(__NR_listen) && \ + defined(__NR_accept4) && defined(__NR_getegid) && defined(__NR_getgid) && \ + defined(__NR_geteuid) && defined(__NR_getuid) && defined(__NR_bind) && \ + defined(__NR_connect) && defined(__NR_sendto) && defined(__NR_getsockopt) && \ + defined(__NR_recvmsg) && defined(__NR_recvfrom) && defined(__NR_socket) && \ + defined(__NR_socketpair) + +void check_event_order(scap_t *h) { + uint32_t events_to_assert[EVENTS_TO_ASSERT] = { + PPME_SYSCALL_CLOSE_E, PPME_SYSCALL_CLOSE_X, PPME_SYSCALL_OPENAT_2_E, + PPME_SYSCALL_OPENAT_2_X, PPME_SOCKET_LISTEN_E, PPME_SOCKET_LISTEN_X, + PPME_SOCKET_ACCEPT4_6_E, PPME_SOCKET_ACCEPT4_6_X, PPME_SYSCALL_GETEGID_E, + PPME_SYSCALL_GETEGID_X, PPME_SYSCALL_GETGID_E, PPME_SYSCALL_GETGID_X, + PPME_SYSCALL_GETEUID_E, PPME_SYSCALL_GETEUID_X, PPME_SYSCALL_GETUID_E, + PPME_SYSCALL_GETUID_X, PPME_SOCKET_BIND_E, PPME_SOCKET_BIND_X, + PPME_SOCKET_CONNECT_E, PPME_SOCKET_CONNECT_X, PPME_SOCKET_SENDTO_E, + PPME_SOCKET_SENDTO_X, PPME_SOCKET_GETSOCKOPT_E, PPME_SOCKET_GETSOCKOPT_X, + PPME_SOCKET_RECVMSG_E, PPME_SOCKET_RECVMSG_X, PPME_SOCKET_RECVFROM_E, + PPME_SOCKET_RECVFROM_X, PPME_SOCKET_SOCKET_E, PPME_SOCKET_SOCKET_X, + PPME_SOCKET_SOCKETPAIR_E, PPME_SOCKET_SOCKETPAIR_X}; /* Start the capture */ - ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS) << "unable to start the capture: " << scap_getlasterr(h) << std::endl; + ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS) + << "unable to start the capture: " << scap_getlasterr(h) << std::endl; /* 1. Generate a `close` event pair */ syscall(__NR_close, -1); @@ -152,7 +167,8 @@ void check_event_order(scap_t *h) syscall(__NR_socketpair, 0, 0, 0, 0); /* Stop the capture */ - ASSERT_EQ(scap_stop_capture(h), SCAP_SUCCESS) << "unable to stop the capture: " << scap_getlasterr(h) << std::endl; + ASSERT_EQ(scap_stop_capture(h), SCAP_SUCCESS) + << "unable to stop the capture: " << scap_getlasterr(h) << std::endl; scap_evt *evt = NULL; uint16_t buffer_id = 0; @@ -162,26 +178,20 @@ void check_event_order(scap_t *h) /* if we hit 5 consecutive timeouts it means that all buffers are empty (approximation) */ uint16_t timeouts = 0; - for(int i = 0; i < EVENTS_TO_ASSERT; i++) - { - while(true) - { + for(int i = 0; i < EVENTS_TO_ASSERT; i++) { + while(true) { ret = scap_next(h, &evt, &buffer_id, &flags); - if(ret == SCAP_SUCCESS) - { + if(ret == SCAP_SUCCESS) { timeouts = 0; - if(evt->tid == actual_pid && evt->type == events_to_assert[i]) - { + if(evt->tid == actual_pid && evt->type == events_to_assert[i]) { /* We found our event */ break; } - } - else if(ret == SCAP_TIMEOUT) - { + } else if(ret == SCAP_TIMEOUT) { timeouts++; - if(timeouts == 5) - { - FAIL() << "we didn't find event '" << events_to_assert[i] << "' at position '" << i << "'" << std::endl; + if(timeouts == 5) { + FAIL() << "we didn't find event '" << events_to_assert[i] << "' at position '" + << i << "'" << std::endl; } } } @@ -190,8 +200,7 @@ void check_event_order(scap_t *h) #else -void check_event_order(scap_t *h) -{ +void check_event_order(scap_t *h) { GTEST_SKIP() << "Some syscalls required by the test are not defined" << std::endl; } #endif @@ -200,8 +209,7 @@ void check_event_order(scap_t *h) * This is extracted from `libbpf_num_possible_cpus()`. * We avoid to include libbpf just for this helper. */ -static int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz) -{ +static int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz) { int err = 0, n, len, start, end = -1; bool *tmp; @@ -209,34 +217,26 @@ static int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz) *mask_sz = 0; /* Each sub string separated by ',' has format \d+-\d+ or \d+ */ - while(*s) - { - if(*s == ',' || *s == '\n') - { + while(*s) { + if(*s == ',' || *s == '\n') { s++; continue; } n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len); - if(n <= 0 || n > 2) - { + if(n <= 0 || n > 2) { fprintf(stderr, "Failed to get CPU range %s: %d\n", s, n); err = -EINVAL; goto cleanup; - } - else if(n == 1) - { + } else if(n == 1) { end = start; } - if(start < 0 || start > end) - { - fprintf(stderr, "Invalid CPU range [%d,%d] in %s\n", - start, end, s); + if(start < 0 || start > end) { + fprintf(stderr, "Invalid CPU range [%d,%d] in %s\n", start, end, s); err = -EINVAL; goto cleanup; } tmp = (bool *)realloc(*mask, end + 1); - if(!tmp) - { + if(!tmp) { err = -ENOMEM; goto cleanup; } @@ -246,8 +246,7 @@ static int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz) *mask_sz = end + 1; s += len; } - if(!*mask_sz) - { + if(!*mask_sz) { fprintf(stderr, "Empty CPU range\n"); return -EINVAL; } @@ -258,29 +257,25 @@ static int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz) return err; } -static int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz) -{ +static int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz) { int fd, err = 0, len; char buf[128]; fd = open(fcpu, O_RDONLY | O_CLOEXEC); - if(fd < 0) - { + if(fd < 0) { err = -errno; fprintf(stderr, "Failed to open cpu mask file %s: %d\n", fcpu, err); return err; } len = read(fd, buf, sizeof(buf)); close(fd); - if(len <= 0) - { + if(len <= 0) { err = len ? -errno : -EINVAL; fprintf(stderr, "Failed to read cpu mask from %s: %d\n", fcpu, err); return err; } - if(len >= sizeof(buf)) - { + if(len >= sizeof(buf)) { fprintf(stderr, "CPU mask is too big in file %s\n", fcpu); return -E2BIG; @@ -290,26 +285,23 @@ static int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz) return parse_cpu_mask_str(buf, mask, mask_sz); } -int num_possible_cpus(void) -{ +int num_possible_cpus(void) { const char *fcpu = "/sys/devices/system/cpu/possible"; int cpus = 0; int n = 0; /* array of bools for each CPU */ - bool* mask = nullptr; + bool *mask = nullptr; int err = parse_cpu_mask_file(fcpu, &mask, &n); if(err) return -1; - for(int i = 0; i < n; i++) - { + for(int i = 0; i < n; i++) { if(mask[i]) cpus++; } - if(mask) - { + if(mask) { free(mask); } return cpus; diff --git a/test/libscap/test_suites/engines/bpf/bpf.cpp b/test/libscap/test_suites/engines/bpf/bpf.cpp index 6c450e0e2b..1f1b6c0c29 100644 --- a/test/libscap/test_suites/engines/bpf/bpf.cpp +++ b/test/libscap/test_suites/engines/bpf/bpf.cpp @@ -6,97 +6,97 @@ #include #include -scap_t* open_bpf_engine(char* error_buf, int32_t* rc, unsigned long buffer_dim, const char* name, std::unordered_set ppm_sc_set = {}) -{ +scap_t* open_bpf_engine(char* error_buf, + int32_t* rc, + unsigned long buffer_dim, + const char* name, + std::unordered_set ppm_sc_set = {}) { struct scap_open_args oargs {}; /* If empty we fill with all syscalls */ - if(ppm_sc_set.empty()) - { - for(int i = 0; i < PPM_SC_MAX; i++) - { + if(ppm_sc_set.empty()) { + for(int i = 0; i < PPM_SC_MAX; i++) { oargs.ppm_sc_of_interest.ppm_sc[i] = 1; } - } - else - { - for(auto ppm_sc : ppm_sc_set) - { + } else { + for(auto ppm_sc : ppm_sc_set) { oargs.ppm_sc_of_interest.ppm_sc[ppm_sc] = 1; } } struct scap_bpf_engine_params bpf_params = { - .buffer_bytes_dim = buffer_dim, - .bpf_probe = name, + .buffer_bytes_dim = buffer_dim, + .bpf_probe = name, }; oargs.engine_params = &bpf_params; return scap_open(&oargs, &scap_bpf_engine, error_buf, rc); } -TEST(bpf, open_engine) -{ +TEST(bpf, open_engine) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; scap_close(h); } -TEST(bpf, wrong_bpf_path) -{ +TEST(bpf, wrong_bpf_path) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, "."); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the BPF path is wrong, we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) + << "the BPF path is wrong, we should fail: " << error_buffer << std::endl; } -TEST(bpf, empty_bpf_path) -{ +TEST(bpf, empty_bpf_path) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, ""); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the BPF path is wrong, we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) + << "the BPF path is wrong, we should fail: " << error_buffer << std::endl; } -TEST(bpf, wrong_buffer_dim) -{ +TEST(bpf, wrong_buffer_dim) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the buffer dimension is not a system page multiple, so we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) + << "the buffer dimension is not a system page multiple, so we should fail: " + << error_buffer << std::endl; } -/* This check is not so reliable, better than nothing but to be sure we need to obtain the producer and consumer positions from the drivers */ -TEST(bpf, events_not_overwritten) -{ +/* This check is not so reliable, better than nothing but to be sure we need to obtain the producer + * and consumer positions from the drivers */ +TEST(bpf, events_not_overwritten) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; check_event_is_not_overwritten(h); scap_close(h); } -TEST(bpf, read_in_order) -{ +TEST(bpf, read_in_order) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; check_event_order(h); scap_close(h); } -TEST(bpf, scap_stats_check) -{ +TEST(bpf, scap_stats_check) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; scap_stats stats; @@ -107,12 +107,12 @@ TEST(bpf, scap_stats_check) scap_close(h); } -TEST(bpf, double_scap_stats_call) -{ +TEST(bpf, double_scap_stats_call) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; scap_stats stats; @@ -129,12 +129,12 @@ TEST(bpf, double_scap_stats_call) scap_close(h); } -TEST(bpf, metrics_v2_check_per_CPU_stats) -{ +TEST(bpf, metrics_v2_check_per_CPU_stats) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; ssize_t num_possible_CPUs = num_possible_cpus(); @@ -150,56 +150,53 @@ TEST(bpf, metrics_v2_check_per_CPU_stats) uint32_t i = 0; ssize_t found = 0; char expected_name[METRIC_NAME_MAX] = ""; - snprintf(expected_name, METRIC_NAME_MAX, N_EVENTS_PER_CPU_PREFIX"%ld", found); + snprintf(expected_name, METRIC_NAME_MAX, N_EVENTS_PER_CPU_PREFIX "%ld", found); bool check_general_kernel_counters_presence = false; - while(i < nstats) - { + while(i < nstats) { // We check if `METRICS_V2_KERNEL_COUNTERS` are enabled as well - if(strncmp(stats_v2[i].name, N_EVENTS_PREFIX, sizeof(N_EVENTS_PREFIX)) == 0) - { + if(strncmp(stats_v2[i].name, N_EVENTS_PREFIX, sizeof(N_EVENTS_PREFIX)) == 0) { check_general_kernel_counters_presence = true; i++; continue; } // `sizeof(N_EVENTS_PER_CPU_PREFIX)-1` because we need to exclude the `\0` - if(strncmp(stats_v2[i].name, N_EVENTS_PER_CPU_PREFIX, sizeof(N_EVENTS_PER_CPU_PREFIX)-1) == 0) - { + if(strncmp(stats_v2[i].name, + N_EVENTS_PER_CPU_PREFIX, + sizeof(N_EVENTS_PER_CPU_PREFIX) - 1) == 0) { i++; // The next metric should be the number of drops - snprintf(expected_name, METRIC_NAME_MAX, N_DROPS_PER_CPU_PREFIX"%ld", found); - if(strncmp(stats_v2[i].name, N_DROPS_PER_CPU_PREFIX, sizeof(N_DROPS_PER_CPU_PREFIX)-1) == 0) - { + snprintf(expected_name, METRIC_NAME_MAX, N_DROPS_PER_CPU_PREFIX "%ld", found); + if(strncmp(stats_v2[i].name, + N_DROPS_PER_CPU_PREFIX, + sizeof(N_DROPS_PER_CPU_PREFIX) - 1) == 0) { i++; found++; - } - else - { + } else { FAIL() << "Missing CPU drops for CPU " << found; } - } - else - { + } else { i++; } } - ASSERT_TRUE(check_general_kernel_counters_presence) << "per-CPU counter are enabled but general kernel counters are not"; + ASSERT_TRUE(check_general_kernel_counters_presence) + << "per-CPU counter are enabled but general kernel counters are not"; - // This test could fail in case of rare race conditions in which the number of available CPUs changes - // between the scap_open and the `num_possible_cpus` function. In CI we shouldn't have hot plugs so probably we - // can live with this. + // This test could fail in case of rare race conditions in which the number of available CPUs + // changes between the scap_open and the `num_possible_cpus` function. In CI we shouldn't have + // hot plugs so probably we can live with this. ASSERT_EQ(num_possible_CPUs, found) << "We didn't find the stats for all the CPUs"; scap_close(h); } -TEST(bpf, metrics_v2_check_results) -{ +TEST(bpf, metrics_v2_check_results) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; uint32_t flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS; uint32_t nstats; @@ -210,51 +207,51 @@ TEST(bpf, metrics_v2_check_results) /* These names should always be available */ std::unordered_set minimal_stats_name = {"n_evts"}; - if (scap_get_bpf_stats_enabled()) - { - minimal_stats_name.insert({"sys_enter.run_cnt", "sys_enter.run_time_ns", "sys_exit.run_cnt", "sys_exit.run_time_ns", "signal_deliver.run_cnt", "signal_deliver.run_time_ns"}); + if(scap_get_bpf_stats_enabled()) { + minimal_stats_name.insert({"sys_enter.run_cnt", + "sys_enter.run_time_ns", + "sys_exit.run_cnt", + "sys_exit.run_time_ns", + "signal_deliver.run_cnt", + "signal_deliver.run_time_ns"}); } - + uint32_t i = 0; - for(const auto& stat_name : minimal_stats_name) - { - for(i = 0; i < nstats; i++) - { - if(stat_name.compare(stats_v2[i].name) == 0) - { + for(const auto& stat_name : minimal_stats_name) { + for(i = 0; i < nstats; i++) { + if(stat_name.compare(stats_v2[i].name) == 0) { break; } } - if(i == nstats) - { + if(i == nstats) { FAIL() << "unable to find stat '" << stat_name << "' into the array"; } } // Check per-CPU stats are not enabled since we didn't provide the flag. - for(i = 0; i < nstats; i++) - { - if(strncmp(stats_v2[i].name, N_EVENTS_PER_CPU_PREFIX, sizeof(N_EVENTS_PER_CPU_PREFIX)-1) == 0) - { - FAIL() << "per-CPU counters are enabled but we didn't provide the flag!"; - } + for(i = 0; i < nstats; i++) { + if(strncmp(stats_v2[i].name, + N_EVENTS_PER_CPU_PREFIX, + sizeof(N_EVENTS_PER_CPU_PREFIX) - 1) == 0) { + FAIL() << "per-CPU counters are enabled but we didn't provide the flag!"; + } } scap_close(h); } -TEST(bpf, double_metrics_v2_call) -{ +TEST(bpf, double_metrics_v2_call) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; uint32_t flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS; uint32_t nstats; int32_t rc; - + scap_get_stats_v2(h, flags, &nstats, &rc); ASSERT_EQ(rc, SCAP_SUCCESS); ASSERT_GT(nstats, 0); @@ -267,12 +264,12 @@ TEST(bpf, double_metrics_v2_call) scap_close(h); } -TEST(bpf, metrics_v2_check_empty) -{ +TEST(bpf, metrics_v2_check_empty) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_bpf_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_BPF_PROBE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open bpf engine: " << error_buffer << std::endl; uint32_t flags = 0; uint32_t nstats; diff --git a/test/libscap/test_suites/engines/gvisor/gvisor_parsers.cpp b/test/libscap/test_suites/engines/gvisor/gvisor_parsers.cpp index 0487aa1c09..026c574b19 100644 --- a/test/libscap/test_suites/engines/gvisor/gvisor_parsers.cpp +++ b/test/libscap/test_suites/engines/gvisor/gvisor_parsers.cpp @@ -36,472 +36,473 @@ limitations under the License. #endif /* __x86_64__ */ template -uint32_t prepare_message(char *message, uint32_t message_size, uint16_t message_type, T &gvisor_evt) -{ - uint32_t proto_size = static_cast(gvisor_evt.ByteSizeLong()); - uint16_t header_size = sizeof(scap_gvisor::header); - uint32_t total_size = header_size + proto_size; - uint32_t dropped_count = 0; +uint32_t prepare_message(char *message, + uint32_t message_size, + uint16_t message_type, + T &gvisor_evt) { + uint32_t proto_size = static_cast(gvisor_evt.ByteSizeLong()); + uint16_t header_size = sizeof(scap_gvisor::header); + uint32_t total_size = header_size + proto_size; + uint32_t dropped_count = 0; + + // Fill the message header + memcpy(message, &header_size, sizeof(uint16_t)); + memcpy(&message[sizeof(uint16_t)], &message_type, sizeof(uint16_t)); + memcpy(&message[sizeof(uint16_t) + sizeof(uint16_t)], &dropped_count, sizeof(uint32_t)); + + // Serialize proto + gvisor_evt.SerializeToArray(&message[header_size], message_size - header_size); + + return total_size; +} + +TEST(gvisor_parsers, parse_execve_e) { + char message[1024]; + char buffer[1024]; + + gvisor::syscall::Execve gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; + gvisor_evt.set_sysno(__NR_execve); + gvisor_evt.set_pathname("/usr/bin/ls"); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); - // Fill the message header - memcpy(message, &header_size, sizeof(uint16_t)); - memcpy(&message[sizeof(uint16_t)], &message_type, sizeof(uint16_t)); - memcpy(&message[sizeof(uint16_t) + sizeof(uint16_t)], &dropped_count, sizeof(uint32_t)); + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - // Serialize proto - gvisor_evt.SerializeToArray(&message[header_size], message_size - header_size); + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - return total_size; + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); + + EXPECT_EQ(res.scap_events.size(), 1); + + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 1); + EXPECT_STREQ(static_cast(decoded_params[0].buf), "/usr/bin/ls"); } -TEST(gvisor_parsers, parse_execve_e) -{ - char message[1024]; - char buffer[1024]; +TEST(gvisor_parsers, parse_container_id) { + char message[1024]; - gvisor::syscall::Execve gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; - gvisor_evt.set_sysno(__NR_execve); - gvisor_evt.set_pathname("/usr/bin/ls"); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); + std::string container_id = "1234"; + std::string parsed_container_id; + gvisor::syscall::Execve execve_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; + execve_evt.set_sysno(__NR_execve); + execve_evt.set_pathname("/usr/bin/ls"); + auto *context_data = execve_evt.mutable_context_data(); + context_data->set_container_id(container_id); - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + uint32_t total_size = prepare_message(message, 1024, message_type, execve_evt); - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); + parsed_container_id = scap_gvisor::parsers::parse_container_id(gvisor_msg); + EXPECT_EQ(container_id, parsed_container_id); - EXPECT_EQ(res.scap_events.size(), 1); + gvisor::syscall::Fork fork_evt; + message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_FORK; + fork_evt.set_sysno(__NR_fork); + context_data = fork_evt.mutable_context_data(); + container_id = "my_container_id"; + context_data->set_container_id(container_id); - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 1); - EXPECT_STREQ(static_cast(decoded_params[0].buf), "/usr/bin/ls"); -} + total_size = prepare_message(message, 1024, message_type, fork_evt); -TEST(gvisor_parsers, parse_container_id) -{ - char message[1024]; - - std::string container_id = "1234"; - std::string parsed_container_id; - gvisor::syscall::Execve execve_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; - execve_evt.set_sysno(__NR_execve); - execve_evt.set_pathname("/usr/bin/ls"); - auto *context_data = execve_evt.mutable_context_data(); - context_data->set_container_id(container_id); - - uint32_t total_size = prepare_message(message, 1024, message_type, execve_evt); - - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - - parsed_container_id = scap_gvisor::parsers::parse_container_id(gvisor_msg); - EXPECT_EQ(container_id, parsed_container_id); - - gvisor::syscall::Fork fork_evt; - message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_FORK; - fork_evt.set_sysno(__NR_fork); - context_data = fork_evt.mutable_context_data(); - container_id = "my_container_id"; - context_data->set_container_id(container_id); - - total_size = prepare_message(message, 1024, message_type, fork_evt); - - gvisor_msg = {.buf = message, .size = total_size}; - parsed_container_id = scap_gvisor::parsers::parse_container_id(gvisor_msg); - EXPECT_EQ(container_id, parsed_container_id); - - gvisor::container::Start start_evt; - message_type = gvisor::common::MessageType::MESSAGE_CONTAINER_START; - container_id = "deadbeef"; - start_evt.set_id(container_id); - start_evt.mutable_args()->Add("ls"); - context_data = start_evt.mutable_context_data(); - context_data->set_cwd("/root"); - - total_size = prepare_message(message, 1024, message_type, start_evt); - - gvisor_msg = {.buf = message, .size = total_size}; - parsed_container_id = scap_gvisor::parsers::parse_container_id(gvisor_msg); - EXPECT_EQ(container_id, parsed_container_id); -} + gvisor_msg = {.buf = message, .size = total_size}; + parsed_container_id = scap_gvisor::parsers::parse_container_id(gvisor_msg); + EXPECT_EQ(container_id, parsed_container_id); + gvisor::container::Start start_evt; + message_type = gvisor::common::MessageType::MESSAGE_CONTAINER_START; + container_id = "deadbeef"; + start_evt.set_id(container_id); + start_evt.mutable_args()->Add("ls"); + context_data = start_evt.mutable_context_data(); + context_data->set_cwd("/root"); -TEST(gvisor_parsers, parse_execve_x) -{ - char message[1024]; - char buffer[1024]; - - gvisor::syscall::Execve gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; - gvisor_evt.set_sysno(__NR_execve); - gvisor_evt.set_pathname("/usr/bin/ls"); - gvisor_evt.mutable_argv()->Add("ls"); - gvisor_evt.mutable_argv()->Add("a"); - gvisor_evt.mutable_argv()->Add("b"); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); - context_data->set_cwd("/root"); - gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); - exit->set_result(0); - - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); - - EXPECT_EQ(res.scap_events.size(), 1); - - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 27); - EXPECT_STREQ(static_cast(decoded_params[1].buf), "/usr/bin/ls"); // exe - EXPECT_STREQ(static_cast(decoded_params[2].buf), "a"); // args[0] must be argv[1] - EXPECT_STREQ(static_cast(decoded_params[6].buf), "/root"); // cwd - EXPECT_STREQ(static_cast(decoded_params[13].buf), "ls"); // comm - - gvisor::syscall::Execve gvisor_evt2; - message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; - gvisor_evt2.set_sysno(__NR_execve); - gvisor_evt2.set_pathname("/usr/bin/ls"); - context_data = gvisor_evt2.mutable_context_data(); - context_data->set_container_id("1234"); - context_data->set_cwd("/root"); - gvisor_evt2.mutable_exit()->set_result(0); - - total_size = prepare_message(message, 1024, message_type, gvisor_evt2); - - gvisor_msg = {.buf = message, .size = total_size}; - scap_buf = {.buf = buffer, .size = 1024}; - - res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); - - EXPECT_EQ(res.scap_events.size(), 1); - - n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 27); - EXPECT_STREQ(static_cast(decoded_params[1].buf), "/usr/bin/ls"); // exe - EXPECT_EQ(strlen(static_cast(decoded_params[2].buf)), 0); // there must be no args + total_size = prepare_message(message, 1024, message_type, start_evt); + + gvisor_msg = {.buf = message, .size = total_size}; + parsed_container_id = scap_gvisor::parsers::parse_container_id(gvisor_msg); + EXPECT_EQ(container_id, parsed_container_id); } -TEST(gvisor_parsers, parse_fork_e) -{ - char message[1024]; - char buffer[1024]; +TEST(gvisor_parsers, parse_execve_x) { + char message[1024]; + char buffer[1024]; + + gvisor::syscall::Execve gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; + gvisor_evt.set_sysno(__NR_execve); + gvisor_evt.set_pathname("/usr/bin/ls"); + gvisor_evt.mutable_argv()->Add("ls"); + gvisor_evt.mutable_argv()->Add("a"); + gvisor_evt.mutable_argv()->Add("b"); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); + context_data->set_cwd("/root"); + gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); + exit->set_result(0); + + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); + + EXPECT_EQ(res.scap_events.size(), 1); + + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 27); + EXPECT_STREQ(static_cast(decoded_params[1].buf), "/usr/bin/ls"); // exe + EXPECT_STREQ(static_cast(decoded_params[2].buf), "a"); // args[0] must be argv[1] + EXPECT_STREQ(static_cast(decoded_params[6].buf), "/root"); // cwd + EXPECT_STREQ(static_cast(decoded_params[13].buf), "ls"); // comm + + gvisor::syscall::Execve gvisor_evt2; + message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; + gvisor_evt2.set_sysno(__NR_execve); + gvisor_evt2.set_pathname("/usr/bin/ls"); + context_data = gvisor_evt2.mutable_context_data(); + context_data->set_container_id("1234"); + context_data->set_cwd("/root"); + gvisor_evt2.mutable_exit()->set_result(0); + + total_size = prepare_message(message, 1024, message_type, gvisor_evt2); + + gvisor_msg = {.buf = message, .size = total_size}; + scap_buf = {.buf = buffer, .size = 1024}; + + res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); + + EXPECT_EQ(res.scap_events.size(), 1); + + n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 27); + EXPECT_STREQ(static_cast(decoded_params[1].buf), "/usr/bin/ls"); // exe + EXPECT_EQ(strlen(static_cast(decoded_params[2].buf)), + 0); // there must be no args +} + +TEST(gvisor_parsers, parse_fork_e) { + char message[1024]; + char buffer[1024]; - gvisor::syscall::Fork gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_FORK; - gvisor_evt.set_sysno(__NR_fork); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); + gvisor::syscall::Fork gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_FORK; + gvisor_evt.set_sysno(__NR_fork); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); - EXPECT_EQ(res.scap_events.size(), 1); + EXPECT_EQ(res.scap_events.size(), 1); - EXPECT_EQ(res.scap_events[0]->type, PPME_SYSCALL_FORK_20_E); + EXPECT_EQ(res.scap_events[0]->type, PPME_SYSCALL_FORK_20_E); - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 0); + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 0); } -TEST(gvisor_parsers, parse_fork_x) -{ - char message[1024]; - char buffer[1024]; - - gvisor::syscall::Fork gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_FORK; - gvisor_evt.set_sysno(__NR_fork); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); - context_data->set_process_name("ls"); - context_data->set_cwd("/root"); - gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); - exit->set_result(0); - - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); - - EXPECT_EQ(res.scap_events.size(), 1); - - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 21); - EXPECT_STREQ(static_cast(decoded_params[1].buf), "ls"); // exe - EXPECT_STREQ(static_cast(decoded_params[6].buf), "/root"); // cwd - EXPECT_STREQ(static_cast(decoded_params[13].buf), "ls"); // comm +TEST(gvisor_parsers, parse_fork_x) { + char message[1024]; + char buffer[1024]; + + gvisor::syscall::Fork gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_FORK; + gvisor_evt.set_sysno(__NR_fork); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); + context_data->set_process_name("ls"); + context_data->set_cwd("/root"); + gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); + exit->set_result(0); + + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); + + EXPECT_EQ(res.scap_events.size(), 1); + + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 21); + EXPECT_STREQ(static_cast(decoded_params[1].buf), "ls"); // exe + EXPECT_STREQ(static_cast(decoded_params[6].buf), "/root"); // cwd + EXPECT_STREQ(static_cast(decoded_params[13].buf), "ls"); // comm } -TEST(gvisor_parsers, parse_clone_e) -{ - char message[1024]; - char buffer[1024]; +TEST(gvisor_parsers, parse_clone_e) { + char message[1024]; + char buffer[1024]; - gvisor::syscall::Clone gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_CLONE; - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); + gvisor::syscall::Clone gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_CLONE; + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); - EXPECT_EQ(res.scap_events.size(), 1); + EXPECT_EQ(res.scap_events.size(), 1); - EXPECT_EQ(res.scap_events[0]->type, PPME_SYSCALL_CLONE_20_E); + EXPECT_EQ(res.scap_events[0]->type, PPME_SYSCALL_CLONE_20_E); - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 0); + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 0); } -TEST(gvisor_parsers, parse_clone_x) -{ - char message[1024]; - char buffer[1024]; - - gvisor::syscall::Clone gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_CLONE; - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); - context_data->set_process_name("ls"); - context_data->set_cwd("/root"); - gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); - exit->set_result(0); - - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); - - EXPECT_EQ(res.scap_events.size(), 1); - - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 21); - EXPECT_STREQ(static_cast(decoded_params[1].buf), "ls"); // exe - EXPECT_STREQ(static_cast(decoded_params[6].buf), "/root"); // cwd - EXPECT_STREQ(static_cast(decoded_params[13].buf), "ls"); // comm +TEST(gvisor_parsers, parse_clone_x) { + char message[1024]; + char buffer[1024]; + + gvisor::syscall::Clone gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_CLONE; + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); + context_data->set_process_name("ls"); + context_data->set_cwd("/root"); + gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); + exit->set_result(0); + + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); + + EXPECT_EQ(res.scap_events.size(), 1); + + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 21); + EXPECT_STREQ(static_cast(decoded_params[1].buf), "ls"); // exe + EXPECT_STREQ(static_cast(decoded_params[6].buf), "/root"); // cwd + EXPECT_STREQ(static_cast(decoded_params[13].buf), "ls"); // comm } -TEST(gvisor_parsers, parse_socketpair_e) -{ - char message[1024]; - char buffer[1024]; +TEST(gvisor_parsers, parse_socketpair_e) { + char message[1024]; + char buffer[1024]; - gvisor::syscall::SocketPair gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_SOCKETPAIR; - gvisor_evt.set_domain(995); - gvisor_evt.set_type(996); - gvisor_evt.set_protocol(997); - gvisor_evt.set_socket1(998); - gvisor_evt.set_socket2(999); + gvisor::syscall::SocketPair gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_SOCKETPAIR; + gvisor_evt.set_domain(995); + gvisor_evt.set_type(996); + gvisor_evt.set_protocol(997); + gvisor_evt.set_socket1(998); + gvisor_evt.set_socket2(999); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); - EXPECT_EQ(res.scap_events.size(), 1); + EXPECT_EQ(res.scap_events.size(), 1); - EXPECT_EQ(res.scap_events[0]->type, PPME_SOCKET_SOCKETPAIR_E); + EXPECT_EQ(res.scap_events[0]->type, PPME_SOCKET_SOCKETPAIR_E); - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 3); + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 3); - int32_t i32_val; + int32_t i32_val; - EXPECT_EQ(decoded_params[0].size, 4); - memcpy(&i32_val, decoded_params[0].buf, sizeof(i32_val)); - EXPECT_EQ(i32_val, 995); // domain + EXPECT_EQ(decoded_params[0].size, 4); + memcpy(&i32_val, decoded_params[0].buf, sizeof(i32_val)); + EXPECT_EQ(i32_val, 995); // domain - EXPECT_EQ(decoded_params[1].size, 4); - memcpy(&i32_val, decoded_params[1].buf, sizeof(i32_val)); - EXPECT_EQ(i32_val, 996); // type + EXPECT_EQ(decoded_params[1].size, 4); + memcpy(&i32_val, decoded_params[1].buf, sizeof(i32_val)); + EXPECT_EQ(i32_val, 996); // type - EXPECT_EQ(decoded_params[2].size, 4); - memcpy(&i32_val, decoded_params[2].buf, sizeof(i32_val)); - EXPECT_EQ(i32_val, 997); // protocol + EXPECT_EQ(decoded_params[2].size, 4); + memcpy(&i32_val, decoded_params[2].buf, sizeof(i32_val)); + EXPECT_EQ(i32_val, 997); // protocol } -TEST(gvisor_parsers, parse_socketpair_x) -{ - char message[1024]; - char buffer[1024]; +TEST(gvisor_parsers, parse_socketpair_x) { + char message[1024]; + char buffer[1024]; - gvisor::syscall::SocketPair gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_SOCKETPAIR; - gvisor_evt.set_domain(995); - gvisor_evt.set_type(996); - gvisor_evt.set_protocol(997); - gvisor_evt.set_socket1(998); - gvisor_evt.set_socket2(999); + gvisor::syscall::SocketPair gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_SOCKETPAIR; + gvisor_evt.set_domain(995); + gvisor_evt.set_type(996); + gvisor_evt.set_protocol(997); + gvisor_evt.set_socket1(998); + gvisor_evt.set_socket2(999); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); - gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); - exit->set_result(0); + gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); + exit->set_result(0); - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ("", res.error); - EXPECT_EQ(res.status, SCAP_SUCCESS); + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ("", res.error); + EXPECT_EQ(res.status, SCAP_SUCCESS); - EXPECT_EQ(res.scap_events.size(), 1); + EXPECT_EQ(res.scap_events.size(), 1); - EXPECT_EQ(res.scap_events[0]->type, PPME_SOCKET_SOCKETPAIR_X); + EXPECT_EQ(res.scap_events[0]->type, PPME_SOCKET_SOCKETPAIR_X); - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); - EXPECT_EQ(n, 5); + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(res.scap_events[0], decoded_params); + EXPECT_EQ(n, 5); - EXPECT_EQ(decoded_params[1].size, 8); - uint64_t u64_val; - memcpy(&u64_val, decoded_params[1].buf, sizeof(uint64_t)); - EXPECT_EQ(u64_val, 998); // fd1 + EXPECT_EQ(decoded_params[1].size, 8); + uint64_t u64_val; + memcpy(&u64_val, decoded_params[1].buf, sizeof(uint64_t)); + EXPECT_EQ(u64_val, 998); // fd1 - EXPECT_EQ(decoded_params[2].size, 8); - memcpy(&u64_val, decoded_params[2].buf, sizeof(uint64_t)); - EXPECT_EQ(u64_val, 999); // fd2 + EXPECT_EQ(decoded_params[2].size, 8); + memcpy(&u64_val, decoded_params[2].buf, sizeof(uint64_t)); + EXPECT_EQ(u64_val, 999); // fd2 } -TEST(gvisor_parsers, parse_container_start) -{ - char message[1024]; - char buffer[1024]; - - gvisor::container::Start gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_CONTAINER_START; - gvisor_evt.set_id("deadbeef"); - gvisor_evt.mutable_args()->Add("ls"); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_cwd("/root"); - - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - - EXPECT_EQ(res.scap_events.size(), 4); - uint16_t type; - memcpy(&type, &res.scap_events[0]->type, sizeof(type)); - EXPECT_EQ(type, PPME_SYSCALL_CLONE_20_E); - memcpy(&type, &res.scap_events[1]->type, sizeof(type)); - EXPECT_EQ(type, PPME_SYSCALL_CLONE_20_X); - memcpy(&type, &res.scap_events[2]->type, sizeof(type)); - EXPECT_EQ(type, PPME_SYSCALL_EXECVE_19_E); - memcpy(&type, &res.scap_events[3]->type, sizeof(type)); - EXPECT_EQ(type, PPME_SYSCALL_EXECVE_19_X); +TEST(gvisor_parsers, parse_container_start) { + char message[1024]; + char buffer[1024]; + + gvisor::container::Start gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_CONTAINER_START; + gvisor_evt.set_id("deadbeef"); + gvisor_evt.mutable_args()->Add("ls"); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_cwd("/root"); + + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + + EXPECT_EQ(res.scap_events.size(), 4); + uint16_t type; + memcpy(&type, &res.scap_events[0]->type, sizeof(type)); + EXPECT_EQ(type, PPME_SYSCALL_CLONE_20_E); + memcpy(&type, &res.scap_events[1]->type, sizeof(type)); + EXPECT_EQ(type, PPME_SYSCALL_CLONE_20_X); + memcpy(&type, &res.scap_events[2]->type, sizeof(type)); + EXPECT_EQ(type, PPME_SYSCALL_EXECVE_19_E); + memcpy(&type, &res.scap_events[3]->type, sizeof(type)); + EXPECT_EQ(type, PPME_SYSCALL_EXECVE_19_X); } -TEST(gvisor_parsers, unhandled_syscall) -{ - char message[1024]; - char buffer[1024]; +TEST(gvisor_parsers, unhandled_syscall) { + char message[1024]; + char buffer[1024]; - gvisor::syscall::Syscall gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_RAW; - gvisor_evt.set_sysno(999); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); + gvisor::syscall::Syscall gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_RAW; + gvisor_evt.set_sysno(999); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1024}; - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_NE(res.error.find("Unhandled syscall"), std::string::npos); - EXPECT_EQ(res.status, SCAP_NOT_SUPPORTED); + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_NE(res.error.find("Unhandled syscall"), std::string::npos); + EXPECT_EQ(res.status, SCAP_NOT_SUPPORTED); } -TEST(gvisor_parsers, small_buffer) -{ - char message[1024]; - char buffer[1024]; - - gvisor::syscall::Execve gvisor_evt; - uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; - gvisor_evt.set_sysno(__NR_execve); - gvisor_evt.set_pathname("/usr/bin/ls"); - gvisor_evt.mutable_argv()->Add("ls"); - auto *context_data = gvisor_evt.mutable_context_data(); - context_data->set_container_id("1234"); - context_data->set_cwd("/root"); - gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); - exit->set_result(0); - - uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); - - scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; - scap_sized_buffer scap_buf = {.buf = buffer, .size = 1}; - - scap_gvisor::parsers::parse_result res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ(res.status, SCAP_INPUT_TOO_SMALL); - scap_buf.size = res.size; - res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); - EXPECT_EQ(res.status, SCAP_SUCCESS); +TEST(gvisor_parsers, small_buffer) { + char message[1024]; + char buffer[1024]; + + gvisor::syscall::Execve gvisor_evt; + uint16_t message_type = gvisor::common::MessageType::MESSAGE_SYSCALL_EXECVE; + gvisor_evt.set_sysno(__NR_execve); + gvisor_evt.set_pathname("/usr/bin/ls"); + gvisor_evt.mutable_argv()->Add("ls"); + auto *context_data = gvisor_evt.mutable_context_data(); + context_data->set_container_id("1234"); + context_data->set_cwd("/root"); + gvisor::syscall::Exit *exit = gvisor_evt.mutable_exit(); + exit->set_result(0); + + uint32_t total_size = prepare_message(message, 1024, message_type, gvisor_evt); + + scap_const_sized_buffer gvisor_msg = {.buf = message, .size = total_size}; + scap_sized_buffer scap_buf = {.buf = buffer, .size = 1}; + + scap_gvisor::parsers::parse_result res = + scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ(res.status, SCAP_INPUT_TOO_SMALL); + scap_buf.size = res.size; + res = scap_gvisor::parsers::parse_gvisor_proto(10, gvisor_msg, scap_buf); + EXPECT_EQ(res.status, SCAP_SUCCESS); } -TEST(gvisor_parsers, procfs_entry) -{ - std::string not_json = "not a json string"; - uint32_t sandbox_id = 0xdeadbeef; +TEST(gvisor_parsers, procfs_entry) { + std::string not_json = "not a json string"; + uint32_t sandbox_id = 0xdeadbeef; - scap_gvisor::parsers::procfs_result res = scap_gvisor::parsers::parse_procfs_json(not_json, sandbox_id); - EXPECT_EQ(res.status, SCAP_FAILURE); + scap_gvisor::parsers::procfs_result res = + scap_gvisor::parsers::parse_procfs_json(not_json, sandbox_id); + EXPECT_EQ(res.status, SCAP_FAILURE); - std::string json = R"( + std::string json = R"( { "args": [ "bash" ], "clone_ts": 1655473752715788585, @@ -557,37 +558,36 @@ TEST(gvisor_parsers, procfs_entry) } )"; - res = scap_gvisor::parsers::parse_procfs_json(json, sandbox_id); - EXPECT_EQ(res.status, SCAP_SUCCESS); - EXPECT_EQ(res.tinfo.vtid, 1); - EXPECT_STREQ(res.tinfo.comm, "bash"); - EXPECT_STREQ(res.tinfo.exepath, "/usr/bin/bash"); - std::string args = std::string(res.tinfo.args, res.tinfo.args_len); - EXPECT_TRUE(args.find("bash") != std::string::npos); - std::string env = std::string(res.tinfo.env, res.tinfo.env_len); - EXPECT_TRUE(env.find("HOSTNAME=91e91fdd849d") != std::string::npos); - EXPECT_TRUE(env.find("TERM=xterm") != std::string::npos); - EXPECT_TRUE(env.find("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") != std::string::npos); - EXPECT_TRUE(env.find("HOME=/root") != std::string::npos); - - std::string json_missing_fields = "{\"exe\":\"/usr/bin/bash\"}\n"; - res = scap_gvisor::parsers::parse_procfs_json(json_missing_fields, sandbox_id); - EXPECT_EQ(res.status, SCAP_FAILURE); - EXPECT_STREQ(res.error.c_str(), "Missing json field or wrong type: cannot parse procfs entry"); - - std::string args_arr = "[ \"bash\" ]"; - std::string args_no_arr = "\"bash\""; - auto pos = json.find(args_arr); - json.replace(pos, args_arr.size(), args_no_arr); - res = scap_gvisor::parsers::parse_procfs_json(json, sandbox_id); - EXPECT_EQ(res.status, SCAP_FAILURE); - EXPECT_STREQ(res.error.c_str(), "Missing json field or wrong type: cannot parse procfs entry"); - + res = scap_gvisor::parsers::parse_procfs_json(json, sandbox_id); + EXPECT_EQ(res.status, SCAP_SUCCESS); + EXPECT_EQ(res.tinfo.vtid, 1); + EXPECT_STREQ(res.tinfo.comm, "bash"); + EXPECT_STREQ(res.tinfo.exepath, "/usr/bin/bash"); + std::string args = std::string(res.tinfo.args, res.tinfo.args_len); + EXPECT_TRUE(args.find("bash") != std::string::npos); + std::string env = std::string(res.tinfo.env, res.tinfo.env_len); + EXPECT_TRUE(env.find("HOSTNAME=91e91fdd849d") != std::string::npos); + EXPECT_TRUE(env.find("TERM=xterm") != std::string::npos); + EXPECT_TRUE(env.find("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") != + std::string::npos); + EXPECT_TRUE(env.find("HOME=/root") != std::string::npos); + + std::string json_missing_fields = "{\"exe\":\"/usr/bin/bash\"}\n"; + res = scap_gvisor::parsers::parse_procfs_json(json_missing_fields, sandbox_id); + EXPECT_EQ(res.status, SCAP_FAILURE); + EXPECT_STREQ(res.error.c_str(), "Missing json field or wrong type: cannot parse procfs entry"); + + std::string args_arr = "[ \"bash\" ]"; + std::string args_no_arr = "\"bash\""; + auto pos = json.find(args_arr); + json.replace(pos, args_arr.size(), args_no_arr); + res = scap_gvisor::parsers::parse_procfs_json(json, sandbox_id); + EXPECT_EQ(res.status, SCAP_FAILURE); + EXPECT_STREQ(res.error.c_str(), "Missing json field or wrong type: cannot parse procfs entry"); } -TEST(gvisor_parsers, config_socket) -{ - std::string config = R"( +TEST(gvisor_parsers, config_socket) { + std::string config = R"( { "trace_session": { "name": "Default", @@ -642,9 +642,9 @@ TEST(gvisor_parsers, config_socket) } )"; - scap_gvisor::parsers::config_result res; + scap_gvisor::parsers::config_result res; - res = scap_gvisor::parsers::parse_config(config); - EXPECT_EQ(res.status, SCAP_SUCCESS); - EXPECT_STREQ(res.socket_path.c_str(), "/tmp/gvisor.sock"); + res = scap_gvisor::parsers::parse_config(config); + EXPECT_EQ(res.status, SCAP_SUCCESS); + EXPECT_STREQ(res.socket_path.c_str(), "/tmp/gvisor.sock"); } diff --git a/test/libscap/test_suites/engines/gvisor/gvisor_platform.cpp b/test/libscap/test_suites/engines/gvisor/gvisor_platform.cpp index ab5d931680..b406ee0ee3 100644 --- a/test/libscap/test_suites/engines/gvisor/gvisor_platform.cpp +++ b/test/libscap/test_suites/engines/gvisor/gvisor_platform.cpp @@ -20,8 +20,7 @@ limitations under the License. #include #include -TEST(gvisor_platform, generate_sandbox_id) -{ +TEST(gvisor_platform, generate_sandbox_id) { char lasterr[SCAP_LASTERR_SIZE]; scap_gvisor::platform p(lasterr, "/the/root/path"); @@ -31,17 +30,20 @@ TEST(gvisor_platform, generate_sandbox_id) uint32_t insertions = 0; // insert sandboxes - id = p.get_numeric_sandbox_id("8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff817"); + id = p.get_numeric_sandbox_id( + "8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff817"); EXPECT_NE(id, 0); seen_ids.insert(id); EXPECT_EQ(seen_ids.size(), ++insertions); - uint32_t id_18 = p.get_numeric_sandbox_id("8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff818"); + uint32_t id_18 = p.get_numeric_sandbox_id( + "8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff818"); EXPECT_NE(id_18, 0); seen_ids.insert(id_18); EXPECT_EQ(seen_ids.size(), ++insertions); - id = p.get_numeric_sandbox_id("8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff819"); + id = p.get_numeric_sandbox_id( + "8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff819"); EXPECT_NE(id, 0); seen_ids.insert(id); EXPECT_EQ(seen_ids.size(), ++insertions); @@ -57,12 +59,14 @@ TEST(gvisor_platform, generate_sandbox_id) EXPECT_EQ(seen_ids.size(), ++insertions); // retrieve ID - id = p.get_numeric_sandbox_id("8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff818"); + id = p.get_numeric_sandbox_id( + "8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff818"); EXPECT_NE(id, 0); EXPECT_EQ(id_18, id); // release and retrieve p.release_sandbox_id("8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff818"); - id = p.get_numeric_sandbox_id("8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff820"); + id = p.get_numeric_sandbox_id( + "8d966e94e52551866762589eecdd9d44a9d9f87f27cd85af4cf45b7d3d2ff820"); EXPECT_NE(id, 0); } diff --git a/test/libscap/test_suites/engines/kmod/kmod.cpp b/test/libscap/test_suites/engines/kmod/kmod.cpp index 6a1cc4b420..d3ef47cfb6 100644 --- a/test/libscap/test_suites/engines/kmod/kmod.cpp +++ b/test/libscap/test_suites/engines/kmod/kmod.cpp @@ -7,12 +7,9 @@ #include #include -int remove_kmod(char* error_buf) -{ - if(syscall(__NR_delete_module, LIBSCAP_TEST_KERNEL_MODULE_NAME, O_NONBLOCK)) - { - switch(errno) - { +int remove_kmod(char* error_buf) { + if(syscall(__NR_delete_module, LIBSCAP_TEST_KERNEL_MODULE_NAME, O_NONBLOCK)) { + switch(errno) { case ENOENT: return EXIT_SUCCESS; @@ -21,11 +18,9 @@ int remove_kmod(char* error_buf) * case we wait until the module is detached. */ case EWOULDBLOCK: - for(int i = 0; i < 4; i++) - { + for(int i = 0; i < 4; i++) { int ret = syscall(__NR_delete_module, LIBSCAP_TEST_KERNEL_MODULE_NAME, O_NONBLOCK); - if(ret == 0 || errno == ENOENT) - { + if(ret == 0 || errno == ENOENT) { return EXIT_SUCCESS; } sleep(1); @@ -36,122 +31,134 @@ int remove_kmod(char* error_buf) case EBUSY: case EFAULT: case EPERM: - snprintf(error_buf, SCAP_LASTERR_SIZE, "Unable to remove kernel module. Errno message: %s, errno: %d\n", strerror(errno), errno); + snprintf(error_buf, + SCAP_LASTERR_SIZE, + "Unable to remove kernel module. Errno message: %s, errno: %d\n", + strerror(errno), + errno); return EXIT_FAILURE; default: - snprintf(error_buf, SCAP_LASTERR_SIZE, "Unexpected error code. Errno message: %s, errno: %d\n", strerror(errno), errno); + snprintf(error_buf, + SCAP_LASTERR_SIZE, + "Unexpected error code. Errno message: %s, errno: %d\n", + strerror(errno), + errno); return EXIT_FAILURE; } } return EXIT_SUCCESS; } -int insert_kmod(const char* kmod_path, char* error_buf) -{ +int insert_kmod(const char* kmod_path, char* error_buf) { /* Here we want to insert the module if we fail we need to abort the program. */ int fd = open(kmod_path, O_RDONLY); - if(fd < 0) - { - snprintf(error_buf, SCAP_LASTERR_SIZE, "Unable to open the kmod file. Errno message: %s, errno: %d\n", strerror(errno), errno); + if(fd < 0) { + snprintf(error_buf, + SCAP_LASTERR_SIZE, + "Unable to open the kmod file. Errno message: %s, errno: %d\n", + strerror(errno), + errno); return EXIT_FAILURE; } - if(syscall(__NR_finit_module, fd, "", 0)) - { - snprintf(error_buf, SCAP_LASTERR_SIZE, "Unable to inject the kmod. Errno message: %s, errno: %d\n", strerror(errno), errno); + if(syscall(__NR_finit_module, fd, "", 0)) { + snprintf(error_buf, + SCAP_LASTERR_SIZE, + "Unable to inject the kmod. Errno message: %s, errno: %d\n", + strerror(errno), + errno); return EXIT_FAILURE; } return EXIT_SUCCESS; } -scap_t* open_kmod_engine(char* error_buf, int32_t* rc, unsigned long buffer_dim, const char* kmod_path, std::unordered_set ppm_sc_set = {}) -{ +scap_t* open_kmod_engine(char* error_buf, + int32_t* rc, + unsigned long buffer_dim, + const char* kmod_path, + std::unordered_set ppm_sc_set = {}) { struct scap_open_args oargs {}; /* Remove previously inserted kernel module */ - if(remove_kmod(error_buf) != EXIT_SUCCESS) - { + if(remove_kmod(error_buf) != EXIT_SUCCESS) { return NULL; } /* Insert again the kernel module */ - if(insert_kmod(kmod_path, error_buf) != EXIT_SUCCESS) - { + if(insert_kmod(kmod_path, error_buf) != EXIT_SUCCESS) { return NULL; } /* If empty we fill with all syscalls */ - if(ppm_sc_set.empty()) - { - for(int i = 0; i < PPM_SC_MAX; i++) - { + if(ppm_sc_set.empty()) { + for(int i = 0; i < PPM_SC_MAX; i++) { oargs.ppm_sc_of_interest.ppm_sc[i] = 1; } - } - else - { - for(auto ppm_sc : ppm_sc_set) - { + } else { + for(auto ppm_sc : ppm_sc_set) { oargs.ppm_sc_of_interest.ppm_sc[ppm_sc] = 1; } } struct scap_kmod_engine_params kmod_params = { - .buffer_bytes_dim = buffer_dim, + .buffer_bytes_dim = buffer_dim, }; oargs.engine_params = &kmod_params; return scap_open(&oargs, &scap_kmod_engine, error_buf, rc); } -TEST(kmod, open_engine) -{ +TEST(kmod, open_engine) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; scap_close(h); } -TEST(kmod, wrong_buffer_dim) -{ +TEST(kmod, wrong_buffer_dim) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the buffer dimension is not a system page multiple, so we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) + << "the buffer dimension is not a system page multiple, so we should fail: " + << error_buffer << std::endl; } -/* This check is not so reliable, better than nothing but to be sure we need to obtain the producer and consumer positions from the drivers */ -TEST(kmod, events_not_overwritten) -{ +/* This check is not so reliable, better than nothing but to be sure we need to obtain the producer + * and consumer positions from the drivers */ +TEST(kmod, events_not_overwritten) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; check_event_is_not_overwritten(h); scap_close(h); } -TEST(kmod, read_in_order) -{ +TEST(kmod, read_in_order) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ - scap_t* h = open_kmod_engine(error_buffer, &ret, 1 * 1024 * 1024, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + scap_t* h = + open_kmod_engine(error_buffer, &ret, 1 * 1024 * 1024, LIBSCAP_TEST_KERNEL_MODULE_PATH); + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; check_event_order(h); scap_close(h); } -TEST(kmod, scap_stats_check) -{ +TEST(kmod, scap_stats_check) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; scap_stats stats; @@ -162,34 +169,34 @@ TEST(kmod, scap_stats_check) scap_close(h); } -TEST(kmod, double_scap_stats_call) -{ +TEST(kmod, double_scap_stats_call) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; scap_stats stats; ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS); - + ASSERT_EQ(scap_get_stats(h, &stats), SCAP_SUCCESS); ASSERT_GT(stats.n_evts, 0); /* Double call */ ASSERT_EQ(scap_get_stats(h, &stats), SCAP_SUCCESS); ASSERT_GT(stats.n_evts, 0); - + ASSERT_EQ(scap_stop_capture(h), SCAP_SUCCESS); scap_close(h); } -TEST(kmod, metrics_v2_check_per_CPU_stats) -{ +TEST(kmod, metrics_v2_check_per_CPU_stats) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; ssize_t num_online_CPUs = sysconf(_SC_NPROCESSORS_ONLN); @@ -205,56 +212,53 @@ TEST(kmod, metrics_v2_check_per_CPU_stats) uint32_t i = 0; ssize_t found = 0; char expected_name[METRIC_NAME_MAX] = ""; - snprintf(expected_name, METRIC_NAME_MAX, N_EVENTS_PER_DEVICE_PREFIX"%ld", found); + snprintf(expected_name, METRIC_NAME_MAX, N_EVENTS_PER_DEVICE_PREFIX "%ld", found); bool check_general_kernel_counters_presence = false; - while(i < nstats) - { + while(i < nstats) { // We check if `METRICS_V2_KERNEL_COUNTERS` are enabled as well - if(strncmp(stats_v2[i].name, N_EVENTS_PREFIX, sizeof(N_EVENTS_PREFIX)) == 0) - { + if(strncmp(stats_v2[i].name, N_EVENTS_PREFIX, sizeof(N_EVENTS_PREFIX)) == 0) { check_general_kernel_counters_presence = true; i++; continue; } // `sizeof(N_EVENTS_PER_DEVICE_PREFIX)-1` because we need to exclude the `\0` - if(strncmp(stats_v2[i].name, N_EVENTS_PER_DEVICE_PREFIX, sizeof(N_EVENTS_PER_DEVICE_PREFIX)-1) == 0) - { + if(strncmp(stats_v2[i].name, + N_EVENTS_PER_DEVICE_PREFIX, + sizeof(N_EVENTS_PER_DEVICE_PREFIX) - 1) == 0) { i++; // The next metric should be the number of drops - snprintf(expected_name, METRIC_NAME_MAX, N_DROPS_PER_DEVICE_PREFIX"%ld", found); - if(strncmp(stats_v2[i].name, N_DROPS_PER_DEVICE_PREFIX, sizeof(N_DROPS_PER_DEVICE_PREFIX)-1) == 0) - { + snprintf(expected_name, METRIC_NAME_MAX, N_DROPS_PER_DEVICE_PREFIX "%ld", found); + if(strncmp(stats_v2[i].name, + N_DROPS_PER_DEVICE_PREFIX, + sizeof(N_DROPS_PER_DEVICE_PREFIX) - 1) == 0) { i++; found++; - } - else - { + } else { FAIL() << "Missing CPU drops for CPU " << found; } - } - else - { + } else { i++; } } - ASSERT_TRUE(check_general_kernel_counters_presence) << "per-CPU counter are enabled but general kernel counters are not"; + ASSERT_TRUE(check_general_kernel_counters_presence) + << "per-CPU counter are enabled but general kernel counters are not"; - // This test could fail in case of rare race conditions in which the number of online CPUs changes - // between the scap_open and the `sysconf(_SC_NPROCESSORS_ONLN)` function. In CI we shouldn't have hot plugs so probably we - // can live with this. + // This test could fail in case of rare race conditions in which the number of online CPUs + // changes between the scap_open and the `sysconf(_SC_NPROCESSORS_ONLN)` function. In CI we + // shouldn't have hot plugs so probably we can live with this. ASSERT_EQ(num_online_CPUs, found) << "We didn't find the stats for all the CPUs"; scap_close(h); } -TEST(kmod, metrics_v2_check_results) -{ +TEST(kmod, metrics_v2_check_results) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; uint32_t flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS; uint32_t nstats; @@ -267,40 +271,36 @@ TEST(kmod, metrics_v2_check_results) std::unordered_set minimal_stats_name = {"n_evts"}; uint32_t i = 0; - for(const auto& stat_name : minimal_stats_name) - { - for(i = 0; i < nstats; i++) - { - if(stat_name.compare(stats_v2[i].name) == 0) - { + for(const auto& stat_name : minimal_stats_name) { + for(i = 0; i < nstats; i++) { + if(stat_name.compare(stats_v2[i].name) == 0) { break; } } - if(i == nstats) - { + if(i == nstats) { FAIL() << "unable to find stat '" << stat_name << "' into the array"; } } // Check per-CPU stats are not enabled since we didn't provide the flag. - for(i = 0; i < nstats; i++) - { - if(strncmp(stats_v2[i].name, N_EVENTS_PER_DEVICE_PREFIX, sizeof(N_EVENTS_PER_DEVICE_PREFIX)-1) == 0) - { - FAIL() << "per-CPU counters are enabled but we didn't provide the flag!"; - } + for(i = 0; i < nstats; i++) { + if(strncmp(stats_v2[i].name, + N_EVENTS_PER_DEVICE_PREFIX, + sizeof(N_EVENTS_PER_DEVICE_PREFIX) - 1) == 0) { + FAIL() << "per-CPU counters are enabled but we didn't provide the flag!"; + } } - + scap_close(h); } -TEST(kmod, double_metrics_v2_call) -{ +TEST(kmod, double_metrics_v2_call) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; uint32_t flags = METRICS_V2_KERNEL_COUNTERS; uint32_t nstats; @@ -314,16 +314,16 @@ TEST(kmod, double_metrics_v2_call) scap_get_stats_v2(h, flags, &nstats, &rc); ASSERT_EQ(rc, SCAP_SUCCESS); ASSERT_GT(nstats, 0); - + scap_close(h); } -TEST(kmod, metrics_v2_check_empty) -{ +TEST(kmod, metrics_v2_check_empty) { char error_buffer[SCAP_LASTERR_SIZE] = {0}; int ret = 0; scap_t* h = open_kmod_engine(error_buffer, &ret, 4 * 4096, LIBSCAP_TEST_KERNEL_MODULE_PATH); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open kmod engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open kmod engine: " << error_buffer << std::endl; uint32_t flags = 0; uint32_t nstats; diff --git a/test/libscap/test_suites/engines/modern_bpf/modern_bpf.cpp b/test/libscap/test_suites/engines/modern_bpf/modern_bpf.cpp index 3863b17a15..8b50651b99 100644 --- a/test/libscap/test_suites/engines/modern_bpf/modern_bpf.cpp +++ b/test/libscap/test_suites/engines/modern_bpf/modern_bpf.cpp @@ -8,46 +8,42 @@ static falcosecurity_log_severity severity_level = FALCOSECURITY_LOG_SEV_WARNING; -static void test_open_log_fn(const char* component, const char* msg, falcosecurity_log_severity sev) -{ - if(sev <= severity_level) - { - if(component!= NULL) - { +static void test_open_log_fn(const char* component, + const char* msg, + falcosecurity_log_severity sev) { + if(sev <= severity_level) { + if(component != NULL) { printf("%s: %s", component, msg); - } - else - { + } else { // libbpf logs have no components printf("%s", msg); } } } -scap_t* open_modern_bpf_engine(char* error_buf, int32_t* rc, unsigned long buffer_dim, uint16_t cpus_for_each_buffer, bool online_only, std::unordered_set ppm_sc_set = {}) -{ +scap_t* open_modern_bpf_engine(char* error_buf, + int32_t* rc, + unsigned long buffer_dim, + uint16_t cpus_for_each_buffer, + bool online_only, + std::unordered_set ppm_sc_set = {}) { struct scap_open_args oargs {}; /* If empty we fill with all syscalls */ - if(ppm_sc_set.empty()) - { - for(int i = 0; i < PPM_SC_MAX; i++) - { + if(ppm_sc_set.empty()) { + for(int i = 0; i < PPM_SC_MAX; i++) { oargs.ppm_sc_of_interest.ppm_sc[i] = 1; } - } - else - { - for(auto ppm_sc : ppm_sc_set) - { + } else { + for(auto ppm_sc : ppm_sc_set) { oargs.ppm_sc_of_interest.ppm_sc[ppm_sc] = 1; } } struct scap_modern_bpf_engine_params modern_bpf_params = { - .cpus_for_each_buffer = cpus_for_each_buffer, - .allocate_online_only = online_only, - .buffer_bytes_dim = buffer_dim, + .cpus_for_each_buffer = cpus_for_each_buffer, + .allocate_online_only = online_only, + .buffer_bytes_dim = buffer_dim, }; oargs.engine_params = &modern_bpf_params; oargs.log_fn = test_open_log_fn; @@ -55,167 +51,182 @@ scap_t* open_modern_bpf_engine(char* error_buf, int32_t* rc, unsigned long buffe return scap_open(&oargs, &scap_modern_bpf_engine, error_buf, rc); } -TEST(modern_bpf, open_engine) -{ +TEST(modern_bpf, open_engine) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* we want 1 ring buffer for each CPU */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 4 * 4096, 1, true); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open modern bpf engine: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open modern bpf engine: " << error_buffer << std::endl; scap_close(h); } -TEST(modern_bpf, empty_buffer_dim) -{ +TEST(modern_bpf, empty_buffer_dim) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 0, 1, true); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the buffer dimension is 0, we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) + << "the buffer dimension is 0, we should fail: " << error_buffer << std::endl; /* In case of failure the `scap_close(h)` is already called in the vtable `init` method */ } -TEST(modern_bpf, wrong_buffer_dim) -{ +TEST(modern_bpf, wrong_buffer_dim) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* ring buffer dim is not a multiple of PAGE_SIZE */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 + 4 * 4096, 1, true); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the buffer dimension is not a multiple of the page size, we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) + << "the buffer dimension is not a multiple of the page size, we should fail: " + << error_buffer << std::endl; } -TEST(modern_bpf, not_enough_possible_CPUs) -{ +TEST(modern_bpf, not_enough_possible_CPUs) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; ssize_t num_possible_CPUs = num_possible_cpus(); scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 4 * 4096, num_possible_CPUs + 1, false); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the CPUs required for each ring buffer are greater than the system possible CPUs, we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the CPUs required for each ring buffer are greater " + "than the system possible CPUs, we should fail: " + << error_buffer << std::endl; } -TEST(modern_bpf, not_enough_online_CPUs) -{ +TEST(modern_bpf, not_enough_online_CPUs) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; ssize_t num_online_CPUs = sysconf(_SC_NPROCESSORS_ONLN); scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 4 * 4096, num_online_CPUs + 1, true); - ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the CPUs required for each ring buffer are greater than the system online CPUs, we should fail: " << error_buffer << std::endl; + ASSERT_TRUE(!h || ret != SCAP_SUCCESS) << "the CPUs required for each ring buffer are greater " + "than the system online CPUs, we should fail: " + << error_buffer << std::endl; } -TEST(modern_bpf, one_buffer_per_possible_CPU) -{ +TEST(modern_bpf, one_buffer_per_possible_CPU) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 4 * 4096, 1, false); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open modern bpf engine with one ring buffer per CPU: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open modern bpf engine with one ring buffer per CPU: " << error_buffer + << std::endl; ssize_t num_possible_CPUs = num_possible_cpus(); uint32_t num_expected_rings = scap_get_ndevs(h); - ASSERT_EQ(num_expected_rings, num_possible_CPUs) << "we should have a ring buffer for every possible CPU!" << std::endl; + ASSERT_EQ(num_expected_rings, num_possible_CPUs) + << "we should have a ring buffer for every possible CPU!" << std::endl; check_event_is_not_overwritten(h); scap_close(h); } -TEST(modern_bpf, one_buffer_every_two_possible_CPUs) -{ +TEST(modern_bpf, one_buffer_every_two_possible_CPUs) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 4 * 4096, 2, false); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open modern bpf engine with one ring buffer every 2 CPUs: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open modern bpf engine with one ring buffer every 2 CPUs: " + << error_buffer << std::endl; ssize_t num_possible_CPUs = num_possible_cpus(); uint32_t num_expected_rings = num_possible_CPUs / 2; - if(num_possible_CPUs % 2 != 0) - { + if(num_possible_CPUs % 2 != 0) { num_expected_rings++; } uint32_t num_rings = scap_get_ndevs(h); - ASSERT_EQ(num_rings, num_expected_rings) << "we should have one ring buffer every 2 CPUs!" << std::endl; + ASSERT_EQ(num_rings, num_expected_rings) + << "we should have one ring buffer every 2 CPUs!" << std::endl; check_event_is_not_overwritten(h); scap_close(h); } -TEST(modern_bpf, one_buffer_shared_between_all_possible_CPUs_with_special_value) -{ +TEST(modern_bpf, one_buffer_shared_between_all_possible_CPUs_with_special_value) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* `0` is a special value that means one single shared ring buffer */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 4 * 4096, 0, false); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; uint32_t num_rings = scap_get_ndevs(h); - ASSERT_EQ(num_rings, 1) << "we should have only one ring buffer shared between all CPUs!" << std::endl; + ASSERT_EQ(num_rings, 1) << "we should have only one ring buffer shared between all CPUs!" + << std::endl; check_event_is_not_overwritten(h); scap_close(h); } /* In this test we don't need to check for buffer corruption with `check_event_is_not_overwritten` - * we have already done it in the previous test `one_buffer_shared_between_all_CPUs_with_special_value`. + * we have already done it in the previous test + * `one_buffer_shared_between_all_CPUs_with_special_value`. */ -TEST(modern_bpf, one_buffer_shared_between_all_online_CPUs_with_explicit_CPUs_number) -{ +TEST(modern_bpf, one_buffer_shared_between_all_online_CPUs_with_explicit_CPUs_number) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; ssize_t num_possible_CPUs = sysconf(_SC_NPROCESSORS_ONLN); scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 4 * 4096, num_possible_CPUs, true); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; uint32_t num_rings = scap_get_ndevs(h); - ASSERT_EQ(num_rings, 1) << "we should have only one ring buffer shared between all CPUs!" << std::endl; + ASSERT_EQ(num_rings, 1) << "we should have only one ring buffer shared between all CPUs!" + << std::endl; scap_close(h); } -TEST(modern_bpf, read_in_order_one_buffer_per_online_CPU) -{ +TEST(modern_bpf, read_in_order_one_buffer_per_online_CPU) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 1, true); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open modern bpf engine with one ring buffer per CPU: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open modern bpf engine with one ring buffer per CPU: " << error_buffer + << std::endl; check_event_order(h); scap_close(h); } -TEST(modern_bpf, read_in_order_one_buffer_every_two_online_CPUs) -{ +TEST(modern_bpf, read_in_order_one_buffer_every_two_online_CPUs) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 2, true); - ASSERT_FALSE(!h || ret != SCAP_SUCCESS) << "unable to open modern bpf engine with one ring buffer every 2 CPUs: " << error_buffer << std::endl; + ASSERT_FALSE(!h || ret != SCAP_SUCCESS) + << "unable to open modern bpf engine with one ring buffer every 2 CPUs: " + << error_buffer << std::endl; check_event_order(h); scap_close(h); } -TEST(modern_bpf, read_in_order_one_buffer_shared_between_all_possible_CPUs) -{ +TEST(modern_bpf, read_in_order_one_buffer_shared_between_all_possible_CPUs) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 0, false); - ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; check_event_order(h); scap_close(h); } -TEST(modern_bpf, scap_stats_check) -{ +TEST(modern_bpf, scap_stats_check) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 0, false); - ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; scap_stats stats; @@ -226,13 +237,14 @@ TEST(modern_bpf, scap_stats_check) scap_close(h); } -TEST(modern_bpf, double_scap_stats_call) -{ +TEST(modern_bpf, double_scap_stats_call) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 0, false); - ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; scap_stats stats; ASSERT_EQ(scap_start_capture(h), SCAP_SUCCESS); @@ -248,12 +260,13 @@ TEST(modern_bpf, double_scap_stats_call) scap_close(h); } -TEST(modern_bpf, metrics_v2_check_per_CPU_stats) -{ +TEST(modern_bpf, metrics_v2_check_per_CPU_stats) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 0, false); - ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; ssize_t num_possible_CPUs = num_possible_cpus(); @@ -269,57 +282,55 @@ TEST(modern_bpf, metrics_v2_check_per_CPU_stats) uint32_t i = 0; ssize_t found = 0; char expected_name[METRIC_NAME_MAX] = ""; - snprintf(expected_name, METRIC_NAME_MAX, N_EVENTS_PER_CPU_PREFIX"%ld", found); + snprintf(expected_name, METRIC_NAME_MAX, N_EVENTS_PER_CPU_PREFIX "%ld", found); bool check_general_kernel_counters_presence = false; - while(i < nstats) - { + while(i < nstats) { // We check if `METRICS_V2_KERNEL_COUNTERS` are enabled as well - if(strncmp(stats_v2[i].name, N_EVENTS_PREFIX, sizeof(N_EVENTS_PREFIX)) == 0) - { + if(strncmp(stats_v2[i].name, N_EVENTS_PREFIX, sizeof(N_EVENTS_PREFIX)) == 0) { check_general_kernel_counters_presence = true; i++; continue; } // `sizeof(N_EVENTS_PER_CPU_PREFIX)-1` because we need to exclude the `\0` - if(strncmp(stats_v2[i].name, N_EVENTS_PER_CPU_PREFIX, sizeof(N_EVENTS_PER_CPU_PREFIX)-1) == 0) - { + if(strncmp(stats_v2[i].name, + N_EVENTS_PER_CPU_PREFIX, + sizeof(N_EVENTS_PER_CPU_PREFIX) - 1) == 0) { i++; // The next metric should be the number of drops - snprintf(expected_name, METRIC_NAME_MAX, N_DROPS_PER_CPU_PREFIX"%ld", found); - if(strncmp(stats_v2[i].name, N_DROPS_PER_CPU_PREFIX, sizeof(N_DROPS_PER_CPU_PREFIX)-1) == 0) - { + snprintf(expected_name, METRIC_NAME_MAX, N_DROPS_PER_CPU_PREFIX "%ld", found); + if(strncmp(stats_v2[i].name, + N_DROPS_PER_CPU_PREFIX, + sizeof(N_DROPS_PER_CPU_PREFIX) - 1) == 0) { i++; found++; - } - else - { + } else { FAIL() << "Missing CPU drops for CPU " << found; } - } - else - { + } else { i++; } } - ASSERT_TRUE(check_general_kernel_counters_presence) << "per-CPU counter are enabled but general kernel counters are not"; + ASSERT_TRUE(check_general_kernel_counters_presence) + << "per-CPU counter are enabled but general kernel counters are not"; - // This test could fail in case of rare race conditions in which the number of available CPUs changes - // between the scap_open and the `num_possible_cpus` function. In CI we shouldn't have hot plugs so probably we - // can live with this. + // This test could fail in case of rare race conditions in which the number of available CPUs + // changes between the scap_open and the `num_possible_cpus` function. In CI we shouldn't have + // hot plugs so probably we can live with this. ASSERT_EQ(num_possible_CPUs, found) << "We didn't find the stats for all the CPUs"; scap_close(h); } -TEST(modern_bpf, metrics_v2_check_results) -{ +TEST(modern_bpf, metrics_v2_check_results) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 0, false); - ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; uint32_t flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS; uint32_t nstats; @@ -330,47 +341,48 @@ TEST(modern_bpf, metrics_v2_check_results) /* These names should always be available */ std::unordered_set minimal_stats_name = {"n_evts"}; - if (scap_get_bpf_stats_enabled()) - { - minimal_stats_name.insert({"sys_enter.run_cnt", "sys_enter.run_time_ns", "sys_exit.run_cnt", "sys_exit.run_time_ns", "signal_deliver.run_cnt", "signal_deliver.run_time_ns"}); + if(scap_get_bpf_stats_enabled()) { + minimal_stats_name.insert({"sys_enter.run_cnt", + "sys_enter.run_time_ns", + "sys_exit.run_cnt", + "sys_exit.run_time_ns", + "signal_deliver.run_cnt", + "signal_deliver.run_time_ns"}); } uint32_t i = 0; - for(const auto& stat_name : minimal_stats_name) - { - for(i = 0; i < nstats; i++) - { - if(stat_name.compare(stats_v2[i].name) == 0) - { + for(const auto& stat_name : minimal_stats_name) { + for(i = 0; i < nstats; i++) { + if(stat_name.compare(stats_v2[i].name) == 0) { break; } } - if(i == nstats) - { + if(i == nstats) { FAIL() << "unable to find stat '" << stat_name << "' into the array"; } } // Check per-CPU stats are not enabled since we didn't provide the flag. - for(i = 0; i < nstats; i++) - { - if(strncmp(stats_v2[i].name, N_EVENTS_PER_CPU_PREFIX, sizeof(N_EVENTS_PER_CPU_PREFIX)-1) == 0) - { - FAIL() << "per-CPU counters are enabled but we didn't provide the flag!"; - } + for(i = 0; i < nstats; i++) { + if(strncmp(stats_v2[i].name, + N_EVENTS_PER_CPU_PREFIX, + sizeof(N_EVENTS_PER_CPU_PREFIX) - 1) == 0) { + FAIL() << "per-CPU counters are enabled but we didn't provide the flag!"; + } } - + scap_close(h); } -TEST(modern_bpf, metrics_v2_check_empty) -{ +TEST(modern_bpf, metrics_v2_check_empty) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 0, false); - ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; uint32_t flags = 0; uint32_t nstats; @@ -381,13 +393,14 @@ TEST(modern_bpf, metrics_v2_check_empty) scap_close(h); } -TEST(modern_bpf, double_metrics_v2_call) -{ +TEST(modern_bpf, double_metrics_v2_call) { char error_buffer[FILENAME_MAX] = {0}; int ret = 0; /* We use buffers of 1 MB to be sure that we don't have drops */ scap_t* h = open_modern_bpf_engine(error_buffer, &ret, 1 * 1024 * 1024, 0, false); - ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) << "unable to open modern bpf engine with one single shared ring buffer: " << error_buffer << std::endl; + ASSERT_EQ(!h || ret != SCAP_SUCCESS, false) + << "unable to open modern bpf engine with one single shared ring buffer: " + << error_buffer << std::endl; uint32_t flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS; uint32_t nstats; diff --git a/test/libscap/test_suites/userspace/common_strl.cpp b/test/libscap/test_suites/userspace/common_strl.cpp index eec365fde7..4c8731d039 100644 --- a/test/libscap/test_suites/userspace/common_strl.cpp +++ b/test/libscap/test_suites/userspace/common_strl.cpp @@ -22,21 +22,20 @@ limitations under the License. static const char* s_10_chars = "0123456789"; static const char* s_20_chars = "abcdefghijklmnopqrst"; -TEST(common_strl, strlcat_input) -{ - char buf[256]; - size_t res; +TEST(common_strl, strlcat_input) { + char buf[256]; + size_t res; - strlcpy(buf, s_10_chars, sizeof(buf)); + strlcpy(buf, s_10_chars, sizeof(buf)); - res = strlcat(buf, s_20_chars, sizeof(buf)); - ASSERT_EQ(res, 30); - ASSERT_STREQ(buf, "0123456789abcdefghijklmnopqrst"); + res = strlcat(buf, s_20_chars, sizeof(buf)); + ASSERT_EQ(res, 30); + ASSERT_STREQ(buf, "0123456789abcdefghijklmnopqrst"); - strlcpy(buf, s_10_chars, sizeof(buf)); + strlcpy(buf, s_10_chars, sizeof(buf)); - res = strlcat(buf, s_20_chars, 30); - ASSERT_EQ(res, 30); - ASSERT_STREQ(buf, "0123456789abcdefghijklmnopqrs"); - ASSERT_EQ(strlen(buf), 29); + res = strlcat(buf, s_20_chars, 30); + ASSERT_EQ(res, 30); + ASSERT_STREQ(buf, "0123456789abcdefghijklmnopqrs"); + ASSERT_EQ(strlen(buf), 29); } diff --git a/test/libscap/test_suites/userspace/event_table.cpp b/test/libscap/test_suites/userspace/event_table.cpp index 4cf5876c2e..f1cc0bef35 100644 --- a/test/libscap/test_suites/userspace/event_table.cpp +++ b/test/libscap/test_suites/userspace/event_table.cpp @@ -2,8 +2,7 @@ #include #include -TEST(event_table, scap_get_syscall_category_from_event) -{ +TEST(event_table, scap_get_syscall_category_from_event) { ASSERT_EQ(scap_get_syscall_category_from_event(PPME_CONTAINER_JSON_2_E), EC_PROCESS); ASSERT_EQ(scap_get_syscall_category_from_event(PPME_SYSCALL_EXECVE_17_E), EC_PROCESS); ASSERT_EQ(scap_get_syscall_category_from_event(PPME_MESOS_X), EC_UNKNOWN); @@ -12,8 +11,7 @@ TEST(event_table, scap_get_syscall_category_from_event) ASSERT_EQ(scap_get_syscall_category_from_event(PPME_SCHEDSWITCH_1_E), EC_SCHEDULER); } -TEST(event_table, scap_get_event_category_from_event) -{ +TEST(event_table, scap_get_event_category_from_event) { ASSERT_EQ(scap_get_event_category_from_event(PPME_CONTAINER_JSON_2_E), EC_METAEVENT); ASSERT_EQ(scap_get_event_category_from_event(PPME_SYSCALL_EXECVE_17_E), EC_SYSCALL); ASSERT_EQ(scap_get_event_category_from_event(PPME_MESOS_X), EC_UNKNOWN); @@ -26,37 +24,31 @@ TEST(event_table, scap_get_event_category_from_event) * This test will not pass if we forget to update the event table * with one of these event categories! */ -TEST(event_table, check_events_category) -{ +TEST(event_table, check_events_category) { int num_syscall_events = 0; int num_tracepoint_events = 0; int num_metaevents = 0; int num_plugin_events = 0; int num_unknown_events = 0; int overlaps = 0; - for(int event_num = 0; event_num < PPM_EVENT_MAX; event_num++) - { - auto cat = scap_get_event_category_from_event((ppm_event_code) event_num); - if(cat & EC_SYSCALL) - { + for(int event_num = 0; event_num < PPM_EVENT_MAX; event_num++) { + auto cat = scap_get_event_category_from_event((ppm_event_code)event_num); + if(cat & EC_SYSCALL) { overlaps++; num_syscall_events++; } - if(cat & EC_TRACEPOINT) - { + if(cat & EC_TRACEPOINT) { overlaps++; num_tracepoint_events++; } - if(cat & EC_METAEVENT) - { + if(cat & EC_METAEVENT) { overlaps++; num_metaevents++; } - if(cat & EC_PLUGIN) - { + if(cat & EC_PLUGIN) { overlaps++; num_plugin_events++; } @@ -64,25 +56,20 @@ TEST(event_table, check_events_category) /* Please note this is not an `&` but an `==` if one event has * the `EC_UNKNOWN` category, it must have only this category! */ - if(cat == EC_UNKNOWN) - { + if(cat == EC_UNKNOWN) { overlaps++; num_unknown_events++; } - + // note: most of the event types will have only one category, so this // would just be a ++ followed by a --. For those having overlapping // categories, we'll find the overlaps counter being incremented for real. overlaps--; } - auto num_total_events = num_syscall_events - + num_tracepoint_events - + num_metaevents - + num_plugin_events - + num_unknown_events - - overlaps; - ASSERT_EQ(overlaps, 0); // for now, we want events to have 1 category only + auto num_total_events = num_syscall_events + num_tracepoint_events + num_metaevents + + num_plugin_events + num_unknown_events - overlaps; + ASSERT_EQ(overlaps, 0); // for now, we want events to have 1 category only ASSERT_EQ(num_syscall_events, SYSCALL_EVENTS_NUM); ASSERT_EQ(num_tracepoint_events, TRACEPOINT_EVENTS_NUM); ASSERT_EQ(num_metaevents, METAEVENTS_NUM); @@ -104,13 +91,10 @@ TEST(event_table, check_events_category) * Here we want to check that all events have a unique syscall category since * the lowest bits are used as an enum! */ -TEST(event_table, check_unique_events_syscall_category) -{ +TEST(event_table, check_unique_events_syscall_category) { int event_num = 0; - for(event_num = 0; event_num < PPM_EVENT_MAX; event_num++) - { - switch(scap_get_syscall_category_from_event((ppm_event_code)event_num)) - { + for(event_num = 0; event_num < PPM_EVENT_MAX; event_num++) { + switch(scap_get_syscall_category_from_event((ppm_event_code)event_num)) { case EC_UNKNOWN: case EC_OTHER: case EC_FILE: @@ -143,49 +127,43 @@ TEST(event_table, check_unique_events_syscall_category) ASSERT_EQ(event_num, PPM_EVENT_MAX); } -TEST(event_table, check_event_names) -{ +TEST(event_table, check_event_names) { std::map event_names_count; - for(int evt = 0; evt < PPM_EVENT_MAX; evt++) - { + for(int evt = 0; evt < PPM_EVENT_MAX; evt++) { struct ppm_event_info info = scap_get_event_info_table()[evt]; - if(info.flags & EF_OLD_VERSION) - { + if(info.flags & EF_OLD_VERSION) { continue; } event_names_count[info.name]++; } - for(const auto& evt : event_names_count) - { + for(const auto& evt : event_names_count) { /* NA occurrences should be equal to unknown events number, so more than 2 */ - if(evt.first.compare("NA") != 0) - { + if(evt.first.compare("NA") != 0) { /* all events that use exit and enter events should have `evt.second == 2` * while events paired with a `NA` event should have `evt.second == 1` */ - ASSERT_TRUE(evt.second <= 2) << "[fail] " << evt.first << " = " << evt.second << std::endl; + ASSERT_TRUE(evt.second <= 2) + << "[fail] " << evt.first << " = " << evt.second << std::endl; } } } -TEST(event_table, check_usage_of_EC_UNKNOWN_flag) -{ +TEST(event_table, check_usage_of_EC_UNKNOWN_flag) { /* Every time an event is marked with the `EC_UNKNOWN` flag we should use `NA` as its name */ std::string unknown_name = "NA"; - for(int evt = 0; evt < PPM_EVENT_MAX; evt++) - { - if(unknown_name.compare(scap_get_event_info_table()[evt].name) == 0) - { - ASSERT_TRUE(scap_get_syscall_category_from_event((ppm_event_code)evt) == EC_UNKNOWN) << "[fail] event " << evt << " should have the EC_UNKNOWN flag"; + for(int evt = 0; evt < PPM_EVENT_MAX; evt++) { + if(unknown_name.compare(scap_get_event_info_table()[evt].name) == 0) { + ASSERT_TRUE(scap_get_syscall_category_from_event((ppm_event_code)evt) == EC_UNKNOWN) + << "[fail] event " << evt << " should have the EC_UNKNOWN flag"; } - if(scap_get_syscall_category_from_event((ppm_event_code)evt) == EC_UNKNOWN) - { - ASSERT_TRUE(unknown_name.compare(scap_get_event_info_table()[evt].name) == 0) << "[fail] event " << evt << " should have NA as its name"; + if(scap_get_syscall_category_from_event((ppm_event_code)evt) == EC_UNKNOWN) { + ASSERT_TRUE(unknown_name.compare(scap_get_event_info_table()[evt].name) == 0) + << "[fail] event " << evt << " should have NA as its name"; } } } diff --git a/test/libscap/test_suites/userspace/linux/scap_cgroup.cpp b/test/libscap/test_suites/userspace/linux/scap_cgroup.cpp index 34cb9b9257..43e9a2b1d2 100644 --- a/test/libscap/test_suites/userspace/linux/scap_cgroup.cpp +++ b/test/libscap/test_suites/userspace/linux/scap_cgroup.cpp @@ -20,44 +20,55 @@ limitations under the License. #include #include -TEST(cgroups, path_relative) -{ +TEST(cgroups, path_relative) { char final_path[4096]; const char* prefix = "/1/2/3"; const char* path = "/../../../init.scope"; size_t prefix_len = 0; size_t path_strip_len = 0; ASSERT_EQ(scap_cgroup_prefix_path(prefix, path, &prefix_len, &path_strip_len), SCAP_SUCCESS); - snprintf(final_path, sizeof(final_path), "%.*s%s", (int)prefix_len, prefix, path + path_strip_len); - ASSERT_STREQ(final_path,"/init.scope"); + snprintf(final_path, + sizeof(final_path), + "%.*s%s", + (int)prefix_len, + prefix, + path + path_strip_len); + ASSERT_STREQ(final_path, "/init.scope"); } -TEST(cgroups, path_relative_with_final_slash) -{ +TEST(cgroups, path_relative_with_final_slash) { char final_path[4096]; const char* prefix = "/1/2/3/"; const char* path = "/../../../init.scope"; size_t prefix_len = 0; size_t path_strip_len = 0; ASSERT_EQ(scap_cgroup_prefix_path(prefix, path, &prefix_len, &path_strip_len), SCAP_SUCCESS); - snprintf(final_path, sizeof(final_path), "%.*s%s", (int)prefix_len, prefix, path + path_strip_len); - ASSERT_STREQ(final_path,"/1/init.scope"); + snprintf(final_path, + sizeof(final_path), + "%.*s%s", + (int)prefix_len, + prefix, + path + path_strip_len); + ASSERT_STREQ(final_path, "/1/init.scope"); } -TEST(cgroups, path_absolute) -{ +TEST(cgroups, path_absolute) { char final_path[4096]; const char* prefix = "/1/2/3"; const char* path = "/absolute"; size_t prefix_len = 0; size_t path_strip_len = 0; ASSERT_EQ(scap_cgroup_prefix_path(prefix, path, &prefix_len, &path_strip_len), SCAP_SUCCESS); - snprintf(final_path, sizeof(final_path), "%.*s%s", (int)prefix_len, prefix, path + path_strip_len); - ASSERT_STREQ(final_path,"/1/2/3/absolute"); + snprintf(final_path, + sizeof(final_path), + "%.*s%s", + (int)prefix_len, + prefix, + path + path_strip_len); + ASSERT_STREQ(final_path, "/1/2/3/absolute"); } -TEST(cgroups, prefix_empty) -{ +TEST(cgroups, prefix_empty) { const char* prefix = ""; const char* path = "/../../absolute"; size_t prefix_len = 0; @@ -65,14 +76,18 @@ TEST(cgroups, prefix_empty) ASSERT_EQ(scap_cgroup_prefix_path(prefix, path, &prefix_len, &path_strip_len), SCAP_FAILURE); } -TEST(cgroups, path_empty) -{ +TEST(cgroups, path_empty) { char final_path[4096]; const char* prefix = "/1/2/3"; const char* path = ""; size_t prefix_len = 0; size_t path_strip_len = 0; ASSERT_EQ(scap_cgroup_prefix_path(prefix, path, &prefix_len, &path_strip_len), SCAP_SUCCESS); - snprintf(final_path, sizeof(final_path), "%.*s%s", (int)prefix_len, prefix, path + path_strip_len); - ASSERT_STREQ(final_path,"/1/2/3"); + snprintf(final_path, + sizeof(final_path), + "%.*s%s", + (int)prefix_len, + prefix, + path + path_strip_len); + ASSERT_STREQ(final_path, "/1/2/3"); } diff --git a/test/libscap/test_suites/userspace/ppm_sc_names_table.cpp b/test/libscap/test_suites/userspace/ppm_sc_names_table.cpp index f134a3b15e..b5dd65edcf 100644 --- a/test/libscap/test_suites/userspace/ppm_sc_names_table.cpp +++ b/test/libscap/test_suites/userspace/ppm_sc_names_table.cpp @@ -1,8 +1,7 @@ #include #include -TEST(ppm_sc_names, scap_get_ppm_sc_name) -{ +TEST(ppm_sc_names, scap_get_ppm_sc_name) { /* First entry in the table */ ASSERT_STREQ(scap_get_ppm_sc_name(PPM_SC_UNKNOWN), "unknown"); diff --git a/test/libscap/test_suites/userspace/scap_event.cpp b/test/libscap/test_suites/userspace/scap_event.cpp index e674226c8a..863ff357a2 100644 --- a/test/libscap/test_suites/userspace/scap_event.cpp +++ b/test/libscap/test_suites/userspace/scap_event.cpp @@ -20,134 +20,150 @@ limitations under the License. #include // fills the buffer with ASCII data to catch bugs -static void fill_buffer(scap_sized_buffer buf) -{ - char *cbuf = static_cast(buf.buf); - size_t i = 0; - for (char upper = 'A'; upper < 'Z'; upper++) { - for (char lower = 'a'; lower < 'z'; lower++) { - for (char digit = '0'; digit < '9'; digit++) { - if (i == buf.size) return; - cbuf[i] = upper; - i++; - if (i == buf.size) return; - cbuf[i] = lower; - i++; - if (i == buf.size) return; - cbuf[i] = digit; - i++; - } - } - } +static void fill_buffer(scap_sized_buffer buf) { + char *cbuf = static_cast(buf.buf); + size_t i = 0; + for(char upper = 'A'; upper < 'Z'; upper++) { + for(char lower = 'a'; lower < 'z'; lower++) { + for(char digit = '0'; digit < '9'; digit++) { + if(i == buf.size) + return; + cbuf[i] = upper; + i++; + if(i == buf.size) + return; + cbuf[i] = lower; + i++; + if(i == buf.size) + return; + cbuf[i] = digit; + i++; + } + } + } } -// This function behaves exactly like scap_event_encode_params but it will allocate the event and return it by setting the event pointer. -static int32_t scap_event_generate(scap_evt **event, char *error, ppm_event_code event_type, uint32_t n, ...) -{ - scap_sized_buffer event_buf = {NULL, 0}; - size_t event_size; - va_list args; - va_start(args, n); - int32_t ret = scap_event_encode_params_v(event_buf, &event_size, error, event_type, n, args); - va_end(args); - - if(ret != SCAP_INPUT_TOO_SMALL) { - if (ret == SCAP_SUCCESS) { - snprintf(error, SCAP_LASTERR_SIZE, "Could not generate event. Expected SCAP_INPUT_TOO_SMALL, got SCAP_SUCCESS for event type %d with %d args", event_type, n); - } - return SCAP_FAILURE; - } - - event_buf.buf = malloc(event_size); - event_buf.size = event_size; - - fill_buffer(event_buf); - - if(event_buf.buf == NULL) { - snprintf(error, SCAP_LASTERR_SIZE, "Could not generate event. Allocation failed for %zu bytes", event_size); - return SCAP_FAILURE; - } - - va_start(args, n); - ret = scap_event_encode_params_v(event_buf, &event_size, error, event_type, n, args); - va_end(args); - - if(ret != SCAP_SUCCESS) { - free(event_buf.buf); - event_buf.size = 0; - } - - *event = (scap_evt*)event_buf.buf; - - return ret; +// This function behaves exactly like scap_event_encode_params but it will allocate the event and +// return it by setting the event pointer. +static int32_t scap_event_generate(scap_evt **event, + char *error, + ppm_event_code event_type, + uint32_t n, + ...) { + scap_sized_buffer event_buf = {NULL, 0}; + size_t event_size; + va_list args; + va_start(args, n); + int32_t ret = scap_event_encode_params_v(event_buf, &event_size, error, event_type, n, args); + va_end(args); + + if(ret != SCAP_INPUT_TOO_SMALL) { + if(ret == SCAP_SUCCESS) { + snprintf(error, + SCAP_LASTERR_SIZE, + "Could not generate event. Expected SCAP_INPUT_TOO_SMALL, got SCAP_SUCCESS " + "for event type %d with %d args", + event_type, + n); + } + return SCAP_FAILURE; + } + + event_buf.buf = malloc(event_size); + event_buf.size = event_size; + + fill_buffer(event_buf); + + if(event_buf.buf == NULL) { + snprintf(error, + SCAP_LASTERR_SIZE, + "Could not generate event. Allocation failed for %zu bytes", + event_size); + return SCAP_FAILURE; + } + + va_start(args, n); + ret = scap_event_encode_params_v(event_buf, &event_size, error, event_type, n, args); + va_end(args); + + if(ret != SCAP_SUCCESS) { + free(event_buf.buf); + event_buf.size = 0; + } + + *event = (scap_evt *)event_buf.buf; + + return ret; } -TEST(scap_event, empty_clone) -{ - char scap_error[SCAP_LASTERR_SIZE]; - scap_evt *maybe_evt; - uint32_t status = scap_event_generate(&maybe_evt, scap_error, PPME_SYSCALL_CLONE_20_E, 0); - ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; - ASSERT_NE(maybe_evt, nullptr); - std::unique_ptr evt {maybe_evt, free}; +TEST(scap_event, empty_clone) { + char scap_error[SCAP_LASTERR_SIZE]; + scap_evt *maybe_evt; + uint32_t status = scap_event_generate(&maybe_evt, scap_error, PPME_SYSCALL_CLONE_20_E, 0); + ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; + ASSERT_NE(maybe_evt, nullptr); + std::unique_ptr evt{maybe_evt, free}; - EXPECT_EQ(evt->nparams, 0); + EXPECT_EQ(evt->nparams, 0); - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(evt.get(), decoded_params); - EXPECT_EQ(n, 0); + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(evt.get(), decoded_params); + EXPECT_EQ(n, 0); } -TEST(scap_event, int_args) -{ - char scap_error[SCAP_LASTERR_SIZE]; - scap_evt *maybe_evt; - uint32_t status = scap_event_generate(&maybe_evt, scap_error, PPME_SYSCALL_KILL_E, 2, 1234, 9); - ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; - ASSERT_NE(maybe_evt, nullptr); - std::unique_ptr evt {maybe_evt, free}; - - EXPECT_EQ(evt->nparams, 2); - - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(evt.get(), decoded_params); - EXPECT_EQ(n, 2); - EXPECT_EQ(decoded_params[0].size, sizeof(uint64_t)); - uint64_t val64; - memcpy(&val64, decoded_params[0].buf, sizeof(uint64_t)); - EXPECT_EQ(val64, 1234); - - uint8_t val8; - memcpy(&val8, decoded_params[1].buf, sizeof(uint8_t)); - EXPECT_EQ(val8, 9); +TEST(scap_event, int_args) { + char scap_error[SCAP_LASTERR_SIZE]; + scap_evt *maybe_evt; + uint32_t status = scap_event_generate(&maybe_evt, scap_error, PPME_SYSCALL_KILL_E, 2, 1234, 9); + ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; + ASSERT_NE(maybe_evt, nullptr); + std::unique_ptr evt{maybe_evt, free}; + + EXPECT_EQ(evt->nparams, 2); + + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(evt.get(), decoded_params); + EXPECT_EQ(n, 2); + EXPECT_EQ(decoded_params[0].size, sizeof(uint64_t)); + uint64_t val64; + memcpy(&val64, decoded_params[0].buf, sizeof(uint64_t)); + EXPECT_EQ(val64, 1234); + + uint8_t val8; + memcpy(&val8, decoded_params[1].buf, sizeof(uint8_t)); + EXPECT_EQ(val8, 9); } -TEST(scap_event, empty_buffers) -{ - char scap_error[SCAP_LASTERR_SIZE]; - - // empty string should be of size 1 - scap_evt *maybe_evt; - uint32_t status = scap_event_generate(&maybe_evt, scap_error, PPME_SYSCALL_GETCWD_X, 2, 0, ""); - ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; - ASSERT_NE(maybe_evt, nullptr); - std::unique_ptr evt {maybe_evt, free}; - - EXPECT_EQ(evt->nparams, 2); - - scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; - uint32_t n = scap_event_decode_params(evt.get(), decoded_params); - EXPECT_EQ(n, 2); - EXPECT_EQ(decoded_params[0].size, sizeof(uint64_t)); - EXPECT_EQ(decoded_params[1].size, 1); - - status = scap_event_generate(&maybe_evt, scap_error, PPME_SYSCALL_READ_X, 2, 0, scap_const_sized_buffer{nullptr, 0}); - ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; - ASSERT_NE(maybe_evt, nullptr); - evt.reset(maybe_evt); - - n = scap_event_decode_params(evt.get(), decoded_params); - EXPECT_EQ(n, 2); - EXPECT_EQ(decoded_params[0].size, sizeof(uint64_t)); - EXPECT_EQ(decoded_params[1].size, 0); +TEST(scap_event, empty_buffers) { + char scap_error[SCAP_LASTERR_SIZE]; + + // empty string should be of size 1 + scap_evt *maybe_evt; + uint32_t status = scap_event_generate(&maybe_evt, scap_error, PPME_SYSCALL_GETCWD_X, 2, 0, ""); + ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; + ASSERT_NE(maybe_evt, nullptr); + std::unique_ptr evt{maybe_evt, free}; + + EXPECT_EQ(evt->nparams, 2); + + scap_sized_buffer decoded_params[PPM_MAX_EVENT_PARAMS]; + uint32_t n = scap_event_decode_params(evt.get(), decoded_params); + EXPECT_EQ(n, 2); + EXPECT_EQ(decoded_params[0].size, sizeof(uint64_t)); + EXPECT_EQ(decoded_params[1].size, 1); + + status = scap_event_generate(&maybe_evt, + scap_error, + PPME_SYSCALL_READ_X, + 2, + 0, + scap_const_sized_buffer{nullptr, 0}); + ASSERT_EQ(status, SCAP_SUCCESS) << "scap_event_generate failed with error " << scap_error; + ASSERT_NE(maybe_evt, nullptr); + evt.reset(maybe_evt); + + n = scap_event_decode_params(evt.get(), decoded_params); + EXPECT_EQ(n, 2); + EXPECT_EQ(decoded_params[0].size, sizeof(uint64_t)); + EXPECT_EQ(decoded_params[1].size, 0); } diff --git a/test/libscap/test_suites/userspace/scap_ppm_sc.cpp b/test/libscap/test_suites/userspace/scap_ppm_sc.cpp index 4bc660503a..07d2c89587 100644 --- a/test/libscap/test_suites/userspace/scap_ppm_sc.cpp +++ b/test/libscap/test_suites/userspace/scap_ppm_sc.cpp @@ -22,8 +22,7 @@ limitations under the License. extern const syscall_evt_pair g_syscall_table[SYSCALL_TABLE_SIZE]; -TEST(scap_ppm_sc, scap_get_modifies_state_ppm_sc) -{ +TEST(scap_ppm_sc, scap_get_modifies_state_ppm_sc) { /* Failure case */ ASSERT_EQ(scap_get_modifies_state_ppm_sc(NULL), SCAP_FAILURE); @@ -31,20 +30,17 @@ TEST(scap_ppm_sc, scap_get_modifies_state_ppm_sc) ASSERT_EQ(scap_get_modifies_state_ppm_sc(ppm_sc_array), SCAP_SUCCESS); /* All UNEVER_DROP syscalls */ - for(int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) - { - if(g_syscall_table[syscall_nr].flags & UF_NEVER_DROP) - { + for(int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) { + if(g_syscall_table[syscall_nr].flags & UF_NEVER_DROP) { ASSERT_TRUE(ppm_sc_array[g_syscall_table[syscall_nr].ppm_sc]); } } /* Events that have EF_MODIFIES_STATE and are tracepoint or syscalls */ - for(int event_nr = 0; event_nr < PPM_EVENT_MAX; event_nr++) - { + for(int event_nr = 0; event_nr < PPM_EVENT_MAX; event_nr++) { if(((scap_get_event_info_table()[event_nr].flags & EF_MODIFIES_STATE) == 0) || - ((scap_get_event_info_table()[event_nr].category & EC_SYSCALL) == 0 && (scap_get_event_info_table()[event_nr].category & EC_TRACEPOINT) == 0)) - { + ((scap_get_event_info_table()[event_nr].category & EC_SYSCALL) == 0 && + (scap_get_event_info_table()[event_nr].category & EC_TRACEPOINT) == 0)) { continue; } @@ -52,21 +48,18 @@ TEST(scap_ppm_sc, scap_get_modifies_state_ppm_sc) uint8_t events_array_int[PPM_EVENT_MAX] = {0}; events_array_int[event_nr] = 1; ASSERT_EQ(scap_get_ppm_sc_from_events(events_array_int, ppm_sc_array_int), SCAP_SUCCESS); - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if(ppm_sc_array_int[ppm_sc]) - { + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(ppm_sc_array_int[ppm_sc]) { ASSERT_TRUE(ppm_sc_array[ppm_sc]); } } } } -/* This check tries to check the correspondence between the `g_events_to_sc_map` and the `syscall_table` - * when the architecture allows it (in the syscall_table we have ifdefs) +/* This check tries to check the correspondence between the `g_events_to_sc_map` and the + * `syscall_table` when the architecture allows it (in the syscall_table we have ifdefs) */ -TEST(scap_ppm_sc, scap_get_events_from_ppm_sc) -{ +TEST(scap_ppm_sc, scap_get_events_from_ppm_sc) { { /* Failure cases */ uint8_t ppm_sc_array[PPM_SC_MAX] = {0}; @@ -76,43 +69,46 @@ TEST(scap_ppm_sc, scap_get_events_from_ppm_sc) ASSERT_EQ(scap_get_events_from_ppm_sc(NULL, NULL), SCAP_FAILURE); /* Check memset */ - for(int i = 0; i < PPM_EVENT_MAX; i++) - { + for(int i = 0; i < PPM_EVENT_MAX; i++) { events_array[i] = 1; } ASSERT_EQ(scap_get_events_from_ppm_sc(ppm_sc_array, events_array), SCAP_SUCCESS); - for(int i = 0; i < PPM_EVENT_MAX; i++) - { + for(int i = 0; i < PPM_EVENT_MAX; i++) { ASSERT_FALSE(events_array[i]); } } /* Best effort checks, we have ifdefs in the syscall_table. - * We need to skip PPM_SC_UNKNOWN since it is no more associated with any event with the new implementation. + * We need to skip PPM_SC_UNKNOWN since it is no more associated with any event with the new + * implementation. */ - for(int ppm_sc = 1; ppm_sc < PPM_SC_MAX; ppm_sc++) - { + for(int ppm_sc = 1; ppm_sc < PPM_SC_MAX; ppm_sc++) { uint8_t ppm_sc_array[PPM_SC_MAX] = {0}; ppm_sc_array[ppm_sc] = 1; uint8_t events_array[PPM_EVENT_MAX] = {0}; ASSERT_EQ(scap_get_events_from_ppm_sc(ppm_sc_array, events_array), SCAP_SUCCESS); - for(int sys_id = 0; sys_id < SYSCALL_TABLE_SIZE; sys_id++) - { + for(int sys_id = 0; sys_id < SYSCALL_TABLE_SIZE; sys_id++) { syscall_evt_pair pair = g_syscall_table[sys_id]; - if(pair.ppm_sc == ppm_sc) - { - ASSERT_TRUE(events_array[pair.enter_event_type]) << "ppm_sc: " << scap_get_ppm_sc_name((ppm_sc_code)pair.ppm_sc) << " (" << pair.ppm_sc << ") should be associated with event: " << pair.enter_event_type << std::endl; - ASSERT_TRUE(events_array[pair.exit_event_type]) << "ppm_sc: " << scap_get_ppm_sc_name((ppm_sc_code)pair.ppm_sc) << " (" << pair.ppm_sc << ") should be associated with event: " << pair.exit_event_type << std::endl; + if(pair.ppm_sc == ppm_sc) { + ASSERT_TRUE(events_array[pair.enter_event_type]) + << "ppm_sc: " << scap_get_ppm_sc_name((ppm_sc_code)pair.ppm_sc) << " (" + << pair.ppm_sc + << ") should be associated with event: " << pair.enter_event_type + << std::endl; + ASSERT_TRUE(events_array[pair.exit_event_type]) + << "ppm_sc: " << scap_get_ppm_sc_name((ppm_sc_code)pair.ppm_sc) << " (" + << pair.ppm_sc + << ") should be associated with event: " << pair.exit_event_type + << std::endl; } } } } -/* This check tries to check the correspondence between the `g_events_to_sc_map` and the `syscall_table` - * when the architecture allows it (in the syscall_table we have ifdefs) +/* This check tries to check the correspondence between the `g_events_to_sc_map` and the + * `syscall_table` when the architecture allows it (in the syscall_table we have ifdefs) */ -TEST(scap_ppm_sc, scap_get_ppm_sc_from_events) -{ +TEST(scap_ppm_sc, scap_get_ppm_sc_from_events) { { /* Failure cases */ uint8_t ppm_sc_array[PPM_SC_MAX] = {0}; @@ -122,38 +118,34 @@ TEST(scap_ppm_sc, scap_get_ppm_sc_from_events) ASSERT_EQ(scap_get_ppm_sc_from_events(NULL, NULL), SCAP_FAILURE); /* Check memset */ - for(int i = 0; i < PPM_SC_MAX; i++) - { + for(int i = 0; i < PPM_SC_MAX; i++) { ppm_sc_array[i] = 1; } ASSERT_EQ(scap_get_ppm_sc_from_events(events_array, ppm_sc_array), SCAP_SUCCESS); - for(int i = 0; i < PPM_SC_MAX; i++) - { + for(int i = 0; i < PPM_SC_MAX; i++) { ASSERT_FALSE(ppm_sc_array[i]); } } /* Best effort checks, we have ifdefs in the syscall_table. */ - for(int evt_id = 1; evt_id < PPM_EVENT_MAX; evt_id++) - { + for(int evt_id = 1; evt_id < PPM_EVENT_MAX; evt_id++) { uint8_t events_array[PPM_EVENT_MAX] = {0}; events_array[evt_id] = 1; uint8_t ppm_sc_array[PPM_SC_MAX] = {0}; ASSERT_EQ(scap_get_ppm_sc_from_events(events_array, ppm_sc_array), SCAP_SUCCESS); - for(int sys_id = 0; sys_id < SYSCALL_TABLE_SIZE; sys_id++) - { + for(int sys_id = 0; sys_id < SYSCALL_TABLE_SIZE; sys_id++) { syscall_evt_pair pair = g_syscall_table[sys_id]; - if(pair.enter_event_type == evt_id || pair.exit_event_type == evt_id) - { - ASSERT_TRUE(ppm_sc_array[pair.ppm_sc]) << "event: " << scap_get_event_info_table()[evt_id].name << " (" << evt_id << ") should be associated with ppm_sc: " << pair.ppm_sc << std::endl; + if(pair.enter_event_type == evt_id || pair.exit_event_type == evt_id) { + ASSERT_TRUE(ppm_sc_array[pair.ppm_sc]) + << "event: " << scap_get_event_info_table()[evt_id].name << " (" << evt_id + << ") should be associated with ppm_sc: " << pair.ppm_sc << std::endl; } } } } -TEST(scap_ppm_sc, scap_ppm_sc_from_name) -{ +TEST(scap_ppm_sc, scap_ppm_sc_from_name) { ASSERT_EQ(scap_ppm_sc_from_name(NULL), -1); ASSERT_EQ(scap_ppm_sc_from_name(""), -1); ASSERT_EQ(scap_ppm_sc_from_name(" "), -1); @@ -166,8 +158,7 @@ TEST(scap_ppm_sc, scap_ppm_sc_from_name) ASSERT_EQ(scap_ppm_sc_from_name("alarm"), PPM_SC_ALARM); } -TEST(scap_ppm_sc, scap_native_id_to_ppm_sc) -{ +TEST(scap_ppm_sc, scap_native_id_to_ppm_sc) { ASSERT_EQ(scap_native_id_to_ppm_sc(80000000), PPM_SC_UNKNOWN); ASSERT_EQ(scap_native_id_to_ppm_sc(-12), PPM_SC_UNKNOWN); ASSERT_EQ(scap_native_id_to_ppm_sc(SYSCALL_TABLE_SIZE), PPM_SC_UNKNOWN); diff --git a/test/libscap/test_suites/userspace/syscall_table.cpp b/test/libscap/test_suites/userspace/syscall_table.cpp index f97f8cdb3c..8dffdacfb5 100644 --- a/test/libscap/test_suites/userspace/syscall_table.cpp +++ b/test/libscap/test_suites/userspace/syscall_table.cpp @@ -21,23 +21,22 @@ limitations under the License. extern const syscall_evt_pair g_syscall_table[SYSCALL_TABLE_SIZE]; -/* Each syscall_id should have its own PPM_SC, note that this should be true also for generic syscalls - * only the event type is generic, the PPM_SC code is defined! This test is architecture dependent! +/* Each syscall_id should have its own PPM_SC, note that this should be true also for generic + * syscalls only the event type is generic, the PPM_SC code is defined! This test is architecture + * dependent! */ -TEST(syscall_table, check_1_1_match_between_ppm_sc_syscall_id) -{ +TEST(syscall_table, check_1_1_match_between_ppm_sc_syscall_id) { std::vector ppm_sc_count(PPM_SC_MAX, 0); - for(int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) - { + for(int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) { ppm_sc_count[g_syscall_table[syscall_nr].ppm_sc]++; } - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if(ppm_sc != PPM_SC_UNKNOWN) - { - ASSERT_TRUE(ppm_sc_count[ppm_sc] <= 1) << "[fail] SYSCALL (" << scap_get_ppm_sc_name((ppm_sc_code)ppm_sc) << ") is found '" << ppm_sc_count[ppm_sc] << "' times" << std::endl; - } + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(ppm_sc != PPM_SC_UNKNOWN) { + ASSERT_TRUE(ppm_sc_count[ppm_sc] <= 1) + << "[fail] SYSCALL (" << scap_get_ppm_sc_name((ppm_sc_code)ppm_sc) + << ") is found '" << ppm_sc_count[ppm_sc] << "' times" << std::endl; + } } } diff --git a/test/libsinsp_e2e/CMakeLists.txt b/test/libsinsp_e2e/CMakeLists.txt index 2f800f8d74..c718131b1d 100755 --- a/test/libsinsp_e2e/CMakeLists.txt +++ b/test/libsinsp_e2e/CMakeLists.txt @@ -2,74 +2,67 @@ # # Copyright (C) 2024 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # message(STATUS "Libsinsp unit e2e tests build enabled") if(NOT DEFINED DRIVER_NAME) - set(DRIVER_NAME "scap") + set(DRIVER_NAME "scap") endif() add_compile_options(${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS}) add_link_options(${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS}) -# Create a libsinsp_test_var.h file with some variables used by our tests -# for example the kmod path or the bpf path. -configure_file ( - "${CMAKE_CURRENT_SOURCE_DIR}/libsinsp_test_var.h.in" - "${CMAKE_CURRENT_BINARY_DIR}/libsinsp_test_var.h" +# Create a libsinsp_test_var.h file with some variables used by our tests for example the kmod path +# or the bpf path. +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/libsinsp_test_var.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/libsinsp_test_var.h" ) -add_executable(libsinsp_e2e_tests - capture_to_file_test.cpp - container/container.cpp - container/container_cgroup.cpp - container/docker_utils.cpp - event_capture.cpp - forking.cpp - fs.cpp - ipv6.cpp - main.cpp - paths.cpp - process.cpp - subprocess.cpp - suppress_events.cpp - sys_call_test.cpp - tcp_client_server.cpp - tcp_client_server_ipv4_mapped.cpp - threadinfo.cpp - thread_state.cpp - udp_client_server.cpp - unix_client_server.cpp +add_executable( + libsinsp_e2e_tests + capture_to_file_test.cpp + container/container.cpp + container/container_cgroup.cpp + container/docker_utils.cpp + event_capture.cpp + forking.cpp + fs.cpp + ipv6.cpp + main.cpp + paths.cpp + process.cpp + subprocess.cpp + suppress_events.cpp + sys_call_test.cpp + tcp_client_server.cpp + tcp_client_server_ipv4_mapped.cpp + threadinfo.cpp + thread_state.cpp + udp_client_server.cpp + unix_client_server.cpp ) if(BUILD_BPF) - add_dependencies(libsinsp_e2e_tests driver bpf) + add_dependencies(libsinsp_e2e_tests driver bpf) else() - add_dependencies(libsinsp_e2e_tests driver) + add_dependencies(libsinsp_e2e_tests driver) endif() -target_link_libraries(libsinsp_e2e_tests - sinsp - GTest::gtest - pthread -) +target_link_libraries(libsinsp_e2e_tests sinsp GTest::gtest pthread) -target_include_directories(libsinsp_e2e_tests - PRIVATE - ${PROJECT_BINARY_DIR}/driver/src - "${CMAKE_CURRENT_BINARY_DIR}" # used to include `libsinsp_test_var.h` +target_include_directories( + libsinsp_e2e_tests PRIVATE ${PROJECT_BINARY_DIR}/driver/src "${CMAKE_CURRENT_BINARY_DIR}" ) add_executable(test_helper test_helper.cpp) @@ -80,33 +73,28 @@ add_executable(vtidcollision vtidcollision.c) add_dependencies(libsinsp_e2e_tests vtidcollision) execute_process( - COMMAND "uname" "-m" - OUTPUT_VARIABLE ARCH - OUTPUT_STRIP_TRAILING_WHITESPACE + COMMAND "uname" "-m" + OUTPUT_VARIABLE ARCH + OUTPUT_STRIP_TRAILING_WHITESPACE ) if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") - # Build 32-bit tests only for architectures where that is supported - if(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64") - add_executable(test_helper_32 test_helper.cpp) - set_target_properties(test_helper_32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") - target_link_libraries(test_helper_32 pthread) - add_dependencies(libsinsp_e2e_tests test_helper_32) - endif() + # Build 32-bit tests only for architectures where that is supported + if(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64") + add_executable(test_helper_32 test_helper.cpp) + set_target_properties(test_helper_32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") + target_link_libraries(test_helper_32 pthread) + add_dependencies(libsinsp_e2e_tests test_helper_32) + endif() endif("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/test_helper.sh.in - ${CMAKE_CURRENT_BINARY_DIR}/test_helper.sh + ${CMAKE_CURRENT_SOURCE_DIR}/test_helper.sh.in ${CMAKE_CURRENT_BINARY_DIR}/test_helper.sh ) -file(COPY - ${CMAKE_CURRENT_SOURCE_DIR}/resources/ - DESTINATION - ${CMAKE_CURRENT_BINARY_DIR}/resources/ -) +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/resources/ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/resources/) execute_process( - COMMAND tar xzf ${CMAKE_CURRENT_BINARY_DIR}/resources/fake-proc.tar.gz - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/resources/ - ) + COMMAND tar xzf ${CMAKE_CURRENT_BINARY_DIR}/resources/fake-proc.tar.gz + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/resources/ +) diff --git a/test/libsinsp_e2e/capture_to_file_test.cpp b/test/libsinsp_e2e/capture_to_file_test.cpp index 9302b55948..0627501451 100644 --- a/test/libsinsp_e2e/capture_to_file_test.cpp +++ b/test/libsinsp_e2e/capture_to_file_test.cpp @@ -23,22 +23,18 @@ limitations under the License. #include -TEST_F(sys_call_test, can_consume_a_capture_file) -{ +TEST_F(sys_call_test, can_consume_a_capture_file) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { std::string evt_name(evt->get_name()); - return evt_name.find("stat") != std::string::npos && - m_tid_filter(evt) && evt->get_direction() == SCAP_ED_OUT; + return evt_name.find("stat") != std::string::npos && m_tid_filter(evt) && + evt->get_direction() == SCAP_ED_OUT; }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { struct stat sb; - for(int i = 0; i < 100; i++) - { + for(int i = 0; i < 100; i++) { stat("/tmp", &sb); } }; @@ -51,19 +47,17 @@ TEST_F(sys_call_test, can_consume_a_capture_file) sinsp_evt* event; const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); auto filename = std::string(LIBSINSP_TEST_CAPTURES_PATH) + test_info->test_case_name() + "_" + - test_info->name() + ".scap"; + test_info->name() + ".scap"; inspector.open_savefile(filename); callnum = 0; int32_t res; - while((res = inspector.next(&event)) != SCAP_EOF) - { + while((res = inspector.next(&event)) != SCAP_EOF) { ASSERT_EQ(SCAP_SUCCESS, res); std::string evt_name(event->get_name()); - if(evt_name.find("stat") != std::string::npos && - m_tid_filter(event) && event->get_direction() == SCAP_ED_OUT) - { + if(evt_name.find("stat") != std::string::npos && m_tid_filter(event) && + event->get_direction() == SCAP_ED_OUT) { callnum++; } } diff --git a/test/libsinsp_e2e/container/container.cpp b/test/libsinsp_e2e/container/container.cpp index 78d2cd699c..195f2b6a37 100644 --- a/test/libsinsp_e2e/container/container.cpp +++ b/test/libsinsp_e2e/container/container.cpp @@ -26,8 +26,7 @@ limitations under the License. using namespace std; -TEST_F(sys_call_test, container_cgroups) -{ +TEST_F(sys_call_test, container_cgroups) { int ctid; bool done = false; @@ -39,25 +38,18 @@ TEST_F(sys_call_test, container_cgroups) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { ctid = fork(); - if (ctid >= 0) - { - if (ctid == 0) - { + if(ctid >= 0) { + if(ctid == 0) { sleep(1); // _exit prevents asan from complaining for a false positive memory leak. _exit(0); - } - else - { + } else { wait(NULL); } - } - else - { + } else { FAIL(); } }; @@ -65,10 +57,8 @@ TEST_F(sys_call_test, container_cgroups) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { - if (param.m_evt->get_type() == PPME_SYSCALL_CLONE_20_X) - { + captured_event_callback_t callback = [&](const callback_param& param) { + if(param.m_evt->get_type() == PPME_SYSCALL_CLONE_20_X) { sinsp_threadinfo sinsp_tinfo(nullptr); char buf[100]; @@ -86,36 +76,30 @@ TEST_F(sys_call_test, container_cgroups) ASSERT_TRUE(sinsp_cgroups.size() > 0); map cgroups_kernel; - for (uint32_t j = 0; j < cgroups.size(); ++j) - { + for(uint32_t j = 0; j < cgroups.size(); ++j) { cgroups_kernel.insert(pair(cgroups[j].first, cgroups[j].second)); } map cgroups_proc; - for (uint32_t j = 0; j < sinsp_cgroups.size(); ++j) - { + for(uint32_t j = 0; j < sinsp_cgroups.size(); ++j) { cgroups_proc.insert( - pair(sinsp_cgroups[j].first, sinsp_cgroups[j].second)); + pair(sinsp_cgroups[j].first, sinsp_cgroups[j].second)); } ASSERT_TRUE(cgroups_kernel.size() > 0); ASSERT_TRUE(cgroups_proc.size() > 0); - for (const auto& [subsys, path] : cgroups_proc) - { + for(const auto& [subsys, path] : cgroups_proc) { printf(" proc cgroup[%s] == <%s>\n", subsys.c_str(), path.c_str()); } - for (const auto& [subsys, path] : cgroups_kernel) - { + for(const auto& [subsys, path] : cgroups_kernel) { printf(" kernel cgroup[%s] == <%s>\n", subsys.c_str(), path.c_str()); } - for (auto& [proc_subsys, proc_path] : cgroups_proc) - { + for(auto& [proc_subsys, proc_path] : cgroups_proc) { auto it_kernel = cgroups_kernel.find(proc_subsys); - if (it_kernel != cgroups_kernel.end()) - { + if(it_kernel != cgroups_kernel.end()) { EXPECT_EQ(it_kernel->first, proc_subsys); EXPECT_EQ(it_kernel->second, proc_path); } @@ -129,8 +113,7 @@ TEST_F(sys_call_test, container_cgroups) ASSERT_TRUE(done); } -static int clone_callback(void* arg) -{ +static int clone_callback(void* arg) { // Here we need 2 sleeps instead of once because, for some reason, // we miss the first one. This problem is *probably* related to the // fact that before we created a brand new inspector for each test but @@ -140,8 +123,7 @@ static int clone_callback(void* arg) return 0; } -TEST_F(sys_call_test, container_clone_nspid) -{ +TEST_F(sys_call_test, container_clone_nspid) { int ctid; int flags = CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD | CLONE_NEWPID; bool done = false; @@ -154,31 +136,24 @@ TEST_F(sys_call_test, container_clone_nspid) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { const int STACK_SIZE = 65536; /* Stack size for cloned child */ char* stack; /* Start of stack buffer area */ char* stack_top; /* End of stack buffer area */ stack = (char*)malloc(STACK_SIZE); - if (stack == NULL) - { + if(stack == NULL) { FAIL(); } stack_top = stack + STACK_SIZE; ctid = clone(clone_callback, stack_top, flags, NULL); - if (ctid == -1) - { + if(ctid == -1) { FAIL(); - } - else if (ctid == 0) - { + } else if(ctid == 0) { free(stack); _exit(0); - } - else - { + } else { free(stack); waitpid(ctid, NULL, 0); } @@ -187,11 +162,9 @@ TEST_F(sys_call_test, container_clone_nspid) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (e->get_type() == PPME_SYSCALL_CLONE_20_X) - { + if(e->get_type() == PPME_SYSCALL_CLONE_20_X) { sinsp_threadinfo* tinfo = param.m_evt->get_thread_info(); ASSERT_TRUE(tinfo != NULL); ASSERT_TRUE(tinfo->m_vtid == 1); @@ -205,8 +178,7 @@ TEST_F(sys_call_test, container_clone_nspid) ASSERT_TRUE(done); } -TEST_F(sys_call_test, container_clone_nspid_ioctl) -{ +TEST_F(sys_call_test, container_clone_nspid_ioctl) { int ctid; int flags = CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | SIGCHLD | CLONE_NEWPID; bool done = false; @@ -216,15 +188,13 @@ TEST_F(sys_call_test, container_clone_nspid_ioctl) char* stack_top; stack = (char*)malloc(STACK_SIZE); - if (stack == NULL) - { + if(stack == NULL) { FAIL(); } stack_top = stack + STACK_SIZE; ctid = clone(clone_callback, stack_top, flags, NULL); - if (ctid == -1) - { + if(ctid == -1) { FAIL(); } @@ -236,16 +206,16 @@ TEST_F(sys_call_test, container_clone_nspid_ioctl) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) { waitpid(ctid, NULL, 0); }; + run_callback_t test = [&](concurrent_object_handle inspector) { + waitpid(ctid, NULL, 0); + }; // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_threadinfo* tinfo = param.m_evt->get_thread_info(); - if (tinfo && tinfo->m_vtid == 1 && tinfo->m_vpid == 1) - { + if(tinfo && tinfo->m_vtid == 1 && tinfo->m_vpid == 1) { done = true; } }; @@ -255,31 +225,27 @@ TEST_F(sys_call_test, container_clone_nspid_ioctl) ASSERT_TRUE(done); } -static void run_container_docker_test(bool fork_after_container_start) -{ +static void run_container_docker_test(bool fork_after_container_start) { bool done = false; - if (!dutils_check_docker()) - { + if(!dutils_check_docker()) { printf("Docker not running, skipping test\n"); return; } - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return (evt->get_type() == PPME_CONTAINER_JSON_E || evt->get_type() == PPME_CONTAINER_JSON_2_E); }; - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { ASSERT_TRUE(system("docker kill libsinsp_docker > /dev/null 2>&1 || true") == 0); ASSERT_TRUE(system("docker rm -v libsinsp_docker > /dev/null 2>&1 || true") == 0); #ifdef __s390x__ - if (system("docker run -d --name libsinsp_docker s390x/busybox") != 0) + if(system("docker run -d --name libsinsp_docker s390x/busybox") != 0) #else - if (system("docker run -d --name libsinsp_docker busybox") != 0) + if(system("docker run -d --name libsinsp_docker busybox") != 0) #endif { ASSERT_TRUE(false); @@ -290,25 +256,20 @@ static void run_container_docker_test(bool fork_after_container_start) ASSERT_TRUE(system("docker kill libsinsp_docker > /dev/null 2>&1 || true") == 0); ASSERT_TRUE(system("docker rm -v libsinsp_docker > /dev/null 2>&1") == 0); - if (fork_after_container_start) - { + if(fork_after_container_start) { int child_pid = fork(); ASSERT_TRUE(child_pid >= 0) << "Could not fork" << strerror(errno); - if (child_pid == 0) - { + if(child_pid == 0) { // _exit prevents asan from complaining for a false positive memory leak. _exit(0); - } - else - { + } else { wait(NULL); } } }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_threadinfo* tinfo = param.m_evt->get_thread_info(); ASSERT_TRUE(tinfo != NULL); ASSERT_TRUE(tinfo->m_vtid != tinfo->m_tid); @@ -317,7 +278,7 @@ static void run_container_docker_test(bool fork_after_container_start) ASSERT_TRUE(tinfo->m_container_id.length() == 12); const auto container_info = - param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); + param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); ASSERT_TRUE(container_info != NULL); EXPECT_EQ(sinsp_container_lookup::state::SUCCESSFUL, container_info->get_lookup_status()); @@ -336,8 +297,7 @@ static void run_container_docker_test(bool fork_after_container_start) ASSERT_TRUE(done); } -TEST_F(sys_call_test, container_docker) -{ +TEST_F(sys_call_test, container_docker) { bool fork_after_container_start = false; run_container_docker_test(fork_after_container_start); @@ -357,53 +317,45 @@ TEST_F(sys_call_test, container_docker) // hanging/failing/crashing. If this happens, we should remove this // test. -TEST_F(sys_call_test, container_docker_fork) -{ +TEST_F(sys_call_test, container_docker_fork) { bool fork_after_container_start = true; run_container_docker_test(fork_after_container_start); } -TEST_F(sys_call_test, container_docker_bad_socket) -{ +TEST_F(sys_call_test, container_docker_bad_socket) { bool done = false; - if (!dutils_check_docker()) - { + if(!dutils_check_docker()) { printf("Docker not running, skipping test\n"); return; } - before_open_t setup = [&](sinsp* inspector) - { + before_open_t setup = [&](sinsp* inspector) { inspector->set_docker_socket_path("/invalid/path"); }; - event_filter_t filter = [&](sinsp_evt* evt) - { - if (evt->get_type() == PPME_CONTAINER_JSON_E || evt->get_type() == PPME_CONTAINER_JSON_2_E) - { + event_filter_t filter = [&](sinsp_evt* evt) { + if(evt->get_type() == PPME_CONTAINER_JSON_E || evt->get_type() == PPME_CONTAINER_JSON_2_E) { return true; } auto tinfo = evt->get_thread_info(); - if (tinfo) - { + if(tinfo) { return !tinfo->m_container_id.empty(); } return false; }; - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { ASSERT_TRUE(system("docker kill libsinsp_docker > /dev/null 2>&1 || true") == 0); ASSERT_TRUE(system("docker rm -v libsinsp_docker > /dev/null 2>&1 || true") == 0); #ifdef __s390x__ - if (system("docker run -d --name libsinsp_docker s390x/busybox sh -c 'while true; do " - "sleep 1; done'") != 0) + if(system("docker run -d --name libsinsp_docker s390x/busybox sh -c 'while true; do " + "sleep 1; done'") != 0) #else - if (system("docker run -d --name libsinsp_docker busybox sh -c 'while true; do sleep 1; " - "done'") != 0) + if(system("docker run -d --name libsinsp_docker busybox sh -c 'while true; do sleep 1; " + "done'") != 0) #endif { ASSERT_TRUE(false); @@ -415,8 +367,7 @@ TEST_F(sys_call_test, container_docker_bad_socket) ASSERT_TRUE(system("docker rm -v libsinsp_docker > /dev/null 2>&1") == 0); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { // can't get a container event for failed lookup ASSERT_NE(PPME_CONTAINER_JSON_E, param.m_evt->get_type()); ASSERT_NE(PPME_CONTAINER_JSON_2_E, param.m_evt->get_type()); @@ -425,44 +376,39 @@ TEST_F(sys_call_test, container_docker_bad_socket) ASSERT_TRUE(tinfo->m_container_id.length() == 12); ASSERT_TRUE(param.m_inspector->m_container_manager.container_exists(tinfo->m_container_id)); const auto container_info = - param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); - if (container_info && container_info->m_type == CT_DOCKER) - { + param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); + if(container_info && container_info->m_type == CT_DOCKER) { EXPECT_EQ(sinsp_container_lookup::state::FAILED, container_info->get_lookup_status()); done = true; } }; - before_close_t cleanup = [&](sinsp* inspector) - { inspector->set_docker_socket_path("/var/run/docker.sock"); }; + before_close_t cleanup = [&](sinsp* inspector) { + inspector->set_docker_socket_path("/var/run/docker.sock"); + }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter, setup, cleanup); }); ASSERT_TRUE(done); } -TEST_F(sys_call_test, container_libvirt) -{ +TEST_F(sys_call_test, container_libvirt) { bool done = false; - if (system("virsh --help > /dev/null 2>&1") != 0) - { + if(system("virsh --help > /dev/null 2>&1") != 0) { GTEST_SKIP() << "libvirt not installed, skipping test"; return; } - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if (tinfo) - { + if(tinfo) { return !tinfo->m_container_id.empty() && tinfo->m_comm == "sh"; } return false; }; - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { FILE* f = fopen("/tmp/conf.xml", "w"); ASSERT_TRUE(f != NULL); fprintf(f, @@ -480,17 +426,16 @@ TEST_F(sys_call_test, container_libvirt) fclose(f); ASSERT_TRUE( - system("virsh -c lxc:/// undefine libvirt-container > /dev/null 2>&1 || true") == 0); + system("virsh -c lxc:/// undefine libvirt-container > /dev/null 2>&1 || true") == + 0); ASSERT_TRUE(system("virsh -c lxc:/// destroy libvirt-container > /dev/null 2>&1 || true") == 0); - if (system("virsh -c lxc:/// define /tmp/conf.xml") != 0) - { + if(system("virsh -c lxc:/// define /tmp/conf.xml") != 0) { ASSERT_TRUE(false); } - if (system("virsh -c lxc:/// start libvirt-container") != 0) - { + if(system("virsh -c lxc:/// start libvirt-container") != 0) { ASSERT_TRUE(false); } @@ -500,8 +445,7 @@ TEST_F(sys_call_test, container_libvirt) ASSERT_TRUE(system("virsh -c lxc:/// destroy libvirt-container > /dev/null 2>&1") == 0); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_threadinfo* tinfo = param.m_evt->get_thread_info(); ASSERT_TRUE(tinfo != NULL); ASSERT_TRUE(tinfo->m_vtid != tinfo->m_tid); @@ -510,10 +454,10 @@ TEST_F(sys_call_test, container_libvirt) unsigned int lxc_id; ASSERT_TRUE(tinfo->m_container_id.find("libvirt\\x2dcontainer") != string::npos || sscanf(tinfo->m_container_id.c_str(), "lxc-%u-libvirt-container", &lxc_id) == - 1); + 1); const auto container_info = - param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); + param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); ASSERT_TRUE(container_info != NULL); ASSERT_TRUE(container_info->m_type == sinsp_container_type::CT_LIBVIRT_LXC); @@ -527,15 +471,14 @@ TEST_F(sys_call_test, container_libvirt) ASSERT_TRUE(done); } -class container_state -{ +class container_state { public: - container_state() - : container_w_health_probe(false), - root_cmd_seen(false), - second_cmd_seen(false), - healthcheck_seen(false){}; - virtual ~container_state(){}; + container_state(): + container_w_health_probe(false), + root_cmd_seen(false), + second_cmd_seen(false), + healthcheck_seen(false) {}; + virtual ~container_state() {}; bool container_w_health_probe; bool root_cmd_seen; @@ -543,8 +486,7 @@ class container_state bool healthcheck_seen; }; -static std::string capture_stats(sinsp* inspector) -{ +static std::string capture_stats(sinsp* inspector) { scap_stats st; inspector->get_capture_stats(&st); @@ -559,26 +501,22 @@ static std::string capture_stats(sinsp* inspector) static void update_container_state(sinsp* inspector, sinsp_evt* evt, container_state& cstate, - sinsp_threadinfo::command_category expected_cat) -{ + sinsp_threadinfo::command_category expected_cat) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if (tinfo == NULL) - { + if(tinfo == NULL) { return; } - if (inspector->m_container_manager.container_exists(tinfo->m_container_id)) - { + if(inspector->m_container_manager.container_exists(tinfo->m_container_id)) { std::string cmdline; sinsp_threadinfo::populate_cmdline(cmdline, tinfo); const auto container_info = - inspector->m_container_manager.get_container(tinfo->m_container_id); + inspector->m_container_manager.get_container(tinfo->m_container_id); - if (container_info && !container_info->m_health_probes.empty()) - { + if(container_info && !container_info->m_health_probes.empty()) { cstate.container_w_health_probe = true; } @@ -586,23 +524,18 @@ static void update_container_state(sinsp* inspector, // where the health check is the same command, we will see this // command twice--the first time it should not be identified as // a health check, and the second time it should. - if (cmdline == "sh -c /bin/sleep 10") - { - if (!cstate.root_cmd_seen) - { + if(cmdline == "sh -c /bin/sleep 10") { + if(!cstate.root_cmd_seen) { cstate.root_cmd_seen = true; ASSERT_EQ(tinfo->m_category, sinsp_threadinfo::CAT_CONTAINER) - << capture_stats(inspector); - } - else - { + << capture_stats(inspector); + } else { // In some cases, it can take so long for the async fetch of container info to // complete (1.5 seconds) that a healthcheck proc might be run before the container // info has been updated. So only require the threadinfo category to match once // the container info has a health probe. - if (cstate.container_w_health_probe) - { + if(cstate.container_w_health_probe) { cstate.healthcheck_seen = true; ASSERT_EQ(tinfo->m_category, expected_cat) << capture_stats(inspector); } @@ -611,19 +544,14 @@ static void update_container_state(sinsp* inspector, // Child process of the above sh command. Same handling as above, // will see twice only when health check is same as root command. - if (cmdline == "sleep 10") - { - if (!cstate.second_cmd_seen) - { + if(cmdline == "sleep 10") { + if(!cstate.second_cmd_seen) { cstate.second_cmd_seen = true; ASSERT_EQ(tinfo->m_category, sinsp_threadinfo::CAT_CONTAINER) - << capture_stats(inspector); - } - else - { + << capture_stats(inspector); + } else { // See above caveat about slow container info fetches - if (cstate.container_w_health_probe) - { + if(cstate.container_w_health_probe) { // Should inherit container healthcheck property from parent. ASSERT_EQ(tinfo->m_category, expected_cat) << capture_stats(inspector); } @@ -632,8 +560,7 @@ static void update_container_state(sinsp* inspector, // Commandline for the health check of the healthcheck containers, // in direct exec and shell formats. - if (cmdline == "ut-health-check" || cmdline == "sh -c /bin/ut-health-check") - { + if(cmdline == "ut-health-check" || cmdline == "sh -c /bin/ut-health-check") { cstate.healthcheck_seen = true; ASSERT_EQ(tinfo->m_category, expected_cat) << capture_stats(inspector); @@ -645,42 +572,41 @@ static void update_container_state(sinsp* inspector, // state of the initial command for the container, a child proces of // that initial command, and a health check (if one is configured). static void healthcheck_helper( - const char* dockerfile, - bool expect_healthcheck, - const char* build_extra_args, - const char* run_extra_args, - std::vector& labels, - sinsp_threadinfo::command_category expected_cat = sinsp_threadinfo::CAT_HEALTHCHECK) -{ + const char* dockerfile, + bool expect_healthcheck, + const char* build_extra_args, + const char* run_extra_args, + std::vector& labels, + sinsp_threadinfo::command_category expected_cat = sinsp_threadinfo::CAT_HEALTHCHECK) { container_state cstate; bool exited_early = false; std::string capture_stats_str = "(Not Collected Yet)"; - if (!dutils_check_docker()) - { + if(!dutils_check_docker()) { return; } dutils_kill_container("cont_health_ut"); dutils_kill_image("cont_health_ut_img"); std::string docker_res(LIBSINSP_TEST_RESOURCES_PATH "/docker/"); - docker_helper dhelper(docker_res + dockerfile, "cont_health_ut_img", labels, build_extra_args, run_extra_args); + docker_helper dhelper(docker_res + dockerfile, + "cont_health_ut_img", + labels, + build_extra_args, + run_extra_args); ASSERT_TRUE(dhelper.build_image() == 0); - before_open_t setup = [&](sinsp* inspector) - {}; + before_open_t setup = [&](sinsp* inspector) {}; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); return (strcmp(evt->get_name(), "execve") == 0 && evt->get_direction() == SCAP_ED_OUT && tinfo->m_container_id != ""); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { // Setting dropping mode preserves the execs but // reduces the chances that we'll drop events during // the docker fetch. @@ -694,22 +620,19 @@ static void healthcheck_helper( ASSERT_TRUE(exited_early || (rc == 0)); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { update_container_state(param.m_inspector, param.m_evt, cstate, expected_cat); // Exit as soon as we've seen all the initial commands // and the health check (if expecting one) - if (!exited_early && cstate.root_cmd_seen && cstate.second_cmd_seen && - (cstate.healthcheck_seen || !expect_healthcheck)) - { + if(!exited_early && cstate.root_cmd_seen && cstate.second_cmd_seen && + (cstate.healthcheck_seen || !expect_healthcheck)) { exited_early = true; dutils_kill_container("cont_health_ut"); } }; - before_close_t cleanup = [&](sinsp* inspector) - { + before_close_t cleanup = [&](sinsp* inspector) { capture_stats_str = capture_stats(inspector); inspector->stop_dropping_mode(); }; @@ -723,31 +646,30 @@ static void healthcheck_helper( } static void healthcheck_tracefile_helper( - const std::string& dockerfile, - bool expect_healthcheck, - sinsp_threadinfo::command_category expected_cat = sinsp_threadinfo::CAT_HEALTHCHECK) -{ + const std::string& dockerfile, + bool expect_healthcheck, + sinsp_threadinfo::command_category expected_cat = sinsp_threadinfo::CAT_HEALTHCHECK) { container_state cstate; - std::string build_cmdline("cd " LIBSINSP_TEST_RESOURCES_PATH "/docker/health_dockerfiles && docker build -t cont_health_ut_img -f " - + dockerfile + " . > /dev/null 2>&1"); + std::string build_cmdline( + "cd " LIBSINSP_TEST_RESOURCES_PATH + "/docker/health_dockerfiles && docker build -t cont_health_ut_img -f " + + dockerfile + " . > /dev/null 2>&1"); ASSERT_TRUE(system(build_cmdline.c_str()) == 0); - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { // --network=none speeds up the container setup a bit. - ASSERT_TRUE((system("docker run --rm --network=none --name cont_health_ut cont_health_ut_img " - "/bin/sh -c '/bin/sleep 10' > /dev/null 2>&1")) == 0); + ASSERT_TRUE( + (system("docker run --rm --network=none --name cont_health_ut cont_health_ut_img " + "/bin/sh -c '/bin/sleep 10' > /dev/null 2>&1")) == 0); }; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { std::string evt_name(evt->get_name()); - return evt_name.find("execve") != std::string::npos && - evt->get_direction() == SCAP_ED_OUT; + return evt_name.find("execve") != std::string::npos && evt->get_direction() == SCAP_ED_OUT; }; - captured_event_callback_t callback = [&](const callback_param& param) {return;}; + captured_event_callback_t callback = [&](const callback_param& param) { return; }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); @@ -755,9 +677,9 @@ static void healthcheck_tracefile_helper( // update_container_state. const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); auto dumpfile = std::string(LIBSINSP_TEST_CAPTURES_PATH) + test_info->test_case_name() + "_" + - test_info->name() + ".scap"; + test_info->name() + ".scap"; sinsp inspector; inspector.set_hostname_and_port_resolution_mode(false); @@ -765,21 +687,16 @@ static void healthcheck_tracefile_helper( inspector.open_savefile(dumpfile); inspector.start_capture(); - while (1) - { + while(1) { sinsp_evt* ev; int32_t res = inspector.next(&ev); - if (res == SCAP_TIMEOUT) - { + if(res == SCAP_TIMEOUT) { continue; } - if (res == SCAP_FILTERED_EVENT) - { + if(res == SCAP_FILTERED_EVENT) { continue; - } - else if (res == SCAP_EOF) - { + } else if(res == SCAP_EOF) { break; } ASSERT_TRUE(res == SCAP_SUCCESS); @@ -798,20 +715,17 @@ static void healthcheck_tracefile_helper( ASSERT_EQ(cstate.healthcheck_seen, expect_healthcheck) << capture_stats_str; } - // Run container w/o health check, should not find any health check // for the container. Should not identify either the entrypoint // or a second process spawned after as a health check process. -TEST_F(sys_call_test, docker_container_no_healthcheck) -{ +TEST_F(sys_call_test, docker_container_no_healthcheck) { std::vector labels{}; healthcheck_helper("Dockerfile.no_healthcheck", false, "", "", labels); } // A container with HEALTHCHECK=none should behave identically to one // without any container at all. -TEST_F(sys_call_test, docker_container_none_healthcheck) -{ +TEST_F(sys_call_test, docker_container_none_healthcheck) { std::vector labels{}; healthcheck_helper("Dockerfile.none_healthcheck", false, "", "", labels); } @@ -820,8 +734,7 @@ TEST_F(sys_call_test, docker_container_none_healthcheck) // container but not identify entrypoint or second process after as // a health check process. Should identify at least one health // check executed for container. -TEST_F(sys_call_test, docker_container_healthcheck) -{ +TEST_F(sys_call_test, docker_container_healthcheck) { std::vector labels{}; healthcheck_helper("Dockerfile", true, "", "", labels); } @@ -829,82 +742,67 @@ TEST_F(sys_call_test, docker_container_healthcheck) // Run container w/ health check and entrypoint having identical // cmdlines. Should identify healthcheck but not entrypoint as a // health check process. -TEST_F(sys_call_test, docker_container_healthcheck_cmd_overlap) -{ +TEST_F(sys_call_test, docker_container_healthcheck_cmd_overlap) { std::vector labels{}; healthcheck_helper("Dockerfile", true, "", "", labels); } // A health check using shell exec instead of direct exec. -TEST_F(sys_call_test, docker_container_healthcheck_shell) -{ +TEST_F(sys_call_test, docker_container_healthcheck_shell) { std::vector labels{}; - healthcheck_helper("Dockerfile", true, "", "--health-cmd 'sh -c \"/bin/ut-health-check\"' --health-interval 0.5s", labels); + healthcheck_helper("Dockerfile", + true, + "", + "--health-cmd 'sh -c \"/bin/ut-health-check\"' --health-interval 0.5s", + labels); } // A health check where the container has docker labels that make it // look like it was started in k8s. -TEST_F(sys_call_test, docker_container_liveness_probe) -{ - const char* label= R""""(annotation.kubectl.kubernetes.io/last-applied-configuration="{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"mysql-app\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"env\":[{\"name\":\"MYSQL_ROOT_PASSWORD\",\"value\":\"no\"}],\"image\":\"user/mysql:healthcheck\",\"livenessProbe\":{\"exec\":{\"command\":[\"/bin/ut-health-check\"]},\"initialDelaySeconds\":5,\"periodSeconds\":5},\"name\":\"mysql\"}]}}\n")""""; +TEST_F(sys_call_test, docker_container_liveness_probe) { + const char* label = + R""""(annotation.kubectl.kubernetes.io/last-applied-configuration="{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"mysql-app\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"env\":[{\"name\":\"MYSQL_ROOT_PASSWORD\",\"value\":\"no\"}],\"image\":\"user/mysql:healthcheck\",\"livenessProbe\":{\"exec\":{\"command\":[\"/bin/ut-health-check\"]},\"initialDelaySeconds\":5,\"periodSeconds\":5},\"name\":\"mysql\"}]}}\n")""""; std::vector labels{std::string(label)}; - healthcheck_helper("Dockerfile", - true, - "", - "", - labels, - sinsp_threadinfo::CAT_LIVENESS_PROBE); + healthcheck_helper("Dockerfile", true, "", "", labels, sinsp_threadinfo::CAT_LIVENESS_PROBE); } -TEST_F(sys_call_test, docker_container_readiness_probe) -{ - const char* label = R""""(annotation.kubectl.kubernetes.io/last-applied-configuration="{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"mysql-app\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"env\":[{\"name\":\"MYSQL_ROOT_PASSWORD\",\"value\":\"no\"}],\"image\":\"user/mysql:healthcheck\",\"readinessProbe\":{\"exec\":{\"command\":[\"/bin/ut-health-check\"]},\"initialDelaySeconds\":5,\"periodSeconds\":5},\"name\":\"mysql\"}]}}\n")""""; +TEST_F(sys_call_test, docker_container_readiness_probe) { + const char* label = + R""""(annotation.kubectl.kubernetes.io/last-applied-configuration="{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"mysql-app\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"env\":[{\"name\":\"MYSQL_ROOT_PASSWORD\",\"value\":\"no\"}],\"image\":\"user/mysql:healthcheck\",\"readinessProbe\":{\"exec\":{\"command\":[\"/bin/ut-health-check\"]},\"initialDelaySeconds\":5,\"periodSeconds\":5},\"name\":\"mysql\"}]}}\n")""""; std::vector labels{std::string(label)}; - healthcheck_helper("Dockerfile", - true, - "", - "", - labels, - sinsp_threadinfo::CAT_READINESS_PROBE); + healthcheck_helper("Dockerfile", true, "", "", labels, sinsp_threadinfo::CAT_READINESS_PROBE); } // Identical to above tests, but read events from a trace file instead // of live. Only doing selected cases. -TEST_F(sys_call_test, docker_container_healthcheck_trace) -{ +TEST_F(sys_call_test, docker_container_healthcheck_trace) { healthcheck_tracefile_helper("Dockerfile.healthcheck", true); } -TEST_F(sys_call_test, docker_container_healthcheck_cmd_overlap_trace) -{ +TEST_F(sys_call_test, docker_container_healthcheck_cmd_overlap_trace) { healthcheck_tracefile_helper("Dockerfile.healthcheck_cmd_overlap", true); } -TEST_F(sys_call_test, docker_container_liveness_probe_trace) -{ +TEST_F(sys_call_test, docker_container_liveness_probe_trace) { healthcheck_tracefile_helper("Dockerfile.healthcheck_liveness", true, sinsp_threadinfo::CAT_LIVENESS_PROBE); } -TEST_F(sys_call_test, docker_container_readiness_probe_trace) -{ +TEST_F(sys_call_test, docker_container_readiness_probe_trace) { healthcheck_tracefile_helper("Dockerfile.healthcheck_readiness", true, sinsp_threadinfo::CAT_READINESS_PROBE); } - -TEST_F(sys_call_test, docker_container_large_json) -{ +TEST_F(sys_call_test, docker_container_large_json) { bool saw_container_evt = false; - if (!dutils_check_docker()) - { + if(!dutils_check_docker()) { return; } - std::string repeated_string = std::string(4096,'a'); + std::string repeated_string = std::string(4096, 'a'); std::vector labels; labels.emplace_back("url2=" + repeated_string); @@ -926,8 +824,7 @@ TEST_F(sys_call_test, docker_container_large_json) evt->get_type() == PPME_CONTAINER_JSON_2_E; }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { // set container label max to huge value { std::scoped_lock inspector_handle_lock(inspector_handle); @@ -938,15 +835,14 @@ TEST_F(sys_call_test, docker_container_large_json) ASSERT_TRUE(rc == 0); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { saw_container_evt = true; sinsp_threadinfo* tinfo = param.m_evt->get_thread_info(); ASSERT_TRUE(tinfo != NULL); const auto container_info = - param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); + param.m_inspector->m_container_manager.get_container(tinfo->m_container_id); ASSERT_NE(nullptr, container_info); ASSERT_EQ(container_info->m_type, CT_DOCKER); @@ -955,18 +851,17 @@ TEST_F(sys_call_test, docker_container_large_json) ASSERT_STREQ(container_info->m_image.c_str(), "large_container_ut_img"); std::unordered_set labels = { - "url2", - "summary2", - "vcs-type2", - "vcs-ref2", - "description2", - "io.k8s.description2", + "url2", + "summary2", + "vcs-type2", + "vcs-ref2", + "description2", + "io.k8s.description2", }; const std::string aaaaaa(4096, 'a'); - for (const auto& label : container_info->m_labels) - { + for(const auto& label : container_info->m_labels) { EXPECT_EQ(1, labels.erase(label.first)); EXPECT_EQ(4096, label.second.size()); EXPECT_EQ(aaaaaa, label.second); diff --git a/test/libsinsp_e2e/container/container_cgroup.cpp b/test/libsinsp_e2e/container/container_cgroup.cpp index ccc9df89d1..831b618d48 100644 --- a/test/libsinsp_e2e/container/container_cgroup.cpp +++ b/test/libsinsp_e2e/container/container_cgroup.cpp @@ -25,87 +25,79 @@ limitations under the License. using namespace libsinsp::runc; constexpr const cgroup_layout CRI_CGROUP_LAYOUT[] = { - {"/", ""}, // non-systemd containerd - {"/crio-", ""}, // non-systemd cri-o - {"/containerd-", ".scope"}, // systemd containerd (?) - {"/crio-", ".scope"}, // systemd cri-o - {":cri-containerd:", ""}, // unknown containerd seen in the wild - {nullptr, nullptr}}; + {"/", ""}, // non-systemd containerd + {"/crio-", ""}, // non-systemd cri-o + {"/containerd-", ".scope"}, // systemd containerd (?) + {"/crio-", ".scope"}, // systemd cri-o + {":cri-containerd:", ""}, // unknown containerd seen in the wild + {nullptr, nullptr}}; constexpr const cgroup_layout DOCKER_CGROUP_LAYOUT[] = {{"/", ""}, // non-systemd docker {"/docker-", ".scope"}, // systemd docker {nullptr, nullptr}}; -class container_cgroup : public testing::Test -{ -}; +class container_cgroup : public testing::Test {}; -TEST_F(container_cgroup, containerd_cgroupfs) -{ +TEST_F(container_cgroup, containerd_cgroupfs) { std::string container_id; const std::string cgroup = - "/kubepods/besteffort/podac04f3f2-1f2c-11e9-b015-1ebee232acfa/" - "605439acbd4fb18c145069289094b17f17e0cfa938f78012d4960bc797305f22"; + "/kubepods/besteffort/podac04f3f2-1f2c-11e9-b015-1ebee232acfa/" + "605439acbd4fb18c145069289094b17f17e0cfa938f78012d4960bc797305f22"; const std::string expected_container_id = "605439acbd4f"; EXPECT_EQ(true, match_container_id(cgroup, CRI_CGROUP_LAYOUT, container_id)); EXPECT_EQ(expected_container_id, container_id); } -TEST_F(container_cgroup, crio_cgroupfs) -{ +TEST_F(container_cgroup, crio_cgroupfs) { std::string container_id; const std::string cgroup = - "/kubepods/besteffort/pod63b3ebfc-2890-11e9-8154-16bf8ef8d9dc/" - "crio-73bfe475650de66df8e2affdc98d440dcbe84f8df83b6f75a68a82eb7026136a"; + "/kubepods/besteffort/pod63b3ebfc-2890-11e9-8154-16bf8ef8d9dc/" + "crio-73bfe475650de66df8e2affdc98d440dcbe84f8df83b6f75a68a82eb7026136a"; const std::string expected_container_id = "73bfe475650d"; EXPECT_EQ(true, match_container_id(cgroup, CRI_CGROUP_LAYOUT, container_id)); EXPECT_EQ(expected_container_id, container_id); } -TEST_F(container_cgroup, crio_systemd) -{ +TEST_F(container_cgroup, crio_systemd) { std::string container_id; const std::string cgroup = - "/kubepods.slice/kubepods-besteffort.slice/" - "kubepods-besteffort-pod63b3ebfc_2890_11e9_8154_16bf8ef8d9dc.slice/" - "crio-17d8c9eacc629f9945f304d89e9708c0c619649a484a215b240628319548a09f.scope"; + "/kubepods.slice/kubepods-besteffort.slice/" + "kubepods-besteffort-pod63b3ebfc_2890_11e9_8154_16bf8ef8d9dc.slice/" + "crio-17d8c9eacc629f9945f304d89e9708c0c619649a484a215b240628319548a09f.scope"; const std::string expected_container_id = "17d8c9eacc62"; EXPECT_EQ(true, match_container_id(cgroup, CRI_CGROUP_LAYOUT, container_id)); EXPECT_EQ(expected_container_id, container_id); } -TEST_F(container_cgroup, docker_cgroupfs) -{ +TEST_F(container_cgroup, docker_cgroupfs) { std::string container_id; const std::string cgroup = - "/docker/7951fb549ab99e0722a949b6c121634e1f3a36b5bacbe5392991e3b12251e6b8"; + "/docker/7951fb549ab99e0722a949b6c121634e1f3a36b5bacbe5392991e3b12251e6b8"; const std::string expected_container_id = "7951fb549ab9"; EXPECT_EQ(true, match_container_id(cgroup, DOCKER_CGROUP_LAYOUT, container_id)); EXPECT_EQ(expected_container_id, container_id); } -TEST_F(container_cgroup, docker_systemd) -{ +TEST_F(container_cgroup, docker_systemd) { std::string container_id; const std::string cgroup = - "/docker.slice/" - "docker-7951fb549ab99e0722a949b6c121634e1f3a36b5bacbe5392991e3b12251e6b8.scope"; + "/docker.slice/" + "docker-7951fb549ab99e0722a949b6c121634e1f3a36b5bacbe5392991e3b12251e6b8.scope"; const std::string expected_container_id = "7951fb549ab9"; EXPECT_EQ(true, match_container_id(cgroup, DOCKER_CGROUP_LAYOUT, container_id)); EXPECT_EQ(expected_container_id, container_id); } -TEST_F(container_cgroup, containerd_unknown) -{ +TEST_F(container_cgroup, containerd_unknown) { std::string container_id; const std::string cgroup = - "/kubepods-burstable-podbd12dd3393227d950605a2444b13c27a.slice:cri-containerd:" - "d52db56a9c80d536a91354c0951c061187ca46249e64865a12703003d8f42366"; + "/kubepods-burstable-podbd12dd3393227d950605a2444b13c27a.slice:cri-containerd:" + "d52db56a9c80d536a91354c0951c061187ca46249e64865a12703003d8f42366"; const std::string expected_container_id = "d52db56a9c80"; EXPECT_EQ(true, match_container_id(cgroup, CRI_CGROUP_LAYOUT, container_id)); diff --git a/test/libsinsp_e2e/container/docker_utils.cpp b/test/libsinsp_e2e/container/docker_utils.cpp index 3a592fb046..10996935bb 100644 --- a/test/libsinsp_e2e/container/docker_utils.cpp +++ b/test/libsinsp_e2e/container/docker_utils.cpp @@ -27,20 +27,16 @@ limitations under the License. using namespace std; -bool dutils_check_docker() -{ - if (system("service docker status > /dev/null 2>&1") != 0) - { - if (system("systemctl status docker > /dev/null 2>&1") != 0) - { +bool dutils_check_docker() { + if(system("service docker status > /dev/null 2>&1") != 0) { + if(system("systemctl status docker > /dev/null 2>&1") != 0) { printf("Docker not running, skipping test\n"); return false; } } // We depend on docker versions >= 1.10 - if (system("docker --version | grep -qE \"Docker version 1.[56789].\"") == 0) - { + if(system("docker --version | grep -qE \"Docker version 1.[56789].\"") == 0) { printf("Docker version too old, skipping test\n"); return false; } @@ -48,8 +44,7 @@ bool dutils_check_docker() return true; } -void dutils_create_tag(const char* tag, const char* image) -{ +void dutils_create_tag(const char* tag, const char* image) { std::string tag_cmd = string("docker tag ") + image + " " + tag + " > /dev/null 2>&1"; std::string remove_tag_cmd = string("(docker rmi ") + tag + " || true) > /dev/null 2>&1"; @@ -57,8 +52,7 @@ void dutils_create_tag(const char* tag, const char* image) EXPECT_EQ(system(tag_cmd.c_str()), 0); } -void dutils_kill_container_if_exists(const char* name) -{ +void dutils_kill_container_if_exists(const char* name) { std::string kill_cmd = string("(docker kill --signal SIGKILL ") + name + " || true) 2>&1"; std::string rm_cmd = string("(docker rm -fv ") + name + " || true) 2>&1"; @@ -66,53 +60,54 @@ void dutils_kill_container_if_exists(const char* name) system(rm_cmd.c_str()); } -void dutils_kill_container(const char* name) -{ +void dutils_kill_container(const char* name) { std::string kill_cmd = - string("(docker kill --signal SIGKILL ") + name + " || true) > /dev/null 2>&1"; + string("(docker kill --signal SIGKILL ") + name + " || true) > /dev/null 2>&1"; std::string rm_cmd = string("(docker rm -fv ") + name + " || true) > /dev/null 2>&1"; EXPECT_EQ(system(kill_cmd.c_str()), 0); EXPECT_EQ(system(rm_cmd.c_str()), 0); } -void dutils_kill_image(const char* image) -{ +void dutils_kill_image(const char* image) { std::string rmi_cmd = string("(docker rmi ") + image + " || true) > /dev/null 2>&1"; EXPECT_EQ(system(rmi_cmd.c_str()), 0); } -docker_helper::docker_helper(const std::string& dockerfile_path, const std::string& tagname, - const std::vector& labels, const std::string& build_extra_args, - const std::string& run_extra_args, const bool& verbose): - m_dockerfile_path(dockerfile_path), - m_tagname(tagname), - m_labels(labels), - m_build_extra_args(build_extra_args), - m_run_extra_args(run_extra_args), - m_verbose(verbose) {} +docker_helper::docker_helper(const std::string& dockerfile_path, + const std::string& tagname, + const std::vector& labels, + const std::string& build_extra_args, + const std::string& run_extra_args, + const bool& verbose): + m_dockerfile_path(dockerfile_path), + m_tagname(tagname), + m_labels(labels), + m_build_extra_args(build_extra_args), + m_run_extra_args(run_extra_args), + m_verbose(verbose) {} int docker_helper::build_image() { - std::string label_options; - for (const auto& label : m_labels) { - label_options += " --label " + label; - } - std::string command = "docker build " + m_build_extra_args + label_options + " -t " + m_tagname + " -f " + m_dockerfile_path + " ."; - if(!m_verbose) - { + std::string label_options; + for(const auto& label : m_labels) { + label_options += " --label " + label; + } + std::string command = "docker build " + m_build_extra_args + label_options + " -t " + + m_tagname + " -f " + m_dockerfile_path + " ."; + if(!m_verbose) { command += " > /dev/null 2>&1"; - } - return system(command.c_str()); + return system(command.c_str()); } -int docker_helper::run_container(const std::string& container_name, const std::string& cmd, const std::string& additional_options) { - std::string command = "docker run " + additional_options + " " + m_run_extra_args + " --name " + container_name + " " + m_tagname + " " + cmd; - if(!m_verbose) - { +int docker_helper::run_container(const std::string& container_name, + const std::string& cmd, + const std::string& additional_options) { + std::string command = "docker run " + additional_options + " " + m_run_extra_args + " --name " + + container_name + " " + m_tagname + " " + cmd; + if(!m_verbose) { command += " > /dev/null 2>&1"; - } - return system(command.c_str()); + return system(command.c_str()); } diff --git a/test/libsinsp_e2e/container/docker_utils.h b/test/libsinsp_e2e/container/docker_utils.h index d7c8518426..6008bada02 100644 --- a/test/libsinsp_e2e/container/docker_utils.h +++ b/test/libsinsp_e2e/container/docker_utils.h @@ -28,19 +28,23 @@ void dutils_kill_container_if_exists(const char* name); void dutils_kill_image(const char* image); class docker_helper { - public: - docker_helper(const std::string& dockerfile_path, const std::string& tagname, - const std::vector& labels, const std::string& build_extra_args, - const std::string& run_extra_args, const bool& verbose = false); - int build_image(); - int run_container(const std::string& containerName, const std::string& cmd, const std::string& additional_options = "--rm --network=none"); - - private: - std::string m_dockerfile_path; - std::string m_tagname; - std::vector m_labels; - std::string m_build_extra_args; - std::string m_run_extra_args; - bool m_verbose; - +public: + docker_helper(const std::string& dockerfile_path, + const std::string& tagname, + const std::vector& labels, + const std::string& build_extra_args, + const std::string& run_extra_args, + const bool& verbose = false); + int build_image(); + int run_container(const std::string& containerName, + const std::string& cmd, + const std::string& additional_options = "--rm --network=none"); + +private: + std::string m_dockerfile_path; + std::string m_tagname; + std::vector m_labels; + std::string m_build_extra_args; + std::string m_run_extra_args; + bool m_verbose; }; diff --git a/test/libsinsp_e2e/event_capture.cpp b/test/libsinsp_e2e/event_capture.cpp index 9059db35db..64e4c6e453 100644 --- a/test/libsinsp_e2e/event_capture.cpp +++ b/test/libsinsp_e2e/event_capture.cpp @@ -30,69 +30,56 @@ std::string event_capture::m_engine_path = ""; unsigned long event_capture::m_buffer_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM; bool event_capture::inspector_ok = false; -concurrent_object_handle event_capture::get_inspector_handle() -{ +concurrent_object_handle event_capture::get_inspector_handle() { return {get_inspector(), m_inspector_mutex}; } -void event_capture::init_inspector() -{ - get_inspector()->m_thread_manager->set_max_thread_table_size(m_max_thread_table_size); - get_inspector()->m_thread_timeout_ns = m_thread_timeout_ns; - get_inspector()->set_auto_threads_purging_interval_s(m_inactive_thread_scan_time_ns); - get_inspector()->set_auto_threads_purging(false); +void event_capture::init_inspector() { + get_inspector()->m_thread_manager->set_max_thread_table_size(m_max_thread_table_size); + get_inspector()->m_thread_timeout_ns = m_thread_timeout_ns; + get_inspector()->set_auto_threads_purging_interval_s(m_inactive_thread_scan_time_ns); + get_inspector()->set_auto_threads_purging(false); - get_inspector()->set_get_procs_cpu_from_driver(true); + get_inspector()->set_get_procs_cpu_from_driver(true); - ASSERT_FALSE(get_inspector()->is_capture()); - ASSERT_FALSE(get_inspector()->is_live()); - ASSERT_FALSE(get_inspector()->is_nodriver()); + ASSERT_FALSE(get_inspector()->is_capture()); + ASSERT_FALSE(get_inspector()->is_live()); + ASSERT_FALSE(get_inspector()->is_nodriver()); - try - { - if (m_mode == SINSP_MODE_NODRIVER) - { - get_inspector()->open_nodriver(); - } - else - { - open_engine(event_capture::get_engine(), {}); - } + try { + if(m_mode == SINSP_MODE_NODRIVER) { + get_inspector()->open_nodriver(); + } else { + open_engine(event_capture::get_engine(), {}); } - catch (sinsp_exception& e) + } catch(sinsp_exception& e) { + m_start_failed = true; + m_start_failure_message = + "couldn't open inspector (maybe driver hasn't been loaded yet?) err=" + + get_inspector()->getlasterr() + " exception=" + e.what(); { - m_start_failed = true; - m_start_failure_message = - "couldn't open inspector (maybe driver hasn't been loaded yet?) err=" + - get_inspector()->getlasterr() + " exception=" + e.what(); - { - m_capture_started = true; - m_condition_started.notify_one(); - } - return; + m_capture_started = true; + m_condition_started.notify_one(); } + return; + } - get_inspector()->set_debug_mode(true); - get_inspector()->set_hostname_and_port_resolution_mode(false); + get_inspector()->set_debug_mode(true); + get_inspector()->set_hostname_and_port_resolution_mode(false); } -void event_capture::capture() -{ +void event_capture::capture() { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); std::unique_ptr dumper; { std::scoped_lock init_lock(m_inspector_mutex, m_object_state_mutex); - if(!inspector_ok) - { + if(!inspector_ok) { init_inspector(); - if(!m_start_failed) - { + if(!m_start_failed) { inspector_ok = true; - } - else - { + } else { std::cerr << m_start_failure_message << std::endl; return; } @@ -103,12 +90,16 @@ void event_capture::capture() m_before_open(get_inspector()); get_inspector()->start_capture(); - if (m_mode != SINSP_MODE_NODRIVER) - { - m_dump_filename = std::string(LIBSINSP_TEST_CAPTURES_PATH) + test_info->test_case_name() + "_" + - test_info->name() + ".scap"; - dumper = std::make_unique(get_inspector(), m_dump_filename.c_str(), - 0, 0, 0, 0, true); + if(m_mode != SINSP_MODE_NODRIVER) { + m_dump_filename = std::string(LIBSINSP_TEST_CAPTURES_PATH) + + test_info->test_case_name() + "_" + test_info->name() + ".scap"; + dumper = std::make_unique(get_inspector(), + m_dump_filename.c_str(), + 0, + 0, + 0, + 0, + true); } } // End init synchronized section @@ -116,69 +107,55 @@ void event_capture::capture() sinsp_evt* event; bool result = true; int32_t next_result = SCAP_SUCCESS; - while (!m_capture_stopped && result && !::testing::Test::HasFatalFailure()) - { + while(!m_capture_stopped && result && !::testing::Test::HasFatalFailure()) { { std::scoped_lock inspector_next_lock(m_inspector_mutex); next_result = get_inspector()->next(&event); } - if (SCAP_SUCCESS == next_result) - { + if(SCAP_SUCCESS == next_result) { result = handle_event(event); - if (m_mode != SINSP_MODE_NODRIVER && m_dump) - { + if(m_mode != SINSP_MODE_NODRIVER && m_dump) { dumper->dump(event); } } - if (!signaled_start) - { + if(!signaled_start) { signaled_start = true; m_capture_started = true; m_condition_started.notify_one(); } } - if (m_mode != SINSP_MODE_NODRIVER) - { + if(m_mode != SINSP_MODE_NODRIVER) { uint32_t n_timeouts = 0; - while (result && !::testing::Test::HasFatalFailure()) - { + while(result && !::testing::Test::HasFatalFailure()) { { std::scoped_lock inspector_next_lock(m_inspector_mutex); next_result = get_inspector()->next(&event); } - if (next_result == SCAP_TIMEOUT) - { + if(next_result == SCAP_TIMEOUT) { n_timeouts++; - if (n_timeouts < m_max_timeouts) - { + if(n_timeouts < m_max_timeouts) { continue; - } - else - { + } else { break; } } - if (next_result == SCAP_FILTERED_EVENT) - { + if(next_result == SCAP_FILTERED_EVENT) { continue; } - if (next_result != SCAP_SUCCESS) - { + if(next_result != SCAP_SUCCESS) { break; } - if(m_dump) - { + if(m_dump) { dumper->dump(event); } result = handle_event(event); } { std::scoped_lock inspector_next_lock(m_inspector_mutex); - while (SCAP_SUCCESS == get_inspector()->next(&event)) - { + while(SCAP_SUCCESS == get_inspector()->next(&event)) { // just consume the remaining events } } @@ -189,19 +166,16 @@ void event_capture::capture() m_before_close(get_inspector()); get_inspector()->stop_capture(); - if (m_mode != SINSP_MODE_NODRIVER) - { + if(m_mode != SINSP_MODE_NODRIVER) { dumper->close(); } m_capture_stopped = true; m_condition_stopped.notify_one(); } // End teardown synchronized section - } -void event_capture::stop_capture() -{ +void event_capture::stop_capture() { { std::scoped_lock init_lock(m_inspector_mutex, m_object_state_mutex); m_capture_stopped = true; @@ -209,127 +183,98 @@ void event_capture::stop_capture() } } -void event_capture::wait_for_capture_start() -{ +void event_capture::wait_for_capture_start() { std::unique_lock lock(m_object_state_mutex); - m_condition_started.wait(lock, [this]() { - return m_capture_started; - }); + m_condition_started.wait(lock, [this]() { return m_capture_started; }); } -void event_capture::wait_for_capture_stop() -{ +void event_capture::wait_for_capture_stop() { std::unique_lock lock(m_object_state_mutex); - m_condition_stopped.wait(lock, [this]() { - return m_capture_stopped; - }); + m_condition_stopped.wait(lock, [this]() { return m_capture_stopped; }); } -void event_capture::re_read_dump_file() -{ - try - { +void event_capture::re_read_dump_file() { + try { sinsp inspector; sinsp_evt* event; inspector.open_savefile(m_dump_filename); uint32_t res; - do - { + do { res = inspector.next(&event); - } while (res == SCAP_SUCCESS); + } while(res == SCAP_SUCCESS); ASSERT_EQ((int)SCAP_EOF, (int)res); - } - catch (sinsp_exception& e) - { + } catch(sinsp_exception& e) { FAIL() << "caught exception " << e.what(); } } -bool event_capture:: -handle_event(sinsp_evt* event) -{ +bool event_capture::handle_event(sinsp_evt* event) { std::unique_lock object_state_lock(m_object_state_mutex); - if (::testing::Test::HasNonfatalFailure()) - { + if(::testing::Test::HasNonfatalFailure()) { return true; } bool res = true; - if (m_filter(event)) - { - try - { + if(m_filter(event)) { + try { m_param.m_evt = event; m_captured_event_callback(m_param); - } - catch(...) - { + } catch(...) { res = false; } } - if (!m_capture_continue()) - { + if(!m_capture_continue()) { return false; } - if (!res || ::testing::Test::HasNonfatalFailure()) - { + if(!res || ::testing::Test::HasNonfatalFailure()) { std::cerr << "failed on event " << event->get_num() << std::endl; } return res; } -void event_capture::open_engine(const std::string& engine_string, libsinsp::events::set events_sc_codes) -{ - if(false) - { +void event_capture::open_engine(const std::string& engine_string, + libsinsp::events::set events_sc_codes) { + if(false) { } #ifdef HAS_ENGINE_KMOD - else if(!engine_string.compare(KMOD_ENGINE)) - { + else if(!engine_string.compare(KMOD_ENGINE)) { get_inspector()->open_kmod(m_buffer_dim); } #endif #ifdef HAS_ENGINE_BPF - else if(!engine_string.compare(BPF_ENGINE)) - { - if(event_capture::get_engine().empty()) - { - std::cerr << "You must specify the path to the bpf probe if you use the 'bpf' engine" << std::endl; + else if(!engine_string.compare(BPF_ENGINE)) { + if(event_capture::get_engine().empty()) { + std::cerr << "You must specify the path to the bpf probe if you use the 'bpf' engine" + << std::endl; exit(EXIT_FAILURE); } get_inspector()->open_bpf(event_capture::get_engine_path().c_str(), m_buffer_dim); } #endif #ifdef HAS_ENGINE_MODERN_BPF - else if(!engine_string.compare(MODERN_BPF_ENGINE)) - { + else if(!engine_string.compare(MODERN_BPF_ENGINE)) { get_inspector()->open_modern_bpf(m_buffer_dim); } #endif - else - { + else { std::cerr << "Unknown engine" << std::endl; exit(EXIT_FAILURE); } } -void event_capture::set_engine(const std::string& engine_string, const std::string& engine_path) -{ +void event_capture::set_engine(const std::string& engine_string, const std::string& engine_path) { m_engine_string = engine_string; m_engine_path = engine_path; } -void event_capture::set_buffer_dim(const unsigned long& dim) -{ +void event_capture::set_buffer_dim(const unsigned long& dim) { m_buffer_dim = dim; } -const std::string& event_capture::get_engine() -{ +const std::string& event_capture::get_engine() { return m_engine_string; } -const std::string& event_capture::get_engine_path() -{ +const std::string& event_capture::get_engine_path() { return m_engine_path; } diff --git a/test/libsinsp_e2e/event_capture.h b/test/libsinsp_e2e/event_capture.h index 2a8a369479..cac9bbe2ed 100644 --- a/test/libsinsp_e2e/event_capture.h +++ b/test/libsinsp_e2e/event_capture.h @@ -33,8 +33,7 @@ limitations under the License. #include #include -class concurrent_object_handle_state_error : public std::logic_error -{ +class concurrent_object_handle_state_error : public std::logic_error { using std::logic_error::logic_error; }; @@ -46,62 +45,52 @@ class event_capture; * run_callback_t functions passed to event_capture::run(). */ template -class concurrent_object_handle -{ - public: - friend event_capture; - - /** - * Creates a new, unlocked handle with other's wrapped pointer and underlying mutex. - * @param other - */ - concurrent_object_handle(const concurrent_object_handle& other) noexcept - : m_object_ptr(other.m_object_ptr), - m_object_lock(*other.m_object_lock.mutex(), std::defer_lock) - { - } - - void lock() { m_object_lock.lock(); } - - T* operator->() - { - if (!m_object_lock.owns_lock()) - { - throw concurrent_object_handle_state_error( - "Attempt to access wrapped object without obtaining a lock."); - } - return m_object_ptr; +class concurrent_object_handle { +public: + friend event_capture; + + /** + * Creates a new, unlocked handle with other's wrapped pointer and underlying mutex. + * @param other + */ + concurrent_object_handle(const concurrent_object_handle& other) noexcept: + m_object_ptr(other.m_object_ptr), + m_object_lock(*other.m_object_lock.mutex(), std::defer_lock) {} + + void lock() { m_object_lock.lock(); } + + T* operator->() { + if(!m_object_lock.owns_lock()) { + throw concurrent_object_handle_state_error( + "Attempt to access wrapped object without obtaining a lock."); } + return m_object_ptr; + } - inline T* safe_ptr() { return operator->(); } + inline T* safe_ptr() { return operator->(); } - T& operator*() - { - if (!m_object_lock.owns_lock()) - { - throw concurrent_object_handle_state_error( - "Attempt to access wrapped object without obtaining a lock."); - } - return *m_object_ptr; + T& operator*() { + if(!m_object_lock.owns_lock()) { + throw concurrent_object_handle_state_error( + "Attempt to access wrapped object without obtaining a lock."); } + return *m_object_ptr; + } - T* unsafe_ptr() { return m_object_ptr; } + T* unsafe_ptr() { return m_object_ptr; } - void unlock() { m_object_lock.unlock(); } + void unlock() { m_object_lock.unlock(); } - private: - concurrent_object_handle(sinsp* object_ptr, std::mutex& object_mutex) - : m_object_ptr(object_ptr), - m_object_lock(object_mutex, std::defer_lock) - { - } +private: + concurrent_object_handle(sinsp* object_ptr, std::mutex& object_mutex): + m_object_ptr(object_ptr), + m_object_lock(object_mutex, std::defer_lock) {} - T* m_object_ptr; - std::unique_lock m_object_lock; + T* m_object_ptr; + std::unique_lock m_object_lock; }; -class callback_param -{ +class callback_param { public: sinsp_evt* m_evt; sinsp* m_inspector; @@ -118,8 +107,7 @@ typedef std::function capture_continue_t; typedef std::function inspector)> run_callback_t; -class event_capture -{ +class event_capture { public: void init_inspector(); void capture(); @@ -131,10 +119,9 @@ class event_capture static bool always_continue() { return true; } - sinsp* get_inspector() - { - static sinsp inspector = sinsp(); - return &inspector; + sinsp* get_inspector() { + static sinsp inspector = sinsp(); + return &inspector; } static void run(run_callback_t run_function, @@ -148,8 +135,7 @@ class event_capture uint64_t inactive_thread_scan_time_ns = (uint64_t)60 * 1000 * 1000 * 1000, sinsp_mode_t mode = SINSP_MODE_LIVE, uint64_t max_timeouts = 3, - bool dump = true) - { + bool dump = true) { event_capture capturing; { // Synchronized section std::unique_lock object_state_lock(capturing.m_object_state_mutex); @@ -166,21 +152,15 @@ class event_capture capturing.m_dump = dump; } - - std::thread thread([&capturing]() { - capturing.capture(); - }); + std::thread thread([&capturing]() { capturing.capture(); }); capturing.wait_for_capture_start(); - if (!capturing.m_start_failed.load()) - { + if(!capturing.m_start_failed.load()) { run_function(capturing.get_inspector_handle()); capturing.stop_capture(); capturing.wait_for_capture_stop(); - } - else - { + } else { std::unique_lock error_lookup_lock(capturing.m_object_state_mutex); GTEST_MESSAGE_(capturing.m_start_failure_message.c_str(), ::testing::TestPartResult::kFatalFailure); @@ -198,12 +178,7 @@ class event_capture static unsigned long m_buffer_dim; private: - event_capture() - : m_capture_started(false), - m_capture_stopped(false), - m_start_failed(false) - { - } + event_capture(): m_capture_started(false), m_capture_stopped(false), m_start_failed(false) {} concurrent_object_handle get_inspector_handle(); @@ -211,7 +186,8 @@ class event_capture bool handle_event(sinsp_evt* event); - void open_engine(const std::string& engine_string, libsinsp::events::set events_sc_codes); + void open_engine(const std::string& engine_string, + libsinsp::events::set events_sc_codes); std::mutex m_inspector_mutex; // Always lock first std::mutex m_object_state_mutex; // Always lock second diff --git a/test/libsinsp_e2e/forking.cpp b/test/libsinsp_e2e/forking.cpp index 6ab803bc2b..98a01a8154 100644 --- a/test/libsinsp_e2e/forking.cpp +++ b/test/libsinsp_e2e/forking.cpp @@ -39,8 +39,7 @@ limitations under the License. #define FILENAME "test_tmpfile" -TEST_F(sys_call_test, forking) -{ +TEST_F(sys_call_test, forking) { // int callnum = 0; int ptid; // parent tid @@ -51,30 +50,29 @@ TEST_F(sys_call_test, forking) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_tid() == ptid || evt->get_tid() == ctid; }; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_tid() == ptid || evt->get_tid() == ctid; + }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { pid_t childtid; int status; childtid = fork(); int fd = creat(FILENAME, S_IRWXU); - if (childtid >= 0) // fork succeeded + if(childtid >= 0) // fork succeeded { - if (childtid == 0) // fork() returns 0 to the child process + if(childtid == 0) // fork() returns 0 to the child process { ctid = getpid(); usleep(100); // sleep for 0.1 seconds close(fd); _exit(xstatus); // child exits with specific return code - } - else // fork() returns new pid to the parent process + } else // fork() returns new pid to the parent process { ptid = getpid(); gptid = getppid(); @@ -84,9 +82,7 @@ TEST_F(sys_call_test, forking) wait(&status); // wait for child to exit, and store its status // Use WEXITSTATUS to validate status. } - } - else - { + } else { FAIL(); } }; @@ -99,8 +95,7 @@ TEST_F(sys_call_test, forking) ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); } -TEST_F(sys_call_test, forking_while_scap_stopped) -{ +TEST_F(sys_call_test, forking_while_scap_stopped) { int ptid; // parent tid int ctid; // child tid int xstatus = 33; // child exit value @@ -108,14 +103,14 @@ TEST_F(sys_call_test, forking_while_scap_stopped) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_tid() == ptid || evt->get_tid() == ctid; }; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_tid() == ptid || evt->get_tid() == ctid; + }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int status; // @@ -130,9 +125,9 @@ TEST_F(sys_call_test, forking_while_scap_stopped) int fd = creat(FILENAME, S_IRWXU); - if (ctid >= 0) // fork succeeded + if(ctid >= 0) // fork succeeded { - if (ctid == 0) // fork() returns 0 to the child process + if(ctid == 0) // fork() returns 0 to the child process { // // Restart the capture. @@ -152,19 +147,16 @@ TEST_F(sys_call_test, forking_while_scap_stopped) usleep(5000000); close(fd); _exit(xstatus); // child exits with specific return code - } - else // fork() returns new pid to the parent process + } else // fork() returns new pid to the parent process { ptid = getpid(); close(fd); wait(&status); // wait for child to exit, and store its status - // Use WEXITSTATUS to validate status. + // Use WEXITSTATUS to validate status. } - } - else - { + } else { FAIL(); } }; @@ -175,35 +167,29 @@ TEST_F(sys_call_test, forking_while_scap_stopped) bool child_exists = false; bool parent_exists = false; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (e->get_type() == PPME_SCHEDSWITCH_1_E || e->get_type() == PPME_SCHEDSWITCH_6_E || - e->get_type() == PPME_PROCINFO_E) - { + if(e->get_type() == PPME_SCHEDSWITCH_1_E || e->get_type() == PPME_SCHEDSWITCH_6_E || + e->get_type() == PPME_PROCINFO_E) { return; } // // In both cases, the process should exist // - if (e->get_tid() == ptid && !parent_exists) - { + if(e->get_tid() == ptid && !parent_exists) { sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti) - { + if(ti) { parent_exists = true; } EXPECT_NE((sinsp_threadinfo*)NULL, ti); } - if (e->get_tid() == ctid && !child_exists) - { + if(e->get_tid() == ctid && !child_exists) { sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti) - { + if(ti) { child_exists = true; } @@ -217,8 +203,7 @@ TEST_F(sys_call_test, forking_while_scap_stopped) EXPECT_TRUE(parent_exists); } -TEST_F(sys_call_test, forking_process_expired) -{ +TEST_F(sys_call_test, forking_process_expired) { int ptid; // parent tid int ctid; // child tid int status; @@ -231,18 +216,16 @@ TEST_F(sys_call_test, forking_process_expired) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { ctid = fork(); - if (ctid >= 0) // fork succeeded + if(ctid >= 0) // fork succeeded { - if (ctid == 0) // fork() returns 0 to the child process + if(ctid == 0) // fork() returns 0 to the child process { pause(); FAIL(); - } - else // fork() returns new pid to the parent process + } else // fork() returns new pid to the parent process { ptid = getpid(); @@ -258,9 +241,7 @@ TEST_F(sys_call_test, forking_process_expired) kill(ctid, SIGUSR1); wait(&status); } - } - else - { + } else { FAIL(); } }; @@ -270,22 +251,17 @@ TEST_F(sys_call_test, forking_process_expired) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (e->get_tid() == ptid) - { - if (e->get_type() == PPME_SYSCALL_NANOSLEEP_E && !sleep_caught) - { + if(e->get_tid() == ptid) { + if(e->get_type() == PPME_SYSCALL_NANOSLEEP_E && !sleep_caught) { // // The child should exist // sinsp_threadinfo* ti = param.m_inspector->get_thread_ref(ctid, false, true).get(); EXPECT_NE((sinsp_threadinfo*)NULL, ti); - } - else if (e->get_type() == PPME_SYSCALL_NANOSLEEP_X && !sleep_caught) - { + } else if(e->get_type() == PPME_SYSCALL_NANOSLEEP_X && !sleep_caught) { // // The child should exist // @@ -293,9 +269,7 @@ TEST_F(sys_call_test, forking_process_expired) EXPECT_NE((sinsp_threadinfo*)NULL, ti); sleep_caught = true; } - } - else - { + } else { FAIL(); } }; @@ -304,11 +278,11 @@ TEST_F(sys_call_test, forking_process_expired) event_capture::run(test, callback, filter, - event_capture::do_nothing, - event_capture::do_nothing, - event_capture::always_continue, - 131072, - 5 * ONE_SECOND_IN_NS, + event_capture::do_nothing, + event_capture::do_nothing, + event_capture::always_continue, + 131072, + 5 * ONE_SECOND_IN_NS, ONE_SECOND_IN_NS); }); @@ -320,14 +294,12 @@ TEST_F(sys_call_test, forking_process_expired) /////////////////////////////////////////////////////////////////////////////// int ctid; // child tid -typedef struct -{ +typedef struct { int fd; int signal; } clone_params; -static int clone_callback_1(void* arg) -{ +static int clone_callback_1(void* arg) { clone_params* cp; cp = (clone_params*)arg; /* Cast arg to true form */ @@ -352,8 +324,7 @@ static int clone_callback_1(void* arg) * unintended side effects.` Given that we'll disable it upon further * investigation. */ -TEST_F(sys_call_test, DISABLED_forking_clone_fs) -{ +TEST_F(sys_call_test, DISABLED_forking_clone_fs) { int callnum = 0; char bcwd[1024]; int prfd; @@ -362,19 +333,20 @@ TEST_F(sys_call_test, DISABLED_forking_clone_fs) int child_tid; int parent_res; int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_PARENT_SETTID; - int drflags = PPM_CL_CLONE_FILES | PPM_CL_CLONE_FS | PPM_CL_CLONE_VM | PPM_CL_CLONE_PARENT_SETTID; + int drflags = + PPM_CL_CLONE_FILES | PPM_CL_CLONE_FS | PPM_CL_CLONE_VM | PPM_CL_CLONE_PARENT_SETTID; // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_tid() == ptid || evt->get_tid() == child_tid; }; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_tid() == ptid || evt->get_tid() == child_tid; + }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { const int STACK_SIZE = 65536; /* Stack size for cloned child */ char* stack; /* Start of stack buffer area */ char* stackTop; /* End of stack buffer area */ @@ -388,12 +360,12 @@ TEST_F(sys_call_test, DISABLED_forking_clone_fs) set some process attributes that will be modified by child */ cp.fd = open(FILENAME, O_CREAT | O_WRONLY, S_IRWXU); /* Child will close this fd */ - if (cp.fd == -1) + if(cp.fd == -1) FAIL(); prfd = cp.fd; cp.signal = SIGTERM; /* Child will change disposition */ - if (signal(cp.signal, SIG_IGN) == SIG_ERR) + if(signal(cp.signal, SIG_IGN) == SIG_ERR) FAIL(); /* Initialize clone flags using command-line argument (if supplied) */ @@ -401,22 +373,21 @@ TEST_F(sys_call_test, DISABLED_forking_clone_fs) /* Allocate stack for child */ stack = (char*)malloc(STACK_SIZE); - if (stack == NULL) + if(stack == NULL) FAIL(); stackTop = stack + STACK_SIZE; /* Assume stack grows downward */ /* Create child; child commences execution in childFunc() */ - clone_tid = clone(clone_callback_1, stackTop, flags, &cp, - &child_tid); - if (clone_tid == -1) + clone_tid = clone(clone_callback_1, stackTop, flags, &cp, &child_tid); + if(clone_tid == -1) FAIL(); /* Parent falls through to here. Wait for child; __WCLONE option is required for child notifying with signal other than SIGCHLD. */ pid = waitpid(clone_tid, &status, __WCLONE); - if (pid == -1) + if(pid == -1) FAIL(); close(cp.fd); @@ -428,25 +399,19 @@ TEST_F(sys_call_test, DISABLED_forking_clone_fs) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (e->get_type() == PPME_SYSCALL_CLONE_20_X && callnum == 0) - { + if(e->get_type() == PPME_SYSCALL_CLONE_20_X && callnum == 0) { uint64_t res = std::stoll(e->get_param_value_str("res", false)); sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti->get_comm() != "libsinsp_e2e_te") - { + if(ti->get_comm() != "libsinsp_e2e_te") { return; } - if (res == 0) - { + if(res == 0) { EXPECT_EQ(child_tid, ti->m_tid); - } - else - { + } else { EXPECT_EQ(ptid, ti->m_tid); } @@ -455,51 +420,38 @@ TEST_F(sys_call_test, DISABLED_forking_clone_fs) std::string tmps = getcwd(bcwd, 1024); EXPECT_EQ(tmps + "/", ti->get_cwd()); EXPECT_EQ("", e->get_param_value_str("cwd")); - if(drflags == std::stol(e->get_param_value_str("flags", false))) - { + if(drflags == std::stol(e->get_param_value_str("flags", false))) { callnum++; } - } - else if (e->get_type() == PPME_SYSCALL_CLOSE_E) - { + } else if(e->get_type() == PPME_SYSCALL_CLOSE_E) { sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti->m_tid == ptid || ti->m_tid == child_tid) - { + if(ti->m_tid == ptid || ti->m_tid == child_tid) { int64_t clfd = std::stoll(e->get_param_value_str("fd", false)); - if (clfd == prfd) - { + if(clfd == prfd) { callnum++; } } - } - else if (e->get_type() == PPME_SYSCALL_CLOSE_X) - { + } else if(e->get_type() == PPME_SYSCALL_CLOSE_X) { sinsp_threadinfo* ti = e->get_thread_info(false); - if (callnum < 3) - { + if(callnum < 3) { return; } int64_t res = std::stoll(e->get_param_value_str("res", false)); - if (ti->m_tid == ptid) - { + if(ti->m_tid == ptid) { sinsp_fdinfo* fdi = ti->get_fd(prfd); - if(fdi && fdi->tostring_clean().find(FILENAME) != std::string::npos) - { - EXPECT_EQ(parent_res, res) << "filename: " - << fdi->tostring_clean() << std::endl - << "res: " << res << std::endl - << "parent tid: " << ptid << std::endl - << "child tid: " << child_tid << std::endl - << "clone tid: " << clone_tid << std::endl; + if(fdi && fdi->tostring_clean().find(FILENAME) != std::string::npos) { + EXPECT_EQ(parent_res, res) << "filename: " << fdi->tostring_clean() << std::endl + << "res: " << res << std::endl + << "parent tid: " << ptid << std::endl + << "child tid: " << child_tid << std::endl + << "clone tid: " << clone_tid << std::endl; } - } - else if (ti->m_tid == child_tid) - { + } else if(ti->m_tid == child_tid) { EXPECT_EQ(0, res); } @@ -511,8 +463,7 @@ TEST_F(sys_call_test, DISABLED_forking_clone_fs) EXPECT_EQ(callnum, 4); } -TEST_F(sys_call_test, forking_clone_nofs) -{ +TEST_F(sys_call_test, forking_clone_nofs) { int callnum = 0; char bcwd[1024]; int prfd; @@ -523,14 +474,14 @@ TEST_F(sys_call_test, forking_clone_nofs) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_tid() == ptid || evt->get_tid() == ctid; }; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_tid() == ptid || evt->get_tid() == ctid; + }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { const int STACK_SIZE = 65536; /* Stack size for cloned child */ char* stack; /* Start of stack buffer area */ char* stackTop; /* End of stack buffer area */ @@ -544,12 +495,12 @@ TEST_F(sys_call_test, forking_clone_nofs) set some process attributes that will be modified by child */ cp.fd = open(FILENAME, O_CREAT | O_WRONLY, S_IRWXU); /* Child will close this fd */ - if (cp.fd == -1) + if(cp.fd == -1) FAIL(); prfd = cp.fd; cp.signal = SIGTERM; /* Child will change disposition */ - if (signal(cp.signal, SIG_IGN) == SIG_ERR) + if(signal(cp.signal, SIG_IGN) == SIG_ERR) FAIL(); /* Initialize clone flags using command-line argument (if supplied) */ @@ -557,20 +508,20 @@ TEST_F(sys_call_test, forking_clone_nofs) /* Allocate stack for child */ stack = (char*)malloc(STACK_SIZE); - if (stack == NULL) + if(stack == NULL) FAIL(); stackTop = stack + STACK_SIZE; /* Assume stack grows downward */ /* Create child; child commences execution in childFunc() */ - if (clone(clone_callback_1, stackTop, flags, &cp) == -1) + if(clone(clone_callback_1, stackTop, flags, &cp) == -1) FAIL(); /* Parent falls through to here. Wait for child; __WCLONE option is required for child notifying with signal other than SIGCHLD. */ pid = waitpid(-1, &status, __WCLONE); - if (pid == -1) + if(pid == -1) FAIL(); close(cp.fd); @@ -582,25 +533,19 @@ TEST_F(sys_call_test, forking_clone_nofs) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (e->get_type() == PPME_SYSCALL_CLONE_20_X && callnum == 0) - { + if(e->get_type() == PPME_SYSCALL_CLONE_20_X && callnum == 0) { uint64_t res = std::stoull(e->get_param_value_str("res", false)); sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti->get_comm() != "libsinsp_e2e_te") - { + if(ti->get_comm() != "libsinsp_e2e_te") { return; } - if (res == 0) - { + if(res == 0) { EXPECT_EQ(ctid, ti->m_tid); - } - else - { + } else { EXPECT_EQ(ptid, ti->m_tid); } @@ -609,42 +554,31 @@ TEST_F(sys_call_test, forking_clone_nofs) std::string tmps = getcwd(bcwd, 1024); EXPECT_EQ(tmps + "/", ti->get_cwd()); EXPECT_EQ("", e->get_param_value_str("cwd")); - if(drflags == std::stol(e->get_param_value_str("flags", false))) - { + if(drflags == std::stol(e->get_param_value_str("flags", false))) { callnum++; } - } - else if (e->get_type() == PPME_SYSCALL_CLOSE_E) - { + } else if(e->get_type() == PPME_SYSCALL_CLOSE_E) { sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti->m_tid == ptid || ti->m_tid == ctid) - { + if(ti->m_tid == ptid || ti->m_tid == ctid) { int64_t clfd = std::stoll(e->get_param_value_str("fd", false)); - if (clfd == prfd) - { + if(clfd == prfd) { callnum++; } } - } - else if (e->get_type() == PPME_SYSCALL_CLOSE_X) - { + } else if(e->get_type() == PPME_SYSCALL_CLOSE_X) { sinsp_threadinfo* ti = e->get_thread_info(false); - if (callnum < 3) - { + if(callnum < 3) { return; } int64_t res = std::stoll(e->get_param_value_str("res", false)); - if (ti->m_tid == ptid) - { + if(ti->m_tid == ptid) { EXPECT_EQ(0, res); - } - else if (ti->m_tid == ctid) - { + } else if(ti->m_tid == ctid) { EXPECT_EQ(0, res); } @@ -656,12 +590,10 @@ TEST_F(sys_call_test, forking_clone_nofs) EXPECT_EQ(callnum, 4); } -static int clone_callback_2(void* arg) -{ +static int clone_callback_2(void* arg) { char bcwd[256]; - if (chdir("/") != 0) - { + if(chdir("/") != 0) { return -1; } std::string tmps = getcwd(bcwd, 256); @@ -669,8 +601,7 @@ static int clone_callback_2(void* arg) return -1; } -TEST_F(sys_call_test, forking_clone_cwd) -{ +TEST_F(sys_call_test, forking_clone_cwd) { int callnum = 0; char oriwd[1024]; char bcwd[256]; @@ -687,8 +618,7 @@ TEST_F(sys_call_test, forking_clone_cwd) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { const int STACK_SIZE = 65536; /* Stack size for cloned child */ char* stack; /* Start of stack buffer area */ char* stackTop; /* End of stack buffer area */ @@ -701,14 +631,13 @@ TEST_F(sys_call_test, forking_clone_cwd) /* Allocate stack for child */ stack = (char*)malloc(STACK_SIZE); - if (stack == NULL) + if(stack == NULL) FAIL(); stackTop = stack + STACK_SIZE; /* Assume stack grows downward */ /* Create child; child commences execution in childFunc() */ - if (clone(clone_callback_2, stackTop, flags, &cp) == -1) - { + if(clone(clone_callback_2, stackTop, flags, &cp) == -1) { FAIL(); } @@ -725,24 +654,18 @@ TEST_F(sys_call_test, forking_clone_cwd) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (e->get_type() == PPME_SYSCALL_CLONE_20_X) - { + if(e->get_type() == PPME_SYSCALL_CLONE_20_X) { uint64_t res = std::stoull(e->get_param_value_str("res", false)); sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti->get_comm() != "libsinsp_e2e_te") - { + if(ti->get_comm() != "libsinsp_e2e_te") { return; } - if (res == 0) - { + if(res == 0) { EXPECT_EQ(ctid, ti->m_tid); - } - else - { + } else { EXPECT_EQ(ptid, ti->m_tid); } @@ -750,20 +673,14 @@ TEST_F(sys_call_test, forking_clone_cwd) EXPECT_EQ("libsinsp_e2e_te", ti->get_comm()); EXPECT_EQ(drflags, std::stol(e->get_param_value_str("flags", false))); callnum++; - } - else if (e->get_type() == PPME_SYSCALL_GETCWD_E) - { + } else if(e->get_type() == PPME_SYSCALL_GETCWD_E) { sinsp_threadinfo* ti = e->get_thread_info(false); - if (ti->m_tid == ptid) - { - if (callnum > 1) - { + if(ti->m_tid == ptid) { + if(callnum > 1) { EXPECT_EQ(bcwd, ti->get_cwd()); } - } - else if (ti->m_tid == ctid) - { + } else if(ti->m_tid == ctid) { EXPECT_EQ("/", ti->get_cwd()); } @@ -776,44 +693,35 @@ TEST_F(sys_call_test, forking_clone_cwd) EXPECT_EQ(3, callnum); } -TEST_F(sys_call_test, forking_main_thread_exit) -{ +TEST_F(sys_call_test, forking_main_thread_exit) { int evtnum = 0; int callnum = 0; int fd; pid_t cpid; // parent tid - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { sinsp_threadinfo* ti = evt->get_thread_info(); - if (ti) - { + if(ti) { return ti->m_pid == cpid; - } - else - { + } else { return false; } }; - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { int status; // ptid = getpid(); cpid = fork(); EXPECT_NE(-1, cpid); - if (cpid == 0) - { + if(cpid == 0) { execlp(LIBSINSP_TEST_RESOURCES_PATH "/forking_main_thread_exit", LIBSINSP_TEST_RESOURCES_PATH "/forking_main_thread_exit", NULL); perror("execlp"); FAIL(); - } - else - { + } else { // // Father, just wait for termination // @@ -821,35 +729,24 @@ TEST_F(sys_call_test, forking_main_thread_exit) } }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { evtnum++; - if (param.m_evt->get_type() == PPME_SYSCALL_OPEN_X) - { - if (param.m_evt->get_param_value_str("name") == "/etc/passwd") - { + if(param.m_evt->get_type() == PPME_SYSCALL_OPEN_X) { + if(param.m_evt->get_param_value_str("name") == "/etc/passwd") { EXPECT_EQ("/etc/passwd", param.m_evt->get_param_value_str("fd")); fd = *(int64_t*)param.m_evt->get_param(0)->m_val; ++callnum; } - } - else if (param.m_evt->get_type() == PPME_SYSCALL_OPENAT_2_X) - { - if (param.m_evt->get_param_value_str("name") == "/etc/passwd") - { + } else if(param.m_evt->get_type() == PPME_SYSCALL_OPENAT_2_X) { + if(param.m_evt->get_param_value_str("name") == "/etc/passwd") { EXPECT_EQ("/etc/passwd", param.m_evt->get_param_value_str("fd")); memcpy(&fd, (int64_t*)param.m_evt->get_param(0)->m_val, sizeof(fd)); ++callnum; } - } - else if (param.m_evt->get_type() == PPME_PROCEXIT_1_E && param.m_evt->get_tid() == cpid) - { + } else if(param.m_evt->get_type() == PPME_PROCEXIT_1_E && param.m_evt->get_tid() == cpid) { ++callnum; - } - else if (param.m_evt->get_type() == PPME_SYSCALL_READ_E) - { - if (memcmp(&fd, param.m_evt->get_param(0)->m_val, sizeof(fd)) == 0) - { + } else if(param.m_evt->get_type() == PPME_SYSCALL_READ_E) { + if(memcmp(&fd, param.m_evt->get_param(0)->m_val, sizeof(fd)) == 0) { EXPECT_EQ("/etc/passwd", param.m_evt->get_param_value_str("fd")); ++callnum; } @@ -878,13 +775,11 @@ TEST_F(sys_call_test, forking_main_thread_exit) // Create the initial stale process. It chdir()s to "/dev", stops the // inspector, and returns. -static int stop_sinsp_and_exit(void* arg) -{ +static int stop_sinsp_and_exit(void* arg) { // Get our own, unlocked concurrent inspector handle concurrent_object_handle inspector_handle = *(concurrent_object_handle*)arg; - if (chdir("/dev") != 0) - { + if(chdir("/dev") != 0) { return 1; } @@ -902,13 +797,11 @@ static int stop_sinsp_and_exit(void* arg) } // Immediately return. Started by launcher. -static int do_nothing(void* arg) -{ +static int do_nothing(void* arg) { return 0; } -struct stale_clone_ctx -{ +struct stale_clone_ctx { std::mutex m_perform_clone_mtx; std::condition_variable m_perform_clone; bool m_clone_ready; @@ -923,8 +816,7 @@ static pid_t clone_helper(int (*func)(void*), // Wait until signaled by the main test thread, start a single // do_nothing(), signal the main test thread, and exit. -static int launcher(void* arg) -{ +static int launcher(void* arg) { stale_clone_ctx* ctx = (stale_clone_ctx*)arg; std::unique_lock lk(ctx->m_perform_clone_mtx); ctx->m_perform_clone.wait(lk, [&] { return ctx->m_clone_ready; }); @@ -936,8 +828,7 @@ static int launcher(void* arg) lk.unlock(); ctx->m_perform_clone.notify_one(); - if (child == 0) - { + if(child == 0) { return 1; } @@ -952,8 +843,7 @@ static pid_t clone_helper(int (*func)(void*), void* arg, int addl_clone_args, bool wait_for_complete, - char** stackp) -{ + char** stackp) { const int STACK_SIZE = 65536; /* Stack size for cloned child */ char* stack; /* Start of stack buffer area */ char* stackTop; /* End of stack buffer area */ @@ -962,39 +852,32 @@ static pid_t clone_helper(int (*func)(void*), /* Allocate stack for child */ stack = (char*)malloc(STACK_SIZE); - if (stack == NULL) - { + if(stack == NULL) { return 0; } stackTop = stack + STACK_SIZE; /* Assume stack grows downward */ - if ((pid = clone(func, stackTop, flags, arg)) == -1) - { + if((pid = clone(func, stackTop, flags, arg)) == -1) { free(stack); return 0; } - if (wait_for_complete) - { + if(wait_for_complete) { int status; - if (waitpid(pid, &status, 0) == -1 || status != 0) - { + if(waitpid(pid, &status, 0) == -1 || status != 0) { pid = 0; } free(stack); - } - else - { + } else { *stackp = stack; } return pid; } -TEST_F(sys_call_test, remove_stale_thread_clone_exit) -{ +TEST_F(sys_call_test, remove_stale_thread_clone_exit) { std::atomic clones_seen(0); stale_clone_ctx ctx; std::atomic recycle_pid(0); @@ -1009,8 +892,7 @@ TEST_F(sys_call_test, remove_stale_thread_clone_exit) // those cases, we print a message and trivially pass // the test. - if (stat(last_pid_filename, &info) == -1 && errno == ENOENT) - { + if(stat(last_pid_filename, &info) == -1 && errno == ENOENT) { fprintf(stderr, "Doing nothing as %s does not exist\n", last_pid_filename); return; } @@ -1019,15 +901,13 @@ TEST_F(sys_call_test, remove_stale_thread_clone_exit) // recycle_pid is only set once the first thread exits, this // effectively captures the actions of the second thread that // uses the recycled pid. - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); pid_t rp = recycle_pid.load(); return (rp != 0 && tinfo && tinfo->m_tid == rp); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { pid_t launcher_pid; char* launcher_stack = NULL; @@ -1110,17 +990,15 @@ TEST_F(sys_call_test, remove_stale_thread_clone_exit) // If any event with pid=recycled_pid has a cwd of // /dev/, the test fails. - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t etype = e->get_type(); sinsp_threadinfo* tinfo = e->get_thread_info(); ASSERT_TRUE((tinfo != NULL)); - if ((etype == PPME_SYSCALL_CLONE_11_X || etype == PPME_SYSCALL_CLONE_16_X || - etype == PPME_SYSCALL_CLONE_17_X || etype == PPME_SYSCALL_CLONE_20_X) && - e->get_direction() == SCAP_ED_OUT) - { + if((etype == PPME_SYSCALL_CLONE_11_X || etype == PPME_SYSCALL_CLONE_16_X || + etype == PPME_SYSCALL_CLONE_17_X || etype == PPME_SYSCALL_CLONE_20_X) && + e->get_direction() == SCAP_ED_OUT) { ++clones_seen; } diff --git a/test/libsinsp_e2e/fs.cpp b/test/libsinsp_e2e/fs.cpp index b2d9b83865..647f548034 100644 --- a/test/libsinsp_e2e/fs.cpp +++ b/test/libsinsp_e2e/fs.cpp @@ -53,8 +53,7 @@ limitations under the License. ///////////////////////////////////////////////////////////////////////////////////// // creat/unlink ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_creat_ulink) -{ +TEST_F(sys_call_test, fs_creat_ulink) { int callnum = 0; char bcwd[1024]; @@ -70,12 +69,10 @@ TEST_F(sys_call_test, fs_creat_ulink) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { int fd = creat(FILENAME, 0644); - if (fd < 0) - { + if(fd < 0) { FAIL(); } @@ -88,63 +85,49 @@ TEST_F(sys_call_test, fs_creat_ulink) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); std::string name(e->get_name()); - #if defined(__x86_64__) - if (type == PPME_SYSCALL_CREAT_E) - #else - if (name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_IN) - #endif +#if defined(__x86_64__) + if(type == PPME_SYSCALL_CREAT_E) +#else + if(name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_IN) +#endif { callnum++; } - #if defined(__x86_64__) - else if (type == PPME_SYSCALL_CREAT_X) - #else - else if (name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_OUT) +#if defined(__x86_64__) + else if(type == PPME_SYSCALL_CREAT_X) +#else + else if(name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_OUT) #endif { - if (callnum == 1) - { + if(callnum == 1) { std::string fname = e->get_param_value_str("name", false); - if (fname == FILENAME) - { + if(fname == FILENAME) { EXPECT_EQ("0644", e->get_param_value_str("mode")); } EXPECT_LT(0, std::stoll(e->get_param_value_str("fd", false))); callnum++; } - } - else if (type == PPME_SYSCALL_UNLINK_2_E || type == PPME_SYSCALL_UNLINKAT_2_E) - { - if (callnum == 2 || callnum == 4) - { + } else if(type == PPME_SYSCALL_UNLINK_2_E || type == PPME_SYSCALL_UNLINKAT_2_E) { + if(callnum == 2 || callnum == 4) { callnum++; } - } - else if (type == PPME_SYSCALL_UNLINK_2_X || type == PPME_SYSCALL_UNLINKAT_2_X) - { - if (callnum == 3) - { - if(type == PPME_SYSCALL_UNLINK_2_X) - { + } else if(type == PPME_SYSCALL_UNLINK_2_X || type == PPME_SYSCALL_UNLINKAT_2_X) { + if(callnum == 3) { + if(type == PPME_SYSCALL_UNLINK_2_X) { EXPECT_EQ(FILENAME, e->get_param_value_str("path", false)); EXPECT_EQ(cwd + FILENAME, e->get_param_value_str("path")); - } - else - { + } else { EXPECT_EQ(FILENAME, e->get_param_value_str("name", false)); } EXPECT_LE(0, std::stoi(e->get_param_value_str("res", false))); callnum++; - } - else if (callnum == 5) - { + } else if(callnum == 5) { EXPECT_GT(0, std::stoi(e->get_param_value_str("res", false))); callnum++; } @@ -159,8 +142,7 @@ TEST_F(sys_call_test, fs_creat_ulink) ///////////////////////////////////////////////////////////////////////////////////// // mkdir/rmdir ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_mkdir_rmdir) -{ +TEST_F(sys_call_test, fs_mkdir_rmdir) { int callnum = 0; char bcwd[1024]; @@ -176,22 +158,18 @@ TEST_F(sys_call_test, fs_mkdir_rmdir) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { mkdir(UNEXISTENT_DIRNAME, 0); - if (mkdir(DIRNAME, 0) != 0) - { + if(mkdir(DIRNAME, 0) != 0) { FAIL(); } - if (rmdir(DIRNAME) != 0) - { + if(rmdir(DIRNAME) != 0) { FAIL(); } - if (rmdir(DIRNAME) == 0) - { + if(rmdir(DIRNAME) == 0) { FAIL(); } }; @@ -199,85 +177,57 @@ TEST_F(sys_call_test, fs_mkdir_rmdir) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_MKDIR_2_E) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_MKDIR_2_E) { + if(callnum == 0) { EXPECT_EQ("0", e->get_param_value_str("mode")); callnum++; - } - else if (callnum == 2) - { + } else if(callnum == 2) { EXPECT_EQ("0", e->get_param_value_str("mode")); callnum++; } } - if (type == PPME_SYSCALL_MKDIRAT_E) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_MKDIRAT_E) { + if(callnum == 0) { callnum++; - } - else if (callnum == 2) - { + } else if(callnum == 2) { callnum++; } - } - else if (type == PPME_SYSCALL_MKDIR_2_X || type == PPME_SYSCALL_MKDIRAT_X) - { - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_MKDIR_2_X || type == PPME_SYSCALL_MKDIRAT_X) { + if(callnum == 1) { EXPECT_NE("0", e->get_param_value_str("res")); EXPECT_EQ(UNEXISTENT_DIRNAME, e->get_param_value_str("path")); EXPECT_EQ(UNEXISTENT_DIRNAME, e->get_param_value_str("path", false)); callnum++; - } - else if (callnum == 3) - { + } else if(callnum == 3) { EXPECT_EQ("0", e->get_param_value_str("res")); EXPECT_EQ(cwd + DIRNAME, e->get_param_value_str("path")); EXPECT_EQ(DIRNAME, e->get_param_value_str("path", false)); callnum++; } - } - else if (type == PPME_SYSCALL_RMDIR_2_E || type == PPME_SYSCALL_UNLINKAT_2_E) - { - if (callnum == 4 || callnum == 6) - { + } else if(type == PPME_SYSCALL_RMDIR_2_E || type == PPME_SYSCALL_UNLINKAT_2_E) { + if(callnum == 4 || callnum == 6) { callnum++; } - } - else if (type == PPME_SYSCALL_RMDIR_2_X || type == PPME_SYSCALL_UNLINKAT_2_X) - { - if (callnum == 5) - { + } else if(type == PPME_SYSCALL_RMDIR_2_X || type == PPME_SYSCALL_UNLINKAT_2_X) { + if(callnum == 5) { EXPECT_LE(0, std::stoi(e->get_param_value_str("res", false))); - if (type == PPME_SYSCALL_RMDIR_2_X) - { + if(type == PPME_SYSCALL_RMDIR_2_X) { EXPECT_EQ(DIRNAME, e->get_param_value_str("path", false)); EXPECT_EQ(cwd + DIRNAME, e->get_param_value_str("path")); - } - else - { + } else { EXPECT_EQ(DIRNAME, e->get_param_value_str("name", false)); } callnum++; - } - else if (callnum == 7) - { + } else if(callnum == 7) { EXPECT_GT(0, std::stoi(e->get_param_value_str("res", false))); - if (type == PPME_SYSCALL_RMDIR_2_X) - { + if(type == PPME_SYSCALL_RMDIR_2_X) { EXPECT_EQ(DIRNAME, e->get_param_value_str("path", false)); EXPECT_EQ(cwd + DIRNAME, e->get_param_value_str("path")); - } - else - { + } else { EXPECT_EQ(DIRNAME, e->get_param_value_str("name", false)); } callnum++; @@ -293,8 +243,7 @@ TEST_F(sys_call_test, fs_mkdir_rmdir) ///////////////////////////////////////////////////////////////////////////////////// // openat ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_openat) -{ +TEST_F(sys_call_test, fs_openat) { int callnum = 0; char bcwd[1024]; int dirfd; @@ -313,11 +262,9 @@ TEST_F(sys_call_test, fs_openat) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { dirfd = open(".", O_DIRECTORY); - if (dirfd <= 0) - { + if(dirfd <= 0) { FAIL(); } @@ -327,8 +274,7 @@ TEST_F(sys_call_test, fs_openat) // std::string s = FILENAME; fd1 = openat(dirfd, FILENAME, O_CREAT | O_WRONLY, S_IRWXU | S_IRWXG | S_IRWXO); - if (fd1 <= 0) - { + if(fd1 <= 0) { FAIL(); } @@ -340,8 +286,7 @@ TEST_F(sys_call_test, fs_openat) unlink(FILENAME); fd2 = openat(AT_FDCWD, FILENAME, O_CREAT | O_WRONLY, S_IRWXU | S_IRWXG | S_IRWXO); - if (fd2 <= 0) - { + if(fd2 <= 0) { FAIL(); } @@ -352,25 +297,20 @@ TEST_F(sys_call_test, fs_openat) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); std::string filepath = cwd + FILENAME; - if (type == PPME_SYSCALL_OPENAT_2_X && - param.m_evt->get_param_value_str("name") == filepath && - (std::string("") + filepath) == e->get_param_value_str("fd")) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_OPENAT_2_X && + param.m_evt->get_param_value_str("name") == filepath && + (std::string("") + filepath) == e->get_param_value_str("fd")) { + if(callnum == 0) { EXPECT_EQ(dirfd, std::stoll(e->get_param_value_str("dirfd", false))); EXPECT_EQ(fd1, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(std::string("") + bcwd, e->get_param_value_str("dirfd")); callnum++; - } - else if (callnum == 1) - { + } else if(callnum == 1) { EXPECT_EQ(-100, std::stoll(e->get_param_value_str("dirfd", false))); EXPECT_EQ(fd2, std::stoll(e->get_param_value_str("fd", false))); callnum++; @@ -386,8 +326,7 @@ TEST_F(sys_call_test, fs_openat) ///////////////////////////////////////////////////////////////////////////////////// // pread/pwrite ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_pread) -{ +TEST_F(sys_call_test, fs_pread) { int callnum = 0; char buf[32]; int fd; @@ -402,11 +341,9 @@ TEST_F(sys_call_test, fs_pread) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { fd = creat(FILENAME, S_IRWXU); - if (fd < 0) - { + if(fd < 0) { FAIL(); } @@ -423,8 +360,7 @@ TEST_F(sys_call_test, fs_pread) close(fd); fd1 = open(FILENAME, O_RDONLY); - if (fd1 < 0) - { + if(fd1 < 0) { FAIL(); } @@ -438,104 +374,72 @@ TEST_F(sys_call_test, fs_pread) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_WRITE_E) - { - if (std::stoll(e->get_param_value_str("fd", false)) == fd) - { + if(type == PPME_SYSCALL_WRITE_E) { + if(std::stoll(e->get_param_value_str("fd", false)) == fd) { EXPECT_EQ((int)sizeof("QWERTYUI") - 1, std::stoll(e->get_param_value_str("size", false))); callnum++; } - } - else if (type == PPME_SYSCALL_WRITE_X) - { - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_WRITE_X) { + if(callnum == 1) { EXPECT_EQ((int)sizeof("QWERTYUI") - 1, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ("QWERTYUI", e->get_param_value_str("data")); callnum++; } } - if (type == PPME_SYSCALL_PWRITE_E) - { - if (std::stoll(e->get_param_value_str("fd", false)) == fd) - { - if (callnum == 2) - { + if(type == PPME_SYSCALL_PWRITE_E) { + if(std::stoll(e->get_param_value_str("fd", false)) == fd) { + if(callnum == 2) { EXPECT_EQ((int)sizeof("ABCD") - 1, std::stoll(e->get_param_value_str("size", false))); EXPECT_EQ("4", e->get_param_value_str("pos")); callnum++; - } - else - { + } else { EXPECT_EQ((int)sizeof("ABCD") - 1, std::stoll(e->get_param_value_str("size", false))); EXPECT_EQ("987654321987654", e->get_param_value_str("pos")); callnum++; } } - } - else if (type == PPME_SYSCALL_PWRITE_X) - { - if (callnum == 3) - { - EXPECT_EQ((int)sizeof("ABCD") - 1, - std::stoi(e->get_param_value_str("res", false))); + } else if(type == PPME_SYSCALL_PWRITE_X) { + if(callnum == 3) { + EXPECT_EQ((int)sizeof("ABCD") - 1, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ("ABCD", e->get_param_value_str("data")); callnum++; - } - else - { - if (pwrite64_succeeded) - { + } else { + if(pwrite64_succeeded) { EXPECT_EQ((int)sizeof("ABCD") - 1, std::stoi(e->get_param_value_str("res", false))); - } - else - { + } else { EXPECT_GT(0, std::stoi(e->get_param_value_str("res", false))); } EXPECT_EQ("ABCD", e->get_param_value_str("data")); callnum++; } } - if (type == PPME_SYSCALL_PREAD_E) - { - if (callnum == 6) - { + if(type == PPME_SYSCALL_PREAD_E) { + if(callnum == 6) { EXPECT_EQ("32", e->get_param_value_str("size")); EXPECT_EQ("1234567891234", e->get_param_value_str("pos")); callnum++; - } - else if (callnum == 8) - { + } else if(callnum == 8) { EXPECT_EQ("4", e->get_param_value_str("size")); EXPECT_EQ("4", e->get_param_value_str("pos")); callnum++; - } - else - { + } else { FAIL(); } - } - else if (type == PPME_SYSCALL_PREAD_X) - { - if (callnum == 7) - { + } else if(type == PPME_SYSCALL_PREAD_X) { + if(callnum == 7) { EXPECT_NE("0", e->get_param_value_str("res", false)); callnum++; - } - else if (callnum == 9) - { - EXPECT_EQ((int)sizeof("ABCD") - 1, - std::stoi(e->get_param_value_str("res", false))); + } else if(callnum == 9) { + EXPECT_EQ((int)sizeof("ABCD") - 1, std::stoi(e->get_param_value_str("res", false))); callnum++; } } @@ -549,8 +453,7 @@ TEST_F(sys_call_test, fs_pread) ///////////////////////////////////////////////////////////////////////////////////// // writev/readv ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_readv) -{ +TEST_F(sys_call_test, fs_readv) { int callnum = 0; int fd; int fd1; @@ -564,8 +467,7 @@ TEST_F(sys_call_test, fs_readv) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { int wv_count; char msg1[10] = "aaaaa"; char msg2[10] = "bbbbb"; @@ -584,8 +486,7 @@ TEST_F(sys_call_test, fs_readv) wv_count = 3; bytes_sent = writev(fd, wv, wv_count); - if (bytes_sent <= 0) - { + if(bytes_sent <= 0) { FAIL(); } @@ -598,8 +499,7 @@ TEST_F(sys_call_test, fs_readv) wv[2].iov_len = sizeof(msg3); rres = readv(fd1, wv, wv_count); - if (rres <= 0) - { + if(rres <= 0) { FAIL(); } @@ -611,35 +511,25 @@ TEST_F(sys_call_test, fs_readv) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_WRITEV_E) - { + if(type == PPME_SYSCALL_WRITEV_E) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(15, std::stoll(e->get_param_value_str("size"))); callnum++; - } - else if (type == PPME_SYSCALL_WRITEV_X) - { - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_WRITEV_X) { + if(callnum == 1) { EXPECT_EQ(15, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ("aaaaabbbbbccccc", e->get_param_value_str("data")); callnum++; } - } - else if (type == PPME_SYSCALL_READV_E) - { + } else if(type == PPME_SYSCALL_READV_E) { EXPECT_EQ(fd1, std::stoll(e->get_param_value_str("fd", false))); callnum++; - } - else if (type == PPME_SYSCALL_READV_X) - { - if (callnum == 3) - { + } else if(type == PPME_SYSCALL_READV_X) { + if(callnum == 3) { EXPECT_EQ(15, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ("aaaaabbbbbccccc", (e->get_param_value_str("data")).substr(0, 15)); EXPECT_EQ(15, std::stoll(e->get_param_value_str("size"))); @@ -656,8 +546,7 @@ TEST_F(sys_call_test, fs_readv) ///////////////////////////////////////////////////////////////////////////////////// // pwritev/preadv ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_preadv) -{ +TEST_F(sys_call_test, fs_preadv) { int callnum = 0; int fd; int fd1; @@ -672,8 +561,7 @@ TEST_F(sys_call_test, fs_preadv) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { int wv_count; char msg1[10] = "aaaaa"; char msg2[10] = "bbbbb"; @@ -700,8 +588,7 @@ TEST_F(sys_call_test, fs_preadv) pwritev64_succeeded = bytes_sent > 0; bytes_sent = pwritev(fd, wv, wv_count, 10); - if (bytes_sent <= 0) - { + if(bytes_sent <= 0) { FAIL(); } @@ -716,8 +603,7 @@ TEST_F(sys_call_test, fs_preadv) rres = preadv64(fd1, wv, wv_count, 987654321098); rres = preadv(fd1, wv, wv_count, 10); - if (rres <= 0) - { + if(rres <= 0) { FAIL(); } @@ -729,70 +615,49 @@ TEST_F(sys_call_test, fs_preadv) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_PWRITEV_E) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_PWRITEV_E) { + if(callnum == 0) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(15, std::stoll(e->get_param_value_str("size"))); EXPECT_EQ(132456789012345LL, std::stoll(e->get_param_value_str("pos"))); callnum++; - } - else - { + } else { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(10, std::stoll(e->get_param_value_str("pos"))); EXPECT_EQ(15, std::stoll(e->get_param_value_str("size"))); callnum++; } - } - else if (type == PPME_SYSCALL_PWRITEV_X) - { - if (callnum == 1) - { - if (pwritev64_succeeded) - { + } else if(type == PPME_SYSCALL_PWRITEV_X) { + if(callnum == 1) { + if(pwritev64_succeeded) { EXPECT_EQ(15, std::stoi(e->get_param_value_str("res", false))); - } - else - { + } else { EXPECT_GT(0, std::stoi(e->get_param_value_str("res", false))); } EXPECT_EQ("aaaaabbbbbccccc", e->get_param_value_str("data")); callnum++; - } - else - { + } else { EXPECT_EQ(15, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ("aaaaabbbbbccccc", e->get_param_value_str("data")); callnum++; } - } - else if (type == PPME_SYSCALL_PREADV_E) - { - if (callnum == 4) - { + } else if(type == PPME_SYSCALL_PREADV_E) { + if(callnum == 4) { EXPECT_EQ(fd1, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(987654321098, std::stoll(e->get_param_value_str("pos"))); callnum++; - } - else - { + } else { EXPECT_EQ(fd1, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(10, std::stoll(e->get_param_value_str("pos"))); callnum++; } - } - else if (type == PPME_SYSCALL_PREADV_X) - { - if (callnum == 3) - { + } else if(type == PPME_SYSCALL_PREADV_X) { + if(callnum == 3) { EXPECT_EQ(15, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ("aaaaabbbbb", e->get_param_value_str("data")); EXPECT_EQ(30, std::stoll(e->get_param_value_str("size"))); @@ -809,8 +674,7 @@ TEST_F(sys_call_test, fs_preadv) ///////////////////////////////////////////////////////////////////////////////////// // dup ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_dup) -{ +TEST_F(sys_call_test, fs_dup) { int callnum = 0; int fd; int fd1; @@ -823,21 +687,18 @@ TEST_F(sys_call_test, fs_dup) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { uint16_t type = evt->get_type(); - return m_tid_filter(evt) && - (type == PPME_SYSCALL_DUP_1_E || type == PPME_SYSCALL_DUP2_E || - type == PPME_SYSCALL_DUP3_E || type == PPME_SYSCALL_DUP_E || - type == PPME_SYSCALL_DUP_1_X || type == PPME_SYSCALL_DUP2_X || - type == PPME_SYSCALL_DUP3_X || type == PPME_SYSCALL_DUP_X); + return m_tid_filter(evt) && (type == PPME_SYSCALL_DUP_1_E || type == PPME_SYSCALL_DUP2_E || + type == PPME_SYSCALL_DUP3_E || type == PPME_SYSCALL_DUP_E || + type == PPME_SYSCALL_DUP_1_X || type == PPME_SYSCALL_DUP2_X || + type == PPME_SYSCALL_DUP3_X || type == PPME_SYSCALL_DUP_X); }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { fd = open(FILENAME, O_CREAT | O_WRONLY, 0); fd1 = dup(fd); fd2 = dup2(fd, 333); @@ -863,97 +724,72 @@ TEST_F(sys_call_test, fs_dup) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_DUP_1_E || type == PPME_SYSCALL_DUP2_E || - type == PPME_SYSCALL_DUP3_E || type == PPME_SYSCALL_DUP_E) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_DUP_1_E || type == PPME_SYSCALL_DUP2_E || + type == PPME_SYSCALL_DUP3_E || type == PPME_SYSCALL_DUP_E) { + if(callnum == 0) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); callnum++; - } - else if (callnum == 2) - { + } else if(callnum == 2) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); callnum++; - } - else if (callnum == 4) - { + } else if(callnum == 4) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); callnum++; - } - else if (callnum == 6) - { + } else if(callnum == 6) { EXPECT_EQ(fd3, std::stoll(e->get_param_value_str("fd", false))); callnum++; - } - else if (callnum == 8) - { + } else if(callnum == 8) { EXPECT_EQ("-1", e->get_param_value_str("fd", false)); callnum++; - } - else if (callnum == 10) - { + } else if(callnum == 10) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); callnum++; } - } - else if (type == PPME_SYSCALL_DUP_1_X || type == PPME_SYSCALL_DUP2_X || - type == PPME_SYSCALL_DUP3_X || type == PPME_SYSCALL_DUP_X) - { - ASSERT_NE( - (sinsp_threadinfo*)&*param.m_inspector->get_thread_ref(e->get_tid(), false, true), - nullptr); - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_DUP_1_X || type == PPME_SYSCALL_DUP2_X || + type == PPME_SYSCALL_DUP3_X || type == PPME_SYSCALL_DUP_X) { + ASSERT_NE((sinsp_threadinfo*)&*param.m_inspector->get_thread_ref(e->get_tid(), + false, + true), + nullptr); + if(callnum == 1) { EXPECT_EQ(fd1, std::stoi(e->get_param_value_str("res", false))); EXPECT_NE((sinsp_threadinfo*)NULL, (sinsp_threadinfo*)&*param.m_inspector - ->get_thread_ref(e->get_tid(), false, true) - ->get_fd(fd1)); + ->get_thread_ref(e->get_tid(), false, true) + ->get_fd(fd1)); callnum++; - } - else if (callnum == 3) - { + } else if(callnum == 3) { EXPECT_EQ(fd2, std::stoi(e->get_param_value_str("res", false))); EXPECT_NE((sinsp_threadinfo*)NULL, (sinsp_threadinfo*)&*param.m_inspector - ->get_thread_ref(e->get_tid(), false, true) - ->get_fd(fd2)); + ->get_thread_ref(e->get_tid(), false, true) + ->get_fd(fd2)); callnum++; - } - else if (callnum == 5) - { + } else if(callnum == 5) { EXPECT_EQ(fd3, std::stoi(e->get_param_value_str("res", false))); EXPECT_NE((sinsp_threadinfo*)NULL, (sinsp_threadinfo*)&*param.m_inspector - ->get_thread_ref(e->get_tid(), false, true) - ->get_fd(fd3)); + ->get_thread_ref(e->get_tid(), false, true) + ->get_fd(fd3)); callnum++; - } - else if (callnum == 7) - { + } else if(callnum == 7) { EXPECT_EQ(fd4, std::stoi(e->get_param_value_str("res", false))); EXPECT_NE((sinsp_threadinfo*)NULL, (sinsp_threadinfo*)&*param.m_inspector - ->get_thread_ref(e->get_tid(), false, true) - ->get_fd(fd4)); + ->get_thread_ref(e->get_tid(), false, true) + ->get_fd(fd4)); callnum++; - } - else if (callnum == 9) - { + } else if(callnum == 9) { EXPECT_GT(0, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ((sinsp_threadinfo*)NULL, (sinsp_threadinfo*)&*param.m_inspector - ->get_thread_ref(e->get_tid(), false, true) - ->get_fd(fd5)); + ->get_thread_ref(e->get_tid(), false, true) + ->get_fd(fd5)); callnum++; - } - else if (callnum == 11) - { + } else if(callnum == 11) { EXPECT_EQ(fd6, std::stoi(e->get_param_value_str("res", false))); callnum++; } @@ -973,8 +809,7 @@ TEST_F(sys_call_test, fs_dup) ///////////////////////////////////////////////////////////////////////////////////// // fcntl ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_fcntl) -{ +TEST_F(sys_call_test, fs_fcntl) { int callnum = 0; int fd; int fd1; @@ -988,8 +823,7 @@ TEST_F(sys_call_test, fs_fcntl) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { fd = open(FILENAME, O_CREAT | O_WRONLY, 0); fd1 = fcntl(fd, F_DUPFD, 0); fd2 = fcntl(fd, F_DUPFD_CLOEXEC, 0); @@ -1005,45 +839,36 @@ TEST_F(sys_call_test, fs_fcntl) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_FCNTL_E) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_FCNTL_E) { + if(callnum == 0) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); callnum++; - } - else if (callnum == 2) - { + } else if(callnum == 2) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); callnum++; } - } - else if (type == PPME_SYSCALL_FCNTL_X) - { - ASSERT_NE( - (sinsp_threadinfo*)&*param.m_inspector->get_thread_ref(e->get_tid(), false, true), - nullptr); - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_FCNTL_X) { + ASSERT_NE((sinsp_threadinfo*)&*param.m_inspector->get_thread_ref(e->get_tid(), + false, + true), + nullptr); + if(callnum == 1) { EXPECT_EQ(fd1, std::stoi(e->get_param_value_str("res", false))); EXPECT_NE((sinsp_threadinfo*)NULL, (sinsp_threadinfo*)&*param.m_inspector - ->get_thread_ref(e->get_tid(), false, true) - ->get_fd(fd1)); + ->get_thread_ref(e->get_tid(), false, true) + ->get_fd(fd1)); callnum++; - } - else if (callnum == 3) - { + } else if(callnum == 3) { EXPECT_EQ(fd2, std::stoi(e->get_param_value_str("res", false))); EXPECT_NE((sinsp_threadinfo*)NULL, (sinsp_threadinfo*)&*param.m_inspector - ->get_thread_ref(e->get_tid(), false, true) - ->get_fd(fd1)); + ->get_thread_ref(e->get_tid(), false, true) + ->get_fd(fd1)); callnum++; } } @@ -1057,8 +882,7 @@ TEST_F(sys_call_test, fs_fcntl) ///////////////////////////////////////////////////////////////////////////////////// // sendfile ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, fs_sendfile) -{ +TEST_F(sys_call_test, fs_sendfile) { int callnum = 0; int read_fd; int write_fd; @@ -1073,8 +897,7 @@ TEST_F(sys_call_test, fs_sendfile) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { struct stat stat_buf; read_fd = open("/etc/passwd", O_RDONLY); @@ -1096,21 +919,17 @@ TEST_F(sys_call_test, fs_sendfile) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_SENDFILE_E) - { + if(type == PPME_SYSCALL_SENDFILE_E) { EXPECT_EQ(write_fd, std::stoll(e->get_param_value_str("out_fd", false))); EXPECT_EQ(read_fd, std::stoll(e->get_param_value_str("in_fd", false))); EXPECT_EQ(size, std::stoll(e->get_param_value_str("size", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("offset", false))); callnum++; - } - else if (type == PPME_SYSCALL_SENDFILE_X) - { + } else if(type == PPME_SYSCALL_SENDFILE_X) { EXPECT_LE(0, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ(offset, std::stoll(e->get_param_value_str("offset", false))); callnum++; @@ -1122,8 +941,7 @@ TEST_F(sys_call_test, fs_sendfile) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, fs_sendfile_nulloff) -{ +TEST_F(sys_call_test, fs_sendfile_nulloff) { int callnum = 0; int read_fd; int write_fd; @@ -1137,8 +955,7 @@ TEST_F(sys_call_test, fs_sendfile_nulloff) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { struct stat stat_buf; read_fd = open("/etc/passwd", O_RDONLY); @@ -1160,21 +977,17 @@ TEST_F(sys_call_test, fs_sendfile_nulloff) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_SENDFILE_E) - { + if(type == PPME_SYSCALL_SENDFILE_E) { EXPECT_EQ(write_fd, std::stoll(e->get_param_value_str("out_fd", false))); EXPECT_EQ(read_fd, std::stoll(e->get_param_value_str("in_fd", false))); EXPECT_EQ(size, std::stoll(e->get_param_value_str("size", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("offset", false))); callnum++; - } - else if (type == PPME_SYSCALL_SENDFILE_X) - { + } else if(type == PPME_SYSCALL_SENDFILE_X) { EXPECT_LE(0, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("offset", false))); callnum++; @@ -1186,8 +999,7 @@ TEST_F(sys_call_test, fs_sendfile_nulloff) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, fs_sendfile_failed) -{ +TEST_F(sys_call_test, fs_sendfile_failed) { int callnum = 0; // int size; @@ -1199,8 +1011,7 @@ TEST_F(sys_call_test, fs_sendfile_failed) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { int res = sendfile(-1, -2, NULL, 444); EXPECT_GT(0, res); }; @@ -1208,13 +1019,11 @@ TEST_F(sys_call_test, fs_sendfile_failed) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_SENDFILE_E) - { + if(type == PPME_SYSCALL_SENDFILE_E) { EXPECT_NO_THROW({ EXPECT_EQ("-1", e->get_param_value_str("out_fd", false)); EXPECT_EQ("-2", e->get_param_value_str("in_fd", false)); @@ -1223,9 +1032,7 @@ TEST_F(sys_call_test, fs_sendfile_failed) }); callnum++; - } - else if (type == PPME_SYSCALL_SENDFILE_X) - { + } else if(type == PPME_SYSCALL_SENDFILE_X) { EXPECT_NO_THROW({ EXPECT_GT(0, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("offset", false))); @@ -1239,8 +1046,7 @@ TEST_F(sys_call_test, fs_sendfile_failed) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, fs_sendfile_invalidoff) -{ +TEST_F(sys_call_test, fs_sendfile_invalidoff) { int callnum = 0; int read_fd; int write_fd; @@ -1254,8 +1060,7 @@ TEST_F(sys_call_test, fs_sendfile_invalidoff) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { struct stat stat_buf; read_fd = open("/etc/passwd", O_RDONLY); @@ -1277,21 +1082,17 @@ TEST_F(sys_call_test, fs_sendfile_invalidoff) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_SENDFILE_E) - { + if(type == PPME_SYSCALL_SENDFILE_E) { EXPECT_EQ(write_fd, std::stoll(e->get_param_value_str("out_fd", false))); EXPECT_EQ(read_fd, std::stoll(e->get_param_value_str("in_fd", false))); EXPECT_EQ(size, std::stoll(e->get_param_value_str("size", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("offset", false))); callnum++; - } - else if (type == PPME_SYSCALL_SENDFILE_X) - { + } else if(type == PPME_SYSCALL_SENDFILE_X) { EXPECT_GT(0, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("offset", false))); callnum++; @@ -1304,8 +1105,7 @@ TEST_F(sys_call_test, fs_sendfile_invalidoff) } #ifdef __i386__ -TEST_F(sys_call_test, fs_sendfile64) -{ +TEST_F(sys_call_test, fs_sendfile64) { int callnum = 0; int read_fd; int write_fd; @@ -1320,8 +1120,7 @@ TEST_F(sys_call_test, fs_sendfile64) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { struct stat stat_buf; read_fd = open("/etc/passwd", O_RDONLY); @@ -1343,21 +1142,17 @@ TEST_F(sys_call_test, fs_sendfile64) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_SENDFILE_E) - { + if(type == PPME_SYSCALL_SENDFILE_E) { EXPECT_EQ(write_fd, std::stoll(e->get_param_value_str("out_fd", false))); EXPECT_EQ(read_fd, std::stoll(e->get_param_value_str("in_fd", false))); EXPECT_EQ(size, std::stoll(e->get_param_value_str("size", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("offset", false))); callnum++; - } - else if (type == PPME_SYSCALL_SENDFILE_X) - { + } else if(type == PPME_SYSCALL_SENDFILE_X) { EXPECT_LE(0, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ(offset, std::stoll(e->get_param_value_str("offset", false))); callnum++; @@ -1370,8 +1165,7 @@ TEST_F(sys_call_test, fs_sendfile64) } #endif -TEST_F(sys_call_test, large_read_write) -{ +TEST_F(sys_call_test, large_read_write) { const int buf_size = PPM_MAX_ARG_SIZE * 10; std::vector buf(buf_size); @@ -1380,19 +1174,13 @@ TEST_F(sys_call_test, large_read_write) srandom(42); - before_open_t setup = [&](sinsp* inspector) - { - inspector->set_snaplen(SNAPLEN_MAX); - }; + before_open_t setup = [&](sinsp* inspector) { inspector->set_snaplen(SNAPLEN_MAX); }; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - + run_callback_t test = [&](concurrent_object_handle inspector_handle) { fd1 = creat(FILENAME, S_IRWXU); - if (fd1 < 0) - { + if(fd1 < 0) { FAIL(); } @@ -1402,8 +1190,7 @@ TEST_F(sys_call_test, large_read_write) close(fd1); fd2 = open(FILENAME, O_RDONLY); - if (fd2 < 0) - { + if(fd2 < 0) { FAIL(); } @@ -1415,22 +1202,16 @@ TEST_F(sys_call_test, large_read_write) unlink(FILENAME); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_WRITE_E) - { - if (std::stoll(e->get_param_value_str("fd", false)) == fd1) - { + if(type == PPME_SYSCALL_WRITE_E) { + if(std::stoll(e->get_param_value_str("fd", false)) == fd1) { callnum++; } - } - else if (type == PPME_SYSCALL_WRITE_X) - { - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_WRITE_X) { + if(callnum == 1) { const sinsp_evt_param* p = e->get_param_by_name("data"); EXPECT_EQ(p->m_len, SNAPLEN_MAX); @@ -1439,17 +1220,12 @@ TEST_F(sys_call_test, large_read_write) callnum++; } } - if (type == PPME_SYSCALL_READ_E) - { - if (callnum == 2) - { + if(type == PPME_SYSCALL_READ_E) { + if(callnum == 2) { callnum++; } - } - else if (type == PPME_SYSCALL_READ_X) - { - if (callnum == 3) - { + } else if(type == PPME_SYSCALL_READ_X) { + if(callnum == 3) { const sinsp_evt_param* p = e->get_param_by_name("data"); EXPECT_EQ(p->m_len, SNAPLEN_MAX); @@ -1460,22 +1236,28 @@ TEST_F(sys_call_test, large_read_write) } }; - before_close_t cleanup = [&](sinsp* inspector) - { - inspector->set_snaplen(DEFAULT_SNAPLEN); - }; + before_close_t cleanup = [&](sinsp* inspector) { inspector->set_snaplen(DEFAULT_SNAPLEN); }; // We don't dump events to scap files, otherwise we could stuck with modern bpf. - ASSERT_NO_FATAL_FAILURE({event_capture::run(test, callback, filter, setup, - cleanup, event_capture::always_continue, 131072, - (uint64_t)60 * 1000 * 1000 * 1000, (uint64_t)60 * 1000 * 1000 * 1000, - SINSP_MODE_LIVE, 3, false); }); + ASSERT_NO_FATAL_FAILURE({ + event_capture::run(test, + callback, + filter, + setup, + cleanup, + event_capture::always_continue, + 131072, + (uint64_t)60 * 1000 * 1000 * 1000, + (uint64_t)60 * 1000 * 1000 * 1000, + SINSP_MODE_LIVE, + 3, + false); + }); EXPECT_EQ(4, callnum); } -TEST_F(sys_call_test, large_readv_writev) -{ +TEST_F(sys_call_test, large_readv_writev) { const int buf_size = PPM_MAX_ARG_SIZE * 10; const int chunks = 10; @@ -1485,23 +1267,17 @@ TEST_F(sys_call_test, large_readv_writev) srandom(42); - for (int j = 0; j < buf_size; ++j) - { + for(int j = 0; j < buf_size; ++j) { buf[j] = random(); } - before_open_t setup = [&](sinsp* inspector) - { - inspector->set_snaplen(SNAPLEN_MAX); - }; + before_open_t setup = [&](sinsp* inspector) { inspector->set_snaplen(SNAPLEN_MAX); }; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { fd = creat(FILENAME, S_IRWXU); - if (fd < 0) - { + if(fd < 0) { FAIL(); } @@ -1509,8 +1285,7 @@ TEST_F(sys_call_test, large_readv_writev) int chunk_size = buf_size / chunks; int off = 0; - for (int j = 0; j < chunks; ++j) - { + for(int j = 0; j < chunks; ++j) { iovs[j].iov_base = buf + off; iovs[j].iov_len = chunk_size; @@ -1523,8 +1298,7 @@ TEST_F(sys_call_test, large_readv_writev) close(fd); int fd = open(FILENAME, O_RDONLY); - if (fd < 0) - { + if(fd < 0) { FAIL(); } @@ -1536,37 +1310,28 @@ TEST_F(sys_call_test, large_readv_writev) unlink(FILENAME); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { const int max_kmod_buf = getpagesize() - sizeof(struct iovec) * chunks - 1; (void)max_kmod_buf; sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_WRITEV_E) - { - if (std::stoll(e->get_param_value_str("fd", false)) == fd) - { + if(type == PPME_SYSCALL_WRITEV_E) { + if(std::stoll(e->get_param_value_str("fd", false)) == fd) { callnum++; } - } - else if (type == PPME_SYSCALL_WRITEV_X) - { - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_WRITEV_X) { + if(callnum == 1) { const sinsp_evt_param* p = e->get_param_by_name("data"); - if(event_capture::m_engine_string == KMOD_ENGINE) - { + if(event_capture::m_engine_string == KMOD_ENGINE) { // // The driver doesn't have the correct behavior for accumulating // readv/writev, and it uses a single page as a temporary storage area // EXPECT_EQ(p->m_len, max_kmod_buf); EXPECT_EQ(0, memcmp(buf, p->m_val, max_kmod_buf)); - } - else - { + } else { EXPECT_EQ(p->m_len, SNAPLEN_MAX); EXPECT_EQ(0, memcmp(buf, p->m_val, SNAPLEN_MAX)); } @@ -1574,25 +1339,17 @@ TEST_F(sys_call_test, large_readv_writev) callnum++; } } - if (type == PPME_SYSCALL_READV_E) - { - if (callnum == 2) - { + if(type == PPME_SYSCALL_READV_E) { + if(callnum == 2) { callnum++; } - } - else if (type == PPME_SYSCALL_READV_X) - { - if (callnum == 3) - { + } else if(type == PPME_SYSCALL_READV_X) { + if(callnum == 3) { const sinsp_evt_param* p = e->get_param_by_name("data"); - if(event_capture::m_engine_string == KMOD_ENGINE) - { + if(event_capture::m_engine_string == KMOD_ENGINE) { EXPECT_EQ(p->m_len, max_kmod_buf); EXPECT_EQ(0, memcmp(buf, p->m_val, max_kmod_buf)); - } - else - { + } else { EXPECT_EQ(p->m_len, SNAPLEN_MAX); EXPECT_EQ(0, memcmp(buf, p->m_val, SNAPLEN_MAX)); } @@ -1602,22 +1359,28 @@ TEST_F(sys_call_test, large_readv_writev) } }; - before_close_t cleanup = [&](sinsp* inspector) - { - inspector->set_snaplen(DEFAULT_SNAPLEN); - }; + before_close_t cleanup = [&](sinsp* inspector) { inspector->set_snaplen(DEFAULT_SNAPLEN); }; // We don't dump events to scap files, otherwise we could stuck with modern bpf. - ASSERT_NO_FATAL_FAILURE({event_capture::run(test, callback, filter, setup, - cleanup, event_capture::always_continue, 131072, - (uint64_t)60 * 1000 * 1000 * 1000, (uint64_t)60 * 1000 * 1000 * 1000, - SINSP_MODE_LIVE, 3, false); }); + ASSERT_NO_FATAL_FAILURE({ + event_capture::run(test, + callback, + filter, + setup, + cleanup, + event_capture::always_continue, + 131072, + (uint64_t)60 * 1000 * 1000 * 1000, + (uint64_t)60 * 1000 * 1000 * 1000, + SINSP_MODE_LIVE, + 3, + false); + }); EXPECT_EQ(4, callnum); } -TEST_F(sys_call_test, large_open) -{ +TEST_F(sys_call_test, large_open) { const int buf_size = PPM_MAX_ARG_SIZE * 10; int callnum = 0; @@ -1625,15 +1388,13 @@ TEST_F(sys_call_test, large_open) srandom(42); std::string buf; - while (buf.length() < buf_size) - { + while(buf.length() < buf_size) { buf.append(std::to_string(random())); } event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { #ifdef SYS_open int fd = syscall(SYS_open, buf.c_str(), O_RDONLY); #else @@ -1642,31 +1403,22 @@ TEST_F(sys_call_test, large_open) EXPECT_EQ(fd, -1); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; std::string name(e->get_name()); - if (name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_IN) - { + if(name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_IN) { callnum++; - } - else if (name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_OUT) - { + } else if(name.find("open") != std::string::npos && e->get_direction() == SCAP_ED_OUT) { const sinsp_evt_param* p = e->get_param_by_name("name"); - if(event_capture::m_engine_string == KMOD_ENGINE) - { + if(event_capture::m_engine_string == KMOD_ENGINE) { EXPECT_EQ(p->m_len, PPM_MAX_ARG_SIZE); EXPECT_EQ(buf.substr(0, PPM_MAX_ARG_SIZE - 1), std::string(p->m_val)); - } - else if(event_capture::m_engine_string == BPF_ENGINE) - { + } else if(event_capture::m_engine_string == BPF_ENGINE) { EXPECT_EQ(p->m_len, SNAPLEN_MAX); EXPECT_EQ(buf.substr(0, SNAPLEN_MAX - 1), std::string(p->m_val)); - } - else if(event_capture::m_engine_string == MODERN_BPF_ENGINE) - { + } else if(event_capture::m_engine_string == MODERN_BPF_ENGINE) { EXPECT_EQ(p->m_len, PATH_MAX); EXPECT_EQ(buf.substr(0, PATH_MAX - 1), std::string(p->m_val)); } diff --git a/test/libsinsp_e2e/ipv6.cpp b/test/libsinsp_e2e/ipv6.cpp index 49c03ec8fc..43d5c0245b 100644 --- a/test/libsinsp_e2e/ipv6.cpp +++ b/test/libsinsp_e2e/ipv6.cpp @@ -30,11 +30,9 @@ limitations under the License. typedef std::function validate_func_t; -class ipv6_filtercheck_test : public testing::Test -{ +class ipv6_filtercheck_test : public testing::Test { protected: - struct cstring_comp - { + struct cstring_comp { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; @@ -47,25 +45,24 @@ class ipv6_filtercheck_test : public testing::Test virtual void read_file(const char* filename, const char* extra_filter, std::function evtcb, - bool generate_ip_net_filters = true) - { + bool generate_ip_net_filters = true) { m_inspector = file_reader.setup_read_file(); m_socket_connected = false; m_check_local_remote = false; m_check_is_server = false; - if (generate_ip_net_filters) - { + if(generate_ip_net_filters) { gen_ip_net_filters(); } std::string filter = - "evt.type in (socket, connect, recvfrom, sendto, close, accept, connect, bind, read, " - "write, poll) and evt.dir=< and fd.type!=file and fd.type!=unix and fd.type!=file and " - "fd.type!=pipe"; - if (extra_filter) - { + "evt.type in (socket, connect, recvfrom, sendto, close, accept, connect, bind, " + "read, " + "write, poll) and evt.dir=< and fd.type!=file and fd.type!=unix and fd.type!=file " + "and " + "fd.type!=pipe"; + if(extra_filter) { filter += " and "; filter += extra_filter; } @@ -73,20 +70,18 @@ class ipv6_filtercheck_test : public testing::Test file_reader.run_inspector(filename, filter, evtcb); } - void check_ipv6_filterchecks(sinsp_evt* evt) - { + void check_ipv6_filterchecks(sinsp_evt* evt) { std::string full_output; std::string full = - "*%evt.num %evt.outputtime %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type " - "%evt.info"; + "*%evt.num %evt.outputtime %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type " + "%evt.info"; sinsp_evt_formatter(m_inspector.get(), full, m_filterlist).tostring(evt, &full_output); verify_filtercheck(evt, "*%fd.type", "ipv6", full_output); verify_filtercheck(evt, "*%fd.typechar", "6", full_output); verify_filtercheck(evt, "*%fd.sockfamily", "ip", full_output); - if (m_socket_connected) - { + if(m_socket_connected) { verify_filtercheck(evt, "*%fd.name", m_conn_names, full_output); verify_filtercheck(evt, "*%fd.cip", m_client_ip, full_output); @@ -96,39 +91,37 @@ class ipv6_filtercheck_test : public testing::Test verify_filtercheck(evt, "*%fd.sport", m_server_ports, full_output); ASSERT_TRUE(m_ip_client_filter->run(evt)) - << "fd.ip=" << m_client_ip - << " did not match event. Full event output: " << full_output; + << "fd.ip=" << m_client_ip + << " did not match event. Full event output: " << full_output; ASSERT_TRUE(m_ip_server_filter->run(evt)) - << "fd.ip=" << m_server_ip - << " did not match event. Full event output: " << full_output; + << "fd.ip=" << m_server_ip + << " did not match event. Full event output: " << full_output; ASSERT_TRUE(m_net_client_filter->run(evt)) - << "fd.net=" << m_client_net - << " did not match event. Full event output: " << full_output; + << "fd.net=" << m_client_net + << " did not match event. Full event output: " << full_output; ASSERT_TRUE(m_net_server_filter->run(evt)) - << "fd.net=" << m_server_net - << " did not match event. Full event output: " << full_output; + << "fd.net=" << m_server_net + << " did not match event. Full event output: " << full_output; ASSERT_TRUE(m_cnet_filter->run(evt)) - << "fd.cnet=" << m_client_net - << " did not match event. Full event output: " << full_output; + << "fd.cnet=" << m_client_net + << " did not match event. Full event output: " << full_output; ASSERT_TRUE(m_snet_filter->run(evt)) - << "fd.snet=" << m_server_net - << " did not match event. Full event output: " << full_output; + << "fd.snet=" << m_server_net + << " did not match event. Full event output: " << full_output; verify_filtercheck(evt, "*%fd.cproto", m_client_proto, full_output); verify_filtercheck(evt, "*%fd.sproto", m_server_protos, full_output); verify_filtercheck(evt, "*%fd.l4proto", m_l4proto, full_output); - if (m_check_is_server) - { + if(m_check_is_server) { verify_filtercheck(evt, "*%fd.is_server", m_is_server, full_output); } } - if (m_check_local_remote) - { + if(m_check_local_remote) { verify_filtercheck(evt, "*%fd.lip", m_client_ip, full_output); verify_filtercheck(evt, "*%fd.rip", m_server_ip, full_output); @@ -136,11 +129,11 @@ class ipv6_filtercheck_test : public testing::Test verify_filtercheck(evt, "*%fd.rport", m_server_ports, full_output); ASSERT_TRUE(m_lnet_filter->run(evt)) - << "fd.lnet=" << m_client_net - << " did not match event. Full event output: " << full_output; + << "fd.lnet=" << m_client_net + << " did not match event. Full event output: " << full_output; ASSERT_TRUE(m_rnet_filter->run(evt)) - << "fd.rnet=" << m_server_net - << " did not match event. Full event output: " << full_output; + << "fd.rnet=" << m_server_net + << " did not match event. Full event output: " << full_output; verify_filtercheck(evt, "*%fd.lproto", m_client_proto, full_output); verify_filtercheck(evt, "*%fd.rproto", m_server_protos, full_output); @@ -150,8 +143,7 @@ class ipv6_filtercheck_test : public testing::Test void verify_filtercheck(sinsp_evt* evt, const char* format, const char* expectedc, - std::string full_output) - { + std::string full_output) { cstringset_t expected; expected.insert(expectedc); @@ -161,8 +153,7 @@ class ipv6_filtercheck_test : public testing::Test void verify_filtercheck(sinsp_evt* evt, const char* format, std::string& expecteds, - std::string full_output) - { + std::string full_output) { cstringset_t expected; expected.insert(expecteds.c_str()); @@ -172,8 +163,7 @@ class ipv6_filtercheck_test : public testing::Test void verify_filtercheck(sinsp_evt* evt, const char* cformat, cstringset_t& expected, - std::string full_output) - { + std::string full_output) { std::string output; std::string format = cformat; @@ -182,12 +172,11 @@ class ipv6_filtercheck_test : public testing::Test auto it = expected.find(output.c_str()); ASSERT_TRUE(it != expected.end()) - << " Result of format " << cformat - << " did not match any expected value. Full event output: " << full_output; + << " Result of format " << cformat + << " did not match any expected value. Full event output: " << full_output; } - void gen_ip_net_filters() - { + void gen_ip_net_filters() { auto inspector = file_reader.setup_read_file(); sinsp_filter_compiler ip_client(inspector.get(), "fd.ip=" + m_client_ip); m_ip_client_filter = std::move(ip_client.compile()); @@ -242,8 +231,7 @@ class ipv6_filtercheck_test : public testing::Test bool m_check_is_server; }; -TEST_F(ipv6_filtercheck_test, curl_google_dnsreq) -{ +TEST_F(ipv6_filtercheck_test, curl_google_dnsreq) { m_client_ip = "2600:1f18:262c:6542:9aa6:df7a:9a47:d29e"; m_server_ip = "2001:4860:4860::8888"; m_client_port = "40251"; @@ -258,15 +246,13 @@ TEST_F(ipv6_filtercheck_test, curl_google_dnsreq) read_file(LIBSINSP_TEST_CAPTURES_PATH "/curl_google.scap", "thread.tid=17498", - [this](sinsp_evt* evt) - { + [this](sinsp_evt* evt) { std::string evname = std::string(evt->get_name()); // Once we see a connect or bind, we can assume the // socket is connected and it's possible to get // client/server and local/remote information. - if (evname == "connect" || evname == "bind") - { + if(evname == "connect" || evname == "bind") { m_socket_connected = true; m_check_local_remote = true; m_check_is_server = true; @@ -276,8 +262,7 @@ TEST_F(ipv6_filtercheck_test, curl_google_dnsreq) }); } -TEST_F(ipv6_filtercheck_test, curl_google_www) -{ +TEST_F(ipv6_filtercheck_test, curl_google_www) { m_client_ip = "2600:1f18:262c:6542:9aa6:df7a:9a47:d29e"; m_server_ip = "2607:f8b0:4004:802::2004"; m_client_port = "37140"; @@ -292,15 +277,13 @@ TEST_F(ipv6_filtercheck_test, curl_google_www) read_file(LIBSINSP_TEST_CAPTURES_PATH "/curl_google.scap", "thread.tid=17497", - [this](sinsp_evt* evt) - { + [this](sinsp_evt* evt) { std::string evname = std::string(evt->get_name()); // Once we see a connect or bind, we can assume the // socket is connected and it's possible to get // client/server and local/remote information. - if (evname == "connect" || evname == "bind") - { + if(evname == "connect" || evname == "bind") { m_socket_connected = true; m_check_local_remote = true; m_check_is_server = true; @@ -310,8 +293,7 @@ TEST_F(ipv6_filtercheck_test, curl_google_www) }); } -TEST_F(ipv6_filtercheck_test, single_ipv6_conn_client) -{ +TEST_F(ipv6_filtercheck_test, single_ipv6_conn_client) { m_client_ip = "2001:db8::4"; m_server_ip = "2001:db8::3"; m_client_port = "54405"; @@ -331,8 +313,7 @@ TEST_F(ipv6_filtercheck_test, single_ipv6_conn_client) read_file(LIBSINSP_TEST_CAPTURES_PATH "/single_ipv6_conn.scap", "proc.pid=25888", - [this](sinsp_evt* evt) - { + [this](sinsp_evt* evt) { std::string evname = std::string(evt->get_name()); // Once we see a connect, we can assume the @@ -340,8 +321,7 @@ TEST_F(ipv6_filtercheck_test, single_ipv6_conn_client) // client/server information. However, we can *not* // get local/remote information as this connection was // done between two ips on the same local interface. - if (evname == "connect") - { + if(evname == "connect") { m_socket_connected = true; } @@ -349,8 +329,7 @@ TEST_F(ipv6_filtercheck_test, single_ipv6_conn_client) }); } -TEST_F(ipv6_filtercheck_test, single_ipv6_conn_server) -{ +TEST_F(ipv6_filtercheck_test, single_ipv6_conn_server) { m_client_ip = "2001:db8::4"; m_server_ip = "2001:db8::3"; m_client_port = "54405"; @@ -366,8 +345,7 @@ TEST_F(ipv6_filtercheck_test, single_ipv6_conn_server) read_file(LIBSINSP_TEST_CAPTURES_PATH "/single_ipv6_conn.scap", "proc.pid=25886", - [this](sinsp_evt* evt) - { + [this](sinsp_evt* evt) { std::string evname = std::string(evt->get_name()); // Once we see a connect, we can assume the @@ -375,8 +353,7 @@ TEST_F(ipv6_filtercheck_test, single_ipv6_conn_server) // client/server information. However, we can *not* // get local/remote information as this connection was // done between two ips on the same local interface. - if (evname == "connect") - { + if(evname == "connect") { m_socket_connected = true; } @@ -384,8 +361,7 @@ TEST_F(ipv6_filtercheck_test, single_ipv6_conn_server) }); } -TEST_F(ipv6_filtercheck_test, test_ipv6_client) -{ +TEST_F(ipv6_filtercheck_test, test_ipv6_client) { // test_ipv6_client.cpp does the following: // 1. sendto() on an unconnected socket to ::1 // 2. connect to ::1, port 2345 @@ -399,63 +375,55 @@ TEST_F(ipv6_filtercheck_test, test_ipv6_client) // The test verifies that the addresses/ports on the socket // change properly for the connects/sendtos. - enum state_t - { - sendto_unconnected, - send_connected, - send_reconnected, - sendto_reconnected, - done - }; + enum state_t { sendto_unconnected, send_connected, send_reconnected, sendto_reconnected, done }; state_t state = sendto_unconnected; read_file( - LIBSINSP_TEST_CAPTURES_PATH "/test_ipv6_client.scap", - "proc.name=test_ipv6_clien", - [&](sinsp_evt* evt) - { - std::string evname = std::string(evt->get_name()); - - std::string full_output; - std::string full = - "*%evt.num %evt.outputtime %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type " - "%evt.info"; - sinsp_evt_formatter(m_inspector.get(), full, m_filterlist).tostring(evt, &full_output); - - cstringset_t unconnected_names = {"::1:0->::1:2345", "::1:0->::1:dbm"}; - cstringset_t connected_names = {"::1:38255->::1:2345", "::1:38255->::1:dbm"}; - cstringset_t reconnected_names = {"::1:38255->::1:2345", "::1:38255->::1:dbm"}; - - if (evname == "send" || evname == "sendto") - { - switch (state) - { - case sendto_unconnected: - verify_filtercheck(evt, "*%fd.name", unconnected_names, full_output); - state = send_connected; - break; - case send_connected: - verify_filtercheck(evt, "*%fd.name", connected_names, full_output); - state = send_reconnected; - break; - case send_reconnected: - verify_filtercheck(evt, - "*%fd.name", - "::1:38255->2001:4860:4860::8888:domain", - full_output); - state = sendto_reconnected; - break; - case sendto_reconnected: - verify_filtercheck(evt, "*%fd.name", reconnected_names, full_output); - state = done; - break; - case done: - break; - } - } - }, - false); + LIBSINSP_TEST_CAPTURES_PATH "/test_ipv6_client.scap", + "proc.name=test_ipv6_clien", + [&](sinsp_evt* evt) { + std::string evname = std::string(evt->get_name()); + + std::string full_output; + std::string full = + "*%evt.num %evt.outputtime %evt.cpu %proc.name (%thread.tid) %evt.dir " + "%evt.type " + "%evt.info"; + sinsp_evt_formatter(m_inspector.get(), full, m_filterlist) + .tostring(evt, &full_output); + + cstringset_t unconnected_names = {"::1:0->::1:2345", "::1:0->::1:dbm"}; + cstringset_t connected_names = {"::1:38255->::1:2345", "::1:38255->::1:dbm"}; + cstringset_t reconnected_names = {"::1:38255->::1:2345", "::1:38255->::1:dbm"}; + + if(evname == "send" || evname == "sendto") { + switch(state) { + case sendto_unconnected: + verify_filtercheck(evt, "*%fd.name", unconnected_names, full_output); + state = send_connected; + break; + case send_connected: + verify_filtercheck(evt, "*%fd.name", connected_names, full_output); + state = send_reconnected; + break; + case send_reconnected: + verify_filtercheck(evt, + "*%fd.name", + "::1:38255->2001:4860:4860::8888:domain", + full_output); + state = sendto_reconnected; + break; + case sendto_reconnected: + verify_filtercheck(evt, "*%fd.name", reconnected_names, full_output); + state = done; + break; + case done: + break; + } + } + }, + false); ASSERT_TRUE(state == done); } diff --git a/test/libsinsp_e2e/main.cpp b/test/libsinsp_e2e/main.cpp index ac44d0941e..3170ac543c 100644 --- a/test/libsinsp_e2e/main.cpp +++ b/test/libsinsp_e2e/main.cpp @@ -32,8 +32,7 @@ limitations under the License. #define MODERN_BPF_OPTION "modern-bpf" #define BUFFER_OPTION "buffer-dim" -class EventListener : public ::testing::EmptyTestEventListener -{ +class EventListener : public ::testing::EmptyTestEventListener { public: EventListener(bool keep_capture_files) { m_keep_capture_files = keep_capture_files; } @@ -44,12 +43,11 @@ class EventListener : public ::testing::EmptyTestEventListener virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) {} // Called after a test ends. - virtual void OnTestEnd(const ::testing::TestInfo& test_info) - { - if (!m_keep_capture_files && !test_info.result()->Failed()) - { - std::string dump_filename = std::string(LIBSINSP_TEST_CAPTURES_PATH) + test_info.test_case_name() + "_ " + - test_info.name() + ".scap"; + virtual void OnTestEnd(const ::testing::TestInfo& test_info) { + if(!m_keep_capture_files && !test_info.result()->Failed()) { + std::string dump_filename = std::string(LIBSINSP_TEST_CAPTURES_PATH) + + test_info.test_case_name() + "_ " + test_info.name() + + ".scap"; std::remove(dump_filename.c_str()); } } @@ -58,31 +56,27 @@ class EventListener : public ::testing::EmptyTestEventListener bool m_keep_capture_files; }; -int insert_kmod(const std::string& kmod_path) -{ +int insert_kmod(const std::string& kmod_path) { /* Here we want to insert the module if we fail we need to abort the program. */ int fd = open(kmod_path.c_str(), O_RDONLY); - if(fd < 0) - { - std::cout << "Unable to open the kmod file. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + if(fd < 0) { + std::cout << "Unable to open the kmod file. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; } - if(syscall(__NR_finit_module, fd, "", 0)) - { - std::cerr << "Unable to inject the kmod. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + if(syscall(__NR_finit_module, fd, "", 0)) { + std::cerr << "Unable to inject the kmod. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; } close(fd); return EXIT_SUCCESS; } -int remove_kmod() -{ - if(syscall(__NR_delete_module, LIBSINSP_TEST_KERNEL_MODULE_NAME, O_NONBLOCK)) - { - switch(errno) - { +int remove_kmod() { + if(syscall(__NR_delete_module, LIBSINSP_TEST_KERNEL_MODULE_NAME, O_NONBLOCK)) { + switch(errno) { case ENOENT: return EXIT_SUCCESS; @@ -91,11 +85,9 @@ int remove_kmod() * case we wait until the module is detached. */ case EWOULDBLOCK: - for(int i = 0; i < 4; i++) - { + for(int i = 0; i < 4; i++) { int ret = syscall(__NR_delete_module, LIBSINSP_TEST_KERNEL_MODULE_NAME, O_NONBLOCK); - if(ret == 0 || errno == ENOENT) - { + if(ret == 0 || errno == ENOENT) { return EXIT_SUCCESS; } sleep(1); @@ -105,19 +97,20 @@ int remove_kmod() case EBUSY: case EFAULT: case EPERM: - std::cerr << "Unable to remove kernel module. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + std::cerr << "Unable to remove kernel module. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; default: - std::cerr << "Unexpected error code. Errno message: " << strerror(errno) << ", errno: " << errno << std::endl; + std::cerr << "Unexpected error code. Errno message: " << strerror(errno) + << ", errno: " << errno << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } -void print_menu_and_exit() -{ +void print_menu_and_exit() { std::string usage = R"(Usage: tests [options] Overview: The goal of this binary is to run tests against libsinsp. @@ -134,29 +127,25 @@ Overview: The goal of this binary is to run tests against libsinsp. exit(EXIT_SUCCESS); } -int open_engine(int argc, char** argv) -{ - static struct option long_options[] = { - {BPF_OPTION, optional_argument, 0, 'b'}, - {MODERN_BPF_OPTION, no_argument, 0, 'm'}, - {KMOD_OPTION, optional_argument, 0, 'k'}, - {BUFFER_OPTION, required_argument, 0, 'd'}, - {HELP_OPTION, no_argument, 0, 'h'}, - {VERBOSE_OPTION, required_argument, 0, 'v'}, - {0, 0, 0, 0}}; +int open_engine(int argc, char** argv) { + static struct option long_options[] = {{BPF_OPTION, optional_argument, 0, 'b'}, + {MODERN_BPF_OPTION, no_argument, 0, 'm'}, + {KMOD_OPTION, optional_argument, 0, 'k'}, + {BUFFER_OPTION, required_argument, 0, 'd'}, + {HELP_OPTION, no_argument, 0, 'h'}, + {VERBOSE_OPTION, required_argument, 0, 'v'}, + {0, 0, 0, 0}}; /* Remove kmod if injected, we remove it always even if we use another engine * in this way we are sure the unique driver in the system is the one we will use. */ - if(remove_kmod()) - { + if(remove_kmod()) { return EXIT_FAILURE; } /* Get current cwd as a base directory for the driver path */ char driver_path[FILENAME_MAX]; - if(!getcwd(driver_path, FILENAME_MAX)) - { + if(!getcwd(driver_path, FILENAME_MAX)) { std::cerr << "Unable to get current dir" << std::endl; return EXIT_FAILURE; } @@ -164,12 +153,8 @@ int open_engine(int argc, char** argv) /* Parse CLI options */ int op = 0; int long_index = 0; - while((op = getopt_long(argc, argv, - "b::mk::d:hv:", - long_options, &long_index)) != -1) - { - switch(op) - { + while((op = getopt_long(argc, argv, "b::mk::d:hv:", long_options, &long_index)) != -1) { + switch(op) { case 'b': #ifdef HAS_ENGINE_BPF event_capture::set_engine(BPF_ENGINE, LIBSINSP_TEST_BPF_PROBE_PATH); @@ -214,24 +199,22 @@ int open_engine(int argc, char** argv) return EXIT_SUCCESS; } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); std::string captures_dir = LIBSINSP_TEST_CAPTURES_PATH; - if(!std::filesystem::exists(captures_dir)) - { - if(!std::filesystem::create_directory(captures_dir)) - { - std::cerr << "Failed to create captures directory." << std::endl;; + if(!std::filesystem::exists(captures_dir)) { + if(!std::filesystem::create_directory(captures_dir)) { + std::cerr << "Failed to create captures directory." << std::endl; + ; return EXIT_FAILURE; } } - if(open_engine(argc, argv) == EXIT_FAILURE) - { - std::cerr << "Failed to open the engine." << std::endl;; + if(open_engine(argc, argv) == EXIT_FAILURE) { + std::cerr << "Failed to open the engine." << std::endl; + ; return EXIT_FAILURE; } diff --git a/test/libsinsp_e2e/paths.cpp b/test/libsinsp_e2e/paths.cpp index 84d021bc2b..881da21789 100644 --- a/test/libsinsp_e2e/paths.cpp +++ b/test/libsinsp_e2e/paths.cpp @@ -39,51 +39,41 @@ using namespace std; #define DATA "ABCDEFGHI" -class path_validator -{ +class path_validator { public: path_validator(string filename, string bcwd) { update_cwd(filename, bcwd); } - void update_cwd(string filename, string bcwd) - { + void update_cwd(string filename, string bcwd) { m_callnum = 0; m_filename = filename; std::filesystem::path f(filename); - if(!f.is_absolute()) - { + if(!f.is_absolute()) { m_scat = string("") + std::string(std::filesystem::absolute(f).lexically_normal()); - } - else - { + } else { m_scat = string("") + std::string(f.lexically_normal()); } m_scwd = bcwd; - if (m_scwd[m_scwd.size() != '/']) - { + if(m_scwd[m_scwd.size() != '/']) { m_scwd += '/'; } } - void validate(sinsp_evt* e) - { + void validate(sinsp_evt* e) { uint16_t type = e->get_type(); sinsp_threadinfo* pinfo = e->get_thread_info(false); - switch (m_callnum) - { + switch(m_callnum) { case 0: - if (type == PPME_SYSCALL_OPEN_E || type == PPME_SYSCALL_OPENAT_2_E) - { + if(type == PPME_SYSCALL_OPEN_E || type == PPME_SYSCALL_OPENAT_2_E) { m_callnum++; } break; case 1: - if (type == PPME_SYSCALL_OPEN_X || type == PPME_SYSCALL_OPENAT_2_X) - { + if(type == PPME_SYSCALL_OPEN_X || type == PPME_SYSCALL_OPENAT_2_X) { EXPECT_EQ(e->get_param_value_str("name", false), m_filename); EXPECT_EQ(m_scwd, pinfo->get_cwd()); EXPECT_EQ(m_scat, e->get_param_value_str("fd")); @@ -93,23 +83,19 @@ class path_validator break; case 2: - if (type == PPME_SYSCALL_WRITE_E) - { + if(type == PPME_SYSCALL_WRITE_E) { int cfd = std::stoll(e->get_param_value_str("fd", false)); - if (cfd == m_fd) - { + if(cfd == m_fd) { EXPECT_EQ(m_scat, e->get_param_value_str("fd")); - EXPECT_EQ(std::to_string(sizeof(DATA) - 1), - e->get_param_value_str("size")); + EXPECT_EQ(std::to_string(sizeof(DATA) - 1), e->get_param_value_str("size")); m_callnum++; } } break; case 3: - if (type == PPME_SYSCALL_WRITE_X) - { + if(type == PPME_SYSCALL_WRITE_X) { EXPECT_EQ(std::to_string(sizeof(DATA) - 1), e->get_param_value_str("res")); EXPECT_EQ(m_scwd, pinfo->get_cwd()); EXPECT_EQ(DATA, e->get_param_value_str("data")); @@ -130,8 +116,7 @@ class path_validator string m_scat; }; -void testdir(string filename, string chdirtarget = "") -{ +void testdir(string filename, string chdirtarget = "") { char bcwd[1024]; ASSERT_TRUE(getcwd(bcwd, 1024) != NULL); @@ -141,18 +126,13 @@ void testdir(string filename, string chdirtarget = "") // FILTER // int tid = getpid(); - event_filter_t filter = [&](sinsp_evt* evt) - { - return evt->get_tid() == tid; - }; + event_filter_t filter = [&](sinsp_evt* evt) { return evt->get_tid() == tid; }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - if (chdirtarget != "") - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { + if(chdirtarget != "") { char tcwd[1024]; ASSERT_TRUE(chdir(chdirtarget.c_str()) == 0); @@ -165,13 +145,10 @@ void testdir(string filename, string chdirtarget = "") FILE* f = fopen(vldt.m_filename.c_str(), "w+"); - if (f) - { + if(f) { fwrite(DATA, sizeof(DATA) - 1, 1, f); fclose(f); - } - else - { + } else { std::filesystem::path cwd = std::filesystem::current_path(); std::cout << "FAIL " << std::string(cwd) << std::endl; FAIL(); @@ -179,8 +156,7 @@ void testdir(string filename, string chdirtarget = "") unlink(vldt.m_filename.c_str()); - if (chdirtarget != "") - { + if(chdirtarget != "") { ASSERT_TRUE(chdir(bcwd) == 0); } }; @@ -188,103 +164,86 @@ void testdir(string filename, string chdirtarget = "") // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { vldt.validate(param.m_evt); }; + captured_event_callback_t callback = [&](const callback_param& param) { + vldt.validate(param.m_evt); + }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); EXPECT_EQ(4, vldt.m_callnum); } -std::string cwd() -{ +std::string cwd() { return std::filesystem::current_path().filename().string(); } ///////////////////////////////////////////////////////////////////////////////////// // relative path-based tests ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, dir_path_1) -{ +TEST_F(sys_call_test, dir_path_1) { testdir("./test_tmpfile"); } -TEST_F(sys_call_test, dir_path_2) -{ +TEST_F(sys_call_test, dir_path_2) { testdir("../test_tmpfile"); } -TEST_F(sys_call_test, dir_path_3) -{ +TEST_F(sys_call_test, dir_path_3) { testdir("/test_tmpfile"); } -TEST_F(sys_call_test, dir_path_4) -{ +TEST_F(sys_call_test, dir_path_4) { testdir("//test_tmpfile"); } -TEST_F(sys_call_test, dir_path_5) -{ +TEST_F(sys_call_test, dir_path_5) { testdir("///test_tmpfile"); } -TEST_F(sys_call_test, dir_path_6) -{ +TEST_F(sys_call_test, dir_path_6) { testdir("////test_tmpfile"); } -TEST_F(sys_call_test, dir_path_7) -{ +TEST_F(sys_call_test, dir_path_7) { testdir("//////////////////////////////test_tmpfile"); } -TEST_F(sys_call_test, dir_path_8) -{ +TEST_F(sys_call_test, dir_path_8) { testdir("../" + cwd() + "/test_tmpfile"); } -TEST_F(sys_call_test, dir_path_9) -{ +TEST_F(sys_call_test, dir_path_9) { testdir("../" + cwd() + "/../" + cwd() + "/../" + cwd() + "/../" + cwd() + "/test_tmpfile"); } -TEST_F(sys_call_test, dir_path_10) -{ +TEST_F(sys_call_test, dir_path_10) { testdir("/./test_tmpfile"); } -TEST_F(sys_call_test, dir_path_11) -{ +TEST_F(sys_call_test, dir_path_11) { testdir("/../test_tmpfile"); } -TEST_F(sys_call_test, dir_path_12) -{ +TEST_F(sys_call_test, dir_path_12) { testdir("/../../../../../../test_tmpfile"); } -TEST_F(sys_call_test, dir_path_13) -{ +TEST_F(sys_call_test, dir_path_13) { testdir("../../../../../../test_tmpfile"); } -TEST_F(sys_call_test, dir_path_14) -{ +TEST_F(sys_call_test, dir_path_14) { testdir("././././././test_tmpfile"); } -TEST_F(sys_call_test, dir_path_15) -{ +TEST_F(sys_call_test, dir_path_15) { testdir(".././.././.././test_tmpfile"); } -TEST_F(sys_call_test, dir_path_16) -{ +TEST_F(sys_call_test, dir_path_16) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -293,11 +252,9 @@ TEST_F(sys_call_test, dir_path_16) rmdir("./tmpdir"); } -TEST_F(sys_call_test, dir_path_17) -{ +TEST_F(sys_call_test, dir_path_17) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -306,11 +263,9 @@ TEST_F(sys_call_test, dir_path_17) rmdir("./tmpdir"); } -TEST_F(sys_call_test, dir_path_18) -{ +TEST_F(sys_call_test, dir_path_18) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -319,11 +274,9 @@ TEST_F(sys_call_test, dir_path_18) rmdir("./tmpdir"); } -TEST_F(sys_call_test, dir_path_19) -{ +TEST_F(sys_call_test, dir_path_19) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -335,87 +288,70 @@ TEST_F(sys_call_test, dir_path_19) ///////////////////////////////////////////////////////////////////////////////////// // chdir-based tests ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, dir_chdir_1) -{ +TEST_F(sys_call_test, dir_chdir_1) { testdir("test_tmpfile", "./"); } -TEST_F(sys_call_test, dir_chdir_2) -{ +TEST_F(sys_call_test, dir_chdir_2) { testdir("test_tmpfile", "../"); } -TEST_F(sys_call_test, dir_chdir_3) -{ +TEST_F(sys_call_test, dir_chdir_3) { testdir("test_tmpfile", "/"); } -TEST_F(sys_call_test, dir_chdir_4) -{ +TEST_F(sys_call_test, dir_chdir_4) { testdir("test_tmpfile", "//"); } -TEST_F(sys_call_test, dir_chdir_5) -{ +TEST_F(sys_call_test, dir_chdir_5) { testdir("test_tmpfile", "///"); } -TEST_F(sys_call_test, dir_chdir_6) -{ +TEST_F(sys_call_test, dir_chdir_6) { testdir("test_tmpfile", "////"); } -TEST_F(sys_call_test, dir_chdir_7) -{ +TEST_F(sys_call_test, dir_chdir_7) { testdir("test_tmpfile", "//////////////////////////////"); } -TEST_F(sys_call_test, dir_chdir_8) -{ +TEST_F(sys_call_test, dir_chdir_8) { testdir("test_tmpfile", "../" + cwd() + "/"); } -TEST_F(sys_call_test, dir_chdir_9) -{ +TEST_F(sys_call_test, dir_chdir_9) { testdir("test_tmpfile", "../" + cwd() + "/../" + cwd() + "/../" + cwd() + "/../" + cwd()); } -TEST_F(sys_call_test, dir_chdir_10) -{ +TEST_F(sys_call_test, dir_chdir_10) { testdir("test_tmpfile", "/./"); } -TEST_F(sys_call_test, dir_chdir_11) -{ +TEST_F(sys_call_test, dir_chdir_11) { testdir("test_tmpfile", "/.."); } -TEST_F(sys_call_test, dir_chdir_12) -{ +TEST_F(sys_call_test, dir_chdir_12) { testdir("test_tmpfile", "/../../../../../../"); } -TEST_F(sys_call_test, dir_chdir_13) -{ +TEST_F(sys_call_test, dir_chdir_13) { testdir("test_tmpfile", "../../../../../.."); } -TEST_F(sys_call_test, dir_chdir_14) -{ +TEST_F(sys_call_test, dir_chdir_14) { testdir("test_tmpfile", "././././././"); } -TEST_F(sys_call_test, dir_chdir_15) -{ +TEST_F(sys_call_test, dir_chdir_15) { testdir("test_tmpfile", ".././.././.././"); } -TEST_F(sys_call_test, dir_chdir_16) -{ +TEST_F(sys_call_test, dir_chdir_16) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -424,11 +360,9 @@ TEST_F(sys_call_test, dir_chdir_16) rmdir("./tmpdir"); } -TEST_F(sys_call_test, dir_chdir_17) -{ +TEST_F(sys_call_test, dir_chdir_17) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -437,11 +371,9 @@ TEST_F(sys_call_test, dir_chdir_17) rmdir("./tmpdir"); } -TEST_F(sys_call_test, dir_chdir_18) -{ +TEST_F(sys_call_test, dir_chdir_18) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -450,11 +382,9 @@ TEST_F(sys_call_test, dir_chdir_18) rmdir("./tmpdir"); } -TEST_F(sys_call_test, dir_chdir_19) -{ +TEST_F(sys_call_test, dir_chdir_19) { int res = mkdir("./tmpdir", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0; - if (res < 0 && res != EEXIST) - { + if(res < 0 && res != EEXIST) { FAIL(); } @@ -466,8 +396,7 @@ TEST_F(sys_call_test, dir_chdir_19) ///////////////////////////////////////////////////////////////////////////////////// // chdir/getcwd ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, dir_getcwd) -{ +TEST_F(sys_call_test, dir_getcwd) { int callnum = 0; char dir0[] = "./"; char dir1[] = ".."; @@ -492,8 +421,7 @@ TEST_F(sys_call_test, dir_getcwd) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { ASSERT_TRUE(chdir(dir0) == 0); ASSERT_TRUE(getcwd(cwd0, 256) != NULL); @@ -516,24 +444,19 @@ TEST_F(sys_call_test, dir_getcwd) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); sinsp_threadinfo* pinfo = e->get_thread_info(false); - if (type == PPME_SYSCALL_CHDIR_E) - { + if(type == PPME_SYSCALL_CHDIR_E) { callnum++; - } - else if (type == PPME_SYSCALL_CHDIR_X) - { + } else if(type == PPME_SYSCALL_CHDIR_X) { string cdir; string cdir1; string adir; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ("0", e->get_param_value_str("res")); cdir = string(cwd0); @@ -574,12 +497,9 @@ TEST_F(sys_call_test, dir_getcwd) // // pinfo->get_cwd() contains a / at the end of the directory // - if (cdir != "/") - { + if(cdir != "/") { cdir1 = cdir + "/"; - } - else - { + } else { cdir1 = cdir; } EXPECT_EQ(cdir1, pinfo->get_cwd()); @@ -596,8 +516,7 @@ TEST_F(sys_call_test, dir_getcwd) ///////////////////////////////////////////////////////////////////////////////////// // fchdir ///////////////////////////////////////////////////////////////////////////////////// -TEST_F(sys_call_test, dir_fchdir) -{ +TEST_F(sys_call_test, dir_fchdir) { int callnum = 0; char dir0[] = "./"; char dir1[] = ".."; @@ -621,13 +540,11 @@ TEST_F(sys_call_test, dir_fchdir) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int fd; fd = open(dir0, O_RDONLY); - if (fd < 0) - { + if(fd < 0) { FAIL(); } ASSERT_TRUE(fchdir(fd) == 0); @@ -635,8 +552,7 @@ TEST_F(sys_call_test, dir_fchdir) close(fd); fd = open(dir1, O_RDONLY); - if (fd < 0) - { + if(fd < 0) { FAIL(); } ASSERT_TRUE(fchdir(fd) == 0); @@ -644,8 +560,7 @@ TEST_F(sys_call_test, dir_fchdir) close(fd); fd = open(dir2, O_RDONLY); - if (fd < 0) - { + if(fd < 0) { FAIL(); } ASSERT_TRUE(fchdir(fd) == 0); @@ -653,8 +568,7 @@ TEST_F(sys_call_test, dir_fchdir) close(fd); fd = open(dir3, O_RDONLY); - if (fd < 0) - { + if(fd < 0) { FAIL(); } ASSERT_TRUE(fchdir(fd) == 0); @@ -666,8 +580,7 @@ TEST_F(sys_call_test, dir_fchdir) close(fd); fd = open(cwd_ori, O_RDONLY); - if (fd < 0) - { + if(fd < 0) { FAIL(); } ASSERT_TRUE(fchdir(fd) == 0); @@ -678,18 +591,15 @@ TEST_F(sys_call_test, dir_fchdir) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); sinsp_threadinfo* pinfo = e->get_thread_info(false); - if (type == PPME_SYSCALL_FCHDIR_E) - { + if(type == PPME_SYSCALL_FCHDIR_E) { string adir; - switch (callnum) - { + switch(callnum) { case 0: adir = string("") + string(cwd0); break; @@ -716,14 +626,11 @@ TEST_F(sys_call_test, dir_fchdir) EXPECT_EQ(adir, e->get_param_value_str("fd")); callnum++; - } - else if (type == PPME_SYSCALL_FCHDIR_X) - { + } else if(type == PPME_SYSCALL_FCHDIR_X) { string cdir; string cdir1; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ("0", e->get_param_value_str("res")); cdir = string(cwd0); @@ -756,12 +663,9 @@ TEST_F(sys_call_test, dir_fchdir) // // pinfo->get_cwd() contains a / at the end of the directory // - if (cdir != "/") - { + if(cdir != "/") { cdir1 = cdir + "/"; - } - else - { + } else { cdir1 = cdir; } diff --git a/test/libsinsp_e2e/process.cpp b/test/libsinsp_e2e/process.cpp index f960fbb397..ad556bd587 100644 --- a/test/libsinsp_e2e/process.cpp +++ b/test/libsinsp_e2e/process.cpp @@ -49,8 +49,7 @@ limitations under the License. #include #include -TEST_F(sys_call_test, process_signalfd_kill) -{ +TEST_F(sys_call_test, process_signalfd_kill) { int callnum = 0; int ptid; // parent tid @@ -62,22 +61,21 @@ TEST_F(sys_call_test, process_signalfd_kill) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_tid() == ptid || evt->get_tid() == ctid; }; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_tid() == ptid || evt->get_tid() == ctid; + }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int status; int sfd; ctid = fork(); - if (ctid >= 0) // fork succeeded + if(ctid >= 0) // fork succeeded { - if (ctid == 0) - { + if(ctid == 0) { // // CHILD PROCESS // @@ -90,20 +88,17 @@ TEST_F(sys_call_test, process_signalfd_kill) /* Block the signals that we handle using signalfd(), so they don't * cause signal handlers or default signal actions to execute. */ - if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) - { + if(sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { FAIL(); } /* Create a file descriptor from which we will read the signals. */ sfd = signalfd(-1, &mask, 0); - if (sfd < 0) - { + if(sfd < 0) { FAIL(); } - while (true) - { + while(true) { /** The buffer for read(), this structure contains information * about the signal we've read. */ struct signalfd_siginfo si; @@ -112,25 +107,18 @@ TEST_F(sys_call_test, process_signalfd_kill) res = read(sfd, &si, sizeof(si)); - if (res < 0) - { + if(res < 0) { FAIL(); } - if (res != sizeof(si)) - { + if(res != sizeof(si)) { FAIL(); } - if (si.ssi_signo == SIGTERM) - { + if(si.ssi_signo == SIGTERM) { continue; - } - else if (si.ssi_signo == SIGINT) - { + } else if(si.ssi_signo == SIGINT) { break; - } - else - { + } else { FAIL(); } } @@ -144,9 +132,7 @@ TEST_F(sys_call_test, process_signalfd_kill) // Remember to use _exit or the test system will get fucked!! // _exit(xstatus); - } - else - { + } else { // // PARENT PROCESS // @@ -166,9 +152,7 @@ TEST_F(sys_call_test, process_signalfd_kill) // ASSERT_EQ(waitpid(ctid, &status, 0), ctid); } - } - else - { + } else { FAIL(); } }; @@ -176,59 +160,43 @@ TEST_F(sys_call_test, process_signalfd_kill) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_SIGNALFD_E) - { + if(type == PPME_SYSCALL_SIGNALFD_E) { EXPECT_EQ(-1, std::stoi(e->get_param_value_str("fd", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("mask"))); EXPECT_EQ(0, std::stol(e->get_param_value_str("flags"))); callnum++; - } - else if (type == PPME_SYSCALL_SIGNALFD4_E) - { + } else if(type == PPME_SYSCALL_SIGNALFD4_E) { EXPECT_EQ(-1, stoi(e->get_param_value_str("fd", false))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("mask"))); callnum++; - } - else if (type == PPME_SYSCALL_SIGNALFD_X || type == PPME_SYSCALL_SIGNALFD4_X) - { + } else if(type == PPME_SYSCALL_SIGNALFD_X || type == PPME_SYSCALL_SIGNALFD4_X) { ssfd = std::stoi(e->get_param_value_str("res", false)); callnum++; - } - else if (type == PPME_SYSCALL_READ_E) - { - if (callnum == 2) - { + } else if(type == PPME_SYSCALL_READ_E) { + if(callnum == 2) { EXPECT_EQ("", e->get_param_value_str("fd")); EXPECT_EQ(ssfd, std::stoi(e->get_param_value_str("fd", false))); callnum++; } - } - else if (type == PPME_SYSCALL_KILL_E) - { - if (callnum == 3) - { + } else if(type == PPME_SYSCALL_KILL_E) { + if(callnum == 3) { EXPECT_EQ("libsinsp_e2e_te", e->get_param_value_str("pid")); EXPECT_EQ(ctid, std::stoi(e->get_param_value_str("pid", false))); EXPECT_EQ("SIGTERM", e->get_param_value_str("sig")); EXPECT_EQ(SIGTERM, std::stoi(e->get_param_value_str("sig", false))); callnum++; - } - else if (callnum == 5) - { + } else if(callnum == 5) { EXPECT_EQ("libsinsp_e2e_te", e->get_param_value_str("pid")); EXPECT_EQ(ctid, std::stoi(e->get_param_value_str("pid", false))); EXPECT_EQ("SIGINT", e->get_param_value_str("sig")); EXPECT_EQ(SIGINT, std::stoi(e->get_param_value_str("sig", false))); callnum++; } - } - else if (type == PPME_SYSCALL_KILL_X) - { + } else if(type == PPME_SYSCALL_KILL_X) { EXPECT_EQ(0, std::stoi(e->get_param_value_str("res", false))); callnum++; } @@ -240,8 +208,7 @@ TEST_F(sys_call_test, process_signalfd_kill) } // This test is disabled until the new syscall for sleep is implemented. -TEST_F(sys_call_test, DISABLED_process_usleep) -{ +TEST_F(sys_call_test, DISABLED_process_usleep) { int callnum = 0; // @@ -252,43 +219,33 @@ TEST_F(sys_call_test, DISABLED_process_usleep) // // TEST CODE // - run_callback_t test = [](concurrent_object_handle inspector_handle) - { - + run_callback_t test = [](concurrent_object_handle inspector_handle) { struct timespec req; req.tv_sec = 0; req.tv_nsec = 123456; - nanosleep(&req,nullptr); + nanosleep(&req, nullptr); req.tv_sec = 5; req.tv_nsec = 0; - nanosleep(&req,nullptr); + nanosleep(&req, nullptr); }; // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_NANOSLEEP_E) - { - if (callnum == 0) - { - if (std::stoll(e->get_param_value_str("interval", false)) == 123456000) - { + if(type == PPME_SYSCALL_NANOSLEEP_E) { + if(callnum == 0) { + if(std::stoll(e->get_param_value_str("interval", false)) == 123456000) { callnum++; } - } - else if (callnum == 2) - { + } else if(callnum == 2) { EXPECT_EQ(5000000000, std::stoll(e->get_param_value_str("interval", false))); callnum++; } - } - else if (type == PPME_SYSCALL_NANOSLEEP_X) - { + } else if(type == PPME_SYSCALL_NANOSLEEP_X) { EXPECT_EQ(0, stoi(e->get_param_value_str("res", false))); callnum++; } @@ -302,8 +259,7 @@ TEST_F(sys_call_test, DISABLED_process_usleep) #define EVENT_SIZE (sizeof(struct inotify_event)) #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16)) -TEST_F(sys_call_test, process_inotify) -{ +TEST_F(sys_call_test, process_inotify) { int callnum = 0; int fd; @@ -315,8 +271,7 @@ TEST_F(sys_call_test, process_inotify) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int length; int wd; char buffer[EVENT_BUF_LEN]; @@ -327,8 +282,7 @@ TEST_F(sys_call_test, process_inotify) fd = inotify_init(); /*checking for error*/ - if (fd < 0) - { + if(fd < 0) { FAIL(); } @@ -342,8 +296,7 @@ TEST_F(sys_call_test, process_inotify) // read to determine the event changes // length = read(fd, buffer, EVENT_BUF_LEN); - if (length < 0) - { + if(length < 0) { FAIL(); } @@ -361,30 +314,21 @@ TEST_F(sys_call_test, process_inotify) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); std::string name(e->get_name()); - if (type == PPME_SYSCALL_INOTIFY_INIT_E) - { + if(type == PPME_SYSCALL_INOTIFY_INIT_E) { EXPECT_EQ(0, std::stoi(e->get_param_value_str("flags"))); callnum++; - } - else if (type == PPME_SYSCALL_INOTIFY_INIT1_E) - { + } else if(type == PPME_SYSCALL_INOTIFY_INIT1_E) { callnum++; - } - else if (type == PPME_SYSCALL_INOTIFY_INIT_X || type == PPME_SYSCALL_INOTIFY_INIT1_X) - { + } else if(type == PPME_SYSCALL_INOTIFY_INIT_X || type == PPME_SYSCALL_INOTIFY_INIT1_X) { EXPECT_EQ(fd, std::stoi(e->get_param_value_str("res", false))); callnum++; - } - else if (name.find("read") != std::string::npos && e->get_direction() == SCAP_ED_IN) - { - if (callnum == 2) - { + } else if(name.find("read") != std::string::npos && e->get_direction() == SCAP_ED_IN) { + if(callnum == 2) { EXPECT_EQ("", e->get_param_value_str("fd")); EXPECT_EQ(fd, std::stoi(e->get_param_value_str("fd", false))); callnum++; @@ -397,8 +341,7 @@ TEST_F(sys_call_test, process_inotify) EXPECT_EQ(3, callnum); } -TEST(procinfo, process_not_existent) -{ +TEST(procinfo, process_not_existent) { sinsp inspector; inspector.open_nodriver(true); @@ -417,8 +360,7 @@ TEST(procinfo, process_not_existent) // sinsp_threadinfo* tinfo = inspector.get_thread_ref(0xffff, true, true).get(); EXPECT_NE((sinsp_threadinfo*)NULL, tinfo); - if (tinfo) - { + if(tinfo) { EXPECT_EQ("", tinfo->m_comm); } @@ -427,16 +369,14 @@ TEST(procinfo, process_not_existent) // tinfo = inspector.get_thread_ref(0xffff, false, true).get(); EXPECT_NE((sinsp_threadinfo*)NULL, tinfo); - if (tinfo) - { + if(tinfo) { EXPECT_EQ("", tinfo->m_comm); } inspector.close(); } -TEST_F(sys_call_test, process_rlimit) -{ +TEST_F(sys_call_test, process_rlimit) { int callnum = 0; // @@ -447,8 +387,7 @@ TEST_F(sys_call_test, process_rlimit) // // TEST CODE // - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { struct rlimit rl; sleep(1); @@ -464,73 +403,56 @@ TEST_F(sys_call_test, process_rlimit) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_GETRLIMIT_E) - { + if(type == PPME_SYSCALL_GETRLIMIT_E) { EXPECT_EQ((int64_t)PPM_RLIMIT_NOFILE, std::stoll(e->get_param_value_str("resource", false))); callnum++; } - if (type == PPME_SYSCALL_GETRLIMIT_X) - { - if (callnum == 1) - { + if(type == PPME_SYSCALL_GETRLIMIT_X) { + if(callnum == 1) { EXPECT_GT((int64_t)0, std::stoll(e->get_param_value_str("res", false))); - } - else - { + } else { EXPECT_EQ((int64_t)0, std::stoll(e->get_param_value_str("res", false))); - if (callnum == 7) - { - EXPECT_EQ((int64_t)500, - std::stoll(e->get_param_value_str("cur", false))); - EXPECT_EQ((int64_t)1000, - std::stoll(e->get_param_value_str("max", false))); + if(callnum == 7) { + EXPECT_EQ((int64_t)500, std::stoll(e->get_param_value_str("cur", false))); + EXPECT_EQ((int64_t)1000, std::stoll(e->get_param_value_str("max", false))); } } callnum++; } - if (type == PPME_SYSCALL_SETRLIMIT_E) - { + if(type == PPME_SYSCALL_SETRLIMIT_E) { EXPECT_EQ((int64_t)PPM_RLIMIT_NOFILE, std::stoll(e->get_param_value_str("resource", false))); callnum++; } - if (type == PPME_SYSCALL_SETRLIMIT_X) - { + if(type == PPME_SYSCALL_SETRLIMIT_X) { EXPECT_EQ((int64_t)0, std::stoll(e->get_param_value_str("res", false))); - if (callnum == 5) - { - EXPECT_EQ((int64_t)500, - std::stoll(e->get_param_value_str("cur", false))); - EXPECT_EQ((int64_t)1000, - std::stoll(e->get_param_value_str("max", false))); + if(callnum == 5) { + EXPECT_EQ((int64_t)500, std::stoll(e->get_param_value_str("cur", false))); + EXPECT_EQ((int64_t)1000, std::stoll(e->get_param_value_str("max", false))); } callnum++; } - if (type == PPME_SYSCALL_PRLIMIT_E) - { + if(type == PPME_SYSCALL_PRLIMIT_E) { EXPECT_EQ((int64_t)PPM_RLIMIT_NOFILE, std::stoll(e->get_param_value_str("resource", false))); callnum++; } - if (type == PPME_SYSCALL_PRLIMIT_X) - { + if(type == PPME_SYSCALL_PRLIMIT_X) { int64_t res = std::stoll(e->get_param_value_str("res", false)); int64_t newcur = std::stoll(e->get_param_value_str("newcur", false)); int64_t newmax = std::stoll(e->get_param_value_str("newmax", false)); int64_t oldcur = std::stoll(e->get_param_value_str("oldcur", false)); int64_t oldmax = std::stoll(e->get_param_value_str("oldmax", false)); - switch (callnum) - { + switch(callnum) { case 1: EXPECT_GT(0, res); break; @@ -563,8 +485,7 @@ TEST_F(sys_call_test, process_rlimit) EXPECT_EQ(8, callnum); } -TEST_F(sys_call_test, process_prlimit) -{ +TEST_F(sys_call_test, process_prlimit) { int callnum = 0; struct rlimit tmprl; struct rlimit orirl; @@ -572,16 +493,12 @@ TEST_F(sys_call_test, process_prlimit) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { - return m_tid_filter(evt); - }; + event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { struct rlimit newrl; struct rlimit oldrl; @@ -595,63 +512,44 @@ TEST_F(sys_call_test, process_prlimit) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_PRLIMIT_E) - { + if(type == PPME_SYSCALL_PRLIMIT_E) { EXPECT_EQ((int64_t)PPM_RLIMIT_NOFILE, std::stoll(e->get_param_value_str("resource", false))); - EXPECT_EQ((int64_t)getpid(), - std::stoll(e->get_param_value_str("pid", false))); + EXPECT_EQ((int64_t)getpid(), std::stoll(e->get_param_value_str("pid", false))); callnum++; - } - else if(type == PPME_SYSCALL_PRLIMIT_X) - { + } else if(type == PPME_SYSCALL_PRLIMIT_X) { EXPECT_GE((int64_t)0, std::stoll(e->get_param_value_str("res", false))); - if (callnum == 1) - { - EXPECT_EQ((int64_t)0, - std::stoll(e->get_param_value_str("newcur", false))); - EXPECT_EQ((int64_t)0, - std::stoll(e->get_param_value_str("newmax", false))); + if(callnum == 1) { + EXPECT_EQ((int64_t)0, std::stoll(e->get_param_value_str("newcur", false))); + EXPECT_EQ((int64_t)0, std::stoll(e->get_param_value_str("newmax", false))); EXPECT_EQ((int64_t)orirl.rlim_cur, std::stoll(e->get_param_value_str("oldcur", false))); EXPECT_EQ((int64_t)orirl.rlim_max, std::stoll(e->get_param_value_str("oldmax", false))); - } - else if (callnum == 3) - { - EXPECT_EQ((int64_t)500, - std::stoll(e->get_param_value_str("newcur", false))); - EXPECT_EQ((int64_t)1000, - std::stoll(e->get_param_value_str("newmax", false))); + } else if(callnum == 3) { + EXPECT_EQ((int64_t)500, std::stoll(e->get_param_value_str("newcur", false))); + EXPECT_EQ((int64_t)1000, std::stoll(e->get_param_value_str("newmax", false))); EXPECT_EQ((int64_t)orirl.rlim_cur, std::stoll(e->get_param_value_str("oldcur", false))); EXPECT_EQ((int64_t)orirl.rlim_max, std::stoll(e->get_param_value_str("oldmax", false))); - } - else if (callnum == 5) - { - EXPECT_EQ((int64_t)0, - std::stoll(e->get_param_value_str("newcur", false))); - EXPECT_EQ((int64_t)0, - std::stoll(e->get_param_value_str("newmax", false))); - EXPECT_EQ((int64_t)500, - std::stoll(e->get_param_value_str("oldcur", false))); - EXPECT_EQ((int64_t)1000, - std::stoll(e->get_param_value_str("oldmax", false))); + } else if(callnum == 5) { + EXPECT_EQ((int64_t)0, std::stoll(e->get_param_value_str("newcur", false))); + EXPECT_EQ((int64_t)0, std::stoll(e->get_param_value_str("newmax", false))); + EXPECT_EQ((int64_t)500, std::stoll(e->get_param_value_str("oldcur", false))); + EXPECT_EQ((int64_t)1000, std::stoll(e->get_param_value_str("oldmax", false))); } callnum++; } }; - if (syscall(SYS_prlimit64, getpid(), RLIMIT_NOFILE, NULL, &tmprl) != 0) - { + if(syscall(SYS_prlimit64, getpid(), RLIMIT_NOFILE, NULL, &tmprl) != 0) { return; } @@ -660,47 +558,40 @@ TEST_F(sys_call_test, process_prlimit) EXPECT_EQ(6, callnum); } -class loadthread -{ +class loadthread { public: - loadthread() - { + loadthread() { m_die = false; m_tid = -1; m_utime_delta = 0; m_prevutime = 0; } - uint64_t read_utime() - { + uint64_t read_utime() { struct rusage ru; getrusage(RUSAGE_THREAD, &ru); return ru.ru_utime.tv_sec * 1000000 + ru.ru_utime.tv_usec; } - void run() - { + void run() { uint64_t k = 0; uint64_t t = 0; m_tid = syscall(SYS_gettid); m_prevutime = read_utime(); - while (true) - { + while(true) { t += k; t = t % 35689; - if (m_read_cpu) - { + if(m_read_cpu) { auto utime = read_utime(); m_utime_delta = utime - m_prevutime; m_prevutime = utime; m_read_cpu = false; } - if (m_die) - { + if(m_die) { return; } } @@ -715,8 +606,7 @@ class loadthread int64_t m_tid; }; -TEST_F(sys_call_test, process_scap_proc_get) -{ +TEST_F(sys_call_test, process_scap_proc_get) { int callnum = 0; // @@ -727,8 +617,7 @@ TEST_F(sys_call_test, process_scap_proc_get) // // TEST CODE // - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { usleep(1000); int s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); @@ -746,27 +635,22 @@ TEST_F(sys_call_test, process_scap_proc_get) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_NANOSLEEP_E) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_NANOSLEEP_E) { + if(callnum == 0) { scap_threadinfo scap_proc; auto rc = - scap_proc_get(param.m_inspector->get_scap_platform(), 0, &scap_proc, false); + scap_proc_get(param.m_inspector->get_scap_platform(), 0, &scap_proc, false); EXPECT_NE(SCAP_SUCCESS, rc); int64_t tid = e->get_tid(); rc = scap_proc_get(param.m_inspector->get_scap_platform(), tid, &scap_proc, false); EXPECT_EQ(SCAP_SUCCESS, rc); - } - else - { + } else { scap_threadinfo scap_proc; scap_fdinfo* fdi; scap_fdinfo* tfdi; @@ -776,14 +660,14 @@ TEST_F(sys_call_test, process_scap_proc_get) // // try with scan_sockets=true // - auto rc = - scap_proc_get(param.m_inspector->get_scap_platform(), tid, &scap_proc, false); + auto rc = scap_proc_get(param.m_inspector->get_scap_platform(), + tid, + &scap_proc, + false); EXPECT_EQ(SCAP_SUCCESS, rc); - HASH_ITER(hh, scap_proc.fdlist, fdi, tfdi) - { - if (fdi->type == SCAP_FD_IPV4_SOCK) - { + HASH_ITER(hh, scap_proc.fdlist, fdi, tfdi) { + if(fdi->type == SCAP_FD_IPV4_SOCK) { nsocks++; } } @@ -796,10 +680,8 @@ TEST_F(sys_call_test, process_scap_proc_get) rc = scap_proc_get(param.m_inspector->get_scap_platform(), tid, &scap_proc, true); EXPECT_EQ(SCAP_SUCCESS, rc); - HASH_ITER(hh, scap_proc.fdlist, fdi, tfdi) - { - if (fdi->type == SCAP_FD_IPV4_SOCK) - { + HASH_ITER(hh, scap_proc.fdlist, fdi, tfdi) { + if(fdi->type == SCAP_FD_IPV4_SOCK) { nsocks++; } } @@ -814,8 +696,7 @@ TEST_F(sys_call_test, process_scap_proc_get) ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); } -TEST_F(sys_call_test, procinfo_processchild_cpuload) -{ +TEST_F(sys_call_test, procinfo_processchild_cpuload) { int callnum = 0; int lastcpu = 0; int64_t ctid = -1; @@ -834,10 +715,8 @@ TEST_F(sys_call_test, procinfo_processchild_cpuload) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - for (uint32_t j = 0; j < 5; j++) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { + for(uint32_t j = 0; j < 5; j++) { sleep(1); } @@ -849,31 +728,26 @@ TEST_F(sys_call_test, procinfo_processchild_cpuload) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_PROCINFO_E) - { + if(type == PPME_PROCINFO_E) { sinsp_threadinfo* tinfo = e->get_thread_info(); - if (tinfo) - { - if (tinfo->m_tid == ctid) - { + if(tinfo) { + if(tinfo->m_tid == ctid) { uint64_t tcpu; const sinsp_evt_param* parinfo = e->get_param(0); - //tcpu = *(uint64_t*)parinfo->m_val; - memcpy(&tcpu,parinfo->m_val, sizeof(uint64_t)); + // tcpu = *(uint64_t*)parinfo->m_val; + memcpy(&tcpu, parinfo->m_val, sizeof(uint64_t)); uint64_t delta = tcpu - lastcpu; ct.m_read_cpu = true; - if (callnum != 0) - { + if(callnum != 0) { EXPECT_GT(delta, 0U); EXPECT_LT(delta, 110U); } @@ -889,14 +763,12 @@ TEST_F(sys_call_test, procinfo_processchild_cpuload) ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); } -TEST_F(sys_call_test, procinfo_two_processchilds_cpuload) -{ +TEST_F(sys_call_test, procinfo_two_processchilds_cpuload) { int callnum = 0; int lastcpu = 0; int lastcpu1 = 0; - loadthread ct - ; + loadthread ct; std::thread th(&loadthread::run, std::ref(ct)); loadthread ct1; @@ -914,10 +786,8 @@ TEST_F(sys_call_test, procinfo_two_processchilds_cpuload) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - for (uint32_t j = 0; j < 5; j++) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { + for(uint32_t j = 0; j < 5; j++) { sleep(1); } @@ -931,19 +801,15 @@ TEST_F(sys_call_test, procinfo_two_processchilds_cpuload) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_PROCINFO_E) - { + if(type == PPME_PROCINFO_E) { sinsp_threadinfo* tinfo = e->get_thread_info(); - if (tinfo) - { - if (tinfo->m_tid == ctid) - { + if(tinfo) { + if(tinfo->m_tid == ctid) { uint64_t tcpu; const sinsp_evt_param* parinfo = e->get_param(0); @@ -951,8 +817,7 @@ TEST_F(sys_call_test, procinfo_two_processchilds_cpuload) uint64_t delta = tcpu - lastcpu; - if (callnum > 2) - { + if(callnum > 2) { EXPECT_GT(delta, 0U); EXPECT_LT(delta, 110U); } @@ -960,9 +825,7 @@ TEST_F(sys_call_test, procinfo_two_processchilds_cpuload) lastcpu = tcpu; callnum++; - } - else if (tinfo->m_tid == ctid1) - { + } else if(tinfo->m_tid == ctid1) { uint64_t tcpu; const sinsp_evt_param* parinfo = e->get_param(0); @@ -970,8 +833,7 @@ TEST_F(sys_call_test, procinfo_two_processchilds_cpuload) uint64_t delta = tcpu - lastcpu1; - if (callnum > 2) - { + if(callnum > 2) { EXPECT_GT(delta, 0U); EXPECT_LT(delta, 110U); } diff --git a/test/libsinsp_e2e/resources/CMakeLists.txt b/test/libsinsp_e2e/resources/CMakeLists.txt index fccdf9eae2..2671f11275 100644 --- a/test/libsinsp_e2e/resources/CMakeLists.txt +++ b/test/libsinsp_e2e/resources/CMakeLists.txt @@ -4,15 +4,15 @@ add_compile_options(${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS}) add_link_options(${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS}) install( - DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - DESTINATION ${CMAKE_INSTALL_PREFIX}/test - COMPONENT tests + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + DESTINATION ${CMAKE_INSTALL_PREFIX}/test + COMPONENT tests ) execute_process( - COMMAND "uname" "-m" - OUTPUT_VARIABLE ARCH - OUTPUT_STRIP_TRAILING_WHITESPACE + COMMAND "uname" "-m" + OUTPUT_VARIABLE ARCH + OUTPUT_STRIP_TRAILING_WHITESPACE ) add_executable(forking_main_thread_exit forking_main_thread_exit.c) @@ -27,15 +27,14 @@ add_executable(chname chname.cpp) target_link_libraries(chname pthread) add_dependencies(libsinsp_e2e_tests chname) - if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") - add_executable(execve execve.c) - add_dependencies(libsinsp_e2e_tests execve) - - # Build 32-bit tests only for architectures where that is supported - if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64") - add_executable(execve32 execve.c) - set_target_properties(execve32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") - add_dependencies(libsinsp_e2e_tests execve32) - endif() + add_executable(execve execve.c) + add_dependencies(libsinsp_e2e_tests execve) + + # Build 32-bit tests only for architectures where that is supported + if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64") + add_executable(execve32 execve.c) + set_target_properties(execve32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") + add_dependencies(libsinsp_e2e_tests execve32) + endif() endif("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") diff --git a/test/libsinsp_e2e/resources/chname.cpp b/test/libsinsp_e2e/resources/chname.cpp index 34e4ff526f..37f9357e39 100644 --- a/test/libsinsp_e2e/resources/chname.cpp +++ b/test/libsinsp_e2e/resources/chname.cpp @@ -29,31 +29,25 @@ limitations under the License. #include #include -void run() -{ - while (true) - { +void run() { + while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } -void changer(char** argv) -{ +void changer(char** argv) { char pname[] = "sysdig"; memcpy((void*)argv[0], pname, sizeof(pname)); - while (true) - { + while(true) { std::this_thread::sleep_for(std::chrono::seconds(2)); } } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { char pname[] = "savonarola"; prctl(PR_SET_NAME, (unsigned long)&pname, 0, 0, 0); std::vector> threads; - for (int j = 0; j < 20; ++j) - { + for(int j = 0; j < 20; ++j) { threads.push_back(std::make_shared(run)); } diff --git a/test/libsinsp_e2e/resources/docker/health_dockerfiles/CMakeLists.txt b/test/libsinsp_e2e/resources/docker/health_dockerfiles/CMakeLists.txt index 0ea56df7da..d1abd153bb 100644 --- a/test/libsinsp_e2e/resources/docker/health_dockerfiles/CMakeLists.txt +++ b/test/libsinsp_e2e/resources/docker/health_dockerfiles/CMakeLists.txt @@ -1,17 +1,17 @@ foreach( - dockerfile - Dockerfile.healthcheck - Dockerfile.healthcheck_shell - Dockerfile.healthcheck_cmd_overlap - Dockerfile.healthcheck_liveness - Dockerfile.healthcheck_readiness - Dockerfile.no_healthcheck - Dockerfile.none_healthcheck + dockerfile + Dockerfile.healthcheck + Dockerfile.healthcheck_shell + Dockerfile.healthcheck_cmd_overlap + Dockerfile.healthcheck_liveness + Dockerfile.healthcheck_readiness + Dockerfile.no_healthcheck + Dockerfile.none_healthcheck ) - configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/${dockerfile} ${CMAKE_CURRENT_BINARY_DIR}/${dockerfile} - COPYONLY - ) + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${dockerfile} ${CMAKE_CURRENT_BINARY_DIR}/${dockerfile} + COPYONLY + ) endforeach(dockerfile) diff --git a/test/libsinsp_e2e/resources/execve.c b/test/libsinsp_e2e/resources/execve.c index f7fcd4878d..c0a2016364 100644 --- a/test/libsinsp_e2e/resources/execve.c +++ b/test/libsinsp_e2e/resources/execve.c @@ -21,18 +21,13 @@ limitations under the License. #include #include -int main(int argc, char** argv) -{ - if (argc > 1) - { - if (execv(argv[1], argv + 1) != 0) - { +int main(int argc, char** argv) { + if(argc > 1) { + if(execv(argv[1], argv + 1) != 0) { fprintf(stderr, "Can't exec %s: %s\n", argv[1], strerror(errno)); } return 1; - } - else - { + } else { return 0; } } diff --git a/test/libsinsp_e2e/resources/forking_main_thread_exit.c b/test/libsinsp_e2e/resources/forking_main_thread_exit.c index 2193844b5f..3d6e3d816c 100644 --- a/test/libsinsp_e2e/resources/forking_main_thread_exit.c +++ b/test/libsinsp_e2e/resources/forking_main_thread_exit.c @@ -26,12 +26,10 @@ limitations under the License. static int fd; -void* callback(void* arg) -{ +void* callback(void* arg) { char buf[1024]; sleep(1); - if (read(fd, buf, sizeof(buf)) < 0) - { + if(read(fd, buf, sizeof(buf)) < 0) { perror("read"); } sleep(10); @@ -42,13 +40,11 @@ void* callback(void* arg) // This is outside the test files because gtest doesn't like // pthread_exit() since it triggers an exception to unwind the stack // -int main() -{ +int main() { pthread_t thread; fd = open("/etc/passwd", O_RDONLY); - if (fd == -1) - { + if(fd == -1) { perror("open"); } diff --git a/test/libsinsp_e2e/resources/forking_nested.c b/test/libsinsp_e2e/resources/forking_nested.c index 9e18320095..1f938c3317 100644 --- a/test/libsinsp_e2e/resources/forking_nested.c +++ b/test/libsinsp_e2e/resources/forking_nested.c @@ -24,20 +24,17 @@ limitations under the License. #include #include -void* callback(void* arg) -{ +void* callback(void* arg) { return NULL; } -int main() -{ +int main() { int ctid; int cctid, cctid1, cctid2, cctid3, cctid4, cctid5; ctid = fork(); - if (ctid == 0) - { + if(ctid == 0) { // // CHILD PROCESS // @@ -48,8 +45,7 @@ int main() usleep(100000); cctid = fork(); - if (cctid == 0) - { + if(cctid == 0) { // // CHILD PROCESS // @@ -60,8 +56,7 @@ int main() usleep(100000); cctid1 = fork(); - if (cctid1 == 0) - { + if(cctid1 == 0) { // // CHILD PROCESS // @@ -72,8 +67,7 @@ int main() usleep(100000); cctid2 = fork(); - if (cctid2 == 0) - { + if(cctid2 == 0) { // // CHILD PROCESS // @@ -84,8 +78,7 @@ int main() usleep(100000); cctid3 = fork(); - if (cctid3 == 0) - { + if(cctid3 == 0) { printf("*5\n"); // // CHILD PROCESS @@ -96,8 +89,7 @@ int main() usleep(100000); cctid4 = fork(); - if (cctid4 == 0) - { + if(cctid4 == 0) { printf("*6\n"); // // CHILD PROCESS @@ -108,43 +100,28 @@ int main() usleep(100000); cctid5 = fork(); - if (cctid5 == 0) - { + if(cctid5 == 0) { printf("*7\n"); return 0; - } - else - { + } else { return 0; } - } - else - { + } else { return 0; } - } - else - { + } else { return 0; } - } - else - { + } else { return 0; } - } - else - { + } else { return 0; } - } - else - { + } else { return 0; } - } - else - { + } else { return 0; } } diff --git a/test/libsinsp_e2e/scap_file_reader.h b/test/libsinsp_e2e/scap_file_reader.h index 94bbcd9cf2..6d883344fa 100644 --- a/test/libsinsp_e2e/scap_file_reader.h +++ b/test/libsinsp_e2e/scap_file_reader.h @@ -24,15 +24,12 @@ limitations under the License. #include #include -class scap_file_reader -{ +class scap_file_reader { public: virtual ~scap_file_reader() { m_inspector = nullptr; } - virtual std::shared_ptr setup_read_file() - { - if (!m_inspector) - { + virtual std::shared_ptr setup_read_file() { + if(!m_inspector) { m_inspector = std::make_shared(); m_inspector->set_hostname_and_port_resolution_mode(true); } @@ -41,32 +38,23 @@ class scap_file_reader virtual void run_inspector(const char* filename, const std::string filter, - std::function evtcb) - { + std::function evtcb) { m_inspector->open_savefile(filename); m_inspector->set_filter(filter.c_str()); - while (true) - { + while(true) { int32_t res; sinsp_evt* evt; res = m_inspector->next(&evt); - if (res == SCAP_TIMEOUT) - { + if(res == SCAP_TIMEOUT) { continue; - } - else if (res == SCAP_FILTERED_EVENT) - { + } else if(res == SCAP_FILTERED_EVENT) { continue; - } - else if (res == SCAP_EOF) - { + } else if(res == SCAP_EOF) { break; - } - else if (res != SCAP_SUCCESS) - { + } else if(res != SCAP_SUCCESS) { break; } @@ -78,8 +66,7 @@ class scap_file_reader virtual void read_file_filtered(const char* filename, const std::string filter, - std::function evtcb) - { + std::function evtcb) { setup_read_file(); run_inspector(filename, filter, evtcb); } diff --git a/test/libsinsp_e2e/subprocess.cpp b/test/libsinsp_e2e/subprocess.cpp index 4912f86827..c40be2745f 100644 --- a/test/libsinsp_e2e/subprocess.cpp +++ b/test/libsinsp_e2e/subprocess.cpp @@ -30,136 +30,119 @@ limitations under the License. #include #include -subprocess::subprocess(std::string command, std::vector arguments, - bool start_now, int retry_attempts): - m_pid(-1), - m_retry_attemps(retry_attempts), - m_command(command), - m_args(arguments) -{ - if(start_now) - { - start(); - } +subprocess::subprocess(std::string command, + std::vector arguments, + bool start_now, + int retry_attempts): + m_pid(-1), + m_retry_attemps(retry_attempts), + m_command(command), + m_args(arguments) { + if(start_now) { + start(); + } } -subprocess::~subprocess() -{ - delete m_in_filebuf; - delete m_out_filebuf; - delete m_in_stream; - delete m_out_stream; +subprocess::~subprocess() { + delete m_in_filebuf; + delete m_out_filebuf; + delete m_in_stream; + delete m_out_stream; } -void subprocess::wait_for_start() -{ - fd_set read_set; - FD_ZERO(&read_set); - FD_SET(m_out_pipe[0], &read_set); - - struct timeval timeout; - timeout.tv_sec = 10; - timeout.tv_usec = 0; - - int result = select(m_out_pipe[0] + 1, &read_set, nullptr, nullptr, &timeout); - int attempt = 0; - - while(attempt < m_retry_attemps) - { - switch(result) - { - case -1: - perror("select"); - break; - case 0: - std::cerr << "Timeout waiting for process to start. Retry n." - << (attempt + 1) << "/" << m_retry_attemps << std::endl; - break; - default: - if (!FD_ISSET(m_out_pipe[0], &read_set)) { - std::cerr << "Unexpected error during select." << std::endl; - } - break; - } - attempt++; - } - +void subprocess::wait_for_start() { + fd_set read_set; + FD_ZERO(&read_set); + FD_SET(m_out_pipe[0], &read_set); + + struct timeval timeout; + timeout.tv_sec = 10; + timeout.tv_usec = 0; + + int result = select(m_out_pipe[0] + 1, &read_set, nullptr, nullptr, &timeout); + int attempt = 0; + + while(attempt < m_retry_attemps) { + switch(result) { + case -1: + perror("select"); + break; + case 0: + std::cerr << "Timeout waiting for process to start. Retry n." << (attempt + 1) << "/" + << m_retry_attemps << std::endl; + break; + default: + if(!FD_ISSET(m_out_pipe[0], &read_set)) { + std::cerr << "Unexpected error during select." << std::endl; + } + break; + } + attempt++; + } } -pid_t subprocess::get_pid() -{ - return m_pid; +pid_t subprocess::get_pid() { + return m_pid; } -std::ostream& subprocess::in() -{ - return *m_in_stream; +std::ostream& subprocess::in() { + return *m_in_stream; } -std::string subprocess::out() -{ - std::string buf; - std::getline(*m_out_stream, buf); - return buf; +std::string subprocess::out() { + std::string buf; + std::getline(*m_out_stream, buf); + return buf; } -int subprocess::wait() -{ - int status; - waitpid(get_pid(), &status, 0); - return status; +int subprocess::wait() { + int status; + waitpid(get_pid(), &status, 0); + return status; } -void subprocess::start() -{ - if (pipe(m_in_pipe) == -1 || pipe(m_out_pipe) == -1) - { - throw std::system_error(errno, std::system_category()); - } - - pid_t child_pid = fork(); - - if (child_pid == -1) - { - std::cerr << "Failed to fork." << std::endl; - } - else if (child_pid == 0) - { - // child process - dup2(m_in_pipe[0], STDIN_FILENO); - dup2(m_out_pipe[1], STDOUT_FILENO); - - close(m_in_pipe[0]); - close(m_out_pipe[1]); - if(m_out_pipe[0] != -1) - close(m_out_pipe[0]); - - std::vector args; - args.push_back(const_cast(m_command.c_str())); - for (const auto& arg : m_args) { - args.push_back(const_cast(arg.c_str())); - } - args.push_back(nullptr); - - execvp(m_command.c_str(), args.data()); - std::cerr << "Failed to execute the process." << std::endl; - exit(EXIT_FAILURE); - } - else // Parent process - { - close(m_in_pipe[0]); - close(m_out_pipe[1]); - - m_pid = child_pid; - - m_in_filebuf = new __gnu_cxx::stdio_filebuf(m_in_pipe[1], std::ios_base::out, 1); - m_in_stream = new std::ostream(m_in_filebuf); - - if (m_out_pipe[0] != -1) - { - m_out_filebuf = new __gnu_cxx::stdio_filebuf(m_out_pipe[0], std::ios_base::in, 1); - m_out_stream = new std::istream(m_out_filebuf); - } - - } +void subprocess::start() { + if(pipe(m_in_pipe) == -1 || pipe(m_out_pipe) == -1) { + throw std::system_error(errno, std::system_category()); + } + + pid_t child_pid = fork(); + + if(child_pid == -1) { + std::cerr << "Failed to fork." << std::endl; + } else if(child_pid == 0) { + // child process + dup2(m_in_pipe[0], STDIN_FILENO); + dup2(m_out_pipe[1], STDOUT_FILENO); + + close(m_in_pipe[0]); + close(m_out_pipe[1]); + if(m_out_pipe[0] != -1) + close(m_out_pipe[0]); + + std::vector args; + args.push_back(const_cast(m_command.c_str())); + for(const auto& arg : m_args) { + args.push_back(const_cast(arg.c_str())); + } + args.push_back(nullptr); + + execvp(m_command.c_str(), args.data()); + std::cerr << "Failed to execute the process." << std::endl; + exit(EXIT_FAILURE); + } else // Parent process + { + close(m_in_pipe[0]); + close(m_out_pipe[1]); + + m_pid = child_pid; + + m_in_filebuf = new __gnu_cxx::stdio_filebuf(m_in_pipe[1], std::ios_base::out, 1); + m_in_stream = new std::ostream(m_in_filebuf); + + if(m_out_pipe[0] != -1) { + m_out_filebuf = new __gnu_cxx::stdio_filebuf(m_out_pipe[0], std::ios_base::in, 1); + m_out_stream = new std::istream(m_out_filebuf); + } + } } diff --git a/test/libsinsp_e2e/subprocess.h b/test/libsinsp_e2e/subprocess.h index ef9fe01ca1..27570748e0 100644 --- a/test/libsinsp_e2e/subprocess.h +++ b/test/libsinsp_e2e/subprocess.h @@ -30,32 +30,34 @@ limitations under the License. #include class subprocess { - public: - subprocess(std::string command, std::vector arguments, - bool start_now=true, int retry_attempts=3); - ~subprocess(); +public: + subprocess(std::string command, + std::vector arguments, + bool start_now = true, + int retry_attempts = 3); + ~subprocess(); - void wait_for_start(); - int wait(); + void wait_for_start(); + int wait(); - pid_t get_pid(); + pid_t get_pid(); - std::ostream& in(); - std::string out(); + std::ostream& in(); + std::string out(); - void start(); + void start(); - private: - std::string m_command; - std::vector m_args; - pid_t m_pid; - int m_in_pipe[2]; - int m_out_pipe[2]; - int m_retry_attemps; +private: + std::string m_command; + std::vector m_args; + pid_t m_pid; + int m_in_pipe[2]; + int m_out_pipe[2]; + int m_retry_attemps; - std::ostream* m_in_stream; - std::istream* m_out_stream; + std::ostream* m_in_stream; + std::istream* m_out_stream; - __gnu_cxx::stdio_filebuf* m_in_filebuf; - __gnu_cxx::stdio_filebuf* m_out_filebuf; + __gnu_cxx::stdio_filebuf* m_in_filebuf; + __gnu_cxx::stdio_filebuf* m_out_filebuf; }; diff --git a/test/libsinsp_e2e/suppress_events.cpp b/test/libsinsp_e2e/suppress_events.cpp index c9af42179c..0e8c945b0c 100644 --- a/test/libsinsp_e2e/suppress_events.cpp +++ b/test/libsinsp_e2e/suppress_events.cpp @@ -13,15 +13,13 @@ extern sinsp_evttables g_infotables; -struct test_helper_args -{ +struct test_helper_args { bool start_before; bool suppress_before; bool spawn_with_bash; }; -static void test_helper_quotactl(test_helper_args& hargs) -{ +static void test_helper_quotactl(test_helper_args& hargs) { // We start the test_helper process before starting the // capture, so the initial proc scan will see the pid. Once // the capture has started we let the test_helper process @@ -30,8 +28,7 @@ static void test_helper_quotactl(test_helper_args& hargs) bool test_helper_done = false; std::string bin = LIBSINSP_TEST_PATH "/test_helper"; - if (hargs.spawn_with_bash) - { + if(hargs.spawn_with_bash) { bin = LIBSINSP_TEST_PATH "/test_helper.sh"; } @@ -41,19 +38,16 @@ static void test_helper_quotactl(test_helper_args& hargs) // Access/modify inspector before opening // - before_open_t before_open = [&](sinsp* inspector) - { + before_open_t before_open = [&](sinsp* inspector) { inspector->clear_suppress_events_comm(); inspector->clear_suppress_events_tid(); - if (hargs.suppress_before) - { + if(hargs.suppress_before) { inspector->suppress_events_comm( - std::string((hargs.spawn_with_bash ? "test_helper.sh" : "test_helper"))); + std::string((hargs.spawn_with_bash ? "test_helper.sh" : "test_helper"))); } - if (hargs.start_before) - { + if(hargs.start_before) { test_proc.start(); } }; @@ -68,17 +62,14 @@ static void test_helper_quotactl(test_helper_args& hargs) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - if (!hargs.suppress_before) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { + if(!hargs.suppress_before) { std::scoped_lock inspector_handle_lock(inspector_handle); inspector_handle->suppress_events_comm( - std::string((hargs.spawn_with_bash ? "test_helper.sh" : "test_helper"))); + std::string((hargs.spawn_with_bash ? "test_helper.sh" : "test_helper"))); } - if (!hargs.start_before) - { + if(!hargs.start_before) { test_proc.start(); } @@ -94,25 +85,19 @@ static void test_helper_quotactl(test_helper_args& hargs) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* evt = param.m_evt; // make sure we don't add suppresed threads during initial /proc scan - if (param.m_inspector->check_suppressed(evt->get_tid())) - { + if(param.m_inspector->check_suppressed(evt->get_tid())) { ASSERT_EQ(nullptr, param.m_inspector->get_thread_ref(evt->get_tid(), false, true)); } - switch (evt->get_type()) - { + switch(evt->get_type()) { case PPME_SYSCALL_QUOTACTL_X: - if (evt->get_tid() != pid) - { + if(evt->get_tid() != pid) { FAIL() << "Should not have observed any quotactl event"; - } - else - { + } else { test_helper_done = true; } break; @@ -124,8 +109,7 @@ static void test_helper_quotactl(test_helper_args& hargs) capture_continue_t should_continue = [&]() { return (!test_helper_done); }; - before_close_t before_close = [](sinsp* inspector) - { + before_close_t before_close = [](sinsp* inspector) { scap_stats st; inspector->get_capture_stats(&st); @@ -139,21 +123,20 @@ static void test_helper_quotactl(test_helper_args& hargs) ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, - callback, - filter, - before_open, - before_close, - should_continue, - 131072, - 6000, - 6000, - SINSP_MODE_LIVE, - 1000); + callback, + filter, + before_open, + before_close, + should_continue, + 131072, + 6000, + 6000, + SINSP_MODE_LIVE, + 1000); }); } -TEST_F(sys_call_test, suppress_new_process) -{ +TEST_F(sys_call_test, suppress_new_process) { test_helper_args hargs; hargs.start_before = false; hargs.suppress_before = true; @@ -162,8 +145,7 @@ TEST_F(sys_call_test, suppress_new_process) test_helper_quotactl(hargs); } -TEST_F(sys_call_test, suppress_add_new_value_while_running) -{ +TEST_F(sys_call_test, suppress_add_new_value_while_running) { test_helper_args hargs; hargs.start_before = false; hargs.suppress_before = false; @@ -172,8 +154,7 @@ TEST_F(sys_call_test, suppress_add_new_value_while_running) test_helper_quotactl(hargs); } -TEST_F(sys_call_test, suppress_grandchildren) -{ +TEST_F(sys_call_test, suppress_grandchildren) { test_helper_args hargs; hargs.start_before = false; hargs.suppress_before = true; @@ -182,8 +163,7 @@ TEST_F(sys_call_test, suppress_grandchildren) test_helper_quotactl(hargs); } -class suppress_types : public sys_call_test -{ +class suppress_types : public sys_call_test { protected: static bool is_target_call(uint16_t type); void do_syscalls(); @@ -195,10 +175,8 @@ class suppress_types : public sys_call_test int m_expected_calls; }; -bool suppress_types::is_target_call(uint16_t type) -{ - switch (type) - { +bool suppress_types::is_target_call(uint16_t type) { + switch(type) { case PPME_SYSCALL_FCNTL_E: case PPME_SYSCALL_FCNTL_X: case PPME_SYSCALL_GETRLIMIT_E: @@ -209,8 +187,7 @@ bool suppress_types::is_target_call(uint16_t type) return false; } -void suppress_types::do_syscalls() -{ +void suppress_types::do_syscalls() { struct rlimit limits; // getrlimit called directly because libc likes prlimit() syscall(SYS_getrlimit, RLIMIT_AS, &limits); @@ -218,21 +195,16 @@ void suppress_types::do_syscalls() // enter+exit for each syscall m_expected_calls = 4; - for (const auto ii : m_suppressed_evttypes) - { - if (is_target_call(ii)) - { + for(const auto ii : m_suppressed_evttypes) { + if(is_target_call(ii)) { m_expected_calls--; } } } -bool suppress_types::is_suppressed_evttype(uint16_t type) const -{ - for (const auto ii : m_suppressed_evttypes) - { - if (type == ii) - { +bool suppress_types::is_suppressed_evttype(uint16_t type) const { + for(const auto ii : m_suppressed_evttypes) { + if(type == ii) { return true; } } @@ -241,26 +213,21 @@ bool suppress_types::is_suppressed_evttype(uint16_t type) const } void parse_syscall_names(const std::vector& supp_strs, - std::vector& supp_ids) -{ + std::vector& supp_ids) { supp_ids.clear(); - for (auto sc = 0; sc < PPM_SC_MAX; sc++) - { + for(auto sc = 0; sc < PPM_SC_MAX; sc++) { const char* name = scap_get_ppm_sc_name(static_cast(sc)); auto iter = std::find(supp_strs.begin(), supp_strs.end(), std::string(name)); - if (iter != supp_strs.end()) - { + if(iter != supp_strs.end()) { supp_ids.push_back(static_cast(sc)); } } } -const char* event_name_by_id(uint16_t id) -{ - if (id >= PPM_EVENT_MAX) - { +const char* event_name_by_id(uint16_t id) { + if(id >= PPM_EVENT_MAX) { ASSERT(false); return "NA"; } @@ -268,20 +235,16 @@ const char* event_name_by_id(uint16_t id) } void parse_suppressed_types(const std::vector& supp_strs, - std::vector* supp_ids) -{ - for (auto ii = 0; ii < PPM_EVENT_MAX; ii++) - { + std::vector* supp_ids) { + for(auto ii = 0; ii < PPM_EVENT_MAX; ii++) { auto iter = std::find(supp_strs.begin(), supp_strs.end(), event_name_by_id(ii)); - if (iter != supp_strs.end()) - { + if(iter != supp_strs.end()) { supp_ids->push_back(static_cast(ii)); } } } -void suppress_types::run_test(std::vector supp_syscalls) -{ +void suppress_types::run_test(std::vector supp_syscalls) { int callnum = 0; parse_syscall_names(supp_syscalls, m_suppressed_syscalls); @@ -290,20 +253,15 @@ void suppress_types::run_test(std::vector supp_syscalls) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - for (auto sc : m_suppressed_syscalls) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { + for(auto sc : m_suppressed_syscalls) { bool expect_exception = (sc >= PPM_SC_MAX); bool caught_exception = false; - try - { + try { std::scoped_lock inspector_handle_lock(inspector_handle); inspector_handle->mark_ppm_sc_of_interest(sc, false); - } - catch (sinsp_exception& e) - { + } catch(sinsp_exception& e) { caught_exception = true; } @@ -312,18 +270,14 @@ void suppress_types::run_test(std::vector supp_syscalls) do_syscalls(); - for (auto sc : m_suppressed_syscalls) - { + for(auto sc : m_suppressed_syscalls) { bool expect_exception = (sc >= PPM_SC_MAX); bool caught_exception = false; - try - { + try { std::scoped_lock inspector_handle_lock(inspector_handle); inspector_handle->mark_ppm_sc_of_interest(sc, true); - } - catch (sinsp_exception& e) - { + } catch(sinsp_exception& e) { caught_exception = true; } @@ -334,12 +288,10 @@ void suppress_types::run_test(std::vector supp_syscalls) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { auto type = param.m_evt->get_type(); EXPECT_FALSE(is_suppressed_evttype(type)); - if (is_target_call(type)) - { + if(is_target_call(type)) { callnum++; } }; @@ -348,30 +300,25 @@ void suppress_types::run_test(std::vector supp_syscalls) EXPECT_EQ(m_expected_calls, callnum); } -TEST_F(suppress_types, block_getrlimit) -{ +TEST_F(suppress_types, block_getrlimit) { // PPME_SYSCALL_GETRLIMIT_(E|X) ASSERT_NO_FATAL_FAILURE(run_test({"getrlimit"})); } -TEST_F(suppress_types, block_fcntl) -{ +TEST_F(suppress_types, block_fcntl) { // PPME_SYSCALL_FCNTL_(E|X) ASSERT_NO_FATAL_FAILURE(run_test({"fcntl"})); } -TEST_F(suppress_types, block_getrlimit_and_fcntl) -{ +TEST_F(suppress_types, block_getrlimit_and_fcntl) { // PPME_SYSCALL_GETRLIMIT_(E|X) && PPME_SYSCALL_FCNTL_(E|X) ASSERT_NO_FATAL_FAILURE(run_test({"getrlimit", "fcntl"})); } -TEST_F(suppress_types, block_none) -{ +TEST_F(suppress_types, block_none) { ASSERT_NO_FATAL_FAILURE(run_test({})); } -TEST_F(suppress_types, block_nonexistent_call) -{ +TEST_F(suppress_types, block_nonexistent_call) { ASSERT_NO_FATAL_FAILURE(run_test({"notarealname"})); } diff --git a/test/libsinsp_e2e/sys_call_test.cpp b/test/libsinsp_e2e/sys_call_test.cpp index 4f724ceb62..f2361311f5 100644 --- a/test/libsinsp_e2e/sys_call_test.cpp +++ b/test/libsinsp_e2e/sys_call_test.cpp @@ -56,33 +56,27 @@ limitations under the License. using namespace std; -uint32_t get_server_address() -{ +uint32_t get_server_address() { struct ifaddrs* interfaceArray = NULL; struct ifaddrs* tempIfAddr = NULL; int rc = 0; uint32_t address = 0; rc = getifaddrs(&interfaceArray); - if (rc != 0) - { + if(rc != 0) { return -1; } - for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) - { - if (tempIfAddr->ifa_addr == NULL) - { + for(tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) { + if(tempIfAddr->ifa_addr == NULL) { // "eql" interface like on EC2 continue; } - if (tempIfAddr->ifa_addr->sa_family != AF_INET) - { + if(tempIfAddr->ifa_addr->sa_family != AF_INET) { continue; } - if (0 == strcmp("lo", tempIfAddr->ifa_name)) - { + if(0 == strcmp("lo", tempIfAddr->ifa_name)) { continue; } address = *(uint32_t*)&((struct sockaddr_in*)tempIfAddr->ifa_addr)->sin_addr; @@ -93,18 +87,15 @@ uint32_t get_server_address() return address; } -TEST_F(sys_call_test, stat) -{ +TEST_F(sys_call_test, stat) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { std::string evt_name(evt->get_name()); return evt_name.find("stat") != std::string::npos && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { struct stat sb; stat("/tmp", &sb); }; @@ -114,28 +105,25 @@ TEST_F(sys_call_test, stat) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, open_close) -{ +TEST_F(sys_call_test, open_close) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return (0 == strcmp(evt->get_name(), "open") || 0 == strcmp(evt->get_name(), "openat") || 0 == strcmp(evt->get_name(), "close")) && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { int fd = open("/tmp", O_RDONLY); close(fd); }; - captured_event_callback_t callback = [&](const callback_param& param) - { - if((0 == strcmp(param.m_evt->get_name(), "open") || 0 == strcmp(param.m_evt->get_name(), "openat") || - 0 == strcmp(param.m_evt->get_name(), "close")) && "/tmp" == param.m_evt->get_param_value_str("fd")) - { + captured_event_callback_t callback = [&](const callback_param& param) { + if((0 == strcmp(param.m_evt->get_name(), "open") || + 0 == strcmp(param.m_evt->get_name(), "openat") || + 0 == strcmp(param.m_evt->get_name(), "close")) && + "/tmp" == param.m_evt->get_param_value_str("fd")) { callnum++; } }; @@ -144,56 +132,47 @@ TEST_F(sys_call_test, open_close) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, open_close_dropping) -{ +TEST_F(sys_call_test, open_close_dropping) { int callnum = 0; - before_open_t setup = [&](sinsp* inspector) - { - inspector->start_dropping_mode(1); - }; + before_open_t setup = [&](sinsp* inspector) { inspector->start_dropping_mode(1); }; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return (0 == strcmp(evt->get_name(), "open") || 0 == strcmp(evt->get_name(), "openat") || 0 == strcmp(evt->get_name(), "close")) && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { int fd = open("/tmp", O_RDONLY); close(fd); }; - captured_event_callback_t callback = [&](const callback_param& param) - { - if((0 == strcmp(param.m_evt->get_name(), "open") || 0 == strcmp(param.m_evt->get_name(), "openat") || - 0 == strcmp(param.m_evt->get_name(), "close")) && "/tmp" == param.m_evt->get_param_value_str("fd")) - { + captured_event_callback_t callback = [&](const callback_param& param) { + if((0 == strcmp(param.m_evt->get_name(), "open") || + 0 == strcmp(param.m_evt->get_name(), "openat") || + 0 == strcmp(param.m_evt->get_name(), "close")) && + "/tmp" == param.m_evt->get_param_value_str("fd")) { callnum++; } }; - before_close_t cleanup = [&](sinsp* inspector) - { - inspector->stop_dropping_mode(); - }; + before_close_t cleanup = [&](sinsp* inspector) { inspector->stop_dropping_mode(); }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter, setup, cleanup); }); EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, fcntl_getfd) -{ +TEST_F(sys_call_test, fcntl_getfd) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return 0 == strcmp(evt->get_name(), "fcntl") && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) { fcntl(0, F_GETFL); }; + run_callback_t test = [](concurrent_object_handle inspector_handle) { + fcntl(0, F_GETFL); + }; captured_event_callback_t callback = [&](const callback_param& param) { callnum++; }; @@ -201,45 +180,36 @@ TEST_F(sys_call_test, fcntl_getfd) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, fcntl_getfd_dropping) -{ +TEST_F(sys_call_test, fcntl_getfd_dropping) { int callnum = 0; - before_open_t setup = [&](sinsp* inspector) - { - inspector->start_dropping_mode(1); - }; + before_open_t setup = [&](sinsp* inspector) { inspector->start_dropping_mode(1); }; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return 0 == strcmp(evt->get_name(), "fcntl") && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { fcntl(0, F_GETFL); }; captured_event_callback_t callback = [&](const callback_param& param) { callnum++; }; - before_close_t cleanup = [&](sinsp* inspector) - { - inspector->stop_dropping_mode(); - }; + before_close_t cleanup = [&](sinsp* inspector) { inspector->stop_dropping_mode(); }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter, setup, cleanup); }); EXPECT_EQ(0, callnum); } -TEST_F(sys_call_test, bind_error) -{ +TEST_F(sys_call_test, bind_error) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return 0 == strcmp(evt->get_name(), "bind") && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) { bind(0, NULL, 0); }; + run_callback_t test = [](concurrent_object_handle inspector_handle) { + bind(0, NULL, 0); + }; captured_event_callback_t callback = [&](const callback_param& param) { callnum++; }; @@ -247,60 +217,43 @@ TEST_F(sys_call_test, bind_error) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, bind_error_dropping) -{ +TEST_F(sys_call_test, bind_error_dropping) { int callnum = 0; - before_open_t setup = [&](sinsp* inspector) - { - inspector->start_dropping_mode(1); - }; + before_open_t setup = [&](sinsp* inspector) { inspector->start_dropping_mode(1); }; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return 0 == strcmp(evt->get_name(), "bind") && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { bind(0, NULL, 0); }; captured_event_callback_t callback = [&](const callback_param& param) { callnum++; }; - before_close_t cleanup = [&](sinsp* inspector) - { - inspector->stop_dropping_mode(); - }; + before_close_t cleanup = [&](sinsp* inspector) { inspector->stop_dropping_mode(); }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter, setup, cleanup); }); EXPECT_EQ(1, callnum); } -TEST_F(sys_call_test, close_badfd) -{ +TEST_F(sys_call_test, close_badfd) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return 0 == strcmp(evt->get_name(), "close") && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { close(-1); close(INT_MAX); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { int fd = param.m_evt->get_param(0)->as(); - if(param.m_evt->get_direction() == SCAP_ED_IN && - (fd == -1 || fd == INT_MAX)) - { + if(param.m_evt->get_direction() == SCAP_ED_IN && (fd == -1 || fd == INT_MAX)) { callnum++; - } - else if(param.m_evt->get_direction() == SCAP_ED_OUT && fd == -EBADF) - { + } else if(param.m_evt->get_direction() == SCAP_ED_OUT && fd == -EBADF) { callnum++; } }; @@ -309,44 +262,30 @@ TEST_F(sys_call_test, close_badfd) EXPECT_EQ(4, callnum); } -TEST_F(sys_call_test, close_badfd_dropping) -{ +TEST_F(sys_call_test, close_badfd_dropping) { int callnum = 0; - before_open_t setup = [&](sinsp* inspector) - { - inspector->start_dropping_mode(1); - }; + before_open_t setup = [&](sinsp* inspector) { inspector->start_dropping_mode(1); }; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return 0 == strcmp(evt->get_name(), "close") && m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { close(-1); close(INT_MAX); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { int fd = param.m_evt->get_param(0)->as(); - if(param.m_evt->get_direction() == SCAP_ED_IN && - (fd == -1 || fd == INT_MAX)) - { + if(param.m_evt->get_direction() == SCAP_ED_IN && (fd == -1 || fd == INT_MAX)) { callnum++; - } - else if(param.m_evt->get_direction() == SCAP_ED_OUT && fd == -EBADF) - { + } else if(param.m_evt->get_direction() == SCAP_ED_OUT && fd == -EBADF) { callnum++; } }; - before_close_t cleanup = [&](sinsp* inspector) - { - inspector->stop_dropping_mode(); - }; + before_close_t cleanup = [&](sinsp* inspector) { inspector->stop_dropping_mode(); }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter, setup, cleanup); }); EXPECT_EQ(0, callnum); @@ -354,23 +293,19 @@ TEST_F(sys_call_test, close_badfd_dropping) // The poll syscall is not defined on arm64. #if !defined(__aarch64__) -TEST_F(sys_call_test, poll_timeout) -{ +TEST_F(sys_call_test, poll_timeout) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { uint16_t type = evt->get_type(); auto ti = evt->get_thread_info(false); - return (type == PPME_SYSCALL_POLL_E || - type == PPME_SYSCALL_POLL_X) && - ti->m_comm == "test_helper"; + return (type == PPME_SYSCALL_POLL_E || type == PPME_SYSCALL_POLL_X) && + ti->m_comm == "test_helper"; }; std::string my_pipe[2]; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { subprocess handle(LIBSINSP_TEST_PATH "/test_helper", {"poll_timeout"}); std::stringstream ss; ss << handle.out(); @@ -383,51 +318,43 @@ TEST_F(sys_call_test, poll_timeout) ss.str(" "); handle.wait(); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_POLL_E) - { + if(type == PPME_SYSCALL_POLL_E) { // // stdin and stdout can be a file or a fifo depending // on how the tests are invoked // std::string fds = e->get_param_value_str("fds"); - std::string expected_fds = my_pipe[0] + ":p1 " + - my_pipe[1] + ":p4"; - EXPECT_EQ(expected_fds, fds) - << "Value of fds is not one of expected values: " << fds; + std::string expected_fds = my_pipe[0] + ":p1 " + my_pipe[1] + ":p4"; + EXPECT_EQ(expected_fds, fds) << "Value of fds is not one of expected values: " << fds; EXPECT_EQ("20", e->get_param_value_str("timeout")); callnum++; - } - else if (type == PPME_SYSCALL_POLL_X) - { + } else if(type == PPME_SYSCALL_POLL_X) { std::string fds = e->get_param_value_str("fds"); - std::string expected_fds = my_pipe[0] + ":p0 " + - my_pipe[1] + ":p4"; + std::string expected_fds = my_pipe[0] + ":p0 " + my_pipe[1] + ":p4"; int64_t res = std::stol(e->get_param_value_str("res")); EXPECT_GT(res, 0); EXPECT_LE(res, 2); - switch (res) - { - case 1: - EXPECT_EQ(expected_fds, fds) - << "Value of fds is not one of expected values: " << fds; - ; - break; - case 2: - // - // On EC2 called from jenkins stdin returns POLLHUP - // - EXPECT_EQ(expected_fds, fds) - << "Value of fds is not one of expected values: " << fds; - break; - default: - FAIL(); + switch(res) { + case 1: + EXPECT_EQ(expected_fds, fds) + << "Value of fds is not one of expected values: " << fds; + ; + break; + case 2: + // + // On EC2 called from jenkins stdin returns POLLHUP + // + EXPECT_EQ(expected_fds, fds) + << "Value of fds is not one of expected values: " << fds; + break; + default: + FAIL(); } callnum++; @@ -438,21 +365,18 @@ TEST_F(sys_call_test, poll_timeout) } #endif -TEST(inspector, invalid_file_name) -{ +TEST(inspector, invalid_file_name) { sinsp inspector; ASSERT_THROW(inspector.open_savefile("invalid_file_name"), sinsp_exception); } -TEST_F(sys_call_test, ioctl) -{ +TEST_F(sys_call_test, ioctl) { int callnum = 0; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; int status; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int fd; fd = open("/dev/ttyS0", O_RDONLY); @@ -460,13 +384,11 @@ TEST_F(sys_call_test, ioctl) close(fd); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_IOCTL_3_E) - { + if(type == PPME_SYSCALL_IOCTL_3_E) { std::ostringstream oss; oss << std::hex << std::uppercase << TIOCMGET; EXPECT_EQ("/dev/ttyS0", e->get_param_value_str("fd")); @@ -476,9 +398,7 @@ TEST_F(sys_call_test, ioctl) oss << std::hex << std::uppercase << ((unsigned long)&status); EXPECT_EQ(oss.str(), e->get_param_value_str("argument")); callnum++; - } - else if (type == PPME_SYSCALL_IOCTL_3_X) - { + } else if(type == PPME_SYSCALL_IOCTL_3_X) { string res = e->get_param_value_str("res"); EXPECT_TRUE(res == "0" || res == "EIO"); callnum++; @@ -487,17 +407,14 @@ TEST_F(sys_call_test, ioctl) ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); } -TEST_F(sys_call_test, shutdown) -{ +TEST_F(sys_call_test, shutdown) { int callnum = 0; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; int sock; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { + if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { FAIL() << "socket() failed"; return; } @@ -509,32 +426,23 @@ TEST_F(sys_call_test, shutdown) close(sock); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SOCKET_SHUTDOWN_E) - { + if(type == PPME_SOCKET_SHUTDOWN_E) { EXPECT_EQ(std::to_string(sock), e->get_param_value_str("fd", false)); - if (callnum == 0) - { + if(callnum == 0) { EXPECT_EQ("0", e->get_param_value_str("how", false)); - } - else if (callnum == 2) - { + } else if(callnum == 2) { EXPECT_EQ("1", e->get_param_value_str("how", false)); - } - else if (callnum == 4) - { + } else if(callnum == 4) { EXPECT_EQ("2", e->get_param_value_str("how", false)); } callnum++; - } - else if (type == PPME_SOCKET_SHUTDOWN_X) - { + } else if(type == PPME_SOCKET_SHUTDOWN_X) { EXPECT_GT(0, std::stoll(e->get_param_value_str("res", false))); callnum++; } @@ -545,15 +453,13 @@ TEST_F(sys_call_test, shutdown) EXPECT_EQ(6, callnum); } -TEST_F(sys_call_test, timerfd) -{ +TEST_F(sys_call_test, timerfd) { int callnum = 0; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; int fd; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int ret; unsigned int ns; unsigned int sec; @@ -563,8 +469,7 @@ TEST_F(sys_call_test, timerfd) /* Create the timer */ fd = timerfd_create(CLOCK_MONOTONIC, 0); - if (fd == -1) - { + if(fd == -1) { FAIL(); } @@ -580,34 +485,26 @@ TEST_F(sys_call_test, timerfd) /* Wait for the next timer event. If we have missed any the number is written to "missed" */ ret = read(fd, &missed, sizeof(missed)); - if (ret == -1) - { + if(ret == -1) { FAIL(); } close(fd); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_TIMERFD_CREATE_E) - { + if(type == PPME_SYSCALL_TIMERFD_CREATE_E) { EXPECT_EQ(0, std::stoll(e->get_param_value_str("clockid"))); EXPECT_EQ(0, std::stoll(e->get_param_value_str("flags"))); callnum++; - } - else if (type == PPME_SYSCALL_TIMERFD_CREATE_X) - { + } else if(type == PPME_SYSCALL_TIMERFD_CREATE_X) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("res", false))); callnum++; - } - else if (type == PPME_SYSCALL_READ_E) - { - if (callnum == 2) - { + } else if(type == PPME_SYSCALL_READ_E) { + if(callnum == 2) { EXPECT_EQ("", e->get_param_value_str("fd")); EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); callnum++; @@ -620,21 +517,18 @@ TEST_F(sys_call_test, timerfd) EXPECT_EQ(3, callnum); } -TEST_F(sys_call_test, timestamp) -{ +TEST_F(sys_call_test, timestamp) { static const uint64_t TIMESTAMP_DELTA_NS = - 1000000; // We should at least always have 1 ms resolution + 1000000; // We should at least always have 1 ms resolution uint64_t timestampv[20]; int callnum = 0; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { useconds_t sleep_period = 10; struct timeval tv; - for (uint32_t j = 0; j < sizeof(timestampv) / sizeof(timestampv[0]); ++j) - { + for(uint32_t j = 0; j < sizeof(timestampv) / sizeof(timestampv[0]); ++j) { syscall(SYS_gettimeofday, &tv, NULL); timestampv[j] = tv.tv_sec * 1000000000LL + tv.tv_usec * 1000; usleep(sleep_period); @@ -642,11 +536,9 @@ TEST_F(sys_call_test, timestamp) } }; - captured_event_callback_t callback = [&](const callback_param& param) - { - if (param.m_evt->get_type() == PPME_GENERIC_X && - param.m_evt->get_param_value_str("ID") == "gettimeofday") - { + captured_event_callback_t callback = [&](const callback_param& param) { + if(param.m_evt->get_type() == PPME_GENERIC_X && + param.m_evt->get_param_value_str("ID") == "gettimeofday") { EXPECT_LE(param.m_evt->get_ts(), timestampv[callnum] + TIMESTAMP_DELTA_NS); EXPECT_GE(param.m_evt->get_ts(), timestampv[callnum] - TIMESTAMP_DELTA_NS); ++callnum; @@ -657,14 +549,12 @@ TEST_F(sys_call_test, timestamp) EXPECT_EQ((int)(sizeof(timestampv) / sizeof(timestampv[0])), callnum); } -TEST_F(sys_call_test, brk) -{ +TEST_F(sys_call_test, brk) { int callnum = 0; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; - run_callback_t test = [](concurrent_object_handle inspector_handle) - { + run_callback_t test = [](concurrent_object_handle inspector_handle) { sbrk(1000); sbrk(100000); }; @@ -675,26 +565,20 @@ TEST_F(sys_call_test, brk) uint32_t after_brk_vmrss; bool ignore_this_call = false; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_BRK_4_E) - { + if(type == PPME_SYSCALL_BRK_4_E) { uint64_t addr = e->get_param_by_name("addr")->as(); - if (addr == 0) - { + if(addr == 0) { ignore_this_call = true; return; } callnum++; - } - else if (type == PPME_SYSCALL_BRK_4_X) - { - if (ignore_this_call) - { + } else if(type == PPME_SYSCALL_BRK_4_X) { + if(ignore_this_call) { ignore_this_call = false; return; } @@ -705,13 +589,10 @@ TEST_F(sys_call_test, brk) EXPECT_EQ(e->get_thread_info(false)->m_vmsize_kb, vmsize); EXPECT_EQ(e->get_thread_info(false)->m_vmrss_kb, vmrss); - if (callnum == 1) - { + if(callnum == 1) { before_brk_vmsize = vmsize; before_brk_vmrss = vmrss; - } - else if (callnum == 3) - { + } else if(callnum == 3) { after_brk_vmsize = vmsize; after_brk_vmrss = vmrss; @@ -727,8 +608,7 @@ TEST_F(sys_call_test, brk) EXPECT_EQ(4, callnum); } -TEST_F(sys_call_test, mmap) -{ +TEST_F(sys_call_test, mmap) { int callnum = 0; int errno2; @@ -736,8 +616,7 @@ TEST_F(sys_call_test, mmap) void* p; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { munmap((void*)0x50, 300); p = mmap(0, 0, @@ -757,26 +636,22 @@ TEST_F(sys_call_test, mmap) uint32_t exit_vmsize; uint32_t exit_vmrss; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_MUNMAP_E) - { + if(type == PPME_SYSCALL_MUNMAP_E) { callnum++; enter_vmsize = e->get_thread_info(false)->m_vmsize_kb; enter_vmrss = e->get_thread_info(false)->m_vmrss_kb; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ("50", e->get_param_value_str("addr")); EXPECT_EQ("300", e->get_param_value_str("length")); break; - case 7: - { + case 7: { uint64_t addr = e->get_param_by_name("addr")->as(); #ifdef __LP64__ EXPECT_EQ((uint64_t)p, addr); @@ -789,9 +664,7 @@ TEST_F(sys_call_test, mmap) default: callnum--; } - } - else if (type == PPME_SYSCALL_MUNMAP_X) - { + } else if(type == PPME_SYSCALL_MUNMAP_X) { callnum++; exit_vmsize = e->get_param_by_name("vm_size")->as(); @@ -799,8 +672,7 @@ TEST_F(sys_call_test, mmap) EXPECT_EQ(e->get_thread_info(false)->m_vmsize_kb, exit_vmsize); EXPECT_EQ(e->get_thread_info(false)->m_vmrss_kb, exit_vmrss); - switch (callnum) - { + switch(callnum) { case 2: EXPECT_EQ("EINVAL", e->get_param_value_str("res")); EXPECT_EQ("-22", e->get_param_value_str("res", false)); @@ -813,16 +685,13 @@ TEST_F(sys_call_test, mmap) default: callnum--; } - } - else if (type == PPME_SYSCALL_MMAP_E || type == PPME_SYSCALL_MMAP2_E) - { + } else if(type == PPME_SYSCALL_MMAP_E || type == PPME_SYSCALL_MMAP2_E) { callnum++; enter_vmsize = e->get_thread_info(false)->m_vmsize_kb; enter_vmrss = e->get_thread_info(false)->m_vmrss_kb; - switch (callnum) - { + switch(callnum) { case 3: EXPECT_EQ("0", e->get_param_value_str("addr")); EXPECT_EQ("0", e->get_param_value_str("length")); @@ -836,12 +705,9 @@ TEST_F(sys_call_test, mmap) #else EXPECT_EQ("-1", e->get_param_value_str("fd", false)); #endif - if (type == PPME_SYSCALL_MMAP_E) - { + if(type == PPME_SYSCALL_MMAP_E) { EXPECT_EQ("0", e->get_param_value_str("offset")); - } - else - { + } else { EXPECT_EQ("0", e->get_param_value_str("pgoffset")); } break; @@ -856,21 +722,16 @@ TEST_F(sys_call_test, mmap) #else EXPECT_EQ("-1", e->get_param_value_str("fd", false)); #endif - if (type == PPME_SYSCALL_MMAP_E) - { + if(type == PPME_SYSCALL_MMAP_E) { EXPECT_EQ("0", e->get_param_value_str("offset")); - } - else - { + } else { EXPECT_EQ("0", e->get_param_value_str("pgoffset")); } break; default: callnum--; } - } - else if (type == PPME_SYSCALL_MMAP_X || type == PPME_SYSCALL_MMAP2_X) - { + } else if(type == PPME_SYSCALL_MMAP_X || type == PPME_SYSCALL_MMAP2_X) { callnum++; exit_vmsize = e->get_param_by_name("vm_size")->as(); @@ -878,16 +739,13 @@ TEST_F(sys_call_test, mmap) EXPECT_EQ(e->get_thread_info(false)->m_vmsize_kb, exit_vmsize); EXPECT_EQ(e->get_thread_info(false)->m_vmrss_kb, exit_vmrss); - switch (callnum) - { - case 4: - { + switch(callnum) { + case 4: { uint64_t res = e->get_param_by_name("res")->as(); EXPECT_EQ(-errno2, (int64_t)res); break; } - case 6: - { + case 6: { uint64_t res = e->get_param_by_name("res")->as(); EXPECT_EQ((uint64_t)p, res); EXPECT_GT(exit_vmsize, enter_vmsize + 500); @@ -904,18 +762,15 @@ TEST_F(sys_call_test, mmap) EXPECT_EQ(8, callnum); } -TEST_F(sys_call_test, quotactl_ko) -{ +TEST_F(sys_call_test, quotactl_ko) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return evt->get_type() == PPME_SYSCALL_QUOTACTL_X || evt->get_type() == PPME_SYSCALL_QUOTACTL_E; }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { quotactl(QCMD(Q_QUOTAON, USRQUOTA), "/dev/xxx", 2, @@ -923,15 +778,12 @@ TEST_F(sys_call_test, quotactl_ko) quotactl(QCMD(Q_QUOTAOFF, GRPQUOTA), "/dev/xxx", 0, NULL); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_QUOTACTL_E) - { + if(type == PPME_SYSCALL_QUOTACTL_E) { ++callnum; - switch (callnum) - { + switch(callnum) { case 1: printf("quotactl: on str: %s\n", e->get_param_value_str("cmd").c_str()); @@ -943,12 +795,9 @@ TEST_F(sys_call_test, quotactl_ko) EXPECT_EQ("Q_QUOTAOFF", e->get_param_value_str("cmd")); EXPECT_EQ("GRPQUOTA", e->get_param_value_str("type")); } - } - else if (type == PPME_SYSCALL_QUOTACTL_X) - { + } else if(type == PPME_SYSCALL_QUOTACTL_X) { ++callnum; - switch (callnum) - { + switch(callnum) { case 2: EXPECT_EQ("-2", e->get_param_value_str("res", false)); EXPECT_EQ("/dev/xxx", e->get_param_value_str("special")); @@ -964,8 +813,7 @@ TEST_F(sys_call_test, quotactl_ko) EXPECT_EQ(4, callnum); } -TEST_F(sys_call_test, quotactl_ok) -{ +TEST_F(sys_call_test, quotactl_ok) { int callnum = 0; // Clean environment @@ -973,28 +821,25 @@ TEST_F(sys_call_test, quotactl_ok) ret = system("rm -rf /tmp/testquotactl /tmp/testquotamnt"); // Setup a tmpdisk to test quotas char command[] = - "dd if=/dev/zero of=/tmp/testquotactl bs=1M count=200 &&\n" - "echo y | mkfs.ext4 -q /tmp/testquotactl &&\n" - "mkdir -p /tmp/testquotamnt &&\n" - "mount -o usrquota,grpquota,loop=/dev/loop0 /tmp/testquotactl /tmp/testquotamnt &&\n" - "quotacheck -cug /tmp/testquotamnt"; + "dd if=/dev/zero of=/tmp/testquotactl bs=1M count=200 &&\n" + "echo y | mkfs.ext4 -q /tmp/testquotactl &&\n" + "mkdir -p /tmp/testquotamnt &&\n" + "mount -o usrquota,grpquota,loop=/dev/loop0 /tmp/testquotactl /tmp/testquotamnt &&\n" + "quotacheck -cug /tmp/testquotamnt"; ret = system(command); - if (ret != 0) - { + if(ret != 0) { // If we don't have quota utilities, skip this test return; } - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return evt->get_type() == PPME_SYSCALL_QUOTACTL_X || evt->get_type() == PPME_SYSCALL_QUOTACTL_E; }; struct dqblk mydqblk; struct dqinfo mydqinfo; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { quotactl(QCMD(Q_QUOTAON, USRQUOTA), "/dev/loop0", 2, @@ -1004,15 +849,12 @@ TEST_F(sys_call_test, quotactl_ok) quotactl(QCMD(Q_QUOTAOFF, USRQUOTA), "/dev/loop0", 0, NULL); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_QUOTACTL_E) - { + if(type == PPME_SYSCALL_QUOTACTL_E) { ++callnum; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ("Q_QUOTAON", e->get_param_value_str("cmd")); EXPECT_EQ("USRQUOTA", e->get_param_value_str("type")); @@ -1032,12 +874,9 @@ TEST_F(sys_call_test, quotactl_ok) EXPECT_EQ("USRQUOTA", e->get_param_value_str("type")); break; } - } - else if (type == PPME_SYSCALL_QUOTACTL_X) - { + } else if(type == PPME_SYSCALL_QUOTACTL_X) { ++callnum; - switch (callnum) - { + switch(callnum) { case 2: EXPECT_EQ("0", e->get_param_value_str("res", false)); EXPECT_EQ("/dev/loop0", e->get_param_value_str("special")); @@ -1048,35 +887,35 @@ TEST_F(sys_call_test, quotactl_ok) EXPECT_EQ("/dev/loop0", e->get_param_value_str("special")); EXPECT_EQ(mydqblk.dqb_bhardlimit, *reinterpret_cast( - e->get_param_by_name("dqb_bhardlimit")->m_val)); + e->get_param_by_name("dqb_bhardlimit")->m_val)); EXPECT_EQ(mydqblk.dqb_bsoftlimit, *reinterpret_cast( - e->get_param_by_name("dqb_bsoftlimit")->m_val)); + e->get_param_by_name("dqb_bsoftlimit")->m_val)); EXPECT_EQ(mydqblk.dqb_curspace, *reinterpret_cast( - e->get_param_by_name("dqb_curspace")->m_val)); + e->get_param_by_name("dqb_curspace")->m_val)); EXPECT_EQ(mydqblk.dqb_ihardlimit, *reinterpret_cast( - e->get_param_by_name("dqb_ihardlimit")->m_val)); + e->get_param_by_name("dqb_ihardlimit")->m_val)); EXPECT_EQ(mydqblk.dqb_isoftlimit, *reinterpret_cast( - e->get_param_by_name("dqb_isoftlimit")->m_val)); - EXPECT_EQ( - mydqblk.dqb_btime, - *reinterpret_cast(e->get_param_by_name("dqb_btime")->m_val)); - EXPECT_EQ( - mydqblk.dqb_itime, - *reinterpret_cast(e->get_param_by_name("dqb_itime")->m_val)); + e->get_param_by_name("dqb_isoftlimit")->m_val)); + EXPECT_EQ(mydqblk.dqb_btime, + *reinterpret_cast( + e->get_param_by_name("dqb_btime")->m_val)); + EXPECT_EQ(mydqblk.dqb_itime, + *reinterpret_cast( + e->get_param_by_name("dqb_itime")->m_val)); break; case 6: EXPECT_EQ("0", e->get_param_value_str("res", false)); EXPECT_EQ("/dev/loop0", e->get_param_value_str("special")); - EXPECT_EQ( - mydqinfo.dqi_bgrace, - *reinterpret_cast(e->get_param_by_name("dqi_bgrace")->m_val)); - EXPECT_EQ( - mydqinfo.dqi_igrace, - *reinterpret_cast(e->get_param_by_name("dqi_igrace")->m_val)); + EXPECT_EQ(mydqinfo.dqi_bgrace, + *reinterpret_cast( + e->get_param_by_name("dqi_bgrace")->m_val)); + EXPECT_EQ(mydqinfo.dqi_igrace, + *reinterpret_cast( + e->get_param_by_name("dqi_igrace")->m_val)); break; case 8: EXPECT_EQ("0", e->get_param_value_str("res", false)); @@ -1089,20 +928,18 @@ TEST_F(sys_call_test, quotactl_ok) EXPECT_EQ(8, callnum); } -TEST_F(sys_call_test, getsetuid_and_gid) -{ +TEST_F(sys_call_test, getsetuid_and_gid) { static const uint32_t test_gid = 6566; int callnum = 0; - uint32_t orig_uid = getuid(); + uint32_t orig_uid = getuid(); uint32_t orig_euid = geteuid(); - uint32_t orig_gid = getgid(); + uint32_t orig_gid = getgid(); uint32_t orig_egid = getegid(); event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { auto res = setuid(0); EXPECT_EQ(0, res); res = setgid(test_gid); @@ -1113,12 +950,10 @@ TEST_F(sys_call_test, getsetuid_and_gid) getegid(); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - switch (type) - { + switch(type) { case PPME_SYSCALL_SETUID_E: ++callnum; EXPECT_EQ("0", e->get_param_value_str("uid", false)); @@ -1176,8 +1011,7 @@ TEST_F(sys_call_test, getsetuid_and_gid) result += setgid(orig_gid); result += setegid(orig_egid); - if(result != 0) - { + if(result != 0) { FAIL() << "Cannot restore initial id state."; } @@ -1186,13 +1020,11 @@ TEST_F(sys_call_test, getsetuid_and_gid) #ifdef __x86_64__ -TEST_F(sys_call_test32, execve_ia32_emulation) -{ +TEST_F(sys_call_test32, execve_ia32_emulation) { int callnum = 0; std::unique_ptr is_subprocess_execve; - before_open_t before_open = [&](sinsp* inspector) - { + before_open_t before_open = [&](sinsp* inspector) { sinsp_filter_compiler compiler(inspector, "evt.type=execve and proc.apid=" + std::to_string(getpid())); is_subprocess_execve = compiler.compile(); @@ -1200,25 +1032,21 @@ TEST_F(sys_call_test32, execve_ia32_emulation) event_filter_t filter = [&](sinsp_evt* evt) { return is_subprocess_execve->run(evt); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { - auto ret = system(LIBSINSP_TEST_RESOURCES_PATH "execve32 " - LIBSINSP_TEST_RESOURCES_PATH "execve " - LIBSINSP_TEST_RESOURCES_PATH "execve32"); + run_callback_t test = [&](concurrent_object_handle inspector_handle) { + auto ret = system(LIBSINSP_TEST_RESOURCES_PATH "execve32 " LIBSINSP_TEST_RESOURCES_PATH + "execve " LIBSINSP_TEST_RESOURCES_PATH + "execve32"); EXPECT_EQ(0, ret); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); auto tinfo = e->get_thread_info(true); - if (type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E || - type == PPME_SYSCALL_EXECVE_17_E) - { + if(type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E || + type == PPME_SYSCALL_EXECVE_17_E) { ++callnum; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ(tinfo->m_comm, "libsinsp_e2e_te"); break; @@ -1232,15 +1060,12 @@ TEST_F(sys_call_test32, execve_ia32_emulation) EXPECT_EQ(tinfo->m_comm, "execve"); break; } - } - else if (type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X || - type == PPME_SYSCALL_EXECVE_17_X) - { + } else if(type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X || + type == PPME_SYSCALL_EXECVE_17_X) { ++callnum; EXPECT_EQ("0", e->get_param_value_str("res", false)); auto comm = e->get_param_value_str("comm", false); - switch (callnum) - { + switch(callnum) { case 2: EXPECT_EQ(comm, "sh"); break; @@ -1260,31 +1085,25 @@ TEST_F(sys_call_test32, execve_ia32_emulation) EXPECT_EQ(8, callnum); } -TEST_F(sys_call_test32, quotactl_ko) -{ +TEST_F(sys_call_test32, quotactl_ko) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return evt->get_type() == PPME_SYSCALL_QUOTACTL_X || evt->get_type() == PPME_SYSCALL_QUOTACTL_E; }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { subprocess handle(LIBSINSP_TEST_PATH "/test_helper_32", {"quotactl_ko"}); handle.wait(); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_QUOTACTL_E) - { + if(type == PPME_SYSCALL_QUOTACTL_E) { ++callnum; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ("Q_QUOTAON", e->get_param_value_str("cmd")); EXPECT_EQ("USRQUOTA", e->get_param_value_str("type")); @@ -1294,12 +1113,9 @@ TEST_F(sys_call_test32, quotactl_ko) EXPECT_EQ("Q_QUOTAOFF", e->get_param_value_str("cmd")); EXPECT_EQ("GRPQUOTA", e->get_param_value_str("type")); } - } - else if (type == PPME_SYSCALL_QUOTACTL_X) - { + } else if(type == PPME_SYSCALL_QUOTACTL_X) { ++callnum; - switch (callnum) - { + switch(callnum) { case 2: EXPECT_EQ("-2", e->get_param_value_str("res", false)); EXPECT_EQ("/dev/xxx", e->get_param_value_str("special")); @@ -1317,28 +1133,23 @@ TEST_F(sys_call_test32, quotactl_ko) #endif -TEST_F(sys_call_test, setns_test) -{ +TEST_F(sys_call_test, setns_test) { int callnum = 0; int fd; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt) && (evt->get_type() == PPME_SYSCALL_SETNS_E || evt->get_type() == PPME_SYSCALL_SETNS_X); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { fd = open("/proc/self/ns/net", O_RDONLY); ASSERT_NE(0, fd); ASSERT_EQ(0, setns(fd, CLONE_NEWNET)); ASSERT_EQ(0, close(fd)); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - switch (type) - { + switch(type) { case PPME_SYSCALL_SETNS_E: EXPECT_EQ("/proc/self/ns/net", e->get_param_value_str("fd")); break; @@ -1352,32 +1163,27 @@ TEST_F(sys_call_test, setns_test) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, unshare_) -{ +TEST_F(sys_call_test, unshare_) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto tinfo = evt->get_thread_info(true); - return tinfo->get_comm() == "libsinsp_e2e_te" && (evt->get_type() == PPME_SYSCALL_UNSHARE_E || - evt->get_type() == PPME_SYSCALL_UNSHARE_X); + return tinfo->get_comm() == "libsinsp_e2e_te" && + (evt->get_type() == PPME_SYSCALL_UNSHARE_E || + evt->get_type() == PPME_SYSCALL_UNSHARE_X); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { auto child = fork(); - if (child == 0) - { + if(child == 0) { unshare(CLONE_NEWUTS); // _exit prevents asan from complaining for a false positive memory leak. _exit(0); } waitpid(child, NULL, 0); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - switch (type) - { + switch(type) { case PPME_SYSCALL_UNSHARE_E: EXPECT_EQ("CLONE_NEWUTS", e->get_param_value_str("flags")); break; @@ -1391,16 +1197,13 @@ TEST_F(sys_call_test, unshare_) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) -{ +TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto tinfo = evt->get_thread_info(true); return tinfo->get_comm() == "libsinsp_e2e_te" && evt->get_type() == PPME_SOCKET_RECVMSG_X; }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int server_sd, worker_sd, pair_sd[2]; int rc = socketpair(AF_UNIX, SOCK_DGRAM, 0, pair_sd); ASSERT_GE(rc, 0); @@ -1408,17 +1211,16 @@ TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) worker_sd = pair_sd[1]; auto child = fork(); - if (child == 0) - { + if(child == 0) { struct msghdr child_msg = {}; - struct cmsghdr *cmsghdr; + struct cmsghdr* cmsghdr; struct iovec iov[1]; char buf[CMSG_SPACE(sizeof(int))], c; iov[0].iov_base = &c; iov[0].iov_len = sizeof(c); memset(buf, 0x0d, sizeof(buf)); - cmsghdr = (struct cmsghdr *)buf; + cmsghdr = (struct cmsghdr*)buf; cmsghdr->cmsg_len = CMSG_LEN(sizeof(int)); cmsghdr->cmsg_level = SOL_SOCKET; cmsghdr->cmsg_type = SCM_RIGHTS; @@ -1430,16 +1232,14 @@ TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) ASSERT_GE(rc, 0); // _exit prevents asan from complaining for a false positive memory leak. _exit(0); - } - else - { + } else { struct msghdr parent_msg = {}; - struct cmsghdr *cmsghdr; + struct cmsghdr* cmsghdr; struct iovec iov[1]; - int *p; + int* p; char buf[CMSG_SPACE(sizeof(int))], c; - FILE *f = tmpfile(); + FILE* f = tmpfile(); ASSERT_NE(nullptr, f); int fd = fileno(f); @@ -1447,7 +1247,7 @@ TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) iov[0].iov_base = &c; iov[0].iov_len = sizeof(c); memset(buf, 0x0b, sizeof(buf)); - cmsghdr = (struct cmsghdr *)buf; + cmsghdr = (struct cmsghdr*)buf; cmsghdr->cmsg_len = CMSG_LEN(sizeof(int)); cmsghdr->cmsg_level = SOL_SOCKET; cmsghdr->cmsg_type = SCM_RIGHTS; @@ -1455,7 +1255,7 @@ TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) parent_msg.msg_iovlen = sizeof(iov) / sizeof(iov[0]); parent_msg.msg_control = cmsghdr; parent_msg.msg_controllen = CMSG_LEN(sizeof(int)); - p = (int *)CMSG_DATA(cmsghdr); + p = (int*)CMSG_DATA(cmsghdr); *p = fd; rc = sendmsg(server_sd, &parent_msg, 0); @@ -1464,18 +1264,14 @@ TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) fclose(f); } }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (e->get_num_params() >= 5) - { + if(e->get_num_params() >= 5) { auto parinfo = e->get_param(4); - if(parinfo->m_len > sizeof(cmsghdr)) - { + if(parinfo->m_len > sizeof(cmsghdr)) { cmsghdr cmsg = {}; memcpy(&cmsg, parinfo->m_val, sizeof(cmsghdr)); - if(cmsg.cmsg_type == SCM_RIGHTS) - { + if(cmsg.cmsg_type == SCM_RIGHTS) { ++callnum; } } @@ -1485,30 +1281,25 @@ TEST_F(sys_call_test, sendmsg_recvmsg_SCM_RIGHTS) EXPECT_EQ(1, callnum); } -TEST_F(sys_call_test, ppoll_timeout) -{ +TEST_F(sys_call_test, ppoll_timeout) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto ti = evt->get_thread_info(false); return (evt->get_type() == PPME_SYSCALL_PPOLL_E || evt->get_type() == PPME_SYSCALL_PPOLL_X) && - ti->m_comm == "test_helper"; + ti->m_comm == "test_helper"; }; - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { subprocess handle(LIBSINSP_TEST_PATH "/test_helper", {"ppoll_timeout"}); handle.wait(); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_PPOLL_E) - { + if(type == PPME_SYSCALL_PPOLL_E) { // // stdin and stdout can be a file or a fifo depending // on how the tests are invoked @@ -1518,9 +1309,7 @@ TEST_F(sys_call_test, ppoll_timeout) EXPECT_EQ("1000000", e->get_param_value_str("timeout", false)); EXPECT_EQ("SIGHUP SIGCHLD", e->get_param_value_str("sigmask", false)); callnum++; - } - else if (type == PPME_SYSCALL_PPOLL_X) - { + } else if(type == PPME_SYSCALL_PPOLL_X) { int64_t res = stoi(e->get_param_value_str("res")); EXPECT_EQ(res, 1); @@ -1536,8 +1325,7 @@ TEST_F(sys_call_test, ppoll_timeout) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, getsetresuid_and_gid) -{ +TEST_F(sys_call_test, getsetresuid_and_gid) { static const uint32_t test_uid = 5454; static const uint32_t test_gid = 6565; int callnum = 0; @@ -1570,27 +1358,27 @@ TEST_F(sys_call_test, getsetresuid_and_gid) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto type = evt->get_type(); auto tinfo = evt->get_thread_info(true); return tinfo->m_comm != "sudo" && - (type == PPME_USER_ADDED_E || type == PPME_USER_ADDED_X || - type == PPME_GROUP_ADDED_E || type == PPME_GROUP_ADDED_X || - type == PPME_SYSCALL_GETRESUID_E || type == PPME_SYSCALL_GETRESUID_X || - type == PPME_SYSCALL_GETRESGID_E || type == PPME_SYSCALL_GETRESGID_X || - type == PPME_SYSCALL_SETRESUID_E || type == PPME_SYSCALL_SETRESUID_X || - type == PPME_SYSCALL_SETRESGID_E || type == PPME_SYSCALL_SETRESGID_X); }; + (type == PPME_USER_ADDED_E || type == PPME_USER_ADDED_X || + type == PPME_GROUP_ADDED_E || type == PPME_GROUP_ADDED_X || + type == PPME_SYSCALL_GETRESUID_E || type == PPME_SYSCALL_GETRESUID_X || + type == PPME_SYSCALL_GETRESGID_E || type == PPME_SYSCALL_GETRESGID_X || + type == PPME_SYSCALL_SETRESUID_E || type == PPME_SYSCALL_SETRESUID_X || + type == PPME_SYSCALL_SETRESGID_E || type == PPME_SYSCALL_SETRESGID_X); + }; // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { - char command[] = "useradd -u 5454 testsetresuid && " - "groupadd -g 6565 testsetresgid && " - "sudo -u testsetresuid echo && " - "sudo -g testsetresgid echo"; + run_callback_t test = [&](concurrent_object_handle inspector) { + char command[] = + "useradd -u 5454 testsetresuid && " + "groupadd -g 6565 testsetresgid && " + "sudo -u testsetresuid echo && " + "sudo -g testsetresgid echo"; ret = system(command); ASSERT_EQ(0, ret); @@ -1605,12 +1393,11 @@ TEST_F(sys_call_test, getsetresuid_and_gid) // // OUTPUT VALIDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_SETRESUID_E && e->get_param_value_str("ruid", false) != "-1" && !setresuid_e_ok) - { + if(type == PPME_SYSCALL_SETRESUID_E && e->get_param_value_str("ruid", false) != "-1" && + !setresuid_e_ok) { ++callnum; EXPECT_EQ("5454", e->get_param_value_str("ruid", false)); EXPECT_EQ("testsetresuid", e->get_param_value_str("ruid")); @@ -1619,15 +1406,12 @@ TEST_F(sys_call_test, getsetresuid_and_gid) EXPECT_EQ("-1", e->get_param_value_str("suid", false)); EXPECT_EQ("", e->get_param_value_str("suid")); setresuid_e_ok = true; - } - else if (type == PPME_SYSCALL_SETRESUID_X && !setresuid_ok) - { + } else if(type == PPME_SYSCALL_SETRESUID_X && !setresuid_ok) { ++callnum; EXPECT_EQ("0", e->get_param_value_str("res", false)); setresuid_ok = true; - } - else if (type == PPME_SYSCALL_SETRESGID_E && e->get_param_value_str("rgid", false) != "-1" && !setresgid_e_ok) - { + } else if(type == PPME_SYSCALL_SETRESGID_E && + e->get_param_value_str("rgid", false) != "-1" && !setresgid_e_ok) { ++callnum; EXPECT_EQ("6565", e->get_param_value_str("rgid", false)); EXPECT_EQ("testsetresgid", e->get_param_value_str("rgid")); @@ -1636,25 +1420,17 @@ TEST_F(sys_call_test, getsetresuid_and_gid) EXPECT_EQ("-1", e->get_param_value_str("sgid", false)); EXPECT_EQ("", e->get_param_value_str("sgid")); setresgid_e_ok = true; - } - else if (type == PPME_SYSCALL_SETRESGID_X && !setresgid_ok) - { + } else if(type == PPME_SYSCALL_SETRESGID_X && !setresgid_ok) { ++callnum; EXPECT_EQ("0", e->get_param_value_str("res", false)); setresgid_ok = true; - } - else if (type == PPME_SYSCALL_GETRESUID_E && !getresuid_e_ok) - { + } else if(type == PPME_SYSCALL_GETRESUID_E && !getresuid_e_ok) { ++callnum; getresuid_e_ok = true; - } - else if (type == PPME_SYSCALL_GETRESGID_E && !getresgid_e_ok) - { + } else if(type == PPME_SYSCALL_GETRESGID_E && !getresgid_e_ok) { ++callnum; getresgid_e_ok = true; - } - else if (type == PPME_SYSCALL_GETRESUID_X && !getresuid_ok) - { + } else if(type == PPME_SYSCALL_GETRESUID_X && !getresuid_ok) { ++callnum; EXPECT_EQ("0", e->get_param_value_str("res", false)); EXPECT_EQ("5454", e->get_param_value_str("ruid", false)); @@ -1664,9 +1440,7 @@ TEST_F(sys_call_test, getsetresuid_and_gid) EXPECT_EQ("0", e->get_param_value_str("suid", false)); EXPECT_EQ("root", e->get_param_value_str("suid")); getresuid_ok = true; - } - else if (type == PPME_SYSCALL_GETRESGID_X && !getresgid_ok) - { + } else if(type == PPME_SYSCALL_GETRESGID_X && !getresgid_ok) { ++callnum; EXPECT_EQ("0", e->get_param_value_str("res", false)); EXPECT_EQ("6565", e->get_param_value_str("rgid", false)); @@ -1679,25 +1453,23 @@ TEST_F(sys_call_test, getsetresuid_and_gid) } }; - before_close_t cleanup = [&](sinsp* inspector) - { + before_close_t cleanup = [&](sinsp* inspector) { int result = 0; result += setresuid(orig_uids[0], orig_uids[1], orig_uids[2]); result += setresgid(orig_gids[0], orig_gids[1], orig_gids[2]); - if(result != 0) - { + if(result != 0) { FAIL() << "Cannot restore initial id state."; } }; - - ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter, event_capture::do_nothing, cleanup); }); + + ASSERT_NO_FATAL_FAILURE( + { event_capture::run(test, callback, filter, event_capture::do_nothing, cleanup); }); EXPECT_EQ(8, callnum); } -TEST_F(sys_call_test, failing_execve) -{ +TEST_F(sys_call_test, failing_execve) { int callnum = 0; event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt); }; @@ -1712,26 +1484,21 @@ TEST_F(sys_call_test, failing_execve) printf("%s %s %s %s %s\n", eargv[0], eargv[1], eargv[2], eargv[3], eargv[4]); printf("%s %s %s %s\n", eenvp[0], eenvp[1], eenvp[2], eenvp[3]); - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { int ret = execve(eargv[0], (char* const*)eargv, (char* const*)eenvp); ASSERT_TRUE(ret < 0); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E) - { + if(type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E) { ++callnum; string filename = e->get_param_value_str("filename"); EXPECT_EQ(filename, eargv[0]); - } - else if (type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X) - { + } else if(type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X) { ++callnum; string res = e->get_param_value_str("res"); @@ -1752,8 +1519,7 @@ TEST_F(sys_call_test, failing_execve) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test, large_execve) -{ +TEST_F(sys_call_test, large_execve) { const int buf_size = 100 * 1024; const int driver_truncation_size = getpagesize(); const string non_existing_binary = "/non/existent"; @@ -1767,22 +1533,18 @@ TEST_F(sys_call_test, large_execve) srandom(42); string buf; - while (buf.length() < buf_size) - { + while(buf.length() < buf_size) { buf.append(std::to_string(random())); } - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { ctid = fork(); - if (ctid < 0) - { + if(ctid < 0) { FAIL(); } - if (ctid == 0) - { + if(ctid == 0) { { const char* eargv[] = {non_existing_binary.c_str(), buf.c_str(), NULL}; @@ -1800,66 +1562,51 @@ TEST_F(sys_call_test, large_execve) int ret = execve(eargv[0], (char* const*)eargv, (char* const*)eenvp); ASSERT_TRUE(ret == 0); } - } - else - { + } else { wait(NULL); sleep(1); } }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E) - { + if(type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E) { ++callnum; string filename = e->get_param_value_str("filename"); - if (callnum == 1) - { + if(callnum == 1) { EXPECT_EQ(filename, non_existing_binary); - } - else if (callnum == 3) - { + } else if(callnum == 3) { EXPECT_EQ(filename, existing_binary); - } - else - { + } else { FAIL(); } - } - else if (type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X) - { + } else if(type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X) { ++callnum; string exe = e->get_param_value_str("exe"); string args = e->get_param_value_str("args"); - if (callnum == 2) - { + if(callnum == 2) { // This is the failed execve. exe and // args will be available, but env // will not. EXPECT_EQ(exe, non_existing_binary.c_str()); EXPECT_EQ(args, - buf.substr(0, driver_truncation_size - non_existing_binary.length() - 2) + "."); - } - else if (callnum == 4) - { + buf.substr(0, driver_truncation_size - non_existing_binary.length() - 2) + + "."); + } else if(callnum == 4) { string env = e->get_param_value_str("env"); EXPECT_EQ(exe, existing_binary); EXPECT_EQ( - args, - buf.substr(0, driver_truncation_size - existing_binary.length() - 2) + "."); + args, + buf.substr(0, driver_truncation_size - existing_binary.length() - 2) + "."); EXPECT_EQ(env, buf.substr(0, driver_truncation_size - 1) + "."); - } - else - { + } else { FAIL(); } } @@ -1871,14 +1618,12 @@ TEST_F(sys_call_test, large_execve) #ifdef __x86_64__ -TEST_F(sys_call_test32, failing_execve) -{ +TEST_F(sys_call_test32, failing_execve) { int callnum = 0; // INIT FILTER std::unique_ptr is_subprocess_execve; - before_open_t before_open = [&](sinsp* inspector) - { + before_open_t before_open = [&](sinsp* inspector) { sinsp_filter_compiler compiler(inspector, "evt.type=execve and proc.apid=" + std::to_string(getpid())); is_subprocess_execve.reset(compiler.compile().release()); @@ -1892,8 +1637,7 @@ TEST_F(sys_call_test32, failing_execve) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { auto ret = system(LIBSINSP_TEST_RESOURCES_PATH "execve32_fail"); ASSERT_TRUE(ret > 0); ret = system(LIBSINSP_TEST_RESOURCES_PATH "execve32 ./fail"); @@ -1903,17 +1647,14 @@ TEST_F(sys_call_test32, failing_execve) // // OUTPUT VALIDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); auto tinfo = e->get_thread_info(true); - if (type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E || - type == PPME_SYSCALL_EXECVE_17_E) - { + if(type == PPME_SYSCALL_EXECVE_19_E || type == PPME_SYSCALL_EXECVE_18_E || + type == PPME_SYSCALL_EXECVE_17_E) { ++callnum; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ(tinfo->m_comm, "libsinsp_e2e_te"); break; @@ -1932,17 +1673,14 @@ TEST_F(sys_call_test32, failing_execve) default: FAIL() << "Wrong execve entry callnum (" << callnum << ")"; } - } - else if (type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X || - type == PPME_SYSCALL_EXECVE_17_X) - { + } else if(type == PPME_SYSCALL_EXECVE_19_X || type == PPME_SYSCALL_EXECVE_18_X || + type == PPME_SYSCALL_EXECVE_17_X) { ++callnum; auto res = e->get_param_value_str("res", false); auto comm = e->get_param_value_str("comm", false); auto exe = e->get_param_value_str("exe", false); - switch (callnum) - { + switch(callnum) { case 2: EXPECT_EQ("0", res); EXPECT_EQ(comm, "sh"); @@ -1975,8 +1713,7 @@ TEST_F(sys_call_test32, failing_execve) EXPECT_EQ(10, callnum); } -TEST_F(sys_call_test32, mmap) -{ +TEST_F(sys_call_test32, mmap) { int callnum = 0; int errno2; @@ -1985,11 +1722,9 @@ TEST_F(sys_call_test32, mmap) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto tinfo = evt->get_thread_info(false); - return tinfo && tinfo->m_comm == "test_helper_32" - && ps_filter(evt); + return tinfo && tinfo->m_comm == "test_helper_32" && ps_filter(evt); }; uint64_t p = 0; @@ -1997,10 +1732,11 @@ TEST_F(sys_call_test32, mmap) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { subprocess handle(LIBSINSP_TEST_PATH "/test_helper_32", - {"mmap_test",}); + { + "mmap_test", + }); std::stringstream tmp; handle.out(); tmp << handle.out(); @@ -2022,26 +1758,22 @@ TEST_F(sys_call_test32, mmap) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_MUNMAP_E) - { + if(type == PPME_SYSCALL_MUNMAP_E) { callnum++; enter_vmsize = e->get_thread_info(false)->m_vmsize_kb; enter_vmrss = e->get_thread_info(false)->m_vmrss_kb; - switch (callnum) - { + switch(callnum) { case 1: EXPECT_EQ("50", e->get_param_value_str("addr")); EXPECT_EQ("300", e->get_param_value_str("length")); break; - case 7: - { + case 7: { uint64_t addr = 0; memcpy(&addr, e->get_param_by_name("addr")->m_val, sizeof(uint64_t)); #ifdef __LP64__ @@ -2055,9 +1787,7 @@ TEST_F(sys_call_test32, mmap) default: callnum--; } - } - else if (type == PPME_SYSCALL_MUNMAP_X) - { + } else if(type == PPME_SYSCALL_MUNMAP_X) { callnum++; memcpy(&exit_vmsize, e->get_param_by_name("vm_size")->m_val, sizeof(uint32_t)); @@ -2065,8 +1795,7 @@ TEST_F(sys_call_test32, mmap) EXPECT_EQ(e->get_thread_info(false)->m_vmsize_kb, exit_vmsize); EXPECT_EQ(e->get_thread_info(false)->m_vmrss_kb, exit_vmrss); - switch (callnum) - { + switch(callnum) { case 2: EXPECT_EQ("EINVAL", e->get_param_value_str("res")); EXPECT_EQ("-22", e->get_param_value_str("res", false)); @@ -2079,30 +1808,24 @@ TEST_F(sys_call_test32, mmap) default: callnum--; } - } - else if (type == PPME_SYSCALL_MMAP_E || type == PPME_SYSCALL_MMAP2_E) - { + } else if(type == PPME_SYSCALL_MMAP_E || type == PPME_SYSCALL_MMAP2_E) { callnum++; enter_vmsize = e->get_thread_info(false)->m_vmsize_kb; enter_vmrss = e->get_thread_info(false)->m_vmrss_kb; - switch (callnum) - { + switch(callnum) { case 3: EXPECT_EQ("0", e->get_param_value_str("addr")); EXPECT_EQ("0", e->get_param_value_str("length")); EXPECT_EQ("PROT_READ|PROT_WRITE|PROT_EXEC", e->get_param_value_str("prot")); EXPECT_EQ("MAP_SHARED|MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE", - e->get_param_value_str("flags")); + e->get_param_value_str("flags")); EXPECT_EQ("-1", e->get_param_value_str("fd", false)); - if (type == PPME_SYSCALL_MMAP_E) - { + if(type == PPME_SYSCALL_MMAP_E) { EXPECT_EQ("0", e->get_param_value_str("offset")); - } - else - { + } else { EXPECT_EQ("0", e->get_param_value_str("pgoffset")); } break; @@ -2113,21 +1836,16 @@ TEST_F(sys_call_test32, mmap) EXPECT_EQ("MAP_PRIVATE|MAP_ANONYMOUS", e->get_param_value_str("flags")); EXPECT_EQ("-1", e->get_param_value_str("fd", false)); - if (type == PPME_SYSCALL_MMAP_E) - { + if(type == PPME_SYSCALL_MMAP_E) { EXPECT_EQ("0", e->get_param_value_str("offset")); - } - else - { + } else { EXPECT_EQ("0", e->get_param_value_str("pgoffset")); } break; default: callnum--; } - } - else if (type == PPME_SYSCALL_MMAP_X || type == PPME_SYSCALL_MMAP2_X) - { + } else if(type == PPME_SYSCALL_MMAP_X || type == PPME_SYSCALL_MMAP2_X) { callnum++; memcpy(&exit_vmsize, e->get_param_by_name("vm_size")->m_val, sizeof(uint32_t)); @@ -2135,17 +1853,14 @@ TEST_F(sys_call_test32, mmap) EXPECT_EQ(e->get_thread_info(false)->m_vmsize_kb, exit_vmsize); EXPECT_EQ(e->get_thread_info(false)->m_vmrss_kb, exit_vmrss); - switch (callnum) - { - case 4: - { + switch(callnum) { + case 4: { uint64_t res = 0; memcpy(&res, e->get_param_by_name("res")->m_val, sizeof(uint64_t)); EXPECT_EQ(-errno2, (int64_t)res); break; } - case 6: - { + case 6: { uint64_t res = 0; memcpy(&res, e->get_param_by_name("res")->m_val, sizeof(uint64_t)); EXPECT_EQ((uint64_t)p, res); @@ -2163,11 +1878,9 @@ TEST_F(sys_call_test32, mmap) EXPECT_EQ(8, callnum); } -TEST_F(sys_call_test32, ppoll_timeout) -{ +TEST_F(sys_call_test32, ppoll_timeout) { int callnum = 0; - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto tinfo = evt->get_thread_info(false); return (evt->get_type() == PPME_SYSCALL_PPOLL_E || evt->get_type() == PPME_SYSCALL_PPOLL_X) && @@ -2176,10 +1889,11 @@ TEST_F(sys_call_test32, ppoll_timeout) std::string my_pipe[2]; - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { subprocess handle(LIBSINSP_TEST_PATH "/test_helper_32", - {"ppoll_timeout",}); + { + "ppoll_timeout", + }); std::stringstream ss; ss << handle.out(); my_pipe[0] = ss.str(); @@ -2192,39 +1906,32 @@ TEST_F(sys_call_test32, ppoll_timeout) handle.wait(); }; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_PPOLL_E) - { + if(type == PPME_SYSCALL_PPOLL_E) { // // stdin and stdout can be a file or a fifo depending // on how the tests are invoked // std::string fds = e->get_param_value_str("fds"); - std::string expected_fds = my_pipe[0] + ":p1 " + - my_pipe[1] + ":p4"; + std::string expected_fds = my_pipe[0] + ":p1 " + my_pipe[1] + ":p4"; EXPECT_EQ(expected_fds, fds); EXPECT_EQ("1000000", e->get_param_value_str("timeout", false)); EXPECT_EQ("SIGHUP SIGCHLD", e->get_param_value_str("sigmask", false)); callnum++; - } - else if (type == PPME_SYSCALL_PPOLL_X) - { + } else if(type == PPME_SYSCALL_PPOLL_X) { int64_t res = std::stol(e->get_param_value_str("res")); EXPECT_GT(res, 0); EXPECT_LE(res, 2); string fds = e->get_param_value_str("fds"); - std::string expected_fds = my_pipe[0] + ":p0 " + - my_pipe[1] + ":p4"; + std::string expected_fds = my_pipe[0] + ":p0 " + my_pipe[1] + ":p4"; - switch (res) - { + switch(res) { case 1: EXPECT_EQ(expected_fds, fds); break; @@ -2245,8 +1952,7 @@ TEST_F(sys_call_test32, ppoll_timeout) EXPECT_EQ(2, callnum); } -TEST_F(sys_call_test32, fs_preadv) -{ +TEST_F(sys_call_test32, fs_preadv) { int callnum = 0; int fd = 0; int fd1 = 0; @@ -2257,16 +1963,12 @@ TEST_F(sys_call_test32, fs_preadv) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto tinfo = evt->get_thread_info(false); - if (tinfo && tinfo->m_comm == "test_helper_32") - { + if(tinfo && tinfo->m_comm == "test_helper_32") { auto type = evt->get_type(); - return (type == PPME_SYSCALL_PREADV_E - || type == PPME_SYSCALL_PREADV_X - || type == PPME_SYSCALL_PWRITEV_E - || type == PPME_SYSCALL_PWRITEV_X); + return (type == PPME_SYSCALL_PREADV_E || type == PPME_SYSCALL_PREADV_X || + type == PPME_SYSCALL_PWRITEV_E || type == PPME_SYSCALL_PWRITEV_X); } return false; }; @@ -2274,8 +1976,7 @@ TEST_F(sys_call_test32, fs_preadv) // // TEST CODE // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { subprocess test_proc(LIBSINSP_TEST_PATH "/test_helper_32", {"preadv_pwritev"}); fd = std::stoi(test_proc.out()); int bool_n = std::stoi(test_proc.out()); @@ -2291,62 +1992,44 @@ TEST_F(sys_call_test32, fs_preadv) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (type == PPME_SYSCALL_PWRITEV_E) - { - if (callnum == 0) - { + if(type == PPME_SYSCALL_PWRITEV_E) { + if(callnum == 0) { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(987654321, std::stoll(e->get_param_value_str("pos"))); EXPECT_EQ(15, std::stoll(e->get_param_value_str("size"))); callnum++; - } - else - { + } else { EXPECT_EQ(fd, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(10, std::stoll(e->get_param_value_str("pos"))); EXPECT_EQ(15, std::stoll(e->get_param_value_str("size"))); callnum++; } - } - else if (type == PPME_SYSCALL_PWRITEV_X) - { - if (callnum == 1) - { + } else if(type == PPME_SYSCALL_PWRITEV_X) { + if(callnum == 1) { pwrite1_res = std::stoi(e->get_param_value_str("res", false)); EXPECT_EQ("aaaaabbbbbccccc", e->get_param_value_str("data")); callnum++; - } - else - { + } else { pwrite2_res = std::stoi(e->get_param_value_str("res", false)); EXPECT_EQ("aaaaabbbbbccccc", e->get_param_value_str("data")); callnum++; } - } - else if (type == PPME_SYSCALL_PREADV_E) - { - if (callnum == 4) - { + } else if(type == PPME_SYSCALL_PREADV_E) { + if(callnum == 4) { EXPECT_EQ(fd1, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(987654321, std::stoll(e->get_param_value_str("pos"))); callnum++; - } - else - { + } else { EXPECT_EQ(fd1, std::stoll(e->get_param_value_str("fd", false))); EXPECT_EQ(10, std::stoll(e->get_param_value_str("pos"))); callnum++; } - } - else if (type == PPME_SYSCALL_PREADV_X) - { - if (callnum == 3) - { + } else if(type == PPME_SYSCALL_PREADV_X) { + if(callnum == 3) { EXPECT_EQ(15, std::stoi(e->get_param_value_str("res", false))); EXPECT_EQ("aaaaabbbbb", e->get_param_value_str("data")); EXPECT_EQ(30, std::stoll(e->get_param_value_str("size"))); @@ -2357,188 +2040,168 @@ TEST_F(sys_call_test32, fs_preadv) ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); EXPECT_EQ(6, callnum); - if (pwritev64_succeeded) - { + if(pwritev64_succeeded) { EXPECT_EQ(15, pwrite1_res); - } - else - { + } else { EXPECT_GT(0, pwrite1_res); } - if (pwritev64_succeeded2) - { + if(pwritev64_succeeded2) { EXPECT_EQ(15, pwrite2_res); - } - else - { + } else { EXPECT_EQ(-22, pwrite2_res); } } #endif -extern "C" -{ - int32_t scap_proc_read_thread(struct scap_linux_platform* linux_platform, - char* procdirname, - uint64_t tid, - struct scap_threadinfo* tinfo, - char* error, - bool scan_sockets); +extern "C" { +int32_t scap_proc_read_thread(struct scap_linux_platform* linux_platform, + char* procdirname, + uint64_t tid, + struct scap_threadinfo* tinfo, + char* error, + bool scan_sockets); } -TEST_F(sys_call_test, thread_lookup_static) -{ +TEST_F(sys_call_test, thread_lookup_static) { char err_buf[SCAP_LASTERR_SIZE]; - scap_threadinfo scap_tinfo; - char proc[] = LIBSINSP_TEST_RESOURCES_PATH "/_proc"; - struct stat s = {}; - if (stat(proc, &s) != 0) - { - fprintf(stderr, "%s not found, skipping test\n", proc); - FAIL(); - } - - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_type() != PPME_PROCEXIT_1_E && evt->get_tid() > 0; }; - run_callback_t test = [&](concurrent_object_handle inspector) {return;}; - captured_event_callback_t callback = [&](const callback_param& param) {return;}; - scap_linux_platform *platform; - - before_close_t before_close = [&](sinsp* inspector) - { - platform = (scap_linux_platform*)inspector->get_scap_platform(); - }; - - ASSERT_NO_FATAL_FAILURE( - { event_capture::run(test, callback, filter, event_capture::do_nothing, before_close); }); - - ASSERT_EQ(SCAP_SUCCESS, - scap_proc_read_thread(platform, proc, 1, &scap_tinfo, err_buf, false)); - - EXPECT_EQ(1, scap_tinfo.tid); - EXPECT_EQ(1, scap_tinfo.pid); - EXPECT_EQ(1, scap_tinfo.vtid); - EXPECT_EQ(0, scap_tinfo.ptid); - - ASSERT_EQ(SCAP_SUCCESS, - scap_proc_read_thread(platform, proc, 62725, &scap_tinfo, err_buf, false)); - EXPECT_EQ(62725, scap_tinfo.tid); - EXPECT_EQ(62725, scap_tinfo.pid); - EXPECT_EQ(62725, scap_tinfo.vtid); - EXPECT_EQ(1, scap_tinfo.ptid); - - ASSERT_EQ(SCAP_SUCCESS, - scap_proc_read_thread(platform, proc, 62727, &scap_tinfo, err_buf, false)); - EXPECT_EQ(62727, scap_tinfo.tid); - EXPECT_EQ(62725, scap_tinfo.pid); - EXPECT_EQ(62727, scap_tinfo.vtid); - EXPECT_EQ(1, scap_tinfo.ptid); + scap_threadinfo scap_tinfo; + char proc[] = LIBSINSP_TEST_RESOURCES_PATH "/_proc"; + struct stat s = {}; + if(stat(proc, &s) != 0) { + fprintf(stderr, "%s not found, skipping test\n", proc); + FAIL(); + } + + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_type() != PPME_PROCEXIT_1_E && evt->get_tid() > 0; + }; + run_callback_t test = [&](concurrent_object_handle inspector) { return; }; + captured_event_callback_t callback = [&](const callback_param& param) { return; }; + scap_linux_platform* platform; + + before_close_t before_close = [&](sinsp* inspector) { + platform = (scap_linux_platform*)inspector->get_scap_platform(); + }; + ASSERT_NO_FATAL_FAILURE({ + event_capture::run(test, callback, filter, event_capture::do_nothing, before_close); + }); + + ASSERT_EQ(SCAP_SUCCESS, scap_proc_read_thread(platform, proc, 1, &scap_tinfo, err_buf, false)); + + EXPECT_EQ(1, scap_tinfo.tid); + EXPECT_EQ(1, scap_tinfo.pid); + EXPECT_EQ(1, scap_tinfo.vtid); + EXPECT_EQ(0, scap_tinfo.ptid); + + ASSERT_EQ(SCAP_SUCCESS, + scap_proc_read_thread(platform, proc, 62725, &scap_tinfo, err_buf, false)); + EXPECT_EQ(62725, scap_tinfo.tid); + EXPECT_EQ(62725, scap_tinfo.pid); + EXPECT_EQ(62725, scap_tinfo.vtid); + EXPECT_EQ(1, scap_tinfo.ptid); + + ASSERT_EQ(SCAP_SUCCESS, + scap_proc_read_thread(platform, proc, 62727, &scap_tinfo, err_buf, false)); + EXPECT_EQ(62727, scap_tinfo.tid); + EXPECT_EQ(62725, scap_tinfo.pid); + EXPECT_EQ(62727, scap_tinfo.vtid); + EXPECT_EQ(1, scap_tinfo.ptid); } -TEST_F(sys_call_test, thread_lookup_live) -{ +TEST_F(sys_call_test, thread_lookup_live) { char err_buf[SCAP_LASTERR_SIZE]; - scap_threadinfo scap_tinfo; - char proc[] = "/proc"; - - std::unordered_set seen_tids; - - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_type() != PPME_PROCEXIT_1_E && evt->get_tid() > 0; }; - run_callback_t test = [&](concurrent_object_handle inspector) - { - // a very short sleep to gather some events, - // we'll take much longer than this to process them all - usleep(1000); - }; - captured_event_callback_t callback = [&](const callback_param& param) - { - sinsp_evt* e = param.m_evt; - auto tid = e->get_tid(); - if (!seen_tids.insert(tid).second) - { - return; - } - fprintf(stderr, "looking up tid %ld in /proc\n", tid); - // In some cases scap_proc_read_thread can return SCAP_SUCCESS without - // filling in scap_tinfo - if (scap_proc_read_thread((scap_linux_platform*)param.m_inspector->get_scap_platform(), - proc, tid, &scap_tinfo, err_buf, false) == SCAP_SUCCESS) - { - auto tinfo = e->get_thread_info(false); - if (!tinfo) - { - return; - } - EXPECT_NE(0, scap_tinfo.tid); - EXPECT_NE(0, scap_tinfo.pid); - EXPECT_NE(0, scap_tinfo.vtid); - EXPECT_EQ(tinfo->m_tid, scap_tinfo.tid); - EXPECT_EQ(tinfo->m_pid, scap_tinfo.pid); - EXPECT_EQ(tinfo->m_vtid, scap_tinfo.vtid); - // Not testing scap_tinfo.ptid because it can change in between event and lookup - } - }; - - scap_linux_platform *platform; - - before_close_t before_close = [&](sinsp* inspector) - { - // close scap to maintain the num_consumers at exit == 0 assertion - //close_capture(scap, platform); - platform = (scap_linux_platform*)inspector->get_scap_platform(); - }; - ASSERT_NO_FATAL_FAILURE( - { event_capture::run(test, callback, filter, event_capture::do_nothing, before_close); }); - - ASSERT_EQ(SCAP_SUCCESS, - scap_proc_read_thread(platform, proc, getpid(), - &scap_tinfo, err_buf, false)); - EXPECT_EQ(getpid(), scap_tinfo.tid); - EXPECT_EQ(getpid(), scap_tinfo.pid); - EXPECT_EQ(getpid(), scap_tinfo.vtid); - EXPECT_EQ(getppid(), scap_tinfo.ptid); - - ASSERT_EQ(SCAP_SUCCESS, - scap_proc_read_thread(platform, proc, 1, - &scap_tinfo, err_buf, false)); - EXPECT_EQ(1, scap_tinfo.tid); - EXPECT_EQ(1, scap_tinfo.pid); - EXPECT_EQ(1, scap_tinfo.vtid); - EXPECT_EQ(0, scap_tinfo.ptid); + scap_threadinfo scap_tinfo; + char proc[] = "/proc"; + + std::unordered_set seen_tids; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_type() != PPME_PROCEXIT_1_E && evt->get_tid() > 0; + }; + run_callback_t test = [&](concurrent_object_handle inspector) { + // a very short sleep to gather some events, + // we'll take much longer than this to process them all + usleep(1000); + }; + captured_event_callback_t callback = [&](const callback_param& param) { + sinsp_evt* e = param.m_evt; + auto tid = e->get_tid(); + if(!seen_tids.insert(tid).second) { + return; + } + fprintf(stderr, "looking up tid %ld in /proc\n", tid); + // In some cases scap_proc_read_thread can return SCAP_SUCCESS without + // filling in scap_tinfo + if(scap_proc_read_thread((scap_linux_platform*)param.m_inspector->get_scap_platform(), + proc, + tid, + &scap_tinfo, + err_buf, + false) == SCAP_SUCCESS) { + auto tinfo = e->get_thread_info(false); + if(!tinfo) { + return; + } + EXPECT_NE(0, scap_tinfo.tid); + EXPECT_NE(0, scap_tinfo.pid); + EXPECT_NE(0, scap_tinfo.vtid); + EXPECT_EQ(tinfo->m_tid, scap_tinfo.tid); + EXPECT_EQ(tinfo->m_pid, scap_tinfo.pid); + EXPECT_EQ(tinfo->m_vtid, scap_tinfo.vtid); + // Not testing scap_tinfo.ptid because it can change in between event and lookup + } + }; + + scap_linux_platform* platform; + + before_close_t before_close = [&](sinsp* inspector) { + // close scap to maintain the num_consumers at exit == 0 assertion + // close_capture(scap, platform); + platform = (scap_linux_platform*)inspector->get_scap_platform(); + }; + ASSERT_NO_FATAL_FAILURE({ + event_capture::run(test, callback, filter, event_capture::do_nothing, before_close); + }); + + ASSERT_EQ(SCAP_SUCCESS, + scap_proc_read_thread(platform, proc, getpid(), &scap_tinfo, err_buf, false)); + EXPECT_EQ(getpid(), scap_tinfo.tid); + EXPECT_EQ(getpid(), scap_tinfo.pid); + EXPECT_EQ(getpid(), scap_tinfo.vtid); + EXPECT_EQ(getppid(), scap_tinfo.ptid); + + ASSERT_EQ(SCAP_SUCCESS, scap_proc_read_thread(platform, proc, 1, &scap_tinfo, err_buf, false)); + EXPECT_EQ(1, scap_tinfo.tid); + EXPECT_EQ(1, scap_tinfo.pid); + EXPECT_EQ(1, scap_tinfo.vtid); + EXPECT_EQ(0, scap_tinfo.ptid); } -TEST_F(sys_call_test, fd_name_max_path) -{ +TEST_F(sys_call_test, fd_name_max_path) { int callnum = 0; std::string pathname("/"); // Using only 1022 chars otherwise the path will be "/PATH_TOO_LONG". pathname.insert(1, 1021, 'A'); - event_filter_t filter = [&](sinsp_evt* evt) - { - return (0 == strcmp(evt->get_name(), "open") || 0 == strcmp(evt->get_name(), "openat")) - && m_tid_filter(evt); + event_filter_t filter = [&](sinsp_evt* evt) { + return (0 == strcmp(evt->get_name(), "open") || 0 == strcmp(evt->get_name(), "openat")) && + m_tid_filter(evt); }; - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { open(pathname.c_str(), O_RDONLY); }; sinsp_filter_check_list m_filterlist; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { if((0 == strcmp(param.m_evt->get_name(), "open")) || - (0 == strcmp(param.m_evt->get_name(), "openat"))) - { + (0 == strcmp(param.m_evt->get_name(), "openat"))) { std::string output; - sinsp_evt_formatter(param.m_inspector, "*%fd.name", m_filterlist).tostring(param.m_evt, &output); - if(pathname == output) - { + sinsp_evt_formatter(param.m_inspector, "*%fd.name", m_filterlist) + .tostring(param.m_evt, &output); + if(pathname == output) { callnum++; } } diff --git a/test/libsinsp_e2e/sys_call_test.h b/test/libsinsp_e2e/sys_call_test.h index 24aeab65e4..1f1036ad68 100644 --- a/test/libsinsp_e2e/sys_call_test.h +++ b/test/libsinsp_e2e/sys_call_test.h @@ -32,42 +32,35 @@ limitations under the License. uint32_t get_server_address(); -class proc_started_filter -{ - public: - bool operator()(sinsp_evt* evt) - { - if (!m_child_ready && evt->get_type() == PPME_SYSCALL_WRITE_X) - { - auto buffer = evt->get_param_value_str("data", false); - if(buffer.find("SERVER UP") != std::string::npos || - buffer.find("STARTED") != std::string::npos) - { - m_child_ready = true; - } +class proc_started_filter { +public: + bool operator()(sinsp_evt* evt) { + if(!m_child_ready && evt->get_type() == PPME_SYSCALL_WRITE_X) { + auto buffer = evt->get_param_value_str("data", false); + if(buffer.find("SERVER UP") != std::string::npos || + buffer.find("STARTED") != std::string::npos) { + m_child_ready = true; } - return m_child_ready; } + return m_child_ready; + } - private: - bool m_child_ready{false}; +private: + bool m_child_ready{false}; }; -class sys_call_test : public testing::Test -{ +class sys_call_test : public testing::Test { public: static void SetUpTestCase() {} static void TearDownTestCase() {} protected: - void SetUp() - { + void SetUp() { m_tid = getpid(); - m_tid_filter = [this](sinsp_evt* evt) - { - if (evt->get_param_value_str("fd").find(LIBSINSP_TEST_KERNEL_MODULE_NAME) != std::string::npos) - { + m_tid_filter = [this](sinsp_evt* evt) { + if(evt->get_param_value_str("fd").find(LIBSINSP_TEST_KERNEL_MODULE_NAME) != + std::string::npos) { return false; } return evt->get_tid() == m_tid; diff --git a/test/libsinsp_e2e/tcp_client_server.cpp b/test/libsinsp_e2e/tcp_client_server.cpp index d5a4656f02..c5d9625ca2 100644 --- a/test/libsinsp_e2e/tcp_client_server.cpp +++ b/test/libsinsp_e2e/tcp_client_server.cpp @@ -44,10 +44,12 @@ limitations under the License. static const std::string default_payload = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM"; static const std::string http_payload = - "GET / " - "0123456789QWERTYUIOPASDFGHJKLZXCVBNM0123456789QWERTYUIOPASDFGHJKLZXCVBNM0123456789QWERTYUIOPAS" - "DFGHJKLZXCVBNM0123456789QWERTYUIOPASDFGHJKLZXCVBNM0123456789QWERTYUIOPASDFGHJKLZXCVBNM01234567" - "89QWERTYUIOPASDFGHJKLZXCVBNO"; + "GET / " + "0123456789QWERTYUIOPASDFGHJKLZXCVBNM0123456789QWERTYUIOPASDFGHJKLZXCVBNM0123456789QWERTYUI" + "OPAS" + "DFGHJKLZXCVBNM0123456789QWERTYUIOPASDFGHJKLZXCVBNM0123456789QWERTYUIOPASDFGHJKLZXCVBNM0123" + "4567" + "89QWERTYUIOPASDFGHJKLZXCVBNO"; void runtest(iotype iot, const std::string& payload = default_payload, @@ -55,30 +57,26 @@ void runtest(iotype iot, bool use_accept4 = false, uint32_t ntransactions = 1, bool exit_no_close = false, - bool ia32_mode = false) -{ + bool ia32_mode = false) { proc_started_filter client_started_filter; proc_started_filter server_started_filter; - auto stringify_bool = [](bool v) - { - return v ? "true" : "false"; - }; + auto stringify_bool = [](bool v) { return v ? "true" : "false"; }; unsigned callnum = 0; std::string helper_exe = LIBSINSP_TEST_PATH "/test_helper"; - if (ia32_mode) - { + if(ia32_mode) { helper_exe += "_32"; } auto iot_s = std::to_string(iot); auto ntransactions_s = std::to_string(ntransactions); subprocess server_proc(helper_exe, - {"tcp_server", - iot_s.c_str(), - "false", - stringify_bool(use_shutdown), - stringify_bool(use_accept4), - ntransactions_s.c_str(), - stringify_bool(exit_no_close)}, false); + {"tcp_server", + iot_s.c_str(), + "false", + stringify_bool(use_shutdown), + stringify_bool(use_accept4), + ntransactions_s.c_str(), + stringify_bool(exit_no_close)}, + false); int64_t server_pid; int64_t client_pid; struct in_addr server_in_addr; @@ -86,27 +84,23 @@ void runtest(iotype iot, char* server_address = inet_ntoa(server_in_addr); std::string sport; subprocess test_proc(helper_exe, - {"tcp_client", - server_address, - iot_s.c_str(), - payload, - stringify_bool(false), - ntransactions_s, - stringify_bool(exit_no_close)}, false); + {"tcp_client", + server_address, + iot_s.c_str(), + payload, + stringify_bool(false), + ntransactions_s, + stringify_bool(exit_no_close)}, + false); // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { auto tinfo = evt->get_thread_info(false); - if (tinfo && tinfo->m_exe == helper_exe) - { - if (tinfo->m_pid == server_pid) - { + if(tinfo && tinfo->m_exe == helper_exe) { + if(tinfo->m_pid == server_pid) { return server_started_filter(evt); - } - else if (tinfo->m_pid == client_pid) - { + } else if(tinfo->m_pid == client_pid) { return client_started_filter(evt); } } @@ -116,8 +110,7 @@ void runtest(iotype iot, // // INITIALIZATION // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { { std::scoped_lock inspector_handle_lock(inspector_handle); inspector_handle->dynamic_snaplen(true); @@ -134,30 +127,26 @@ void runtest(iotype iot, tee(-1, -1, 0, 0); }; - std::function log_param = [](const callback_param& param) - { + std::function log_param = [](const callback_param& param) { // cerr << param.m_evt->get_name() << endl; }; // // OUTPUT VALIDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { std::string src_addr; std::string src_port; std::string dst_addr; std::string dst_port; sinsp_evt* evt = param.m_evt; - if (evt->get_type() == PPME_SOCKET_CONNECT_X) - { + if(evt->get_type() == PPME_SOCKET_CONNECT_X) { std::string tuple = evt->get_param_value_str("tuple"); EXPECT_NE((sinsp_fdinfo*)NULL, evt->get_fd_info()); - if (evt->get_fd_info()->m_type != SCAP_FD_IPV4_SOCK) - { + if(evt->get_fd_info()->m_type != SCAP_FD_IPV4_SOCK) { // // Skip non-tcp sockets. Python opens unix sockets. // @@ -167,59 +156,43 @@ void runtest(iotype iot, parse_tuple(tuple, src_addr, src_port, dst_addr, dst_port); EXPECT_EQ(server_address, src_addr); - if (sport == "") - { + if(sport == "") { EXPECT_NE("0", src_port); sport = src_port; - } - else - { + } else { EXPECT_EQ(sport, src_port); } EXPECT_EQ(server_address, dst_addr); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, dst_port); } log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SOCKET_LISTEN_E) - { + } else if(evt->get_type() == PPME_SOCKET_LISTEN_E) { EXPECT_EQ("1", evt->get_param_value_str("backlog")); log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SOCKET_LISTEN_X) - { + } else if(evt->get_type() == PPME_SOCKET_LISTEN_X) { EXPECT_EQ("0", evt->get_param_value_str("res")); log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SOCKET_ACCEPT4_6_E) - { + } else if(evt->get_type() == PPME_SOCKET_ACCEPT4_6_E) { EXPECT_EQ("0", evt->get_param_value_str("flags")); - } - else if (evt->get_type() == PPME_SOCKET_ACCEPT_5_X || - evt->get_type() == PPME_SOCKET_ACCEPT4_6_X) - { + } else if(evt->get_type() == PPME_SOCKET_ACCEPT_5_X || + evt->get_type() == PPME_SOCKET_ACCEPT4_6_X) { parse_tuple(evt->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port); EXPECT_EQ(server_address, src_addr); - if (sport == "") - { + if(sport == "") { EXPECT_NE("0", src_port); sport = src_port; - } - else - { + } else { EXPECT_EQ(sport, src_port); } EXPECT_EQ(server_address, dst_addr); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, dst_port); } @@ -227,8 +200,7 @@ void runtest(iotype iot, callnum++; } - if (callnum < 1) - { + if(callnum < 1) { return; } @@ -236,61 +208,54 @@ void runtest(iotype iot, // 32bit uses send() and recv(), while 64bit always uses sendto() and // recvfrom() and sets the address to NULL // - if ((evt->get_type() == PPME_SOCKET_SEND_E || evt->get_type() == PPME_SOCKET_RECV_E || - evt->get_type() == PPME_SOCKET_SENDTO_E || evt->get_type() == PPME_SOCKET_RECVFROM_E || - evt->get_type() == PPME_SYSCALL_READ_E || evt->get_type() == PPME_SYSCALL_WRITE_E || - evt->get_type() == PPME_SYSCALL_READV_E || evt->get_type() == PPME_SYSCALL_WRITEV_E) && - evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK) - { - if (evt->get_type() == PPME_SOCKET_RECVFROM_E) - { - if (evt->get_param_value_str("tuple") != "") - { + if((evt->get_type() == PPME_SOCKET_SEND_E || evt->get_type() == PPME_SOCKET_RECV_E || + evt->get_type() == PPME_SOCKET_SENDTO_E || evt->get_type() == PPME_SOCKET_RECVFROM_E || + evt->get_type() == PPME_SYSCALL_READ_E || evt->get_type() == PPME_SYSCALL_WRITE_E || + evt->get_type() == PPME_SYSCALL_READV_E || evt->get_type() == PPME_SYSCALL_WRITEV_E) && + evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK) { + if(evt->get_type() == PPME_SOCKET_RECVFROM_E) { + if(evt->get_param_value_str("tuple") != "") { EXPECT_EQ("NULL", evt->get_param_value_str("tuple")); } } std::string tuple = evt->get_param_value_str("fd"); - tuple = tuple.substr(tuple.find(">")+1); + tuple = tuple.substr(tuple.find(">") + 1); parse_tuple(tuple, src_addr, src_port, dst_addr, dst_port); EXPECT_EQ(server_address, src_addr); EXPECT_EQ(sport, src_port); EXPECT_EQ(server_address, dst_addr); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, dst_port); } log_param(param); callnum++; - } - else if ((evt->get_type() == PPME_SOCKET_RECV_X || - evt->get_type() == PPME_SOCKET_RECVFROM_X || - evt->get_type() == PPME_SYSCALL_READ_X || - evt->get_type() == PPME_SYSCALL_READV_X || - evt->get_type() == PPME_SYSCALL_WRITEV_X || - evt->get_type() == PPME_SYSCALL_WRITE_X || - evt->get_type() == PPME_SOCKET_SENDTO_X || - evt->get_type() == PPME_SOCKET_SEND_X) && - evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK) - { - if (evt->get_type() == PPME_SOCKET_RECVFROM_X) - { - if(!parse_tuple(evt->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port)) - { + } else if((evt->get_type() == PPME_SOCKET_RECV_X || + evt->get_type() == PPME_SOCKET_RECVFROM_X || + evt->get_type() == PPME_SYSCALL_READ_X || + evt->get_type() == PPME_SYSCALL_READV_X || + evt->get_type() == PPME_SYSCALL_WRITEV_X || + evt->get_type() == PPME_SYSCALL_WRITE_X || + evt->get_type() == PPME_SOCKET_SENDTO_X || + evt->get_type() == PPME_SOCKET_SEND_X) && + evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK) { + if(evt->get_type() == PPME_SOCKET_RECVFROM_X) { + if(!parse_tuple(evt->get_param_value_str("tuple"), + src_addr, + src_port, + dst_addr, + dst_port)) { return; } EXPECT_EQ(server_address, src_addr); EXPECT_EQ(server_address, dst_addr); - if(callnum == 7) - { + if(callnum == 7) { EXPECT_EQ(sport, src_port); EXPECT_EQ(SERVER_PORT_STR, dst_port); - } - else if(callnum == 9) - { + } else if(callnum == 9) { EXPECT_EQ(sport, dst_port); EXPECT_EQ(SERVER_PORT_STR, src_port); } @@ -301,71 +266,69 @@ void runtest(iotype iot, log_param(param); callnum++; } - }; // // OUTPUT VALDATION // - ASSERT_NO_FATAL_FAILURE({event_capture::run(test, callback, filter, event_capture::do_nothing, - event_capture::do_nothing, event_capture::always_continue, 131072, - (uint64_t)60 * 1000 * 1000 * 1000, (uint64_t)60 * 1000 * 1000 * 1000, - SINSP_MODE_LIVE, 3, false); }); - ASSERT_GT(callnum,0); + ASSERT_NO_FATAL_FAILURE({ + event_capture::run(test, + callback, + filter, + event_capture::do_nothing, + event_capture::do_nothing, + event_capture::always_continue, + 131072, + (uint64_t)60 * 1000 * 1000 * 1000, + (uint64_t)60 * 1000 * 1000 * 1000, + SINSP_MODE_LIVE, + 3, + false); + }); + ASSERT_GT(callnum, 0); } -TEST_F(sys_call_test, tcp_client_server) -{ +TEST_F(sys_call_test, tcp_client_server) { runtest(SENDRECEIVE); } -TEST_F(sys_call_test, tcp_client_server_read_write) -{ +TEST_F(sys_call_test, tcp_client_server_read_write) { runtest(READWRITE); } -TEST_F(sys_call_test, tcp_client_server_readv_writev) -{ +TEST_F(sys_call_test, tcp_client_server_readv_writev) { runtest(READVWRITEV); } -TEST_F(sys_call_test, tcp_client_server_shutdown) -{ +TEST_F(sys_call_test, tcp_client_server_shutdown) { runtest(SENDRECEIVE, default_payload, true); } -TEST_F(sys_call_test, tcp_client_server_accept4) -{ +TEST_F(sys_call_test, tcp_client_server_accept4) { runtest(SENDRECEIVE, default_payload, false, true); } -TEST_F(sys_call_test, tcp_client_server_multiple) -{ +TEST_F(sys_call_test, tcp_client_server_multiple) { runtest(SENDRECEIVE, default_payload, false, false, 10); } -TEST_F(sys_call_test, tcp_client_server_noclose) -{ +TEST_F(sys_call_test, tcp_client_server_noclose) { runtest(SENDRECEIVE, default_payload, false, false, 1, true); } -TEST_F(sys_call_test, tcp_client_server_http_snaplen) -{ +TEST_F(sys_call_test, tcp_client_server_http_snaplen) { runtest(SENDRECEIVE, http_payload); } -TEST_F(sys_call_test, tcp_client_server_read_write_http_snaplen) -{ +TEST_F(sys_call_test, tcp_client_server_read_write_http_snaplen) { runtest(READWRITE, http_payload); } -TEST_F(sys_call_test, tcp_client_server_readv_writev_http_snaplen) -{ +TEST_F(sys_call_test, tcp_client_server_readv_writev_http_snaplen) { runtest(READVWRITEV, http_payload); } -TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts) -{ +TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts) { std::thread server_thread; std::thread client_thread; tcp_server server(SENDRECEIVE, true); @@ -377,14 +340,14 @@ TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_tid() == server.get_tid() || evt->get_tid() == client.get_tid(); }; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_tid() == server.get_tid() || evt->get_tid() == client.get_tid(); + }; // // INITIALIZATION // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { server.signal_continue(); client.signal_continue(); server_thread.join(); @@ -394,11 +357,9 @@ TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts) // // OUTPUT VALIDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* evt = param.m_evt; - if (PPME_SYSCALL_CLOSE_X == evt->get_type() && evt->get_tid() == server.get_tid()) - { + if(PPME_SYSCALL_CLOSE_X == evt->get_type() && evt->get_tid() == server.get_tid()) { state = 1; } }; @@ -408,47 +369,49 @@ TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts) server.wait_till_ready(); client.wait_till_ready(); - ASSERT_NO_FATAL_FAILURE({event_capture::run(test, callback, filter, event_capture::do_nothing, - event_capture::do_nothing, event_capture::always_continue, 131072, - (uint64_t)60 * 1000 * 1000 * 1000, (uint64_t)60 * 1000 * 1000 * 1000, - SINSP_MODE_LIVE, 3, false); }); + ASSERT_NO_FATAL_FAILURE({ + event_capture::run(test, + callback, + filter, + event_capture::do_nothing, + event_capture::do_nothing, + event_capture::always_continue, + 131072, + (uint64_t)60 * 1000 * 1000 * 1000, + (uint64_t)60 * 1000 * 1000 * 1000, + SINSP_MODE_LIVE, + 3, + false); + }); ASSERT_EQ(1, state); } - #ifdef __x86_64__ -TEST_F(sys_call_test32, tcp_client_server) -{ +TEST_F(sys_call_test32, tcp_client_server) { runtest(SENDRECEIVE, default_payload, false, false, 1, false, true); } -TEST_F(sys_call_test32, tcp_client_server_read_write) -{ +TEST_F(sys_call_test32, tcp_client_server_read_write) { runtest(READWRITE, default_payload, false, false, 1, false, true); } -TEST_F(sys_call_test32, tcp_client_server_readv_writev) -{ +TEST_F(sys_call_test32, tcp_client_server_readv_writev) { runtest(READVWRITEV, default_payload, false, false, 1, false, true); } -TEST_F(sys_call_test32, tcp_client_server_shutdown) -{ +TEST_F(sys_call_test32, tcp_client_server_shutdown) { runtest(SENDRECEIVE, default_payload, true, false, 1, false, true); } -TEST_F(sys_call_test32, tcp_client_server_accept4) -{ +TEST_F(sys_call_test32, tcp_client_server_accept4) { runtest(SENDRECEIVE, default_payload, false, true, 1, false, true); } -TEST_F(sys_call_test32, tcp_client_server_multiple) -{ +TEST_F(sys_call_test32, tcp_client_server_multiple) { runtest(SENDRECEIVE, default_payload, false, false, 10, false, true); } -TEST_F(sys_call_test32, tcp_client_server_noclose) -{ +TEST_F(sys_call_test32, tcp_client_server_noclose) { runtest(SENDRECEIVE, default_payload, false, false, 1, true, true); } #endif diff --git a/test/libsinsp_e2e/tcp_client_server.h b/test/libsinsp_e2e/tcp_client_server.h index 0f4cd26605..4a4ae96a1a 100644 --- a/test/libsinsp_e2e/tcp_client_server.h +++ b/test/libsinsp_e2e/tcp_client_server.h @@ -45,31 +45,20 @@ limitations under the License. #define SERVER_PORT_STR "3555" #define FALSE 0 -typedef enum iotype -{ - READWRITE, - SENDRECEIVE, - READVWRITEV -} iotype; - -class std_event -{ +typedef enum iotype { READWRITE, SENDRECEIVE, READVWRITEV } iotype; + +class std_event { public: - void set() - { + void set() { std::lock_guard lock(m_mutex); m_is_set = true; m_cond.notify_one(); } - void wait() - { + void wait() { std::unique_lock lock(m_mutex); - if (m_is_set) - { + if(m_is_set) { return; - } - else - { + } else { m_cond.wait(lock, [this]() { return m_is_set; }); } } @@ -80,16 +69,14 @@ class std_event bool m_is_set{false}; }; -class tcp_server -{ +class tcp_server { public: tcp_server(iotype iot, bool wait_for_signal_to_continue = false, bool use_shutdown = false, bool use_accept4 = false, uint32_t ntransactions = 1, - bool exit_no_close = false) - { + bool exit_no_close = false) { m_iot = iot; m_wait_for_signal_to_continue = wait_for_signal_to_continue; m_use_shutdown = use_shutdown; @@ -98,8 +85,7 @@ class tcp_server m_exit_no_close = exit_no_close; } - void run() - { + void run() { int servSock; int clntSock; struct sockaddr_in server_address; @@ -111,8 +97,7 @@ class tcp_server m_tid = syscall(SYS_gettid); /* Create socket for incoming connections */ - if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) - { + if((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { perror("socket() failed"); return; } @@ -124,24 +109,21 @@ class tcp_server server_address.sin_port = htons(port); /* Local port */ int yes = 1; - if (setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) - { + if(setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { #ifdef FAIL FAIL() << "setsockopt() failed"; #endif } /* Bind to the local address */ - if (::bind(servSock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) - { + if(::bind(servSock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) { #ifdef FAIL FAIL() << "bind() failed"; #endif return; } /* Mark the socket so it will listen for incoming connections */ - if (listen(servSock, 1) < 0) - { + if(listen(servSock, 1) < 0) { close(servSock); #ifdef FAIL FAIL() << "listen() failed"; @@ -149,30 +131,25 @@ class tcp_server return; } std::cout << "SERVER UP" << std::endl; - do - { + do { /* Set the size of the in-out parameter */ client_len = sizeof(client_address); signal_ready(); /* Wait for a client to connect */ - if (m_use_accept4) - { - if ((clntSock = - accept4(servSock, (struct sockaddr*)&client_address, &client_len, 0)) < 0) - { + if(m_use_accept4) { + if((clntSock = + accept4(servSock, (struct sockaddr*)&client_address, &client_len, 0)) < + 0) { close(servSock); #ifdef FAIL FAIL() << "accept() failed"; #endif break; } - } - else - { - if ((clntSock = accept(servSock, (struct sockaddr*)&client_address, &client_len)) < - 0) - { + } else { + if((clntSock = accept(servSock, (struct sockaddr*)&client_address, &client_len)) < + 0) { close(servSock); #ifdef FAIL FAIL() << "accept() failed"; @@ -185,38 +162,30 @@ class tcp_server wait_for_continue(); char echoBuffer[1024]; /* Buffer for echo string */ int recvMsgSize; /* Size of received message */ - for (j = 0; j < m_ntransactions; j++) - { - if (m_iot == SENDRECEIVE) - { - if ((recvMsgSize = recv(clntSock, echoBuffer, sizeof(echoBuffer), 0)) < 0) - { + for(j = 0; j < m_ntransactions; j++) { + if(m_iot == SENDRECEIVE) { + if((recvMsgSize = recv(clntSock, echoBuffer, sizeof(echoBuffer), 0)) < 0) { #ifdef FAIL FAIL() << "recv() failed"; #endif break; } - if (send(clntSock, echoBuffer, recvMsgSize, 0) != recvMsgSize) - { + if(send(clntSock, echoBuffer, recvMsgSize, 0) != recvMsgSize) { #ifdef FAIL FAIL() << "send() failed"; #endif break; } - } - else if (m_iot == READWRITE || m_iot == READVWRITEV) - { - if ((recvMsgSize = read(clntSock, echoBuffer, sizeof(echoBuffer))) < 0) - { + } else if(m_iot == READWRITE || m_iot == READVWRITEV) { + if((recvMsgSize = read(clntSock, echoBuffer, sizeof(echoBuffer))) < 0) { #ifdef FAIL FAIL() << "recv() failed"; #endif break; } - if (write(clntSock, echoBuffer, recvMsgSize) != recvMsgSize) - { + if(write(clntSock, echoBuffer, recvMsgSize) != recvMsgSize) { #ifdef FAIL FAIL() << "send() failed"; #endif @@ -225,32 +194,25 @@ class tcp_server } } - if (m_exit_no_close) - { + if(m_exit_no_close) { return; } - if (m_use_shutdown) - { + if(m_use_shutdown) { #ifdef ASSERT_EQ ASSERT_EQ(0, shutdown(clntSock, SHUT_WR)); #endif - } - else - { + } else { close(clntSock); /* Close client socket */ } break; - } while (0); + } while(0); - if (m_use_shutdown) - { + if(m_use_shutdown) { #ifdef ASSERT_EQ ASSERT_EQ(0, shutdown(servSock, SHUT_RDWR)); #endif - } - else - { + } else { close(servSock); } } @@ -264,10 +226,8 @@ class tcp_server private: void signal_ready() { m_ready.set(); } - void wait_for_continue() - { - if (m_wait_for_signal_to_continue) - { + void wait_for_continue() { + if(m_wait_for_signal_to_continue) { m_continue.wait(); } } @@ -283,16 +243,14 @@ class tcp_server bool m_exit_no_close; }; -class tcp_client -{ +class tcp_client { public: tcp_client(uint32_t server_ip_address, iotype iot, const std::string& payload = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM", bool on_thread = false, uint32_t ntransactions = 1, - bool exit_no_close = false) - { + bool exit_no_close = false) { m_server_ip_address = server_ip_address; m_iot = iot; m_payload = payload; @@ -301,8 +259,7 @@ class tcp_client m_exit_no_close = exit_no_close; } - void run() - { + void run() { int sock; struct sockaddr_in server_address; char buffer[m_payload.size() + 1]; @@ -313,8 +270,7 @@ class tcp_client m_tid = syscall(SYS_gettid); /* Create a reliable, stream socket using TCP */ - if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) - { + if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { #ifdef FAIL FAIL() << "socket() failed"; #endif @@ -329,8 +285,7 @@ class tcp_client server_address.sin_port = htons(port); /* Server port */ /* Establish the connection to the server */ - if (connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) - { + if(connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) { #ifdef FAIL FAIL() << "connect() failed"; #endif @@ -340,14 +295,11 @@ class tcp_client signal_ready(); wait_for_continue(); - for (j = 0; j < m_ntransactions; j++) - { + for(j = 0; j < m_ntransactions; j++) { /* Send the string to the server */ - if (m_iot == SENDRECEIVE) - { - if (send(sock, m_payload.c_str(), m_payload.length(), 0) != - (ssize_t)m_payload.length()) - { + if(m_iot == SENDRECEIVE) { + if(send(sock, m_payload.c_str(), m_payload.length(), 0) != + (ssize_t)m_payload.length()) { close(sock); #ifdef FAIL FAIL() << "send() sent a different number of bytes than expected"; @@ -355,8 +307,7 @@ class tcp_client return; } - if ((bytes_received = recv(sock, buffer, m_payload.length(), 0)) <= 0) - { + if((bytes_received = recv(sock, buffer, m_payload.length(), 0)) <= 0) { close(sock); #ifdef FAIL FAIL() << "recv() failed or connection closed prematurely"; @@ -368,12 +319,9 @@ class tcp_client #ifdef ASSERT_STREQ ASSERT_STREQ(m_payload.c_str(), buffer); #endif - } - else if (m_iot == READWRITE) - { - if (write(sock, m_payload.c_str(), m_payload.length()) != - (ssize_t)m_payload.length()) - { + } else if(m_iot == READWRITE) { + if(write(sock, m_payload.c_str(), m_payload.length()) != + (ssize_t)m_payload.length()) { close(sock); #ifdef FAIL FAIL() << "send() sent a different number of bytes than expected"; @@ -381,8 +329,7 @@ class tcp_client return; } - if ((bytes_received = read(sock, buffer, m_payload.length())) <= 0) - { + if((bytes_received = read(sock, buffer, m_payload.length())) <= 0) { close(sock); #ifdef FAIL FAIL() << "recv() failed or connection closed prematurely"; @@ -394,9 +341,7 @@ class tcp_client #ifdef ASSERT_STREQ ASSERT_STREQ(m_payload.c_str(), buffer); #endif - } - else if (m_iot == READVWRITEV) - { + } else if(m_iot == READVWRITEV) { int wv_count; char msg1[m_payload.length() / 3 + 1]; char msg2[m_payload.length() / 3 + 1]; @@ -421,8 +366,7 @@ class tcp_client wv[2].iov_len = m_payload.length() / 3; wv_count = 3; - if (writev(sock, wv, wv_count) != (ssize_t)m_payload.length()) - { + if(writev(sock, wv, wv_count) != (ssize_t)m_payload.length()) { close(sock); #ifdef FAIL FAIL() << "send() sent a different number of bytes than expected"; @@ -430,8 +374,7 @@ class tcp_client return; } - if ((bytes_received = readv(sock, wv, wv_count)) <= 0) - { + if((bytes_received = readv(sock, wv, wv_count)) <= 0) { close(sock); #ifdef FAIL FAIL() << "recv() failed or connection closed prematurely"; @@ -441,8 +384,7 @@ class tcp_client } } - if (m_exit_no_close) - { + if(m_exit_no_close) { return; } @@ -458,10 +400,8 @@ class tcp_client private: void signal_ready() { m_ready.set(); } - void wait_for_continue() - { - if (m_on_thread) - { + void wait_for_continue() { + if(m_on_thread) { m_continue.wait(); } } diff --git a/test/libsinsp_e2e/tcp_client_server_ipv4_mapped.cpp b/test/libsinsp_e2e/tcp_client_server_ipv4_mapped.cpp index 32cf874b99..c05561014f 100644 --- a/test/libsinsp_e2e/tcp_client_server_ipv4_mapped.cpp +++ b/test/libsinsp_e2e/tcp_client_server_ipv4_mapped.cpp @@ -49,16 +49,14 @@ limitations under the License. #define BUFFER_LENGTH sizeof(PAYLOAD) #define FALSE 0 -class tcp_server_ipv4m -{ +class tcp_server_ipv4m { public: tcp_server_ipv4m(iotype iot, bool wait_for_signal_to_continue = false, bool use_shutdown = false, bool use_accept4 = false, - uint32_t ntransactions = 1, - bool exit_no_close = false) - { + uint32_t ntransactions = 1, + bool exit_no_close = false) { m_iot = iot; m_wait_for_signal_to_continue = wait_for_signal_to_continue; m_use_shutdown = use_shutdown; @@ -67,8 +65,7 @@ class tcp_server_ipv4m m_exit_no_close = exit_no_close; } - void run() - { + void run() { int servSock; int clntSock; struct sockaddr_in6 server_address; @@ -81,8 +78,7 @@ class tcp_server_ipv4m m_tid = syscall(SYS_gettid); /* Create socket for incoming connections */ - if ((servSock = socket(AF_INET6, SOCK_STREAM, 0)) < 0) - { + if((servSock = socket(AF_INET6, SOCK_STREAM, 0)) < 0) { perror("socket() failed"); return; } @@ -94,47 +90,39 @@ class tcp_server_ipv4m server_address.sin6_addr = in6addr_any; int yes = 1; - if (setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) - { + if(setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { FAIL() << "setsockopt() failed"; } /* Bind to the local address */ - if (::bind(servSock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) - { + if(::bind(servSock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) { perror("bind() failed"); FAIL(); return; } /* Mark the socket so it will listen for incoming connections */ - if (listen(servSock, 1) < 0) - { + if(listen(servSock, 1) < 0) { close(servSock); FAIL() << "listen() failed"; return; } - do - { + do { /* Set the size of the in-out parameter */ client_len = sizeof(client_address); signal_ready(); /* Wait for a client to connect */ - if (m_use_accept4) - { - if ((clntSock = - accept4(servSock, (struct sockaddr*)&client_address, &client_len, 0)) < 0) - { + if(m_use_accept4) { + if((clntSock = + accept4(servSock, (struct sockaddr*)&client_address, &client_len, 0)) < + 0) { close(servSock); FAIL() << "accept() failed"; break; } - } - else - { - if ((clntSock = accept(servSock, (struct sockaddr*)&client_address, &client_len)) < - 0) - { + } else { + if((clntSock = accept(servSock, (struct sockaddr*)&client_address, &client_len)) < + 0) { close(servSock); FAIL() << "accept() failed"; break; @@ -145,60 +133,45 @@ class tcp_server_ipv4m wait_for_continue(); char echoBuffer[BUFFER_LENGTH]; /* Buffer for echo string */ int recvMsgSize; /* Size of received message */ - for (j = 0; j < m_ntransactions; j++) - { - if (m_iot == SENDRECEIVE) - { - if ((recvMsgSize = recv(clntSock, echoBuffer, BUFFER_LENGTH, 0)) < 0) - { + for(j = 0; j < m_ntransactions; j++) { + if(m_iot == SENDRECEIVE) { + if((recvMsgSize = recv(clntSock, echoBuffer, BUFFER_LENGTH, 0)) < 0) { FAIL() << "recv() failed"; break; } - if (send(clntSock, echoBuffer, recvMsgSize, 0) != recvMsgSize) - { + if(send(clntSock, echoBuffer, recvMsgSize, 0) != recvMsgSize) { FAIL() << "send() failed"; break; } - } - else if (m_iot == READWRITE || m_iot == READVWRITEV) - { - if ((recvMsgSize = read(clntSock, echoBuffer, BUFFER_LENGTH)) < 0) - { + } else if(m_iot == READWRITE || m_iot == READVWRITEV) { + if((recvMsgSize = read(clntSock, echoBuffer, BUFFER_LENGTH)) < 0) { FAIL() << "recv() failed"; break; } - if (write(clntSock, echoBuffer, recvMsgSize) != recvMsgSize) - { + if(write(clntSock, echoBuffer, recvMsgSize) != recvMsgSize) { FAIL() << "send() failed"; break; } } } - if (m_exit_no_close) - { + if(m_exit_no_close) { return; } - if (m_use_shutdown) - { + if(m_use_shutdown) { ASSERT_EQ(0, shutdown(clntSock, SHUT_WR)); - } - else - { + } else { close(clntSock); /* Close client socket */ } break; - } while (0); + } while(0); - if (m_use_shutdown) - { + if(m_use_shutdown) { ASSERT_EQ(0, shutdown(servSock, SHUT_RDWR)); - } - else - { + } else { close(servSock); } } @@ -212,10 +185,8 @@ class tcp_server_ipv4m private: void signal_ready() { m_ready.set(); } - void wait_for_continue() - { - if (m_wait_for_signal_to_continue) - { + void wait_for_continue() { + if(m_wait_for_signal_to_continue) { m_continue.wait(); } } @@ -231,15 +202,13 @@ class tcp_server_ipv4m bool m_exit_no_close; }; -class tcp_client_ipv4m -{ +class tcp_client_ipv4m { public: tcp_client_ipv4m(uint32_t server_ip_address, iotype iot, bool on_thread = false, uint32_t ntransactions = 1, - bool exit_no_close = false) - { + bool exit_no_close = false) { m_server_ip_address = server_ip_address; m_iot = iot; m_on_thread = on_thread; @@ -247,8 +216,7 @@ class tcp_client_ipv4m m_exit_no_close = exit_no_close; } - void run() - { + void run() { int sock; struct sockaddr_in server_address; char buffer[BUFFER_LENGTH]; @@ -260,8 +228,7 @@ class tcp_client_ipv4m m_tid = syscall(SYS_gettid); /* Create a reliable, stream socket using TCP */ - if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) - { + if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { FAIL() << "socket() failed"; return; } @@ -273,8 +240,7 @@ class tcp_client_ipv4m server_address.sin_port = htons(port); /* Server port */ /* Establish the connection to the server */ - if (connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) - { + if(connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) { perror("connect() failed"); FAIL(); return; @@ -283,20 +249,16 @@ class tcp_client_ipv4m wait_for_continue(); payload_length = strlen(PAYLOAD); /* Determine input length */ - for (j = 0; j < m_ntransactions; j++) - { + for(j = 0; j < m_ntransactions; j++) { /* Send the string to the server */ - if (m_iot == SENDRECEIVE) - { - if (send(sock, PAYLOAD, payload_length, 0) != payload_length) - { + if(m_iot == SENDRECEIVE) { + if(send(sock, PAYLOAD, payload_length, 0) != payload_length) { close(sock); FAIL() << "send() sent a different number of bytes than expected"; return; } - if ((bytes_received = recv(sock, buffer, BUFFER_LENGTH - 1, 0)) <= 0) - { + if((bytes_received = recv(sock, buffer, BUFFER_LENGTH - 1, 0)) <= 0) { close(sock); FAIL() << "recv() failed or connection closed prematurely"; return; @@ -304,18 +266,14 @@ class tcp_client_ipv4m buffer[bytes_received] = '\0'; /* Terminate the string! */ ASSERT_STREQ(PAYLOAD, buffer); - } - else if (m_iot == READWRITE) - { - if (write(sock, PAYLOAD, payload_length) != payload_length) - { + } else if(m_iot == READWRITE) { + if(write(sock, PAYLOAD, payload_length) != payload_length) { close(sock); FAIL() << "send() sent a different number of bytes than expected"; return; } - if ((bytes_received = read(sock, buffer, BUFFER_LENGTH - 1)) <= 0) - { + if((bytes_received = read(sock, buffer, BUFFER_LENGTH - 1)) <= 0) { close(sock); FAIL() << "recv() failed or connection closed prematurely"; return; @@ -323,9 +281,7 @@ class tcp_client_ipv4m buffer[bytes_received] = '\0'; /* Terminate the string! */ ASSERT_STREQ(PAYLOAD, buffer); - } - else if (m_iot == READVWRITEV) - { + } else if(m_iot == READVWRITEV) { std::string ps(PAYLOAD); int wv_count; char msg1[BUFFER_LENGTH / 3 + 1]; @@ -349,15 +305,13 @@ class tcp_client_ipv4m wv[2].iov_len = BUFFER_LENGTH / 3; wv_count = 3; - if (writev(sock, wv, wv_count) != payload_length) - { + if(writev(sock, wv, wv_count) != payload_length) { close(sock); FAIL() << "send() sent a different number of bytes than expected"; return; } - if ((bytes_received = readv(sock, wv, wv_count)) <= 0) - { + if((bytes_received = readv(sock, wv, wv_count)) <= 0) { close(sock); FAIL() << "recv() failed or connection closed prematurely"; return; @@ -365,8 +319,7 @@ class tcp_client_ipv4m } } - if (m_exit_no_close) - { + if(m_exit_no_close) { return; } @@ -382,10 +335,8 @@ class tcp_client_ipv4m private: void signal_ready() { m_ready.set(); } - void wait_for_continue() - { - if (m_on_thread) - { + void wait_for_continue() { + if(m_on_thread) { m_continue.wait(); } } @@ -404,11 +355,15 @@ void runtest_ipv4m(iotype iot, bool use_shutdown = false, bool use_accept4 = false, uint32_t ntransactions = 1, - bool exit_no_close = false) -{ + bool exit_no_close = false) { int callnum = 0; std::thread server_thread; - std::shared_ptr server = std::make_shared(iot, false, use_shutdown, use_accept4, ntransactions, exit_no_close); + std::shared_ptr server = std::make_shared(iot, + false, + use_shutdown, + use_accept4, + ntransactions, + exit_no_close); uint32_t server_ip_address = get_server_address(); @@ -424,16 +379,14 @@ void runtest_ipv4m(iotype iot, // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return evt->get_tid() == server->get_tid() || evt->get_tid() == tid; }; // // INITIALIZATION // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { server_thread = std::thread(&tcp_server_ipv4m::run, server); server->wait_till_ready(); @@ -449,34 +402,29 @@ void runtest_ipv4m(iotype iot, tee(-1, -1, 0, 0); }; - std::function log_param = [](const callback_param& param) - { - //std::cerr << param.m_evt->get_name() << std::endl; + std::function log_param = [](const callback_param& param) { + // std::cerr << param.m_evt->get_name() << std::endl; }; // // OUTPUT VALIDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { std::string src_addr; std::string src_port; std::string dst_addr; std::string dst_port; sinsp_evt* evt = param.m_evt; - if (evt->get_type() == PPME_SOCKET_CONNECT_X) - { + if(evt->get_type() == PPME_SOCKET_CONNECT_X) { std::string tuple = evt->get_param_value_str("tuple"); - if(!parse_tuple(tuple, src_addr, src_port, dst_addr, dst_port)) - { + if(!parse_tuple(tuple, src_addr, src_port, dst_addr, dst_port)) { return; } EXPECT_NE((sinsp_fdinfo*)NULL, evt->get_fd_info()); - if (evt->get_fd_info()->m_type != SCAP_FD_IPV4_SOCK) - { + if(evt->get_fd_info()->m_type != SCAP_FD_IPV4_SOCK) { // // Skip non-tcp sockets. Python opens unix sockets // to god knows what. @@ -485,62 +433,49 @@ void runtest_ipv4m(iotype iot, } EXPECT_EQ(server_address, src_addr); - if (sport == "") - { + if(sport == "") { EXPECT_NE("0", src_port); sport = src_port; - } - else - { + } else { EXPECT_EQ(sport, src_port); } EXPECT_EQ(server_address, dst_addr); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, dst_port); } log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SOCKET_LISTEN_E) - { + } else if(evt->get_type() == PPME_SOCKET_LISTEN_E) { EXPECT_EQ("1", evt->get_param_value_str("backlog")); log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SOCKET_LISTEN_X) - { + } else if(evt->get_type() == PPME_SOCKET_LISTEN_X) { EXPECT_EQ("0", evt->get_param_value_str("res")); log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SOCKET_ACCEPT4_6_E) - { + } else if(evt->get_type() == PPME_SOCKET_ACCEPT4_6_E) { EXPECT_EQ("0", evt->get_param_value_str("flags")); - } - else if (evt->get_type() == PPME_SOCKET_ACCEPT_5_X || - evt->get_type() == PPME_SOCKET_ACCEPT4_6_X) - { - if(!parse_tuple(evt->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port)) - { + } else if(evt->get_type() == PPME_SOCKET_ACCEPT_5_X || + evt->get_type() == PPME_SOCKET_ACCEPT4_6_X) { + if(!parse_tuple(evt->get_param_value_str("tuple"), + src_addr, + src_port, + dst_addr, + dst_port)) { return; } EXPECT_EQ(server_address, src_addr); - if (sport == "") - { + if(sport == "") { EXPECT_NE("0", src_port); sport = src_port; - } - else - { + } else { EXPECT_EQ(sport, src_port); } EXPECT_EQ(server_address, dst_addr); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, dst_port); } @@ -548,8 +483,7 @@ void runtest_ipv4m(iotype iot, callnum++; } - if (callnum < 1) - { + if(callnum < 1) { return; } @@ -557,23 +491,19 @@ void runtest_ipv4m(iotype iot, // 32bit uses send() and recv(), while 64bit always uses sendto() and // recvfrom() and sets the address to NULL // - if (evt->get_type() == PPME_SOCKET_SEND_E || evt->get_type() == PPME_SOCKET_RECV_E || - evt->get_type() == PPME_SOCKET_SENDTO_E || evt->get_type() == PPME_SOCKET_RECVFROM_E || - evt->get_type() == PPME_SYSCALL_READ_E || evt->get_type() == PPME_SYSCALL_WRITE_E || - evt->get_type() == PPME_SYSCALL_READV_E || evt->get_type() == PPME_SYSCALL_WRITEV_E) - { - if (evt->get_type() == PPME_SOCKET_RECVFROM_E) - { - if (evt->get_param_value_str("tuple") != "") - { + if(evt->get_type() == PPME_SOCKET_SEND_E || evt->get_type() == PPME_SOCKET_RECV_E || + evt->get_type() == PPME_SOCKET_SENDTO_E || evt->get_type() == PPME_SOCKET_RECVFROM_E || + evt->get_type() == PPME_SYSCALL_READ_E || evt->get_type() == PPME_SYSCALL_WRITE_E || + evt->get_type() == PPME_SYSCALL_READV_E || evt->get_type() == PPME_SYSCALL_WRITEV_E) { + if(evt->get_type() == PPME_SOCKET_RECVFROM_E) { + if(evt->get_param_value_str("tuple") != "") { EXPECT_EQ("NULL", evt->get_param_value_str("tuple")); } } std::string tuple = evt->get_param_value_str("fd"); - tuple = tuple.substr(tuple.find(">")+1); - if(!parse_tuple(tuple, src_addr, src_port, dst_addr, dst_port)) - { + tuple = tuple.substr(tuple.find(">") + 1); + if(!parse_tuple(tuple, src_addr, src_port, dst_addr, dst_port)) { return; } @@ -581,48 +511,38 @@ void runtest_ipv4m(iotype iot, EXPECT_EQ(sport, src_port); EXPECT_EQ(server_address, dst_addr); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, dst_port); } log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SOCKET_RECV_X || - evt->get_type() == PPME_SOCKET_RECVFROM_X || - evt->get_type() == PPME_SYSCALL_READ_X) - { - if (evt->get_type() == PPME_SOCKET_RECVFROM_X) - { - if(!parse_tuple(evt->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port)) - { + } else if(evt->get_type() == PPME_SOCKET_RECV_X || + evt->get_type() == PPME_SOCKET_RECVFROM_X || + evt->get_type() == PPME_SYSCALL_READ_X) { + if(evt->get_type() == PPME_SOCKET_RECVFROM_X) { + if(!parse_tuple(evt->get_param_value_str("tuple"), + src_addr, + src_port, + dst_addr, + dst_port)) { return; } EXPECT_EQ(server_address, src_addr); EXPECT_EQ(server_address, dst_addr); - if(callnum == 7) - { + if(callnum == 7) { EXPECT_EQ(sport, src_port); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, dst_port); - } - else - { + } else { EXPECT_EQ(SERVER_PORT_NOCLOSE_STR, dst_port); } - } - else if(callnum == 9) - { + } else if(callnum == 9) { EXPECT_EQ(sport, dst_port); - if (!exit_no_close) - { + if(!exit_no_close) { EXPECT_EQ(SERVER_PORT_STR, src_port); - } - else - { + } else { EXPECT_EQ(SERVER_PORT_NOCLOSE_STR, src_port); } } @@ -632,9 +552,7 @@ void runtest_ipv4m(iotype iot, log_param(param); callnum++; - } - else if (evt->get_type() == PPME_SYSCALL_READV_X) - { + } else if(evt->get_type() == PPME_SYSCALL_READV_X) { std::string ds = evt->get_param_value_str("data"); EXPECT_EQ(ds, evt->get_param_value_str("data")); @@ -643,25 +561,20 @@ void runtest_ipv4m(iotype iot, callnum++; } - if ((PPME_SYSCALL_CLOSE_X == evt->get_type() || - PPME_SOCKET_SHUTDOWN_X == evt->get_type()) && - 0 == state && evt->get_tid() == server->get_tid()) - { - if (exit_no_close) - { + if((PPME_SYSCALL_CLOSE_X == evt->get_type() || PPME_SOCKET_SHUTDOWN_X == evt->get_type()) && + 0 == state && evt->get_tid() == server->get_tid()) { + if(exit_no_close) { FAIL(); } state = 1; } - if (!(use_shutdown || exit_no_close)) - { - if (evt->get_type() == PPME_GENERIC_E) - { - if (std::stoll(evt->get_param_value_str("ID", false)) == PPM_SC_TEE) - { - sinsp_threadinfo* ti = param.m_inspector->get_thread_ref(server->get_tid(), false, true).get(); + if(!(use_shutdown || exit_no_close)) { + if(evt->get_type() == PPME_GENERIC_E) { + if(std::stoll(evt->get_param_value_str("ID", false)) == PPM_SC_TEE) { + sinsp_threadinfo* ti = + param.m_inspector->get_thread_ref(server->get_tid(), false, true).get(); ASSERT_NE(ti, nullptr); ti = param.m_inspector->get_thread_ref(ctid, false, true).get(); ASSERT_NE(ti, nullptr); @@ -670,49 +583,51 @@ void runtest_ipv4m(iotype iot, } }; - ASSERT_NO_FATAL_FAILURE({event_capture::run(test, callback, filter, event_capture::do_nothing, - event_capture::do_nothing, event_capture::always_continue, 131072, - (uint64_t)60 * 1000 * 1000 * 1000, (uint64_t)60 * 1000 * 1000 * 1000, - SINSP_MODE_LIVE, 3, false); }); + ASSERT_NO_FATAL_FAILURE({ + event_capture::run(test, + callback, + filter, + event_capture::do_nothing, + event_capture::do_nothing, + event_capture::always_continue, + 131072, + (uint64_t)60 * 1000 * 1000 * 1000, + (uint64_t)60 * 1000 * 1000 * 1000, + SINSP_MODE_LIVE, + 3, + false); + }); } -TEST_F(sys_call_test, tcp_client_server_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_ipv4m) { runtest_ipv4m(SENDRECEIVE); } -TEST_F(sys_call_test, tcp_client_server_read_write_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_read_write_ipv4m) { runtest_ipv4m(READWRITE); } -TEST_F(sys_call_test, tcp_client_server_readv_writev_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_readv_writev_ipv4m) { runtest_ipv4m(READVWRITEV); } -TEST_F(sys_call_test, tcp_client_server_shutdown_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_shutdown_ipv4m) { runtest_ipv4m(SENDRECEIVE, true); } -TEST_F(sys_call_test, tcp_client_server_accept4_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_accept4_ipv4m) { runtest_ipv4m(SENDRECEIVE, false, true); } -TEST_F(sys_call_test, tcp_client_server_multiple_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_multiple_ipv4m) { runtest_ipv4m(SENDRECEIVE, false, false, 10); } -TEST_F(sys_call_test, tcp_client_server_noclose_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_noclose_ipv4m) { runtest_ipv4m(SENDRECEIVE, false, false, 1, true); } -TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts_ipv4m) -{ +TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts_ipv4m) { std::thread server_thread; std::thread client_thread; tcp_server_ipv4m server(SENDRECEIVE, true); @@ -724,14 +639,14 @@ TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts_ // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { return evt->get_tid() == server.get_tid() || evt->get_tid() == client.get_tid(); }; + event_filter_t filter = [&](sinsp_evt* evt) { + return evt->get_tid() == server.get_tid() || evt->get_tid() == client.get_tid(); + }; // // INITIALIZATION // - run_callback_t test = [&](concurrent_object_handle inspector) - { + run_callback_t test = [&](concurrent_object_handle inspector) { server.signal_continue(); client.signal_continue(); server_thread.join(); @@ -741,11 +656,9 @@ TEST_F(sys_call_test, tcp_client_server_with_connection_before_capturing_starts_ // // OUTPUT VALIDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* evt = param.m_evt; - if (PPME_SYSCALL_CLOSE_X == evt->get_type() && evt->get_tid() == server.get_tid()) - { + if(PPME_SYSCALL_CLOSE_X == evt->get_type() && evt->get_tid() == server.get_tid()) { state = 1; } }; diff --git a/test/libsinsp_e2e/test_helper.cpp b/test/libsinsp_e2e/test_helper.cpp index c9ae1ca7e5..11764f22c7 100644 --- a/test/libsinsp_e2e/test_helper.cpp +++ b/test/libsinsp_e2e/test_helper.cpp @@ -52,8 +52,7 @@ limitations under the License. using namespace std; -void proc_mgmt(const vector& args) -{ +void proc_mgmt(const vector& args) { auto filename = args.at(0).c_str(); static const char DATA[] = "ABCDEFGHI"; unlink(filename); @@ -65,8 +64,7 @@ void proc_mgmt(const vector& args) unlink(filename); } -void mmap_test(const vector& args) -{ +void mmap_test(const vector& args) { int errno2; void* p; @@ -89,40 +87,32 @@ void mmap_test(const vector& args) fflush(stdout); } -bool str_to_bool(const string& s) -{ - if (s == "true") - { +bool str_to_bool(const string& s) { + if(s == "true") { return true; - } - else - { + } else { return false; } } -void pread_pwrite(const vector& args) -{ +void pread_pwrite(const vector& args) { char buf[32]; const auto FILENAME = "test_pread_pwrite"; int fd = creat(FILENAME, S_IRWXU); - if (fd < 0) - { + if(fd < 0) { cerr << "ERROR (creat)" << endl; return; } auto ret = write(fd, "ABCDEFGH", sizeof("ABCDEFGH") - 1); assert(ret > 0); - if (ret <= 0) - { + if(ret <= 0) { cerr << "ERROR (write)" << endl; } ret = pwrite(fd, "QWER", sizeof("QWER") - 1, 4); assert(ret > 0); - if (ret <= 0) - { + if(ret <= 0) { cerr << "ERROR (pwrite)" << endl; } @@ -135,22 +125,19 @@ void pread_pwrite(const vector& args) cout << (pwrite64_succeeded ? 1 : 0) << endl; - if (pread64(fd, buf, 32, 987654321) < 0) - { + if(pread64(fd, buf, 32, 987654321) < 0) { cerr << "ERROR (pread64)" << endl; } close(fd); int fd1 = open(FILENAME, O_RDONLY); - if (fd1 < 0) - { + if(fd1 < 0) { cerr << "ERROR (open)" << endl; return; } - if (pread(fd1, buf, 4, 4) < 0) - { + if(pread(fd1, buf, 4, 4) < 0) { cerr << "ERROR (pread)" << endl; } @@ -159,8 +146,7 @@ void pread_pwrite(const vector& args) unlink(FILENAME); } -void preadv_pwritev(const vector& args) -{ +void preadv_pwritev(const vector& args) { const auto FILENAME = "test_preadv_pwritev"; int wv_count; char msg1[10] = "aaaaa"; @@ -170,8 +156,7 @@ void preadv_pwritev(const vector& args) int rres; auto fd = open(FILENAME, O_CREAT | O_WRONLY, S_IRWXU); - if (write(fd, "123456789012345678901234567890", sizeof("ABCDEFGH") - 1) < 0) - { + if(write(fd, "123456789012345678901234567890", sizeof("ABCDEFGH") - 1) < 0) { cerr << "ERROR (write)" << endl; } @@ -211,8 +196,7 @@ void preadv_pwritev(const vector& args) rres = preadv64(fd1, wv, wv_count, 987654321); rres = preadv(fd1, wv, wv_count, 10); - if (rres <= 0) - { + if(rres <= 0) { cerr << "ERROR" << endl; } @@ -222,8 +206,7 @@ void preadv_pwritev(const vector& args) cout << flush; } -void quotactl_ko(const vector& args) -{ +void quotactl_ko(const vector& args) { quotactl(QCMD(Q_QUOTAON, USRQUOTA), "/dev/xxx", 2, @@ -231,15 +214,14 @@ void quotactl_ko(const vector& args) quotactl(QCMD(Q_QUOTAOFF, GRPQUOTA), "/dev/xxx", 0, NULL); } -void quotactl_ok(const vector& args) -{ +void quotactl_ok(const vector& args) { struct dqblk mydqblk; struct dqinfo mydqinfo; std::string caddr = args[0] + "/aquota.user"; quotactl(QCMD(Q_QUOTAON, USRQUOTA), args[1].c_str(), 2, - (caddr_t)caddr.c_str()); // 2 => QFMT_VFS_V0 + (caddr_t)caddr.c_str()); // 2 => QFMT_VFS_V0 quotactl(QCMD(Q_GETQUOTA, USRQUOTA), args[1].c_str(), 0, (caddr_t)&mydqblk); // 0 => root user fwrite(&mydqblk.dqb_bhardlimit, 1, sizeof(uint64_t), stdout); fwrite(&mydqblk.dqb_bsoftlimit, 1, sizeof(uint64_t), stdout); @@ -254,12 +236,10 @@ void quotactl_ok(const vector& args) quotactl(QCMD(Q_QUOTAOFF, USRQUOTA), args[1].c_str(), 0, NULL); } -void poll_timeout(const vector& args) -{ +void poll_timeout(const vector& args) { int my_pipe[2]; auto ret = pipe(my_pipe); - if (ret != 0) - { + if(ret != 0) { return; } @@ -277,12 +257,10 @@ void poll_timeout(const vector& args) fflush(stdout); } -void ppoll_timeout(const vector& args) -{ +void ppoll_timeout(const vector& args) { int my_pipe[2]; auto ret = pipe(my_pipe); - if (ret != 0) - { + if(ret != 0) { return; } @@ -308,14 +286,12 @@ void ppoll_timeout(const vector& args) fflush(stdout); } -void pgid_test(const vector& args) -{ +void pgid_test(const vector& args) { int pgid = atoi(args[0].c_str()); // Change back to child's process group int rc = setpgid(getpid(), pgid); - if (rc != 0) - { + if(rc != 0) { fprintf(stderr, "Can't call setpgid(): %s\n", strerror(errno)); return; } @@ -324,22 +300,18 @@ void pgid_test(const vector& args) // parser to pick up the new pgid. char* const exargs[] = {(char*)"/bin/echo", (char*)"-n", nullptr}; char* const exenv[] = {nullptr}; - if ((rc = execve("/bin/echo", exargs, exenv)) != 0) - { + if((rc = execve("/bin/echo", exargs, exenv)) != 0) { fprintf(stderr, "Can't exec \"/bin/echo -n\": %s\n", strerror(errno)); return; } } -bool custom_container_set_cgroup() -{ +bool custom_container_set_cgroup() { string cpu_cgroup = "/sys/fs/cgroup/cpu/custom_container_foo"; struct stat s; - if (stat(cpu_cgroup.c_str(), &s) < 0) - { - if (mkdir(cpu_cgroup.c_str(), 0777) < 0) - { + if(stat(cpu_cgroup.c_str(), &s) < 0) { + if(mkdir(cpu_cgroup.c_str(), 0777) < 0) { fprintf(stderr, "Could not create cgroup directory %s: %s\n", cpu_cgroup.c_str(), @@ -349,24 +321,21 @@ bool custom_container_set_cgroup() } auto fp = fopen((cpu_cgroup + "/cgroup.procs").c_str(), "w"); - if (!fp) - { + if(!fp) { fprintf(stderr, "Could not open cgroup.procs file in %s: %s\n", cpu_cgroup.c_str(), strerror(errno)); return false; } - if (fprintf(fp, "%d\n", getpid()) < 0) - { + if(fprintf(fp, "%d\n", getpid()) < 0) { fprintf(stderr, "Could not write pid to cgroup.procs file in %s: %s\n", cpu_cgroup.c_str(), strerror(errno)); return false; } - if (fclose(fp) < 0) - { + if(fclose(fp) < 0) { fprintf(stderr, "Could not close cgroup.procs file in %s: %s\n", cpu_cgroup.c_str(), @@ -376,12 +345,10 @@ bool custom_container_set_cgroup() return true; } -void custom_container_simple() -{ +void custom_container_simple() { signal(SIGCHLD, SIG_IGN); pid_t pid = fork(); - switch (pid) - { + switch(pid) { case 0: // child { char* const exargs[] = {(char*)"/bin/echo", (char*)"-n", nullptr}; @@ -394,26 +361,22 @@ void custom_container_simple() case -1: // error fprintf(stderr, "Could not fork: %s\n", strerror(errno)); return; - default: - { + default: { int status; waitpid(pid, &status, 0); } } } -void custom_container_huge_env() -{ +void custom_container_huge_env() { signal(SIGCHLD, SIG_IGN); pid_t pid = fork(); - switch (pid) - { + switch(pid) { case 0: // child { string junk(100, 'x'); vector env_vec; - for (auto i = 0; i < 200; ++i) - { + for(auto i = 0; i < 200; ++i) { env_vec.emplace_back("VAR" + to_string(i) + "=" + junk); } @@ -421,8 +384,7 @@ void custom_container_huge_env() int i = 0; exenv[i++] = const_cast("CUSTOM_CONTAINER_NAME=custom_name"); exenv[i++] = const_cast("CUSTOM_CONTAINER_IMAGE=custom_image"); - for (const auto& var : env_vec) - { + for(const auto& var : env_vec) { exenv[i++] = const_cast(var.c_str()); } exenv[i] = nullptr; @@ -434,26 +396,22 @@ void custom_container_huge_env() case -1: // error fprintf(stderr, "Could not fork: %s\n", strerror(errno)); return; - default: - { + default: { int status; waitpid(pid, &status, 0); } } } -void custom_container_huge_env_echo() -{ +void custom_container_huge_env_echo() { signal(SIGCHLD, SIG_IGN); pid_t pid = fork(); - switch (pid) - { + switch(pid) { case 0: // child { string junk(100, 'x'); vector env_vec; - for (auto i = 0; i < 200; ++i) - { + for(auto i = 0; i < 200; ++i) { env_vec.emplace_back("VAR" + to_string(i) + "=" + junk); } @@ -461,8 +419,7 @@ void custom_container_huge_env_echo() int i = 0; exenv[i++] = const_cast("CUSTOM_CONTAINER_NAME=custom_name"); exenv[i++] = const_cast("CUSTOM_CONTAINER_IMAGE=custom_image"); - for (const auto& var : env_vec) - { + for(const auto& var : env_vec) { exenv[i++] = const_cast(var.c_str()); } exenv[i] = nullptr; @@ -474,33 +431,28 @@ void custom_container_huge_env_echo() case -1: // error fprintf(stderr, "Could not fork: %s\n", strerror(errno)); return; - default: - { + default: { int status; waitpid(pid, &status, 0); } } } -void custom_container_huge_env_at_end() -{ +void custom_container_huge_env_at_end() { signal(SIGCHLD, SIG_IGN); pid_t pid = fork(); - switch (pid) - { + switch(pid) { case 0: // child { string junk(100, 'x'); vector env_vec; - for (auto i = 0; i < 200; ++i) - { + for(auto i = 0; i < 200; ++i) { env_vec.emplace_back("VAR" + to_string(i) + "=" + junk); } char* exenv[env_vec.size() + 3]; int i = 0; - for (const auto& var : env_vec) - { + for(const auto& var : env_vec) { exenv[i++] = const_cast(var.c_str()); } exenv[i++] = const_cast("CUSTOM_CONTAINER_NAME=custom_name"); @@ -514,21 +466,18 @@ void custom_container_huge_env_at_end() case -1: // error fprintf(stderr, "Could not fork: %s\n", strerror(errno)); return; - default: - { + default: { int status; waitpid(pid, &status, 0); } } } -void custom_container_halfnhalf() -{ +void custom_container_halfnhalf() { signal(SIGCHLD, SIG_IGN); pid_t pid = fork(); - switch (pid) - { + switch(pid) { case 0: // child { char* const exargs[] = {(char*)"/bin/echo", (char*)"-n", nullptr}; @@ -539,11 +488,9 @@ void custom_container_halfnhalf() case -1: // error fprintf(stderr, "Could not fork: %s\n", strerror(errno)); return; - default: - { + default: { pid_t pid2 = fork(); - switch (pid2) - { + switch(pid2) { case 0: // child { char* const exargs[] = {(char*)"/bin/echo", (char*)"-n", nullptr}; @@ -554,8 +501,7 @@ void custom_container_halfnhalf() case -1: // error fprintf(stderr, "Could not fork: %s\n", strerror(errno)); return; - default: - { + default: { int status; waitpid(pid, &status, 0); waitpid(pid2, &status, 0); @@ -565,48 +511,35 @@ void custom_container_halfnhalf() } } -void custom_container(const vector& args) -{ - if (!custom_container_set_cgroup()) - { +void custom_container(const vector& args) { + if(!custom_container_set_cgroup()) { return; } - if (args.empty()) - { + if(args.empty()) { return custom_container_simple(); } const auto& arg = args.at(0); - if (arg == "halfnhalf") - { + if(arg == "halfnhalf") { return custom_container_halfnhalf(); - } - else if (arg == "huge_env") - { + } else if(arg == "huge_env") { return custom_container_huge_env(); - } - else if (arg == "huge_env_echo") - { + } else if(arg == "huge_env_echo") { return custom_container_huge_env_echo(); - } - else if (arg == "huge_env_at_end") - { + } else if(arg == "huge_env_at_end") { return custom_container_huge_env_at_end(); } } -bool cri_container_set_cgroup() -{ +bool cri_container_set_cgroup() { string cpu_cgroup = - "/sys/fs/cgroup/cpu/docker/" - "aec4c703604b4504df03108eef12e8256870eca8aabcb251855a35bf4f0337f1"; + "/sys/fs/cgroup/cpu/docker/" + "aec4c703604b4504df03108eef12e8256870eca8aabcb251855a35bf4f0337f1"; struct stat s; - if (stat(cpu_cgroup.c_str(), &s) < 0) - { - if (mkdir(cpu_cgroup.c_str(), 0777) < 0) - { + if(stat(cpu_cgroup.c_str(), &s) < 0) { + if(mkdir(cpu_cgroup.c_str(), 0777) < 0) { fprintf(stderr, "Could not create cgroup directory %s: %s\n", cpu_cgroup.c_str(), @@ -616,24 +549,21 @@ bool cri_container_set_cgroup() } auto fp = fopen((cpu_cgroup + "/cgroup.procs").c_str(), "w"); - if (!fp) - { + if(!fp) { fprintf(stderr, "Could not open cgroup.procs file in %s: %s\n", cpu_cgroup.c_str(), strerror(errno)); return false; } - if (fprintf(fp, "%d\n", getpid()) < 0) - { + if(fprintf(fp, "%d\n", getpid()) < 0) { fprintf(stderr, "Could not write pid to cgroup.procs file in %s: %s\n", cpu_cgroup.c_str(), strerror(errno)); return false; } - if (fclose(fp) < 0) - { + if(fclose(fp) < 0) { fprintf(stderr, "Could not close cgroup.procs file in %s: %s\n", cpu_cgroup.c_str(), @@ -643,12 +573,10 @@ bool cri_container_set_cgroup() return true; } -void cri_container_simple(char* const exargs[]) -{ +void cri_container_simple(char* const exargs[]) { signal(SIGCHLD, SIG_IGN); pid_t pid = fork(); - switch (pid) - { + switch(pid) { case 0: // child { char* const exenv[] = {nullptr}; @@ -658,18 +586,15 @@ void cri_container_simple(char* const exargs[]) case -1: // error fprintf(stderr, "Could not fork: %s\n", strerror(errno)); return; - default: - { + default: { int status; waitpid(pid, &status, 0); } } } -void cri_container_echo(const vector& args) -{ - if (!cri_container_set_cgroup()) - { +void cri_container_echo(const vector& args) { + if(!cri_container_set_cgroup()) { return; } @@ -677,10 +602,8 @@ void cri_container_echo(const vector& args) return cri_container_simple(exargs); } -void cri_container_sleep_gzip(const vector& args) -{ - if (!cri_container_set_cgroup()) - { +void cri_container_sleep_gzip(const vector& args) { + if(!cri_container_set_cgroup()) { return; } @@ -691,10 +614,8 @@ void cri_container_sleep_gzip(const vector& args) return cri_container_simple(exargs); } -void cri_container_sleep_bzip2(const vector& args) -{ - if (!cri_container_set_cgroup()) - { +void cri_container_sleep_bzip2(const vector& args) { + if(!cri_container_set_cgroup()) { return; } @@ -705,10 +626,8 @@ void cri_container_sleep_bzip2(const vector& args) return cri_container_simple(exargs); } -void cri_container_sleep_lzcat(const vector& args) -{ - if (!cri_container_set_cgroup()) - { +void cri_container_sleep_lzcat(const vector& args) { + if(!cri_container_set_cgroup()) { return; } @@ -720,51 +639,47 @@ void cri_container_sleep_lzcat(const vector& args) } const unordered_map&)>> func_map = { - {"proc_mgmt", proc_mgmt}, - {"mmap_test", mmap_test}, - {"tcp_client", - [](const vector& args) - { - auto iot = static_cast(stoi(args.at(1))); - tcp_client client(inet_addr(args.at(0).c_str()), - iot, - args.at(2), - str_to_bool(args.at(3)), - stoi(args.at(4)), - str_to_bool(args.at(5))); - client.run(); - }}, - {"tcp_server", - [](const vector& args) - { - auto iot = static_cast(stoi(args.at(0))); - - tcp_server server(iot, - str_to_bool(args.at(1)), - str_to_bool(args.at(2)), - str_to_bool(args.at(3)), - stoi(args.at(4)), - str_to_bool(args.at(5))); - server.run(); - }}, - {"pread_pwrite", pread_pwrite}, - {"preadv_pwritev", preadv_pwritev}, - {"quotactl_ko", quotactl_ko}, - {"quotactl_ok", quotactl_ok}, - {"poll_timeout", poll_timeout}, - {"ppoll_timeout", ppoll_timeout}, - {"pgid_test", pgid_test}, - {"custom_container", custom_container}, - {"cri_container_echo", cri_container_echo}, - {"cri_container_sleep_gzip", cri_container_sleep_gzip}, - {"cri_container_sleep_bzip2", cri_container_sleep_bzip2}, - {"cri_container_sleep_lzcat", cri_container_sleep_lzcat}}; + {"proc_mgmt", proc_mgmt}, + {"mmap_test", mmap_test}, + {"tcp_client", + [](const vector& args) { + auto iot = static_cast(stoi(args.at(1))); + tcp_client client(inet_addr(args.at(0).c_str()), + iot, + args.at(2), + str_to_bool(args.at(3)), + stoi(args.at(4)), + str_to_bool(args.at(5))); + client.run(); + }}, + {"tcp_server", + [](const vector& args) { + auto iot = static_cast(stoi(args.at(0))); + + tcp_server server(iot, + str_to_bool(args.at(1)), + str_to_bool(args.at(2)), + str_to_bool(args.at(3)), + stoi(args.at(4)), + str_to_bool(args.at(5))); + server.run(); + }}, + {"pread_pwrite", pread_pwrite}, + {"preadv_pwritev", preadv_pwritev}, + {"quotactl_ko", quotactl_ko}, + {"quotactl_ok", quotactl_ok}, + {"poll_timeout", poll_timeout}, + {"ppoll_timeout", ppoll_timeout}, + {"pgid_test", pgid_test}, + {"custom_container", custom_container}, + {"cri_container_echo", cri_container_echo}, + {"cri_container_sleep_gzip", cri_container_sleep_gzip}, + {"cri_container_sleep_bzip2", cri_container_sleep_bzip2}, + {"cri_container_sleep_lzcat", cri_container_sleep_lzcat}}; // Helper to test ia32 emulation on 64bit -int main(int argc, char** argv) -{ - if (argc > 1) - { +int main(int argc, char** argv) { + if(argc > 1) { bool threaded = false; // The first argument might be "threaded", meaning @@ -772,33 +687,25 @@ int main(int argc, char** argv) // thread. int j = 1; - if (strcmp(argv[j], "threaded") == 0) - { + if(strcmp(argv[j], "threaded") == 0) { threaded = true; j++; } vector args; - for (; j < argc; ++j) - { + for(; j < argc; ++j) { args.emplace_back(argv[j]); } auto cmd = args.front(); args.erase(args.begin()); - auto do_work = [&]() - { - func_map.at(cmd)(args); - }; + auto do_work = [&]() { func_map.at(cmd)(args); }; - if (threaded) - { + if(threaded) { std::thread t(do_work); t.join(); - } - else - { + } else { do_work(); } } diff --git a/test/libsinsp_e2e/thread_state.cpp b/test/libsinsp_e2e/thread_state.cpp index 0e2259048f..80d1371870 100644 --- a/test/libsinsp_e2e/thread_state.cpp +++ b/test/libsinsp_e2e/thread_state.cpp @@ -28,15 +28,12 @@ limitations under the License. using namespace std; -class thread_state_test : public ::testing::Test -{ +class thread_state_test : public ::testing::Test { protected: - virtual void SetUp() - { + virtual void SetUp() { // Each entry in the vector has a parent of the previous // entry. The first entry has a parent of 1. - for (int64_t pid = 100, i = 0; i < m_max; pid++, i++) - { + for(int64_t pid = 100, i = 0; i < m_max; pid++, i++) { int64_t ppid = (i == 0 ? 1 : m_threads[i - 1]->m_tid); std::unique_ptr thr = m_inspector.build_threadinfo(); thr->init(); @@ -52,11 +49,9 @@ class thread_state_test : public ::testing::Test virtual void TearDown() {} - void reset() - { + void reset() { // Reset the state - for (uint32_t i = 0; i < m_max; i++) - { + for(uint32_t i = 0; i < m_max; i++) { int64_t ppid = (i == 0 ? 1 : m_threads[i - 1]->m_tid); sinsp_threadinfo* tinfo = m_threads[i]; tinfo->m_lastevent_fd = 0; @@ -65,28 +60,25 @@ class thread_state_test : public ::testing::Test } } - void traverse_with_timeout(sinsp_threadinfo* tinfo) - { + void traverse_with_timeout(sinsp_threadinfo* tinfo) { promise finished; auto result = finished.get_future(); - sinsp_threadinfo::visitor_func_t visitor = [](sinsp_threadinfo* tinfo) - { + sinsp_threadinfo::visitor_func_t visitor = [](sinsp_threadinfo* tinfo) { tinfo->m_lastevent_fd = 1; return true; }; thread runner = thread( - [](promise finished, - sinsp_threadinfo* tinfo, - sinsp_threadinfo::visitor_func_t visitor) - { - tinfo->traverse_parent_state(visitor); - finished.set_value(true); - }, - std::move(finished), - tinfo, - visitor); + [](promise finished, + sinsp_threadinfo* tinfo, + sinsp_threadinfo::visitor_func_t visitor) { + tinfo->traverse_parent_state(visitor); + finished.set_value(true); + }, + std::move(finished), + tinfo, + visitor); runner.detach(); @@ -97,19 +89,16 @@ class thread_state_test : public ::testing::Test // This just verifies that the mechanism of wait_for with a // timeout actually works in the face of a thread that never // stops - void loop_almost_forever() - { + void loop_almost_forever() { promise finished; auto result = finished.get_future(); // This runs for 3 seconds which is greater than the 1 // second timeout below - thread runner = thread( - [&finished]() - { - sleep(3); - finished.set_value(true); - }); + thread runner = thread([&finished]() { + sleep(3); + finished.set_value(true); + }); runner.detach(); @@ -119,12 +108,10 @@ class thread_state_test : public ::testing::Test EXPECT_TRUE(result.wait_for(chrono::milliseconds(1000)) != future_status::timeout); } - void verify(uint32_t test_idx, bool loop_detected, vector& visited) - { + void verify(uint32_t test_idx, bool loop_detected, vector& visited) { SCOPED_TRACE("test_idx=" + to_string(test_idx)); EXPECT_EQ(m_threads[test_idx]->parent_loop_detected(), loop_detected); - for (uint32_t i = 0; i < m_max; i++) - { + for(uint32_t i = 0; i < m_max; i++) { SCOPED_TRACE("i=" + to_string(i)); EXPECT_EQ(m_threads[i]->m_lastevent_fd, visited[i]); } @@ -135,8 +122,7 @@ class thread_state_test : public ::testing::Test uint32_t m_max = 5; }; -TEST_F(thread_state_test, parent_state_single) -{ +TEST_F(thread_state_test, parent_state_single) { reset(); traverse_with_timeout(m_threads[0]); @@ -146,8 +132,7 @@ TEST_F(thread_state_test, parent_state_single) verify(0, false, expected); } -TEST_F(thread_state_test, parent_state_parent) -{ +TEST_F(thread_state_test, parent_state_parent) { reset(); traverse_with_timeout(m_threads[1]); @@ -155,8 +140,7 @@ TEST_F(thread_state_test, parent_state_parent) verify(1, false, expected); } -TEST_F(thread_state_test, parent_state_parent_ancestors) -{ +TEST_F(thread_state_test, parent_state_parent_ancestors) { reset(); traverse_with_timeout(m_threads[4]); @@ -164,8 +148,7 @@ TEST_F(thread_state_test, parent_state_parent_ancestors) verify(4, false, expected); } -TEST_F(thread_state_test, parent_state_single_loop) -{ +TEST_F(thread_state_test, parent_state_single_loop) { reset(); m_threads[0]->m_ptid = m_threads[0]->m_tid; traverse_with_timeout(m_threads[0]); @@ -176,8 +159,7 @@ TEST_F(thread_state_test, parent_state_single_loop) verify(0, true, expected); } -TEST_F(thread_state_test, parent_state_short_loop) -{ +TEST_F(thread_state_test, parent_state_short_loop) { reset(); m_threads[0]->m_ptid = m_threads[1]->m_tid; traverse_with_timeout(m_threads[1]); @@ -188,8 +170,7 @@ TEST_F(thread_state_test, parent_state_short_loop) verify(0, false, expected); } -TEST_F(thread_state_test, parent_state_loop) -{ +TEST_F(thread_state_test, parent_state_loop) { reset(); m_threads[0]->m_ptid = m_threads[4]->m_tid; traverse_with_timeout(m_threads[4]); @@ -198,8 +179,7 @@ TEST_F(thread_state_test, parent_state_loop) verify(4, true, expected); } -TEST_F(thread_state_test, parent_state_lollipop) -{ +TEST_F(thread_state_test, parent_state_lollipop) { reset(); m_threads[0]->m_ptid = m_threads[2]->m_tid; traverse_with_timeout(m_threads[4]); @@ -210,7 +190,6 @@ TEST_F(thread_state_test, parent_state_lollipop) verify(4, true, expected); } -TEST_F(thread_state_test, parent_state_verify_timeout) -{ +TEST_F(thread_state_test, parent_state_verify_timeout) { loop_almost_forever(); } diff --git a/test/libsinsp_e2e/threadinfo.cpp b/test/libsinsp_e2e/threadinfo.cpp index 560b52d452..6b5a021cc7 100644 --- a/test/libsinsp_e2e/threadinfo.cpp +++ b/test/libsinsp_e2e/threadinfo.cpp @@ -24,20 +24,16 @@ limitations under the License. #include #include -class threadinfo_test : public testing::Test -{ -}; +class threadinfo_test : public testing::Test {}; static void check_iov(struct iovec* iov, int iovcnt, std::string rem, std::vector& expected, - std::string expectedrem) -{ + std::string expectedrem) { ASSERT_EQ((unsigned)iovcnt, expected.size()); - for (int i = 0; i < iovcnt; i++) - { + for(int i = 0; i < iovcnt; i++) { ASSERT_EQ(iov[i].iov_len, expected[i].iov_len); ASSERT_TRUE(memcmp(iov[i].iov_base, expected[i].iov_base, iov[i].iov_len) == 0); } @@ -45,28 +41,20 @@ static void check_iov(struct iovec* iov, EXPECT_TRUE(rem == expectedrem); } -enum test_type -{ - TEST_ARGS = 0, - TEST_ENV = 1, - TEST_CGROUPS = 2 -}; +enum test_type { TEST_ARGS = 0, TEST_ENV = 1, TEST_CGROUPS = 2 }; static void run_test(test_type ttype, std::vector& vals, std::vector& expected, - std::string expectedrem) -{ + std::string expectedrem) { sinsp_threadinfo ti(nullptr); struct iovec* iov; int iovcnt; std::string rem; sinsp_threadinfo::cgroups_t cg; - for (auto& val : vals) - { - switch (ttype) - { + for(auto& val : vals) { + switch(ttype) { case TEST_ARGS: ti.m_args.push_back(val.c_str()); break; @@ -81,8 +69,7 @@ static void run_test(test_type ttype, } } - switch (ttype) - { + switch(ttype) { case TEST_ARGS: ti.args_to_iovec(&iov, &iovcnt, rem); break; @@ -96,15 +83,11 @@ static void run_test(test_type ttype, }; std::vector expected_iov; - for (auto& exp : expected) - { - if (ttype == TEST_ARGS || ttype == TEST_ENV) - { + for(auto& exp : expected) { + if(ttype == TEST_ARGS || ttype == TEST_ENV) { // A trailing NULL is assumed for all values expected_iov.emplace_back(iovec{(void*)exp.c_str(), exp.size() + 1}); - } - else - { + } else { expected_iov.emplace_back(iovec{(void*)exp.data(), exp.size()}); } } @@ -114,16 +97,14 @@ static void run_test(test_type ttype, free(iov); } -TEST_F(threadinfo_test, args) -{ +TEST_F(threadinfo_test, args) { std::vector args = {"-i", "206", "--switch", "f"}; std::string expectedrem; run_test(TEST_ARGS, args, args, expectedrem); } -TEST_F(threadinfo_test, args_skip) -{ +TEST_F(threadinfo_test, args_skip) { std::string full(SCAP_MAX_ARGS_SIZE - 1, 'a'); std::vector args = {full, "will-be-skipped"}; @@ -133,8 +114,7 @@ TEST_F(threadinfo_test, args_skip) run_test(TEST_ARGS, args, expected, expectedrem); } -TEST_F(threadinfo_test, argstrunc_single) -{ +TEST_F(threadinfo_test, argstrunc_single) { std::string full(SCAP_MAX_ARGS_SIZE, 'a'); std::string trunc(SCAP_MAX_ARGS_SIZE - 1, 'a'); @@ -145,8 +125,7 @@ TEST_F(threadinfo_test, argstrunc_single) run_test(TEST_ARGS, args, expected, expectedrem); } -TEST_F(threadinfo_test, argstrunc_multi) -{ +TEST_F(threadinfo_test, argstrunc_multi) { std::string full(SCAP_MAX_ARGS_SIZE, 'a'); std::string trunc(SCAP_MAX_ARGS_SIZE - 6, 'a'); @@ -157,16 +136,14 @@ TEST_F(threadinfo_test, argstrunc_multi) run_test(TEST_ARGS, args, expected, expectedrem); } -TEST_F(threadinfo_test, envs) -{ +TEST_F(threadinfo_test, envs) { std::vector envs = {"-i", "206", "--switch", "f"}; std::string expectedrem; run_test(TEST_ENV, envs, envs, expectedrem); } -TEST_F(threadinfo_test, envs_skip) -{ +TEST_F(threadinfo_test, envs_skip) { std::string full(SCAP_MAX_ENV_SIZE - 1, 'a'); std::vector envs = {full, "will-be-skipped"}; @@ -176,8 +153,7 @@ TEST_F(threadinfo_test, envs_skip) run_test(TEST_ENV, envs, expected, expectedrem); } -TEST_F(threadinfo_test, envstrunc_single) -{ +TEST_F(threadinfo_test, envstrunc_single) { std::string full(SCAP_MAX_ENV_SIZE, 'a'); std::string trunc(SCAP_MAX_ENV_SIZE - 1, 'a'); @@ -188,8 +164,7 @@ TEST_F(threadinfo_test, envstrunc_single) run_test(TEST_ENV, envs, expected, expectedrem); } -TEST_F(threadinfo_test, envstrunc_multi) -{ +TEST_F(threadinfo_test, envstrunc_multi) { std::string full(SCAP_MAX_ENV_SIZE, 'a'); std::string trunc(SCAP_MAX_ENV_SIZE - 6, 'a'); @@ -200,27 +175,26 @@ TEST_F(threadinfo_test, envstrunc_multi) run_test(TEST_ENV, envs, expected, expectedrem); } -TEST_F(threadinfo_test, cgroups) -{ +TEST_F(threadinfo_test, cgroups) { std::vector cgroups = { - "cpuset=/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", - "perf_event=/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", - "memory=/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", - "rdma=/"}; + "cpuset=/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", + "perf_event=/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", + "memory=/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", + "rdma=/"}; std::vector expected = { - "cpuset", - "=", - "/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", - "perf_event", - "=", - "/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", - "memory", - "=", - "/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", - "rdma", - "=", - "/"}; + "cpuset", + "=", + "/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", + "perf_event", + "=", + "/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", + "memory", + "=", + "/docker/875f9d8728e84761e4669b21acbf035b3a3fda62d7f6e35dd857781932cd74e8", + "rdma", + "=", + "/"}; expected[2].push_back('\0'); expected[5].push_back('\0'); @@ -231,8 +205,7 @@ TEST_F(threadinfo_test, cgroups) run_test(TEST_CGROUPS, cgroups, expected, expectedrem); } -TEST_F(threadinfo_test, cgroups_skip) -{ +TEST_F(threadinfo_test, cgroups_skip) { std::string full(SCAP_MAX_CGROUPS_SIZE - 8, 'a'); std::vector cgroups = {"cpuset=" + full, "rdma=will-be-skipped"}; @@ -243,8 +216,7 @@ TEST_F(threadinfo_test, cgroups_skip) run_test(TEST_CGROUPS, cgroups, expected, expectedrem); } -TEST_F(threadinfo_test, cgroupstrunc_single) -{ +TEST_F(threadinfo_test, cgroupstrunc_single) { std::string full(SCAP_MAX_CGROUPS_SIZE - 7, 'a'); std::string trunc(SCAP_MAX_CGROUPS_SIZE - 8, 'a'); @@ -256,8 +228,7 @@ TEST_F(threadinfo_test, cgroupstrunc_single) run_test(TEST_CGROUPS, cgroups, expected, expectedrem); } -TEST_F(threadinfo_test, cgroupstrunc_multi) -{ +TEST_F(threadinfo_test, cgroupstrunc_multi) { std::string full(SCAP_MAX_CGROUPS_SIZE, 'a'); std::string trunc(SCAP_MAX_CGROUPS_SIZE - 15, 'a'); @@ -270,8 +241,7 @@ TEST_F(threadinfo_test, cgroupstrunc_multi) run_test(TEST_CGROUPS, cgroups, expected, expectedrem); } -TEST_F(threadinfo_test, cgroupstrunc_noeq) -{ +TEST_F(threadinfo_test, cgroupstrunc_noeq) { std::string full(SCAP_MAX_CGROUPS_SIZE, 'a'); std::string trunc(SCAP_MAX_CGROUPS_SIZE - 10, 'a'); diff --git a/test/libsinsp_e2e/udp_client_server.cpp b/test/libsinsp_e2e/udp_client_server.cpp index 353fd6f1c5..77b23247e2 100644 --- a/test/libsinsp_e2e/udp_client_server.cpp +++ b/test/libsinsp_e2e/udp_client_server.cpp @@ -43,450 +43,389 @@ using namespace std; #define FALSE 0 #define NTRANSACTIONS 2 -class udp_server -{ - public: - udp_server(bool use_unix, bool use_sendmsg, bool recvmsg_twobufs, uint32_t port_offset = 0) - { - m_use_unix = use_unix; - m_use_sendmsg = use_sendmsg; - m_recvmsg_twobufs = recvmsg_twobufs; - m_port = SERVER_PORT + port_offset; - m_server_ready = false; +class udp_server { +public: + udp_server(bool use_unix, bool use_sendmsg, bool recvmsg_twobufs, uint32_t port_offset = 0) { + m_use_unix = use_unix; + m_use_sendmsg = use_sendmsg; + m_recvmsg_twobufs = recvmsg_twobufs; + m_port = SERVER_PORT + port_offset; + m_server_ready = false; + } + + void run() { + int sd = -1, rc; + char buffer[BUFFER_LENGTH + 10]; + char buffer1[BUFFER_LENGTH - 10]; + struct sockaddr_in serveraddr; + struct sockaddr_in clientaddr; + socklen_t clientaddrlen = sizeof(clientaddr); + int j; + int domain; + + m_tid = syscall(SYS_gettid); + + if(m_use_unix) { + domain = AF_UNIX; + } else { + domain = AF_INET; } - void run() - { - int sd = -1, rc; - char buffer[BUFFER_LENGTH + 10]; - char buffer1[BUFFER_LENGTH - 10]; - struct sockaddr_in serveraddr; - struct sockaddr_in clientaddr; - socklen_t clientaddrlen = sizeof(clientaddr); - int j; - int domain; + do { + sd = socket(domain, SOCK_DGRAM, 0); + if(sd < 0) { + perror("socket() failed"); + break; + } - m_tid = syscall(SYS_gettid); + memset(&serveraddr, 0, sizeof(serveraddr)); + serveraddr.sin_family = domain; + serveraddr.sin_port = htons(m_port); + serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); - if (m_use_unix) - { - domain = AF_UNIX; - } - else - { - domain = AF_INET; + rc = ::bind(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); + if(rc < 0) { + perror("bind() failed"); + break; } - do { - sd = socket(domain, SOCK_DGRAM, 0); - if (sd < 0) - { - perror("socket() failed"); - break; - } - - memset(&serveraddr, 0, sizeof(serveraddr)); - serveraddr.sin_family = domain; - serveraddr.sin_port = htons(m_port); - serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); - - rc = ::bind(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); - if (rc < 0) - { - perror("bind() failed"); - break; - } + std::unique_lock lock(m_mutex); + m_server_ready = true; + m_condition_server_ready.notify_one(); + } - { - std::unique_lock lock(m_mutex); - m_server_ready = true; - m_condition_server_ready.notify_one(); - } + for(j = 0; j < NTRANSACTIONS; j++) { + if(m_use_sendmsg) { + struct msghdr msg; + struct iovec iov[2]; + + if(m_recvmsg_twobufs) { + iov[0].iov_base = buffer1; + iov[0].iov_len = BUFFER_LENGTH - 10; + iov[1].iov_base = buffer; + iov[1].iov_len = BUFFER_LENGTH - 10; + + msg.msg_name = &clientaddr; + msg.msg_namelen = clientaddrlen; + msg.msg_iov = iov; + msg.msg_iovlen = 2; + msg.msg_control = 0; + msg.msg_controllen = 0; + msg.msg_flags = 0; - for (j = 0; j < NTRANSACTIONS; j++) - { - if (m_use_sendmsg) - { - struct msghdr msg; - struct iovec iov[2]; - - if (m_recvmsg_twobufs) - { - iov[0].iov_base = buffer1; - iov[0].iov_len = BUFFER_LENGTH - 10; - iov[1].iov_base = buffer; - iov[1].iov_len = BUFFER_LENGTH - 10; - - msg.msg_name = &clientaddr; - msg.msg_namelen = clientaddrlen; - msg.msg_iov = iov; - msg.msg_iovlen = 2; - msg.msg_control = 0; - msg.msg_controllen = 0; - msg.msg_flags = 0; - - // - // Receive the data - // - int res = recvmsg(sd, &msg, 0); - EXPECT_EQ(res, (int)BUFFER_LENGTH); - - // - // Set the send buffer - // - iov[0].iov_len = BUFFER_LENGTH - 10; - iov[1].iov_len = 10; - } - else - { - iov[0].iov_base = buffer; - iov[0].iov_len = BUFFER_LENGTH + 10; - - msg.msg_name = &clientaddr; - msg.msg_namelen = clientaddrlen; - msg.msg_iov = iov; - msg.msg_iovlen = 1; - msg.msg_control = 0; - msg.msg_controllen = 0; - msg.msg_flags = 0; - - // - // Receive the data - // - int res = recvmsg(sd, &msg, 0); - EXPECT_EQ(res, (int)BUFFER_LENGTH); - - // - // Set the send buffer - // - iov[0].iov_len = BUFFER_LENGTH; - } + // + // Receive the data + // + int res = recvmsg(sd, &msg, 0); + EXPECT_EQ(res, (int)BUFFER_LENGTH); // - // Echo the data back to the client + // Set the send buffer // - if (sendmsg(sd, &msg, 0) == -1) - { - perror("sendmsg() failed"); - break; - } - } - else - { + iov[0].iov_len = BUFFER_LENGTH - 10; + iov[1].iov_len = 10; + } else { + iov[0].iov_base = buffer; + iov[0].iov_len = BUFFER_LENGTH + 10; + + msg.msg_name = &clientaddr; + msg.msg_namelen = clientaddrlen; + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = 0; + msg.msg_controllen = 0; + msg.msg_flags = 0; + // // Receive the data // - rc = recvfrom(sd, - buffer, - sizeof(buffer), - 0, - (struct sockaddr*)&clientaddr, - &clientaddrlen); - if (rc < 0) - { - perror("recvfrom() failed"); - break; - } + int res = recvmsg(sd, &msg, 0); + EXPECT_EQ(res, (int)BUFFER_LENGTH); // - // Echo the data back to the client + // Set the send buffer // - rc = sendto(sd, - buffer, - sizeof(buffer), - 0, - (struct sockaddr*)&clientaddr, - sizeof(clientaddr)); - if (rc < 0) - { - FAIL(); - perror("sendto() failed"); - break; - } + iov[0].iov_len = BUFFER_LENGTH; + } + + // + // Echo the data back to the client + // + if(sendmsg(sd, &msg, 0) == -1) { + perror("sendmsg() failed"); + break; + } + } else { + // + // Receive the data + // + rc = recvfrom(sd, + buffer, + sizeof(buffer), + 0, + (struct sockaddr*)&clientaddr, + &clientaddrlen); + if(rc < 0) { + perror("recvfrom() failed"); + break; + } + + // + // Echo the data back to the client + // + rc = sendto(sd, + buffer, + sizeof(buffer), + 0, + (struct sockaddr*)&clientaddr, + sizeof(clientaddr)); + if(rc < 0) { + FAIL(); + perror("sendto() failed"); + break; } } - } while (FALSE); + } + } while(FALSE); - if (sd != -1) - close(sd); - } + if(sd != -1) + close(sd); + } - void wait_for_server_ready() + void wait_for_server_ready() { { - { - std::unique_lock lock(m_mutex); - m_condition_server_ready.wait(lock, [this]() { - return m_server_ready; - }); - m_server_ready = false; - } + std::unique_lock lock(m_mutex); + m_condition_server_ready.wait(lock, [this]() { return m_server_ready; }); + m_server_ready = false; } + } - int64_t get_tid() { return m_tid; } - - private: - std::mutex m_mutex; - std::condition_variable m_condition_server_ready; - bool m_server_ready; - int64_t m_tid; - bool m_use_unix; - bool m_use_sendmsg; - bool m_recvmsg_twobufs; - uint16_t m_port; + int64_t get_tid() { return m_tid; } + +private: + std::mutex m_mutex; + std::condition_variable m_condition_server_ready; + bool m_server_ready; + int64_t m_tid; + bool m_use_unix; + bool m_use_sendmsg; + bool m_recvmsg_twobufs; + uint16_t m_port; }; -class udp_client -{ - public: - udp_client(uint32_t server_ip_address, - bool use_connect, - uint16_t base_port = SERVER_PORT, - uint32_t num_servers = 1) - : m_use_sendmsg(false), - m_recv(true), - m_payload(PAYLOAD), - m_ignore_errors(false), - m_n_transactions(NTRANSACTIONS) - { - m_use_unix = false; - m_server_ip_address = server_ip_address; - m_use_connect = use_connect; - for (uint32_t idx = 0; idx < num_servers; idx++) - { - m_server_ports.push_back(base_port + idx); - } +class udp_client { +public: + udp_client(uint32_t server_ip_address, + bool use_connect, + uint16_t base_port = SERVER_PORT, + uint32_t num_servers = 1): + m_use_sendmsg(false), + m_recv(true), + m_payload(PAYLOAD), + m_ignore_errors(false), + m_n_transactions(NTRANSACTIONS) { + m_use_unix = false; + m_server_ip_address = server_ip_address; + m_use_connect = use_connect; + for(uint32_t idx = 0; idx < num_servers; idx++) { + m_server_ports.push_back(base_port + idx); } + } - void run() - { - int sd; - int domain; + void run() { + int sd; + int domain; - if (m_use_unix) - { - domain = AF_UNIX; - } - else - { - domain = AF_INET; - } + if(m_use_unix) { + domain = AF_UNIX; + } else { + domain = AF_INET; + } - sd = socket(domain, SOCK_DGRAM, 0); - if (sd < 0) - { - FAIL(); - } + sd = socket(domain, SOCK_DGRAM, 0); + if(sd < 0) { + FAIL(); + } - for (auto port : m_server_ports) - { - run_using_port(sd, domain, port); - } + for(auto port : m_server_ports) { + run_using_port(sd, domain, port); + } - if (sd != -1) - { - close(sd); - } + if(sd != -1) { + close(sd); } + } - void run_using_port(int sd, int domain, uint16_t port) - { - int rc; - int j; - struct sockaddr_in serveraddr; - socklen_t serveraddrlen = sizeof(serveraddr); + void run_using_port(int sd, int domain, uint16_t port) { + int rc; + int j; + struct sockaddr_in serveraddr; + socklen_t serveraddrlen = sizeof(serveraddr); - memset(&serveraddr, 0, sizeof(serveraddr)); - serveraddr.sin_family = domain; - serveraddr.sin_port = htons(port); - serveraddr.sin_addr.s_addr = m_server_ip_address; + memset(&serveraddr, 0, sizeof(serveraddr)); + serveraddr.sin_family = domain; + serveraddr.sin_port = htons(port); + serveraddr.sin_addr.s_addr = m_server_ip_address; - if (m_use_connect) - { - if (connect(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0 && - !m_ignore_errors) - { - close(sd); - FAIL() << "connect() failed"; - } + if(m_use_connect) { + if(connect(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0 && + !m_ignore_errors) { + close(sd); + FAIL() << "connect() failed"; } + } - for (j = 0; j < m_n_transactions; j++) - { - if (!m_use_sendmsg) - { - if (m_use_connect) - { - rc = sendto(sd, m_payload.data(), m_payload.size(), 0, NULL, 0); - } - else - { - rc = sendto(sd, - m_payload.data(), - m_payload.size(), - 0, - (struct sockaddr*)&serveraddr, - sizeof(serveraddr)); - } + for(j = 0; j < m_n_transactions; j++) { + if(!m_use_sendmsg) { + if(m_use_connect) { + rc = sendto(sd, m_payload.data(), m_payload.size(), 0, NULL, 0); + } else { + rc = sendto(sd, + m_payload.data(), + m_payload.size(), + 0, + (struct sockaddr*)&serveraddr, + sizeof(serveraddr)); } - else - { - struct msghdr msg = {0}; - if (m_use_connect) - { - msg.msg_name = NULL; - } - else - { - msg.msg_name = (void*)&serveraddr; - msg.msg_namelen = sizeof(serveraddr); - } - struct iovec iov; - iov.iov_base = (void*)m_payload.data(); - iov.iov_len = m_payload.size(); - msg.msg_iov = &iov; - msg.msg_iovlen = 1; - rc = sendmsg(sd, &msg, MSG_DONTWAIT); + } else { + struct msghdr msg = {0}; + if(m_use_connect) { + msg.msg_name = NULL; + } else { + msg.msg_name = (void*)&serveraddr; + msg.msg_namelen = sizeof(serveraddr); } - if (rc < 0 && !m_ignore_errors) - { + struct iovec iov; + iov.iov_base = (void*)m_payload.data(); + iov.iov_len = m_payload.size(); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + rc = sendmsg(sd, &msg, MSG_DONTWAIT); + } + if(rc < 0 && !m_ignore_errors) { + close(sd); + FAIL(); + } + + // + // Use the recvfrom() function to receive the data back from the + // server. + // + if(m_recv) { + char* buffer = (char*)malloc(m_payload.size()); + rc = recvfrom(sd, + buffer, + m_payload.size(), + 0, + (struct sockaddr*)&serveraddr, + &serveraddrlen); + free(buffer); + if(rc < 0 && !m_ignore_errors) { close(sd); FAIL(); } - - // - // Use the recvfrom() function to receive the data back from the - // server. - // - if (m_recv) - { - char* buffer = (char*)malloc(m_payload.size()); - rc = recvfrom(sd, - buffer, - m_payload.size(), - 0, - (struct sockaddr*)&serveraddr, - &serveraddrlen); - free(buffer); - if (rc < 0 && !m_ignore_errors) - { - close(sd); - FAIL(); - } - } } } + } - bool m_use_sendmsg; - bool m_recv; - std::string m_payload; - bool m_use_connect; - bool m_ignore_errors; - int m_n_transactions; - - private: - bool m_use_unix; - uint32_t m_server_ip_address; - std::vector m_server_ports; + bool m_use_sendmsg; + bool m_recv; + std::string m_payload; + bool m_use_connect; + bool m_ignore_errors; + int m_n_transactions; + +private: + bool m_use_unix; + uint32_t m_server_ip_address; + std::vector m_server_ports; }; -class udp_servers_and_client -{ - public: - udp_servers_and_client(bool use_unix, - bool use_sendmsg, - bool recvmsg_twobufs, - bool use_connect, - uint32_t num_servers) - { - m_server_ip_address = get_server_address(); - struct in_addr server_in_addr; - server_in_addr.s_addr = m_server_ip_address; - m_server_address = inet_ntoa(server_in_addr); - m_use_connect = use_connect; - - for (uint32_t idx = 0; idx < num_servers; idx++) - { - m_server_ports.insert(SERVER_PORT + idx); - m_servers.emplace_back( - std::make_shared(use_unix, use_sendmsg, recvmsg_twobufs, idx)); - } +class udp_servers_and_client { +public: + udp_servers_and_client(bool use_unix, + bool use_sendmsg, + bool recvmsg_twobufs, + bool use_connect, + uint32_t num_servers) { + m_server_ip_address = get_server_address(); + struct in_addr server_in_addr; + server_in_addr.s_addr = m_server_ip_address; + m_server_address = inet_ntoa(server_in_addr); + m_use_connect = use_connect; + + for(uint32_t idx = 0; idx < num_servers; idx++) { + m_server_ports.insert(SERVER_PORT + idx); + m_servers.emplace_back( + std::make_shared(use_unix, use_sendmsg, recvmsg_twobufs, idx)); } + } - uint32_t server_ip_address() { return m_server_ip_address; } + uint32_t server_ip_address() { return m_server_ip_address; } - std::string& server_address() { return m_server_address; } + std::string& server_address() { return m_server_address; } - bool is_server_tid(int64_t tid) - { - for (auto& srv : m_servers) - { - if (tid == srv->get_tid()) - { - return true; - } + bool is_server_tid(int64_t tid) { + for(auto& srv : m_servers) { + if(tid == srv->get_tid()) { + return true; } - - return false; } - std::vector>& get_servers() { return m_servers; } + return false; + } - bool is_server_port(std::string& portstr) - { - uint16_t port = std::stoi(portstr); + std::vector>& get_servers() { return m_servers; } - return (port >= SERVER_PORT && port < SERVER_PORT + m_servers.size()); - } + bool is_server_port(std::string& portstr) { + uint16_t port = std::stoi(portstr); - bool filter(sinsp_evt* evt) { return is_server_tid(evt->get_tid()); } + return (port >= SERVER_PORT && port < SERVER_PORT + m_servers.size()); + } - std::string server_port_yaml() - { - std::stringstream out; - for (auto port : m_server_ports) - { - out << " - " << port << "\n"; - } - return out.str(); + bool filter(sinsp_evt* evt) { return is_server_tid(evt->get_tid()); } + + std::string server_port_yaml() { + std::stringstream out; + for(auto port : m_server_ports) { + out << " - " << port << "\n"; } + return out.str(); + } - void start() - { - for (uint32_t idx = 0; idx < m_servers.size(); idx++) - { - m_threads.emplace_back(std::thread(&udp_server::run, m_servers[idx])); - m_servers[idx]->wait_for_server_ready(); - } + void start() { + for(uint32_t idx = 0; idx < m_servers.size(); idx++) { + m_threads.emplace_back(std::thread(&udp_server::run, m_servers[idx])); + m_servers[idx]->wait_for_server_ready(); + } - udp_client client(m_server_ip_address, m_use_connect, SERVER_PORT, m_servers.size()); - client.run(); + udp_client client(m_server_ip_address, m_use_connect, SERVER_PORT, m_servers.size()); + client.run(); - for (auto& thread : m_threads) - { - thread.join(); - } + for(auto& thread : m_threads) { + thread.join(); } + } - private: - uint32_t m_server_ip_address; - std::string m_server_address; - std::vector m_threads; - std::vector> m_servers; - std::set m_server_ports; - bool m_use_connect; +private: + uint32_t m_server_ip_address; + std::string m_server_address; + std::vector m_threads; + std::vector> m_servers; + std::set m_server_ports; + bool m_use_connect; }; inline void parse_tuple(const std::string& tuple, - std::string& src_addr, - std::string& src_port, - std::string& dst_addr, - std::string& dst_port) -{ + std::string& src_addr, + std::string& src_port, + std::string& dst_addr, + std::string& dst_port) { std::string token; std::stringstream ss(tuple); std::vector tst; - while (std::getline(ss, token, '>')) { + while(std::getline(ss, token, '>')) { tst.push_back(token); } @@ -496,7 +435,7 @@ inline void parse_tuple(const std::string& tuple, ss.clear(); ss.str(srcstr); std::vector sst; - while (std::getline(ss, token, ':')) { + while(std::getline(ss, token, ':')) { sst.push_back(token); } @@ -507,17 +446,15 @@ inline void parse_tuple(const std::string& tuple, ss.clear(); ss.str(dststr); std::vector dst; - while (std::getline(ss, token, ':')) { + while(std::getline(ss, token, ':')) { dst.push_back(token); } EXPECT_EQ(2, (int)dst.size()); dst_addr = dst[0]; dst_port = dst[1]; - } -TEST_F(sys_call_test, udp_client_server) -{ +TEST_F(sys_call_test, udp_client_server) { int32_t state = 0; bool use_unix = false, use_sendmsg = false, recvmsg_twobufs = false, use_connect = false; uint32_t num_servers = 1; @@ -537,8 +474,7 @@ TEST_F(sys_call_test, udp_client_server) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); std::string src_addr; @@ -546,99 +482,104 @@ TEST_F(sys_call_test, udp_client_server) std::string dst_addr; std::string dst_port; - if (type == PPME_SOCKET_RECVFROM_E) - { + if(type == PPME_SOCKET_RECVFROM_E) { memcpy(&fd_server_socket, e->get_param(0)->m_val, sizeof(fd_server_socket)); } - switch (state) - { - case 0: - EXPECT_NE(PPME_SOCKET_SENDTO_X, type); - EXPECT_NE(PPME_SOCKET_RECVFROM_X, type); - - if (type == PPME_SOCKET_SENDTO_E) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, - src_port, dst_addr, dst_port); - EXPECT_EQ("0.0.0.0", src_addr); - - EXPECT_EQ(udps.server_address(), dst_addr); - EXPECT_TRUE(udps.is_server_port(dst_port)); - - state++; - } - break; - case 1: - if (type == PPME_SOCKET_RECVFROM_X) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, - src_port, dst_addr, dst_port); - - EXPECT_EQ(udps.server_address(), src_addr); - EXPECT_NE("0", src_port); - EXPECT_EQ("0.0.0.0", dst_addr); - EXPECT_TRUE(udps.is_server_port(dst_port)); - - EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); - sinsp_fdinfo* fdinfo = e->get_thread_info(false)->get_fd(fd_server_socket); - ASSERT_TRUE(fdinfo); - EXPECT_EQ(udps.server_ip_address(), fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); - - EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); - - state++; - } - break; - case 2: - EXPECT_NE(PPME_SOCKET_SENDTO_X, type); - EXPECT_NE(PPME_SOCKET_RECVFROM_X, type); - - if (type == PPME_SOCKET_SENDTO_E) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, - src_port, dst_addr, dst_port); - - EXPECT_EQ("0.0.0.0", src_addr); - EXPECT_TRUE(udps.is_server_port(src_port)); - EXPECT_EQ(udps.server_address(), dst_addr); - EXPECT_NE("0", dst_port); - - state++; - } - break; - case 3: - if (type == PPME_SOCKET_RECVFROM_X) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, - src_port, dst_addr, dst_port); - - EXPECT_EQ(udps.server_address(), src_addr); - EXPECT_TRUE(udps.is_server_port(src_port)); - - EXPECT_EQ("0.0.0.0", dst_addr); - EXPECT_NE("0", dst_port); - - EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); - sinsp_fdinfo* fdinfo = e->get_thread_info(false)->get_fd(fd_server_socket); - ASSERT_TRUE(fdinfo); - EXPECT_EQ(udps.server_ip_address(), fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); - - state = 4; - } - break; - case 4: - break; - default: - FAIL(); - break; + switch(state) { + case 0: + EXPECT_NE(PPME_SOCKET_SENDTO_X, type); + EXPECT_NE(PPME_SOCKET_RECVFROM_X, type); + + if(type == PPME_SOCKET_SENDTO_E) { + parse_tuple(e->get_param_value_str("tuple"), + src_addr, + src_port, + dst_addr, + dst_port); + EXPECT_EQ("0.0.0.0", src_addr); + + EXPECT_EQ(udps.server_address(), dst_addr); + EXPECT_TRUE(udps.is_server_port(dst_port)); + + state++; + } + break; + case 1: + if(type == PPME_SOCKET_RECVFROM_X) { + parse_tuple(e->get_param_value_str("tuple"), + src_addr, + src_port, + dst_addr, + dst_port); + + EXPECT_EQ(udps.server_address(), src_addr); + EXPECT_NE("0", src_port); + EXPECT_EQ("0.0.0.0", dst_addr); + EXPECT_TRUE(udps.is_server_port(dst_port)); + + EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); + sinsp_fdinfo* fdinfo = e->get_thread_info(false)->get_fd(fd_server_socket); + ASSERT_TRUE(fdinfo); + EXPECT_EQ(udps.server_ip_address(), fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); + + EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); + + state++; + } + break; + case 2: + EXPECT_NE(PPME_SOCKET_SENDTO_X, type); + EXPECT_NE(PPME_SOCKET_RECVFROM_X, type); + + if(type == PPME_SOCKET_SENDTO_E) { + parse_tuple(e->get_param_value_str("tuple"), + src_addr, + src_port, + dst_addr, + dst_port); + + EXPECT_EQ("0.0.0.0", src_addr); + EXPECT_TRUE(udps.is_server_port(src_port)); + EXPECT_EQ(udps.server_address(), dst_addr); + EXPECT_NE("0", dst_port); + + state++; + } + break; + case 3: + if(type == PPME_SOCKET_RECVFROM_X) { + parse_tuple(e->get_param_value_str("tuple"), + src_addr, + src_port, + dst_addr, + dst_port); + + EXPECT_EQ(udps.server_address(), src_addr); + EXPECT_TRUE(udps.is_server_port(src_port)); + + EXPECT_EQ("0.0.0.0", dst_addr); + EXPECT_NE("0", dst_port); + + EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); + sinsp_fdinfo* fdinfo = e->get_thread_info(false)->get_fd(fd_server_socket); + ASSERT_TRUE(fdinfo); + EXPECT_EQ(udps.server_ip_address(), fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); + + state = 4; + } + break; + case 4: + break; + default: + FAIL(); + break; } }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); } -TEST_F(sys_call_test, udp_client_server_with_connect_by_client) -{ +TEST_F(sys_call_test, udp_client_server_with_connect_by_client) { bool use_unix = false, use_sendmsg = false, recvmsg_twobufs = false, use_connect = true; uint32_t num_servers = 1; udp_servers_and_client udps(use_unix, use_sendmsg, recvmsg_twobufs, use_connect, num_servers); @@ -662,14 +603,11 @@ TEST_F(sys_call_test, udp_client_server_with_connect_by_client) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); - if (PPME_SOCKET_CONNECT_X == type) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, - src_port, dst_addr, dst_port); + if(PPME_SOCKET_CONNECT_X == type) { + parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port); EXPECT_EQ(udps.server_address(), src_addr); @@ -684,8 +622,7 @@ TEST_F(sys_call_test, udp_client_server_with_connect_by_client) ASSERT_EQ(1, callnum); } -TEST_F(sys_call_test, udp_client_server_sendmsg) -{ +TEST_F(sys_call_test, udp_client_server_sendmsg) { bool use_unix = false, use_sendmsg = true, recvmsg_twobufs = false, use_connect = false; uint32_t num_servers = 1; udp_servers_and_client udps(use_unix, use_sendmsg, recvmsg_twobufs, use_connect, num_servers); @@ -703,8 +640,7 @@ TEST_F(sys_call_test, udp_client_server_sendmsg) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); std::string src_addr; @@ -712,11 +648,9 @@ TEST_F(sys_call_test, udp_client_server_sendmsg) std::string dst_addr; std::string dst_port; - if (type == PPME_SOCKET_RECVMSG_X) - { + if(type == PPME_SOCKET_RECVMSG_X) { std::cout << e->get_param_value_str("tuple") << std::endl; - parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, - dst_addr, dst_port); + parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port); EXPECT_EQ(udps.server_address(), src_addr); EXPECT_NE("0", src_port); @@ -727,11 +661,8 @@ TEST_F(sys_call_test, udp_client_server_sendmsg) EXPECT_EQ(udps.server_ip_address(), e->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_sip); - } - else if (type == PPME_SOCKET_SENDMSG_E) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, - dst_addr, dst_port); + } else if(type == PPME_SOCKET_SENDMSG_E) { + parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port); EXPECT_EQ("0.0.0.0", src_addr); EXPECT_TRUE(udps.is_server_port(src_port)); @@ -739,9 +670,7 @@ TEST_F(sys_call_test, udp_client_server_sendmsg) EXPECT_NE("0", dst_port); EXPECT_EQ((int)BUFFER_LENGTH, std::stoi(e->get_param_value_str("size"))); - } - else if (type == PPME_SOCKET_SENDMSG_X) - { + } else if(type == PPME_SOCKET_SENDMSG_X) { EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); } }; @@ -749,8 +678,7 @@ TEST_F(sys_call_test, udp_client_server_sendmsg) ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); } -TEST_F(sys_call_test, udp_client_server_sendmsg_2buf) -{ +TEST_F(sys_call_test, udp_client_server_sendmsg_2buf) { bool use_unix = false, use_sendmsg = true, recvmsg_twobufs = true, use_connect = false; uint32_t num_servers = 1; udp_servers_and_client udps(use_unix, use_sendmsg, recvmsg_twobufs, use_connect, num_servers); @@ -768,8 +696,7 @@ TEST_F(sys_call_test, udp_client_server_sendmsg_2buf) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; uint16_t type = e->get_type(); std::string src_addr; @@ -777,10 +704,8 @@ TEST_F(sys_call_test, udp_client_server_sendmsg_2buf) std::string dst_addr; std::string dst_port; - if (type == PPME_SOCKET_RECVMSG_X) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, - dst_addr, dst_port); + if(type == PPME_SOCKET_RECVMSG_X) { + parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port); EXPECT_EQ(udps.server_address(), src_addr); EXPECT_NE("0", src_port); @@ -791,11 +716,8 @@ TEST_F(sys_call_test, udp_client_server_sendmsg_2buf) EXPECT_EQ(udps.server_ip_address(), e->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_sip); - } - else if (type == PPME_SOCKET_SENDMSG_E) - { - parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, - dst_addr, dst_port); + } else if(type == PPME_SOCKET_SENDMSG_E) { + parse_tuple(e->get_param_value_str("tuple"), src_addr, src_port, dst_addr, dst_port); EXPECT_EQ("0.0.0.0", src_addr); EXPECT_TRUE(udps.is_server_port(src_port)); @@ -803,9 +725,7 @@ TEST_F(sys_call_test, udp_client_server_sendmsg_2buf) EXPECT_EQ(udps.server_address(), dst_addr); EXPECT_NE("0", dst_port); EXPECT_EQ((int)BUFFER_LENGTH, std::stoi(e->get_param_value_str("size"))); - } - else if (type == PPME_SOCKET_SENDMSG_X) - { + } else if(type == PPME_SOCKET_SENDMSG_X) { EXPECT_EQ(PAYLOAD, e->get_param_value_str("data")); } }; @@ -817,8 +737,7 @@ static void run_fd_name_changed_test(bool use_sendmsg, bool recvmsg_twobufs, bool use_connect, event_filter_t m_tid_filter, - uint32_t expected_name_changed_evts) -{ + uint32_t expected_name_changed_evts) { bool use_unix = false; uint32_t num_servers = 2; udp_servers_and_client udps(use_unix, use_sendmsg, recvmsg_twobufs, use_connect, num_servers); @@ -828,8 +747,7 @@ static void run_fd_name_changed_test(bool use_sendmsg, uint32_t num_name_changed_evts = 0; // INIT FILTER - before_open_t before_open = [&](sinsp* inspector) - { + before_open_t before_open = [&](sinsp* inspector) { sinsp_filter_compiler compiler(inspector, "fd.name_changed=true"); fd_name_changed = std::move(compiler.compile()); }; @@ -847,11 +765,9 @@ static void run_fd_name_changed_test(bool use_sendmsg, // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (fd_name_changed->run(e)) - { + if(fd_name_changed->run(e)) { num_name_changed_evts++; } }; @@ -861,8 +777,7 @@ static void run_fd_name_changed_test(bool use_sendmsg, ASSERT_EQ(num_name_changed_evts, expected_name_changed_evts); } -TEST_F(sys_call_test, udp_client_server_fd_name_changed) -{ +TEST_F(sys_call_test, udp_client_server_fd_name_changed) { bool use_sendmsg = false, recvmsg_twobufs = false, use_connect = false; // This test only needs to count events. We want to @@ -888,8 +803,7 @@ TEST_F(sys_call_test, udp_client_server_fd_name_changed) run_fd_name_changed_test(use_sendmsg, recvmsg_twobufs, use_connect, m_tid_filter, 7); } -TEST_F(sys_call_test, udp_client_server_connect_fd_name_changed) -{ +TEST_F(sys_call_test, udp_client_server_connect_fd_name_changed) { bool use_sendmsg = false, recvmsg_twobufs = false, use_connect = true; // When the client uses connect, there is one fewer name @@ -899,21 +813,18 @@ TEST_F(sys_call_test, udp_client_server_connect_fd_name_changed) run_fd_name_changed_test(use_sendmsg, recvmsg_twobufs, use_connect, m_tid_filter, 6); } -TEST_F(sys_call_test, udp_client_server_sendmsg_fd_name_changed) -{ +TEST_F(sys_call_test, udp_client_server_sendmsg_fd_name_changed) { bool use_sendmsg = true, recvmsg_twobufs = false, use_connect = false; run_fd_name_changed_test(use_sendmsg, recvmsg_twobufs, use_connect, m_tid_filter, 7); } -TEST_F(sys_call_test, udp_client_server_multiple_connect_name_changed) -{ +TEST_F(sys_call_test, udp_client_server_multiple_connect_name_changed) { unique_ptr fd_name_changed; uint32_t num_name_changed_evts = 0; // INIT FILTER - before_open_t before_open = [&](sinsp* inspector) - { + before_open_t before_open = [&](sinsp* inspector) { sinsp_filter_compiler compiler(inspector, "fd.name_changed=true"); fd_name_changed = std::move(compiler.compile()); }; @@ -926,20 +837,17 @@ TEST_F(sys_call_test, udp_client_server_multiple_connect_name_changed) // // INITIALIZATION // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { int sd; sd = socket(AF_INET, SOCK_DGRAM, 0); - if (sd < 0) - { + if(sd < 0) { FAIL(); } std::list ports = {8172, 8193, 8193, 8172, 8171}; - for (auto& port : ports) - { + for(auto& port : ports) { struct sockaddr_in serveraddr; memset(&serveraddr, 0, sizeof(serveraddr)); @@ -947,8 +855,7 @@ TEST_F(sys_call_test, udp_client_server_multiple_connect_name_changed) serveraddr.sin_port = htons(port); serveraddr.sin_addr.s_addr = get_server_address(); - if (connect(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0) - { + if(connect(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0) { close(sd); FAIL() << "connect() failed"; } @@ -958,11 +865,9 @@ TEST_F(sys_call_test, udp_client_server_multiple_connect_name_changed) // // OUTPUT VALDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; - if (fd_name_changed->run(e)) - { + if(fd_name_changed->run(e)) { num_name_changed_evts++; } }; @@ -973,30 +878,25 @@ TEST_F(sys_call_test, udp_client_server_multiple_connect_name_changed) ASSERT_EQ(num_name_changed_evts, 4u); } -TEST_F(sys_call_test, udp_client_server_sendmsg_2buf_fd_name_changed) -{ +TEST_F(sys_call_test, udp_client_server_sendmsg_2buf_fd_name_changed) { bool use_sendmsg = true, recvmsg_twobufs = true, use_connect = false; run_fd_name_changed_test(use_sendmsg, recvmsg_twobufs, use_connect, m_tid_filter, 7); } -TEST_F(sys_call_test, statsd_client_snaplen) -{ +TEST_F(sys_call_test, statsd_client_snaplen) { // Test if the driver correctly increase snaplen for statsd traffic std::string payload = - "soluta.necessitatibus.voluptatem.consequuntur.dignissimos.repudiandae.nostrum.lorem.ipsum:" - "18|c"; + "soluta.necessitatibus.voluptatem.consequuntur.dignissimos.repudiandae.nostrum.lorem." + "ipsum:" + "18|c"; - before_open_t setup = [&](sinsp* inspector) - { - inspector->dynamic_snaplen(true); - }; + before_open_t setup = [&](sinsp* inspector) { inspector->dynamic_snaplen(true); }; // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt) && (evt->get_type() == PPME_SOCKET_SENDMSG_X || evt->get_type() == PPME_SOCKET_SENDTO_X); }; @@ -1004,8 +904,7 @@ TEST_F(sys_call_test, statsd_client_snaplen) // // INITIALIZATION // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { // sendto with addr udp_client client(0x0100007F, false, 8125); client.m_payload = payload; @@ -1032,36 +931,30 @@ TEST_F(sys_call_test, statsd_client_snaplen) // OUTPUT VALDATION // int n = 0; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; EXPECT_EQ(payload, e->get_param_value_str("data")) - << "Failure on " << e->get_name() << " n=" << n; + << "Failure on " << e->get_name() << " n=" << n; n++; }; - before_close_t cleanup = [&](sinsp* inspector) - { - inspector->dynamic_snaplen(false); - }; - + before_close_t cleanup = [&](sinsp* inspector) { inspector->dynamic_snaplen(false); }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter, setup, cleanup); }); EXPECT_EQ(4, n); } -TEST_F(sys_call_test, statsd_client_no_snaplen) -{ +TEST_F(sys_call_test, statsd_client_no_snaplen) { // Test if the driver correctly increase snaplen for statsd traffic std::string payload = - "soluta.necessitatibus.voluptatem.consequuntur.dignissimos.repudiandae.nostrum.lorem.ipsum:" - "18|c"; + "soluta.necessitatibus.voluptatem.consequuntur.dignissimos.repudiandae.nostrum.lorem." + "ipsum:" + "18|c"; // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { return m_tid_filter(evt) && (evt->get_type() == PPME_SOCKET_SENDMSG_X || evt->get_type() == PPME_SOCKET_SENDTO_X); }; @@ -1069,8 +962,7 @@ TEST_F(sys_call_test, statsd_client_no_snaplen) // // INITIALIZATION // - run_callback_t test = [&](concurrent_object_handle inspector_handle) - { + run_callback_t test = [&](concurrent_object_handle inspector_handle) { // sendto with addr // Different port udp_client client(0x0100007F, false, 8126); @@ -1098,12 +990,11 @@ TEST_F(sys_call_test, statsd_client_no_snaplen) // OUTPUT VALDATION // int n = 0; - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* e = param.m_evt; ++n; EXPECT_EQ(payload.substr(0, 80), e->get_param_value_str("data")) - << "Failure on " << e->get_name() << " n=" << n; + << "Failure on " << e->get_name() << " n=" << n; }; ASSERT_NO_FATAL_FAILURE({ event_capture::run(test, callback, filter); }); diff --git a/test/libsinsp_e2e/unix_client_server.cpp b/test/libsinsp_e2e/unix_client_server.cpp index 9dc537033b..6d4d38004e 100644 --- a/test/libsinsp_e2e/unix_client_server.cpp +++ b/test/libsinsp_e2e/unix_client_server.cpp @@ -51,34 +51,33 @@ limitations under the License. #define FALSE 0 inline void parse_tuple(const std::string& tuple, - std::string& srcstr, - std::string& dststr, bool shift = false) -{ + std::string& srcstr, + std::string& dststr, + bool shift = false) { std::string token; std::stringstream ss(tuple); std::vector tst; - int base = shift? 1 : 0; + int base = shift ? 1 : 0; - while (std::getline(ss, token, '>')) { + while(std::getline(ss, token, '>')) { tst.push_back(token); } - int size = shift? 3 : 2; + int size = shift ? 3 : 2; EXPECT_EQ(size, (int)tst.size()); srcstr = tst[base].substr(0, tst[base].size() - 1); - dststr = tst[base+1]; + dststr = tst[base + 1]; } -inline bool ends_with(const std::string& value, const std::string& ending) -{ - if (ending.size() > value.size()) return false; +inline bool ends_with(const std::string& value, const std::string& ending) { + if(ending.size() > value.size()) + return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } -TEST_F(sys_call_test, unix_client_server) -{ +TEST_F(sys_call_test, unix_client_server) { int32_t callnum = 0; bool first_connect_or_accept_seen = true; std::string sport; @@ -88,15 +87,12 @@ TEST_F(sys_call_test, unix_client_server) // // FILTER // - event_filter_t filter = [&](sinsp_evt* evt) - { + event_filter_t filter = [&](sinsp_evt* evt) { sinsp_threadinfo* ti = evt->get_thread_info(false); - if (ti) - { - if (ti->get_comm() == "python2" && ti->m_args.size() >= 1) - { - return ends_with(ti->m_args[0],"unix_client_server.py") || - ends_with(ti->m_args[0],"unix_client_server.py"); + if(ti) { + if(ti->get_comm() == "python2" && ti->m_args.size() >= 1) { + return ends_with(ti->m_args[0], "unix_client_server.py") || + ends_with(ti->m_args[0], "unix_client_server.py"); } } @@ -106,13 +102,14 @@ TEST_F(sys_call_test, unix_client_server) // // INITIALIZATION // - run_callback_t test = [](concurrent_object_handle inspector) - { - subprocess server("python2", {LIBSINSP_TEST_RESOURCES_PATH "/unix_client_server.py", "server"}); + run_callback_t test = [](concurrent_object_handle inspector) { + subprocess server("python2", + {LIBSINSP_TEST_RESOURCES_PATH "/unix_client_server.py", "server"}); server.wait_for_start(); - subprocess client("python2", {LIBSINSP_TEST_RESOURCES_PATH "/unix_client_server.py", "client"}); + subprocess client("python2", + {LIBSINSP_TEST_RESOURCES_PATH "/unix_client_server.py", "client"}); server.wait(); client.wait(); }; @@ -120,14 +117,12 @@ TEST_F(sys_call_test, unix_client_server) // // OUTPUT VALIDATION // - captured_event_callback_t callback = [&](const callback_param& param) - { + captured_event_callback_t callback = [&](const callback_param& param) { sinsp_evt* evt = param.m_evt; - //std::cout << evt->get_name() << std::endl; + // std::cout << evt->get_name() << std::endl; - if (evt->get_type() == PPME_SOCKET_CONNECT_X) - { + if(evt->get_type() == PPME_SOCKET_CONNECT_X) { std::string tuple = evt->get_param_value_str("tuple"); std::string addrs = tuple.substr(0, tuple.find(" ")); std::string file = tuple.substr(tuple.find(" ") + 1); @@ -145,23 +140,18 @@ TEST_F(sys_call_test, unix_client_server) // connect() and accept() can return // in a different order // - if (first_connect_or_accept_seen) - { + if(first_connect_or_accept_seen) { first_connect_or_accept_seen = false; src_addr = srcstr.substr(1); dest_addr = dststr; - } - else - { + } else { EXPECT_EQ(src_addr, srcstr.substr(1)); EXPECT_EQ(dest_addr, dststr); } callnum++; - } - else if ((evt->get_type() == PPME_SOCKET_ACCEPT_5_X) || - (evt->get_type() == PPME_SOCKET_ACCEPT4_6_X)) - { + } else if((evt->get_type() == PPME_SOCKET_ACCEPT_5_X) || + (evt->get_type() == PPME_SOCKET_ACCEPT4_6_X)) { std::string tuple = evt->get_param_value_str("tuple"); std::string addrs = tuple.substr(0, tuple.find(" ")); std::string file = tuple.substr(tuple.find(" ") + 1); @@ -179,14 +169,11 @@ TEST_F(sys_call_test, unix_client_server) // connect() and accept() can return // in a different order // - if (first_connect_or_accept_seen) - { + if(first_connect_or_accept_seen) { first_connect_or_accept_seen = false; src_addr = srcstr.substr(1); dest_addr = dststr; - } - else - { + } else { EXPECT_EQ(src_addr, srcstr.substr(1)); EXPECT_EQ(dest_addr, dststr); } @@ -207,8 +194,7 @@ TEST_F(sys_call_test, unix_client_server) callnum++; } - if (callnum < 1) - { + if(callnum < 1) { return; } @@ -216,13 +202,11 @@ TEST_F(sys_call_test, unix_client_server) // 32bit (and s390x) uses send() and recv(), while 64bit // uses sendto() and recvfrom() and sets the address to NULL // - if (evt->get_type() == PPME_SOCKET_SEND_E || evt->get_type() == PPME_SOCKET_RECV_E || - evt->get_type() == PPME_SOCKET_SENDTO_E || evt->get_type() == PPME_SOCKET_RECVFROM_E) - { - if (((evt->get_type() == PPME_SOCKET_RECVFROM_X) || - (evt->get_type() == PPME_SOCKET_RECVFROM_X)) && - (evt->get_param_value_str("tuple") != "")) - { + if(evt->get_type() == PPME_SOCKET_SEND_E || evt->get_type() == PPME_SOCKET_RECV_E || + evt->get_type() == PPME_SOCKET_SENDTO_E || evt->get_type() == PPME_SOCKET_RECVFROM_E) { + if(((evt->get_type() == PPME_SOCKET_RECVFROM_X) || + (evt->get_type() == PPME_SOCKET_RECVFROM_X)) && + (evt->get_param_value_str("tuple") != "")) { EXPECT_EQ("NULL", evt->get_param_value_str("tuple")); } @@ -240,27 +224,23 @@ TEST_F(sys_call_test, unix_client_server) EXPECT_NE("0", fddststr); callnum++; - } - else if ((evt->get_type() == PPME_SOCKET_RECV_X) || - (evt->get_type() == PPME_SOCKET_RECVFROM_X)) - { - if (evt->get_type() == PPME_SOCKET_RECVFROM_X) - { - if (callnum == 5) - { - std::string tuple = evt->get_param_value_str("tuple"); - std::string addrs = tuple.substr(0, tuple.find(" ")); - std::string file = tuple.substr(tuple.find(" ") + 1); - - EXPECT_EQ(NAME, file); + } else if((evt->get_type() == PPME_SOCKET_RECV_X) || + (evt->get_type() == PPME_SOCKET_RECVFROM_X)) { + if(evt->get_type() == PPME_SOCKET_RECVFROM_X) { + if(callnum == 5) { + std::string tuple = evt->get_param_value_str("tuple"); + std::string addrs = tuple.substr(0, tuple.find(" ")); + std::string file = tuple.substr(tuple.find(" ") + 1); + + EXPECT_EQ(NAME, file); std::string srcstr; std::string dststr; parse_tuple(tuple, srcstr, dststr); - EXPECT_NE("0000000000000000", srcstr); - EXPECT_NE("0000000000000000", dststr); - } + EXPECT_NE("0000000000000000", srcstr); + EXPECT_NE("0000000000000000", dststr); + } } EXPECT_EQ(PAYLOAD, evt->get_param_value_str("data")); @@ -275,4 +255,3 @@ TEST_F(sys_call_test, unix_client_server) EXPECT_FALSE(first_connect_or_accept_seen); EXPECT_EQ(8, callnum); } - diff --git a/test/libsinsp_e2e/utils.h b/test/libsinsp_e2e/utils.h index 0514a0eab1..426156458c 100644 --- a/test/libsinsp_e2e/utils.h +++ b/test/libsinsp_e2e/utils.h @@ -25,23 +25,21 @@ limitations under the License. #include inline bool parse_tuple(const std::string& tuple, - std::string& src_addr, - std::string& src_port, - std::string& dst_addr, - std::string& dst_port) -{ + std::string& src_addr, + std::string& src_port, + std::string& dst_addr, + std::string& dst_port) { std::string token; std::stringstream ss(tuple); std::vector tst; std::string srcstr; std::string dststr; - if(tuple.find("->") == std::string::npos) - { + if(tuple.find("->") == std::string::npos) { return false; } - while (std::getline(ss, token, '>')) { + while(std::getline(ss, token, '>')) { tst.push_back(token); } @@ -51,7 +49,7 @@ inline bool parse_tuple(const std::string& tuple, ss.clear(); ss.str(srcstr); std::vector sst; - while (std::getline(ss, token, ':')) { + while(std::getline(ss, token, ':')) { sst.push_back(token); } @@ -62,7 +60,7 @@ inline bool parse_tuple(const std::string& tuple, ss.clear(); ss.str(dststr); std::vector dst; - while (std::getline(ss, token, ':')) { + while(std::getline(ss, token, ':')) { dst.push_back(token); } EXPECT_EQ(2, (int)dst.size()); @@ -72,8 +70,7 @@ inline bool parse_tuple(const std::string& tuple, return true; } -class nsenter -{ +class nsenter { public: nsenter(int pid, const std::string& type); virtual ~nsenter(); diff --git a/test/libsinsp_e2e/vtidcollision.c b/test/libsinsp_e2e/vtidcollision.c index 180ac5fe2d..604b4ed760 100644 --- a/test/libsinsp_e2e/vtidcollision.c +++ b/test/libsinsp_e2e/vtidcollision.c @@ -63,58 +63,48 @@ limitations under the License. * */ -void waitall() -{ +void waitall() { int status; - while (wait(&status) == 0 || errno == EAGAIN) - { + while(wait(&status) == 0 || errno == EAGAIN) { } } -int child_main(int efd, int parent_efd) -{ +int child_main(int efd, int parent_efd) { char buf[64]; char* endptr; long init_ns_pid; unsigned long efd_counter = 0; - while (efd_counter < 2) - { - switch (fork()) - { + while(efd_counter < 2) { + switch(fork()) { case -1: abort(); case 0: - if (readlink("/proc/self", buf, sizeof(buf)) <= 0) - { + if(readlink("/proc/self", buf, sizeof(buf)) <= 0) { eventfd_write(efd, 2); _exit(1); } init_ns_pid = strtoul(buf, &endptr, 10); - if (getpid() == init_ns_pid) - { + if(getpid() == init_ns_pid) { int pid = getpid(); usleep(100000); eventfd_write(efd, 2); - if (setuid(getpid()) != 0 || seteuid(getpid()) != 0) - { + if(setuid(getpid()) != 0 || seteuid(getpid()) != 0) { _exit(1); } - switch (fork()) - { + switch(fork()) { case -1: abort(); case 0: - if (readlink("/proc/self", buf, sizeof(buf)) <= 0) - { + if(readlink("/proc/self", buf, sizeof(buf)) <= 0) { _exit(1); } @@ -137,8 +127,7 @@ int child_main(int efd, int parent_efd) break; } } - if (eventfd_write(parent_efd, 2) != 0) - { + if(eventfd_write(parent_efd, 2) != 0) { abort(); } waitall(); @@ -146,15 +135,12 @@ int child_main(int efd, int parent_efd) return 0; } -int parent_main(int efd) -{ +int parent_main(int efd) { unsigned long efd_counter = 0; int ret; - while (efd_counter < 2) - { - switch (fork()) - { + while(efd_counter < 2) { + switch(fork()) { case -1: abort(); @@ -163,8 +149,7 @@ int parent_main(int efd) default: ret = eventfd_read(efd, &efd_counter); - if (ret >= 2) - { + if(ret >= 2) { abort(); } break; @@ -175,25 +160,21 @@ int parent_main(int efd) return 0; } -int main() -{ +int main() { printf("STARTED\n"); fflush(stdout); signal(SIGCHLD, SIG_IGN); int efd = eventfd(1, EFD_NONBLOCK); int parent_efd = eventfd(1, EFD_NONBLOCK); - switch (fork()) - { + switch(fork()) { case -1: return 1; case 0: - if (unshare(CLONE_NEWPID) != 0) - { + if(unshare(CLONE_NEWPID) != 0) { abort(); } - switch (fork()) - { + switch(fork()) { case -1: abort(); case 0: diff --git a/test/vm/CMakeLists.txt b/test/vm/CMakeLists.txt index 08775186bb..4f70bb00e9 100644 --- a/test/vm/CMakeLists.txt +++ b/test/vm/CMakeLists.txt @@ -2,7 +2,8 @@ set(UBUNTU_CONTAINER1 "vm-ubuntu2004:latest") set(UBUNTU_CONTAINER2 "vm-ubuntu2204:latest") set(UBUNTU_CONTAINER3 "vm-ubuntu2404:latest") set(DEBIANBUSTER_CONTAINER "vm-debianbuster:latest") -# TODO In case we have an equivalent upstream supported container, remove the custom modern-falco-builder +# TODO In case we have an equivalent upstream supported container, remove the custom +# modern-falco-builder set(MODERN_FALCO_BUILDER_CONTAINER "modern-falco-builder:latest") set(VM_PROVIDER_VBOX "virtualbox") set(VM_NAMES_VBOX_VAGRANT_CENTOS7 "centos7") @@ -10,70 +11,92 @@ set(VM_NAMES_VBOX_VAGRANT_UBUNTU "ubuntu") set(VM_NAMES_VBOX_VAGRANT_AMAZONLINUX2 "amazonlinux2") set(VM_NAMES_VBOX_VAGRANT "centos7 ubuntu amazonlinux2") # needs to be one string -set(VM_CONTAINERS - ${UBUNTU_CONTAINER1} - ${UBUNTU_CONTAINER2} - ${UBUNTU_CONTAINER3} - ${DEBIANBUSTER_CONTAINER} - ${MODERN_FALCO_BUILDER_CONTAINER} +set(VM_CONTAINERS ${UBUNTU_CONTAINER1} ${UBUNTU_CONTAINER2} ${UBUNTU_CONTAINER3} + ${DEBIANBUSTER_CONTAINER} ${MODERN_FALCO_BUILDER_CONTAINER} ) -add_custom_target(vm-dependency-check - COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/dependency_check.sh; +add_custom_target( + vm-dependency-check COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/dependency_check.sh; ) -add_custom_target(vm-container - COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/ubuntu2004.Dockerfile -t ${UBUNTU_CONTAINER1} .; - COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/ubuntu2204.Dockerfile -t ${UBUNTU_CONTAINER2} .; - COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/ubuntu2404.Dockerfile -t ${UBUNTU_CONTAINER3} .; - COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/debianbuster.Dockerfile -t ${DEBIANBUSTER_CONTAINER} .; - COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/modern-falco-builder.Dockerfile -t ${MODERN_FALCO_BUILDER_CONTAINER} .; +add_custom_target( + vm-container + COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/ubuntu2004.Dockerfile -t + ${UBUNTU_CONTAINER1} .; + COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/ubuntu2204.Dockerfile -t + ${UBUNTU_CONTAINER2} .; + COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/ubuntu2404.Dockerfile -t + ${UBUNTU_CONTAINER3} .; + COMMAND time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/debianbuster.Dockerfile -t + ${DEBIANBUSTER_CONTAINER} .; + COMMAND + time docker build -f ${CMAKE_CURRENT_SOURCE_DIR}/containers/modern-falco-builder.Dockerfile + -t ${MODERN_FALCO_BUILDER_CONTAINER} .; ) -add_custom_target(vm-kernel +add_custom_target( + vm-kernel COMMAND mkdir -p ${CMAKE_CURRENT_SOURCE_DIR}/build; - COMMAND time docker run -v ${CMAKE_CURRENT_SOURCE_DIR}:/vm:z ${UBUNTU_CONTAINER2} '/bin/bash /vm/scripts/kernel_download.sh /vm/build /vm/kernels.jsonl'; - COMMAND time docker run -v ${CMAKE_CURRENT_SOURCE_DIR}:/vm:z ${UBUNTU_CONTAINER2} '/bin/bash /vm/scripts/kernel_extract.sh /vm/build/headers /vm/build/headers_extracted'; + COMMAND time docker run -v ${CMAKE_CURRENT_SOURCE_DIR}:/vm:z ${UBUNTU_CONTAINER2} '/bin/bash + /vm/scripts/kernel_download.sh /vm/build /vm/kernels.jsonl'; + COMMAND time docker run -v ${CMAKE_CURRENT_SOURCE_DIR}:/vm:z ${UBUNTU_CONTAINER2} '/bin/bash + /vm/scripts/kernel_extract.sh /vm/build/headers /vm/build/headers_extracted'; DEPENDS vm-container ) # Prepares containers, kernel packages and VMs for vm-tests - typically run once -add_custom_target(vm-init - COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_init.sh ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT}; +add_custom_target( + vm-init + COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_init.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT}; DEPENDS vm-kernel ) # Main test to build scap-open and each driver for array of compiler versions -add_custom_target(vm-compile +add_custom_target( + vm-compile COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_compile.sh ${CMAKE_CURRENT_SOURCE_DIR}; - COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} ${UBUNTU_CONTAINER2}; + COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${UBUNTU_CONTAINER2}; ) # Loop over centos7 kernels -add_custom_target(vm-centos7 - COMMAND time bash -c 'bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vagrant_loop.sh ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT_CENTOS7}'; - COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} ${UBUNTU_CONTAINER2}; +add_custom_target( + vm-centos7 + COMMAND time bash -c 'bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vagrant_loop.sh + ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT_CENTOS7}'; + COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${UBUNTU_CONTAINER2}; ) # Loop over ubuntu kernels -add_custom_target(vm-ubuntu - COMMAND time bash -c 'bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vagrant_loop.sh ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT_UBUNTU}'; - COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} ${UBUNTU_CONTAINER2}; +add_custom_target( + vm-ubuntu + COMMAND time bash -c 'bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vagrant_loop.sh + ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT_UBUNTU}'; + COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${UBUNTU_CONTAINER2}; ) # Loop over amazonlinux2 kernels, less stable, can have issues recovering from failed kmod tests -add_custom_target(vm-amazonlinux2 - COMMAND time bash -c 'bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vagrant_loop.sh ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT_AMAZONLINUX2}'; - COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} ${UBUNTU_CONTAINER2}; +add_custom_target( + vm-amazonlinux2 + COMMAND time bash -c 'bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vagrant_loop.sh + ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX} ${VM_NAMES_VBOX_VAGRANT_AMAZONLINUX2}'; + COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${UBUNTU_CONTAINER2}; ) # Create result tables -add_custom_target(vm-result - COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh ${CMAKE_CURRENT_SOURCE_DIR} ${UBUNTU_CONTAINER2}; +add_custom_target( + vm-result COMMAND time bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_result.sh + ${CMAKE_CURRENT_SOURCE_DIR} ${UBUNTU_CONTAINER2}; ) -add_custom_target(vm-cleanup +add_custom_target( + vm-cleanup COMMAND docker rm -f ${VM_CONTAINERS}; COMMAND docker image rm -f ${VM_CONTAINERS}; - COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_cleanup.sh ${CMAKE_CURRENT_SOURCE_DIR} ${VM_PROVIDER_VBOX}; + COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/scripts/vm_cleanup.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${VM_PROVIDER_VBOX}; ) diff --git a/userspace/libpman/CMakeLists.txt b/userspace/libpman/CMakeLists.txt index da92e9f275..8457571158 100644 --- a/userspace/libpman/CMakeLists.txt +++ b/userspace/libpman/CMakeLists.txt @@ -2,59 +2,52 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # add_compile_options(${FALCOSECURITY_LIBS_USERSPACE_COMPILE_FLAGS}) add_link_options(${FALCOSECURITY_LIBS_USERSPACE_LINK_FLAGS}) -add_library(pman - src/stats.c - src/maps.c - src/lifecycle.c - src/programs.c - src/ringbuffer.c - src/configuration.c - src/state.c - src/sc_set.c +add_library( + pman + src/stats.c + src/maps.c + src/lifecycle.c + src/programs.c + src/ringbuffer.c + src/configuration.c + src/state.c + src/sc_set.c ) -target_include_directories(pman -PUBLIC - $ -PRIVATE - $ - $ # ppm_enum and tables - $ # scap-stats struct - ${ZLIB_INCLUDE} - ${LIBBPF_INCLUDE} - ${MODERN_BPF_SKEL_DIR} - ${LIBELF_INCLUDE} +target_include_directories( + pman + PUBLIC $ + PRIVATE $ + $ # ppm_enum and tables + $ # scap-stats struct + ${ZLIB_INCLUDE} + ${LIBBPF_INCLUDE} + ${MODERN_BPF_SKEL_DIR} + ${LIBELF_INCLUDE} ) -target_link_libraries(pman -PUBLIC - scap_event_schema - scap_platform - ${LIBBPF_LIB} - ${LIBELF_LIB} - ${ZLIB_LIB} +target_link_libraries( + pman PUBLIC scap_event_schema scap_platform ${LIBBPF_LIB} ${LIBELF_LIB} ${ZLIB_LIB} ) -if (TARGET ProbeSkeleton) - add_dependencies(pman ProbeSkeleton) +if(TARGET ProbeSkeleton) + add_dependencies(pman ProbeSkeleton) endif() if(USE_BUNDLED_LIBBPF) - add_dependencies(pman libbpf) + add_dependencies(pman libbpf) endif() diff --git a/userspace/libpman/include/libpman.h b/userspace/libpman/include/libpman.h index eaf473fc0c..00c9f8212f 100644 --- a/userspace/libpman/include/libpman.h +++ b/userspace/libpman/include/libpman.h @@ -24,437 +24,438 @@ limitations under the License. #include #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - /* Forward declare them */ - struct metrics_v2; - struct scap_stats; - - /* `libpman` return values convention: - * In case of success `0` is returned otherwise `errno`. If `errno` is not - * available `-1` is returned. - * - * Please Note: - * Libbpf always sets `errno` to the corresponding Exx (positive) error code. - * Libbpf APIs usually return `0` in case of success. - */ - - ///////////////////////////// - // SETUP CONFIGURATION - ///////////////////////////// - - /** - * @brief Set `libpman` initial state: - * - set `libbpf` strict mode. - * - set `libbpf` logging function according to the verbosity. - * - set available number of CPUs. - * - set dimension of a single per-CPU ring buffer. - * - * @param log_fn logging callback - * @param buf_bytes_dim dimension of a single per-CPU buffer in bytes. - * @param cpus_for_each_buffer number of CPUs to which we want to associate a ring buffer. - * @param allocate_online_only if true, allocate ring buffers taking only into account online CPUs. - * @return `0` on success, `-1` in case of error. - */ - int pman_init_state(falcosecurity_log_fn log_fn, unsigned long buf_bytes_dim, uint16_t cpus_for_each_buffer, - bool allocate_online_only); - - /** - * @brief Clear the `libpman` global state before it is used. - * This API could be useful if we open the modern bpf engine multiple times. - */ - void pman_clear_state(void); - - /** - * @brief Return the number of allocated ring buffers. - * - * @return number of allocated ring buffers. - */ - int pman_get_required_buffers(void); - - /** - * @brief Return whether modern bpf is supported by running kernel. - * - * @return supported true or false. - */ - bool pman_check_support(); - - ///////////////////////////// - // PROBE LIFECYCLE - ///////////////////////////// - - /** - * @brief Open the bpf skeleton obtaining a pointer - * to it. - * - * @return `0` on success, `errno` in case of error. - */ - int pman_open_probe(void); - - /** - * @brief Load into the kernel all the programs and maps - * contained into the skeleton. - * - * @return `0` on success, `errno` in case of error. - */ - int pman_load_probe(void); - - /** - * @brief Clean what we have previously allocated: - * - bpf_skeleton - * - ringbuffer manager - * - consumers/producers vectors - * - stats buffer dynamically allocated - */ - void pman_close_probe(void); - - ///////////////////////////// - // ATTACH PROGRAMS - ///////////////////////////// - - /// todo(@Andreagit97): these methods probably shouldn't be exposed to the final users - /** - * @brief Attach only the syscall_exit_dispatcher - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_syscall_exit_dispatcher(void); - - /** - * @brief Detach only the syscall_exit_dispatcher - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_syscall_exit_dispatcher(void); - - /** - * @brief Attach only the syscall_enter_dispatcher - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_syscall_enter_dispatcher(void); - - /** - * @brief Detach only the syscall_enter_dispatcher - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_syscall_enter_dispatcher(void); - - /** - * @brief Attach only the sched_process_exit tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_sched_proc_exit(void); - - /** - * @brief Detach only the sched_process_exit tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_sched_proc_exit(void); - - /** - * @brief Attach only the sched_switch tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_sched_switch(void); - - /** - * @brief Detach only the sched_switch tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_sched_switch(void); - - /** - * @brief Attach only the sched_proc_exec tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_sched_proc_exec(void); - - /** - * @brief Detach only the sched_proc_exec tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_sched_proc_exec(void); - - /** - * @brief Attach only the sched_proc_fork tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_sched_proc_fork(void); - - /** - * @brief Detach only the sched_proc_fork tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_sched_proc_fork(void); - - /** - * @brief Attach only the page_fault_user tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_page_fault_user(void); - - /** - * @brief Detach only the page_fault_user tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_page_fault_user(void); - - /** - * @brief Attach only the page_fault_kernel tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_page_fault_kernel(void); - - /** - * @brief Detach only the page_fault_kernel tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_page_fault_kernel(void); - - /** - * @brief Attach only the signal_deliver tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_attach_signal_deliver(void); - - /** - * @brief Detach only the signal_deliver tracepoint - * - * @return `0` on success, `errno` in case of error. - */ - int pman_detach_signal_deliver(void); - - ///////////////////////////// - // MANAGE RINGBUFFERS - ///////////////////////////// - - /** - * @brief Performs all necessary operations on ringbuf array before the - * loading phase: - * - Set inner map dimension. - * - Set array max entries. - * - Allocate memory for producers and consumers. - * - * @return `0` on success, `errno` in case of error. - */ - int pman_prepare_ringbuf_array_before_loading(void); - - /** - * @brief Performs all necessary operations on ringbuf array after the - * loading phase: - * - Create all the ring_buffer maps inside the array. - * - * @return `0` on success, `errno` in case of error. - */ - int pman_finalize_ringbuf_array_after_loading(void); - - /** - * @brief Search for the event with the lowest timestamp in - * all the ring buffers. - * - * @param event_ptr in case of success return a pointer - * to the event, otherwise return NULL. - * @param buffer_id in case of success returns the id of the ring buffer - * from which we retrieved the event, otherwise return `-1`. - */ - void pman_consume_first_event(void** event_ptr, int16_t* buffer_id); - - ///////////////////////////// - // CAPTURE (EXCHANGE VALUES WITH BPF SIDE) - ///////////////////////////// - - /** - * @brief Instrument the bpf probe with the right sc_set. This API - * sets both interesting syscalls and interesting tracepoints. - * - * @param sc_set pointer to the interesting sc_set - * - * @return `0` on success, `1` in case of error. - */ - int pman_enforce_sc_set(bool* sc_set); - - /** - * @brief Receive a pointer to `struct scap_stats` and fill it - * with info about the number of events and number of drops. - * - * @param scap_stats_struct pointer to `struct scap_stats`. - * @return `0` on success, `errno` in case of error. - */ - int pman_get_scap_stats(struct scap_stats* scap_stats_struct); - - /** - * @brief Return a `metrics_v2` struct filled with statistics. - * - * @param flags holding statistics category flags. - * @param nstats number of stats allocated. - * @param rc return code, SCAP_FAILURE in case of error. - * - * @return pointer to `struct metrics_v2` - */ - struct metrics_v2* pman_get_metrics_v2(uint32_t flags, uint32_t* nstats, int32_t* rc); - - /** - * @brief Receive an array with `nCPUs` elements. For every CPU - * we set the number of events caught. - * - * @param n_events_per_cpu array of `nCPUs` elements. - * @return `0` on success, `errno` in case of error. - */ - int pman_get_n_tracepoint_hit(long* n_events_per_cpu); - - ///////////////////////////// - // MAPS - ///////////////////////////// - - /** - * @brief Ensure that `bytebufs` cannot be longer than - * `snaplen`. - * - * @param desired_snaplen maximum length we accept - */ - void pman_set_snaplen(uint32_t desired_snaplen); - - /** - * @brief Set the boot_time so all the events generated - * by the probe can provide a full timestamp based on Epoch. - * - * @param boot_time system boot_time from Epoch. - */ - void pman_set_boot_time(uint64_t boot_time); - - void pman_set_dropping_mode(bool value); - - void pman_set_sampling_ratio(uint32_t value); - - /** - * @brief Ask driver to drop failed syscalls. - * It only applied to syscall exit events. - * - * @param drop_failed whether to enable the drop failed mode. - */ - void pman_set_drop_failed(bool drop_failed); - - /** - * @brief Ask driver to enable/disable dynamic_snaplen. - * - * @param do_dynamic_snaplen whether to enable the dynamic_snaplen. - */ - void pman_set_do_dynamic_snaplen(bool do_dynamic_snaplen); - - /** - * @brief Ask driver to set a range of interesting ports. - * - * @param range_start first interesting port. - * @param range_end last interesting port. - */ - void pman_set_fullcapture_port_range(uint16_t range_start, uint16_t range_end); - - /** - * @brief Ask driver to set a specific statsd_port. - * - * @param statsd_port port number. - */ - void pman_set_statsd_port(uint16_t statsd_port); - - /** - * @brief Set scap tid for socket calibration logic. - * - * @param scap_tid - */ - void pman_set_scap_tid(int32_t scap_tid); - - /** - * @brief Get API version to check it a runtime. - * - * @return API version - */ - uint64_t pman_get_probe_api_ver(void); - - /** - * @brief Get schema version to check it a runtime. - * - * @return schema version - */ - uint64_t pman_get_probe_schema_ver(void); - - /** - * @brief Some bpf programs exceed the maximum complexity - * so they have to tail-call other programs. To do that, they - * need a particular tail table that we call `extra_event_prog_tail_table`. - * - * -> EXTRA EVENT PROG TAIL TABLE - * extra_event_prog_tail_table(extra_event_prog_code, program_fd). - * - * `extra_event_prog_code` is an enum defined in - * `/driver/ppm_events_public.h` - * - * @return `0` on success, `errno` in case of error. - */ - int pman_fill_extra_event_prog_tail_table(void); - - /** - * @brief The syscall dispatchers will look into these tables - * to understand which programs they have to call. We have 2 - * different tables one for syscall enter events and the other - * for syscall exit events: - * - * -> SYSCALL ENTER TAIL TABLE - * syscall_enter_tail_table(syscall_id, enter_program_fd). - * Returns the fd of the right bpf program to call. - * - * -> SYSCALL EXIT TAIL TABLE - * syscall_exit_tail_table(syscall_id, exit_program_fd). - * Returns the fd of the right bpf program to call. - * - * @return `0` on success, `errno` in case of error. - */ - int pman_fill_syscalls_tail_table(void); - - /** - * @brief Performs all necessary operations on maps before the - * loading phase: - * - Fill read-only global variables. - * - Set the number of entries for `BPF_MAP_TYPE_ARRAY`. - * - * @return `0` on success, `errno` in case of error. - */ - int pman_prepare_maps_before_loading(void); - - /** - * @brief Performs all necessary operations on maps after the - * loading phase: - * - Set values to BPF global variables. - * - Fill tail tables. - * - * @return `0` on success, `errno` in case of error. - */ - int pman_finalize_maps_after_loading(void); - - /** - * @brief Mark a single syscall as (un)interesting - * - * @param syscall_id syscall system id. - * @param interesting true if the syscall must be marked as interesting. - * - */ - void pman_mark_single_64bit_syscall(int syscall_id, bool interesting); +/* Forward declare them */ +struct metrics_v2; +struct scap_stats; + +/* `libpman` return values convention: + * In case of success `0` is returned otherwise `errno`. If `errno` is not + * available `-1` is returned. + * + * Please Note: + * Libbpf always sets `errno` to the corresponding Exx (positive) error code. + * Libbpf APIs usually return `0` in case of success. + */ + +///////////////////////////// +// SETUP CONFIGURATION +///////////////////////////// + +/** + * @brief Set `libpman` initial state: + * - set `libbpf` strict mode. + * - set `libbpf` logging function according to the verbosity. + * - set available number of CPUs. + * - set dimension of a single per-CPU ring buffer. + * + * @param log_fn logging callback + * @param buf_bytes_dim dimension of a single per-CPU buffer in bytes. + * @param cpus_for_each_buffer number of CPUs to which we want to associate a ring buffer. + * @param allocate_online_only if true, allocate ring buffers taking only into account online CPUs. + * @return `0` on success, `-1` in case of error. + */ +int pman_init_state(falcosecurity_log_fn log_fn, + unsigned long buf_bytes_dim, + uint16_t cpus_for_each_buffer, + bool allocate_online_only); + +/** + * @brief Clear the `libpman` global state before it is used. + * This API could be useful if we open the modern bpf engine multiple times. + */ +void pman_clear_state(void); + +/** + * @brief Return the number of allocated ring buffers. + * + * @return number of allocated ring buffers. + */ +int pman_get_required_buffers(void); + +/** + * @brief Return whether modern bpf is supported by running kernel. + * + * @return supported true or false. + */ +bool pman_check_support(); + +///////////////////////////// +// PROBE LIFECYCLE +///////////////////////////// + +/** + * @brief Open the bpf skeleton obtaining a pointer + * to it. + * + * @return `0` on success, `errno` in case of error. + */ +int pman_open_probe(void); + +/** + * @brief Load into the kernel all the programs and maps + * contained into the skeleton. + * + * @return `0` on success, `errno` in case of error. + */ +int pman_load_probe(void); + +/** + * @brief Clean what we have previously allocated: + * - bpf_skeleton + * - ringbuffer manager + * - consumers/producers vectors + * - stats buffer dynamically allocated + */ +void pman_close_probe(void); + +///////////////////////////// +// ATTACH PROGRAMS +///////////////////////////// + +/// todo(@Andreagit97): these methods probably shouldn't be exposed to the final users +/** + * @brief Attach only the syscall_exit_dispatcher + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_syscall_exit_dispatcher(void); + +/** + * @brief Detach only the syscall_exit_dispatcher + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_syscall_exit_dispatcher(void); + +/** + * @brief Attach only the syscall_enter_dispatcher + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_syscall_enter_dispatcher(void); + +/** + * @brief Detach only the syscall_enter_dispatcher + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_syscall_enter_dispatcher(void); + +/** + * @brief Attach only the sched_process_exit tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_sched_proc_exit(void); + +/** + * @brief Detach only the sched_process_exit tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_sched_proc_exit(void); + +/** + * @brief Attach only the sched_switch tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_sched_switch(void); + +/** + * @brief Detach only the sched_switch tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_sched_switch(void); + +/** + * @brief Attach only the sched_proc_exec tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_sched_proc_exec(void); + +/** + * @brief Detach only the sched_proc_exec tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_sched_proc_exec(void); + +/** + * @brief Attach only the sched_proc_fork tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_sched_proc_fork(void); + +/** + * @brief Detach only the sched_proc_fork tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_sched_proc_fork(void); + +/** + * @brief Attach only the page_fault_user tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_page_fault_user(void); + +/** + * @brief Detach only the page_fault_user tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_page_fault_user(void); + +/** + * @brief Attach only the page_fault_kernel tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_page_fault_kernel(void); + +/** + * @brief Detach only the page_fault_kernel tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_page_fault_kernel(void); + +/** + * @brief Attach only the signal_deliver tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_attach_signal_deliver(void); + +/** + * @brief Detach only the signal_deliver tracepoint + * + * @return `0` on success, `errno` in case of error. + */ +int pman_detach_signal_deliver(void); + +///////////////////////////// +// MANAGE RINGBUFFERS +///////////////////////////// + +/** + * @brief Performs all necessary operations on ringbuf array before the + * loading phase: + * - Set inner map dimension. + * - Set array max entries. + * - Allocate memory for producers and consumers. + * + * @return `0` on success, `errno` in case of error. + */ +int pman_prepare_ringbuf_array_before_loading(void); + +/** + * @brief Performs all necessary operations on ringbuf array after the + * loading phase: + * - Create all the ring_buffer maps inside the array. + * + * @return `0` on success, `errno` in case of error. + */ +int pman_finalize_ringbuf_array_after_loading(void); + +/** + * @brief Search for the event with the lowest timestamp in + * all the ring buffers. + * + * @param event_ptr in case of success return a pointer + * to the event, otherwise return NULL. + * @param buffer_id in case of success returns the id of the ring buffer + * from which we retrieved the event, otherwise return `-1`. + */ +void pman_consume_first_event(void** event_ptr, int16_t* buffer_id); + +///////////////////////////// +// CAPTURE (EXCHANGE VALUES WITH BPF SIDE) +///////////////////////////// + +/** + * @brief Instrument the bpf probe with the right sc_set. This API + * sets both interesting syscalls and interesting tracepoints. + * + * @param sc_set pointer to the interesting sc_set + * + * @return `0` on success, `1` in case of error. + */ +int pman_enforce_sc_set(bool* sc_set); + +/** + * @brief Receive a pointer to `struct scap_stats` and fill it + * with info about the number of events and number of drops. + * + * @param scap_stats_struct pointer to `struct scap_stats`. + * @return `0` on success, `errno` in case of error. + */ +int pman_get_scap_stats(struct scap_stats* scap_stats_struct); + +/** + * @brief Return a `metrics_v2` struct filled with statistics. + * + * @param flags holding statistics category flags. + * @param nstats number of stats allocated. + * @param rc return code, SCAP_FAILURE in case of error. + * + * @return pointer to `struct metrics_v2` + */ +struct metrics_v2* pman_get_metrics_v2(uint32_t flags, uint32_t* nstats, int32_t* rc); + +/** + * @brief Receive an array with `nCPUs` elements. For every CPU + * we set the number of events caught. + * + * @param n_events_per_cpu array of `nCPUs` elements. + * @return `0` on success, `errno` in case of error. + */ +int pman_get_n_tracepoint_hit(long* n_events_per_cpu); + +///////////////////////////// +// MAPS +///////////////////////////// + +/** + * @brief Ensure that `bytebufs` cannot be longer than + * `snaplen`. + * + * @param desired_snaplen maximum length we accept + */ +void pman_set_snaplen(uint32_t desired_snaplen); + +/** + * @brief Set the boot_time so all the events generated + * by the probe can provide a full timestamp based on Epoch. + * + * @param boot_time system boot_time from Epoch. + */ +void pman_set_boot_time(uint64_t boot_time); + +void pman_set_dropping_mode(bool value); + +void pman_set_sampling_ratio(uint32_t value); + +/** + * @brief Ask driver to drop failed syscalls. + * It only applied to syscall exit events. + * + * @param drop_failed whether to enable the drop failed mode. + */ +void pman_set_drop_failed(bool drop_failed); + +/** + * @brief Ask driver to enable/disable dynamic_snaplen. + * + * @param do_dynamic_snaplen whether to enable the dynamic_snaplen. + */ +void pman_set_do_dynamic_snaplen(bool do_dynamic_snaplen); + +/** + * @brief Ask driver to set a range of interesting ports. + * + * @param range_start first interesting port. + * @param range_end last interesting port. + */ +void pman_set_fullcapture_port_range(uint16_t range_start, uint16_t range_end); + +/** + * @brief Ask driver to set a specific statsd_port. + * + * @param statsd_port port number. + */ +void pman_set_statsd_port(uint16_t statsd_port); + +/** + * @brief Set scap tid for socket calibration logic. + * + * @param scap_tid + */ +void pman_set_scap_tid(int32_t scap_tid); + +/** + * @brief Get API version to check it a runtime. + * + * @return API version + */ +uint64_t pman_get_probe_api_ver(void); + +/** + * @brief Get schema version to check it a runtime. + * + * @return schema version + */ +uint64_t pman_get_probe_schema_ver(void); + +/** + * @brief Some bpf programs exceed the maximum complexity + * so they have to tail-call other programs. To do that, they + * need a particular tail table that we call `extra_event_prog_tail_table`. + * + * -> EXTRA EVENT PROG TAIL TABLE + * extra_event_prog_tail_table(extra_event_prog_code, program_fd). + * + * `extra_event_prog_code` is an enum defined in + * `/driver/ppm_events_public.h` + * + * @return `0` on success, `errno` in case of error. + */ +int pman_fill_extra_event_prog_tail_table(void); + +/** + * @brief The syscall dispatchers will look into these tables + * to understand which programs they have to call. We have 2 + * different tables one for syscall enter events and the other + * for syscall exit events: + * + * -> SYSCALL ENTER TAIL TABLE + * syscall_enter_tail_table(syscall_id, enter_program_fd). + * Returns the fd of the right bpf program to call. + * + * -> SYSCALL EXIT TAIL TABLE + * syscall_exit_tail_table(syscall_id, exit_program_fd). + * Returns the fd of the right bpf program to call. + * + * @return `0` on success, `errno` in case of error. + */ +int pman_fill_syscalls_tail_table(void); + +/** + * @brief Performs all necessary operations on maps before the + * loading phase: + * - Fill read-only global variables. + * - Set the number of entries for `BPF_MAP_TYPE_ARRAY`. + * + * @return `0` on success, `errno` in case of error. + */ +int pman_prepare_maps_before_loading(void); + +/** + * @brief Performs all necessary operations on maps after the + * loading phase: + * - Set values to BPF global variables. + * - Fill tail tables. + * + * @return `0` on success, `errno` in case of error. + */ +int pman_finalize_maps_after_loading(void); + +/** + * @brief Mark a single syscall as (un)interesting + * + * @param syscall_id syscall system id. + * @param interesting true if the syscall must be marked as interesting. + * + */ +void pman_mark_single_64bit_syscall(int syscall_id, bool interesting); #ifdef __cplusplus } diff --git a/userspace/libpman/src/configuration.c b/userspace/libpman/src/configuration.c index 870f517664..40e4e684fc 100644 --- a/userspace/libpman/src/configuration.c +++ b/userspace/libpman/src/configuration.c @@ -23,11 +23,9 @@ limitations under the License. #include /* Definition of AT_* constants */ #include -static int libbpf_print(enum libbpf_print_level level, const char* format, va_list args) -{ +static int libbpf_print(enum libbpf_print_level level, const char *format, va_list args) { enum falcosecurity_log_severity sev; - switch(level) - { + switch(level) { case LIBBPF_WARN: sev = FALCOSECURITY_LOG_SEV_WARNING; break; @@ -44,10 +42,10 @@ static int libbpf_print(enum libbpf_print_level level, const char* format, va_li if(g_state.log_fn == NULL) return vfprintf(stderr, format, args); - // This should be already allocated by the caller, but if for some reason libbpf wants to log again after initialization we create a smaller buffer. - // We need a big buffer only for verifier logs at initialization time. - if(g_state.log_buf == NULL) - { + // This should be already allocated by the caller, but if for some reason libbpf wants to log + // again after initialization we create a smaller buffer. We need a big buffer only for verifier + // logs at initialization time. + if(g_state.log_buf == NULL) { g_state.log_buf_size = 0; // this will be freed when the global state is destroyed. g_state.log_buf = calloc(1, BPF_LOG_SMALL_BUF_SIZE); @@ -64,8 +62,7 @@ static int libbpf_print(enum libbpf_print_level level, const char* format, va_li return rc; } -void pman_clear_state() -{ +void pman_clear_state() { g_state.skel = NULL; g_state.rb_manager = NULL; g_state.n_possible_cpus = 0; @@ -81,25 +78,24 @@ void pman_clear_state() g_state.last_ring_read = -1; g_state.last_event_size = 0; - for(int j = 0; j < MODERN_BPF_PROG_ATTACHED_MAX; j++) - { + for(int j = 0; j < MODERN_BPF_PROG_ATTACHED_MAX; j++) { g_state.attached_progs_fds[j] = -1; } - + g_state.stats = NULL; g_state.nstats = 0; g_state.log_fn = NULL; - if(g_state.log_buf) - { + if(g_state.log_buf) { free(g_state.log_buf); } g_state.log_buf = NULL; g_state.log_buf_size = 0; } -int pman_init_state(falcosecurity_log_fn log_fn, unsigned long buf_bytes_dim, uint16_t cpus_for_each_buffer, - bool allocate_online_only) -{ +int pman_init_state(falcosecurity_log_fn log_fn, + unsigned long buf_bytes_dim, + uint16_t cpus_for_each_buffer, + bool allocate_online_only) { char error_message[MAX_ERROR_MESSAGE_LEN]; /* `LIBBPF_STRICT_ALL` turns on all supported strict features @@ -125,38 +121,31 @@ int pman_init_state(falcosecurity_log_fn log_fn, unsigned long buf_bytes_dim, ui struct rlimit rl = {0}; rl.rlim_max = RLIM_INFINITY; rl.rlim_cur = rl.rlim_max; - if(setrlimit(RLIMIT_MEMLOCK, &rl)) - { + if(setrlimit(RLIMIT_MEMLOCK, &rl)) { pman_print_error("unable to bump RLIMIT_MEMLOCK to RLIM_INFINITY"); return -1; } /* Set the available number of CPUs inside the internal state. */ g_state.n_possible_cpus = libbpf_num_possible_cpus(); - if(g_state.n_possible_cpus <= 0) - { + if(g_state.n_possible_cpus <= 0) { pman_print_error("no available cpus"); return -1; } g_state.allocate_online_only = allocate_online_only; - if(g_state.allocate_online_only) - { + if(g_state.allocate_online_only) { ssize_t online_cpus = sysconf(_SC_NPROCESSORS_ONLN); - if(online_cpus != -1) - { + if(online_cpus != -1) { /* We will allocate buffers only for online CPUs */ g_state.n_interesting_cpus = online_cpus; - } - else - { - /* Fallback to all available CPU even if the `allocate_online_only` flag is set to `true` */ + } else { + /* Fallback to all available CPU even if the `allocate_online_only` flag is set to + * `true` */ g_state.n_interesting_cpus = g_state.n_possible_cpus; } - } - else - { + } else { /* We will allocate buffers only for all available CPUs */ g_state.n_interesting_cpus = g_state.n_possible_cpus; } @@ -164,31 +153,30 @@ int pman_init_state(falcosecurity_log_fn log_fn, unsigned long buf_bytes_dim, ui /* We are requiring a buffer every `cpus_for_each_buffer` CPUs, * but `cpus_for_each_buffer` is greater than our possible CPU number! */ - if(cpus_for_each_buffer > g_state.n_interesting_cpus) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, - "buffer every '%d' CPUs, but '%d' is greater than our interesting CPU number (%d)!", - cpus_for_each_buffer, cpus_for_each_buffer, g_state.n_interesting_cpus); - pman_print_error((const char*)error_message); + if(cpus_for_each_buffer > g_state.n_interesting_cpus) { + snprintf( + error_message, + MAX_ERROR_MESSAGE_LEN, + "buffer every '%d' CPUs, but '%d' is greater than our interesting CPU number (%d)!", + cpus_for_each_buffer, + cpus_for_each_buffer, + g_state.n_interesting_cpus); + pman_print_error((const char *)error_message); return -1; } /* `0` is a special value that means a single ring buffer shared between all the CPUs */ - if(cpus_for_each_buffer == 0) - { + if(cpus_for_each_buffer == 0) { /* We want a single ring buffer so 1 ring buffer for all the interesting CPUs we have */ g_state.cpus_for_each_buffer = g_state.n_interesting_cpus; - } - else - { + } else { g_state.cpus_for_each_buffer = cpus_for_each_buffer; } /* Set the number of ring buffers we need */ g_state.n_required_buffers = g_state.n_interesting_cpus / g_state.cpus_for_each_buffer; /* If we have some remaining CPUs it means that we need another buffer */ - if((g_state.n_interesting_cpus % g_state.cpus_for_each_buffer) != 0) - { + if((g_state.n_interesting_cpus % g_state.cpus_for_each_buffer) != 0) { g_state.n_required_buffers++; } /* Set the dimension of a single ring buffer */ @@ -200,156 +188,133 @@ int pman_init_state(falcosecurity_log_fn log_fn, unsigned long buf_bytes_dim, ui return 0; } -int pman_get_required_buffers() { return g_state.n_required_buffers; } +int pman_get_required_buffers() { + return g_state.n_required_buffers; +} -bool check_location(const char* path) -{ +bool check_location(const char *path) { static const char bpf_trace_raw_byte_array[] = "BPF_TRACE_RAW_TP"; bool res = false; // On success `faccessat` returns 0. - if(faccessat(0, path, R_OK, AT_EACCESS) != 0) - { + if(faccessat(0, path, R_OK, AT_EACCESS) != 0) { return false; } char *file_content = NULL; FILE *f = fopen(path, "r"); - if(!f) - { + if(!f) { return false; } // Seek to the end of file - if(fseek(f, 0, SEEK_END)) - { + if(fseek(f, 0, SEEK_END)) { goto cleanup; } - + // Return the dimension of the file long sz = ftell(f); - if (sz < 0) - { + if(sz < 0) { goto cleanup; } // Seek again to the beginning of the file - if(fseek(f, 0, SEEK_SET)) - { + if(fseek(f, 0, SEEK_SET)) { goto cleanup; } - // pre-alloc memory to read all of BTF data + // pre-alloc memory to read all of BTF data file_content = malloc(sz); - if (!file_content) - { + if(!file_content) { goto cleanup; } // read all of BTF data - if(fread(file_content, 1, sz, f) < sz) - { + if(fread(file_content, 1, sz, f) < sz) { goto cleanup; } // Search 'BPF_TRACE_RAW_TP' byte array int z = 0; - for(int j = 0; j< sz; j++) - { - if(file_content[j] == bpf_trace_raw_byte_array[z]) - { + for(int j = 0; j < sz; j++) { + if(file_content[j] == bpf_trace_raw_byte_array[z]) { z++; - if(z == sizeof(bpf_trace_raw_byte_array) / sizeof(*bpf_trace_raw_byte_array)) - { + if(z == sizeof(bpf_trace_raw_byte_array) / sizeof(*bpf_trace_raw_byte_array)) { res = true; break; } - } - else - { + } else { z = 0; } } cleanup: - if(f) - { + if(f) { fclose(f); } - if(file_content) - { + if(file_content) { free(file_content); } return res; } -bool probe_BPF_TRACE_RAW_TP_type(void) -{ +bool probe_BPF_TRACE_RAW_TP_type(void) { // These locations are taken from libbpf library: // https://elixir.bootlin.com/linux/latest/source/tools/lib/bpf/btf.c#L4767 const char *locations[] = { - "/sys/kernel/btf/vmlinux", - "/boot/vmlinux-%1$s", - "/lib/modules/%1$s/vmlinux-%1$s", - "/lib/modules/%1$s/build/vmlinux", - "/usr/lib/modules/%1$s/kernel/vmlinux", - "/usr/lib/debug/boot/vmlinux-%1$s", - "/usr/lib/debug/boot/vmlinux-%1$s.debug", - "/usr/lib/debug/lib/modules/%1$s/vmlinux", + "/sys/kernel/btf/vmlinux", + "/boot/vmlinux-%1$s", + "/lib/modules/%1$s/vmlinux-%1$s", + "/lib/modules/%1$s/build/vmlinux", + "/usr/lib/modules/%1$s/kernel/vmlinux", + "/usr/lib/debug/boot/vmlinux-%1$s", + "/usr/lib/debug/boot/vmlinux-%1$s.debug", + "/usr/lib/debug/lib/modules/%1$s/vmlinux", }; // Try canonical `vmlinux` BTF through `sysfs` first. - if(check_location(locations[0])) - { + if(check_location(locations[0])) { return true; } // Fall back to trying to find `vmlinux` on disk otherwise struct utsname buf = {}; - if(uname(&buf) == -1) - { + if(uname(&buf) == -1) { return false; } char path[PATH_MAX + 1]; // Skip vmlinux since we already tested it. - for (int i = 1; i < sizeof(locations) / sizeof(*locations); i++) - { + for(int i = 1; i < sizeof(locations) / sizeof(*locations); i++) { snprintf(path, PATH_MAX, locations[i], buf.release); - if(check_location(path)) - { + if(check_location(path)) { return true; } } return false; } - /* * Probe the kernel for required dependencies, ring buffer maps and tracing * progs needs to be supported. */ -bool pman_check_support() -{ +bool pman_check_support() { bool res = libbpf_probe_bpf_map_type(BPF_MAP_TYPE_RINGBUF, NULL) > 0; - if(!res) - { + if(!res) { pman_print_error("ring buffer map type is not supported"); return res; } res = libbpf_probe_bpf_prog_type(BPF_PROG_TYPE_TRACING, NULL) > 0; - if(!res) - { + if(!res) { // The above function checks for the `BPF_TRACE_FENTRY` attach type presence, while we need // to check for the `BPF_TRACE_RAW_TP` one. If `BPF_TRACE_FENTRY` is defined we are // sure `BPF_TRACE_RAW_TP` is defined as well, in all other cases, we need to search // for it in the `vmlinux` file. res = probe_BPF_TRACE_RAW_TP_type(); - if(!res) - { + if(!res) { // Clear the errno for `pman_print_error` errno = 0; pman_print_error("prog 'BPF_TRACE_RAW_TP' is not supported"); diff --git a/userspace/libpman/src/events_prog_names.h b/userspace/libpman/src/events_prog_names.h index bfccac5030..ed2577ec0d 100644 --- a/userspace/libpman/src/events_prog_names.h +++ b/userspace/libpman/src/events_prog_names.h @@ -23,348 +23,348 @@ limitations under the License. /* For every event here we have the name of the corresponding bpf program. */ static const char* event_prog_names[PPM_EVENT_MAX] = { - [PPME_GENERIC_E] = "generic_e", - [PPME_GENERIC_X] = "generic_x", - [PPME_SYSCALL_GETCWD_E] = "getcwd_e", - [PPME_SYSCALL_GETCWD_X] = "getcwd_x", - [PPME_SYSCALL_GETDENTS_E] = "getdents_e", - [PPME_SYSCALL_GETDENTS_X] = "getdents_x", - [PPME_SYSCALL_GETDENTS64_E] = "getdents64_e", - [PPME_SYSCALL_GETDENTS64_X] = "getdents64_x", - [PPME_SYSCALL_EPOLLWAIT_E] = "epoll_wait_e", - [PPME_SYSCALL_EPOLLWAIT_X] = "epoll_wait_x", - [PPME_SOCKET_GETPEERNAME_E] = "getpeername_e", - [PPME_SOCKET_GETPEERNAME_X] = "getpeername_x", - [PPME_SOCKET_GETSOCKNAME_E] = "getsockname_e", - [PPME_SOCKET_GETSOCKNAME_X] = "getsockname_x", - [PPME_SYSCALL_MKDIR_2_E] = "mkdir_e", - [PPME_SYSCALL_MKDIR_2_X] = "mkdir_x", - [PPME_SYSCALL_MMAP_E] = "mmap_e", - [PPME_SYSCALL_MMAP_X] = "mmap_x", - [PPME_SYSCALL_MUNMAP_E] = "munmap_e", - [PPME_SYSCALL_MUNMAP_X] = "munmap_x", - [PPME_SYSCALL_OPEN_E] = "open_e", - [PPME_SYSCALL_OPEN_X] = "open_x", - [PPME_SYSCALL_OPENAT_2_E] = "openat_e", - [PPME_SYSCALL_OPENAT_2_X] = "openat_x", - [PPME_SYSCALL_OPENAT2_E] = "openat2_e", - [PPME_SYSCALL_OPENAT2_X] = "openat2_x", - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = "open_by_handle_at_e", - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = "open_by_handle_at_x", - [PPME_SYSCALL_CLOSE_E] = "close_e", - [PPME_SYSCALL_CLOSE_X] = "close_x", - [PPME_SYSCALL_COPY_FILE_RANGE_E] = "copy_file_range_e", - [PPME_SYSCALL_COPY_FILE_RANGE_X] = "copy_file_range_x", - [PPME_SYSCALL_CREAT_E] = "creat_e", - [PPME_SYSCALL_CREAT_X] = "creat_x", - [PPME_SYSCALL_DUP_1_E] = "dup_e", - [PPME_SYSCALL_DUP_1_X] = "dup_x", - [PPME_SYSCALL_DUP2_E] = "dup2_e", - [PPME_SYSCALL_DUP2_X] = "dup2_x", - [PPME_SYSCALL_DUP3_E] = "dup3_e", - [PPME_SYSCALL_DUP3_X] = "dup3_x", - [PPME_SYSCALL_CHDIR_E] = "chdir_e", - [PPME_SYSCALL_CHDIR_X] = "chdir_x", - [PPME_SYSCALL_CHMOD_E] = "chmod_e", - [PPME_SYSCALL_CHMOD_X] = "chmod_x", - [PPME_SYSCALL_CHROOT_E] = "chroot_e", - [PPME_SYSCALL_CHROOT_X] = "chroot_x", - [PPME_SYSCALL_FCHDIR_E] = "fchdir_e", - [PPME_SYSCALL_FCHDIR_X] = "fchdir_x", - [PPME_SYSCALL_FCHMOD_E] = "fchmod_e", - [PPME_SYSCALL_FCHMOD_X] = "fchmod_x", - [PPME_SYSCALL_FCHMODAT_E] = "fchmodat_e", - [PPME_SYSCALL_FCHMODAT_X] = "fchmodat_x", - [PPME_SYSCALL_MKDIRAT_E] = "mkdirat_e", - [PPME_SYSCALL_MKDIRAT_X] = "mkdirat_x", - [PPME_SYSCALL_RMDIR_2_E] = "rmdir_e", - [PPME_SYSCALL_RMDIR_2_X] = "rmdir_x", - [PPME_SYSCALL_EVENTFD_E] = "eventfd_e", - [PPME_SYSCALL_EVENTFD_X] = "eventfd_x", - [PPME_SYSCALL_INOTIFY_INIT_E] = "inotify_init_e", - [PPME_SYSCALL_INOTIFY_INIT_X] = "inotify_init_x", - [PPME_SYSCALL_TIMERFD_CREATE_E] = "timerfd_create_e", - [PPME_SYSCALL_TIMERFD_CREATE_X] = "timerfd_create_x", - [PPME_SYSCALL_USERFAULTFD_E] = "userfaultfd_e", - [PPME_SYSCALL_USERFAULTFD_X] = "userfaultfd_x", - [PPME_SYSCALL_SIGNALFD_E] = "signalfd_e", - [PPME_SYSCALL_SIGNALFD_X] = "signalfd_x", - [PPME_SYSCALL_KILL_E] = "kill_e", - [PPME_SYSCALL_KILL_X] = "kill_x", - [PPME_SYSCALL_TGKILL_E] = "tgkill_e", - [PPME_SYSCALL_TGKILL_X] = "tgkill_x", - [PPME_SYSCALL_TKILL_E] = "tkill_e", - [PPME_SYSCALL_TKILL_X] = "tkill_x", - [PPME_SYSCALL_SECCOMP_E] = "seccomp_e", - [PPME_SYSCALL_SECCOMP_X] = "seccomp_x", - [PPME_SYSCALL_PTRACE_E] = "ptrace_e", - [PPME_SYSCALL_PTRACE_X] = "ptrace_x", - [PPME_SYSCALL_CAPSET_E] = "capset_e", - [PPME_SYSCALL_CAPSET_X] = "capset_x", - [PPME_SOCKET_SOCKET_E] = "socket_e", - [PPME_SOCKET_SOCKET_X] = "socket_x", - [PPME_SOCKET_CONNECT_E] = "connect_e", - [PPME_SOCKET_CONNECT_X] = "connect_x", - [PPME_SOCKET_SOCKETPAIR_E] = "socketpair_e", - [PPME_SOCKET_SOCKETPAIR_X] = "socketpair_x", - [PPME_SOCKET_ACCEPT_5_E] = "accept_e", - [PPME_SOCKET_ACCEPT_5_X] = "accept_x", - [PPME_SOCKET_BIND_E] = "bind_e", - [PPME_SOCKET_BIND_X] = "bind_x", - [PPME_SOCKET_LISTEN_E] = "listen_e", - [PPME_SOCKET_LISTEN_X] = "listen_x", - [PPME_SYSCALL_EXECVE_19_E] = "execve_e", - [PPME_SYSCALL_EXECVE_19_X] = "execve_x", - [PPME_SYSCALL_EXECVEAT_E] = "execveat_e", - [PPME_SYSCALL_EXECVEAT_X] = "execveat_x", - [PPME_SYSCALL_CLONE_20_E] = "clone_e", - [PPME_SYSCALL_CLONE_20_X] = "clone_x", - [PPME_SYSCALL_CLONE3_E] = "clone3_e", - [PPME_SYSCALL_CLONE3_X] = "clone3_x", - [PPME_SYSCALL_FORK_20_E] = "fork_e", - [PPME_SYSCALL_FORK_20_X] = "fork_x", - [PPME_SYSCALL_VFORK_20_E] = "vfork_e", - [PPME_SYSCALL_VFORK_20_X] = "vfork_x", - [PPME_SYSCALL_RENAME_E] = "rename_e", - [PPME_SYSCALL_RENAME_X] = "rename_x", - [PPME_SYSCALL_RENAMEAT_E] = "renameat_e", - [PPME_SYSCALL_RENAMEAT_X] = "renameat_x", - [PPME_SYSCALL_RENAMEAT2_E] = "renameat2_e", - [PPME_SYSCALL_RENAMEAT2_X] = "renameat2_x", - [PPME_SYSCALL_PIPE_E] = "pipe_e", - [PPME_SYSCALL_PIPE_X] = "pipe_x", - [PPME_SYSCALL_READV_E] = "readv_e", - [PPME_SYSCALL_READV_X] = "readv_x", - [PPME_SYSCALL_PREADV_E] = "preadv_e", - [PPME_SYSCALL_PREADV_X] = "preadv_x", - [PPME_SYSCALL_PREAD_E] = "pread64_e", - [PPME_SYSCALL_PREAD_X] = "pread64_x", - [PPME_SYSCALL_BPF_2_E] = "bpf_e", - [PPME_SYSCALL_BPF_2_X] = "bpf_x", - [PPME_SYSCALL_FLOCK_E] = "flock_e", - [PPME_SYSCALL_FLOCK_X] = "flock_x", - [PPME_SYSCALL_IOCTL_3_E] = "ioctl_e", - [PPME_SYSCALL_IOCTL_3_X] = "ioctl_x", - [PPME_SYSCALL_QUOTACTL_E] = "quotactl_e", - [PPME_SYSCALL_QUOTACTL_X] = "quotactl_x", - [PPME_SYSCALL_UNSHARE_E] = "unshare_e", - [PPME_SYSCALL_UNSHARE_X] = "unshare_x", - [PPME_SYSCALL_MOUNT_E] = "mount_e", - [PPME_SYSCALL_MOUNT_X] = "mount_x", - [PPME_SYSCALL_UMOUNT2_E] = "umount2_e", - [PPME_SYSCALL_UMOUNT2_X] = "umount2_x", - [PPME_SYSCALL_LINK_2_E] = "link_e", - [PPME_SYSCALL_LINK_2_X] = "link_x", - [PPME_SYSCALL_LINKAT_2_E] = "linkat_e", - [PPME_SYSCALL_LINKAT_2_X] = "linkat_x", - [PPME_SYSCALL_SYMLINK_E] = "symlink_e", - [PPME_SYSCALL_SYMLINK_X] = "symlink_x", - [PPME_SYSCALL_SYMLINKAT_E] = "symlinkat_e", - [PPME_SYSCALL_SYMLINKAT_X] = "symlinkat_x", - [PPME_SYSCALL_UNLINK_2_E] = "unlink_e", - [PPME_SYSCALL_UNLINK_2_X] = "unlink_x", - [PPME_SYSCALL_UNLINKAT_2_E] = "unlinkat_e", - [PPME_SYSCALL_UNLINKAT_2_X] = "unlinkat_x", - [PPME_SYSCALL_SETGID_E] = "setgid_e", - [PPME_SYSCALL_SETGID_X] = "setgid_x", - [PPME_SYSCALL_SETUID_E] = "setuid_e", - [PPME_SYSCALL_SETUID_X] = "setuid_x", - [PPME_SYSCALL_SETNS_E] = "setns_e", - [PPME_SYSCALL_SETNS_X] = "setns_x", - [PPME_SYSCALL_SETPGID_E] = "setpgid_e", - [PPME_SYSCALL_SETPGID_X] = "setpgid_x", - [PPME_SYSCALL_SETRESGID_E] = "setresgid_e", - [PPME_SYSCALL_SETRESGID_X] = "setresgid_x", - [PPME_SYSCALL_SETRESUID_E] = "setresuid_e", - [PPME_SYSCALL_SETRESUID_X] = "setresuid_x", - [PPME_SYSCALL_SETSID_E] = "setsid_e", - [PPME_SYSCALL_SETSID_X] = "setsid_x", - [PPME_SYSCALL_SETRLIMIT_E] = "setrlimit_e", - [PPME_SYSCALL_SETRLIMIT_X] = "setrlimit_x", - [PPME_SYSCALL_PRLIMIT_E] = "prlimit64_e", - [PPME_SYSCALL_PRLIMIT_X] = "prlimit64_x", - [PPME_SOCKET_SETSOCKOPT_E] = "setsockopt_e", - [PPME_SOCKET_SETSOCKOPT_X] = "setsockopt_x", - [PPME_SOCKET_SENDMSG_E] = "sendmsg_e", - [PPME_SOCKET_SENDMSG_X] = "sendmsg_x", - [PPME_SOCKET_SENDTO_E] = "sendto_e", - [PPME_SOCKET_SENDTO_X] = "sendto_x", - [PPME_SOCKET_RECVMSG_E] = "recvmsg_e", - [PPME_SOCKET_RECVMSG_X] = "recvmsg_x", - [PPME_SOCKET_RECVFROM_E] = "recvfrom_e", - [PPME_SOCKET_RECVFROM_X] = "recvfrom_x", - [PPME_SYSCALL_FCNTL_E] = "fcntl_e", - [PPME_SYSCALL_FCNTL_X] = "fcntl_x", - [PPME_SOCKET_SHUTDOWN_E] = "shutdown_e", - [PPME_SOCKET_SHUTDOWN_X] = "shutdown_x", - [PPME_SYSCALL_FSCONFIG_E] = "fsconfig_e", - [PPME_SYSCALL_FSCONFIG_X] = "fsconfig_x", - [PPME_SYSCALL_EPOLL_CREATE_E] = "epoll_create_e", - [PPME_SYSCALL_EPOLL_CREATE_X] = "epoll_create_x", - [PPME_SYSCALL_EPOLL_CREATE1_E] = "epoll_create1_e", - [PPME_SYSCALL_EPOLL_CREATE1_X] = "epoll_create1_x", - [PPME_SYSCALL_ACCESS_E] = "access_e", - [PPME_SYSCALL_ACCESS_X] = "access_x", - [PPME_SOCKET_GETSOCKOPT_E] = "getsockopt_e", - [PPME_SOCKET_GETSOCKOPT_X] = "getsockopt_x", - [PPME_SYSCALL_MPROTECT_E] = "mprotect_e", - [PPME_SYSCALL_MPROTECT_X] = "mprotect_x", - [PPME_SYSCALL_GETUID_E] = "getuid_e", - [PPME_SYSCALL_GETUID_X] = "getuid_x", - [PPME_SYSCALL_GETGID_E] = "getgid_e", - [PPME_SYSCALL_GETGID_X] = "getgid_x", - [PPME_SYSCALL_GETEUID_E] = "geteuid_e", - [PPME_SYSCALL_GETEUID_X] = "geteuid_x", - [PPME_SYSCALL_GETEGID_E] = "getegid_e", - [PPME_SYSCALL_GETEGID_X] = "getegid_x", - [PPME_SYSCALL_MLOCK_E] = "mlock_e", - [PPME_SYSCALL_MLOCK_X] = "mlock_x", - [PPME_SYSCALL_MLOCK2_E] = "mlock2_e", - [PPME_SYSCALL_MLOCK2_X] = "mlock2_x", - [PPME_SYSCALL_MUNLOCK_E] = "munlock_e", - [PPME_SYSCALL_MUNLOCK_X] = "munlock_x", - [PPME_SYSCALL_MLOCKALL_E] = "mlockall_e", - [PPME_SYSCALL_MLOCKALL_X] = "mlockall_x", - [PPME_SYSCALL_MUNLOCKALL_E] = "munlockall_e", - [PPME_SYSCALL_MUNLOCKALL_X] = "munlockall_x", - [PPME_SYSCALL_READ_E] = "read_e", - [PPME_SYSCALL_READ_X] = "read_x", - [PPME_SYSCALL_IO_URING_ENTER_E] = "io_uring_enter_e", - [PPME_SYSCALL_IO_URING_ENTER_X] = "io_uring_enter_x", - [PPME_SYSCALL_IO_URING_REGISTER_E] = "io_uring_register_e", - [PPME_SYSCALL_IO_URING_REGISTER_X] = "io_uring_register_x", - [PPME_SYSCALL_IO_URING_SETUP_E] = "io_uring_setup_e", - [PPME_SYSCALL_IO_URING_SETUP_X] = "io_uring_setup_x", - [PPME_SYSCALL_POLL_E] = "poll_e", - [PPME_SYSCALL_POLL_X] = "poll_x", - [PPME_SYSCALL_PPOLL_E] = "ppoll_e", - [PPME_SYSCALL_PPOLL_X] = "ppoll_x", - [PPME_SYSCALL_MMAP2_E] = "mmap2_e", - [PPME_SYSCALL_MMAP2_X] = "mmap2_x", - [PPME_SYSCALL_SEMGET_E] = "semget_e", - [PPME_SYSCALL_SEMGET_X] = "semget_x", - [PPME_SYSCALL_SEMCTL_E] = "semctl_e", - [PPME_SYSCALL_SEMCTL_X] = "semctl_x", - [PPME_SYSCALL_SELECT_E] = "select_e", - [PPME_SYSCALL_SELECT_X] = "select_x", - [PPME_SYSCALL_SPLICE_E] = "splice_e", - [PPME_SYSCALL_SPLICE_X] = "splice_x", - [PPME_SOCKET_RECVMMSG_E] = "recvmmsg_e", - [PPME_SOCKET_RECVMMSG_X] = "recvmmsg_x", - [PPME_SOCKET_SENDMMSG_E] = "sendmmsg_e", - [PPME_SOCKET_SENDMMSG_X] = "sendmmsg_x", - [PPME_SYSCALL_SEMOP_E] = "semop_e", - [PPME_SYSCALL_SEMOP_X] = "semop_x", - [PPME_SYSCALL_GETRESUID_E] = "getresuid_e", - [PPME_SYSCALL_GETRESUID_X] = "getresuid_x", - [PPME_SYSCALL_SENDFILE_E] = "sendfile_e", - [PPME_SYSCALL_SENDFILE_X] = "sendfile_x", - [PPME_SYSCALL_FUTEX_E] = "futex_e", - [PPME_SYSCALL_FUTEX_X] = "futex_x", - [PPME_SYSCALL_STAT_E] = "stat_e", - [PPME_SYSCALL_STAT_X] = "stat_x", - [PPME_SYSCALL_LSTAT_E] = "lstat_e", - [PPME_SYSCALL_LSTAT_X] = "lstat_x", - [PPME_SYSCALL_FSTAT_E] = "fstat_e", - [PPME_SYSCALL_FSTAT_X] = "fstat_x", - [PPME_SYSCALL_LSEEK_E] = "lseek_e", - [PPME_SYSCALL_LSEEK_X] = "lseek_x", - [PPME_SYSCALL_LLSEEK_E] = "llseek_e", - [PPME_SYSCALL_LLSEEK_X] = "llseek_x", - [PPME_SYSCALL_WRITE_E] = "write_e", - [PPME_SYSCALL_WRITE_X] = "write_x", - [PPME_SYSCALL_WRITEV_E] = "writev_e", - [PPME_SYSCALL_WRITEV_X] = "writev_x", - [PPME_SYSCALL_PWRITEV_E] = "pwritev_e", - [PPME_SYSCALL_PWRITEV_X] = "pwritev_x", - [PPME_SYSCALL_PWRITE_E] = "pwrite64_e", - [PPME_SYSCALL_PWRITE_X] = "pwrite64_x", - [PPME_SYSCALL_GETRESGID_E] = "getresgid_e", - [PPME_SYSCALL_GETRESGID_X] = "getresgid_x", - [PPME_SYSCALL_CHOWN_E] = "chown_e", - [PPME_SYSCALL_CHOWN_X] = "chown_x", - [PPME_SYSCALL_LCHOWN_E] = "lchown_e", - [PPME_SYSCALL_LCHOWN_X] = "lchown_x", - [PPME_SYSCALL_FCHOWN_E] = "fchown_e", - [PPME_SYSCALL_FCHOWN_X] = "fchown_x", - [PPME_SYSCALL_FCHOWNAT_E] = "fchownat_e", - [PPME_SYSCALL_FCHOWNAT_X] = "fchownat_x", - [PPME_SYSCALL_BRK_4_E] = "brk_e", - [PPME_SYSCALL_BRK_4_X] = "brk_x", - [PPME_SYSCALL_GETRLIMIT_E] = "getrlimit_e", - [PPME_SYSCALL_GETRLIMIT_X] = "getrlimit_x", - [PPME_SOCKET_SEND_E] = "send_e", - [PPME_SOCKET_SEND_X] = "send_x", - [PPME_SOCKET_RECV_E] = "recv_e", - [PPME_SOCKET_RECV_X] = "recv_x", - [PPME_SYSCALL_NANOSLEEP_E] = "nanosleep_e", - [PPME_SYSCALL_NANOSLEEP_X] = "nanosleep_x", - [PPME_SYSCALL_UMOUNT_1_E] = "umount_e", - [PPME_SYSCALL_UMOUNT_1_X] = "umount_x", - [PPME_SOCKET_ACCEPT4_6_E] = "accept4_e", - [PPME_SOCKET_ACCEPT4_6_X] = "accept4_x", - [PPME_SYSCALL_PIPE2_E] = "pipe2_e", - [PPME_SYSCALL_PIPE2_X] = "pipe2_x", - [PPME_SYSCALL_INOTIFY_INIT1_E] = "inotify_init1_e", - [PPME_SYSCALL_INOTIFY_INIT1_X] = "inotify_init1_x", - [PPME_SYSCALL_EVENTFD2_E] = "eventfd2_e", - [PPME_SYSCALL_EVENTFD2_X] = "eventfd2_x", - [PPME_SYSCALL_SIGNALFD4_E] = "signalfd4_e", - [PPME_SYSCALL_SIGNALFD4_X] = "signalfd4_x", - [PPME_SYSCALL_PRCTL_E] = "prctl_e", - [PPME_SYSCALL_PRCTL_X] = "prctl_x", - [PPME_SYSCALL_MEMFD_CREATE_E] = "memfd_create_e", - [PPME_SYSCALL_MEMFD_CREATE_X] = "memfd_create_x", - [PPME_SYSCALL_PIDFD_GETFD_E] = "pidfd_getfd_e", - [PPME_SYSCALL_PIDFD_GETFD_X] = "pidfd_getfd_x", - [PPME_SYSCALL_PIDFD_OPEN_E] = "pidfd_open_e", - [PPME_SYSCALL_PIDFD_OPEN_X] = "pidfd_open_x", - [PPME_SYSCALL_INIT_MODULE_E] = "init_module_e", - [PPME_SYSCALL_INIT_MODULE_X] = "init_module_x", - [PPME_SYSCALL_FINIT_MODULE_E] = "finit_module_e", - [PPME_SYSCALL_FINIT_MODULE_X] = "finit_module_x", - [PPME_SYSCALL_MKNOD_E] = "mknod_e", - [PPME_SYSCALL_MKNOD_X] = "mknod_x", - [PPME_SYSCALL_MKNODAT_E] = "mknodat_e", - [PPME_SYSCALL_MKNODAT_X] = "mknodat_x", - [PPME_SYSCALL_NEWFSTATAT_E] = "newfstatat_e", - [PPME_SYSCALL_NEWFSTATAT_X] = "newfstatat_x", - [PPME_SYSCALL_PROCESS_VM_READV_E] = "process_vm_readv_e", - [PPME_SYSCALL_PROCESS_VM_READV_X] = "process_vm_readv_x", - [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = "process_vm_writev_e", - [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = "process_vm_writev_x", - [PPME_SYSCALL_DELETE_MODULE_E] = "delete_module_e", - [PPME_SYSCALL_DELETE_MODULE_X] = "delete_module_x", - [PPME_SYSCALL_SETREUID_E] = "setreuid_e", - [PPME_SYSCALL_SETREUID_X] = "setreuid_x", - [PPME_SYSCALL_SETREGID_E] = "setregid_e", - [PPME_SYSCALL_SETREGID_X] = "setregid_x", + [PPME_GENERIC_E] = "generic_e", + [PPME_GENERIC_X] = "generic_x", + [PPME_SYSCALL_GETCWD_E] = "getcwd_e", + [PPME_SYSCALL_GETCWD_X] = "getcwd_x", + [PPME_SYSCALL_GETDENTS_E] = "getdents_e", + [PPME_SYSCALL_GETDENTS_X] = "getdents_x", + [PPME_SYSCALL_GETDENTS64_E] = "getdents64_e", + [PPME_SYSCALL_GETDENTS64_X] = "getdents64_x", + [PPME_SYSCALL_EPOLLWAIT_E] = "epoll_wait_e", + [PPME_SYSCALL_EPOLLWAIT_X] = "epoll_wait_x", + [PPME_SOCKET_GETPEERNAME_E] = "getpeername_e", + [PPME_SOCKET_GETPEERNAME_X] = "getpeername_x", + [PPME_SOCKET_GETSOCKNAME_E] = "getsockname_e", + [PPME_SOCKET_GETSOCKNAME_X] = "getsockname_x", + [PPME_SYSCALL_MKDIR_2_E] = "mkdir_e", + [PPME_SYSCALL_MKDIR_2_X] = "mkdir_x", + [PPME_SYSCALL_MMAP_E] = "mmap_e", + [PPME_SYSCALL_MMAP_X] = "mmap_x", + [PPME_SYSCALL_MUNMAP_E] = "munmap_e", + [PPME_SYSCALL_MUNMAP_X] = "munmap_x", + [PPME_SYSCALL_OPEN_E] = "open_e", + [PPME_SYSCALL_OPEN_X] = "open_x", + [PPME_SYSCALL_OPENAT_2_E] = "openat_e", + [PPME_SYSCALL_OPENAT_2_X] = "openat_x", + [PPME_SYSCALL_OPENAT2_E] = "openat2_e", + [PPME_SYSCALL_OPENAT2_X] = "openat2_x", + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = "open_by_handle_at_e", + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = "open_by_handle_at_x", + [PPME_SYSCALL_CLOSE_E] = "close_e", + [PPME_SYSCALL_CLOSE_X] = "close_x", + [PPME_SYSCALL_COPY_FILE_RANGE_E] = "copy_file_range_e", + [PPME_SYSCALL_COPY_FILE_RANGE_X] = "copy_file_range_x", + [PPME_SYSCALL_CREAT_E] = "creat_e", + [PPME_SYSCALL_CREAT_X] = "creat_x", + [PPME_SYSCALL_DUP_1_E] = "dup_e", + [PPME_SYSCALL_DUP_1_X] = "dup_x", + [PPME_SYSCALL_DUP2_E] = "dup2_e", + [PPME_SYSCALL_DUP2_X] = "dup2_x", + [PPME_SYSCALL_DUP3_E] = "dup3_e", + [PPME_SYSCALL_DUP3_X] = "dup3_x", + [PPME_SYSCALL_CHDIR_E] = "chdir_e", + [PPME_SYSCALL_CHDIR_X] = "chdir_x", + [PPME_SYSCALL_CHMOD_E] = "chmod_e", + [PPME_SYSCALL_CHMOD_X] = "chmod_x", + [PPME_SYSCALL_CHROOT_E] = "chroot_e", + [PPME_SYSCALL_CHROOT_X] = "chroot_x", + [PPME_SYSCALL_FCHDIR_E] = "fchdir_e", + [PPME_SYSCALL_FCHDIR_X] = "fchdir_x", + [PPME_SYSCALL_FCHMOD_E] = "fchmod_e", + [PPME_SYSCALL_FCHMOD_X] = "fchmod_x", + [PPME_SYSCALL_FCHMODAT_E] = "fchmodat_e", + [PPME_SYSCALL_FCHMODAT_X] = "fchmodat_x", + [PPME_SYSCALL_MKDIRAT_E] = "mkdirat_e", + [PPME_SYSCALL_MKDIRAT_X] = "mkdirat_x", + [PPME_SYSCALL_RMDIR_2_E] = "rmdir_e", + [PPME_SYSCALL_RMDIR_2_X] = "rmdir_x", + [PPME_SYSCALL_EVENTFD_E] = "eventfd_e", + [PPME_SYSCALL_EVENTFD_X] = "eventfd_x", + [PPME_SYSCALL_INOTIFY_INIT_E] = "inotify_init_e", + [PPME_SYSCALL_INOTIFY_INIT_X] = "inotify_init_x", + [PPME_SYSCALL_TIMERFD_CREATE_E] = "timerfd_create_e", + [PPME_SYSCALL_TIMERFD_CREATE_X] = "timerfd_create_x", + [PPME_SYSCALL_USERFAULTFD_E] = "userfaultfd_e", + [PPME_SYSCALL_USERFAULTFD_X] = "userfaultfd_x", + [PPME_SYSCALL_SIGNALFD_E] = "signalfd_e", + [PPME_SYSCALL_SIGNALFD_X] = "signalfd_x", + [PPME_SYSCALL_KILL_E] = "kill_e", + [PPME_SYSCALL_KILL_X] = "kill_x", + [PPME_SYSCALL_TGKILL_E] = "tgkill_e", + [PPME_SYSCALL_TGKILL_X] = "tgkill_x", + [PPME_SYSCALL_TKILL_E] = "tkill_e", + [PPME_SYSCALL_TKILL_X] = "tkill_x", + [PPME_SYSCALL_SECCOMP_E] = "seccomp_e", + [PPME_SYSCALL_SECCOMP_X] = "seccomp_x", + [PPME_SYSCALL_PTRACE_E] = "ptrace_e", + [PPME_SYSCALL_PTRACE_X] = "ptrace_x", + [PPME_SYSCALL_CAPSET_E] = "capset_e", + [PPME_SYSCALL_CAPSET_X] = "capset_x", + [PPME_SOCKET_SOCKET_E] = "socket_e", + [PPME_SOCKET_SOCKET_X] = "socket_x", + [PPME_SOCKET_CONNECT_E] = "connect_e", + [PPME_SOCKET_CONNECT_X] = "connect_x", + [PPME_SOCKET_SOCKETPAIR_E] = "socketpair_e", + [PPME_SOCKET_SOCKETPAIR_X] = "socketpair_x", + [PPME_SOCKET_ACCEPT_5_E] = "accept_e", + [PPME_SOCKET_ACCEPT_5_X] = "accept_x", + [PPME_SOCKET_BIND_E] = "bind_e", + [PPME_SOCKET_BIND_X] = "bind_x", + [PPME_SOCKET_LISTEN_E] = "listen_e", + [PPME_SOCKET_LISTEN_X] = "listen_x", + [PPME_SYSCALL_EXECVE_19_E] = "execve_e", + [PPME_SYSCALL_EXECVE_19_X] = "execve_x", + [PPME_SYSCALL_EXECVEAT_E] = "execveat_e", + [PPME_SYSCALL_EXECVEAT_X] = "execveat_x", + [PPME_SYSCALL_CLONE_20_E] = "clone_e", + [PPME_SYSCALL_CLONE_20_X] = "clone_x", + [PPME_SYSCALL_CLONE3_E] = "clone3_e", + [PPME_SYSCALL_CLONE3_X] = "clone3_x", + [PPME_SYSCALL_FORK_20_E] = "fork_e", + [PPME_SYSCALL_FORK_20_X] = "fork_x", + [PPME_SYSCALL_VFORK_20_E] = "vfork_e", + [PPME_SYSCALL_VFORK_20_X] = "vfork_x", + [PPME_SYSCALL_RENAME_E] = "rename_e", + [PPME_SYSCALL_RENAME_X] = "rename_x", + [PPME_SYSCALL_RENAMEAT_E] = "renameat_e", + [PPME_SYSCALL_RENAMEAT_X] = "renameat_x", + [PPME_SYSCALL_RENAMEAT2_E] = "renameat2_e", + [PPME_SYSCALL_RENAMEAT2_X] = "renameat2_x", + [PPME_SYSCALL_PIPE_E] = "pipe_e", + [PPME_SYSCALL_PIPE_X] = "pipe_x", + [PPME_SYSCALL_READV_E] = "readv_e", + [PPME_SYSCALL_READV_X] = "readv_x", + [PPME_SYSCALL_PREADV_E] = "preadv_e", + [PPME_SYSCALL_PREADV_X] = "preadv_x", + [PPME_SYSCALL_PREAD_E] = "pread64_e", + [PPME_SYSCALL_PREAD_X] = "pread64_x", + [PPME_SYSCALL_BPF_2_E] = "bpf_e", + [PPME_SYSCALL_BPF_2_X] = "bpf_x", + [PPME_SYSCALL_FLOCK_E] = "flock_e", + [PPME_SYSCALL_FLOCK_X] = "flock_x", + [PPME_SYSCALL_IOCTL_3_E] = "ioctl_e", + [PPME_SYSCALL_IOCTL_3_X] = "ioctl_x", + [PPME_SYSCALL_QUOTACTL_E] = "quotactl_e", + [PPME_SYSCALL_QUOTACTL_X] = "quotactl_x", + [PPME_SYSCALL_UNSHARE_E] = "unshare_e", + [PPME_SYSCALL_UNSHARE_X] = "unshare_x", + [PPME_SYSCALL_MOUNT_E] = "mount_e", + [PPME_SYSCALL_MOUNT_X] = "mount_x", + [PPME_SYSCALL_UMOUNT2_E] = "umount2_e", + [PPME_SYSCALL_UMOUNT2_X] = "umount2_x", + [PPME_SYSCALL_LINK_2_E] = "link_e", + [PPME_SYSCALL_LINK_2_X] = "link_x", + [PPME_SYSCALL_LINKAT_2_E] = "linkat_e", + [PPME_SYSCALL_LINKAT_2_X] = "linkat_x", + [PPME_SYSCALL_SYMLINK_E] = "symlink_e", + [PPME_SYSCALL_SYMLINK_X] = "symlink_x", + [PPME_SYSCALL_SYMLINKAT_E] = "symlinkat_e", + [PPME_SYSCALL_SYMLINKAT_X] = "symlinkat_x", + [PPME_SYSCALL_UNLINK_2_E] = "unlink_e", + [PPME_SYSCALL_UNLINK_2_X] = "unlink_x", + [PPME_SYSCALL_UNLINKAT_2_E] = "unlinkat_e", + [PPME_SYSCALL_UNLINKAT_2_X] = "unlinkat_x", + [PPME_SYSCALL_SETGID_E] = "setgid_e", + [PPME_SYSCALL_SETGID_X] = "setgid_x", + [PPME_SYSCALL_SETUID_E] = "setuid_e", + [PPME_SYSCALL_SETUID_X] = "setuid_x", + [PPME_SYSCALL_SETNS_E] = "setns_e", + [PPME_SYSCALL_SETNS_X] = "setns_x", + [PPME_SYSCALL_SETPGID_E] = "setpgid_e", + [PPME_SYSCALL_SETPGID_X] = "setpgid_x", + [PPME_SYSCALL_SETRESGID_E] = "setresgid_e", + [PPME_SYSCALL_SETRESGID_X] = "setresgid_x", + [PPME_SYSCALL_SETRESUID_E] = "setresuid_e", + [PPME_SYSCALL_SETRESUID_X] = "setresuid_x", + [PPME_SYSCALL_SETSID_E] = "setsid_e", + [PPME_SYSCALL_SETSID_X] = "setsid_x", + [PPME_SYSCALL_SETRLIMIT_E] = "setrlimit_e", + [PPME_SYSCALL_SETRLIMIT_X] = "setrlimit_x", + [PPME_SYSCALL_PRLIMIT_E] = "prlimit64_e", + [PPME_SYSCALL_PRLIMIT_X] = "prlimit64_x", + [PPME_SOCKET_SETSOCKOPT_E] = "setsockopt_e", + [PPME_SOCKET_SETSOCKOPT_X] = "setsockopt_x", + [PPME_SOCKET_SENDMSG_E] = "sendmsg_e", + [PPME_SOCKET_SENDMSG_X] = "sendmsg_x", + [PPME_SOCKET_SENDTO_E] = "sendto_e", + [PPME_SOCKET_SENDTO_X] = "sendto_x", + [PPME_SOCKET_RECVMSG_E] = "recvmsg_e", + [PPME_SOCKET_RECVMSG_X] = "recvmsg_x", + [PPME_SOCKET_RECVFROM_E] = "recvfrom_e", + [PPME_SOCKET_RECVFROM_X] = "recvfrom_x", + [PPME_SYSCALL_FCNTL_E] = "fcntl_e", + [PPME_SYSCALL_FCNTL_X] = "fcntl_x", + [PPME_SOCKET_SHUTDOWN_E] = "shutdown_e", + [PPME_SOCKET_SHUTDOWN_X] = "shutdown_x", + [PPME_SYSCALL_FSCONFIG_E] = "fsconfig_e", + [PPME_SYSCALL_FSCONFIG_X] = "fsconfig_x", + [PPME_SYSCALL_EPOLL_CREATE_E] = "epoll_create_e", + [PPME_SYSCALL_EPOLL_CREATE_X] = "epoll_create_x", + [PPME_SYSCALL_EPOLL_CREATE1_E] = "epoll_create1_e", + [PPME_SYSCALL_EPOLL_CREATE1_X] = "epoll_create1_x", + [PPME_SYSCALL_ACCESS_E] = "access_e", + [PPME_SYSCALL_ACCESS_X] = "access_x", + [PPME_SOCKET_GETSOCKOPT_E] = "getsockopt_e", + [PPME_SOCKET_GETSOCKOPT_X] = "getsockopt_x", + [PPME_SYSCALL_MPROTECT_E] = "mprotect_e", + [PPME_SYSCALL_MPROTECT_X] = "mprotect_x", + [PPME_SYSCALL_GETUID_E] = "getuid_e", + [PPME_SYSCALL_GETUID_X] = "getuid_x", + [PPME_SYSCALL_GETGID_E] = "getgid_e", + [PPME_SYSCALL_GETGID_X] = "getgid_x", + [PPME_SYSCALL_GETEUID_E] = "geteuid_e", + [PPME_SYSCALL_GETEUID_X] = "geteuid_x", + [PPME_SYSCALL_GETEGID_E] = "getegid_e", + [PPME_SYSCALL_GETEGID_X] = "getegid_x", + [PPME_SYSCALL_MLOCK_E] = "mlock_e", + [PPME_SYSCALL_MLOCK_X] = "mlock_x", + [PPME_SYSCALL_MLOCK2_E] = "mlock2_e", + [PPME_SYSCALL_MLOCK2_X] = "mlock2_x", + [PPME_SYSCALL_MUNLOCK_E] = "munlock_e", + [PPME_SYSCALL_MUNLOCK_X] = "munlock_x", + [PPME_SYSCALL_MLOCKALL_E] = "mlockall_e", + [PPME_SYSCALL_MLOCKALL_X] = "mlockall_x", + [PPME_SYSCALL_MUNLOCKALL_E] = "munlockall_e", + [PPME_SYSCALL_MUNLOCKALL_X] = "munlockall_x", + [PPME_SYSCALL_READ_E] = "read_e", + [PPME_SYSCALL_READ_X] = "read_x", + [PPME_SYSCALL_IO_URING_ENTER_E] = "io_uring_enter_e", + [PPME_SYSCALL_IO_URING_ENTER_X] = "io_uring_enter_x", + [PPME_SYSCALL_IO_URING_REGISTER_E] = "io_uring_register_e", + [PPME_SYSCALL_IO_URING_REGISTER_X] = "io_uring_register_x", + [PPME_SYSCALL_IO_URING_SETUP_E] = "io_uring_setup_e", + [PPME_SYSCALL_IO_URING_SETUP_X] = "io_uring_setup_x", + [PPME_SYSCALL_POLL_E] = "poll_e", + [PPME_SYSCALL_POLL_X] = "poll_x", + [PPME_SYSCALL_PPOLL_E] = "ppoll_e", + [PPME_SYSCALL_PPOLL_X] = "ppoll_x", + [PPME_SYSCALL_MMAP2_E] = "mmap2_e", + [PPME_SYSCALL_MMAP2_X] = "mmap2_x", + [PPME_SYSCALL_SEMGET_E] = "semget_e", + [PPME_SYSCALL_SEMGET_X] = "semget_x", + [PPME_SYSCALL_SEMCTL_E] = "semctl_e", + [PPME_SYSCALL_SEMCTL_X] = "semctl_x", + [PPME_SYSCALL_SELECT_E] = "select_e", + [PPME_SYSCALL_SELECT_X] = "select_x", + [PPME_SYSCALL_SPLICE_E] = "splice_e", + [PPME_SYSCALL_SPLICE_X] = "splice_x", + [PPME_SOCKET_RECVMMSG_E] = "recvmmsg_e", + [PPME_SOCKET_RECVMMSG_X] = "recvmmsg_x", + [PPME_SOCKET_SENDMMSG_E] = "sendmmsg_e", + [PPME_SOCKET_SENDMMSG_X] = "sendmmsg_x", + [PPME_SYSCALL_SEMOP_E] = "semop_e", + [PPME_SYSCALL_SEMOP_X] = "semop_x", + [PPME_SYSCALL_GETRESUID_E] = "getresuid_e", + [PPME_SYSCALL_GETRESUID_X] = "getresuid_x", + [PPME_SYSCALL_SENDFILE_E] = "sendfile_e", + [PPME_SYSCALL_SENDFILE_X] = "sendfile_x", + [PPME_SYSCALL_FUTEX_E] = "futex_e", + [PPME_SYSCALL_FUTEX_X] = "futex_x", + [PPME_SYSCALL_STAT_E] = "stat_e", + [PPME_SYSCALL_STAT_X] = "stat_x", + [PPME_SYSCALL_LSTAT_E] = "lstat_e", + [PPME_SYSCALL_LSTAT_X] = "lstat_x", + [PPME_SYSCALL_FSTAT_E] = "fstat_e", + [PPME_SYSCALL_FSTAT_X] = "fstat_x", + [PPME_SYSCALL_LSEEK_E] = "lseek_e", + [PPME_SYSCALL_LSEEK_X] = "lseek_x", + [PPME_SYSCALL_LLSEEK_E] = "llseek_e", + [PPME_SYSCALL_LLSEEK_X] = "llseek_x", + [PPME_SYSCALL_WRITE_E] = "write_e", + [PPME_SYSCALL_WRITE_X] = "write_x", + [PPME_SYSCALL_WRITEV_E] = "writev_e", + [PPME_SYSCALL_WRITEV_X] = "writev_x", + [PPME_SYSCALL_PWRITEV_E] = "pwritev_e", + [PPME_SYSCALL_PWRITEV_X] = "pwritev_x", + [PPME_SYSCALL_PWRITE_E] = "pwrite64_e", + [PPME_SYSCALL_PWRITE_X] = "pwrite64_x", + [PPME_SYSCALL_GETRESGID_E] = "getresgid_e", + [PPME_SYSCALL_GETRESGID_X] = "getresgid_x", + [PPME_SYSCALL_CHOWN_E] = "chown_e", + [PPME_SYSCALL_CHOWN_X] = "chown_x", + [PPME_SYSCALL_LCHOWN_E] = "lchown_e", + [PPME_SYSCALL_LCHOWN_X] = "lchown_x", + [PPME_SYSCALL_FCHOWN_E] = "fchown_e", + [PPME_SYSCALL_FCHOWN_X] = "fchown_x", + [PPME_SYSCALL_FCHOWNAT_E] = "fchownat_e", + [PPME_SYSCALL_FCHOWNAT_X] = "fchownat_x", + [PPME_SYSCALL_BRK_4_E] = "brk_e", + [PPME_SYSCALL_BRK_4_X] = "brk_x", + [PPME_SYSCALL_GETRLIMIT_E] = "getrlimit_e", + [PPME_SYSCALL_GETRLIMIT_X] = "getrlimit_x", + [PPME_SOCKET_SEND_E] = "send_e", + [PPME_SOCKET_SEND_X] = "send_x", + [PPME_SOCKET_RECV_E] = "recv_e", + [PPME_SOCKET_RECV_X] = "recv_x", + [PPME_SYSCALL_NANOSLEEP_E] = "nanosleep_e", + [PPME_SYSCALL_NANOSLEEP_X] = "nanosleep_x", + [PPME_SYSCALL_UMOUNT_1_E] = "umount_e", + [PPME_SYSCALL_UMOUNT_1_X] = "umount_x", + [PPME_SOCKET_ACCEPT4_6_E] = "accept4_e", + [PPME_SOCKET_ACCEPT4_6_X] = "accept4_x", + [PPME_SYSCALL_PIPE2_E] = "pipe2_e", + [PPME_SYSCALL_PIPE2_X] = "pipe2_x", + [PPME_SYSCALL_INOTIFY_INIT1_E] = "inotify_init1_e", + [PPME_SYSCALL_INOTIFY_INIT1_X] = "inotify_init1_x", + [PPME_SYSCALL_EVENTFD2_E] = "eventfd2_e", + [PPME_SYSCALL_EVENTFD2_X] = "eventfd2_x", + [PPME_SYSCALL_SIGNALFD4_E] = "signalfd4_e", + [PPME_SYSCALL_SIGNALFD4_X] = "signalfd4_x", + [PPME_SYSCALL_PRCTL_E] = "prctl_e", + [PPME_SYSCALL_PRCTL_X] = "prctl_x", + [PPME_SYSCALL_MEMFD_CREATE_E] = "memfd_create_e", + [PPME_SYSCALL_MEMFD_CREATE_X] = "memfd_create_x", + [PPME_SYSCALL_PIDFD_GETFD_E] = "pidfd_getfd_e", + [PPME_SYSCALL_PIDFD_GETFD_X] = "pidfd_getfd_x", + [PPME_SYSCALL_PIDFD_OPEN_E] = "pidfd_open_e", + [PPME_SYSCALL_PIDFD_OPEN_X] = "pidfd_open_x", + [PPME_SYSCALL_INIT_MODULE_E] = "init_module_e", + [PPME_SYSCALL_INIT_MODULE_X] = "init_module_x", + [PPME_SYSCALL_FINIT_MODULE_E] = "finit_module_e", + [PPME_SYSCALL_FINIT_MODULE_X] = "finit_module_x", + [PPME_SYSCALL_MKNOD_E] = "mknod_e", + [PPME_SYSCALL_MKNOD_X] = "mknod_x", + [PPME_SYSCALL_MKNODAT_E] = "mknodat_e", + [PPME_SYSCALL_MKNODAT_X] = "mknodat_x", + [PPME_SYSCALL_NEWFSTATAT_E] = "newfstatat_e", + [PPME_SYSCALL_NEWFSTATAT_X] = "newfstatat_x", + [PPME_SYSCALL_PROCESS_VM_READV_E] = "process_vm_readv_e", + [PPME_SYSCALL_PROCESS_VM_READV_X] = "process_vm_readv_x", + [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = "process_vm_writev_e", + [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = "process_vm_writev_x", + [PPME_SYSCALL_DELETE_MODULE_E] = "delete_module_e", + [PPME_SYSCALL_DELETE_MODULE_X] = "delete_module_x", + [PPME_SYSCALL_SETREUID_E] = "setreuid_e", + [PPME_SYSCALL_SETREUID_X] = "setreuid_x", + [PPME_SYSCALL_SETREGID_E] = "setregid_e", + [PPME_SYSCALL_SETREGID_X] = "setregid_x", }; /* Some events can require more than one bpf program to collect all the data. */ static const char* extra_event_prog_names[TAIL_EXTRA_EVENT_PROG_MAX] = { - [T1_EXECVE_X] = "t1_execve_x", - [T1_EXECVEAT_X] = "t1_execveat_x", - [T1_CLONE_X] = "t1_clone_x", - [T1_CLONE3_X] = "t1_clone3_x", - [T1_FORK_X] = "t1_fork_x", - [T1_VFORK_X] = "t1_vfork_x", + [T1_EXECVE_X] = "t1_execve_x", + [T1_EXECVEAT_X] = "t1_execveat_x", + [T1_CLONE_X] = "t1_clone_x", + [T1_CLONE3_X] = "t1_clone3_x", + [T1_FORK_X] = "t1_fork_x", + [T1_VFORK_X] = "t1_vfork_x", #ifdef CAPTURE_SCHED_PROC_EXEC - [T1_SCHED_PROC_EXEC] = "t1_sched_p_exec", - [T2_SCHED_PROC_EXEC] = "t2_sched_p_exec", + [T1_SCHED_PROC_EXEC] = "t1_sched_p_exec", + [T2_SCHED_PROC_EXEC] = "t2_sched_p_exec", #endif #ifdef CAPTURE_SCHED_PROC_FORK - [T1_SCHED_PROC_FORK] = "t1_sched_p_fork", - [T2_SCHED_PROC_FORK] = "t2_sched_p_fork", + [T1_SCHED_PROC_FORK] = "t1_sched_p_fork", + [T2_SCHED_PROC_FORK] = "t2_sched_p_fork", #endif - [T2_CLONE_X] = "t2_clone_x", - [T2_CLONE3_X] = "t2_clone3_x", - [T2_FORK_X] = "t2_fork_x", - [T2_VFORK_X] = "t2_vfork_x", - [T1_DROP_E] = "t1_drop_e", - [T1_DROP_X] = "t1_drop_x", - [T1_HOTPLUG_E] = "t1_hotplug_e", - [T1_OPEN_BY_HANDLE_AT_X] = "t1_open_by_handle_at_x", - [T2_EXECVE_X] = "t2_execve_x", - [T2_EXECVEAT_X] = "t2_execveat_x", + [T2_CLONE_X] = "t2_clone_x", + [T2_CLONE3_X] = "t2_clone3_x", + [T2_FORK_X] = "t2_fork_x", + [T2_VFORK_X] = "t2_vfork_x", + [T1_DROP_E] = "t1_drop_e", + [T1_DROP_X] = "t1_drop_x", + [T1_HOTPLUG_E] = "t1_hotplug_e", + [T1_OPEN_BY_HANDLE_AT_X] = "t1_open_by_handle_at_x", + [T2_EXECVE_X] = "t2_execve_x", + [T2_EXECVEAT_X] = "t2_execveat_x", }; diff --git a/userspace/libpman/src/lifecycle.c b/userspace/libpman/src/lifecycle.c index bc1aabe7d9..68d0ad87be 100644 --- a/userspace/libpman/src/lifecycle.c +++ b/userspace/libpman/src/lifecycle.c @@ -19,19 +19,16 @@ limitations under the License. #include "state.h" #include -int pman_open_probe() -{ +int pman_open_probe() { g_state.skel = bpf_probe__open(); - if(!g_state.skel) - { + if(!g_state.skel) { pman_print_error("failed to open BPF skeleton"); return errno; } return 0; } -static void pman_save_attached_progs() -{ +static void pman_save_attached_progs() { g_state.attached_progs_fds[0] = bpf_program__fd(g_state.skel->progs.sys_enter); g_state.attached_progs_fds[1] = bpf_program__fd(g_state.skel->progs.sys_exit); g_state.attached_progs_fds[2] = bpf_program__fd(g_state.skel->progs.sched_proc_exit); @@ -49,17 +46,14 @@ static void pman_save_attached_progs() g_state.attached_progs_fds[8] = bpf_program__fd(g_state.skel->progs.signal_deliver); } -int pman_load_probe() -{ - if(bpf_probe__load(g_state.skel)) - { +int pman_load_probe() { + if(bpf_probe__load(g_state.skel)) { pman_print_error("failed to load BPF object"); return errno; } pman_save_attached_progs(); // Programs are loaded so we passed the verifier we can free the 16 MB - if(g_state.log_buf) - { + if(g_state.log_buf) { free(g_state.log_buf); g_state.log_buf = NULL; g_state.log_buf_size = 0; @@ -67,34 +61,28 @@ int pman_load_probe() return 0; } -void pman_close_probe() -{ - if(g_state.stats) - { +void pman_close_probe() { + if(g_state.stats) { free(g_state.stats); g_state.stats = NULL; } - if(g_state.cons_pos) - { + if(g_state.cons_pos) { free(g_state.cons_pos); g_state.cons_pos = NULL; } - if(g_state.prod_pos) - { + if(g_state.prod_pos) { free(g_state.prod_pos); g_state.prod_pos = NULL; } - if(g_state.skel) - { + if(g_state.skel) { bpf_probe__detach(g_state.skel); bpf_probe__destroy(g_state.skel); } - if(g_state.rb_manager) - { + if(g_state.rb_manager) { ring_buffer__free(g_state.rb_manager); } } diff --git a/userspace/libpman/src/maps.c b/userspace/libpman/src/maps.c index 26c654e2c9..0229119747 100644 --- a/userspace/libpman/src/maps.c +++ b/userspace/libpman/src/maps.c @@ -31,32 +31,26 @@ extern const int g_ia32_64_map[]; /// TODO: in a future optimization we can think to remove this table, /// defining macros for `nparams` and directly use them inside bpf /// programs instead of reading from a map. -static void fill_event_params_table() -{ +static void fill_event_params_table() { uint8_t nparams_event = 0; - for(int j = 0; j < PPM_EVENT_MAX; ++j) - { + for(int j = 0; j < PPM_EVENT_MAX; ++j) { nparams_event = (uint8_t)g_event_info[j].nparams; g_state.skel->rodata->g_event_params_table[j] = nparams_event; } } -static void fill_ppm_sc_table() -{ - for(int j = 0; j < SYSCALL_TABLE_SIZE; ++j) - { +static void fill_ppm_sc_table() { + for(int j = 0; j < SYSCALL_TABLE_SIZE; ++j) { g_state.skel->rodata->g_ppm_sc_table[j] = (uint16_t)g_syscall_table[j].ppm_sc; } } -uint64_t pman_get_probe_api_ver() -{ +uint64_t pman_get_probe_api_ver() { return g_state.skel->rodata->probe_api_ver; } -uint64_t pman_get_probe_schema_ver() -{ +uint64_t pman_get_probe_schema_ver() { return g_state.skel->rodata->probe_schema_var; } @@ -64,95 +58,79 @@ uint64_t pman_get_probe_schema_ver() /*=============================== BPF GLOBAL VARIABLES ===============================*/ -void pman_set_snaplen(uint32_t desired_snaplen) -{ +void pman_set_snaplen(uint32_t desired_snaplen) { g_state.skel->bss->g_settings.snaplen = desired_snaplen; } -void pman_set_boot_time(uint64_t boot_time) -{ +void pman_set_boot_time(uint64_t boot_time) { g_state.skel->bss->g_settings.boot_time = boot_time; } -void pman_set_dropping_mode(bool value) -{ +void pman_set_dropping_mode(bool value) { g_state.skel->bss->g_settings.dropping_mode = value; } -void pman_set_sampling_ratio(uint32_t value) -{ +void pman_set_sampling_ratio(uint32_t value) { g_state.skel->bss->g_settings.sampling_ratio = value; } -void pman_set_drop_failed(bool drop_failed) -{ +void pman_set_drop_failed(bool drop_failed) { g_state.skel->bss->g_settings.drop_failed = drop_failed; } -void pman_set_do_dynamic_snaplen(bool do_dynamic_snaplen) -{ +void pman_set_do_dynamic_snaplen(bool do_dynamic_snaplen) { g_state.skel->bss->g_settings.do_dynamic_snaplen = do_dynamic_snaplen; } -void pman_set_fullcapture_port_range(uint16_t range_start, uint16_t range_end) -{ +void pman_set_fullcapture_port_range(uint16_t range_start, uint16_t range_end) { g_state.skel->bss->g_settings.fullcapture_port_range_start = range_start; g_state.skel->bss->g_settings.fullcapture_port_range_end = range_end; } -void pman_set_statsd_port(uint16_t statsd_port) -{ +void pman_set_statsd_port(uint16_t statsd_port) { g_state.skel->bss->g_settings.statsd_port = statsd_port; } -void pman_set_scap_tid(int32_t scap_tid) -{ +void pman_set_scap_tid(int32_t scap_tid) { g_state.skel->bss->g_settings.scap_tid = scap_tid; } -void pman_mark_single_64bit_syscall(int intersting_syscall_id, bool interesting) -{ +void pman_mark_single_64bit_syscall(int intersting_syscall_id, bool interesting) { g_state.skel->bss->g_64bit_interesting_syscalls_table[intersting_syscall_id] = interesting; } -void pman_fill_syscall_sampling_table() -{ - for(int syscall_id = 0; syscall_id < SYSCALL_TABLE_SIZE; syscall_id++) - { - if(g_syscall_table[syscall_id].flags & UF_NEVER_DROP) - { +void pman_fill_syscall_sampling_table() { + for(int syscall_id = 0; syscall_id < SYSCALL_TABLE_SIZE; syscall_id++) { + if(g_syscall_table[syscall_id].flags & UF_NEVER_DROP) { g_state.skel->bss->g_64bit_sampling_syscall_table[syscall_id] = UF_NEVER_DROP; continue; } /* Syscalls with `g_syscall_table[syscall_id].flags == UF_NONE` are the generic ones */ - if(g_syscall_table[syscall_id].flags & UF_ALWAYS_DROP || g_syscall_table[syscall_id].flags == UF_NONE) - { + if(g_syscall_table[syscall_id].flags & UF_ALWAYS_DROP || + g_syscall_table[syscall_id].flags == UF_NONE) { g_state.skel->bss->g_64bit_sampling_syscall_table[syscall_id] = UF_ALWAYS_DROP; continue; } - if(g_syscall_table[syscall_id].flags & UF_USED) - { + if(g_syscall_table[syscall_id].flags & UF_USED) { g_state.skel->bss->g_64bit_sampling_syscall_table[syscall_id] = 0; continue; } } } -void pman_fill_syscall_tracepoint_table() -{ - /* Right now these are the only 2 tracepoints involved in the dropping logic. We need to add them here */ +void pman_fill_syscall_tracepoint_table() { + /* Right now these are the only 2 tracepoints involved in the dropping logic. We need to add + * them here */ g_state.skel->bss->g_64bit_sampling_tracepoint_table[PPME_PROCEXIT_1_E] = UF_NEVER_DROP; g_state.skel->bss->g_64bit_sampling_tracepoint_table[PPME_SCHEDSWITCH_6_E] = 0; g_state.skel->bss->g_64bit_sampling_tracepoint_table[PPME_PAGE_FAULT_E] = UF_ALWAYS_DROP; g_state.skel->bss->g_64bit_sampling_tracepoint_table[PPME_SIGNALDELIVER_E] = UF_ALWAYS_DROP; } -void pman_fill_ia32_to_64_table() -{ - for(int syscall_id = 0; syscall_id < SYSCALL_TABLE_SIZE; syscall_id++) - { +void pman_fill_ia32_to_64_table() { + for(int syscall_id = 0; syscall_id < SYSCALL_TABLE_SIZE; syscall_id++) { // Note: we will map all syscalls from the upper limit of the ia32 table // up to SYSCALL_TABLE_SIZE to 0 (because they are not set in the g_ia32_64_map). // 0 is read on x86_64; this is not a problem though because @@ -162,21 +140,21 @@ void pman_fill_ia32_to_64_table() } } - /*=============================== BPF GLOBAL VARIABLES ===============================*/ /*=============================== BPF_MAP_TYPE_PROG_ARRAY ===============================*/ -static int add_bpf_program_to_tail_table(int tail_table_fd, const char* bpf_prog_name, int key) -{ +static int add_bpf_program_to_tail_table(int tail_table_fd, const char* bpf_prog_name, int key) { char error_message[MAX_ERROR_MESSAGE_LEN]; struct bpf_program* bpf_prog = NULL; int bpf_prog_fd = 0; bpf_prog = bpf_object__find_program_by_name(g_state.skel->obj, bpf_prog_name); - if(!bpf_prog) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "unable to find BPF program '%s'", bpf_prog_name); + if(!bpf_prog) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "unable to find BPF program '%s'", + bpf_prog_name); pman_print_msg(FALCOSECURITY_LOG_SEV_DEBUG, (const char*)error_message); /* @@ -188,16 +166,20 @@ static int add_bpf_program_to_tail_table(int tail_table_fd, const char* bpf_prog } bpf_prog_fd = bpf_program__fd(bpf_prog); - if(bpf_prog_fd <= 0) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "unable to get the fd for BPF program '%s'", bpf_prog_name); + if(bpf_prog_fd <= 0) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "unable to get the fd for BPF program '%s'", + bpf_prog_name); pman_print_error((const char*)error_message); goto clean_add_program_to_tail_table; } - if(bpf_map_update_elem(tail_table_fd, &key, &bpf_prog_fd, BPF_ANY)) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "unable to update the tail table with BPF program '%s'", bpf_prog_name); + if(bpf_map_update_elem(tail_table_fd, &key, &bpf_prog_fd, BPF_ANY)) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "unable to update the tail table with BPF program '%s'", + bpf_prog_name); pman_print_error((const char*)error_message); goto clean_add_program_to_tail_table; } @@ -208,8 +190,7 @@ static int add_bpf_program_to_tail_table(int tail_table_fd, const char* bpf_prog return errno; } -int pman_fill_syscalls_tail_table() -{ +int pman_fill_syscalls_tail_table() { int syscall_enter_tail_table_fd = 0; int syscall_exit_tail_table_fd = 0; int enter_event_type = 0; @@ -218,22 +199,18 @@ int pman_fill_syscalls_tail_table() const char* exit_prog_name; syscall_enter_tail_table_fd = bpf_map__fd(g_state.skel->maps.syscall_enter_tail_table); - if(syscall_enter_tail_table_fd <= 0) - { + if(syscall_enter_tail_table_fd <= 0) { pman_print_error("unable to get the syscall enter tail table"); return errno; } syscall_exit_tail_table_fd = bpf_map__fd(g_state.skel->maps.syscall_exit_tail_table); - if(syscall_exit_tail_table_fd <= 0) - { + if(syscall_exit_tail_table_fd <= 0) { pman_print_error("unable to get the syscall exit tail table"); return errno; } - for(int syscall_id = 0; syscall_id < SYSCALL_TABLE_SIZE; syscall_id++) - { - + for(int syscall_id = 0; syscall_id < SYSCALL_TABLE_SIZE; syscall_id++) { /* Get event type from `g_syscall_table` */ enter_event_type = g_syscall_table[syscall_id].enter_event_type; exit_event_type = g_syscall_table[syscall_id].exit_event_type; @@ -244,35 +221,32 @@ int pman_fill_syscalls_tail_table() * will be associated with the wrong bpf program, `generic_e` instead * of `generic_x`. */ - if(exit_event_type == PPME_GENERIC_E) - { + if(exit_event_type == PPME_GENERIC_E) { exit_event_type = PPME_GENERIC_X; } - /* At the end of the work, we should always have a corresponding bpf program for every event. - * Until we miss some syscalls, this is not true so we manage these cases as generic events. - * We need to remove this workaround when all syscalls will be implemented. + /* At the end of the work, we should always have a corresponding bpf program for every + * event. Until we miss some syscalls, this is not true so we manage these cases as generic + * events. We need to remove this workaround when all syscalls will be implemented. */ enter_prog_name = event_prog_names[enter_event_type]; exit_prog_name = event_prog_names[exit_event_type]; - if(!enter_prog_name) - { + if(!enter_prog_name) { enter_prog_name = event_prog_names[PPME_GENERIC_E]; } - if(!exit_prog_name) - { + if(!exit_prog_name) { exit_prog_name = event_prog_names[PPME_GENERIC_X]; } - if(add_bpf_program_to_tail_table(syscall_enter_tail_table_fd, enter_prog_name, syscall_id)) - { + if(add_bpf_program_to_tail_table(syscall_enter_tail_table_fd, + enter_prog_name, + syscall_id)) { goto clean_fill_syscalls_tail_table; } - if(add_bpf_program_to_tail_table(syscall_exit_tail_table_fd, exit_prog_name, syscall_id)) - { + if(add_bpf_program_to_tail_table(syscall_exit_tail_table_fd, exit_prog_name, syscall_id)) { goto clean_fill_syscalls_tail_table; } } @@ -284,29 +258,24 @@ int pman_fill_syscalls_tail_table() return errno; } -int pman_fill_extra_event_prog_tail_table() -{ +int pman_fill_extra_event_prog_tail_table() { int extra_event_prog_tail_table_fd = 0; const char* tail_prog_name; extra_event_prog_tail_table_fd = bpf_map__fd(g_state.skel->maps.extra_event_prog_tail_table); - if(extra_event_prog_tail_table_fd <= 0) - { + if(extra_event_prog_tail_table_fd <= 0) { pman_print_error("unable to get the extra event programs tail table"); return errno; } - for(int j = 0; j < TAIL_EXTRA_EVENT_PROG_MAX; j++) - { + for(int j = 0; j < TAIL_EXTRA_EVENT_PROG_MAX; j++) { tail_prog_name = extra_event_prog_names[j]; - if(!tail_prog_name) - { + if(!tail_prog_name) { continue; } - if(add_bpf_program_to_tail_table(extra_event_prog_tail_table_fd, tail_prog_name, j)) - { + if(add_bpf_program_to_tail_table(extra_event_prog_tail_table_fd, tail_prog_name, j)) { close(extra_event_prog_tail_table_fd); return errno; } @@ -318,22 +287,18 @@ int pman_fill_extra_event_prog_tail_table() /*=============================== BPF_MAP_TYPE_ARRAY ===============================*/ -static int size_auxiliary_maps() -{ +static int size_auxiliary_maps() { /* We always allocate auxiliary maps from all the CPUs, even if some of them are not online. */ - if(bpf_map__set_max_entries(g_state.skel->maps.auxiliary_maps, g_state.n_possible_cpus)) - { + if(bpf_map__set_max_entries(g_state.skel->maps.auxiliary_maps, g_state.n_possible_cpus)) { pman_print_error("unable to set max entries for 'auxiliary_maps'"); return errno; } return 0; } -static int size_counter_maps() -{ +static int size_counter_maps() { /* We always allocate counter maps from all the CPUs, even if some of them are not online. */ - if(bpf_map__set_max_entries(g_state.skel->maps.counter_maps, g_state.n_possible_cpus)) - { + if(bpf_map__set_max_entries(g_state.skel->maps.counter_maps, g_state.n_possible_cpus)) { pman_print_error(" unable to set max entries for 'counter_maps'"); return errno; } @@ -345,8 +310,7 @@ static int size_counter_maps() /* Here we split maps operations, before and after the loading phase. */ -int pman_prepare_maps_before_loading() -{ +int pman_prepare_maps_before_loading() { int err; /* Read-only global variables must be set before loading phase. */ @@ -361,8 +325,7 @@ int pman_prepare_maps_before_loading() return err; } -int pman_finalize_maps_after_loading() -{ +int pman_finalize_maps_after_loading() { int err; /* set bpf global variables. */ diff --git a/userspace/libpman/src/programs.c b/userspace/libpman/src/programs.c index d8437223d8..17f73bea9a 100644 --- a/userspace/libpman/src/programs.c +++ b/userspace/libpman/src/programs.c @@ -26,86 +26,71 @@ limitations under the License. /*=============================== ATTACH PROGRAMS ===============================*/ -int pman_attach_syscall_enter_dispatcher() -{ +int pman_attach_syscall_enter_dispatcher() { /* The program is already attached. */ - if(g_state.skel->links.sys_enter != NULL) - { + if(g_state.skel->links.sys_enter != NULL) { return 0; } g_state.skel->links.sys_enter = bpf_program__attach(g_state.skel->progs.sys_enter); - if(!g_state.skel->links.sys_enter) - { + if(!g_state.skel->links.sys_enter) { pman_print_error("failed to attach the 'sys_enter' program"); return errno; } return 0; } -int pman_attach_syscall_exit_dispatcher() -{ +int pman_attach_syscall_exit_dispatcher() { /* The program is already attached. */ - if(g_state.skel->links.sys_exit != NULL) - { + if(g_state.skel->links.sys_exit != NULL) { return 0; } g_state.skel->links.sys_exit = bpf_program__attach(g_state.skel->progs.sys_exit); - if(!g_state.skel->links.sys_exit) - { + if(!g_state.skel->links.sys_exit) { pman_print_error("failed to attach the 'sys_exit' program"); return errno; } return 0; } -int pman_attach_sched_proc_exit() -{ +int pman_attach_sched_proc_exit() { /* The program is already attached. */ - if(g_state.skel->links.sched_proc_exit != NULL) - { + if(g_state.skel->links.sched_proc_exit != NULL) { return 0; } g_state.skel->links.sched_proc_exit = bpf_program__attach(g_state.skel->progs.sched_proc_exit); - if(!g_state.skel->links.sched_proc_exit) - { + if(!g_state.skel->links.sched_proc_exit) { pman_print_error("failed to attach the 'sched_proc_exit' program"); return errno; } return 0; } -int pman_attach_sched_switch() -{ +int pman_attach_sched_switch() { /* The program is already attached. */ - if(g_state.skel->links.sched_switch != NULL) - { + if(g_state.skel->links.sched_switch != NULL) { return 0; } g_state.skel->links.sched_switch = bpf_program__attach(g_state.skel->progs.sched_switch); - if(!g_state.skel->links.sched_switch) - { + if(!g_state.skel->links.sched_switch) { pman_print_error("failed to attach the 'sched_switch' program"); return errno; } return 0; } -int pman_attach_sched_proc_exec() -{ +int pman_attach_sched_proc_exec() { #ifdef CAPTURE_SCHED_PROC_EXEC /* The program is already attached. */ - if(g_state.skel->links.sched_p_exec != NULL) - { + if(g_state.skel->links.sched_p_exec != NULL) { return 0; } g_state.skel->links.sched_p_exec = bpf_program__attach(g_state.skel->progs.sched_p_exec); - if(!g_state.skel->links.sched_p_exec) - { + if(!g_state.skel->links.sched_p_exec) { pman_print_error("failed to attach the 'sched_proc_exec' program"); return errno; } @@ -113,18 +98,15 @@ int pman_attach_sched_proc_exec() return 0; } -int pman_attach_sched_proc_fork() -{ +int pman_attach_sched_proc_fork() { #ifdef CAPTURE_SCHED_PROC_FORK /* The program is already attached. */ - if(g_state.skel->links.sched_p_fork != NULL) - { + if(g_state.skel->links.sched_p_fork != NULL) { return 0; } g_state.skel->links.sched_p_fork = bpf_program__attach(g_state.skel->progs.sched_p_fork); - if(!g_state.skel->links.sched_p_fork) - { + if(!g_state.skel->links.sched_p_fork) { pman_print_error("failed to attach the 'sched_proc_fork' program"); return errno; } @@ -132,18 +114,15 @@ int pman_attach_sched_proc_fork() return 0; } -int pman_attach_page_fault_user() -{ +int pman_attach_page_fault_user() { #ifdef CAPTURE_PAGE_FAULTS /* The program is already attached. */ - if(g_state.skel->links.pf_user != NULL) - { + if(g_state.skel->links.pf_user != NULL) { return 0; } g_state.skel->links.pf_user = bpf_program__attach(g_state.skel->progs.pf_user); - if(!g_state.skel->links.pf_user) - { + if(!g_state.skel->links.pf_user) { pman_print_error("failed to attach the 'pf_user' program"); return errno; } @@ -151,18 +130,15 @@ int pman_attach_page_fault_user() return 0; } -int pman_attach_page_fault_kernel() -{ +int pman_attach_page_fault_kernel() { #ifdef CAPTURE_PAGE_FAULTS /* The program is already attached. */ - if(g_state.skel->links.pf_kernel != NULL) - { + if(g_state.skel->links.pf_kernel != NULL) { return 0; } g_state.skel->links.pf_kernel = bpf_program__attach(g_state.skel->progs.pf_kernel); - if(!g_state.skel->links.pf_kernel) - { + if(!g_state.skel->links.pf_kernel) { pman_print_error("failed to attach the 'pf_kernel' program"); return errno; } @@ -170,17 +146,14 @@ int pman_attach_page_fault_kernel() return 0; } -int pman_attach_signal_deliver() -{ +int pman_attach_signal_deliver() { /* The program is already attached. */ - if(g_state.skel->links.signal_deliver != NULL) - { + if(g_state.skel->links.signal_deliver != NULL) { return 0; } g_state.skel->links.signal_deliver = bpf_program__attach(g_state.skel->progs.signal_deliver); - if(!g_state.skel->links.signal_deliver) - { + if(!g_state.skel->links.signal_deliver) { pman_print_error("failed to attach the 'signal_deliver' program"); return errno; } @@ -191,10 +164,8 @@ int pman_attach_signal_deliver() /*=============================== DETACH PROGRAMS ===============================*/ -int pman_detach_syscall_enter_dispatcher() -{ - if(g_state.skel->links.sys_enter && bpf_link__destroy(g_state.skel->links.sys_enter)) - { +int pman_detach_syscall_enter_dispatcher() { + if(g_state.skel->links.sys_enter && bpf_link__destroy(g_state.skel->links.sys_enter)) { pman_print_error("failed to detach the 'sys_enter' program"); return errno; } @@ -202,10 +173,8 @@ int pman_detach_syscall_enter_dispatcher() return 0; } -int pman_detach_syscall_exit_dispatcher() -{ - if(g_state.skel->links.sys_exit && bpf_link__destroy(g_state.skel->links.sys_exit)) - { +int pman_detach_syscall_exit_dispatcher() { + if(g_state.skel->links.sys_exit && bpf_link__destroy(g_state.skel->links.sys_exit)) { pman_print_error("failed to detach the 'sys_exit' program"); return errno; } @@ -213,10 +182,9 @@ int pman_detach_syscall_exit_dispatcher() return 0; } -int pman_detach_sched_proc_exit() -{ - if(g_state.skel->links.sched_proc_exit && bpf_link__destroy(g_state.skel->links.sched_proc_exit)) - { +int pman_detach_sched_proc_exit() { + if(g_state.skel->links.sched_proc_exit && + bpf_link__destroy(g_state.skel->links.sched_proc_exit)) { pman_print_error("failed to detach the 'sched_proc_exit' program"); return errno; } @@ -224,10 +192,8 @@ int pman_detach_sched_proc_exit() return 0; } -int pman_detach_sched_switch() -{ - if(g_state.skel->links.sched_switch && bpf_link__destroy(g_state.skel->links.sched_switch)) - { +int pman_detach_sched_switch() { + if(g_state.skel->links.sched_switch && bpf_link__destroy(g_state.skel->links.sched_switch)) { pman_print_error("failed to detach the 'sched_switch' program"); return errno; } @@ -235,11 +201,9 @@ int pman_detach_sched_switch() return 0; } -int pman_detach_sched_proc_exec() -{ +int pman_detach_sched_proc_exec() { #ifdef CAPTURE_SCHED_PROC_EXEC - if(g_state.skel->links.sched_p_exec && bpf_link__destroy(g_state.skel->links.sched_p_exec)) - { + if(g_state.skel->links.sched_p_exec && bpf_link__destroy(g_state.skel->links.sched_p_exec)) { pman_print_error("failed to detach the 'sched_proc_exec' program"); return errno; } @@ -248,11 +212,9 @@ int pman_detach_sched_proc_exec() return 0; } -int pman_detach_sched_proc_fork() -{ +int pman_detach_sched_proc_fork() { #ifdef CAPTURE_SCHED_PROC_FORK - if(g_state.skel->links.sched_p_fork && bpf_link__destroy(g_state.skel->links.sched_p_fork)) - { + if(g_state.skel->links.sched_p_fork && bpf_link__destroy(g_state.skel->links.sched_p_fork)) { pman_print_error("failed to detach the 'sched_proc_fork' program"); return errno; } @@ -261,11 +223,9 @@ int pman_detach_sched_proc_fork() return 0; } -int pman_detach_page_fault_user() -{ +int pman_detach_page_fault_user() { #ifdef CAPTURE_PAGE_FAULTS - if(g_state.skel->links.pf_user && bpf_link__destroy(g_state.skel->links.pf_user)) - { + if(g_state.skel->links.pf_user && bpf_link__destroy(g_state.skel->links.pf_user)) { pman_print_error("failed to detach the 'pf_user' program"); return errno; } @@ -274,11 +234,9 @@ int pman_detach_page_fault_user() return 0; } -int pman_detach_page_fault_kernel() -{ +int pman_detach_page_fault_kernel() { #ifdef CAPTURE_PAGE_FAULTS - if(g_state.skel->links.pf_kernel && bpf_link__destroy(g_state.skel->links.pf_kernel)) - { + if(g_state.skel->links.pf_kernel && bpf_link__destroy(g_state.skel->links.pf_kernel)) { pman_print_error("failed to detach the 'pf_kernel' program"); return errno; } @@ -287,10 +245,9 @@ int pman_detach_page_fault_kernel() return 0; } -int pman_detach_signal_deliver() -{ - if(g_state.skel->links.signal_deliver && bpf_link__destroy(g_state.skel->links.signal_deliver)) - { +int pman_detach_signal_deliver() { + if(g_state.skel->links.signal_deliver && + bpf_link__destroy(g_state.skel->links.signal_deliver)) { pman_print_error("failed to detach the 'signal_deliver' program"); return errno; } diff --git a/userspace/libpman/src/ringbuffer.c b/userspace/libpman/src/ringbuffer.c index 2fb4f7844f..4e4207b153 100644 --- a/userspace/libpman/src/ringbuffer.c +++ b/userspace/libpman/src/ringbuffer.c @@ -32,20 +32,18 @@ limitations under the License. /* This must be done to please the verifier! At load-time, the verifier must know the * size of a map inside the array. */ -static int ringbuf_array_set_inner_map() -{ +static int ringbuf_array_set_inner_map() { int err = 0; - int inner_map_fd = bpf_map_create(BPF_MAP_TYPE_RINGBUF, NULL, 0, 0, g_state.buffer_bytes_dim, NULL); - if(inner_map_fd < 0) - { + int inner_map_fd = + bpf_map_create(BPF_MAP_TYPE_RINGBUF, NULL, 0, 0, g_state.buffer_bytes_dim, NULL); + if(inner_map_fd < 0) { pman_print_error("failed to create the dummy inner map"); return errno; } /* Set the inner map file descriptor into the outer map. */ err = bpf_map__set_inner_map_fd(g_state.skel->maps.ringbuf_maps, inner_map_fd); - if(err) - { + if(err) { pman_print_error("failed to set the dummy inner map inside the ringbuf array"); close(inner_map_fd); return errno; @@ -56,27 +54,23 @@ static int ringbuf_array_set_inner_map() return 0; } -static int ringbuf_array_set_max_entries() -{ +static int ringbuf_array_set_max_entries() { /* We always allocate a number of entries equal to the available CPUs. * This doesn't mean that we allocate a ring buffer for every available CPU, * it means only that every CPU will have an associated entry. */ - if(bpf_map__set_max_entries(g_state.skel->maps.ringbuf_maps, g_state.n_possible_cpus)) - { + if(bpf_map__set_max_entries(g_state.skel->maps.ringbuf_maps, g_state.n_possible_cpus)) { pman_print_error("unable to set max entries for the ringbuf_array"); return errno; } return 0; } -static int allocate_consumer_producer_positions() -{ +static int allocate_consumer_producer_positions() { g_state.ringbuf_pos = 0; g_state.cons_pos = (unsigned long *)calloc(g_state.n_required_buffers, sizeof(unsigned long)); g_state.prod_pos = (unsigned long *)calloc(g_state.n_required_buffers, sizeof(unsigned long)); - if(g_state.cons_pos == NULL || g_state.prod_pos == NULL) - { + if(g_state.cons_pos == NULL || g_state.prod_pos == NULL) { pman_print_error("failed to alloc memory for cons_pos and prod_pos"); return errno; } @@ -84,8 +78,7 @@ static int allocate_consumer_producer_positions() } /* Before loading */ -int pman_prepare_ringbuf_array_before_loading() -{ +int pman_prepare_ringbuf_array_before_loading() { int err; err = ringbuf_array_set_inner_map(); err = err ?: ringbuf_array_set_max_entries(); @@ -94,11 +87,9 @@ int pman_prepare_ringbuf_array_before_loading() return err; } -static bool is_cpu_online(uint16_t cpu_id) -{ +static bool is_cpu_online(uint16_t cpu_id) { /* CPU 0 is always online */ - if(cpu_id == 0) - { + if(cpu_id == 0) { return true; } @@ -106,26 +97,21 @@ static bool is_cpu_online(uint16_t cpu_id) int online = 0; snprintf(filename, sizeof(filename), "/sys/devices/system/cpu/cpu%d/online", cpu_id); FILE *fp = fopen(filename, "r"); - if(fp == NULL) - { + if(fp == NULL) { /* When missing NUMA properties, CPUs do not expose online information. * Fallback at considering them online if we can at least reach their folder. * This is useful for example for raspPi devices. * See: https://github.com/kubernetes/kubernetes/issues/95039 */ snprintf(filename, sizeof(filename), "/sys/devices/system/cpu/cpu%d/", cpu_id); - if(access(filename, F_OK) == 0) - { + if(access(filename, F_OK) == 0) { return true; - } - else - { + } else { return false; } } - if(fscanf(fp, "%d", &online) != 1) - { + if(fscanf(fp, "%d", &online) != 1) { online = 0; } fclose(fp); @@ -133,13 +119,11 @@ static bool is_cpu_online(uint16_t cpu_id) } /* After loading */ -int pman_finalize_ringbuf_array_after_loading() -{ +int pman_finalize_ringbuf_array_after_loading() { int ringubuf_array_fd = -1; char error_message[MAX_ERROR_MESSAGE_LEN]; int *ringbufs_fds = (int *)calloc(g_state.n_required_buffers, sizeof(int)); - if(ringbufs_fds == NULL) - { + if(ringbufs_fds == NULL) { pman_print_error("failed to allocate the ringubufs_fds array"); return errno; } @@ -149,12 +133,15 @@ int pman_finalize_ringbuf_array_after_loading() close(g_state.inner_ringbuf_map_fd); /* Create ring buffer maps. */ - for(int i = 0; i < g_state.n_required_buffers; i++) - { - ringbufs_fds[i] = bpf_map_create(BPF_MAP_TYPE_RINGBUF, NULL, 0, 0, g_state.buffer_bytes_dim, NULL); - if(ringbufs_fds[i] <= 0) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "failed to create the ringbuf map for CPU '%d'. (If you get memory allocation errors try to reduce the buffer dimension)", i); + for(int i = 0; i < g_state.n_required_buffers; i++) { + ringbufs_fds[i] = + bpf_map_create(BPF_MAP_TYPE_RINGBUF, NULL, 0, 0, g_state.buffer_bytes_dim, NULL); + if(ringbufs_fds[i] <= 0) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "failed to create the ringbuf map for CPU '%d'. (If you get memory allocation " + "errors try to reduce the buffer dimension)", + i); pman_print_error((const char *)error_message); goto clean_percpu_ring_buffers; } @@ -162,8 +149,7 @@ int pman_finalize_ringbuf_array_after_loading() /* Create the ringbuf manager */ g_state.rb_manager = ring_buffer__new(ringbufs_fds[0], NULL, NULL, NULL); - if(!g_state.rb_manager) - { + if(!g_state.rb_manager) { pman_print_error("failed to instantiate the ringbuf manager."); goto clean_percpu_ring_buffers; } @@ -172,11 +158,12 @@ int pman_finalize_ringbuf_array_after_loading() * We start from 1 because the first one is * used to instantiate the manager. */ - for(int i = 1; i < g_state.n_required_buffers; i++) - { - if(ring_buffer__add(g_state.rb_manager, ringbufs_fds[i], NULL, NULL)) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "failed to add the ringbuf map for CPU %d into the manager", i); + for(int i = 1; i < g_state.n_required_buffers; i++) { + if(ring_buffer__add(g_state.rb_manager, ringbufs_fds[i], NULL, NULL)) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "failed to add the ringbuf map for CPU %d into the manager", + i); pman_print_error((const char *)error_message); goto clean_percpu_ring_buffers; } @@ -184,8 +171,7 @@ int pman_finalize_ringbuf_array_after_loading() /* `ringbuf_array` is a maps array, every map inside it is a `BPF_MAP_TYPE_RINGBUF`. */ ringubuf_array_fd = bpf_map__fd(g_state.skel->maps.ringbuf_maps); - if(ringubuf_array_fd <= 0) - { + if(ringubuf_array_fd <= 0) { pman_print_error("failed to get the ringubuf_array"); return errno; } @@ -193,35 +179,37 @@ int pman_finalize_ringbuf_array_after_loading() /* We need to associate every CPU to the right ring buffer */ int ringbuf_id = 0; int reached = 0; - for(int i = 0; i < g_state.n_possible_cpus; i++) - { + for(int i = 0; i < g_state.n_possible_cpus; i++) { /* If we want to allocate only buffers for online CPUs and the CPU is online, fill its * ring buffer array entry, otherwise we can go on with the next online CPU */ - if(g_state.allocate_online_only && !is_cpu_online(i)) - { + if(g_state.allocate_online_only && !is_cpu_online(i)) { continue; } - if(ringbuf_id >= g_state.n_required_buffers) - { + if(ringbuf_id >= g_state.n_required_buffers) { /* If we arrive here it means that we have too many CPUs for our allocated ring buffers * so probably we faced a CPU hotplug. */ - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "the actual system configuration requires more than '%d' ring buffers", g_state.n_required_buffers); + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "the actual system configuration requires more than '%d' ring buffers", + g_state.n_required_buffers); pman_print_error((const char *)error_message); goto clean_percpu_ring_buffers; } - if(bpf_map_update_elem(ringubuf_array_fd, &i, &ringbufs_fds[ringbuf_id], BPF_ANY)) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "failed to add the ringbuf map for CPU '%d' to ringbuf '%d'", i, ringbuf_id); + if(bpf_map_update_elem(ringubuf_array_fd, &i, &ringbufs_fds[ringbuf_id], BPF_ANY)) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "failed to add the ringbuf map for CPU '%d' to ringbuf '%d'", + i, + ringbuf_id); pman_print_error((const char *)error_message); goto clean_percpu_ring_buffers; } - if(++reached == g_state.cpus_for_each_buffer) - { + if(++reached == g_state.cpus_for_each_buffer) { /* we need to switch to the next buffer */ reached = 0; ringbuf_id++; @@ -230,44 +218,37 @@ int pman_finalize_ringbuf_array_after_loading() success = true; clean_percpu_ring_buffers: - for(int i = 0; i < g_state.n_required_buffers; i++) - { - if(ringbufs_fds[i]) - { + for(int i = 0; i < g_state.n_required_buffers; i++) { + if(ringbufs_fds[i]) { close(ringbufs_fds[i]); } } free(ringbufs_fds); - if(success) - { + if(success) { return 0; } close(ringubuf_array_fd); - if(g_state.rb_manager) - { + if(g_state.rb_manager) { ring_buffer__free(g_state.rb_manager); } return errno; } -static inline void *ringbuf__get_first_ring_event(struct ring *r, int pos) -{ +static inline void *ringbuf__get_first_ring_event(struct ring *r, int pos) { int *len_ptr = NULL; int len = 0; /* If the consumer reaches the producer update the producer position to * get the newly collected events. */ - if(g_state.cons_pos[pos] == g_state.prod_pos[pos]) - { + if(g_state.cons_pos[pos] == g_state.prod_pos[pos]) { // We try to increment the producer and continue. It is likely that the producer // has produced new events on this CPU and these events could have a timestamp // lowest than all the other events in the other buffers. g_state.prod_pos[pos] = smp_load_acquire(r->producer_pos); - if(g_state.cons_pos[pos] == g_state.prod_pos[pos]) - { + if(g_state.cons_pos[pos] == g_state.prod_pos[pos]) { return NULL; } } @@ -276,20 +257,16 @@ static inline void *ringbuf__get_first_ring_event(struct ring *r, int pos) len = smp_load_acquire(len_ptr); /* The actual event is not yet committed */ - if(len & BPF_RINGBUF_BUSY_BIT) - { + if(len & BPF_RINGBUF_BUSY_BIT) { return NULL; } /* the sample is not discarded kernel side. */ - if((len & BPF_RINGBUF_DISCARD_BIT) == 0) - { + if((len & BPF_RINGBUF_DISCARD_BIT) == 0) { /* Save the size of the event if we need to increment the consumer */ g_state.last_event_size = roundup_len(len); return (void *)len_ptr + BPF_RINGBUF_HDR_SZ; - } - else - { + } else { /* Discard the event kernel side and update the consumer position */ g_state.cons_pos[pos] += roundup_len(len); smp_store_release(r->consumer_pos, g_state.cons_pos[pos]); @@ -297,40 +274,37 @@ static inline void *ringbuf__get_first_ring_event(struct ring *r, int pos) } } -static void ringbuf__consume_first_event(struct ring_buffer *rb, struct ppm_evt_hdr **event_ptr, int16_t *buffer_id) -{ +static void ringbuf__consume_first_event(struct ring_buffer *rb, + struct ppm_evt_hdr **event_ptr, + int16_t *buffer_id) { uint64_t min_ts = 0xffffffffffffffffLL; struct ppm_evt_hdr *tmp_pointer = NULL; int tmp_ring = -1; unsigned long tmp_cons_increment = 0; /* If the last consume operation was successful we can push the consumer position */ - if(g_state.last_ring_read != -1) - { + if(g_state.last_ring_read != -1) { struct ring *r = rb->rings[g_state.last_ring_read]; g_state.cons_pos[g_state.last_ring_read] += g_state.last_event_size; smp_store_release(r->consumer_pos, g_state.cons_pos[g_state.last_ring_read]); } R_D_MSG("\n-----------------------------\nIterate over all the buffers\n"); - for(uint16_t pos = 0; pos < rb->ring_cnt; pos++) - { + for(uint16_t pos = 0; pos < rb->ring_cnt; pos++) { *event_ptr = ringbuf__get_first_ring_event(rb->rings[pos], pos); R_D_EVENT(*event_ptr, pos); /* if NULL search for events in another buffer */ - if(*event_ptr == NULL) - { + if(*event_ptr == NULL) { continue; } - if((*event_ptr)->ts < min_ts) - { + if((*event_ptr)->ts < min_ts) { min_ts = (*event_ptr)->ts; tmp_pointer = *event_ptr; tmp_ring = pos; tmp_cons_increment = g_state.last_event_size; - R_D_MSG("Found new min with ts '%ld' on buffer %d\n",(*event_ptr)->ts, pos); + R_D_MSG("Found new min with ts '%ld' on buffer %d\n", (*event_ptr)->ts, pos); } } @@ -343,7 +317,6 @@ static void ringbuf__consume_first_event(struct ring_buffer *rb, struct ppm_evt_ } /* Consume */ -void pman_consume_first_event(void **event_ptr, int16_t *buffer_id) -{ +void pman_consume_first_event(void **event_ptr, int16_t *buffer_id) { ringbuf__consume_first_event(g_state.rb_manager, (struct ppm_evt_hdr **)event_ptr, buffer_id); } diff --git a/userspace/libpman/src/ringbuffer_debug_macro.h b/userspace/libpman/src/ringbuffer_debug_macro.h index 52dfa1daa0..b022febd24 100644 --- a/userspace/libpman/src/ringbuffer_debug_macro.h +++ b/userspace/libpman/src/ringbuffer_debug_macro.h @@ -28,14 +28,11 @@ limitations under the License. // R_D stands for Ringbuffer Debugging #define R_D_MSG(...) printf(__VA_ARGS__) -#define R_D_EVENT(event, ring_id) \ - if(event == NULL) \ - { \ - R_D_MSG("[NULL Event] buf: %d\n", ring_id); \ - } \ - else \ - { \ - R_D_MSG("[Event] ts: %ld, buf: %d\n", (event)->ts, ring_id); \ +#define R_D_EVENT(event, ring_id) \ + if(event == NULL) { \ + R_D_MSG("[NULL Event] buf: %d\n", ring_id); \ + } else { \ + R_D_MSG("[Event] ts: %ld, buf: %d\n", (event)->ts, ring_id); \ } #else diff --git a/userspace/libpman/src/ringbuffer_definitions.h b/userspace/libpman/src/ringbuffer_definitions.h index 3507b8d988..8c134b7a79 100644 --- a/userspace/libpman/src/ringbuffer_definitions.h +++ b/userspace/libpman/src/ringbuffer_definitions.h @@ -22,8 +22,7 @@ limitations under the License. #include /* Taken from libbpf: /src/ringbuf.c */ -struct ring -{ +struct ring { ring_buffer_sample_fn sample_cb; void *ctx; void *data; @@ -33,8 +32,7 @@ struct ring int map_fd; }; -struct ring_buffer -{ +struct ring_buffer { struct epoll_event *events; struct ring **rings; size_t page_size; @@ -43,8 +41,7 @@ struct ring_buffer }; /* This is done to write on multiples of 8 bytes. */ -static inline int roundup_len(uint32_t len) -{ +static inline int roundup_len(uint32_t len) { /* clear out top 2 bits (discard and busy, if set) */ len <<= 2; len >>= 2; @@ -59,18 +56,16 @@ static inline int roundup_len(uint32_t len) #define READ_ONCE(x) (*(volatile typeof(x) *)&x) #define WRITE_ONCE(x, v) (*(volatile typeof(x) *)&x) = (v) -#define barrier() asm volatile("" :: \ - : "memory") +#define barrier() asm volatile("" ::: "memory") -#define smp_store_release(p, v) \ - do \ - { \ - barrier(); \ - WRITE_ONCE(*p, v); \ +#define smp_store_release(p, v) \ + do { \ + barrier(); \ + WRITE_ONCE(*p, v); \ } while(0) -#define smp_load_acquire(p) \ - ({ \ +#define smp_load_acquire(p) \ + ({ \ typeof(*p) ___p = READ_ONCE(*p); \ barrier(); \ ___p; \ diff --git a/userspace/libpman/src/sc_set.c b/userspace/libpman/src/sc_set.c index 676298db1b..66abd8d511 100644 --- a/userspace/libpman/src/sc_set.c +++ b/userspace/libpman/src/sc_set.c @@ -21,20 +21,17 @@ limitations under the License. #include /* This function should be idempotent, every time it is called it should enforce again the state */ -int pman_enforce_sc_set(bool *sc_set) -{ +int pman_enforce_sc_set(bool *sc_set) { /* If we fail at initialization time the BPF skeleton * is not initialized when we stop the capture for example */ - if(!g_state.skel) - { + if(!g_state.skel) { return SCAP_FAILURE; } /* When we want to disable the capture we receive a NULL pointer here */ bool empty_sc_set[PPM_SC_MAX] = {0}; - if(!sc_set) - { + if(!sc_set) { sc_set = empty_sc_set; } @@ -47,38 +44,28 @@ int pman_enforce_sc_set(bool *sc_set) bool sched_prog_exec = false; /* Enforce interesting syscalls */ - for(int sc = 0; sc < PPM_SC_MAX; sc++) - { + for(int sc = 0; sc < PPM_SC_MAX; sc++) { syscall_id = scap_ppm_sc_to_native_id(sc); /* if `syscall_id` is -1 this is not a syscall */ - if(syscall_id == -1) - { + if(syscall_id == -1) { continue; } - if(!sc_set[sc]) - { + if(!sc_set[sc]) { pman_mark_single_64bit_syscall(syscall_id, false); - } - else - { + } else { sys_enter = true; sys_exit = true; pman_mark_single_64bit_syscall(syscall_id, true); } } - if(sc_set[PPM_SC_FORK] || - sc_set[PPM_SC_VFORK] || - sc_set[PPM_SC_CLONE] || - sc_set[PPM_SC_CLONE3]) - { + if(sc_set[PPM_SC_FORK] || sc_set[PPM_SC_VFORK] || sc_set[PPM_SC_CLONE] || + sc_set[PPM_SC_CLONE3]) { sched_prog_fork = true; } - if(sc_set[PPM_SC_EXECVE] || - sc_set[PPM_SC_EXECVEAT]) - { + if(sc_set[PPM_SC_EXECVE] || sc_set[PPM_SC_EXECVEAT]) { sched_prog_exec = true; } diff --git a/userspace/libpman/src/state.c b/userspace/libpman/src/state.c index 687d061b1b..2418ccc895 100644 --- a/userspace/libpman/src/state.c +++ b/userspace/libpman/src/state.c @@ -25,19 +25,15 @@ limitations under the License. struct internal_state g_state = {}; -static void log_msg(enum falcosecurity_log_severity level, const char* fmt, ...) -{ +static void log_msg(enum falcosecurity_log_severity level, const char* fmt, ...) { va_list args; va_start(args, fmt); - if(g_state.log_fn != NULL) - { + if(g_state.log_fn != NULL) { char buf[MAX_ERROR_MESSAGE_LEN]; vsnprintf(buf, sizeof(buf), fmt, args); g_state.log_fn("libpman", buf, level); - } - else - { + } else { fprintf(stderr, "libpman: "); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); @@ -46,20 +42,16 @@ static void log_msg(enum falcosecurity_log_severity level, const char* fmt, ...) va_end(args); } -void pman_print_error(const char* error_message) -{ +void pman_print_error(const char* error_message) { pman_print_msg(FALCOSECURITY_LOG_SEV_ERROR, error_message); } -void pman_print_msg(enum falcosecurity_log_severity level, const char* error_message) -{ - if(!error_message) - { +void pman_print_msg(enum falcosecurity_log_severity level, const char* error_message) { + if(!error_message) { return; } - if(errno != 0) - { + if(errno != 0) { /* * libbpf uses -ESRCH to indicate that something could not be found, * e.g. vmlinux or btf id. This will be interpreted via strerror as "No @@ -69,9 +61,7 @@ void pman_print_msg(enum falcosecurity_log_severity level, const char* error_mes */ const char* err_str = (errno == ESRCH) ? "Object not found" : strerror(errno); log_msg(level, "%s (errno: %d | message: %s)", error_message, errno, err_str); - } - else - { + } else { log_msg(level, "%s", error_message); } } diff --git a/userspace/libpman/src/state.h b/userspace/libpman/src/state.h index 46a5edcd1e..d70f078b75 100644 --- a/userspace/libpman/src/state.h +++ b/userspace/libpman/src/state.h @@ -29,40 +29,43 @@ limitations under the License. #define MAX_ERROR_MESSAGE_LEN 200 -/* Pay attention this need to be bumped every time we add a new bpf program that is directly attached into the kernel */ +/* Pay attention this need to be bumped every time we add a new bpf program that is directly + * attached into the kernel */ #define MODERN_BPF_PROG_ATTACHED_MAX 9 -#define BPF_LOG_BIG_BUF_SIZE (UINT32_MAX >> 8) /* Recommended log buffer size, taken from libbpf. Used for verifier logs */ +#define BPF_LOG_BIG_BUF_SIZE \ + (UINT32_MAX >> 8) /* Recommended log buffer size, taken from libbpf. Used for verifier logs */ #define BPF_LOG_SMALL_BUF_SIZE 8192 /* Used for libbpf non-verifier logs */ struct metrics_v2; -struct internal_state -{ - struct bpf_probe* skel; /* bpf skeleton with all programs and maps. */ +struct internal_state { + struct bpf_probe* skel; /* bpf skeleton with all programs and maps. */ struct ring_buffer* rb_manager; /* ring_buffer manager with all per-CPU ringbufs. */ - int16_t n_possible_cpus; /* number of possible system CPUs (online and not). */ - int16_t n_interesting_cpus; /* according to userspace configuration we can consider only online CPUs or all - available CPUs. */ - bool allocate_online_only; /* If true we allocate ring buffers only for online CPUs */ - uint32_t n_required_buffers; /* number of ring buffers we need to allocate */ - uint16_t cpus_for_each_buffer; /* Users want a ring buffer every `cpus_for_each_buffer` CPUs */ - int ringbuf_pos; /* actual ringbuf we are considering. */ - unsigned long* cons_pos; /* every ringbuf has a consumer position. */ - unsigned long* prod_pos; /* every ringbuf has a producer position. */ - int32_t inner_ringbuf_map_fd; /* inner map used to configure the ringbuf array before loading phase. */ + int16_t n_possible_cpus; /* number of possible system CPUs (online and not). */ + int16_t n_interesting_cpus; /* according to userspace configuration we can consider only online + CPUs or all available CPUs. */ + bool allocate_online_only; /* If true we allocate ring buffers only for online CPUs */ + uint32_t n_required_buffers; /* number of ring buffers we need to allocate */ + uint16_t cpus_for_each_buffer; /* Users want a ring buffer every `cpus_for_each_buffer` CPUs */ + int ringbuf_pos; /* actual ringbuf we are considering. */ + unsigned long* cons_pos; /* every ringbuf has a consumer position. */ + unsigned long* prod_pos; /* every ringbuf has a producer position. */ + int32_t inner_ringbuf_map_fd; /* inner map used to configure the ringbuf array before loading + phase. */ unsigned long buffer_bytes_dim; /* dimension of a single per-CPU ringbuffer in bytes. */ - int last_ring_read; /* Last ring from which we have correctly read an event. Could be `-1` if there were no - successful reads. */ - unsigned long last_event_size; /* Last event correctly read. Could be `0` if there were no successful reads. */ + int last_ring_read; /* Last ring from which we have correctly read an event. Could be `-1` if + there were no successful reads. */ + unsigned long last_event_size; /* Last event correctly read. Could be `0` if there were no + successful reads. */ /* Stats v2 utilities */ - int32_t attached_progs_fds[MODERN_BPF_PROG_ATTACHED_MAX]; /* file descriptors of attached programs, used to - collect stats */ - struct metrics_v2* stats; /* array of stats collected by libpman */ - uint32_t nstats; /* number of stats */ - char* log_buf; /* buffer used to store logs before sending them to the log_fn */ - size_t log_buf_size; /* size of the log buffer */ + int32_t attached_progs_fds[MODERN_BPF_PROG_ATTACHED_MAX]; /* file descriptors of attached + programs, used to collect stats */ + struct metrics_v2* stats; /* array of stats collected by libpman */ + uint32_t nstats; /* number of stats */ + char* log_buf; /* buffer used to store logs before sending them to the log_fn */ + size_t log_buf_size; /* size of the log buffer */ falcosecurity_log_fn log_fn; }; diff --git a/userspace/libpman/src/stats.c b/userspace/libpman/src/stats.c index 9d4bd16001..2355511840 100644 --- a/userspace/libpman/src/stats.c +++ b/userspace/libpman/src/stats.c @@ -21,8 +21,7 @@ limitations under the License. #include #include -typedef enum modern_bpf_kernel_counters_stats -{ +typedef enum modern_bpf_kernel_counters_stats { MODERN_BPF_N_EVTS = 0, MODERN_BPF_N_DROPS_BUFFER_TOTAL, MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER, @@ -44,8 +43,7 @@ typedef enum modern_bpf_kernel_counters_stats MODERN_BPF_MAX_KERNEL_COUNTERS_STATS } modern_bpf_kernel_counters_stats; -typedef enum modern_bpf_libbpf_stats -{ +typedef enum modern_bpf_libbpf_stats { RUN_CNT = 0, RUN_TIME_NS, AVG_TIME_NS, @@ -53,46 +51,44 @@ typedef enum modern_bpf_libbpf_stats } modern_bpf_libbpf_stats; const char *const modern_bpf_kernel_counters_stats_names[] = { - [MODERN_BPF_N_EVTS] = N_EVENTS_PREFIX, - [MODERN_BPF_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total", - [MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER] = "n_drops_buffer_clone_fork_enter", - [MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT] = "n_drops_buffer_clone_fork_exit", - [MODERN_BPF_N_DROPS_BUFFER_EXECVE_ENTER] = "n_drops_buffer_execve_enter", - [MODERN_BPF_N_DROPS_BUFFER_EXECVE_EXIT] = "n_drops_buffer_execve_exit", - [MODERN_BPF_N_DROPS_BUFFER_CONNECT_ENTER] = "n_drops_buffer_connect_enter", - [MODERN_BPF_N_DROPS_BUFFER_CONNECT_EXIT] = "n_drops_buffer_connect_exit", - [MODERN_BPF_N_DROPS_BUFFER_OPEN_ENTER] = "n_drops_buffer_open_enter", - [MODERN_BPF_N_DROPS_BUFFER_OPEN_EXIT] = "n_drops_buffer_open_exit", - [MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_ENTER] = "n_drops_buffer_dir_file_enter", - [MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_EXIT] = "n_drops_buffer_dir_file_exit", - [MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER] = "n_drops_buffer_other_interest_enter", - [MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT] = "n_drops_buffer_other_interest_exit", - [MODERN_BPF_N_DROPS_BUFFER_CLOSE_EXIT] = "n_drops_buffer_close_exit", - [MODERN_BPF_N_DROPS_BUFFER_PROC_EXIT] = "n_drops_buffer_proc_exit", - [MODERN_BPF_N_DROPS_SCRATCH_MAP] = "n_drops_scratch_map", - [MODERN_BPF_N_DROPS] = "n_drops", + [MODERN_BPF_N_EVTS] = N_EVENTS_PREFIX, + [MODERN_BPF_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total", + [MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER] = "n_drops_buffer_clone_fork_enter", + [MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT] = "n_drops_buffer_clone_fork_exit", + [MODERN_BPF_N_DROPS_BUFFER_EXECVE_ENTER] = "n_drops_buffer_execve_enter", + [MODERN_BPF_N_DROPS_BUFFER_EXECVE_EXIT] = "n_drops_buffer_execve_exit", + [MODERN_BPF_N_DROPS_BUFFER_CONNECT_ENTER] = "n_drops_buffer_connect_enter", + [MODERN_BPF_N_DROPS_BUFFER_CONNECT_EXIT] = "n_drops_buffer_connect_exit", + [MODERN_BPF_N_DROPS_BUFFER_OPEN_ENTER] = "n_drops_buffer_open_enter", + [MODERN_BPF_N_DROPS_BUFFER_OPEN_EXIT] = "n_drops_buffer_open_exit", + [MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_ENTER] = "n_drops_buffer_dir_file_enter", + [MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_EXIT] = "n_drops_buffer_dir_file_exit", + [MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER] = "n_drops_buffer_other_interest_enter", + [MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT] = "n_drops_buffer_other_interest_exit", + [MODERN_BPF_N_DROPS_BUFFER_CLOSE_EXIT] = "n_drops_buffer_close_exit", + [MODERN_BPF_N_DROPS_BUFFER_PROC_EXIT] = "n_drops_buffer_proc_exit", + [MODERN_BPF_N_DROPS_SCRATCH_MAP] = "n_drops_scratch_map", + [MODERN_BPF_N_DROPS] = "n_drops", }; const char *const modern_bpf_libbpf_stats_names[] = { - [RUN_CNT] = ".run_cnt", ///< `bpf_prog_info` run_cnt. - [RUN_TIME_NS] = ".run_time_ns", ///<`bpf_prog_info` run_time_ns. - [AVG_TIME_NS] = ".avg_time_ns", ///< Average time spent in bpg program, calculation: run_time_ns / run_cnt. + [RUN_CNT] = ".run_cnt", ///< `bpf_prog_info` run_cnt. + [RUN_TIME_NS] = ".run_time_ns", ///<`bpf_prog_info` run_time_ns. + [AVG_TIME_NS] = ".avg_time_ns", ///< Average time spent in bpg program, calculation: + ///< run_time_ns / run_cnt. }; -int pman_get_scap_stats(struct scap_stats *stats) -{ +int pman_get_scap_stats(struct scap_stats *stats) { char error_message[MAX_ERROR_MESSAGE_LEN]; struct counter_map cnt_map; - if(!stats) - { + if(!stats) { pman_print_error("pointer to scap_stats is empty"); return errno; } int counter_maps_fd = bpf_map__fd(g_state.skel->maps.counter_maps); - if(counter_maps_fd <= 0) - { + if(counter_maps_fd <= 0) { pman_print_error("unable to get counter maps"); return errno; } @@ -106,11 +102,12 @@ int pman_get_scap_stats(struct scap_stats *stats) /* We always take statistics from all the CPUs, even if some of them are not online. * If the CPU is not online the counter map will be empty. */ - for(int index = 0; index < g_state.n_possible_cpus; index++) - { - if(bpf_map_lookup_elem(counter_maps_fd, &index, &cnt_map) < 0) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "unable to get the counter map for CPU %d", index); + for(int index = 0; index < g_state.n_possible_cpus; index++) { + if(bpf_map_lookup_elem(counter_maps_fd, &index, &cnt_map) < 0) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "unable to get the counter map for CPU %d", + index); pman_print_error((const char *)error_message); goto clean_print_stats; } @@ -140,8 +137,7 @@ int pman_get_scap_stats(struct scap_stats *stats) return errno; } -static void set_u64_monotonic_kernel_counter(uint32_t pos, uint64_t val, uint32_t metric_flag) -{ +static void set_u64_monotonic_kernel_counter(uint32_t pos, uint64_t val, uint32_t metric_flag) { g_state.stats[pos].type = METRIC_VALUE_TYPE_U64; g_state.stats[pos].flags = metric_flag; g_state.stats[pos].unit = METRIC_VALUE_UNIT_COUNT; @@ -149,36 +145,31 @@ static void set_u64_monotonic_kernel_counter(uint32_t pos, uint64_t val, uint32_ g_state.stats[pos].value.u64 = val; } -struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t *rc) -{ +struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t *rc) { *rc = SCAP_FAILURE; *nstats = 0; // If it is the first time we call this function we populate the stats - if(g_state.stats == NULL) - { + if(g_state.stats == NULL) { int nprogs_attached = 0; - for(int j = 0; j < MODERN_BPF_PROG_ATTACHED_MAX; j++) - { - if(g_state.attached_progs_fds[j] != -1) - { + for(int j = 0; j < MODERN_BPF_PROG_ATTACHED_MAX; j++) { + if(g_state.attached_progs_fds[j] != -1) { nprogs_attached++; } } uint32_t per_cpu_stats = 0; - if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) - { + if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) { // At the moment for each available CPU we want: // - the number of events. // - the number of drops. - per_cpu_stats = g_state.n_possible_cpus* 2; + per_cpu_stats = g_state.n_possible_cpus * 2; } - - g_state.nstats = MODERN_BPF_MAX_KERNEL_COUNTERS_STATS + per_cpu_stats + (nprogs_attached * MODERN_BPF_MAX_LIBBPF_STATS); + + g_state.nstats = MODERN_BPF_MAX_KERNEL_COUNTERS_STATS + per_cpu_stats + + (nprogs_attached * MODERN_BPF_MAX_LIBBPF_STATS); g_state.stats = (metrics_v2 *)calloc(g_state.nstats, sizeof(metrics_v2)); - if(!g_state.stats) - { + if(!g_state.stats) { g_state.nstats = 0; pman_print_error("unable to allocate memory for 'metrics_v2' array"); return NULL; @@ -189,20 +180,19 @@ struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t int offset = 0; /* KERNEL COUNTER STATS */ - if(flags & METRICS_V2_KERNEL_COUNTERS) - { + if(flags & METRICS_V2_KERNEL_COUNTERS) { char error_message[MAX_ERROR_MESSAGE_LEN]; int counter_maps_fd = bpf_map__fd(g_state.skel->maps.counter_maps); - if(counter_maps_fd <= 0) - { + if(counter_maps_fd <= 0) { pman_print_error("unable to get 'counter_maps' fd during kernel stats processing"); return NULL; } - for(uint32_t stat = 0; stat < MODERN_BPF_MAX_KERNEL_COUNTERS_STATS; stat++) - { + for(uint32_t stat = 0; stat < MODERN_BPF_MAX_KERNEL_COUNTERS_STATS; stat++) { set_u64_monotonic_kernel_counter(stat, 0, METRICS_V2_KERNEL_COUNTERS); - strlcpy(g_state.stats[stat].name, (char*)modern_bpf_kernel_counters_stats_names[stat], METRIC_NAME_MAX); + strlcpy(g_state.stats[stat].name, + (char *)modern_bpf_kernel_counters_stats_names[stat], + METRIC_NAME_MAX); } /* We always take statistics from all the CPUs, even if some of them are not online. @@ -210,44 +200,71 @@ struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t */ struct counter_map cnt_map = {}; uint32_t pos = MODERN_BPF_MAX_KERNEL_COUNTERS_STATS; - for(uint32_t index = 0; index < g_state.n_possible_cpus; index++) - { - if(bpf_map_lookup_elem(counter_maps_fd, &index, &cnt_map) < 0) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "unable to get the counter map for CPU %d", index); + for(uint32_t index = 0; index < g_state.n_possible_cpus; index++) { + if(bpf_map_lookup_elem(counter_maps_fd, &index, &cnt_map) < 0) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "unable to get the counter map for CPU %d", + index); pman_print_error((const char *)error_message); close(counter_maps_fd); return NULL; } g_state.stats[MODERN_BPF_N_EVTS].value.u64 += cnt_map.n_evts; g_state.stats[MODERN_BPF_N_DROPS_BUFFER_TOTAL].value.u64 += cnt_map.n_drops_buffer; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER].value.u64 += cnt_map.n_drops_buffer_clone_fork_enter; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT].value.u64 += cnt_map.n_drops_buffer_clone_fork_exit; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_EXECVE_ENTER].value.u64 += cnt_map.n_drops_buffer_execve_enter; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_EXECVE_EXIT].value.u64 += cnt_map.n_drops_buffer_execve_exit; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CONNECT_ENTER].value.u64 += cnt_map.n_drops_buffer_connect_enter; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CONNECT_EXIT].value.u64 += cnt_map.n_drops_buffer_connect_exit; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OPEN_ENTER].value.u64 += cnt_map.n_drops_buffer_open_enter; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OPEN_EXIT].value.u64 += cnt_map.n_drops_buffer_open_exit; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_ENTER].value.u64 += cnt_map.n_drops_buffer_dir_file_enter; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_EXIT].value.u64 += cnt_map.n_drops_buffer_dir_file_exit; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER].value.u64 += cnt_map.n_drops_buffer_other_interest_enter; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT].value.u64 += cnt_map.n_drops_buffer_other_interest_exit; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CLOSE_EXIT].value.u64 += cnt_map.n_drops_buffer_close_exit; - g_state.stats[MODERN_BPF_N_DROPS_BUFFER_PROC_EXIT].value.u64 += cnt_map.n_drops_buffer_proc_exit; - g_state.stats[MODERN_BPF_N_DROPS_SCRATCH_MAP].value.u64 += cnt_map.n_drops_max_event_size; - g_state.stats[MODERN_BPF_N_DROPS].value.u64 += (cnt_map.n_drops_buffer + cnt_map.n_drops_max_event_size); - - if((flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) - { + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER].value.u64 += + cnt_map.n_drops_buffer_clone_fork_enter; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT].value.u64 += + cnt_map.n_drops_buffer_clone_fork_exit; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_EXECVE_ENTER].value.u64 += + cnt_map.n_drops_buffer_execve_enter; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_EXECVE_EXIT].value.u64 += + cnt_map.n_drops_buffer_execve_exit; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CONNECT_ENTER].value.u64 += + cnt_map.n_drops_buffer_connect_enter; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CONNECT_EXIT].value.u64 += + cnt_map.n_drops_buffer_connect_exit; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OPEN_ENTER].value.u64 += + cnt_map.n_drops_buffer_open_enter; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OPEN_EXIT].value.u64 += + cnt_map.n_drops_buffer_open_exit; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_ENTER].value.u64 += + cnt_map.n_drops_buffer_dir_file_enter; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_DIR_FILE_EXIT].value.u64 += + cnt_map.n_drops_buffer_dir_file_exit; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER].value.u64 += + cnt_map.n_drops_buffer_other_interest_enter; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT].value.u64 += + cnt_map.n_drops_buffer_other_interest_exit; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_CLOSE_EXIT].value.u64 += + cnt_map.n_drops_buffer_close_exit; + g_state.stats[MODERN_BPF_N_DROPS_BUFFER_PROC_EXIT].value.u64 += + cnt_map.n_drops_buffer_proc_exit; + g_state.stats[MODERN_BPF_N_DROPS_SCRATCH_MAP].value.u64 += + cnt_map.n_drops_max_event_size; + g_state.stats[MODERN_BPF_N_DROPS].value.u64 += + (cnt_map.n_drops_buffer + cnt_map.n_drops_max_event_size); + + if((flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) { // We set the num events for that CPU. - set_u64_monotonic_kernel_counter(pos, cnt_map.n_evts, METRICS_V2_KERNEL_COUNTERS_PER_CPU); - snprintf(g_state.stats[pos].name, METRIC_NAME_MAX, N_EVENTS_PER_CPU_PREFIX"%d", index); + set_u64_monotonic_kernel_counter(pos, + cnt_map.n_evts, + METRICS_V2_KERNEL_COUNTERS_PER_CPU); + snprintf(g_state.stats[pos].name, + METRIC_NAME_MAX, + N_EVENTS_PER_CPU_PREFIX "%d", + index); pos++; // We set the drops for that CPU. - set_u64_monotonic_kernel_counter(pos, cnt_map.n_drops_buffer + cnt_map.n_drops_max_event_size, METRICS_V2_KERNEL_COUNTERS_PER_CPU); - snprintf(g_state.stats[pos].name, METRIC_NAME_MAX, N_DROPS_PER_CPU_PREFIX"%d", index); + set_u64_monotonic_kernel_counter( + pos, + cnt_map.n_drops_buffer + cnt_map.n_drops_max_event_size, + METRICS_V2_KERNEL_COUNTERS_PER_CPU); + snprintf(g_state.stats[pos].name, + METRIC_NAME_MAX, + N_DROPS_PER_CPU_PREFIX "%d", + index); pos++; } } @@ -256,35 +273,29 @@ struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t /* LIBBPF STATS */ - /* At the time of writing (Apr 2, 2023) libbpf stats are only available on a per program granularity. - * This means we cannot measure the statistics for each filler/tail-call individually. - * Hopefully someone upstreams such capabilities to libbpf one day :) - * Meanwhile, we can simulate perf comparisons between future LSM hooks and sys enter and exit tracepoints + /* At the time of writing (Apr 2, 2023) libbpf stats are only available on a per program + * granularity. This means we cannot measure the statistics for each filler/tail-call + * individually. Hopefully someone upstreams such capabilities to libbpf one day :) Meanwhile, + * we can simulate perf comparisons between future LSM hooks and sys enter and exit tracepoints * via leveraging syscall selection mechanisms `handle->curr_sc_set`. */ - if((flags & METRICS_V2_LIBBPF_STATS)) - { + if((flags & METRICS_V2_LIBBPF_STATS)) { int fd = 0; - for(int bpf_prog = 0; bpf_prog < MODERN_BPF_PROG_ATTACHED_MAX; bpf_prog++) - { + for(int bpf_prog = 0; bpf_prog < MODERN_BPF_PROG_ATTACHED_MAX; bpf_prog++) { fd = g_state.attached_progs_fds[bpf_prog]; - if(fd < 0) - { + if(fd < 0) { /* landing here means prog was not attached */ continue; } struct bpf_prog_info info = {}; __u32 len = sizeof(info); - if((bpf_obj_get_info_by_fd(fd, &info, &len))) - { + if((bpf_obj_get_info_by_fd(fd, &info, &len))) { /* no info for that prog, it seems like a bug but we can go on */ continue; } - for(int stat = 0; stat < MODERN_BPF_MAX_LIBBPF_STATS; stat++) - { - if(offset >= g_state.nstats) - { + for(int stat = 0; stat < MODERN_BPF_MAX_LIBBPF_STATS; stat++) { + if(offset >= g_state.nstats) { /* This should never happen, we are doing something wrong */ pman_print_error("no enough space for all the stats"); return NULL; @@ -292,9 +303,10 @@ struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t g_state.stats[offset].type = METRIC_VALUE_TYPE_U64; g_state.stats[offset].flags = METRICS_V2_LIBBPF_STATS; strlcpy(g_state.stats[offset].name, info.name, METRIC_NAME_MAX); - strlcat(g_state.stats[offset].name, modern_bpf_libbpf_stats_names[stat], sizeof(g_state.stats[offset].name)); - switch(stat) - { + strlcat(g_state.stats[offset].name, + modern_bpf_libbpf_stats_names[stat], + sizeof(g_state.stats[offset].name)); + switch(stat) { case RUN_CNT: g_state.stats[offset].unit = METRIC_VALUE_UNIT_COUNT; g_state.stats[offset].metric_type = METRIC_VALUE_METRIC_TYPE_MONOTONIC; @@ -307,10 +319,10 @@ struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t break; case AVG_TIME_NS: g_state.stats[offset].unit = METRIC_VALUE_UNIT_TIME_NS; - g_state.stats[offset].metric_type = METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT; + g_state.stats[offset].metric_type = + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT; g_state.stats[offset].value.u64 = 0; - if(info.run_cnt > 0) - { + if(info.run_cnt > 0) { g_state.stats[offset].value.u64 = info.run_time_ns / info.run_cnt; } break; @@ -329,14 +341,12 @@ struct metrics_v2 *pman_get_metrics_v2(uint32_t flags, uint32_t *nstats, int32_t return g_state.stats; } -int pman_get_n_tracepoint_hit(long *n_events_per_cpu) -{ +int pman_get_n_tracepoint_hit(long *n_events_per_cpu) { char error_message[MAX_ERROR_MESSAGE_LEN]; struct counter_map cnt_map; int counter_maps_fd = bpf_map__fd(g_state.skel->maps.counter_maps); - if(counter_maps_fd <= 0) - { + if(counter_maps_fd <= 0) { pman_print_error("unable to get counter maps"); return errno; } @@ -344,11 +354,12 @@ int pman_get_n_tracepoint_hit(long *n_events_per_cpu) /* We always take statistics from all the CPUs, even if some of them are not online. * If the CPU is not online the counter map will be empty. */ - for(int index = 0; index < g_state.n_possible_cpus; index++) - { - if(bpf_map_lookup_elem(counter_maps_fd, &index, &cnt_map) < 0) - { - snprintf(error_message, MAX_ERROR_MESSAGE_LEN, "unbale to get the counter map for CPU %d", index); + for(int index = 0; index < g_state.n_possible_cpus; index++) { + if(bpf_map_lookup_elem(counter_maps_fd, &index, &cnt_map) < 0) { + snprintf(error_message, + MAX_ERROR_MESSAGE_LEN, + "unbale to get the counter map for CPU %d", + index); pman_print_error((const char *)error_message); goto clean_print_stats; } diff --git a/userspace/libscap/CMakeLists.txt b/userspace/libscap/CMakeLists.txt index ca0e41a135..a1d8b67e5f 100644 --- a/userspace/libscap/CMakeLists.txt +++ b/userspace/libscap/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # include(engine_config) @@ -51,59 +49,49 @@ if(NOT DEFINED SCAP_HOSTNAME_ENV_VAR) endif() add_definitions(-DSCAP_HOSTNAME_ENV_VAR="${SCAP_HOSTNAME_ENV_VAR}") -if (DEFINED SCAP_BPF_PROGS_TAIL_CALLED_MAX) +if(DEFINED SCAP_BPF_PROGS_TAIL_CALLED_MAX) add_definitions(-DBPF_PROGS_TAIL_CALLED_MAX=${SCAP_BPF_PROGS_TAIL_CALLED_MAX}) endif() - -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scap_strl_config.h.in ${CMAKE_CURRENT_BINARY_DIR}/scap_strl_config.h) -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scap_config.h.in ${CMAKE_CURRENT_BINARY_DIR}/scap_config.h) - +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/scap_strl_config.h.in + ${CMAKE_CURRENT_BINARY_DIR}/scap_strl_config.h +) +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/scap_config.h.in ${CMAKE_CURRENT_BINARY_DIR}/scap_config.h +) add_library(scap_error STATIC strerror.c) target_include_directories(scap_error PUBLIC $) -add_library(scap - scap.c - scap_api_version.c - scap_savefile.c - scap_platform_api.c -) +add_library(scap scap.c scap_api_version.c scap_savefile.c scap_platform_api.c) -target_include_directories(scap -PUBLIC - $ - $ - $ +target_include_directories( + scap + PUBLIC $ + $ + $ ) set_scap_target_properties(scap) -add_library(scap_platform_util STATIC - scap_platform.c - scap_fds.c - scap_iflist.c - scap_proc_util.c - scap_procs.c - scap_userlist.c +add_library( + scap_platform_util STATIC scap_platform.c scap_fds.c scap_iflist.c scap_proc_util.c + scap_procs.c scap_userlist.c ) add_dependencies(scap_platform_util uthash) -target_include_directories(scap_platform_util -PUBLIC - $ - $ - $ +target_include_directories( + scap_platform_util + PUBLIC $ $ + $ ) -target_link_libraries(scap -PRIVATE - scap_error - "${ZLIB_LIB}" -) +target_link_libraries(scap PRIVATE scap_error "${ZLIB_LIB}") -add_library(scap_event_schema STATIC +add_library( + scap_event_schema STATIC scap_event.c ppm_sc_names.c ${LIBS_DIR}/driver/dynamic_params_table.c @@ -116,11 +104,10 @@ add_library(scap_event_schema STATIC add_dependencies(scap_event_schema uthash) -target_include_directories(scap_event_schema -PUBLIC - $ - $ - $ +target_include_directories( + scap_event_schema + PUBLIC $ $ + $ ) target_link_libraries(scap PUBLIC scap_event_schema) @@ -132,35 +119,28 @@ if(CMAKE_SYSTEM_NAME MATCHES "Linux") add_subdirectory(linux) target_link_libraries(scap PUBLIC scap_platform) - - add_library(driver_event_schema STATIC - ${LIBS_DIR}/driver/fillers_table.c) + add_library(driver_event_schema STATIC ${LIBS_DIR}/driver/fillers_table.c) target_link_libraries(scap_event_schema driver_event_schema) - - add_library(scap_engine_util STATIC - scap_engine_util.c - ringbuffer/devset.c - ringbuffer/ringbuffer.c - ringbuffer/ringbuffer_dump.c + add_library( + scap_engine_util STATIC scap_engine_util.c ringbuffer/devset.c ringbuffer/ringbuffer.c + ringbuffer/ringbuffer_dump.c ) add_dependencies(scap_engine_util uthash) - target_include_directories(scap_engine_util - PUBLIC - $ - $ - $ + target_include_directories( + scap_engine_util + PUBLIC $ $ + $ ) target_link_libraries(scap PRIVATE scap_engine_util) endif() - -################## LISCAP ENGINES ################## +# ################# LISCAP ENGINES ################## add_subdirectory(engine/noop) -# don't link the noop engine to libscap directly, -# it's a helper library for other engines (it's completely useless on its own) +# don't link the noop engine to libscap directly, it's a helper library for other engines (it's +# completely useless on its own) if(HAS_ENGINE_NODRIVER) add_subdirectory(engine/nodriver) @@ -186,54 +166,39 @@ endif() if(HAS_ENGINE_KMOD) add_subdirectory(engine/kmod) target_link_libraries(scap PUBLIC scap_engine_kmod) - target_include_directories(scap_engine_kmod - PRIVATE - ${PROJECT_BINARY_DIR}/driver/src - ) + target_include_directories(scap_engine_kmod PRIVATE ${PROJECT_BINARY_DIR}/driver/src) endif() if(HAS_ENGINE_BPF) include(libelf) add_subdirectory(engine/bpf) target_link_libraries(scap PUBLIC scap_engine_bpf) - target_include_directories(scap_engine_bpf - PRIVATE - ${PROJECT_BINARY_DIR}/driver/src - ) + target_include_directories(scap_engine_bpf PRIVATE ${PROJECT_BINARY_DIR}/driver/src) endif() if(HAS_ENGINE_MODERN_BPF) include(libelf) add_subdirectory(engine/modern_bpf) target_link_libraries(scap PUBLIC scap_engine_modern_bpf) - target_include_directories(scap_engine_modern_bpf - PRIVATE - ${PROJECT_BINARY_DIR}/driver/src - ) + target_include_directories(scap_engine_modern_bpf PRIVATE ${PROJECT_BINARY_DIR}/driver/src) endif() if(HAS_ENGINE_GVISOR) add_subdirectory(engine/gvisor) - # The static and shared build differs here because a shared scap_engine_gvisor - # will result in circular dependencies. + # The static and shared build differs here because a shared scap_engine_gvisor will result in + # circular dependencies. if(BUILD_SHARED_LIBS) - # We can move this to the gvisor CMakeFile when we use - # CMake 3.13 or later. + # We can move this to the gvisor CMakeFile when we use CMake 3.13 or later. # https://cmake.org/cmake/help/latest/policy/CMP0079.html - target_link_libraries(scap - PRIVATE - ${CMAKE_THREAD_LIBS_INIT} - ${PROTOBUF_LIB} - ${JSONCPP_LIB} - ) + target_link_libraries(scap PRIVATE ${CMAKE_THREAD_LIBS_INIT} ${PROTOBUF_LIB} ${JSONCPP_LIB}) else() target_link_libraries(scap PRIVATE scap_engine_gvisor) endif() endif() -#################################################### +# ################################################################################################## -if (BUILD_LIBSCAP_EXAMPLES) +if(BUILD_LIBSCAP_EXAMPLES) add_subdirectory(examples/01-open) add_subdirectory(examples/02-validatebuffer) endif() diff --git a/userspace/libscap/clock_helpers.h b/userspace/libscap/clock_helpers.h index 1cd34dc16f..f5d4964192 100644 --- a/userspace/libscap/clock_helpers.h +++ b/userspace/libscap/clock_helpers.h @@ -38,22 +38,19 @@ limitations under the License. * - non-monotonic behavior of CLOCK_MONOTONIC * - time values that cannot be represented in uint64_t number of msec */ -static __always_inline uint64_t scap_get_monotonic_ts_ms(uint64_t* context) -{ +static __always_inline uint64_t scap_get_monotonic_ts_ms(uint64_t* context) { // Record previously reported time; will be 0 for first call. uint64_t prev_time = ((*context) & SCAP_GET_CUR_TS_MS_CONTEXT_PREV_VALUE_MASK); // If context indicates error already detected, just return the // last reported time - if ((*context) & SCAP_GET_CUR_TS_MS_CONTEXT_ERROR_FLAG) - { + if((*context) & SCAP_GET_CUR_TS_MS_CONTEXT_ERROR_FLAG) { return prev_time; } // Fetch current monotonic time from kernel struct timespec ts; - if (clock_gettime(CLOCK_MONOTONIC, &ts)) - { + if(clock_gettime(CLOCK_MONOTONIC, &ts)) { // System call failed. // Set error flag *context |= SCAP_GET_CUR_TS_MS_CONTEXT_ERROR_FLAG; @@ -66,9 +63,7 @@ static __always_inline uint64_t scap_get_monotonic_ts_ms(uint64_t* context) uint64_t new_time = S_TO_MS(ts.tv_sec) + NS_TO_MS(ts.tv_nsec); // Check for overflow or non-monotonic behavior - if ((new_time & SCAP_GET_CUR_TS_MS_CONTEXT_ERROR_FLAG) || - (new_time < prev_time)) - { + if((new_time & SCAP_GET_CUR_TS_MS_CONTEXT_ERROR_FLAG) || (new_time < prev_time)) { // System call failed. // Set error flag *context |= SCAP_GET_CUR_TS_MS_CONTEXT_ERROR_FLAG; diff --git a/userspace/libscap/compat/bpf.h b/userspace/libscap/compat/bpf.h index 2b46a050b4..460c3495b3 100644 --- a/userspace/libscap/compat/bpf.h +++ b/userspace/libscap/compat/bpf.h @@ -14,34 +14,34 @@ /* Extended instruction set based on top of classic BPF */ /* instruction classes */ -#define BPF_JMP32 0x06 /* jmp mode in word width */ -#define BPF_ALU64 0x07 /* alu mode in double word width */ +#define BPF_JMP32 0x06 /* jmp mode in word width */ +#define BPF_ALU64 0x07 /* alu mode in double word width */ /* ld/ldx fields */ -#define BPF_DW 0x18 /* double word (64-bit) */ -#define BPF_XADD 0xc0 /* exclusive add */ +#define BPF_DW 0x18 /* double word (64-bit) */ +#define BPF_XADD 0xc0 /* exclusive add */ /* alu/jmp fields */ -#define BPF_MOV 0xb0 /* mov reg to reg */ -#define BPF_ARSH 0xc0 /* sign extending arithmetic shift right */ +#define BPF_MOV 0xb0 /* mov reg to reg */ +#define BPF_ARSH 0xc0 /* sign extending arithmetic shift right */ /* change endianness of a register */ -#define BPF_END 0xd0 /* flags for endianness conversion: */ -#define BPF_TO_LE 0x00 /* convert to little-endian */ -#define BPF_TO_BE 0x08 /* convert to big-endian */ -#define BPF_FROM_LE BPF_TO_LE -#define BPF_FROM_BE BPF_TO_BE +#define BPF_END 0xd0 /* flags for endianness conversion: */ +#define BPF_TO_LE 0x00 /* convert to little-endian */ +#define BPF_TO_BE 0x08 /* convert to big-endian */ +#define BPF_FROM_LE BPF_TO_LE +#define BPF_FROM_BE BPF_TO_BE /* jmp encodings */ -#define BPF_JNE 0x50 /* jump != */ -#define BPF_JLT 0xa0 /* LT is unsigned, '<' */ -#define BPF_JLE 0xb0 /* LE is unsigned, '<=' */ -#define BPF_JSGT 0x60 /* SGT is signed '>', GT in x86 */ -#define BPF_JSGE 0x70 /* SGE is signed '>=', GE in x86 */ -#define BPF_JSLT 0xc0 /* SLT is signed, '<' */ -#define BPF_JSLE 0xd0 /* SLE is signed, '<=' */ -#define BPF_CALL 0x80 /* function call */ -#define BPF_EXIT 0x90 /* function return */ +#define BPF_JNE 0x50 /* jump != */ +#define BPF_JLT 0xa0 /* LT is unsigned, '<' */ +#define BPF_JLE 0xb0 /* LE is unsigned, '<=' */ +#define BPF_JSGT 0x60 /* SGT is signed '>', GT in x86 */ +#define BPF_JSGE 0x70 /* SGE is signed '>=', GE in x86 */ +#define BPF_JSLT 0xc0 /* SLT is signed, '<' */ +#define BPF_JSLE 0xd0 /* SLE is signed, '<=' */ +#define BPF_CALL 0x80 /* function call */ +#define BPF_EXIT 0x90 /* function return */ /* Register numbers */ enum { @@ -60,25 +60,25 @@ enum { }; /* BPF has 10 general purpose 64-bit registers and stack frame. */ -#define MAX_BPF_REG __MAX_BPF_REG +#define MAX_BPF_REG __MAX_BPF_REG struct bpf_insn { - __u8 code; /* opcode */ - __u8 dst_reg:4; /* dest register */ - __u8 src_reg:4; /* source register */ - __s16 off; /* signed offset */ - __s32 imm; /* signed immediate constant */ + __u8 code; /* opcode */ + __u8 dst_reg : 4; /* dest register */ + __u8 src_reg : 4; /* source register */ + __s16 off; /* signed offset */ + __s32 imm; /* signed immediate constant */ }; /* Key of an a BPF_MAP_TYPE_LPM_TRIE entry */ struct bpf_lpm_trie_key { - __u32 prefixlen; /* up to 32 for AF_INET, 128 for AF_INET6 */ - __u8 data[]; /* Arbitrary size */ + __u32 prefixlen; /* up to 32 for AF_INET, 128 for AF_INET6 */ + __u8 data[]; /* Arbitrary size */ }; struct bpf_cgroup_storage_key { - __u64 cgroup_inode_id; /* cgroup inode id */ - __u32 attach_type; /* program attach type */ + __u64 cgroup_inode_id; /* cgroup inode id */ + __u32 attach_type; /* program attach type */ }; /* BPF syscall commands, see bpf(2) man-page for details. */ @@ -264,16 +264,16 @@ enum bpf_attach_type { * All eligible programs are executed regardless of return code from * earlier programs. */ -#define BPF_F_ALLOW_OVERRIDE (1U << 0) -#define BPF_F_ALLOW_MULTI (1U << 1) -#define BPF_F_REPLACE (1U << 2) +#define BPF_F_ALLOW_OVERRIDE (1U << 0) +#define BPF_F_ALLOW_MULTI (1U << 1) +#define BPF_F_REPLACE (1U << 2) /* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the * verifier will perform strict alignment checking as if the kernel * has been built with CONFIG_EFFICIENT_UNALIGNED_ACCESS not set, * and NET_IP_ALIGN defined to 2. */ -#define BPF_F_STRICT_ALIGNMENT (1U << 0) +#define BPF_F_STRICT_ALIGNMENT (1U << 0) /* If BPF_F_ANY_ALIGNMENT is used in BPF_PROF_LOAD command, the * verifier will allow any alignment whatsoever. On platforms @@ -287,7 +287,7 @@ enum bpf_attach_type { * of an unaligned access the alignment check would trigger before * the one we are interested in. */ -#define BPF_F_ANY_ALIGNMENT (1U << 1) +#define BPF_F_ANY_ALIGNMENT (1U << 1) /* BPF_F_TEST_RND_HI32 is used in BPF_PROG_LOAD command for testing purpose. * Verifier does sub-register def/use analysis and identifies instructions whose @@ -305,10 +305,10 @@ enum bpf_attach_type { * Then, if verifier is not doing correct analysis, such randomization will * regress tests to expose bugs. */ -#define BPF_F_TEST_RND_HI32 (1U << 2) +#define BPF_F_TEST_RND_HI32 (1U << 2) /* The verifier internal test flag. Behavior is undefined */ -#define BPF_F_TEST_STATE_FREQ (1U << 3) +#define BPF_F_TEST_STATE_FREQ (1U << 3) /* When BPF ldimm64's insn[0].src_reg != 0 then this can have * two extensions: @@ -321,54 +321,54 @@ enum bpf_attach_type { * ldimm64 rewrite: address of map address of map[0]+offset * verifier type: CONST_PTR_TO_MAP PTR_TO_MAP_VALUE */ -#define BPF_PSEUDO_MAP_FD 1 -#define BPF_PSEUDO_MAP_VALUE 2 +#define BPF_PSEUDO_MAP_FD 1 +#define BPF_PSEUDO_MAP_VALUE 2 /* when bpf_call->src_reg == BPF_PSEUDO_CALL, bpf_call->imm == pc-relative * offset to another bpf function */ -#define BPF_PSEUDO_CALL 1 +#define BPF_PSEUDO_CALL 1 /* flags for BPF_MAP_UPDATE_ELEM command */ enum { - BPF_ANY = 0, /* create new element or update existing */ - BPF_NOEXIST = 1, /* create new element if it didn't exist */ - BPF_EXIST = 2, /* update existing element */ - BPF_F_LOCK = 4, /* spin_lock-ed map_lookup/map_update */ + BPF_ANY = 0, /* create new element or update existing */ + BPF_NOEXIST = 1, /* create new element if it didn't exist */ + BPF_EXIST = 2, /* update existing element */ + BPF_F_LOCK = 4, /* spin_lock-ed map_lookup/map_update */ }; /* flags for BPF_MAP_CREATE command */ enum { - BPF_F_NO_PREALLOC = (1U << 0), + BPF_F_NO_PREALLOC = (1U << 0), /* Instead of having one common LRU list in the - * BPF_MAP_TYPE_LRU_[PERCPU_]HASH map, use a percpu LRU list - * which can scale and perform better. - * Note, the LRU nodes (including free nodes) cannot be moved - * across different LRU lists. + * BPF_MAP_TYPE_LRU_[PERCPU_]HASH map, use a percpu LRU list + * which can scale and perform better. + * Note, the LRU nodes (including free nodes) cannot be moved + * across different LRU lists. */ - BPF_F_NO_COMMON_LRU = (1U << 1), + BPF_F_NO_COMMON_LRU = (1U << 1), /* Specify numa node during map creation */ - BPF_F_NUMA_NODE = (1U << 2), + BPF_F_NUMA_NODE = (1U << 2), /* Flags for accessing BPF object from syscall side. */ - BPF_F_RDONLY = (1U << 3), - BPF_F_WRONLY = (1U << 4), + BPF_F_RDONLY = (1U << 3), + BPF_F_WRONLY = (1U << 4), /* Flag for stack_map, store build_id+offset instead of pointer */ - BPF_F_STACK_BUILD_ID = (1U << 5), + BPF_F_STACK_BUILD_ID = (1U << 5), /* Zero-initialize hash function seed. This should only be used for testing. */ - BPF_F_ZERO_SEED = (1U << 6), + BPF_F_ZERO_SEED = (1U << 6), /* Flags for accessing BPF object from program side. */ - BPF_F_RDONLY_PROG = (1U << 7), - BPF_F_WRONLY_PROG = (1U << 8), + BPF_F_RDONLY_PROG = (1U << 7), + BPF_F_WRONLY_PROG = (1U << 8), /* Clone map from listener for newly accepted socket */ - BPF_F_CLONE = (1U << 9), + BPF_F_CLONE = (1U << 9), /* Enable memory-mapping BPF map */ - BPF_F_MMAPABLE = (1U << 10), + BPF_F_MMAPABLE = (1U << 10), }; /* Flags for BPF_PROG_QUERY. */ @@ -377,7 +377,7 @@ enum { * programs that will be executed for events within a cgroup. * attach_flags with this flag are returned only for directly attached programs. */ -#define BPF_F_QUERY_EFFECTIVE (1U << 0) +#define BPF_F_QUERY_EFFECTIVE (1U << 0) enum bpf_stack_build_id_status { /* user space need an empty entry to identify end of a trace */ @@ -390,157 +390,157 @@ enum bpf_stack_build_id_status { #define BPF_BUILD_ID_SIZE 20 struct bpf_stack_build_id { - __s32 status; - unsigned char build_id[BPF_BUILD_ID_SIZE]; + __s32 status; + unsigned char build_id[BPF_BUILD_ID_SIZE]; union { - __u64 offset; - __u64 ip; + __u64 offset; + __u64 ip; }; }; #define BPF_OBJ_NAME_LEN 16U union bpf_attr { - struct { /* anonymous struct used by BPF_MAP_CREATE command */ - __u32 map_type; /* one of enum bpf_map_type */ - __u32 key_size; /* size of key in bytes */ - __u32 value_size; /* size of value in bytes */ - __u32 max_entries; /* max number of entries in a map */ - __u32 map_flags; /* BPF_MAP_CREATE related - * flags defined above. - */ - __u32 inner_map_fd; /* fd pointing to the inner map */ - __u32 numa_node; /* numa node (effective only if - * BPF_F_NUMA_NODE is set). - */ - char map_name[BPF_OBJ_NAME_LEN]; - __u32 map_ifindex; /* ifindex of netdev to create on */ - __u32 btf_fd; /* fd pointing to a BTF type data */ - __u32 btf_key_type_id; /* BTF type_id of the key */ - __u32 btf_value_type_id; /* BTF type_id of the value */ - __u32 btf_vmlinux_value_type_id;/* BTF type_id of a kernel- - * struct stored as the - * map value - */ + struct { /* anonymous struct used by BPF_MAP_CREATE command */ + __u32 map_type; /* one of enum bpf_map_type */ + __u32 key_size; /* size of key in bytes */ + __u32 value_size; /* size of value in bytes */ + __u32 max_entries; /* max number of entries in a map */ + __u32 map_flags; /* BPF_MAP_CREATE related + * flags defined above. + */ + __u32 inner_map_fd; /* fd pointing to the inner map */ + __u32 numa_node; /* numa node (effective only if + * BPF_F_NUMA_NODE is set). + */ + char map_name[BPF_OBJ_NAME_LEN]; + __u32 map_ifindex; /* ifindex of netdev to create on */ + __u32 btf_fd; /* fd pointing to a BTF type data */ + __u32 btf_key_type_id; /* BTF type_id of the key */ + __u32 btf_value_type_id; /* BTF type_id of the value */ + __u32 btf_vmlinux_value_type_id; /* BTF type_id of a kernel- + * struct stored as the + * map value + */ }; struct { /* anonymous struct used by BPF_MAP_*_ELEM commands */ - __u32 map_fd; - __aligned_u64 key; + __u32 map_fd; + __aligned_u64 key; union { __aligned_u64 value; __aligned_u64 next_key; }; - __u64 flags; + __u64 flags; }; - struct { /* struct used by BPF_MAP_*_BATCH commands */ - __aligned_u64 in_batch; /* start batch, - * NULL to start from beginning - */ - __aligned_u64 out_batch; /* output: next start batch */ - __aligned_u64 keys; - __aligned_u64 values; - __u32 count; /* input/output: - * input: # of key/value - * elements - * output: # of filled elements - */ - __u32 map_fd; - __u64 elem_flags; - __u64 flags; + struct { /* struct used by BPF_MAP_*_BATCH commands */ + __aligned_u64 in_batch; /* start batch, + * NULL to start from beginning + */ + __aligned_u64 out_batch; /* output: next start batch */ + __aligned_u64 keys; + __aligned_u64 values; + __u32 count; /* input/output: + * input: # of key/value + * elements + * output: # of filled elements + */ + __u32 map_fd; + __u64 elem_flags; + __u64 flags; } batch; - struct { /* anonymous struct used by BPF_PROG_LOAD command */ - __u32 prog_type; /* one of enum bpf_prog_type */ - __u32 insn_cnt; - __aligned_u64 insns; - __aligned_u64 license; - __u32 log_level; /* verbosity level of verifier */ - __u32 log_size; /* size of user buffer */ - __aligned_u64 log_buf; /* user supplied buffer */ - __u32 kern_version; /* not used */ - __u32 prog_flags; - char prog_name[BPF_OBJ_NAME_LEN]; - __u32 prog_ifindex; /* ifindex of netdev to prep for */ + struct { /* anonymous struct used by BPF_PROG_LOAD command */ + __u32 prog_type; /* one of enum bpf_prog_type */ + __u32 insn_cnt; + __aligned_u64 insns; + __aligned_u64 license; + __u32 log_level; /* verbosity level of verifier */ + __u32 log_size; /* size of user buffer */ + __aligned_u64 log_buf; /* user supplied buffer */ + __u32 kern_version; /* not used */ + __u32 prog_flags; + char prog_name[BPF_OBJ_NAME_LEN]; + __u32 prog_ifindex; /* ifindex of netdev to prep for */ /* For some prog types expected attach type must be known at * load time to verify attach type specific parts of prog * (context accesses, allowed helpers, etc). */ - __u32 expected_attach_type; - __u32 prog_btf_fd; /* fd pointing to BTF type data */ - __u32 func_info_rec_size; /* userspace bpf_func_info size */ - __aligned_u64 func_info; /* func info */ - __u32 func_info_cnt; /* number of bpf_func_info records */ - __u32 line_info_rec_size; /* userspace bpf_line_info size */ - __aligned_u64 line_info; /* line info */ - __u32 line_info_cnt; /* number of bpf_line_info records */ - __u32 attach_btf_id; /* in-kernel BTF type id to attach to */ - __u32 attach_prog_fd; /* 0 to attach to vmlinux */ + __u32 expected_attach_type; + __u32 prog_btf_fd; /* fd pointing to BTF type data */ + __u32 func_info_rec_size; /* userspace bpf_func_info size */ + __aligned_u64 func_info; /* func info */ + __u32 func_info_cnt; /* number of bpf_func_info records */ + __u32 line_info_rec_size; /* userspace bpf_line_info size */ + __aligned_u64 line_info; /* line info */ + __u32 line_info_cnt; /* number of bpf_line_info records */ + __u32 attach_btf_id; /* in-kernel BTF type id to attach to */ + __u32 attach_prog_fd; /* 0 to attach to vmlinux */ }; struct { /* anonymous struct used by BPF_OBJ_* commands */ - __aligned_u64 pathname; - __u32 bpf_fd; - __u32 file_flags; + __aligned_u64 pathname; + __u32 bpf_fd; + __u32 file_flags; }; - struct { /* anonymous struct used by BPF_PROG_ATTACH/DETACH commands */ - __u32 target_fd; /* container object to attach to */ - __u32 attach_bpf_fd; /* eBPF program to attach */ - __u32 attach_type; - __u32 attach_flags; - __u32 replace_bpf_fd; /* previously attached eBPF - * program to replace if - * BPF_F_REPLACE is used - */ + struct { /* anonymous struct used by BPF_PROG_ATTACH/DETACH commands */ + __u32 target_fd; /* container object to attach to */ + __u32 attach_bpf_fd; /* eBPF program to attach */ + __u32 attach_type; + __u32 attach_flags; + __u32 replace_bpf_fd; /* previously attached eBPF + * program to replace if + * BPF_F_REPLACE is used + */ }; struct { /* anonymous struct used by BPF_PROG_TEST_RUN command */ - __u32 prog_fd; - __u32 retval; - __u32 data_size_in; /* input: len of data_in */ - __u32 data_size_out; /* input/output: len of data_out - * returns ENOSPC if data_out - * is too small. - */ - __aligned_u64 data_in; - __aligned_u64 data_out; - __u32 repeat; - __u32 duration; - __u32 ctx_size_in; /* input: len of ctx_in */ - __u32 ctx_size_out; /* input/output: len of ctx_out - * returns ENOSPC if ctx_out - * is too small. - */ - __aligned_u64 ctx_in; - __aligned_u64 ctx_out; + __u32 prog_fd; + __u32 retval; + __u32 data_size_in; /* input: len of data_in */ + __u32 data_size_out; /* input/output: len of data_out + * returns ENOSPC if data_out + * is too small. + */ + __aligned_u64 data_in; + __aligned_u64 data_out; + __u32 repeat; + __u32 duration; + __u32 ctx_size_in; /* input: len of ctx_in */ + __u32 ctx_size_out; /* input/output: len of ctx_out + * returns ENOSPC if ctx_out + * is too small. + */ + __aligned_u64 ctx_in; + __aligned_u64 ctx_out; } test; struct { /* anonymous struct used by BPF_*_GET_*_ID */ union { - __u32 start_id; - __u32 prog_id; - __u32 map_id; - __u32 btf_id; + __u32 start_id; + __u32 prog_id; + __u32 map_id; + __u32 btf_id; }; - __u32 next_id; - __u32 open_flags; + __u32 next_id; + __u32 open_flags; }; struct { /* anonymous struct used by BPF_OBJ_GET_INFO_BY_FD */ - __u32 bpf_fd; - __u32 info_len; - __aligned_u64 info; + __u32 bpf_fd; + __u32 info_len; + __aligned_u64 info; } info; - struct { /* anonymous struct used by BPF_PROG_QUERY command */ - __u32 target_fd; /* container object to query */ - __u32 attach_type; - __u32 query_flags; - __u32 attach_flags; - __aligned_u64 prog_ids; - __u32 prog_cnt; + struct { /* anonymous struct used by BPF_PROG_QUERY command */ + __u32 target_fd; /* container object to query */ + __u32 attach_type; + __u32 query_flags; + __u32 attach_flags; + __aligned_u64 prog_ids; + __u32 prog_cnt; } query; struct { /* anonymous struct used by BPF_RAW_TRACEPOINT_OPEN command */ @@ -549,44 +549,44 @@ union bpf_attr { } raw_tracepoint; struct { /* anonymous struct for BPF_BTF_LOAD */ - __aligned_u64 btf; - __aligned_u64 btf_log_buf; - __u32 btf_size; - __u32 btf_log_size; - __u32 btf_log_level; + __aligned_u64 btf; + __aligned_u64 btf_log_buf; + __u32 btf_size; + __u32 btf_log_size; + __u32 btf_log_level; }; struct { - __u32 pid; /* input: pid */ - __u32 fd; /* input: fd */ - __u32 flags; /* input: flags */ - __u32 buf_len; /* input/output: buf len */ - __aligned_u64 buf; /* input/output: - * tp_name for tracepoint - * symbol for kprobe - * filename for uprobe - */ - __u32 prog_id; /* output: prod_id */ - __u32 fd_type; /* output: BPF_FD_TYPE_* */ - __u64 probe_offset; /* output: probe_offset */ - __u64 probe_addr; /* output: probe_addr */ + __u32 pid; /* input: pid */ + __u32 fd; /* input: fd */ + __u32 flags; /* input: flags */ + __u32 buf_len; /* input/output: buf len */ + __aligned_u64 buf; /* input/output: + * tp_name for tracepoint + * symbol for kprobe + * filename for uprobe + */ + __u32 prog_id; /* output: prod_id */ + __u32 fd_type; /* output: BPF_FD_TYPE_* */ + __u64 probe_offset; /* output: probe_offset */ + __u64 probe_addr; /* output: probe_addr */ } task_fd_query; - struct { /* struct used by BPF_LINK_CREATE command */ - __u32 prog_fd; /* eBPF program to attach */ - __u32 target_fd; /* object to attach to */ - __u32 attach_type; /* attach type */ - __u32 flags; /* extra flags */ + struct { /* struct used by BPF_LINK_CREATE command */ + __u32 prog_fd; /* eBPF program to attach */ + __u32 target_fd; /* object to attach to */ + __u32 attach_type; /* attach type */ + __u32 flags; /* extra flags */ } link_create; - struct { /* struct used by BPF_LINK_UPDATE command */ - __u32 link_fd; /* link fd */ + struct { /* struct used by BPF_LINK_UPDATE command */ + __u32 link_fd; /* link fd */ /* new program fd to update link with */ - __u32 new_prog_fd; - __u32 flags; /* extra flags */ + __u32 new_prog_fd; + __u32 flags; /* extra flags */ /* expected link's program fd; is specified only if * BPF_F_REPLACE flag is set in flags */ - __u32 old_prog_fd; + __u32 old_prog_fd; } link_update; } __attribute__((aligned(8))); @@ -737,10 +737,9 @@ union bpf_attr { * Return * The SMP id of the processor running the program. * - * int bpf_skb_store_bytes(struct sk_buff *skb, uint32_t offset, const void *from, uint32_t len, uint64_t flags) - * Description - * Store *len* bytes from address *from* into the packet - * associated to *skb*, at *offset*. *flags* are a combination of + * int bpf_skb_store_bytes(struct sk_buff *skb, uint32_t offset, const void *from, uint32_t len, + *uint64_t flags) Description Store *len* bytes from address *from* into the packet associated to + **skb*, at *offset*. *flags* are a combination of * **BPF_F_RECOMPUTE_CSUM** (automatically recompute the * checksum for the packet after storing the bytes) and * **BPF_F_INVALIDATE_HASH** (set *skb*\ **->hash**, *skb*\ @@ -754,14 +753,11 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_l3_csum_replace(struct sk_buff *skb, uint32_t offset, uint64_t from, uint64_t to, uint64_t size) - * Description - * Recompute the layer 3 (e.g. IP) checksum for the packet - * associated to *skb*. Computation is incremental, so the helper - * must know the former value of the header field that was - * modified (*from*), the new value of this field (*to*), and the - * number of bytes (2 or 4) for this field, stored in *size*. - * Alternatively, it is possible to store the difference between + * int bpf_l3_csum_replace(struct sk_buff *skb, uint32_t offset, uint64_t from, uint64_t to, + *uint64_t size) Description Recompute the layer 3 (e.g. IP) checksum for the packet associated to + **skb*. Computation is incremental, so the helper must know the former value of the header field + *that was modified (*from*), the new value of this field (*to*), and the number of bytes (2 or 4) + *for this field, stored in *size*. Alternatively, it is possible to store the difference between * the previous and the new values of the header field in *to*, by * setting *from* and *size* to 0. For both methods, *offset* * indicates the location of the IP checksum within the packet. @@ -779,22 +775,17 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_l4_csum_replace(struct sk_buff *skb, uint32_t offset, uint64_t from, uint64_t to, uint64_t flags) - * Description - * Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the - * packet associated to *skb*. Computation is incremental, so the - * helper must know the former value of the header field that was - * modified (*from*), the new value of this field (*to*), and the - * number of bytes (2 or 4) for this field, stored on the lowest - * four bits of *flags*. Alternatively, it is possible to store - * the difference between the previous and the new values of the - * header field in *to*, by setting *from* and the four lowest - * bits of *flags* to 0. For both methods, *offset* indicates the - * location of the IP checksum within the packet. In addition to - * the size of the field, *flags* can be added (bitwise OR) actual - * flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left - * untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and - * for updates resulting in a null checksum the value is set to + * int bpf_l4_csum_replace(struct sk_buff *skb, uint32_t offset, uint64_t from, uint64_t to, + *uint64_t flags) Description Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the packet + *associated to *skb*. Computation is incremental, so the helper must know the former value of the + *header field that was modified (*from*), the new value of this field (*to*), and the number of + *bytes (2 or 4) for this field, stored on the lowest four bits of *flags*. Alternatively, it is + *possible to store the difference between the previous and the new values of the header field in + **to*, by setting *from* and the four lowest bits of *flags* to 0. For both methods, *offset* + *indicates the location of the IP checksum within the packet. In addition to the size of the field, + **flags* can be added (bitwise OR) actual flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is + *left untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and for updates resulting in a + *null checksum the value is set to * **CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates * the checksum is to be computed against a pseudo-header. * @@ -943,14 +934,11 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_skb_get_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, uint32_t size, uint64_t flags) - * Description - * Get tunnel metadata. This helper takes a pointer *key* to an - * empty **struct bpf_tunnel_key** of **size**, that will be - * filled with tunnel metadata for the packet associated to *skb*. - * The *flags* can be set to **BPF_F_TUNINFO_IPV6**, which - * indicates that the tunnel is based on IPv6 protocol instead of - * IPv4. + * int bpf_skb_get_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, uint32_t size, + *uint64_t flags) Description Get tunnel metadata. This helper takes a pointer *key* to an empty + ***struct bpf_tunnel_key** of **size**, that will be filled with tunnel metadata for the packet + *associated to *skb*. The *flags* can be set to **BPF_F_TUNINFO_IPV6**, which indicates that the + *tunnel is based on IPv6 protocol instead of IPv4. * * The **struct bpf_tunnel_key** is an object that generalizes the * principal parameters used by various tunneling protocols into a @@ -994,11 +982,10 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_skb_set_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, uint32_t size, uint64_t flags) - * Description - * Populate tunnel metadata for packet associated to *skb.* The - * tunnel metadata is set to the contents of *key*, of *size*. The - * *flags* can be set to a combination of the following values: + * int bpf_skb_set_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, uint32_t size, + *uint64_t flags) Description Populate tunnel metadata for packet associated to *skb.* The tunnel + *metadata is set to the contents of *key*, of *size*. The *flags* can be set to a combination of + *the following values: * * **BPF_F_TUNINFO_IPV6** * Indicate that the tunnel is based on IPv6 protocol @@ -1107,12 +1094,10 @@ union bpf_attr { * The realm of the route for the packet associated to *skb*, or 0 * if none was found. * - * int bpf_perf_event_output(void *ctx, struct bpf_map *map, uint64_t flags, void *data, uint64_t size) - * Description - * Write raw *data* blob into a special BPF perf event held by - * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf - * event must have the following attributes: **PERF_SAMPLE_RAW** - * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * int bpf_perf_event_output(void *ctx, struct bpf_map *map, uint64_t flags, void *data, uint64_t + *size) Description Write raw *data* blob into a special BPF perf event held by *map* of type + ***BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf event must have the following attributes: + ***PERF_SAMPLE_RAW** as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. * * The *flags* are used to indicate the index in *map* for which @@ -1211,14 +1196,11 @@ union bpf_attr { * The positive or null stack id on success, or a negative error * in case of failure. * - * int64_t bpf_csum_diff(__be32 *from, uint32_t from_size, __be32 *to, uint32_t to_size, __wsum seed) - * Description - * Compute a checksum difference, from the raw buffer pointed by - * *from*, of length *from_size* (that must be a multiple of 4), - * towards the raw buffer pointed by *to*, of size *to_size* - * (same remark). An optional *seed* can be added to the value - * (this can be cascaded, the seed may come from a previous call - * to the helper). + * int64_t bpf_csum_diff(__be32 *from, uint32_t from_size, __be32 *to, uint32_t to_size, __wsum + *seed) Description Compute a checksum difference, from the raw buffer pointed by *from*, of length + **from_size* (that must be a multiple of 4), towards the raw buffer pointed by *to*, of size + **to_size* (same remark). An optional *seed* can be added to the value (this can be cascaded, the + *seed may come from a previous call to the helper). * * This is flexible enough to be used in several ways: * @@ -1564,13 +1546,11 @@ union bpf_attr { * Return * 0 * - * int bpf_setsockopt(struct bpf_sock_ops *bpf_socket, int level, int optname, void *optval, int optlen) - * Description - * Emulate a call to **setsockopt()** on the socket associated to - * *bpf_socket*, which must be a full socket. The *level* at - * which the option resides and the name *optname* of the option - * must be specified, see **setsockopt(2)** for more information. - * The option value of length *optlen* is pointed by *optval*. + * int bpf_setsockopt(struct bpf_sock_ops *bpf_socket, int level, int optname, void *optval, int + *optlen) Description Emulate a call to **setsockopt()** on the socket associated to *bpf_socket*, + *which must be a full socket. The *level* at which the option resides and the name *optname* of the + *option must be specified, see **setsockopt(2)** for more information. The option value of length + **optlen* is pointed by *optval*. * * This helper actually implements a subset of **setsockopt()**. * It supports the following *level*\ s: @@ -1657,11 +1637,9 @@ union bpf_attr { * Return * **SK_PASS** on success, or **SK_DROP** on error. * - * int bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, uint64_t flags) - * Description - * Add an entry to, or update a *map* referencing sockets. The - * *skops* is used as a new value for the entry associated to - * *key*. *flags* is one of: + * int bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, uint64_t + *flags) Description Add an entry to, or update a *map* referencing sockets. The *skops* is used as + *a new value for the entry associated to *key*. *flags* is one of: * * **BPF_NOEXIST** * The entry for *key* must not exist in the map. @@ -1705,10 +1683,9 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_perf_event_read_value(struct bpf_map *map, uint64_t flags, struct bpf_perf_event_value *buf, uint32_t buf_size) - * Description - * Read the value of a perf event counter, and store it into *buf* - * of size *buf_size*. This helper relies on a *map* of type + * int bpf_perf_event_read_value(struct bpf_map *map, uint64_t flags, struct bpf_perf_event_value + **buf, uint32_t buf_size) Description Read the value of a perf event counter, and store it into + **buf* of size *buf_size*. This helper relies on a *map* of type * **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of the perf event * counter is selected when *map* is updated with perf event file * descriptors. The *map* is an array whose size is the number of @@ -1755,25 +1732,18 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_perf_prog_read_value(struct bpf_perf_event_data *ctx, struct bpf_perf_event_value *buf, uint32_t buf_size) - * Description - * For en eBPF program attached to a perf event, retrieve the - * value of the event counter associated to *ctx* and store it in - * the structure pointed by *buf* and of size *buf_size*. Enabled - * and running times are also stored in the structure (see - * description of helper **bpf_perf_event_read_value**\ () for - * more details). - * Return - * 0 on success, or a negative error in case of failure. + * int bpf_perf_prog_read_value(struct bpf_perf_event_data *ctx, struct bpf_perf_event_value *buf, + *uint32_t buf_size) Description For en eBPF program attached to a perf event, retrieve the value of + *the event counter associated to *ctx* and store it in the structure pointed by *buf* and of size + **buf_size*. Enabled and running times are also stored in the structure (see description of helper + ***bpf_perf_event_read_value**\ () for more details). Return 0 on success, or a negative error in + *case of failure. * - * int bpf_getsockopt(struct bpf_sock_ops *bpf_socket, int level, int optname, void *optval, int optlen) - * Description - * Emulate a call to **getsockopt()** on the socket associated to - * *bpf_socket*, which must be a full socket. The *level* at - * which the option resides and the name *optname* of the option - * must be specified, see **getsockopt(2)** for more information. - * The retrieved value is stored in the structure pointed by - * *opval* and of length *optlen*. + * int bpf_getsockopt(struct bpf_sock_ops *bpf_socket, int level, int optname, void *optval, int + *optlen) Description Emulate a call to **getsockopt()** on the socket associated to *bpf_socket*, + *which must be a full socket. The *level* at which the option resides and the name *optname* of the + *option must be specified, see **getsockopt(2)** for more information. The retrieved value is + *stored in the structure pointed by *opval* and of length *optlen*. * * This helper actually implements a subset of **getsockopt()**. * It supports the following *level*\ s: @@ -1854,12 +1824,10 @@ union bpf_attr { * be set is returned (which comes down to 0 if all bits were set * as required). * - * int bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, uint32_t key, uint64_t flags) - * Description - * This helper is used in programs implementing policies at the - * socket level. If the message *msg* is allowed to pass (i.e. if - * the verdict eBPF program returns **SK_PASS**), redirect it to - * the socket referenced by *map* (of type + * int bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, uint32_t key, uint64_t + *flags) Description This helper is used in programs implementing policies at the socket level. If + *the message *msg* is allowed to pass (i.e. if the verdict eBPF program returns **SK_PASS**), + *redirect it to the socket referenced by *map* (of type * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and * egress interfaces can be used for redirection. The * **BPF_F_INGRESS** value in *flags* is used to make the @@ -1982,9 +1950,9 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_skb_get_xfrm_state(struct sk_buff *skb, uint32_t index, struct bpf_xfrm_state *xfrm_state, uint32_t size, uint64_t flags) - * Description - * Retrieve the XFRM state (IP transform framework, see also + * int bpf_skb_get_xfrm_state(struct sk_buff *skb, uint32_t index, struct bpf_xfrm_state + **xfrm_state, uint32_t size, uint64_t flags) Description Retrieve the XFRM state (IP transform + *framework, see also * **ip-xfrm(8)**) at *index* in XFRM "security path" for *skb*. * * The retrieved value is stored in the **struct bpf_xfrm_state** @@ -2031,14 +1999,12 @@ union bpf_attr { * A non-negative value equal to or less than *size* on success, * or a negative error in case of failure. * - * int bpf_skb_load_bytes_relative(const void *skb, uint32_t offset, void *to, uint32_t len, uint32_t start_header) - * Description - * This helper is similar to **bpf_skb_load_bytes**\ () in that - * it provides an easy way to load *len* bytes from *offset* - * from the packet associated to *skb*, into the buffer pointed - * by *to*. The difference to **bpf_skb_load_bytes**\ () is that - * a fifth argument *start_header* exists in order to select a - * base offset to start from. *start_header* can be one of: + * int bpf_skb_load_bytes_relative(const void *skb, uint32_t offset, void *to, uint32_t len, + *uint32_t start_header) Description This helper is similar to **bpf_skb_load_bytes**\ () in that it + *provides an easy way to load *len* bytes from *offset* from the packet associated to *skb*, into + *the buffer pointed by *to*. The difference to **bpf_skb_load_bytes**\ () is that a fifth argument + **start_header* exists in order to select a base offset to start from. *start_header* can be one + *of: * * **BPF_HDR_START_MAC** * Base offset to load data from is *skb*'s mac header. @@ -2084,11 +2050,9 @@ union bpf_attr { * * > 0 one of **BPF_FIB_LKUP_RET_** codes explaining why the * packet is not forwarded or needs assist from full stack * - * int bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, uint64_t flags) - * Description - * Add an entry to, or update a sockhash *map* referencing sockets. - * The *skops* is used as a new value for the entry associated to - * *key*. *flags* is one of: + * int bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, uint64_t + *flags) Description Add an entry to, or update a sockhash *map* referencing sockets. The *skops* is + *used as a new value for the entry associated to *key*. *flags* is one of: * * **BPF_NOEXIST** * The entry for *key* must not exist in the map. @@ -2103,12 +2067,10 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, uint64_t flags) - * Description - * This helper is used in programs implementing policies at the - * socket level. If the message *msg* is allowed to pass (i.e. if - * the verdict eBPF program returns **SK_PASS**), redirect it to - * the socket referenced by *map* (of type + * int bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, uint64_t + *flags) Description This helper is used in programs implementing policies at the socket level. If + *the message *msg* is allowed to pass (i.e. if the verdict eBPF program returns **SK_PASS**), + *redirect it to the socket referenced by *map* (of type * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and * egress interfaces can be used for redirection. The * **BPF_F_INGRESS** value in *flags* is used to make the @@ -2168,11 +2130,9 @@ union bpf_attr { * Return * 0 on success, or a negative error in case of failure. * - * int bpf_lwt_seg6_store_bytes(struct sk_buff *skb, uint32_t offset, const void *from, uint32_t len) - * Description - * Store *len* bytes from address *from* into the packet - * associated to *skb*, at *offset*. Only the flags, tag and TLVs - * inside the outermost IPv6 Segment Routing Header can be + * int bpf_lwt_seg6_store_bytes(struct sk_buff *skb, uint32_t offset, const void *from, uint32_t + *len) Description Store *len* bytes from address *from* into the packet associated to *skb*, at + **offset*. Only the flags, tag and TLVs inside the outermost IPv6 Segment Routing Header can be * modified through this helper. * * A call to this helper is susceptible to change the underlying @@ -2312,9 +2272,8 @@ union bpf_attr { * Return * A pointer to the local storage area. * - * int bpf_sk_select_reuseport(struct sk_reuseport_md *reuse, struct bpf_map *map, void *key, uint64_t flags) - * Description - * Select a **SO_REUSEPORT** socket from a + * int bpf_sk_select_reuseport(struct sk_reuseport_md *reuse, struct bpf_map *map, void *key, + *uint64_t flags) Description Select a **SO_REUSEPORT** socket from a * **BPF_MAP_TYPE_REUSEPORT_ARRAY** *map*. * It checks the selected socket is matching the incoming * request in the socket buffer. @@ -2339,11 +2298,10 @@ union bpf_attr { * Return * The id is returned or 0 in case the id could not be retrieved. * - * struct bpf_sock *bpf_sk_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, uint32_t tuple_size, uint64_t netns, uint64_t flags) - * Description - * Look for TCP socket matching *tuple*, optionally in a child - * network namespace *netns*. The return value must be checked, - * and if non-**NULL**, released via **bpf_sk_release**\ (). + * struct bpf_sock *bpf_sk_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, uint32_t tuple_size, + *uint64_t netns, uint64_t flags) Description Look for TCP socket matching *tuple*, optionally in a + *child network namespace *netns*. The return value must be checked, and if non-**NULL**, released + *via **bpf_sk_release**\ (). * * The *ctx* should point to the context of the program, such as * the skb or socket (depending on the hook in use). This is used @@ -2376,11 +2334,10 @@ union bpf_attr { * result is from *reuse*\ **->socks**\ [] using the hash of the * tuple. * - * struct bpf_sock *bpf_sk_lookup_udp(void *ctx, struct bpf_sock_tuple *tuple, uint32_t tuple_size, uint64_t netns, uint64_t flags) - * Description - * Look for UDP socket matching *tuple*, optionally in a child - * network namespace *netns*. The return value must be checked, - * and if non-**NULL**, released via **bpf_sk_release**\ (). + * struct bpf_sock *bpf_sk_lookup_udp(void *ctx, struct bpf_sock_tuple *tuple, uint32_t tuple_size, + *uint64_t netns, uint64_t flags) Description Look for UDP socket matching *tuple*, optionally in a + *child network namespace *netns*. The return value must be checked, and if non-**NULL**, released + *via **bpf_sk_release**\ (). * * The *ctx* should point to the context of the program, such as * the skb or socket (depending on the hook in use). This is used @@ -2574,11 +2531,10 @@ union bpf_attr { * A **struct bpf_sock** pointer on success, or **NULL** in * case of failure. * - * struct bpf_sock *bpf_skc_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, uint32_t tuple_size, uint64_t netns, uint64_t flags) - * Description - * Look for TCP socket matching *tuple*, optionally in a child - * network namespace *netns*. The return value must be checked, - * and if non-**NULL**, released via **bpf_sk_release**\ (). + * struct bpf_sock *bpf_skc_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, uint32_t tuple_size, + *uint64_t netns, uint64_t flags) Description Look for TCP socket matching *tuple*, optionally in a + *child network namespace *netns*. The return value must be checked, and if non-**NULL**, released + *via **bpf_sk_release**\ (). * * This function is identical to **bpf_sk_lookup_tcp**\ (), except * that it also returns timewait or request sockets. Use @@ -2593,10 +2549,9 @@ union bpf_attr { * result is from *reuse*\ **->socks**\ [] using the hash of the * tuple. * - * int bpf_tcp_check_syncookie(struct bpf_sock *sk, void *iph, uint32_t iph_len, struct tcphdr *th, uint32_t th_len) - * Description - * Check whether *iph* and *th* contain a valid SYN cookie ACK for - * the listening socket in *sk*. + * int bpf_tcp_check_syncookie(struct bpf_sock *sk, void *iph, uint32_t iph_len, struct tcphdr *th, + *uint32_t th_len) Description Check whether *iph* and *th* contain a valid SYN cookie ACK for the + *listening socket in *sk*. * * *iph* points to the start of the IPv4 or IPv6 header, while * *iph_len* contains **sizeof**\ (**struct iphdr**) or @@ -2776,9 +2731,8 @@ union bpf_attr { * * **-EAGAIN** if bpf program can try again. * - * int64_t bpf_tcp_gen_syncookie(struct bpf_sock *sk, void *iph, uint32_t iph_len, struct tcphdr *th, uint32_t th_len) - * Description - * Try to issue a SYN cookie for the packet with corresponding + * int64_t bpf_tcp_gen_syncookie(struct bpf_sock *sk, void *iph, uint32_t iph_len, struct tcphdr + **th, uint32_t th_len) Description Try to issue a SYN cookie for the packet with corresponding * IP/TCP headers, *iph* and *th*, on the listening socket in *sk*. * * *iph* points to the start of the IPv4 or IPv6 header, while @@ -2920,15 +2874,11 @@ union bpf_attr { * Return * The 64 bit jiffies * - * int bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, uint32_t size, uint64_t flags) - * Description - * For an eBPF program attached to a perf event, retrieve the - * branch records (struct perf_branch_entry) associated to *ctx* - * and store it in the buffer pointed by *buf* up to size - * *size* bytes. - * Return - * On success, number of bytes written to *buf*. On error, a - * negative value. + * int bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, uint32_t size, uint64_t + *flags) Description For an eBPF program attached to a perf event, retrieve the branch records + *(struct perf_branch_entry) associated to *ctx* and store it in the buffer pointed by *buf* up + *to size *size* bytes. Return On success, number of bytes written to *buf*. On error, a negative + *value. * * The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to * instead return the number of bytes required to store all the @@ -2939,10 +2889,9 @@ union bpf_attr { * * **-ENOENT** if architecture does not support branch records. * - * int bpf_get_ns_current_pid_tgid(uint64_t dev, uint64_t ino, struct bpf_pidns_info *nsdata, uint32_t size) - * Description - * Returns 0 on success, values for *pid* and *tgid* as seen from the current - * *namespace* will be returned in *nsdata*. + * int bpf_get_ns_current_pid_tgid(uint64_t dev, uint64_t ino, struct bpf_pidns_info *nsdata, + *uint32_t size) Description Returns 0 on success, values for *pid* and *tgid* as seen from the + *current *namespace* will be returned in *nsdata*. * * On failure, the returned value is one of the following: * @@ -3036,141 +2985,49 @@ union bpf_attr { * Return * Current *ktime*. */ -#define __BPF_FUNC_MAPPER(FN) \ - FN(unspec), \ - FN(map_lookup_elem), \ - FN(map_update_elem), \ - FN(map_delete_elem), \ - FN(probe_read), \ - FN(ktime_get_ns), \ - FN(trace_printk), \ - FN(get_prandom_u32), \ - FN(get_smp_processor_id), \ - FN(skb_store_bytes), \ - FN(l3_csum_replace), \ - FN(l4_csum_replace), \ - FN(tail_call), \ - FN(clone_redirect), \ - FN(get_current_pid_tgid), \ - FN(get_current_uid_gid), \ - FN(get_current_comm), \ - FN(get_cgroup_classid), \ - FN(skb_vlan_push), \ - FN(skb_vlan_pop), \ - FN(skb_get_tunnel_key), \ - FN(skb_set_tunnel_key), \ - FN(perf_event_read), \ - FN(redirect), \ - FN(get_route_realm), \ - FN(perf_event_output), \ - FN(skb_load_bytes), \ - FN(get_stackid), \ - FN(csum_diff), \ - FN(skb_get_tunnel_opt), \ - FN(skb_set_tunnel_opt), \ - FN(skb_change_proto), \ - FN(skb_change_type), \ - FN(skb_under_cgroup), \ - FN(get_hash_recalc), \ - FN(get_current_task), \ - FN(probe_write_user), \ - FN(current_task_under_cgroup), \ - FN(skb_change_tail), \ - FN(skb_pull_data), \ - FN(csum_update), \ - FN(set_hash_invalid), \ - FN(get_numa_node_id), \ - FN(skb_change_head), \ - FN(xdp_adjust_head), \ - FN(probe_read_str), \ - FN(get_socket_cookie), \ - FN(get_socket_uid), \ - FN(set_hash), \ - FN(setsockopt), \ - FN(skb_adjust_room), \ - FN(redirect_map), \ - FN(sk_redirect_map), \ - FN(sock_map_update), \ - FN(xdp_adjust_meta), \ - FN(perf_event_read_value), \ - FN(perf_prog_read_value), \ - FN(getsockopt), \ - FN(override_return), \ - FN(sock_ops_cb_flags_set), \ - FN(msg_redirect_map), \ - FN(msg_apply_bytes), \ - FN(msg_cork_bytes), \ - FN(msg_pull_data), \ - FN(bind), \ - FN(xdp_adjust_tail), \ - FN(skb_get_xfrm_state), \ - FN(get_stack), \ - FN(skb_load_bytes_relative), \ - FN(fib_lookup), \ - FN(sock_hash_update), \ - FN(msg_redirect_hash), \ - FN(sk_redirect_hash), \ - FN(lwt_push_encap), \ - FN(lwt_seg6_store_bytes), \ - FN(lwt_seg6_adjust_srh), \ - FN(lwt_seg6_action), \ - FN(rc_repeat), \ - FN(rc_keydown), \ - FN(skb_cgroup_id), \ - FN(get_current_cgroup_id), \ - FN(get_local_storage), \ - FN(sk_select_reuseport), \ - FN(skb_ancestor_cgroup_id), \ - FN(sk_lookup_tcp), \ - FN(sk_lookup_udp), \ - FN(sk_release), \ - FN(map_push_elem), \ - FN(map_pop_elem), \ - FN(map_peek_elem), \ - FN(msg_push_data), \ - FN(msg_pop_data), \ - FN(rc_pointer_rel), \ - FN(spin_lock), \ - FN(spin_unlock), \ - FN(sk_fullsock), \ - FN(tcp_sock), \ - FN(skb_ecn_set_ce), \ - FN(get_listener_sock), \ - FN(skc_lookup_tcp), \ - FN(tcp_check_syncookie), \ - FN(sysctl_get_name), \ - FN(sysctl_get_current_value), \ - FN(sysctl_get_new_value), \ - FN(sysctl_set_new_value), \ - FN(strtol), \ - FN(strtoul), \ - FN(sk_storage_get), \ - FN(sk_storage_delete), \ - FN(send_signal), \ - FN(tcp_gen_syncookie), \ - FN(skb_output), \ - FN(probe_read_user), \ - FN(probe_read_kernel), \ - FN(probe_read_user_str), \ - FN(probe_read_kernel_str), \ - FN(tcp_send_ack), \ - FN(send_signal_thread), \ - FN(jiffies64), \ - FN(read_branch_records), \ - FN(get_ns_current_pid_tgid), \ - FN(xdp_output), \ - FN(get_netns_cookie), \ - FN(get_current_ancestor_cgroup_id), \ - FN(sk_assign), \ - FN(ktime_get_boot_ns), +#define __BPF_FUNC_MAPPER(FN) \ + FN(unspec), FN(map_lookup_elem), FN(map_update_elem), FN(map_delete_elem), FN(probe_read), \ + FN(ktime_get_ns), FN(trace_printk), FN(get_prandom_u32), FN(get_smp_processor_id), \ + FN(skb_store_bytes), FN(l3_csum_replace), FN(l4_csum_replace), FN(tail_call), \ + FN(clone_redirect), FN(get_current_pid_tgid), FN(get_current_uid_gid), \ + FN(get_current_comm), FN(get_cgroup_classid), FN(skb_vlan_push), FN(skb_vlan_pop), \ + FN(skb_get_tunnel_key), FN(skb_set_tunnel_key), FN(perf_event_read), FN(redirect), \ + FN(get_route_realm), FN(perf_event_output), FN(skb_load_bytes), FN(get_stackid), \ + FN(csum_diff), FN(skb_get_tunnel_opt), FN(skb_set_tunnel_opt), FN(skb_change_proto), \ + FN(skb_change_type), FN(skb_under_cgroup), FN(get_hash_recalc), FN(get_current_task), \ + FN(probe_write_user), FN(current_task_under_cgroup), FN(skb_change_tail), \ + FN(skb_pull_data), FN(csum_update), FN(set_hash_invalid), FN(get_numa_node_id), \ + FN(skb_change_head), FN(xdp_adjust_head), FN(probe_read_str), FN(get_socket_cookie), \ + FN(get_socket_uid), FN(set_hash), FN(setsockopt), FN(skb_adjust_room), \ + FN(redirect_map), FN(sk_redirect_map), FN(sock_map_update), FN(xdp_adjust_meta), \ + FN(perf_event_read_value), FN(perf_prog_read_value), FN(getsockopt), \ + FN(override_return), FN(sock_ops_cb_flags_set), FN(msg_redirect_map), \ + FN(msg_apply_bytes), FN(msg_cork_bytes), FN(msg_pull_data), FN(bind), \ + FN(xdp_adjust_tail), FN(skb_get_xfrm_state), FN(get_stack), \ + FN(skb_load_bytes_relative), FN(fib_lookup), FN(sock_hash_update), \ + FN(msg_redirect_hash), FN(sk_redirect_hash), FN(lwt_push_encap), \ + FN(lwt_seg6_store_bytes), FN(lwt_seg6_adjust_srh), FN(lwt_seg6_action), FN(rc_repeat), \ + FN(rc_keydown), FN(skb_cgroup_id), FN(get_current_cgroup_id), FN(get_local_storage), \ + FN(sk_select_reuseport), FN(skb_ancestor_cgroup_id), FN(sk_lookup_tcp), \ + FN(sk_lookup_udp), FN(sk_release), FN(map_push_elem), FN(map_pop_elem), \ + FN(map_peek_elem), FN(msg_push_data), FN(msg_pop_data), FN(rc_pointer_rel), \ + FN(spin_lock), FN(spin_unlock), FN(sk_fullsock), FN(tcp_sock), FN(skb_ecn_set_ce), \ + FN(get_listener_sock), FN(skc_lookup_tcp), FN(tcp_check_syncookie), \ + FN(sysctl_get_name), FN(sysctl_get_current_value), FN(sysctl_get_new_value), \ + FN(sysctl_set_new_value), FN(strtol), FN(strtoul), FN(sk_storage_get), \ + FN(sk_storage_delete), FN(send_signal), FN(tcp_gen_syncookie), FN(skb_output), \ + FN(probe_read_user), FN(probe_read_kernel), FN(probe_read_user_str), \ + FN(probe_read_kernel_str), FN(tcp_send_ack), FN(send_signal_thread), FN(jiffies64), \ + FN(read_branch_records), FN(get_ns_current_pid_tgid), FN(xdp_output), \ + FN(get_netns_cookie), FN(get_current_ancestor_cgroup_id), FN(sk_assign), \ + FN(ktime_get_boot_ns), /* integer value in 'imm' field of BPF_CALL instruction selects which helper * function eBPF program intends to call */ -#define __BPF_ENUM_FN(x) BPF_FUNC_ ## x +#define __BPF_ENUM_FN(x) BPF_FUNC_##x enum bpf_func_id { - __BPF_FUNC_MAPPER(__BPF_ENUM_FN) - __BPF_FUNC_MAX_ID, + __BPF_FUNC_MAPPER(__BPF_ENUM_FN) __BPF_FUNC_MAX_ID, }; #undef __BPF_ENUM_FN @@ -3178,98 +3035,97 @@ enum bpf_func_id { /* BPF_FUNC_skb_store_bytes flags. */ enum { - BPF_F_RECOMPUTE_CSUM = (1ULL << 0), - BPF_F_INVALIDATE_HASH = (1ULL << 1), + BPF_F_RECOMPUTE_CSUM = (1ULL << 0), + BPF_F_INVALIDATE_HASH = (1ULL << 1), }; /* BPF_FUNC_l3_csum_replace and BPF_FUNC_l4_csum_replace flags. * First 4 bits are for passing the header field size. */ enum { - BPF_F_HDR_FIELD_MASK = 0xfULL, + BPF_F_HDR_FIELD_MASK = 0xfULL, }; /* BPF_FUNC_l4_csum_replace flags. */ enum { - BPF_F_PSEUDO_HDR = (1ULL << 4), - BPF_F_MARK_MANGLED_0 = (1ULL << 5), - BPF_F_MARK_ENFORCE = (1ULL << 6), + BPF_F_PSEUDO_HDR = (1ULL << 4), + BPF_F_MARK_MANGLED_0 = (1ULL << 5), + BPF_F_MARK_ENFORCE = (1ULL << 6), }; /* BPF_FUNC_clone_redirect and BPF_FUNC_redirect flags. */ enum { - BPF_F_INGRESS = (1ULL << 0), + BPF_F_INGRESS = (1ULL << 0), }; /* BPF_FUNC_skb_set_tunnel_key and BPF_FUNC_skb_get_tunnel_key flags. */ enum { - BPF_F_TUNINFO_IPV6 = (1ULL << 0), + BPF_F_TUNINFO_IPV6 = (1ULL << 0), }; /* flags for both BPF_FUNC_get_stackid and BPF_FUNC_get_stack. */ enum { - BPF_F_SKIP_FIELD_MASK = 0xffULL, - BPF_F_USER_STACK = (1ULL << 8), + BPF_F_SKIP_FIELD_MASK = 0xffULL, + BPF_F_USER_STACK = (1ULL << 8), /* flags used by BPF_FUNC_get_stackid only. */ - BPF_F_FAST_STACK_CMP = (1ULL << 9), - BPF_F_REUSE_STACKID = (1ULL << 10), + BPF_F_FAST_STACK_CMP = (1ULL << 9), + BPF_F_REUSE_STACKID = (1ULL << 10), /* flags used by BPF_FUNC_get_stack only. */ - BPF_F_USER_BUILD_ID = (1ULL << 11), + BPF_F_USER_BUILD_ID = (1ULL << 11), }; /* BPF_FUNC_skb_set_tunnel_key flags. */ enum { - BPF_F_ZERO_CSUM_TX = (1ULL << 1), - BPF_F_DONT_FRAGMENT = (1ULL << 2), - BPF_F_SEQ_NUMBER = (1ULL << 3), + BPF_F_ZERO_CSUM_TX = (1ULL << 1), + BPF_F_DONT_FRAGMENT = (1ULL << 2), + BPF_F_SEQ_NUMBER = (1ULL << 3), }; /* BPF_FUNC_perf_event_output, BPF_FUNC_perf_event_read and * BPF_FUNC_perf_event_read_value flags. */ enum { - BPF_F_INDEX_MASK = 0xffffffffULL, - BPF_F_CURRENT_CPU = BPF_F_INDEX_MASK, + BPF_F_INDEX_MASK = 0xffffffffULL, + BPF_F_CURRENT_CPU = BPF_F_INDEX_MASK, /* BPF_FUNC_perf_event_output for sk_buff input context. */ - BPF_F_CTXLEN_MASK = (0xfffffULL << 32), + BPF_F_CTXLEN_MASK = (0xfffffULL << 32), }; /* Current network namespace */ enum { - BPF_F_CURRENT_NETNS = (-1L), + BPF_F_CURRENT_NETNS = (-1L), }; /* BPF_FUNC_skb_adjust_room flags. */ enum { - BPF_F_ADJ_ROOM_FIXED_GSO = (1ULL << 0), - BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 = (1ULL << 1), - BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 = (1ULL << 2), - BPF_F_ADJ_ROOM_ENCAP_L4_GRE = (1ULL << 3), - BPF_F_ADJ_ROOM_ENCAP_L4_UDP = (1ULL << 4), + BPF_F_ADJ_ROOM_FIXED_GSO = (1ULL << 0), + BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 = (1ULL << 1), + BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 = (1ULL << 2), + BPF_F_ADJ_ROOM_ENCAP_L4_GRE = (1ULL << 3), + BPF_F_ADJ_ROOM_ENCAP_L4_UDP = (1ULL << 4), }; enum { - BPF_ADJ_ROOM_ENCAP_L2_MASK = 0xff, - BPF_ADJ_ROOM_ENCAP_L2_SHIFT = 56, + BPF_ADJ_ROOM_ENCAP_L2_MASK = 0xff, + BPF_ADJ_ROOM_ENCAP_L2_SHIFT = 56, }; -#define BPF_F_ADJ_ROOM_ENCAP_L2(len) (((__u64)len & \ - BPF_ADJ_ROOM_ENCAP_L2_MASK) \ - << BPF_ADJ_ROOM_ENCAP_L2_SHIFT) +#define BPF_F_ADJ_ROOM_ENCAP_L2(len) \ + (((__u64)len & BPF_ADJ_ROOM_ENCAP_L2_MASK) << BPF_ADJ_ROOM_ENCAP_L2_SHIFT) /* BPF_FUNC_sysctl_get_name flags. */ enum { - BPF_F_SYSCTL_BASE_NAME = (1ULL << 0), + BPF_F_SYSCTL_BASE_NAME = (1ULL << 0), }; /* BPF_FUNC_sk_storage_get flags */ enum { - BPF_SK_STORAGE_GET_F_CREATE = (1ULL << 0), + BPF_SK_STORAGE_GET_F_CREATE = (1ULL << 0), }; /* BPF_FUNC_read_branch_records flags. */ enum { - BPF_F_GET_BRANCH_RECORDS_SIZE = (1ULL << 0), + BPF_F_GET_BRANCH_RECORDS_SIZE = (1ULL << 0), }; /* Mode for BPF_FUNC_skb_adjust_room helper. */ @@ -3291,11 +3147,11 @@ enum bpf_lwt_encap_mode { BPF_LWT_ENCAP_IP, }; -#define __bpf_md_ptr(type, name) \ -union { \ - type name; \ - __u64 :64; \ -} __attribute__((aligned(8))) +#define __bpf_md_ptr(type, name) \ + union { \ + type name; \ + __u64 : 64; \ + } __attribute__((aligned(8))) /* user accessible mirror of in-kernel sk_buff. * new fields can only be added to the end of this structure @@ -3322,12 +3178,12 @@ struct __sk_buff { /* Accessed by BPF_PROG_TYPE_sk_skb types from here to ... */ __u32 family; - __u32 remote_ip4; /* Stored in network byte order */ - __u32 local_ip4; /* Stored in network byte order */ - __u32 remote_ip6[4]; /* Stored in network byte order */ - __u32 local_ip6[4]; /* Stored in network byte order */ - __u32 remote_port; /* Stored in network byte order */ - __u32 local_port; /* stored in host byte order */ + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ /* ... here. */ __u32 data_meta; @@ -3347,7 +3203,7 @@ struct bpf_tunnel_key { }; __u8 tunnel_tos; __u8 tunnel_ttl; - __u16 tunnel_ext; /* Padding, future use. */ + __u16 tunnel_ext; /* Padding, future use. */ __u32 tunnel_label; }; @@ -3356,12 +3212,12 @@ struct bpf_tunnel_key { */ struct bpf_xfrm_state { __u32 reqid; - __u32 spi; /* Stored in network byte order */ + __u32 spi; /* Stored in network byte order */ __u16 family; - __u16 ext; /* Padding, future use. */ + __u16 ext; /* Padding, future use. */ union { - __u32 remote_ipv4; /* Stored in network byte order */ - __u32 remote_ipv6[4]; /* Stored in network byte order */ + __u32 remote_ipv4; /* Stored in network byte order */ + __u32 remote_ipv6[4]; /* Stored in network byte order */ }; }; @@ -3399,56 +3255,56 @@ struct bpf_sock { /* IP address also allows 1 and 2 bytes access */ __u32 src_ip4; __u32 src_ip6[4]; - __u32 src_port; /* host byte order */ - __u32 dst_port; /* network byte order */ + __u32 src_port; /* host byte order */ + __u32 dst_port; /* network byte order */ __u32 dst_ip4; __u32 dst_ip6[4]; __u32 state; }; struct bpf_tcp_sock { - __u32 snd_cwnd; /* Sending congestion window */ - __u32 srtt_us; /* smoothed round trip time << 3 in usecs */ + __u32 snd_cwnd; /* Sending congestion window */ + __u32 srtt_us; /* smoothed round trip time << 3 in usecs */ __u32 rtt_min; - __u32 snd_ssthresh; /* Slow start size threshold */ - __u32 rcv_nxt; /* What we want to receive next */ - __u32 snd_nxt; /* Next sequence we send */ - __u32 snd_una; /* First byte we want an ack for */ - __u32 mss_cache; /* Cached effective mss, not including SACKS */ - __u32 ecn_flags; /* ECN status bits. */ - __u32 rate_delivered; /* saved rate sample: packets delivered */ - __u32 rate_interval_us; /* saved rate sample: time elapsed */ - __u32 packets_out; /* Packets which are "in flight" */ - __u32 retrans_out; /* Retransmitted packets out */ - __u32 total_retrans; /* Total retransmits for entire connection */ - __u32 segs_in; /* RFC4898 tcpEStatsPerfSegsIn - * total number of segments in. - */ - __u32 data_segs_in; /* RFC4898 tcpEStatsPerfDataSegsIn - * total number of data segments in. - */ - __u32 segs_out; /* RFC4898 tcpEStatsPerfSegsOut - * The total number of segments sent. - */ - __u32 data_segs_out; /* RFC4898 tcpEStatsPerfDataSegsOut - * total number of data segments sent. - */ - __u32 lost_out; /* Lost packets */ - __u32 sacked_out; /* SACK'd packets */ - __u64 bytes_received; /* RFC4898 tcpEStatsAppHCThruOctetsReceived - * sum(delta(rcv_nxt)), or how many bytes - * were acked. - */ - __u64 bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked - * sum(delta(snd_una)), or how many bytes - * were acked. - */ - __u32 dsack_dups; /* RFC4898 tcpEStatsStackDSACKDups - * total number of DSACK blocks received - */ - __u32 delivered; /* Total data packets delivered incl. rexmits */ - __u32 delivered_ce; /* Like the above but only ECE marked packets */ - __u32 icsk_retransmits; /* Number of unrecovered [RTO] timeouts */ + __u32 snd_ssthresh; /* Slow start size threshold */ + __u32 rcv_nxt; /* What we want to receive next */ + __u32 snd_nxt; /* Next sequence we send */ + __u32 snd_una; /* First byte we want an ack for */ + __u32 mss_cache; /* Cached effective mss, not including SACKS */ + __u32 ecn_flags; /* ECN status bits. */ + __u32 rate_delivered; /* saved rate sample: packets delivered */ + __u32 rate_interval_us; /* saved rate sample: time elapsed */ + __u32 packets_out; /* Packets which are "in flight" */ + __u32 retrans_out; /* Retransmitted packets out */ + __u32 total_retrans; /* Total retransmits for entire connection */ + __u32 segs_in; /* RFC4898 tcpEStatsPerfSegsIn + * total number of segments in. + */ + __u32 data_segs_in; /* RFC4898 tcpEStatsPerfDataSegsIn + * total number of data segments in. + */ + __u32 segs_out; /* RFC4898 tcpEStatsPerfSegsOut + * The total number of segments sent. + */ + __u32 data_segs_out; /* RFC4898 tcpEStatsPerfDataSegsOut + * total number of data segments sent. + */ + __u32 lost_out; /* Lost packets */ + __u32 sacked_out; /* SACK'd packets */ + __u64 bytes_received; /* RFC4898 tcpEStatsAppHCThruOctetsReceived + * sum(delta(rcv_nxt)), or how many bytes + * were acked. + */ + __u64 bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked + * sum(delta(snd_una)), or how many bytes + * were acked. + */ + __u32 dsack_dups; /* RFC4898 tcpEStatsStackDSACKDups + * total number of DSACK blocks received + */ + __u32 delivered; /* Total data packets delivered incl. rexmits */ + __u32 delivered_ce; /* Like the above but only ECE marked packets */ + __u32 icsk_retransmits; /* Number of unrecovered [RTO] timeouts */ }; struct bpf_sock_tuple { @@ -3512,13 +3368,13 @@ struct sk_msg_md { __bpf_md_ptr(void *, data_end); __u32 family; - __u32 remote_ip4; /* Stored in network byte order */ - __u32 local_ip4; /* Stored in network byte order */ - __u32 remote_ip6[4]; /* Stored in network byte order */ - __u32 local_ip6[4]; /* Stored in network byte order */ - __u32 remote_port; /* Stored in network byte order */ - __u32 local_port; /* stored in host byte order */ - __u32 size; /* Total size of sk_msg */ + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + __u32 size; /* Total size of sk_msg */ }; struct sk_reuseport_md { @@ -3541,29 +3397,29 @@ struct sk_reuseport_md { * ETH_P_IP(0x0800) and ETH_P_IPV6(0x86DD) */ __u32 eth_protocol; - __u32 ip_protocol; /* IP protocol. e.g. IPPROTO_TCP, IPPROTO_UDP */ - __u32 bind_inany; /* Is sock bound to an INANY address? */ - __u32 hash; /* A hash of the packet 4 tuples */ + __u32 ip_protocol; /* IP protocol. e.g. IPPROTO_TCP, IPPROTO_UDP */ + __u32 bind_inany; /* Is sock bound to an INANY address? */ + __u32 hash; /* A hash of the packet 4 tuples */ }; -#define BPF_TAG_SIZE 8 +#define BPF_TAG_SIZE 8 struct bpf_prog_info { __u32 type; __u32 id; - __u8 tag[BPF_TAG_SIZE]; + __u8 tag[BPF_TAG_SIZE]; __u32 jited_prog_len; __u32 xlated_prog_len; __aligned_u64 jited_prog_insns; __aligned_u64 xlated_prog_insns; - __u64 load_time; /* ns since boottime */ + __u64 load_time; /* ns since boottime */ __u32 created_by_uid; __u32 nr_map_ids; __aligned_u64 map_ids; char name[BPF_OBJ_NAME_LEN]; __u32 ifindex; - __u32 gpl_compatible:1; - __u32 :31; /* alignment pad */ + __u32 gpl_compatible : 1; + __u32 : 31; /* alignment pad */ __u64 netns_dev; __u64 netns_ino; __u32 nr_jited_ksyms; @@ -3593,7 +3449,7 @@ struct bpf_map_info { __u32 value_size; __u32 max_entries; __u32 map_flags; - char name[BPF_OBJ_NAME_LEN]; + char name[BPF_OBJ_NAME_LEN]; __u32 ifindex; __u32 btf_vmlinux_value_type_id; __u64 netns_dev; @@ -3614,25 +3470,25 @@ struct bpf_btf_info { * attach attach type). */ struct bpf_sock_addr { - __u32 user_family; /* Allows 4-byte read, but no write. */ - __u32 user_ip4; /* Allows 1,2,4-byte read and 4-byte write. - * Stored in network byte order. - */ - __u32 user_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. - * Stored in network byte order. - */ - __u32 user_port; /* Allows 4-byte read and write. - * Stored in network byte order - */ - __u32 family; /* Allows 4-byte read, but no write */ - __u32 type; /* Allows 4-byte read, but no write */ - __u32 protocol; /* Allows 4-byte read, but no write */ - __u32 msg_src_ip4; /* Allows 1,2,4-byte read and 4-byte write. - * Stored in network byte order. - */ - __u32 msg_src_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. - * Stored in network byte order. - */ + __u32 user_family; /* Allows 4-byte read, but no write. */ + __u32 user_ip4; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order. + */ + __u32 user_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. + * Stored in network byte order. + */ + __u32 user_port; /* Allows 4-byte read and write. + * Stored in network byte order + */ + __u32 family; /* Allows 4-byte read, but no write */ + __u32 type; /* Allows 4-byte read, but no write */ + __u32 protocol; /* Allows 4-byte read, but no write */ + __u32 msg_src_ip4; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order. + */ + __u32 msg_src_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. + * Stored in network byte order. + */ __bpf_md_ptr(struct bpf_sock *, sk); }; @@ -3645,23 +3501,23 @@ struct bpf_sock_addr { struct bpf_sock_ops { __u32 op; union { - __u32 args[4]; /* Optionally passed to bpf program */ - __u32 reply; /* Returned by bpf program */ - __u32 replylong[4]; /* Optionally returned by bpf prog */ + __u32 args[4]; /* Optionally passed to bpf program */ + __u32 reply; /* Returned by bpf program */ + __u32 replylong[4]; /* Optionally returned by bpf prog */ }; __u32 family; - __u32 remote_ip4; /* Stored in network byte order */ - __u32 local_ip4; /* Stored in network byte order */ - __u32 remote_ip6[4]; /* Stored in network byte order */ - __u32 local_ip6[4]; /* Stored in network byte order */ - __u32 remote_port; /* Stored in network byte order */ - __u32 local_port; /* stored in host byte order */ - __u32 is_fullsock; /* Some TCP fields are only valid if - * there is a full socket. If not, the - * fields read as zero. - */ + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + __u32 is_fullsock; /* Some TCP fields are only valid if + * there is a full socket. If not, the + * fields read as zero. + */ __u32 snd_cwnd; - __u32 srtt_us; /* Averaged RTT << 3 in usecs */ + __u32 srtt_us; /* Averaged RTT << 3 in usecs */ __u32 bpf_sock_ops_cb_flags; /* flags defined in uapi/linux/tcp.h */ __u32 state; __u32 rtt_min; @@ -3690,12 +3546,12 @@ struct bpf_sock_ops { /* Definitions for bpf_sock_ops_cb_flags */ enum { - BPF_SOCK_OPS_RTO_CB_FLAG = (1<<0), - BPF_SOCK_OPS_RETRANS_CB_FLAG = (1<<1), - BPF_SOCK_OPS_STATE_CB_FLAG = (1<<2), - BPF_SOCK_OPS_RTT_CB_FLAG = (1<<3), + BPF_SOCK_OPS_RTO_CB_FLAG = (1 << 0), + BPF_SOCK_OPS_RETRANS_CB_FLAG = (1 << 1), + BPF_SOCK_OPS_STATE_CB_FLAG = (1 << 2), + BPF_SOCK_OPS_RTT_CB_FLAG = (1 << 3), /* Mask of all currently supported cb flags */ - BPF_SOCK_OPS_ALL_CB_FLAGS = 0xF, + BPF_SOCK_OPS_ALL_CB_FLAGS = 0xF, }; /* List of known BPF sock_ops operators. @@ -3703,54 +3559,54 @@ enum { */ enum { BPF_SOCK_OPS_VOID, - BPF_SOCK_OPS_TIMEOUT_INIT, /* Should return SYN-RTO value to use or - * -1 if default value should be used - */ - BPF_SOCK_OPS_RWND_INIT, /* Should return initial advertized - * window (in packets) or -1 if default - * value should be used - */ - BPF_SOCK_OPS_TCP_CONNECT_CB, /* Calls BPF program right before an - * active connection is initialized - */ - BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, /* Calls BPF program when an - * active connection is - * established - */ - BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB, /* Calls BPF program when a - * passive connection is - * established - */ - BPF_SOCK_OPS_NEEDS_ECN, /* If connection's congestion control - * needs ECN - */ - BPF_SOCK_OPS_BASE_RTT, /* Get base RTT. The correct value is - * based on the path and may be - * dependent on the congestion control - * algorithm. In general it indicates - * a congestion threshold. RTTs above - * this indicate congestion - */ - BPF_SOCK_OPS_RTO_CB, /* Called when an RTO has triggered. - * Arg1: value of icsk_retransmits - * Arg2: value of icsk_rto - * Arg3: whether RTO has expired - */ - BPF_SOCK_OPS_RETRANS_CB, /* Called when skb is retransmitted. - * Arg1: sequence number of 1st byte - * Arg2: # segments - * Arg3: return value of - * tcp_transmit_skb (0 => success) - */ - BPF_SOCK_OPS_STATE_CB, /* Called when TCP changes state. - * Arg1: old_state - * Arg2: new_state - */ - BPF_SOCK_OPS_TCP_LISTEN_CB, /* Called on listen(2), right after - * socket transition to LISTEN state. - */ - BPF_SOCK_OPS_RTT_CB, /* Called on every RTT. - */ + BPF_SOCK_OPS_TIMEOUT_INIT, /* Should return SYN-RTO value to use or + * -1 if default value should be used + */ + BPF_SOCK_OPS_RWND_INIT, /* Should return initial advertized + * window (in packets) or -1 if default + * value should be used + */ + BPF_SOCK_OPS_TCP_CONNECT_CB, /* Calls BPF program right before an + * active connection is initialized + */ + BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, /* Calls BPF program when an + * active connection is + * established + */ + BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB, /* Calls BPF program when a + * passive connection is + * established + */ + BPF_SOCK_OPS_NEEDS_ECN, /* If connection's congestion control + * needs ECN + */ + BPF_SOCK_OPS_BASE_RTT, /* Get base RTT. The correct value is + * based on the path and may be + * dependent on the congestion control + * algorithm. In general it indicates + * a congestion threshold. RTTs above + * this indicate congestion + */ + BPF_SOCK_OPS_RTO_CB, /* Called when an RTO has triggered. + * Arg1: value of icsk_retransmits + * Arg2: value of icsk_rto + * Arg3: whether RTO has expired + */ + BPF_SOCK_OPS_RETRANS_CB, /* Called when skb is retransmitted. + * Arg1: sequence number of 1st byte + * Arg2: # segments + * Arg3: return value of + * tcp_transmit_skb (0 => success) + */ + BPF_SOCK_OPS_STATE_CB, /* Called when TCP changes state. + * Arg1: old_state + * Arg2: new_state + */ + BPF_SOCK_OPS_TCP_LISTEN_CB, /* Called on listen(2), right after + * socket transition to LISTEN state. + */ + BPF_SOCK_OPS_RTT_CB, /* Called on every RTT. + */ }; /* List of TCP states. There is a build check in net/ipv4/tcp.c to detect @@ -3769,15 +3625,15 @@ enum { BPF_TCP_CLOSE_WAIT, BPF_TCP_LAST_ACK, BPF_TCP_LISTEN, - BPF_TCP_CLOSING, /* Now a valid state */ + BPF_TCP_CLOSING, /* Now a valid state */ BPF_TCP_NEW_SYN_RECV, - BPF_TCP_MAX_STATES /* Leave at the end! */ + BPF_TCP_MAX_STATES /* Leave at the end! */ }; enum { - TCP_BPF_IW = 1001, /* Set TCP initial congestion window */ - TCP_BPF_SNDCWND_CLAMP = 1002, /* Set sndcwnd_clamp */ + TCP_BPF_IW = 1001, /* Set TCP initial congestion window */ + TCP_BPF_SNDCWND_CLAMP = 1002, /* Set sndcwnd_clamp */ }; struct bpf_perf_event_value { @@ -3787,14 +3643,14 @@ struct bpf_perf_event_value { }; enum { - BPF_DEVCG_ACC_MKNOD = (1ULL << 0), - BPF_DEVCG_ACC_READ = (1ULL << 1), - BPF_DEVCG_ACC_WRITE = (1ULL << 2), + BPF_DEVCG_ACC_MKNOD = (1ULL << 0), + BPF_DEVCG_ACC_READ = (1ULL << 1), + BPF_DEVCG_ACC_WRITE = (1ULL << 2), }; enum { - BPF_DEVCG_DEV_BLOCK = (1ULL << 0), - BPF_DEVCG_DEV_CHAR = (1ULL << 1), + BPF_DEVCG_DEV_BLOCK = (1ULL << 0), + BPF_DEVCG_DEV_CHAR = (1ULL << 1), }; struct bpf_cgroup_dev_ctx { @@ -3812,8 +3668,8 @@ struct bpf_raw_tracepoint_args { * OUTPUT: Do lookup from egress perspective; default is ingress */ enum { - BPF_FIB_LOOKUP_DIRECT = (1U << 0), - BPF_FIB_LOOKUP_OUTPUT = (1U << 1), + BPF_FIB_LOOKUP_DIRECT = (1U << 0), + BPF_FIB_LOOKUP_OUTPUT = (1U << 1), }; enum { @@ -3832,33 +3688,33 @@ struct bpf_fib_lookup { /* input: network family for lookup (AF_INET, AF_INET6) * output: network family of egress nexthop */ - __u8 family; + __u8 family; /* set if lookup is to consider L4 data - e.g., FIB rules */ - __u8 l4_protocol; - __be16 sport; - __be16 dport; + __u8 l4_protocol; + __be16 sport; + __be16 dport; /* total length of packet from network header - used for MTU check */ - __u16 tot_len; + __u16 tot_len; /* input: L3 device index for lookup * output: device index from FIB lookup */ - __u32 ifindex; + __u32 ifindex; union { /* inputs to lookup */ - __u8 tos; /* AF_INET */ - __be32 flowinfo; /* AF_INET6, flow_label + priority */ + __u8 tos; /* AF_INET */ + __be32 flowinfo; /* AF_INET6, flow_label + priority */ /* output: metric of fib result (IPv4/IPv6 only) */ - __u32 rt_metric; + __u32 rt_metric; }; union { - __be32 ipv4_src; - __u32 ipv6_src[4]; /* in6_addr; network order */ + __be32 ipv4_src; + __u32 ipv6_src[4]; /* in6_addr; network order */ }; /* input to bpf_fib_lookup, ipv{4,6}_dst is destination address in @@ -3866,83 +3722,83 @@ struct bpf_fib_lookup { * if FIB lookup returns gateway route */ union { - __be32 ipv4_dst; - __u32 ipv6_dst[4]; /* in6_addr; network order */ + __be32 ipv4_dst; + __u32 ipv6_dst[4]; /* in6_addr; network order */ }; /* output */ - __be16 h_vlan_proto; - __be16 h_vlan_TCI; - __u8 smac[6]; /* ETH_ALEN */ - __u8 dmac[6]; /* ETH_ALEN */ + __be16 h_vlan_proto; + __be16 h_vlan_TCI; + __u8 smac[6]; /* ETH_ALEN */ + __u8 dmac[6]; /* ETH_ALEN */ }; enum bpf_task_fd_type { - BPF_FD_TYPE_RAW_TRACEPOINT, /* tp name */ - BPF_FD_TYPE_TRACEPOINT, /* tp name */ - BPF_FD_TYPE_KPROBE, /* (symbol + offset) or addr */ - BPF_FD_TYPE_KRETPROBE, /* (symbol + offset) or addr */ - BPF_FD_TYPE_UPROBE, /* filename + offset */ - BPF_FD_TYPE_URETPROBE, /* filename + offset */ + BPF_FD_TYPE_RAW_TRACEPOINT, /* tp name */ + BPF_FD_TYPE_TRACEPOINT, /* tp name */ + BPF_FD_TYPE_KPROBE, /* (symbol + offset) or addr */ + BPF_FD_TYPE_KRETPROBE, /* (symbol + offset) or addr */ + BPF_FD_TYPE_UPROBE, /* filename + offset */ + BPF_FD_TYPE_URETPROBE, /* filename + offset */ }; enum { - BPF_FLOW_DISSECTOR_F_PARSE_1ST_FRAG = (1U << 0), - BPF_FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL = (1U << 1), - BPF_FLOW_DISSECTOR_F_STOP_AT_ENCAP = (1U << 2), + BPF_FLOW_DISSECTOR_F_PARSE_1ST_FRAG = (1U << 0), + BPF_FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL = (1U << 1), + BPF_FLOW_DISSECTOR_F_STOP_AT_ENCAP = (1U << 2), }; struct bpf_flow_keys { - __u16 nhoff; - __u16 thoff; - __u16 addr_proto; /* ETH_P_* of valid addrs */ - __u8 is_frag; - __u8 is_first_frag; - __u8 is_encap; - __u8 ip_proto; - __be16 n_proto; - __be16 sport; - __be16 dport; + __u16 nhoff; + __u16 thoff; + __u16 addr_proto; /* ETH_P_* of valid addrs */ + __u8 is_frag; + __u8 is_first_frag; + __u8 is_encap; + __u8 ip_proto; + __be16 n_proto; + __be16 sport; + __be16 dport; union { struct { - __be32 ipv4_src; - __be32 ipv4_dst; + __be32 ipv4_src; + __be32 ipv4_dst; }; struct { - __u32 ipv6_src[4]; /* in6_addr; network order */ - __u32 ipv6_dst[4]; /* in6_addr; network order */ + __u32 ipv6_src[4]; /* in6_addr; network order */ + __u32 ipv6_dst[4]; /* in6_addr; network order */ }; }; - __u32 flags; - __be32 flow_label; + __u32 flags; + __be32 flow_label; }; struct bpf_func_info { - __u32 insn_off; - __u32 type_id; + __u32 insn_off; + __u32 type_id; }; -#define BPF_LINE_INFO_LINE_NUM(line_col) ((line_col) >> 10) -#define BPF_LINE_INFO_LINE_COL(line_col) ((line_col) & 0x3ff) +#define BPF_LINE_INFO_LINE_NUM(line_col) ((line_col) >> 10) +#define BPF_LINE_INFO_LINE_COL(line_col) ((line_col) & 0x3ff) struct bpf_line_info { - __u32 insn_off; - __u32 file_name_off; - __u32 line_off; - __u32 line_col; + __u32 insn_off; + __u32 file_name_off; + __u32 line_off; + __u32 line_col; }; struct bpf_spin_lock { - __u32 val; + __u32 val; }; struct bpf_sysctl { - __u32 write; /* Sysctl is being read (= 0) or written (= 1). - * Allows 1,2,4-byte read, but no write. - */ - __u32 file_pos; /* Sysctl file position to read from, write to. - * Allows 1,2,4-byte read an 4-byte write. - */ + __u32 write; /* Sysctl is being read (= 0) or written (= 1). + * Allows 1,2,4-byte read, but no write. + */ + __u32 file_pos; /* Sysctl file position to read from, write to. + * Allows 1,2,4-byte read an 4-byte write. + */ }; struct bpf_sockopt { @@ -3950,10 +3806,10 @@ struct bpf_sockopt { __bpf_md_ptr(void *, optval); __bpf_md_ptr(void *, optval_end); - __s32 level; - __s32 optname; - __s32 optlen; - __s32 retval; + __s32 level; + __s32 optname; + __s32 optlen; + __s32 retval; }; struct bpf_pidns_info { diff --git a/userspace/libscap/compat/bpf_common.h b/userspace/libscap/compat/bpf_common.h index ee97668bda..8017da3cac 100644 --- a/userspace/libscap/compat/bpf_common.h +++ b/userspace/libscap/compat/bpf_common.h @@ -4,51 +4,51 @@ /* Instruction classes */ #define BPF_CLASS(code) ((code) & 0x07) -#define BPF_LD 0x00 -#define BPF_LDX 0x01 -#define BPF_ST 0x02 -#define BPF_STX 0x03 -#define BPF_ALU 0x04 -#define BPF_JMP 0x05 -#define BPF_RET 0x06 -#define BPF_MISC 0x07 +#define BPF_LD 0x00 +#define BPF_LDX 0x01 +#define BPF_ST 0x02 +#define BPF_STX 0x03 +#define BPF_ALU 0x04 +#define BPF_JMP 0x05 +#define BPF_RET 0x06 +#define BPF_MISC 0x07 /* ld/ldx fields */ -#define BPF_SIZE(code) ((code) & 0x18) -#define BPF_W 0x00 /* 32-bit */ -#define BPF_H 0x08 /* 16-bit */ -#define BPF_B 0x10 /* 8-bit */ +#define BPF_SIZE(code) ((code) & 0x18) +#define BPF_W 0x00 /* 32-bit */ +#define BPF_H 0x08 /* 16-bit */ +#define BPF_B 0x10 /* 8-bit */ /* eBPF BPF_DW 0x18 64-bit */ -#define BPF_MODE(code) ((code) & 0xe0) -#define BPF_IMM 0x00 -#define BPF_ABS 0x20 -#define BPF_IND 0x40 -#define BPF_MEM 0x60 -#define BPF_LEN 0x80 -#define BPF_MSH 0xa0 +#define BPF_MODE(code) ((code) & 0xe0) +#define BPF_IMM 0x00 +#define BPF_ABS 0x20 +#define BPF_IND 0x40 +#define BPF_MEM 0x60 +#define BPF_LEN 0x80 +#define BPF_MSH 0xa0 /* alu/jmp fields */ -#define BPF_OP(code) ((code) & 0xf0) -#define BPF_ADD 0x00 -#define BPF_SUB 0x10 -#define BPF_MUL 0x20 -#define BPF_DIV 0x30 -#define BPF_OR 0x40 -#define BPF_AND 0x50 -#define BPF_LSH 0x60 -#define BPF_RSH 0x70 -#define BPF_NEG 0x80 -#define BPF_MOD 0x90 -#define BPF_XOR 0xa0 +#define BPF_OP(code) ((code) & 0xf0) +#define BPF_ADD 0x00 +#define BPF_SUB 0x10 +#define BPF_MUL 0x20 +#define BPF_DIV 0x30 +#define BPF_OR 0x40 +#define BPF_AND 0x50 +#define BPF_LSH 0x60 +#define BPF_RSH 0x70 +#define BPF_NEG 0x80 +#define BPF_MOD 0x90 +#define BPF_XOR 0xa0 -#define BPF_JA 0x00 -#define BPF_JEQ 0x10 -#define BPF_JGT 0x20 -#define BPF_JGE 0x30 -#define BPF_JSET 0x40 -#define BPF_SRC(code) ((code) & 0x08) -#define BPF_K 0x00 -#define BPF_X 0x08 +#define BPF_JA 0x00 +#define BPF_JEQ 0x10 +#define BPF_JGT 0x20 +#define BPF_JGE 0x30 +#define BPF_JSET 0x40 +#define BPF_SRC(code) ((code) & 0x08) +#define BPF_K 0x00 +#define BPF_X 0x08 #ifndef BPF_MAXINSNS #define BPF_MAXINSNS 4096 diff --git a/userspace/libscap/compat/misc.h b/userspace/libscap/compat/misc.h index acabe0accd..840e1484fd 100644 --- a/userspace/libscap/compat/misc.h +++ b/userspace/libscap/compat/misc.h @@ -31,8 +31,8 @@ limitations under the License. #endif /* - O_TMPFILE was introduced in Linux >= 3.11 and defined as (__O_TMPFILE | O_DIRECTORY). - To maintain compatiblity with different build environments, the below is added. + O_TMPFILE was introduced in Linux >= 3.11 and defined as (__O_TMPFILE | O_DIRECTORY). + To maintain compatiblity with different build environments, the below is added. */ #ifndef O_TMPFILE #define O_TMPFILE 020200000 diff --git a/userspace/libscap/compat/perf_event.h b/userspace/libscap/compat/perf_event.h index 70f005fc97..d52f6aa6bb 100644 --- a/userspace/libscap/compat/perf_event.h +++ b/userspace/libscap/compat/perf_event.h @@ -27,14 +27,14 @@ * attr.type */ enum perf_type_id { - PERF_TYPE_HARDWARE = 0, - PERF_TYPE_SOFTWARE = 1, - PERF_TYPE_TRACEPOINT = 2, - PERF_TYPE_HW_CACHE = 3, - PERF_TYPE_RAW = 4, - PERF_TYPE_BREAKPOINT = 5, - - PERF_TYPE_MAX, /* non-ABI */ + PERF_TYPE_HARDWARE = 0, + PERF_TYPE_SOFTWARE = 1, + PERF_TYPE_TRACEPOINT = 2, + PERF_TYPE_HW_CACHE = 3, + PERF_TYPE_RAW = 4, + PERF_TYPE_BREAKPOINT = 5, + + PERF_TYPE_MAX, /* non-ABI */ }; /* @@ -46,18 +46,18 @@ enum perf_hw_id { /* * Common hardware events, generalized by the kernel: */ - PERF_COUNT_HW_CPU_CYCLES = 0, - PERF_COUNT_HW_INSTRUCTIONS = 1, - PERF_COUNT_HW_CACHE_REFERENCES = 2, - PERF_COUNT_HW_CACHE_MISSES = 3, - PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4, - PERF_COUNT_HW_BRANCH_MISSES = 5, - PERF_COUNT_HW_BUS_CYCLES = 6, - PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7, - PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8, - PERF_COUNT_HW_REF_CPU_CYCLES = 9, - - PERF_COUNT_HW_MAX, /* non-ABI */ + PERF_COUNT_HW_CPU_CYCLES = 0, + PERF_COUNT_HW_INSTRUCTIONS = 1, + PERF_COUNT_HW_CACHE_REFERENCES = 2, + PERF_COUNT_HW_CACHE_MISSES = 3, + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4, + PERF_COUNT_HW_BRANCH_MISSES = 5, + PERF_COUNT_HW_BUS_CYCLES = 6, + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7, + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8, + PERF_COUNT_HW_REF_CPU_CYCLES = 9, + + PERF_COUNT_HW_MAX, /* non-ABI */ }; /* @@ -68,30 +68,30 @@ enum perf_hw_id { * { accesses, misses } */ enum perf_hw_cache_id { - PERF_COUNT_HW_CACHE_L1D = 0, - PERF_COUNT_HW_CACHE_L1I = 1, - PERF_COUNT_HW_CACHE_LL = 2, - PERF_COUNT_HW_CACHE_DTLB = 3, - PERF_COUNT_HW_CACHE_ITLB = 4, - PERF_COUNT_HW_CACHE_BPU = 5, - PERF_COUNT_HW_CACHE_NODE = 6, - - PERF_COUNT_HW_CACHE_MAX, /* non-ABI */ + PERF_COUNT_HW_CACHE_L1D = 0, + PERF_COUNT_HW_CACHE_L1I = 1, + PERF_COUNT_HW_CACHE_LL = 2, + PERF_COUNT_HW_CACHE_DTLB = 3, + PERF_COUNT_HW_CACHE_ITLB = 4, + PERF_COUNT_HW_CACHE_BPU = 5, + PERF_COUNT_HW_CACHE_NODE = 6, + + PERF_COUNT_HW_CACHE_MAX, /* non-ABI */ }; enum perf_hw_cache_op_id { - PERF_COUNT_HW_CACHE_OP_READ = 0, - PERF_COUNT_HW_CACHE_OP_WRITE = 1, - PERF_COUNT_HW_CACHE_OP_PREFETCH = 2, + PERF_COUNT_HW_CACHE_OP_READ = 0, + PERF_COUNT_HW_CACHE_OP_WRITE = 1, + PERF_COUNT_HW_CACHE_OP_PREFETCH = 2, - PERF_COUNT_HW_CACHE_OP_MAX, /* non-ABI */ + PERF_COUNT_HW_CACHE_OP_MAX, /* non-ABI */ }; enum perf_hw_cache_op_result_id { - PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0, - PERF_COUNT_HW_CACHE_RESULT_MISS = 1, + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0, + PERF_COUNT_HW_CACHE_RESULT_MISS = 1, - PERF_COUNT_HW_CACHE_RESULT_MAX, /* non-ABI */ + PERF_COUNT_HW_CACHE_RESULT_MAX, /* non-ABI */ }; /* @@ -101,19 +101,19 @@ enum perf_hw_cache_op_result_id { * well): */ enum perf_sw_ids { - PERF_COUNT_SW_CPU_CLOCK = 0, - PERF_COUNT_SW_TASK_CLOCK = 1, - PERF_COUNT_SW_PAGE_FAULTS = 2, - PERF_COUNT_SW_CONTEXT_SWITCHES = 3, - PERF_COUNT_SW_CPU_MIGRATIONS = 4, - PERF_COUNT_SW_PAGE_FAULTS_MIN = 5, - PERF_COUNT_SW_PAGE_FAULTS_MAJ = 6, - PERF_COUNT_SW_ALIGNMENT_FAULTS = 7, - PERF_COUNT_SW_EMULATION_FAULTS = 8, - PERF_COUNT_SW_DUMMY = 9, - PERF_COUNT_SW_BPF_OUTPUT = 10, - - PERF_COUNT_SW_MAX, /* non-ABI */ + PERF_COUNT_SW_CPU_CLOCK = 0, + PERF_COUNT_SW_TASK_CLOCK = 1, + PERF_COUNT_SW_PAGE_FAULTS = 2, + PERF_COUNT_SW_CONTEXT_SWITCHES = 3, + PERF_COUNT_SW_CPU_MIGRATIONS = 4, + PERF_COUNT_SW_PAGE_FAULTS_MIN = 5, + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 6, + PERF_COUNT_SW_ALIGNMENT_FAULTS = 7, + PERF_COUNT_SW_EMULATION_FAULTS = 8, + PERF_COUNT_SW_DUMMY = 9, + PERF_COUNT_SW_BPF_OUTPUT = 10, + + PERF_COUNT_SW_MAX, /* non-ABI */ }; /* @@ -121,30 +121,30 @@ enum perf_sw_ids { * in the overflow packets. */ enum perf_event_sample_format { - PERF_SAMPLE_IP = 1U << 0, - PERF_SAMPLE_TID = 1U << 1, - PERF_SAMPLE_TIME = 1U << 2, - PERF_SAMPLE_ADDR = 1U << 3, - PERF_SAMPLE_READ = 1U << 4, - PERF_SAMPLE_CALLCHAIN = 1U << 5, - PERF_SAMPLE_ID = 1U << 6, - PERF_SAMPLE_CPU = 1U << 7, - PERF_SAMPLE_PERIOD = 1U << 8, - PERF_SAMPLE_STREAM_ID = 1U << 9, - PERF_SAMPLE_RAW = 1U << 10, - PERF_SAMPLE_BRANCH_STACK = 1U << 11, - PERF_SAMPLE_REGS_USER = 1U << 12, - PERF_SAMPLE_STACK_USER = 1U << 13, - PERF_SAMPLE_WEIGHT = 1U << 14, - PERF_SAMPLE_DATA_SRC = 1U << 15, - PERF_SAMPLE_IDENTIFIER = 1U << 16, - PERF_SAMPLE_TRANSACTION = 1U << 17, - PERF_SAMPLE_REGS_INTR = 1U << 18, - PERF_SAMPLE_PHYS_ADDR = 1U << 19, - - PERF_SAMPLE_MAX = 1U << 20, /* non-ABI */ - - __PERF_SAMPLE_CALLCHAIN_EARLY = 1ULL << 63, /* non-ABI; internal use */ + PERF_SAMPLE_IP = 1U << 0, + PERF_SAMPLE_TID = 1U << 1, + PERF_SAMPLE_TIME = 1U << 2, + PERF_SAMPLE_ADDR = 1U << 3, + PERF_SAMPLE_READ = 1U << 4, + PERF_SAMPLE_CALLCHAIN = 1U << 5, + PERF_SAMPLE_ID = 1U << 6, + PERF_SAMPLE_CPU = 1U << 7, + PERF_SAMPLE_PERIOD = 1U << 8, + PERF_SAMPLE_STREAM_ID = 1U << 9, + PERF_SAMPLE_RAW = 1U << 10, + PERF_SAMPLE_BRANCH_STACK = 1U << 11, + PERF_SAMPLE_REGS_USER = 1U << 12, + PERF_SAMPLE_STACK_USER = 1U << 13, + PERF_SAMPLE_WEIGHT = 1U << 14, + PERF_SAMPLE_DATA_SRC = 1U << 15, + PERF_SAMPLE_IDENTIFIER = 1U << 16, + PERF_SAMPLE_TRANSACTION = 1U << 17, + PERF_SAMPLE_REGS_INTR = 1U << 18, + PERF_SAMPLE_PHYS_ADDR = 1U << 19, + + PERF_SAMPLE_MAX = 1U << 20, /* non-ABI */ + + __PERF_SAMPLE_CALLCHAIN_EARLY = 1ULL << 63, /* non-ABI; internal use */ }; /* @@ -158,88 +158,85 @@ enum perf_event_sample_format { * of branches and therefore it supersedes all the other types. */ enum perf_branch_sample_type_shift { - PERF_SAMPLE_BRANCH_USER_SHIFT = 0, /* user branches */ - PERF_SAMPLE_BRANCH_KERNEL_SHIFT = 1, /* kernel branches */ - PERF_SAMPLE_BRANCH_HV_SHIFT = 2, /* hypervisor branches */ + PERF_SAMPLE_BRANCH_USER_SHIFT = 0, /* user branches */ + PERF_SAMPLE_BRANCH_KERNEL_SHIFT = 1, /* kernel branches */ + PERF_SAMPLE_BRANCH_HV_SHIFT = 2, /* hypervisor branches */ - PERF_SAMPLE_BRANCH_ANY_SHIFT = 3, /* any branch types */ - PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT = 4, /* any call branch */ - PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT = 5, /* any return branch */ - PERF_SAMPLE_BRANCH_IND_CALL_SHIFT = 6, /* indirect calls */ - PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT = 7, /* transaction aborts */ - PERF_SAMPLE_BRANCH_IN_TX_SHIFT = 8, /* in transaction */ - PERF_SAMPLE_BRANCH_NO_TX_SHIFT = 9, /* not in transaction */ - PERF_SAMPLE_BRANCH_COND_SHIFT = 10, /* conditional branches */ + PERF_SAMPLE_BRANCH_ANY_SHIFT = 3, /* any branch types */ + PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT = 4, /* any call branch */ + PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT = 5, /* any return branch */ + PERF_SAMPLE_BRANCH_IND_CALL_SHIFT = 6, /* indirect calls */ + PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT = 7, /* transaction aborts */ + PERF_SAMPLE_BRANCH_IN_TX_SHIFT = 8, /* in transaction */ + PERF_SAMPLE_BRANCH_NO_TX_SHIFT = 9, /* not in transaction */ + PERF_SAMPLE_BRANCH_COND_SHIFT = 10, /* conditional branches */ - PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT = 11, /* call/ret stack */ - PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT = 12, /* indirect jumps */ - PERF_SAMPLE_BRANCH_CALL_SHIFT = 13, /* direct call */ + PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT = 11, /* call/ret stack */ + PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT = 12, /* indirect jumps */ + PERF_SAMPLE_BRANCH_CALL_SHIFT = 13, /* direct call */ - PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT = 14, /* no flags */ - PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT = 15, /* no cycles */ + PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT = 14, /* no flags */ + PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT = 15, /* no cycles */ - PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT = 16, /* save branch type */ + PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT = 16, /* save branch type */ - PERF_SAMPLE_BRANCH_MAX_SHIFT /* non-ABI */ + PERF_SAMPLE_BRANCH_MAX_SHIFT /* non-ABI */ }; enum perf_branch_sample_type { - PERF_SAMPLE_BRANCH_USER = 1U << PERF_SAMPLE_BRANCH_USER_SHIFT, - PERF_SAMPLE_BRANCH_KERNEL = 1U << PERF_SAMPLE_BRANCH_KERNEL_SHIFT, - PERF_SAMPLE_BRANCH_HV = 1U << PERF_SAMPLE_BRANCH_HV_SHIFT, - - PERF_SAMPLE_BRANCH_ANY = 1U << PERF_SAMPLE_BRANCH_ANY_SHIFT, - PERF_SAMPLE_BRANCH_ANY_CALL = 1U << PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT, - PERF_SAMPLE_BRANCH_ANY_RETURN = 1U << PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT, - PERF_SAMPLE_BRANCH_IND_CALL = 1U << PERF_SAMPLE_BRANCH_IND_CALL_SHIFT, - PERF_SAMPLE_BRANCH_ABORT_TX = 1U << PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT, - PERF_SAMPLE_BRANCH_IN_TX = 1U << PERF_SAMPLE_BRANCH_IN_TX_SHIFT, - PERF_SAMPLE_BRANCH_NO_TX = 1U << PERF_SAMPLE_BRANCH_NO_TX_SHIFT, - PERF_SAMPLE_BRANCH_COND = 1U << PERF_SAMPLE_BRANCH_COND_SHIFT, - - PERF_SAMPLE_BRANCH_CALL_STACK = 1U << PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT, - PERF_SAMPLE_BRANCH_IND_JUMP = 1U << PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT, - PERF_SAMPLE_BRANCH_CALL = 1U << PERF_SAMPLE_BRANCH_CALL_SHIFT, - - PERF_SAMPLE_BRANCH_NO_FLAGS = 1U << PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT, - PERF_SAMPLE_BRANCH_NO_CYCLES = 1U << PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT, - - PERF_SAMPLE_BRANCH_TYPE_SAVE = - 1U << PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT, - - PERF_SAMPLE_BRANCH_MAX = 1U << PERF_SAMPLE_BRANCH_MAX_SHIFT, + PERF_SAMPLE_BRANCH_USER = 1U << PERF_SAMPLE_BRANCH_USER_SHIFT, + PERF_SAMPLE_BRANCH_KERNEL = 1U << PERF_SAMPLE_BRANCH_KERNEL_SHIFT, + PERF_SAMPLE_BRANCH_HV = 1U << PERF_SAMPLE_BRANCH_HV_SHIFT, + + PERF_SAMPLE_BRANCH_ANY = 1U << PERF_SAMPLE_BRANCH_ANY_SHIFT, + PERF_SAMPLE_BRANCH_ANY_CALL = 1U << PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT, + PERF_SAMPLE_BRANCH_ANY_RETURN = 1U << PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT, + PERF_SAMPLE_BRANCH_IND_CALL = 1U << PERF_SAMPLE_BRANCH_IND_CALL_SHIFT, + PERF_SAMPLE_BRANCH_ABORT_TX = 1U << PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT, + PERF_SAMPLE_BRANCH_IN_TX = 1U << PERF_SAMPLE_BRANCH_IN_TX_SHIFT, + PERF_SAMPLE_BRANCH_NO_TX = 1U << PERF_SAMPLE_BRANCH_NO_TX_SHIFT, + PERF_SAMPLE_BRANCH_COND = 1U << PERF_SAMPLE_BRANCH_COND_SHIFT, + + PERF_SAMPLE_BRANCH_CALL_STACK = 1U << PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT, + PERF_SAMPLE_BRANCH_IND_JUMP = 1U << PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT, + PERF_SAMPLE_BRANCH_CALL = 1U << PERF_SAMPLE_BRANCH_CALL_SHIFT, + + PERF_SAMPLE_BRANCH_NO_FLAGS = 1U << PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT, + PERF_SAMPLE_BRANCH_NO_CYCLES = 1U << PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT, + + PERF_SAMPLE_BRANCH_TYPE_SAVE = 1U << PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT, + + PERF_SAMPLE_BRANCH_MAX = 1U << PERF_SAMPLE_BRANCH_MAX_SHIFT, }; /* * Common flow change classification */ enum { - PERF_BR_UNKNOWN = 0, /* unknown */ - PERF_BR_COND = 1, /* conditional */ - PERF_BR_UNCOND = 2, /* unconditional */ - PERF_BR_IND = 3, /* indirect */ - PERF_BR_CALL = 4, /* function call */ - PERF_BR_IND_CALL = 5, /* indirect function call */ - PERF_BR_RET = 6, /* function return */ - PERF_BR_SYSCALL = 7, /* syscall */ - PERF_BR_SYSRET = 8, /* syscall return */ - PERF_BR_COND_CALL = 9, /* conditional function call */ - PERF_BR_COND_RET = 10, /* conditional function return */ + PERF_BR_UNKNOWN = 0, /* unknown */ + PERF_BR_COND = 1, /* conditional */ + PERF_BR_UNCOND = 2, /* unconditional */ + PERF_BR_IND = 3, /* indirect */ + PERF_BR_CALL = 4, /* function call */ + PERF_BR_IND_CALL = 5, /* indirect function call */ + PERF_BR_RET = 6, /* function return */ + PERF_BR_SYSCALL = 7, /* syscall */ + PERF_BR_SYSRET = 8, /* syscall return */ + PERF_BR_COND_CALL = 9, /* conditional function call */ + PERF_BR_COND_RET = 10, /* conditional function return */ PERF_BR_MAX, }; #define PERF_SAMPLE_BRANCH_PLM_ALL \ - (PERF_SAMPLE_BRANCH_USER|\ - PERF_SAMPLE_BRANCH_KERNEL|\ - PERF_SAMPLE_BRANCH_HV) + (PERF_SAMPLE_BRANCH_USER | PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_HV) /* * Values to determine ABI of the registers dump. */ enum perf_sample_regs_abi { - PERF_SAMPLE_REGS_ABI_NONE = 0, - PERF_SAMPLE_REGS_ABI_32 = 1, - PERF_SAMPLE_REGS_ABI_64 = 2, + PERF_SAMPLE_REGS_ABI_NONE = 0, + PERF_SAMPLE_REGS_ABI_32 = 1, + PERF_SAMPLE_REGS_ABI_64 = 2, }; /* @@ -247,20 +244,20 @@ enum perf_sample_regs_abi { * abort events. Multiple bits can be set. */ enum { - PERF_TXN_ELISION = (1 << 0), /* From elision */ - PERF_TXN_TRANSACTION = (1 << 1), /* From transaction */ - PERF_TXN_SYNC = (1 << 2), /* Instruction is related */ - PERF_TXN_ASYNC = (1 << 3), /* Instruction not related */ - PERF_TXN_RETRY = (1 << 4), /* Retry possible */ - PERF_TXN_CONFLICT = (1 << 5), /* Conflict abort */ + PERF_TXN_ELISION = (1 << 0), /* From elision */ + PERF_TXN_TRANSACTION = (1 << 1), /* From transaction */ + PERF_TXN_SYNC = (1 << 2), /* Instruction is related */ + PERF_TXN_ASYNC = (1 << 3), /* Instruction not related */ + PERF_TXN_RETRY = (1 << 4), /* Retry possible */ + PERF_TXN_CONFLICT = (1 << 5), /* Conflict abort */ PERF_TXN_CAPACITY_WRITE = (1 << 6), /* Capacity write abort */ - PERF_TXN_CAPACITY_READ = (1 << 7), /* Capacity read abort */ + PERF_TXN_CAPACITY_READ = (1 << 7), /* Capacity read abort */ - PERF_TXN_MAX = (1 << 8), /* non-ABI */ + PERF_TXN_MAX = (1 << 8), /* non-ABI */ /* bits 32..63 are reserved for the abort code */ - PERF_TXN_ABORT_MASK = (0xffffffffULL << 32), + PERF_TXN_ABORT_MASK = (0xffffffffULL << 32), PERF_TXN_ABORT_SHIFT = 32, }; @@ -285,21 +282,21 @@ enum { * }; */ enum perf_event_read_format { - PERF_FORMAT_TOTAL_TIME_ENABLED = 1U << 0, - PERF_FORMAT_TOTAL_TIME_RUNNING = 1U << 1, - PERF_FORMAT_ID = 1U << 2, - PERF_FORMAT_GROUP = 1U << 3, + PERF_FORMAT_TOTAL_TIME_ENABLED = 1U << 0, + PERF_FORMAT_TOTAL_TIME_RUNNING = 1U << 1, + PERF_FORMAT_ID = 1U << 2, + PERF_FORMAT_GROUP = 1U << 3, - PERF_FORMAT_MAX = 1U << 4, /* non-ABI */ + PERF_FORMAT_MAX = 1U << 4, /* non-ABI */ }; -#define PERF_ATTR_SIZE_VER0 64 /* sizeof first published struct */ -#define PERF_ATTR_SIZE_VER1 72 /* add: config2 */ -#define PERF_ATTR_SIZE_VER2 80 /* add: branch_sample_type */ -#define PERF_ATTR_SIZE_VER3 96 /* add: sample_regs_user */ - /* add: sample_stack_user */ -#define PERF_ATTR_SIZE_VER4 104 /* add: sample_regs_intr */ -#define PERF_ATTR_SIZE_VER5 112 /* add: aux_watermark */ +#define PERF_ATTR_SIZE_VER0 64 /* sizeof first published struct */ +#define PERF_ATTR_SIZE_VER1 72 /* add: config2 */ +#define PERF_ATTR_SIZE_VER2 80 /* add: branch_sample_type */ +#define PERF_ATTR_SIZE_VER3 96 /* add: sample_regs_user */ + /* add: sample_stack_user */ +#define PERF_ATTR_SIZE_VER4 104 /* add: sample_regs_intr */ +#define PERF_ATTR_SIZE_VER5 112 /* add: aux_watermark */ /* * Hardware event_id to monitor via a performance monitoring event: @@ -308,104 +305,103 @@ enum perf_event_read_format { * should be < /proc/sys/kernel/perf_event_max_stack */ struct perf_event_attr { - /* * Major type: hardware/software/tracepoint/etc. */ - __u32 type; + __u32 type; /* * Size of the attr structure, for fwd/bwd compat. */ - __u32 size; + __u32 size; /* * Type specific configuration information. */ - __u64 config; + __u64 config; union { - __u64 sample_period; - __u64 sample_freq; + __u64 sample_period; + __u64 sample_freq; }; - __u64 sample_type; - __u64 read_format; - - __u64 disabled : 1, /* off by default */ - inherit : 1, /* children inherit it */ - pinned : 1, /* must always be on PMU */ - exclusive : 1, /* only group on PMU */ - exclude_user : 1, /* don't count user */ - exclude_kernel : 1, /* ditto kernel */ - exclude_hv : 1, /* ditto hypervisor */ - exclude_idle : 1, /* don't count when idle */ - mmap : 1, /* include mmap data */ - comm : 1, /* include comm data */ - freq : 1, /* use freq, not period */ - inherit_stat : 1, /* per task counts */ - enable_on_exec : 1, /* next exec enables */ - task : 1, /* trace fork/exit */ - watermark : 1, /* wakeup_watermark */ - /* - * precise_ip: - * - * 0 - SAMPLE_IP can have arbitrary skid - * 1 - SAMPLE_IP must have constant skid - * 2 - SAMPLE_IP requested to have 0 skid - * 3 - SAMPLE_IP must have 0 skid - * - * See also PERF_RECORD_MISC_EXACT_IP - */ - precise_ip : 2, /* skid constraint */ - mmap_data : 1, /* non-exec mmap data */ - sample_id_all : 1, /* sample_type all events */ - - exclude_host : 1, /* don't count in host */ - exclude_guest : 1, /* don't count in guest */ - - exclude_callchain_kernel : 1, /* exclude kernel callchains */ - exclude_callchain_user : 1, /* exclude user callchains */ - mmap2 : 1, /* include mmap with inode data */ - comm_exec : 1, /* flag comm events that are due to an exec */ - use_clockid : 1, /* use @clockid for time fields */ - context_switch : 1, /* context switch data */ - write_backward : 1, /* Write ring buffer from end to beginning */ - namespaces : 1, /* include namespaces data */ - __reserved_1 : 35; + __u64 sample_type; + __u64 read_format; + + __u64 disabled : 1, /* off by default */ + inherit : 1, /* children inherit it */ + pinned : 1, /* must always be on PMU */ + exclusive : 1, /* only group on PMU */ + exclude_user : 1, /* don't count user */ + exclude_kernel : 1, /* ditto kernel */ + exclude_hv : 1, /* ditto hypervisor */ + exclude_idle : 1, /* don't count when idle */ + mmap : 1, /* include mmap data */ + comm : 1, /* include comm data */ + freq : 1, /* use freq, not period */ + inherit_stat : 1, /* per task counts */ + enable_on_exec : 1, /* next exec enables */ + task : 1, /* trace fork/exit */ + watermark : 1, /* wakeup_watermark */ + /* + * precise_ip: + * + * 0 - SAMPLE_IP can have arbitrary skid + * 1 - SAMPLE_IP must have constant skid + * 2 - SAMPLE_IP requested to have 0 skid + * 3 - SAMPLE_IP must have 0 skid + * + * See also PERF_RECORD_MISC_EXACT_IP + */ + precise_ip : 2, /* skid constraint */ + mmap_data : 1, /* non-exec mmap data */ + sample_id_all : 1, /* sample_type all events */ + + exclude_host : 1, /* don't count in host */ + exclude_guest : 1, /* don't count in guest */ + + exclude_callchain_kernel : 1, /* exclude kernel callchains */ + exclude_callchain_user : 1, /* exclude user callchains */ + mmap2 : 1, /* include mmap with inode data */ + comm_exec : 1, /* flag comm events that are due to an exec */ + use_clockid : 1, /* use @clockid for time fields */ + context_switch : 1, /* context switch data */ + write_backward : 1, /* Write ring buffer from end to beginning */ + namespaces : 1, /* include namespaces data */ + __reserved_1 : 35; union { - __u32 wakeup_events; /* wakeup every n events */ - __u32 wakeup_watermark; /* bytes before wakeup */ + __u32 wakeup_events; /* wakeup every n events */ + __u32 wakeup_watermark; /* bytes before wakeup */ }; - __u32 bp_type; + __u32 bp_type; union { - __u64 bp_addr; - __u64 kprobe_func; /* for perf_kprobe */ - __u64 uprobe_path; /* for perf_uprobe */ - __u64 config1; /* extension of config */ + __u64 bp_addr; + __u64 kprobe_func; /* for perf_kprobe */ + __u64 uprobe_path; /* for perf_uprobe */ + __u64 config1; /* extension of config */ }; union { - __u64 bp_len; - __u64 kprobe_addr; /* when kprobe_func == NULL */ - __u64 probe_offset; /* for perf_[k,u]probe */ - __u64 config2; /* extension of config1 */ + __u64 bp_len; + __u64 kprobe_addr; /* when kprobe_func == NULL */ + __u64 probe_offset; /* for perf_[k,u]probe */ + __u64 config2; /* extension of config1 */ }; - __u64 branch_sample_type; /* enum perf_branch_sample_type */ + __u64 branch_sample_type; /* enum perf_branch_sample_type */ /* * Defines set of user regs to dump on samples. * See asm/perf_regs.h for details. */ - __u64 sample_regs_user; + __u64 sample_regs_user; /* * Defines size of the user stack to dump on samples. */ - __u32 sample_stack_user; + __u32 sample_stack_user; - __s32 clockid; + __s32 clockid; /* * Defines set of regs to dump for each sample * state captured on: @@ -414,14 +410,14 @@ struct perf_event_attr { * * See asm/perf_regs.h for details. */ - __u64 sample_regs_intr; + __u64 sample_regs_intr; /* * Wakeup watermark for AUX area */ - __u32 aux_watermark; - __u16 sample_max_stack; - __u16 __reserved_2; /* align to __u64 */ + __u32 aux_watermark; + __u16 sample_max_stack; + __u16 __reserved_2; /* align to __u64 */ }; /* @@ -433,46 +429,46 @@ struct perf_event_query_bpf { /* * The below ids array length */ - __u32 ids_len; + __u32 ids_len; /* * Set by the kernel to indicate the number of * available programs */ - __u32 prog_cnt; + __u32 prog_cnt; /* * User provided buffer to store program ids */ - __u32 ids[0]; + __u32 ids[0]; }; -#define perf_flags(attr) (*(&(attr)->read_format + 1)) +#define perf_flags(attr) (*(&(attr)->read_format + 1)) /* * Ioctls that can be done on a perf event fd: */ -#define PERF_EVENT_IOC_ENABLE _IO ('$', 0) -#define PERF_EVENT_IOC_DISABLE _IO ('$', 1) -#define PERF_EVENT_IOC_REFRESH _IO ('$', 2) -#define PERF_EVENT_IOC_RESET _IO ('$', 3) -#define PERF_EVENT_IOC_PERIOD _IOW('$', 4, __u64) -#define PERF_EVENT_IOC_SET_OUTPUT _IO ('$', 5) -#define PERF_EVENT_IOC_SET_FILTER _IOW('$', 6, char *) -#define PERF_EVENT_IOC_ID _IOR('$', 7, __u64 *) -#define PERF_EVENT_IOC_SET_BPF _IOW('$', 8, __u32) -#define PERF_EVENT_IOC_PAUSE_OUTPUT _IOW('$', 9, __u32) -#define PERF_EVENT_IOC_QUERY_BPF _IOWR('$', 10, struct perf_event_query_bpf *) -#define PERF_EVENT_IOC_MODIFY_ATTRIBUTES _IOW('$', 11, struct perf_event_attr *) +#define PERF_EVENT_IOC_ENABLE _IO('$', 0) +#define PERF_EVENT_IOC_DISABLE _IO('$', 1) +#define PERF_EVENT_IOC_REFRESH _IO('$', 2) +#define PERF_EVENT_IOC_RESET _IO('$', 3) +#define PERF_EVENT_IOC_PERIOD _IOW('$', 4, __u64) +#define PERF_EVENT_IOC_SET_OUTPUT _IO('$', 5) +#define PERF_EVENT_IOC_SET_FILTER _IOW('$', 6, char *) +#define PERF_EVENT_IOC_ID _IOR('$', 7, __u64 *) +#define PERF_EVENT_IOC_SET_BPF _IOW('$', 8, __u32) +#define PERF_EVENT_IOC_PAUSE_OUTPUT _IOW('$', 9, __u32) +#define PERF_EVENT_IOC_QUERY_BPF _IOWR('$', 10, struct perf_event_query_bpf *) +#define PERF_EVENT_IOC_MODIFY_ATTRIBUTES _IOW('$', 11, struct perf_event_attr *) enum perf_event_ioc_flags { - PERF_IOC_FLAG_GROUP = 1U << 0, + PERF_IOC_FLAG_GROUP = 1U << 0, }; /* * Structure of the page that can be mapped via mmap */ struct perf_event_mmap_page { - __u32 version; /* version number of this structure */ - __u32 compat_version; /* lowest version this is compat with */ + __u32 version; /* version number of this structure */ + __u32 compat_version; /* lowest version this is compat with */ /* * Bits needed to read the hw events in user-space. @@ -509,21 +505,21 @@ struct perf_event_mmap_page { * NOTE: for obvious reason this only works on self-monitoring * processes. */ - __u32 lock; /* seqlock for synchronization */ - __u32 index; /* hardware event identifier */ - __s64 offset; /* add to hardware event value */ - __u64 time_enabled; /* time event active */ - __u64 time_running; /* time event on cpu */ + __u32 lock; /* seqlock for synchronization */ + __u32 index; /* hardware event identifier */ + __s64 offset; /* add to hardware event value */ + __u64 time_enabled; /* time event active */ + __u64 time_running; /* time event on cpu */ union { - __u64 capabilities; + __u64 capabilities; struct { - __u64 cap_bit0 : 1, /* Always 0, deprecated, see commit 860f085b74e9 */ - cap_bit0_is_deprecated : 1, /* Always 1, signals that bit 0 is zero */ + __u64 cap_bit0 : 1, /* Always 0, deprecated, see commit 860f085b74e9 */ + cap_bit0_is_deprecated : 1, /* Always 1, signals that bit 0 is zero */ - cap_user_rdpmc : 1, /* The RDPMC instruction can be used to read counts */ - cap_user_time : 1, /* The time_* fields are used */ - cap_user_time_zero : 1, /* The time_zero field is used */ - cap_____res : 59; + cap_user_rdpmc : 1, /* The RDPMC instruction can be used to read counts */ + cap_user_time : 1, /* The time_* fields are used */ + cap_user_time_zero : 1, /* The time_zero field is used */ + cap_____res : 59; }; }; @@ -536,7 +532,7 @@ struct perf_event_mmap_page { * pmc >>= 64 - width; // signed shift right * count += pmc; */ - __u16 pmc_width; + __u16 pmc_width; /* * If cap_usr_time the below fields can be used to compute the time @@ -562,9 +558,9 @@ struct perf_event_mmap_page { * rem = count % running; * count = quot * enabled + (rem * enabled) / running; */ - __u16 time_shift; - __u32 time_mult; - __u64 time_offset; + __u16 time_shift; + __u32 time_mult; + __u64 time_offset; /* * If cap_usr_time_zero, the hardware clock (e.g. TSC) can be calculated * from sample timestamps. @@ -581,14 +577,14 @@ struct perf_event_mmap_page { * timestamp = time_zero + quot * time_mult + * ((rem * time_mult) >> time_shift); */ - __u64 time_zero; - __u32 size; /* Header size up to __reserved[] fields. */ + __u64 time_zero; + __u32 size; /* Header size up to __reserved[] fields. */ - /* - * Hole for extension of the self monitor capabilities - */ + /* + * Hole for extension of the self monitor capabilities + */ - __u8 __reserved[118*8+4]; /* align to 1k. */ + __u8 __reserved[118 * 8 + 4]; /* align to 1k. */ /* * Control data for the mmap() data buffer. @@ -606,10 +602,10 @@ struct perf_event_mmap_page { * data_{offset,size} indicate the location and size of the perf record * buffer within the mmapped area. */ - __u64 data_head; /* head in the data section */ - __u64 data_tail; /* user-space written tail */ - __u64 data_offset; /* where the buffer starts */ - __u64 data_size; /* data buffer size */ + __u64 data_head; /* head in the data section */ + __u64 data_tail; /* user-space written tail */ + __u64 data_offset; /* where the buffer starts */ + __u64 data_size; /* data buffer size */ /* * AUX area is defined by aux_{offset,size} fields that should be set @@ -622,24 +618,24 @@ struct perf_event_mmap_page { * Ring buffer pointers aux_{head,tail} have the same semantics as * data_{head,tail} and same ordering rules apply. */ - __u64 aux_head; - __u64 aux_tail; - __u64 aux_offset; - __u64 aux_size; + __u64 aux_head; + __u64 aux_tail; + __u64 aux_offset; + __u64 aux_size; }; -#define PERF_RECORD_MISC_CPUMODE_MASK (7 << 0) -#define PERF_RECORD_MISC_CPUMODE_UNKNOWN (0 << 0) -#define PERF_RECORD_MISC_KERNEL (1 << 0) -#define PERF_RECORD_MISC_USER (2 << 0) -#define PERF_RECORD_MISC_HYPERVISOR (3 << 0) -#define PERF_RECORD_MISC_GUEST_KERNEL (4 << 0) -#define PERF_RECORD_MISC_GUEST_USER (5 << 0) +#define PERF_RECORD_MISC_CPUMODE_MASK (7 << 0) +#define PERF_RECORD_MISC_CPUMODE_UNKNOWN (0 << 0) +#define PERF_RECORD_MISC_KERNEL (1 << 0) +#define PERF_RECORD_MISC_USER (2 << 0) +#define PERF_RECORD_MISC_HYPERVISOR (3 << 0) +#define PERF_RECORD_MISC_GUEST_KERNEL (4 << 0) +#define PERF_RECORD_MISC_GUEST_USER (5 << 0) /* * Indicates that /proc/PID/maps parsing are truncated by time out. */ -#define PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT (1 << 12) +#define PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT (1 << 12) /* * Following PERF_RECORD_MISC_* are used on different * events, so can reuse the same bit position: @@ -648,9 +644,9 @@ struct perf_event_mmap_page { * PERF_RECORD_MISC_COMM_EXEC - PERF_RECORD_COMM event * PERF_RECORD_MISC_SWITCH_OUT - PERF_RECORD_SWITCH* events */ -#define PERF_RECORD_MISC_MMAP_DATA (1 << 13) -#define PERF_RECORD_MISC_COMM_EXEC (1 << 13) -#define PERF_RECORD_MISC_SWITCH_OUT (1 << 13) +#define PERF_RECORD_MISC_MMAP_DATA (1 << 13) +#define PERF_RECORD_MISC_COMM_EXEC (1 << 13) +#define PERF_RECORD_MISC_SWITCH_OUT (1 << 13) /* * These PERF_RECORD_MISC_* flags below are safely reused * for the following events: @@ -667,34 +663,34 @@ struct perf_event_mmap_page { * PERF_RECORD_MISC_SWITCH_OUT_PREEMPT: * Indicates that thread was preempted in TASK_RUNNING state. */ -#define PERF_RECORD_MISC_EXACT_IP (1 << 14) -#define PERF_RECORD_MISC_SWITCH_OUT_PREEMPT (1 << 14) +#define PERF_RECORD_MISC_EXACT_IP (1 << 14) +#define PERF_RECORD_MISC_SWITCH_OUT_PREEMPT (1 << 14) /* * Reserve the last bit to indicate some extended misc field */ -#define PERF_RECORD_MISC_EXT_RESERVED (1 << 15) +#define PERF_RECORD_MISC_EXT_RESERVED (1 << 15) struct perf_event_header { - __u32 type; - __u16 misc; - __u16 size; + __u32 type; + __u16 misc; + __u16 size; }; struct perf_ns_link_info { - __u64 dev; - __u64 ino; + __u64 dev; + __u64 ino; }; enum { - NET_NS_INDEX = 0, - UTS_NS_INDEX = 1, - IPC_NS_INDEX = 2, - PID_NS_INDEX = 3, - USER_NS_INDEX = 4, - MNT_NS_INDEX = 5, - CGROUP_NS_INDEX = 6, - - NR_NAMESPACES, /* number of available namespaces */ + NET_NS_INDEX = 0, + UTS_NS_INDEX = 1, + IPC_NS_INDEX = 2, + PID_NS_INDEX = 3, + USER_NS_INDEX = 4, + MNT_NS_INDEX = 5, + CGROUP_NS_INDEX = 6, + + NR_NAMESPACES, /* number of available namespaces */ }; enum perf_event_type { @@ -738,7 +734,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_MMAP = 1, + PERF_RECORD_MMAP = 1, /* * struct { @@ -748,7 +744,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_LOST = 2, + PERF_RECORD_LOST = 2, /* * struct { @@ -759,7 +755,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_COMM = 3, + PERF_RECORD_COMM = 3, /* * struct { @@ -770,7 +766,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_EXIT = 4, + PERF_RECORD_EXIT = 4, /* * struct { @@ -781,8 +777,8 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_THROTTLE = 5, - PERF_RECORD_UNTHROTTLE = 6, + PERF_RECORD_THROTTLE = 5, + PERF_RECORD_UNTHROTTLE = 6, /* * struct { @@ -793,7 +789,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_FORK = 7, + PERF_RECORD_FORK = 7, /* * struct { @@ -804,7 +800,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_READ = 8, + PERF_RECORD_READ = 8, /* * struct { @@ -863,7 +859,7 @@ enum perf_event_type { * { uint64_t phys_addr;} && PERF_SAMPLE_PHYS_ADDR * }; */ - PERF_RECORD_SAMPLE = 9, + PERF_RECORD_SAMPLE = 9, /* * The MMAP2 records are an augmented version of MMAP, they add @@ -885,7 +881,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_MMAP2 = 10, + PERF_RECORD_MMAP2 = 10, /* * Records that new data landed in the AUX buffer part. @@ -899,7 +895,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_AUX = 11, + PERF_RECORD_AUX = 11, /* * Indicates that instruction trace has started @@ -911,7 +907,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_ITRACE_START = 12, + PERF_RECORD_ITRACE_START = 12, /* * Records the dropped/lost sample number. @@ -923,7 +919,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_LOST_SAMPLES = 13, + PERF_RECORD_LOST_SAMPLES = 13, /* * Records a context switch in or out (flagged by @@ -935,7 +931,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_SWITCH = 14, + PERF_RECORD_SWITCH = 14, /* * CPU-wide version of PERF_RECORD_SWITCH with next_prev_pid and @@ -949,7 +945,7 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_SWITCH_CPU_WIDE = 15, + PERF_RECORD_SWITCH_CPU_WIDE = 15, /* * struct { @@ -961,67 +957,66 @@ enum perf_event_type { * struct sample_id sample_id; * }; */ - PERF_RECORD_NAMESPACES = 16, + PERF_RECORD_NAMESPACES = 16, - PERF_RECORD_MAX, /* non-ABI */ + PERF_RECORD_MAX, /* non-ABI */ }; -#define PERF_MAX_STACK_DEPTH 127 -#define PERF_MAX_CONTEXTS_PER_STACK 8 +#define PERF_MAX_STACK_DEPTH 127 +#define PERF_MAX_CONTEXTS_PER_STACK 8 enum perf_callchain_context { - PERF_CONTEXT_HV = (__u64)-32, - PERF_CONTEXT_KERNEL = (__u64)-128, - PERF_CONTEXT_USER = (__u64)-512, + PERF_CONTEXT_HV = (__u64)-32, + PERF_CONTEXT_KERNEL = (__u64)-128, + PERF_CONTEXT_USER = (__u64)-512, - PERF_CONTEXT_GUEST = (__u64)-2048, - PERF_CONTEXT_GUEST_KERNEL = (__u64)-2176, - PERF_CONTEXT_GUEST_USER = (__u64)-2560, + PERF_CONTEXT_GUEST = (__u64)-2048, + PERF_CONTEXT_GUEST_KERNEL = (__u64)-2176, + PERF_CONTEXT_GUEST_USER = (__u64)-2560, - PERF_CONTEXT_MAX = (__u64)-4095, + PERF_CONTEXT_MAX = (__u64)-4095, }; /** * PERF_RECORD_AUX::flags bits */ -#define PERF_AUX_FLAG_TRUNCATED 0x01 /* record was truncated to fit */ -#define PERF_AUX_FLAG_OVERWRITE 0x02 /* snapshot from overwrite mode */ -#define PERF_AUX_FLAG_PARTIAL 0x04 /* record contains gaps */ -#define PERF_AUX_FLAG_COLLISION 0x08 /* sample collided with another */ +#define PERF_AUX_FLAG_TRUNCATED 0x01 /* record was truncated to fit */ +#define PERF_AUX_FLAG_OVERWRITE 0x02 /* snapshot from overwrite mode */ +#define PERF_AUX_FLAG_PARTIAL 0x04 /* record contains gaps */ +#define PERF_AUX_FLAG_COLLISION 0x08 /* sample collided with another */ -#define PERF_FLAG_FD_NO_GROUP (1UL << 0) -#define PERF_FLAG_FD_OUTPUT (1UL << 1) -#define PERF_FLAG_PID_CGROUP (1UL << 2) /* pid=cgroup id, per-cpu mode only */ -#define PERF_FLAG_FD_CLOEXEC (1UL << 3) /* O_CLOEXEC */ +#define PERF_FLAG_FD_NO_GROUP (1UL << 0) +#define PERF_FLAG_FD_OUTPUT (1UL << 1) +#define PERF_FLAG_PID_CGROUP (1UL << 2) /* pid=cgroup id, per-cpu mode only */ +#define PERF_FLAG_FD_CLOEXEC (1UL << 3) /* O_CLOEXEC */ #if defined(__LITTLE_ENDIAN_BITFIELD) union perf_mem_data_src { __u64 val; struct { - __u64 mem_op:5, /* type of opcode */ - mem_lvl:14, /* memory hierarchy level */ - mem_snoop:5, /* snoop mode */ - mem_lock:2, /* lock instr */ - mem_dtlb:7, /* tlb access */ - mem_lvl_num:4, /* memory hierarchy level number */ - mem_remote:1, /* remote */ - mem_snoopx:2, /* snoop mode, ext */ - mem_rsvd:24; + __u64 mem_op : 5, /* type of opcode */ + mem_lvl : 14, /* memory hierarchy level */ + mem_snoop : 5, /* snoop mode */ + mem_lock : 2, /* lock instr */ + mem_dtlb : 7, /* tlb access */ + mem_lvl_num : 4, /* memory hierarchy level number */ + mem_remote : 1, /* remote */ + mem_snoopx : 2, /* snoop mode, ext */ + mem_rsvd : 24; }; }; #elif defined(__BIG_ENDIAN_BITFIELD) union perf_mem_data_src { __u64 val; struct { - __u64 mem_rsvd:24, - mem_snoopx:2, /* snoop mode, ext */ - mem_remote:1, /* remote */ - mem_lvl_num:4, /* memory hierarchy level number */ - mem_dtlb:7, /* tlb access */ - mem_lock:2, /* lock instr */ - mem_snoop:5, /* snoop mode */ - mem_lvl:14, /* memory hierarchy level */ - mem_op:5; /* type of opcode */ + __u64 mem_rsvd : 24, mem_snoopx : 2, /* snoop mode, ext */ + mem_remote : 1, /* remote */ + mem_lvl_num : 4, /* memory hierarchy level number */ + mem_dtlb : 7, /* tlb access */ + mem_lock : 2, /* lock instr */ + mem_snoop : 5, /* snoop mode */ + mem_lvl : 14, /* memory hierarchy level */ + mem_op : 5; /* type of opcode */ }; }; #else @@ -1029,75 +1024,74 @@ union perf_mem_data_src { #endif /* type of opcode (load/store/prefetch,code) */ -#define PERF_MEM_OP_NA 0x01 /* not available */ -#define PERF_MEM_OP_LOAD 0x02 /* load instruction */ -#define PERF_MEM_OP_STORE 0x04 /* store instruction */ -#define PERF_MEM_OP_PFETCH 0x08 /* prefetch */ -#define PERF_MEM_OP_EXEC 0x10 /* code (execution) */ -#define PERF_MEM_OP_SHIFT 0 +#define PERF_MEM_OP_NA 0x01 /* not available */ +#define PERF_MEM_OP_LOAD 0x02 /* load instruction */ +#define PERF_MEM_OP_STORE 0x04 /* store instruction */ +#define PERF_MEM_OP_PFETCH 0x08 /* prefetch */ +#define PERF_MEM_OP_EXEC 0x10 /* code (execution) */ +#define PERF_MEM_OP_SHIFT 0 /* memory hierarchy (memory level, hit or miss) */ -#define PERF_MEM_LVL_NA 0x01 /* not available */ -#define PERF_MEM_LVL_HIT 0x02 /* hit level */ -#define PERF_MEM_LVL_MISS 0x04 /* miss level */ -#define PERF_MEM_LVL_L1 0x08 /* L1 */ -#define PERF_MEM_LVL_LFB 0x10 /* Line Fill Buffer */ -#define PERF_MEM_LVL_L2 0x20 /* L2 */ -#define PERF_MEM_LVL_L3 0x40 /* L3 */ -#define PERF_MEM_LVL_LOC_RAM 0x80 /* Local DRAM */ -#define PERF_MEM_LVL_REM_RAM1 0x100 /* Remote DRAM (1 hop) */ -#define PERF_MEM_LVL_REM_RAM2 0x200 /* Remote DRAM (2 hops) */ -#define PERF_MEM_LVL_REM_CCE1 0x400 /* Remote Cache (1 hop) */ -#define PERF_MEM_LVL_REM_CCE2 0x800 /* Remote Cache (2 hops) */ -#define PERF_MEM_LVL_IO 0x1000 /* I/O memory */ -#define PERF_MEM_LVL_UNC 0x2000 /* Uncached memory */ -#define PERF_MEM_LVL_SHIFT 5 - -#define PERF_MEM_REMOTE_REMOTE 0x01 /* Remote */ -#define PERF_MEM_REMOTE_SHIFT 37 - -#define PERF_MEM_LVLNUM_L1 0x01 /* L1 */ -#define PERF_MEM_LVLNUM_L2 0x02 /* L2 */ -#define PERF_MEM_LVLNUM_L3 0x03 /* L3 */ -#define PERF_MEM_LVLNUM_L4 0x04 /* L4 */ +#define PERF_MEM_LVL_NA 0x01 /* not available */ +#define PERF_MEM_LVL_HIT 0x02 /* hit level */ +#define PERF_MEM_LVL_MISS 0x04 /* miss level */ +#define PERF_MEM_LVL_L1 0x08 /* L1 */ +#define PERF_MEM_LVL_LFB 0x10 /* Line Fill Buffer */ +#define PERF_MEM_LVL_L2 0x20 /* L2 */ +#define PERF_MEM_LVL_L3 0x40 /* L3 */ +#define PERF_MEM_LVL_LOC_RAM 0x80 /* Local DRAM */ +#define PERF_MEM_LVL_REM_RAM1 0x100 /* Remote DRAM (1 hop) */ +#define PERF_MEM_LVL_REM_RAM2 0x200 /* Remote DRAM (2 hops) */ +#define PERF_MEM_LVL_REM_CCE1 0x400 /* Remote Cache (1 hop) */ +#define PERF_MEM_LVL_REM_CCE2 0x800 /* Remote Cache (2 hops) */ +#define PERF_MEM_LVL_IO 0x1000 /* I/O memory */ +#define PERF_MEM_LVL_UNC 0x2000 /* Uncached memory */ +#define PERF_MEM_LVL_SHIFT 5 + +#define PERF_MEM_REMOTE_REMOTE 0x01 /* Remote */ +#define PERF_MEM_REMOTE_SHIFT 37 + +#define PERF_MEM_LVLNUM_L1 0x01 /* L1 */ +#define PERF_MEM_LVLNUM_L2 0x02 /* L2 */ +#define PERF_MEM_LVLNUM_L3 0x03 /* L3 */ +#define PERF_MEM_LVLNUM_L4 0x04 /* L4 */ /* 5-0xa available */ #define PERF_MEM_LVLNUM_ANY_CACHE 0x0b /* Any cache */ -#define PERF_MEM_LVLNUM_LFB 0x0c /* LFB */ -#define PERF_MEM_LVLNUM_RAM 0x0d /* RAM */ -#define PERF_MEM_LVLNUM_PMEM 0x0e /* PMEM */ -#define PERF_MEM_LVLNUM_NA 0x0f /* N/A */ +#define PERF_MEM_LVLNUM_LFB 0x0c /* LFB */ +#define PERF_MEM_LVLNUM_RAM 0x0d /* RAM */ +#define PERF_MEM_LVLNUM_PMEM 0x0e /* PMEM */ +#define PERF_MEM_LVLNUM_NA 0x0f /* N/A */ -#define PERF_MEM_LVLNUM_SHIFT 33 +#define PERF_MEM_LVLNUM_SHIFT 33 /* snoop mode */ -#define PERF_MEM_SNOOP_NA 0x01 /* not available */ -#define PERF_MEM_SNOOP_NONE 0x02 /* no snoop */ -#define PERF_MEM_SNOOP_HIT 0x04 /* snoop hit */ -#define PERF_MEM_SNOOP_MISS 0x08 /* snoop miss */ -#define PERF_MEM_SNOOP_HITM 0x10 /* snoop hit modified */ -#define PERF_MEM_SNOOP_SHIFT 19 - -#define PERF_MEM_SNOOPX_FWD 0x01 /* forward */ +#define PERF_MEM_SNOOP_NA 0x01 /* not available */ +#define PERF_MEM_SNOOP_NONE 0x02 /* no snoop */ +#define PERF_MEM_SNOOP_HIT 0x04 /* snoop hit */ +#define PERF_MEM_SNOOP_MISS 0x08 /* snoop miss */ +#define PERF_MEM_SNOOP_HITM 0x10 /* snoop hit modified */ +#define PERF_MEM_SNOOP_SHIFT 19 + +#define PERF_MEM_SNOOPX_FWD 0x01 /* forward */ /* 1 free */ -#define PERF_MEM_SNOOPX_SHIFT 37 +#define PERF_MEM_SNOOPX_SHIFT 37 /* locked instruction */ -#define PERF_MEM_LOCK_NA 0x01 /* not available */ -#define PERF_MEM_LOCK_LOCKED 0x02 /* locked transaction */ -#define PERF_MEM_LOCK_SHIFT 24 +#define PERF_MEM_LOCK_NA 0x01 /* not available */ +#define PERF_MEM_LOCK_LOCKED 0x02 /* locked transaction */ +#define PERF_MEM_LOCK_SHIFT 24 /* TLB access */ -#define PERF_MEM_TLB_NA 0x01 /* not available */ -#define PERF_MEM_TLB_HIT 0x02 /* hit level */ -#define PERF_MEM_TLB_MISS 0x04 /* miss level */ -#define PERF_MEM_TLB_L1 0x08 /* L1 */ -#define PERF_MEM_TLB_L2 0x10 /* L2 */ -#define PERF_MEM_TLB_WK 0x20 /* Hardware Walker*/ -#define PERF_MEM_TLB_OS 0x40 /* OS fault handler */ -#define PERF_MEM_TLB_SHIFT 26 - -#define PERF_MEM_S(a, s) \ - (((__u64)PERF_MEM_##a##_##s) << PERF_MEM_##a##_SHIFT) +#define PERF_MEM_TLB_NA 0x01 /* not available */ +#define PERF_MEM_TLB_HIT 0x02 /* hit level */ +#define PERF_MEM_TLB_MISS 0x04 /* miss level */ +#define PERF_MEM_TLB_L1 0x08 /* L1 */ +#define PERF_MEM_TLB_L2 0x10 /* L2 */ +#define PERF_MEM_TLB_WK 0x20 /* Hardware Walker*/ +#define PERF_MEM_TLB_OS 0x40 /* OS fault handler */ +#define PERF_MEM_TLB_SHIFT 26 + +#define PERF_MEM_S(a, s) (((__u64)PERF_MEM_##a##_##s) << PERF_MEM_##a##_SHIFT) /* * single taken branch record layout: @@ -1116,15 +1110,15 @@ union perf_mem_data_src { * type: branch type */ struct perf_branch_entry { - __u64 from; - __u64 to; - __u64 mispred:1, /* target mispredicted */ - predicted:1,/* target predicted */ - in_tx:1, /* in transaction */ - abort:1, /* transaction abort */ - cycles:16, /* cycle count to last branch */ - type:4, /* branch type */ - reserved:40; + __u64 from; + __u64 to; + __u64 mispred : 1, /* target mispredicted */ + predicted : 1, /* target predicted */ + in_tx : 1, /* in transaction */ + abort : 1, /* transaction abort */ + cycles : 16, /* cycle count to last branch */ + type : 4, /* branch type */ + reserved : 40; }; #endif /* _UAPI_LINUX_PERF_EVENT_H */ diff --git a/userspace/libscap/debug_log_helpers.h b/userspace/libscap/debug_log_helpers.h index 51ce4d3c19..132fa4cb51 100644 --- a/userspace/libscap/debug_log_helpers.h +++ b/userspace/libscap/debug_log_helpers.h @@ -23,16 +23,18 @@ limitations under the License. #include #define scap_log(HANDLE, sev, ...) scap_log_impl(HANDLE->m_log_fn, sev, __VA_ARGS__) -#define scap_debug_log(HANDLE, ...) scap_log_impl(HANDLE->m_log_fn, FALCOSECURITY_LOG_SEV_DEBUG, __VA_ARGS__) +#define scap_debug_log(HANDLE, ...) \ + scap_log_impl(HANDLE->m_log_fn, FALCOSECURITY_LOG_SEV_DEBUG, __VA_ARGS__) /** * If debug_log_fn has been established in the handle, call that function * to log a debug message. */ -static inline void scap_log_impl(falcosecurity_log_fn log_fn, enum falcosecurity_log_severity sev, const char* fmt, ...) -{ - if(log_fn != NULL) - { +static inline void scap_log_impl(falcosecurity_log_fn log_fn, + enum falcosecurity_log_severity sev, + const char* fmt, + ...) { + if(log_fn != NULL) { char buf[256]; va_list ap; va_start(ap, fmt); diff --git a/userspace/libscap/emscripten/gettimeofday.h b/userspace/libscap/emscripten/gettimeofday.h index 58af1b8064..21c6fc8841 100644 --- a/userspace/libscap/emscripten/gettimeofday.h +++ b/userspace/libscap/emscripten/gettimeofday.h @@ -21,14 +21,12 @@ limitations under the License. #include #include -static inline uint64_t get_timestamp_ns() -{ +static inline uint64_t get_timestamp_ns() { uint64_t ts; struct timeval tv; gettimeofday(&tv, NULL); - ts = tv.tv_sec * (uint64_t) 1000000000 + tv.tv_usec * 1000; + ts = tv.tv_sec * (uint64_t)1000000000 + tv.tv_usec * 1000; return ts; } - diff --git a/userspace/libscap/emscripten/sleep.h b/userspace/libscap/emscripten/sleep.h index 26578cdd87..4e0db527d0 100644 --- a/userspace/libscap/emscripten/sleep.h +++ b/userspace/libscap/emscripten/sleep.h @@ -20,7 +20,6 @@ limitations under the License. #include -static inline void sleep_ms(int ms) -{ +static inline void sleep_ms(int ms) { usleep(ms * 1000); } diff --git a/userspace/libscap/engine/bpf/CMakeLists.txt b/userspace/libscap/engine/bpf/CMakeLists.txt index ab461b0960..7e0e7ac22f 100644 --- a/userspace/libscap/engine/bpf/CMakeLists.txt +++ b/userspace/libscap/engine/bpf/CMakeLists.txt @@ -2,28 +2,21 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # add_library(scap_engine_bpf scap_bpf.c attached_prog.c) add_dependencies(scap_engine_bpf libelf zlib) -target_link_libraries(scap_engine_bpf -PRIVATE - scap_event_schema - scap_platform - scap_engine_util - scap_error - ${LIBELF_LIB} - ${ZLIB_LIB} +target_link_libraries( + scap_engine_bpf PRIVATE scap_event_schema scap_platform scap_engine_util scap_error + ${LIBELF_LIB} ${ZLIB_LIB} ) target_include_directories(scap_engine_bpf PRIVATE ${LIBELF_INCLUDE}) diff --git a/userspace/libscap/engine/bpf/attached_prog.c b/userspace/libscap/engine/bpf/attached_prog.c index 8dcc3495ea..9dd76688cf 100644 --- a/userspace/libscap/engine/bpf/attached_prog.c +++ b/userspace/libscap/engine/bpf/attached_prog.c @@ -33,33 +33,31 @@ limitations under the License. /*=============================== INTERNALS ===============================*/ -static int __attach_raw_tp(struct bpf_attached_prog* prog, char* last_err) -{ +static int __attach_raw_tp(struct bpf_attached_prog* prog, char* last_err) { union bpf_attr attr; memset(&attr, 0, sizeof(attr)); attr.raw_tracepoint.name = (unsigned long)prog->name; attr.raw_tracepoint.prog_fd = prog->fd; prog->efd = syscall(__NR_bpf, BPF_RAW_TRACEPOINT_OPEN, &attr, sizeof(attr)); - if(prog->efd < 0) - { - return scap_errprintf(last_err, -prog->efd, "BPF_RAW_TRACEPOINT_OPEN: event %s", prog->name); + if(prog->efd < 0) { + return scap_errprintf(last_err, + -prog->efd, + "BPF_RAW_TRACEPOINT_OPEN: event %s", + prog->name); } return SCAP_SUCCESS; } -static int __attach_tp(struct bpf_attached_prog* prog, char* last_err) -{ +static int __attach_tp(struct bpf_attached_prog* prog, char* last_err) { int efd = 0; int err = 0; char buf[SCAP_MAX_PATH_SIZE]; snprintf(buf, sizeof(buf), "/sys/kernel/debug/tracing/events/%s/id", prog->name); efd = open(buf, O_RDONLY, 0); - if(efd < 0) - { + if(efd < 0) { if(strcmp(prog->name, "exceptions/page_fault_user") == 0 || - strcmp(prog->name, "exceptions/page_fault_kernel") == 0) - { + strcmp(prog->name, "exceptions/page_fault_kernel") == 0) { return SCAP_SUCCESS; } @@ -67,8 +65,7 @@ static int __attach_tp(struct bpf_attached_prog* prog, char* last_err) } err = read(efd, buf, sizeof(buf)); - if(err < 0 || err >= sizeof(buf)) - { + if(err < 0 || err >= sizeof(buf)) { int err = errno; close(efd); return scap_errprintf(last_err, err, "read from '%s' failed", prog->name); @@ -86,13 +83,11 @@ static int __attach_tp(struct bpf_attached_prog* prog, char* last_err) attr.config = id; efd = syscall(__NR_perf_event_open, &attr, -1, 0, -1, 0); - if(efd < 0) - { + if(efd < 0) { return scap_errprintf(last_err, -efd, "event %d", id); } - if(ioctl(efd, PERF_EVENT_IOC_SET_BPF, prog->fd)) - { + if(ioctl(efd, PERF_EVENT_IOC_SET_BPF, prog->fd)) { int err = errno; close(efd); return scap_errprintf(last_err, err, "PERF_EVENT_IOC_SET_BPF"); @@ -103,84 +98,82 @@ static int __attach_tp(struct bpf_attached_prog* prog, char* last_err) /*=============================== INTERNALS ===============================*/ -bool is_sys_enter(const char* name) -{ +bool is_sys_enter(const char* name) { /* We need the double-check because it could be a raw_tracepoint or a plain tracepoint */ return (memcmp(name, "sys_enter", sizeof("sys_enter") - 1) == 0) || (memcmp(name, "raw_syscalls/sys_enter", sizeof("raw_syscalls/sys_enter") - 1) == 0); } -bool is_sys_exit(const char* name) -{ +bool is_sys_exit(const char* name) { return (memcmp(name, "sys_exit", sizeof("sys_exit") - 1) == 0) || (memcmp(name, "raw_syscalls/sys_exit", sizeof("raw_syscalls/sys_exit") - 1) == 0); } -bool is_sched_proc_exit(const char* name) -{ +bool is_sched_proc_exit(const char* name) { return (memcmp(name, "sched_process_exit", sizeof("sched_process_exit") - 1) == 0) || (memcmp(name, "sched/sched_process_exit", sizeof("sched/sched_process_exit") - 1) == 0); } -bool is_sched_switch(const char* name) -{ +bool is_sched_switch(const char* name) { return (memcmp(name, "sched_switch", sizeof("sched_switch") - 1) == 0) || (memcmp(name, "sched/sched_switch", sizeof("sched/sched_switch") - 1) == 0); } -bool is_page_fault_user(const char* name) -{ +bool is_page_fault_user(const char* name) { return (memcmp(name, "page_fault_user", sizeof("page_fault_user") - 1) == 0) || - (memcmp(name, "exceptions/page_fault_user", sizeof("exceptions/page_fault_user") - 1) == 0); + (memcmp(name, "exceptions/page_fault_user", sizeof("exceptions/page_fault_user") - 1) == + 0); } -bool is_page_fault_kernel(const char* name) -{ +bool is_page_fault_kernel(const char* name) { return (memcmp(name, "page_fault_kernel", sizeof("page_fault_kernel") - 1) == 0) || - (memcmp(name, "exceptions/page_fault_kernel", sizeof("exceptions/page_fault_kernel") - 1) == 0); + (memcmp(name, + "exceptions/page_fault_kernel", + sizeof("exceptions/page_fault_kernel") - 1) == 0); } -bool is_signal_deliver(const char* name) -{ +bool is_signal_deliver(const char* name) { return (memcmp(name, "signal_deliver", sizeof("signal_deliver") - 1) == 0) || (memcmp(name, "signal/signal_deliver", sizeof("signal/signal_deliver") - 1) == 0); } -bool is_sched_prog_fork_move_args(const char* name) -{ +bool is_sched_prog_fork_move_args(const char* name) { /* Note that the `&1` is a workaround we put in place when we want to attach more than one * bpf program to the same tracepoint! */ return (memcmp(name, "sched_process_fork&1", sizeof("sched_process_fork&1") - 1) == 0) || - (memcmp(name, "sched/sched_process_fork&1", sizeof("sched/sched_process_fork&1") - 1) == 0); + (memcmp(name, "sched/sched_process_fork&1", sizeof("sched/sched_process_fork&1") - 1) == + 0); } -bool is_sched_prog_fork_missing_child(const char* name) -{ - /* if we found the `&` char in the section name it means that we need to remove the last 2 chars from `name` - * this is a workaround we use to attach more than one BPF prog to the same tracepoint. We will need the - * real section name to attach the program for this reason we are removing this workaround here. +bool is_sched_prog_fork_missing_child(const char* name) { + /* if we found the `&` char in the section name it means that we need to remove the last 2 chars + * from `name` this is a workaround we use to attach more than one BPF prog to the same + * tracepoint. We will need the real section name to attach the program for this reason we are + * removing this workaround here. */ return (memcmp(name, "sched_process_fork&2", sizeof("sched_process_fork&2") - 1) == 0) || - (memcmp(name, "sched/sched_process_fork&2", sizeof("sched/sched_process_fork&2") - 1) == 0); + (memcmp(name, "sched/sched_process_fork&2", sizeof("sched/sched_process_fork&2") - 1) == + 0); } -bool is_sched_prog_exec_missing_exit(const char* name) -{ +bool is_sched_prog_exec_missing_exit(const char* name) { return (memcmp(name, "sched_process_exec", sizeof("sched_process_exec") - 1) == 0) || (memcmp(name, "sched/sched_process_exec", sizeof("sched/sched_process_exec") - 1) == 0); } -void fill_attached_prog_info(struct bpf_attached_prog* prog, bool raw_tp, const char* name, int fd) -{ +void fill_attached_prog_info(struct bpf_attached_prog* prog, + bool raw_tp, + const char* name, + int fd) { prog->fd = fd; int size_to_read = NAME_MAX; - /* if we found the `&` char in the section name it means that we need to remove the last 2 chars from `name` - * this is a workaround we use to attach more than one BPF prog to the same tracepoint. We will need the - * real section name to attach the program for this reason we are removing this workaround here. + /* if we found the `&` char in the section name it means that we need to remove the last 2 chars + * from `name` this is a workaround we use to attach more than one BPF prog to the same + * tracepoint. We will need the real section name to attach the program for this reason we are + * removing this workaround here. */ - if(strrchr(name, '&') != NULL) - { + if(strrchr(name, '&') != NULL) { size_to_read = (strlen(name) - 1) < NAME_MAX ? (strlen(name) - 1) : NAME_MAX; } strlcpy(prog->name, name, size_to_read); @@ -188,46 +181,37 @@ void fill_attached_prog_info(struct bpf_attached_prog* prog, bool raw_tp, const prog->efd = -1; /* not attached */ } -int attach_bpf_prog(struct bpf_attached_prog* prog, char* last_err) -{ +int attach_bpf_prog(struct bpf_attached_prog* prog, char* last_err) { /* The program is already attached or is never found in the elf file (prog->fd == -1) * A program might be never found in the elf file for example page_faults or tracepoints * enabled only on some architectures. */ - if(prog->efd != -1 || prog->fd == -1) - { + if(prog->efd != -1 || prog->fd == -1) { return SCAP_SUCCESS; } int ret = 0; - if(prog->raw_tp) - { + if(prog->raw_tp) { ret = __attach_raw_tp(prog, last_err); - } - else - { + } else { ret = __attach_tp(prog, last_err); } return ret; } -void detach_bpf_prog(struct bpf_attached_prog* prog) -{ +void detach_bpf_prog(struct bpf_attached_prog* prog) { /* The program is already detached */ - if(prog->efd == -1) - { + if(prog->efd == -1) { return; } close(prog->efd); prog->efd = -1; } -void unload_bpf_prog(struct bpf_attached_prog* prog) -{ +void unload_bpf_prog(struct bpf_attached_prog* prog) { /* The program is already unloaded */ - if(prog->fd == -1) - { + if(prog->fd == -1) { return; } close(prog->fd); diff --git a/userspace/libscap/engine/bpf/attached_prog.h b/userspace/libscap/engine/bpf/attached_prog.h index d3b83ffe75..ab657faeeb 100644 --- a/userspace/libscap/engine/bpf/attached_prog.h +++ b/userspace/libscap/engine/bpf/attached_prog.h @@ -21,8 +21,7 @@ limitations under the License. #include #include -typedef enum -{ +typedef enum { BPF_PROG_SYS_ENTER = 0, BPF_PROG_SYS_EXIT = 1, BPF_PROG_SCHED_PROC_EXIT = 2, @@ -30,18 +29,20 @@ typedef enum BPF_PROG_PAGE_FAULT_USER = 4, BPF_PROG_PAGE_FAULT_KERNEL = 5, BPF_PROG_SIGNAL_DELIVER = 6, - BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS = 7, /* This is only used when raw_tp are not available */ - BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD = 8, /* This is only used on architectures where the clone/fork child event is missing. Only when we have raw_tp */ - BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT = 9, /* This is only used on architectures where the execve/execveat success event is missing */ + BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS = 7, /* This is only used when raw_tp are not available */ + BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD = + 8, /* This is only used on architectures where the clone/fork child event is missing. + Only when we have raw_tp */ + BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT = 9, /* This is only used on architectures where the + execve/execveat success event is missing */ BPF_PROG_ATTACHED_MAX = 10, } bpf_attached_prog_codes; -typedef struct bpf_attached_prog -{ - int fd; /* fd used to load/unload bpf progs */ - int efd; /* fd used to attach/detach bpf progs */ +typedef struct bpf_attached_prog { + int fd; /* fd used to load/unload bpf progs */ + int efd; /* fd used to attach/detach bpf progs */ char name[NAME_MAX]; /* name of the program, used to attach it into the kernel */ - bool raw_tp; /* tells if a program is a raw tracepoint or not */ + bool raw_tp; /* tells if a program is a raw tracepoint or not */ } bpf_attached_prog; bool is_sys_enter(const char* name); diff --git a/userspace/libscap/engine/bpf/bpf.h b/userspace/libscap/engine/bpf/bpf.h index b317be073b..fe7c824457 100644 --- a/userspace/libscap/engine/bpf/bpf.h +++ b/userspace/libscap/engine/bpf/bpf.h @@ -35,8 +35,7 @@ limitations under the License. #define BPF_MAPS_MAX 32 -struct bpf_engine -{ +struct bpf_engine { struct scap_device_set m_dev_set; size_t m_ncpus; char* m_lasterr; @@ -51,7 +50,7 @@ struct bpf_engine /* ELF related */ int program_fd; - Elf *elf; + Elf* elf; GElf_Ehdr ehdr; interesting_ppm_sc_set curr_sc_set; diff --git a/userspace/libscap/engine/bpf/bpf_public.h b/userspace/libscap/engine/bpf/bpf_public.h index 3e665f6ca9..b3765e72c3 100644 --- a/userspace/libscap/engine/bpf/bpf_public.h +++ b/userspace/libscap/engine/bpf/bpf_public.h @@ -19,15 +19,15 @@ limitations under the License. #define BPF_ENGINE "bpf" #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - struct scap_bpf_engine_params - { - unsigned long buffer_bytes_dim; ///< Dimension of a single per-CPU buffer in bytes. Please note: this buffer will be mapped twice in the process virtual memory, so pay attention to its size. - const char* bpf_probe; ///< The path to the BPF probe object file. - }; +struct scap_bpf_engine_params { + unsigned long buffer_bytes_dim; ///< Dimension of a single per-CPU buffer in bytes. Please + ///< note: this buffer will be mapped twice in the process + ///< virtual memory, so pay attention to its size. + const char* bpf_probe; ///< The path to the BPF probe object file. +}; #ifdef __cplusplus }; diff --git a/userspace/libscap/engine/bpf/scap_bpf.c b/userspace/libscap/engine/bpf/scap_bpf.c index f814072f57..3f7ea6e586 100644 --- a/userspace/libscap/engine/bpf/scap_bpf.c +++ b/userspace/libscap/engine/bpf/scap_bpf.c @@ -33,7 +33,7 @@ limitations under the License. #include #include -#define HANDLE(engine) ((struct bpf_engine*)(engine.m_handle)) +#define HANDLE(engine) ((struct bpf_engine *)(engine.m_handle)) #include #include @@ -49,46 +49,42 @@ limitations under the License. #include #include -static const char * const bpf_kernel_counters_stats_names[] = { - [BPF_N_EVTS] = N_EVENTS_PREFIX, - [BPF_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total", - [BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER] = "n_drops_buffer_clone_fork_enter", - [BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT] = "n_drops_buffer_clone_fork_exit", - [BPF_N_DROPS_BUFFER_EXECVE_ENTER] = "n_drops_buffer_execve_enter", - [BPF_N_DROPS_BUFFER_EXECVE_EXIT] = "n_drops_buffer_execve_exit", - [BPF_N_DROPS_BUFFER_CONNECT_ENTER] = "n_drops_buffer_connect_enter", - [BPF_N_DROPS_BUFFER_CONNECT_EXIT] = "n_drops_buffer_connect_exit", - [BPF_N_DROPS_BUFFER_OPEN_ENTER] = "n_drops_buffer_open_enter", - [BPF_N_DROPS_BUFFER_OPEN_EXIT] = "n_drops_buffer_open_exit", - [BPF_N_DROPS_BUFFER_DIR_FILE_ENTER] = "n_drops_buffer_dir_file_enter", - [BPF_N_DROPS_BUFFER_DIR_FILE_EXIT] = "n_drops_buffer_dir_file_exit", - [BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER] = "n_drops_buffer_other_interest_enter", - [BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT] = "n_drops_buffer_other_interest_exit", - [BPF_N_DROPS_BUFFER_CLOSE_EXIT] = "n_drops_buffer_close_exit", - [BPF_N_DROPS_BUFFER_PROC_EXIT] = "n_drops_buffer_proc_exit", - [BPF_N_DROPS_SCRATCH_MAP] = "n_drops_scratch_map", - [BPF_N_DROPS_PAGE_FAULTS] = "n_drops_page_faults", - [BPF_N_DROPS_BUG] = "n_drops_bug", - [BPF_N_DROPS] = "n_drops", +static const char *const bpf_kernel_counters_stats_names[] = { + [BPF_N_EVTS] = N_EVENTS_PREFIX, + [BPF_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total", + [BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER] = "n_drops_buffer_clone_fork_enter", + [BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT] = "n_drops_buffer_clone_fork_exit", + [BPF_N_DROPS_BUFFER_EXECVE_ENTER] = "n_drops_buffer_execve_enter", + [BPF_N_DROPS_BUFFER_EXECVE_EXIT] = "n_drops_buffer_execve_exit", + [BPF_N_DROPS_BUFFER_CONNECT_ENTER] = "n_drops_buffer_connect_enter", + [BPF_N_DROPS_BUFFER_CONNECT_EXIT] = "n_drops_buffer_connect_exit", + [BPF_N_DROPS_BUFFER_OPEN_ENTER] = "n_drops_buffer_open_enter", + [BPF_N_DROPS_BUFFER_OPEN_EXIT] = "n_drops_buffer_open_exit", + [BPF_N_DROPS_BUFFER_DIR_FILE_ENTER] = "n_drops_buffer_dir_file_enter", + [BPF_N_DROPS_BUFFER_DIR_FILE_EXIT] = "n_drops_buffer_dir_file_exit", + [BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER] = "n_drops_buffer_other_interest_enter", + [BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT] = "n_drops_buffer_other_interest_exit", + [BPF_N_DROPS_BUFFER_CLOSE_EXIT] = "n_drops_buffer_close_exit", + [BPF_N_DROPS_BUFFER_PROC_EXIT] = "n_drops_buffer_proc_exit", + [BPF_N_DROPS_SCRATCH_MAP] = "n_drops_scratch_map", + [BPF_N_DROPS_PAGE_FAULTS] = "n_drops_page_faults", + [BPF_N_DROPS_BUG] = "n_drops_bug", + [BPF_N_DROPS] = "n_drops", }; -static const char * const bpf_libbpf_stats_names[] = { - [RUN_CNT] = ".run_cnt", ///< `bpf_prog_info` run_cnt. - [RUN_TIME_NS] = ".run_time_ns", ///<`bpf_prog_info` run_time_ns. - [AVG_TIME_NS] = ".avg_time_ns", ///< Average time spent in bpg program, calculation: run_time_ns / run_cnt. +static const char *const bpf_libbpf_stats_names[] = { + [RUN_CNT] = ".run_cnt", ///< `bpf_prog_info` run_cnt. + [RUN_TIME_NS] = ".run_time_ns", ///<`bpf_prog_info` run_time_ns. + [AVG_TIME_NS] = ".avg_time_ns", ///< Average time spent in bpg program, calculation: + ///< run_time_ns / run_cnt. }; -static inline scap_evt* scap_bpf_next_event(scap_device* dev) -{ +static inline scap_evt *scap_bpf_next_event(scap_device *dev) { return scap_bpf_evt_from_perf_sample(dev->m_sn_next_event); } -static inline void scap_bpf_advance_to_next_evt(scap_device* dev, scap_evt *event) -{ - scap_bpf_advance_to_evt(dev, true, - dev->m_sn_next_event, - &dev->m_sn_next_event, - &dev->m_sn_len); +static inline void scap_bpf_advance_to_next_evt(scap_device *dev, scap_evt *event) { + scap_bpf_advance_to_evt(dev, true, dev->m_sn_next_event, &dev->m_sn_next_event, &dev->m_sn_len); } #define GET_BUF_POINTERS scap_bpf_get_buf_pointers @@ -114,19 +110,15 @@ struct bpf_map_data { struct bpf_map_def def; }; -static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) -{ +static void *alloc_handle(scap_t *main_handle, char *lasterr_ptr) { struct bpf_engine *engine = calloc(1, sizeof(struct bpf_engine)); - if(engine) - { + if(engine) { engine->m_lasterr = lasterr_ptr; - for(int j=0; j < BPF_PROGS_TAIL_CALLED_MAX; j++) - { + for(int j = 0; j < BPF_PROGS_TAIL_CALLED_MAX; j++) { engine->m_tail_called_fds[j] = -1; } - for(int j=0; j < BPF_PROG_ATTACHED_MAX; j++) - { + for(int j = 0; j < BPF_PROG_ATTACHED_MAX; j++) { engine->m_attached_progs[j].fd = -1; engine->m_attached_progs[j].efd = -1; } @@ -136,60 +128,54 @@ static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) return engine; } -static void free_handle(struct scap_engine_handle engine) -{ +static void free_handle(struct scap_engine_handle engine) { free(engine.m_handle); } #ifndef UINT32_MAX -# define UINT32_MAX (4294967295U) +#define UINT32_MAX (4294967295U) #endif /* Recommended log buffer size. - * Taken from libbpf source code: https://github.com/libbpf/libbpf/blob/67a4b1464349345e483df26ed93f8d388a60cee1/src/bpf.h#L201 + * Taken from libbpf source code: + * https://github.com/libbpf/libbpf/blob/67a4b1464349345e483df26ed93f8d388a60cee1/src/bpf.h#L201 */ static const int BPF_LOG_SIZE = UINT32_MAX >> 8; /* verifier maximum in kernels <= 5.1 */ -static char* license; +static char *license; #define FILLER_NAME_FN(x) #x, -static const char *g_filler_names[PPM_FILLER_MAX] = { - FILLER_LIST_MAPPER(FILLER_NAME_FN) -}; +static const char *g_filler_names[PPM_FILLER_MAX] = {FILLER_LIST_MAPPER(FILLER_NAME_FN)}; #undef FILLER_NAME_FN -static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr, unsigned int size) -{ +static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr, unsigned int size) { return syscall(__NR_bpf, cmd, attr, size); } static int sys_perf_event_open(struct perf_event_attr *attr, - pid_t pid, int cpu, int group_fd, - unsigned long flags) -{ + pid_t pid, + int cpu, + int group_fd, + unsigned long flags) { return syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags); } -static inline __u64 ptr_to_u64(const void *ptr) -{ - return (__u64) (unsigned long) ptr; +static inline __u64 ptr_to_u64(const void *ptr) { + return (__u64)(unsigned long)ptr; } /* Here the filler_name is something like 'sys_open_x'. * Starting from the entire section name 'raw_tracepoint/filler/sys_open_x' * here we obtain just the final part 'sys_open_x'. */ -static int32_t lookup_filler_id(const char *filler_name) -{ +static int32_t lookup_filler_id(const char *filler_name) { int j; /* In our table we must have a filler_name corresponding to the final * part of the elf section. */ - for(j = 0; j < sizeof(g_filler_names) / sizeof(g_filler_names[0]); ++j) - { - if(strcmp(filler_name, g_filler_names[j]) == 0) - { + for(j = 0; j < sizeof(g_filler_names) / sizeof(g_filler_names[0]); ++j) { + if(strcmp(filler_name, g_filler_names[j]) == 0) { return j; } } @@ -197,37 +183,36 @@ static int32_t lookup_filler_id(const char *filler_name) return -1; } -static int bpf_map_update_elem(int fd, const void *key, const void *value, uint64_t flags) -{ +static int bpf_map_update_elem(int fd, const void *key, const void *value, uint64_t flags) { union bpf_attr attr; bzero(&attr, sizeof(attr)); attr.map_fd = fd; - attr.key = (unsigned long) key; - attr.value = (unsigned long) value; + attr.key = (unsigned long)key; + attr.value = (unsigned long)value; attr.flags = flags; return sys_bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr)); } -static int bpf_map_lookup_elem(int fd, const void *key, void *value) -{ +static int bpf_map_lookup_elem(int fd, const void *key, void *value) { union bpf_attr attr; bzero(&attr, sizeof(attr)); attr.map_fd = fd; - attr.key = (unsigned long) key; - attr.value = (unsigned long) value; + attr.key = (unsigned long)key; + attr.value = (unsigned long)value; return sys_bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr)); } static int bpf_map_create(enum bpf_map_type map_type, - int key_size, int value_size, int max_entries, - uint32_t map_flags) -{ + int key_size, + int value_size, + int max_entries, + uint32_t map_flags) { union bpf_attr attr; bzero(&attr, sizeof(attr)); @@ -241,8 +226,7 @@ static int bpf_map_create(enum bpf_map_type map_type, return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr)); } -static int bpf_map_freeze(int fd) -{ +static int bpf_map_freeze(int fd) { union bpf_attr attr; bzero(&attr, sizeof(attr)); @@ -254,8 +238,7 @@ static int bpf_map_freeze(int fd) return SCAP_SUCCESS; } -static int bpf_obj_get_info_by_fd(int fd, void *info, __u32 *info_len) -{ +static int bpf_obj_get_info_by_fd(int fd, void *info, __u32 *info_len) { union bpf_attr attr; int err; @@ -265,31 +248,30 @@ static int bpf_obj_get_info_by_fd(int fd, void *info, __u32 *info_len) attr.info.info = ptr_to_u64(info); err = sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr)); - if (!err) + if(!err) *info_len = attr.info.info_len; return SCAP_SUCCESS; } static int bpf_load_program(const struct bpf_insn *insns, - enum bpf_prog_type type, - size_t insns_cnt, - char *log_buf, - size_t log_buf_sz, - const char *prog_name) -{ + enum bpf_prog_type type, + size_t insns_cnt, + char *log_buf, + size_t log_buf_sz, + const char *prog_name) { union bpf_attr attr; int fd; bzero(&attr, sizeof(attr)); attr.prog_type = type; - attr.insn_cnt = (uint32_t) insns_cnt; - attr.insns = (unsigned long) insns; - attr.license = (unsigned long) license; - attr.log_buf = (unsigned long) NULL; + attr.insn_cnt = (uint32_t)insns_cnt; + attr.insns = (unsigned long)insns; + attr.license = (unsigned long)license; + attr.log_buf = (unsigned long)NULL; attr.log_size = 0; attr.log_level = 0; - if (prog_name != NULL) { + if(prog_name != NULL) { snprintf(attr.prog_name, BPF_OBJ_NAME_LEN, "%s", prog_name); } @@ -299,8 +281,7 @@ static int bpf_load_program(const struct bpf_insn *insns, * the second one would be useless without catching logs. */ fd = sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr)); - if(fd >= 0 || !log_buf || !log_buf_sz) - { + if(fd >= 0 || !log_buf || !log_buf_sz) { return fd; } @@ -308,7 +289,7 @@ static int bpf_load_program(const struct bpf_insn *insns, * only if we have a buffer for collecting them (so only if we * pass to `bpf_load_program()` function a `log_buf`!= NULL). */ - attr.log_buf = (unsigned long) log_buf; + attr.log_buf = (unsigned long)log_buf; attr.log_size = log_buf_sz; attr.log_level = 1; log_buf[0] = 0; @@ -316,90 +297,84 @@ static int bpf_load_program(const struct bpf_insn *insns, return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr)); } -static int32_t get_elf_section(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname, GElf_Shdr *shdr, Elf_Data **data) -{ +static int32_t get_elf_section(Elf *elf, + int i, + GElf_Ehdr *ehdr, + char **shname, + GElf_Shdr *shdr, + Elf_Data **data) { Elf_Scn *scn = elf_getscn(elf, i); - if(!scn) - { + if(!scn) { return SCAP_FAILURE; } - if(gelf_getshdr(scn, shdr) != shdr) - { + if(gelf_getshdr(scn, shdr) != shdr) { return SCAP_FAILURE; } *shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name); - if(!*shname || !shdr->sh_size) - { + if(!*shname || !shdr->sh_size) { return SCAP_FAILURE; } *data = elf_getdata(scn, 0); - if(!*data || elf_getdata(scn, *data) != NULL) - { + if(!*data || elf_getdata(scn, *data) != NULL) { return SCAP_FAILURE; } return SCAP_SUCCESS; } -static int cmp_symbols(const void *l, const void *r) -{ +static int cmp_symbols(const void *l, const void *r) { const GElf_Sym *lsym = (const GElf_Sym *)l; const GElf_Sym *rsym = (const GElf_Sym *)r; - if(lsym->st_value < rsym->st_value) - { + if(lsym->st_value < rsym->st_value) { return -1; - } - else if(lsym->st_value > rsym->st_value) - { + } else if(lsym->st_value > rsym->st_value) { return 1; - } - else - { + } else { return 0; } } -static int32_t load_elf_maps_section(struct bpf_engine *handle, struct bpf_map_data *maps, - int maps_shndx, Elf *elf, Elf_Data *symbols, - int strtabidx, int *nr_maps) -{ +static int32_t load_elf_maps_section(struct bpf_engine *handle, + struct bpf_map_data *maps, + int maps_shndx, + Elf *elf, + Elf_Data *symbols, + int strtabidx, + int *nr_maps) { Elf_Data *data_maps = NULL; GElf_Sym *sym; Elf_Scn *scn; int i; scn = elf_getscn(elf, maps_shndx); - if(scn) - { + if(scn) { data_maps = elf_getdata(scn, NULL); } - if(!scn || !data_maps) - { - return scap_errprintf(handle->m_lasterr, 0, "Failed to get Elf_Data from maps section %d", maps_shndx); + if(!scn || !data_maps) { + return scap_errprintf(handle->m_lasterr, + 0, + "Failed to get Elf_Data from maps section %d", + maps_shndx); } *nr_maps = 0; sym = calloc(BPF_MAPS_MAX + 1, sizeof(GElf_Sym)); - if(sym == NULL) - { + if(sym == NULL) { return scap_errprintf(handle->m_lasterr, 0, "calloc(BPF_MAPS_MAX + 1) failed"); } - for(i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) - { + for(i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) { ASSERT(*nr_maps < BPF_MAPS_MAX + 1); - if(!gelf_getsym(symbols, i, &sym[*nr_maps])) - { + if(!gelf_getsym(symbols, i, &sym[*nr_maps])) { continue; } - if(sym[*nr_maps].st_shndx != maps_shndx) - { + if(sym[*nr_maps].st_shndx != maps_shndx) { continue; } @@ -410,8 +385,7 @@ static int32_t load_elf_maps_section(struct bpf_engine *handle, struct bpf_map_d ASSERT(data_maps->d_size / *nr_maps == sizeof(struct bpf_map_def)); - for(i = 0; i < *nr_maps; i++) - { + for(i = 0; i < *nr_maps; i++) { struct bpf_map_def *def; size_t offset; @@ -425,36 +399,32 @@ static int32_t load_elf_maps_section(struct bpf_engine *handle, struct bpf_map_d return SCAP_SUCCESS; } -static int32_t load_maps(struct bpf_engine *handle, struct bpf_map_data *maps, int nr_maps) -{ +static int32_t load_maps(struct bpf_engine *handle, struct bpf_map_data *maps, int nr_maps) { int j; - for(j = 0; j < nr_maps; ++j) - { - if(j == SCAP_PERF_MAP || - j == SCAP_LOCAL_STATE_MAP || - j == SCAP_FRAME_SCRATCH_MAP || - j == SCAP_TMP_SCRATCH_MAP) - { + for(j = 0; j < nr_maps; ++j) { + if(j == SCAP_PERF_MAP || j == SCAP_LOCAL_STATE_MAP || j == SCAP_FRAME_SCRATCH_MAP || + j == SCAP_TMP_SCRATCH_MAP) { // We allocate entries for all the available CPUs. maps[j].def.max_entries = handle->m_ncpus; } handle->m_bpf_map_fds[j] = bpf_map_create(maps[j].def.type, - maps[j].def.key_size, - maps[j].def.value_size, - maps[j].def.max_entries, - maps[j].def.map_flags); + maps[j].def.key_size, + maps[j].def.value_size, + maps[j].def.max_entries, + maps[j].def.map_flags); maps[j].fd = handle->m_bpf_map_fds[j]; - if(handle->m_bpf_map_fds[j] < 0) - { - return scap_errprintf(handle->m_lasterr, -handle->m_bpf_map_fds[j], "can't create map %d", j); + if(handle->m_bpf_map_fds[j] < 0) { + return scap_errprintf(handle->m_lasterr, + -handle->m_bpf_map_fds[j], + "can't create map %d", + j); } - if(maps[j].def.type == BPF_MAP_TYPE_PROG_ARRAY) - { + if(maps[j].def.type == BPF_MAP_TYPE_PROG_ARRAY) { handle->m_bpf_prog_array_map_idx = j; } } @@ -462,17 +432,19 @@ static int32_t load_maps(struct bpf_engine *handle, struct bpf_map_data *maps, i return SCAP_SUCCESS; } -static int32_t parse_relocations(struct bpf_engine *handle, Elf_Data *data, Elf_Data *symbols, - GElf_Shdr *shdr, struct bpf_insn *insns, - struct bpf_map_data *maps, int nr_maps) -{ +static int32_t parse_relocations(struct bpf_engine *handle, + Elf_Data *data, + Elf_Data *symbols, + GElf_Shdr *shdr, + struct bpf_insn *insns, + struct bpf_map_data *maps, + int nr_maps) { int nrels; int i; nrels = shdr->sh_size / shdr->sh_entsize; - for(i = 0; i < nrels; i++) - { + for(i = 0; i < nrels; i++) { GElf_Sym sym; GElf_Rel rel; unsigned int insn_idx; @@ -489,30 +461,31 @@ static int32_t parse_relocations(struct bpf_engine *handle, Elf_Data *data, Elf_ memcpy(&insn, &insns[insn_idx], sizeof(insn)); - if(insn.code != (BPF_LD | BPF_IMM | BPF_DW)) - { - return scap_errprintf(handle->m_lasterr, 0, "invalid relocation for insn[%d].code 0x%x", insn_idx, insn.code); + if(insn.code != (BPF_LD | BPF_IMM | BPF_DW)) { + return scap_errprintf(handle->m_lasterr, + 0, + "invalid relocation for insn[%d].code 0x%x", + insn_idx, + insn.code); } insn.src_reg = BPF_PSEUDO_MAP_FD; - for(map_idx = 0; map_idx < nr_maps; map_idx++) - { - if(maps[map_idx].elf_offset == sym.st_value) - { + for(map_idx = 0; map_idx < nr_maps; map_idx++) { + if(maps[map_idx].elf_offset == sym.st_value) { match = true; break; } } - if(match) - { + if(match) { insn.imm = maps[map_idx].fd; memcpy(&insns[insn_idx], &insn, sizeof(insn)); - } - else - { - return scap_errprintf(handle->m_lasterr, 0, "invalid relocation for insn[%d] no map_data match\n", insn_idx); + } else { + return scap_errprintf(handle->m_lasterr, + 0, + "invalid relocation for insn[%d] no map_data match\n", + insn_idx); } } @@ -520,8 +493,10 @@ static int32_t parse_relocations(struct bpf_engine *handle, Elf_Data *data, Elf_ } /* load all bpf programs */ -static int32_t load_single_prog(struct bpf_engine* handle, const char *event, struct bpf_insn *prog, int size) -{ +static int32_t load_single_prog(struct bpf_engine *handle, + const char *event, + struct bpf_insn *prog, + int size) { enum bpf_prog_type program_type; size_t insns_cnt; bool raw_tp; @@ -532,27 +507,22 @@ static int32_t load_single_prog(struct bpf_engine* handle, const char *event, st insns_cnt = size / sizeof(struct bpf_insn); char *error = malloc(BPF_LOG_SIZE); - if(!error) - { + if(!error) { return scap_errprintf(handle->m_lasterr, 0, "malloc(BPF_LOG_BUF_SIZE) failed"); } const char *full_event = event; - if(memcmp(event, "raw_tracepoint/", sizeof("raw_tracepoint/") - 1) == 0) - { + if(memcmp(event, "raw_tracepoint/", sizeof("raw_tracepoint/") - 1) == 0) { raw_tp = true; program_type = BPF_PROG_TYPE_RAW_TRACEPOINT; event += sizeof("raw_tracepoint/") - 1; - } - else - { + } else { raw_tp = false; program_type = BPF_PROG_TYPE_TRACEPOINT; event += sizeof("tracepoint/") - 1; } - if(*event == 0) - { + if(*event == 0) { free(error); return scap_errprintf(handle->m_lasterr, 0, "event name cannot be empty"); } @@ -561,25 +531,26 @@ static int32_t load_single_prog(struct bpf_engine* handle, const char *event, st * to the last word after '/', if possible. */ final_section_name = strrchr(event, '/'); - if (final_section_name != NULL) { + if(final_section_name != NULL) { final_section_name++; } else { final_section_name = event; } fd = bpf_load_program(prog, program_type, insns_cnt, error, BPF_LOG_SIZE, final_section_name); - if(fd < 0) - { + if(fd < 0) { /* It is possible than some old kernels don't support the prog_name so in case * of loading failure, we try again the loading without the name. See it in libbpf: * https://github.com/torvalds/linux/blob/16a8829130ca22666ac6236178a6233208d425c3/tools/lib/bpf/libbpf.c#L4833 */ fd = bpf_load_program(prog, program_type, insns_cnt, error, BPF_LOG_SIZE, NULL); - if(fd < 0) - { + if(fd < 0) { fprintf(stderr, "-- BEGIN PROG LOAD LOG --\n%s\n-- END PROG LOAD LOG --\n", error); free(error); - return scap_errprintf(handle->m_lasterr, -fd, "libscap: bpf_load_program() event=%s", full_event); + return scap_errprintf(handle->m_lasterr, + -fd, + "libscap: bpf_load_program() event=%s", + full_event); } } free(error); @@ -588,100 +559,119 @@ static int32_t load_single_prog(struct bpf_engine* handle, const char *event, st * we save the fd and populate the filler table. Note that we store the `fd` to free * the prog at the end of the capture, we will never use it again during the capture! */ - if(memcmp(event, "filler/", sizeof("filler/") - 1) == 0) - { - if(handle->m_tail_called_cnt + 1 >= BPF_PROGS_TAIL_CALLED_MAX) - { - return scap_errprintf(handle->m_lasterr, 0, "libscap: too many tail_called programs recorded: %d (limit is %d)", handle->m_tail_called_cnt + 1 ,BPF_PROGS_TAIL_CALLED_MAX); + if(memcmp(event, "filler/", sizeof("filler/") - 1) == 0) { + if(handle->m_tail_called_cnt + 1 >= BPF_PROGS_TAIL_CALLED_MAX) { + return scap_errprintf( + handle->m_lasterr, + 0, + "libscap: too many tail_called programs recorded: %d (limit is %d)", + handle->m_tail_called_cnt + 1, + BPF_PROGS_TAIL_CALLED_MAX); } handle->m_tail_called_fds[handle->m_tail_called_cnt++] = fd; event += sizeof("filler/") - 1; - if(*event == 0) - { + if(*event == 0) { return scap_errprintf(handle->m_lasterr, 0, "filler name cannot be empty"); } int prog_id = lookup_filler_id(event); - if(prog_id == -1) - { + if(prog_id == -1) { return scap_errprintf(handle->m_lasterr, 0, "invalid filler name: %s", event); - } - else if (prog_id >= BPF_PROGS_TAIL_CALLED_MAX) - { - return scap_errprintf(handle->m_lasterr, 0, "program ID exceeds BPF_PROGS_TAIL_CALLED_MAX limit (%d/%d)", prog_id, BPF_PROGS_TAIL_CALLED_MAX); + } else if(prog_id >= BPF_PROGS_TAIL_CALLED_MAX) { + return scap_errprintf(handle->m_lasterr, + 0, + "program ID exceeds BPF_PROGS_TAIL_CALLED_MAX limit (%d/%d)", + prog_id, + BPF_PROGS_TAIL_CALLED_MAX); } /* Fill the tail table. The key is our filler internal code extracted * from `g_filler_names` in `lookup_filler_id` function. The value * is the program fd. */ - err = bpf_map_update_elem(handle->m_bpf_map_fds[handle->m_bpf_prog_array_map_idx], &prog_id, &fd, BPF_ANY); - if(err < 0) - { + err = bpf_map_update_elem(handle->m_bpf_map_fds[handle->m_bpf_prog_array_map_idx], + &prog_id, + &fd, + BPF_ANY); + if(err < 0) { return scap_errprintf(handle->m_lasterr, -err, "failure populating program array"); } return SCAP_SUCCESS; } - /* If we reach this point we are evaluating a program that should be directly attached to the kernel */ - if(is_sys_enter(event)) - { + /* If we reach this point we are evaluating a program that should be directly attached to the + * kernel */ + if(is_sys_enter(event)) { fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SYS_ENTER], raw_tp, event, fd); } - if(is_sys_exit(event)) - { + if(is_sys_exit(event)) { fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SYS_EXIT], raw_tp, event, fd); } - if(is_sched_proc_exit(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXIT], raw_tp, event, fd); + if(is_sched_proc_exit(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXIT], + raw_tp, + event, + fd); } - if(is_sched_switch(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_SWITCH], raw_tp, event, fd); + if(is_sched_switch(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_SWITCH], + raw_tp, + event, + fd); } - if(is_page_fault_user(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_PAGE_FAULT_USER], raw_tp, event, fd); + if(is_page_fault_user(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_PAGE_FAULT_USER], + raw_tp, + event, + fd); } - if(is_page_fault_kernel(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_PAGE_FAULT_KERNEL], raw_tp, event, fd); + if(is_page_fault_kernel(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_PAGE_FAULT_KERNEL], + raw_tp, + event, + fd); } - if(is_signal_deliver(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SIGNAL_DELIVER], raw_tp, event, fd); + if(is_signal_deliver(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SIGNAL_DELIVER], + raw_tp, + event, + fd); } - if(is_sched_prog_fork_move_args(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS], raw_tp, event, fd); + if(is_sched_prog_fork_move_args(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS], + raw_tp, + event, + fd); } - if(is_sched_prog_fork_missing_child(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD], raw_tp, event, fd); + if(is_sched_prog_fork_missing_child(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD], + raw_tp, + event, + fd); } - if(is_sched_prog_exec_missing_exit(event)) - { - fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT], raw_tp, event, fd); + if(is_sched_prog_exec_missing_exit(event)) { + fill_attached_prog_info(&handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT], + raw_tp, + event, + fd); } return SCAP_SUCCESS; } -static int32_t load_bpf_file(struct bpf_engine *handle) -{ +static int32_t load_bpf_file(struct bpf_engine *handle) { int j; int maps_shndx = 0; int strtabidx = 0; @@ -699,130 +689,118 @@ static int32_t load_bpf_file(struct bpf_engine *handle) bool got_api_version = false; bool got_schema_version = false; - if(uname(&osname)) - { + if(uname(&osname)) { return scap_errprintf(handle->m_lasterr, errno, "can't call uname()"); } - if(elf_version(EV_CURRENT) == EV_NONE) - { + if(elf_version(EV_CURRENT) == EV_NONE) { return scap_errprintf(handle->m_lasterr, 0, "invalid ELF version"); } - if (!handle->elf) - { + if(!handle->elf) { handle->program_fd = open(handle->m_filepath, O_RDONLY, 0); - if(handle->program_fd < 0) - { - return scap_errprintf(handle->m_lasterr, 0, "can't open BPF probe '%s'", handle->m_filepath); + if(handle->program_fd < 0) { + return scap_errprintf(handle->m_lasterr, + 0, + "can't open BPF probe '%s'", + handle->m_filepath); } handle->elf = elf_begin(handle->program_fd, ELF_C_READ_MMAP_PRIVATE, NULL); - if(!handle->elf) - { + if(!handle->elf) { scap_errprintf(handle->m_lasterr, 0, "can't read ELF format"); goto end; } - if(gelf_getehdr(handle->elf, &handle->ehdr) != &handle->ehdr) - { + if(gelf_getehdr(handle->elf, &handle->ehdr) != &handle->ehdr) { scap_errprintf(handle->m_lasterr, 0, "can't read ELF header"); goto end; } - for(j = 0; j < handle->ehdr.e_shnum; ++j) - { - if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != SCAP_SUCCESS) - { + for(j = 0; j < handle->ehdr.e_shnum; ++j) { + if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != + SCAP_SUCCESS) { continue; } - if(strcmp(shname, "maps") == 0) - { + if(strcmp(shname, "maps") == 0) { maps_shndx = j; - } - else if(shdr.sh_type == SHT_SYMTAB) - { + } else if(shdr.sh_type == SHT_SYMTAB) { strtabidx = shdr.sh_link; symbols = data; - } - else if(strcmp(shname, "kernel_version") == 0) - { - if(strcmp(osname.release, data->d_buf)) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "BPF probe is compiled for %s, but running version is %s", - (char *)data->d_buf, osname.release); + } else if(strcmp(shname, "kernel_version") == 0) { + if(strcmp(osname.release, data->d_buf)) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "BPF probe is compiled for %s, but running version is %s", + (char *)data->d_buf, + osname.release); goto end; } - } - else if(strcmp(shname, "api_version") == 0) - { + } else if(strcmp(shname, "api_version") == 0) { got_api_version = true; memcpy(&handle->m_api_version, data->d_buf, sizeof(handle->m_api_version)); - } - else if(strcmp(shname, "schema_version") == 0) - { + } else if(strcmp(shname, "schema_version") == 0) { got_schema_version = true; memcpy(&handle->m_schema_version, data->d_buf, sizeof(handle->m_schema_version)); - } - else if(strcmp(shname, "license") == 0) - { + } else if(strcmp(shname, "license") == 0) { license = data->d_buf; snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "BPF probe license is %s", license); } } - if(!got_api_version) - { + if(!got_api_version) { snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "missing api_version section"); goto end; } - if(!got_schema_version) - { + if(!got_schema_version) { snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "missing schema_version section"); goto end; } - if(!symbols) - { + if(!symbols) { snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "missing SHT_SYMTAB section"); goto end; } - if(maps_shndx) - { - if(load_elf_maps_section(handle, maps, maps_shndx, handle->elf, symbols, strtabidx, &nr_maps) != SCAP_SUCCESS) - { + if(maps_shndx) { + if(load_elf_maps_section(handle, + maps, + maps_shndx, + handle->elf, + symbols, + strtabidx, + &nr_maps) != SCAP_SUCCESS) { goto end; } - if(load_maps(handle, maps, nr_maps) != SCAP_SUCCESS) - { + if(load_maps(handle, maps, nr_maps) != SCAP_SUCCESS) { goto end; } } - for(j = 0; j < handle->ehdr.e_shnum; ++j) - { - if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != SCAP_SUCCESS) - { + for(j = 0; j < handle->ehdr.e_shnum; ++j) { + if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != + SCAP_SUCCESS) { continue; } - if(shdr.sh_type == SHT_REL) - { + if(shdr.sh_type == SHT_REL) { struct bpf_insn *insns; - if(get_elf_section(handle->elf, shdr.sh_info, &handle->ehdr, &shname_prog, &shdr_prog, &data_prog) != SCAP_SUCCESS) - { + if(get_elf_section(handle->elf, + shdr.sh_info, + &handle->ehdr, + &shname_prog, + &shdr_prog, + &data_prog) != SCAP_SUCCESS) { continue; } insns = (struct bpf_insn *)data_prog->d_buf; - if(parse_relocations(handle, data, symbols, &shdr, insns, maps, nr_maps)) - { + if(parse_relocations(handle, data, symbols, &shdr, insns, maps, nr_maps)) { continue; } } @@ -833,25 +811,19 @@ static int32_t load_bpf_file(struct bpf_engine *handle) return res; } -static int load_all_progs(struct bpf_engine *handle) -{ +static int load_all_progs(struct bpf_engine *handle) { GElf_Shdr shdr; Elf_Data *data; char *shname; - for(int j = 0; j < handle->ehdr.e_shnum; ++j) - { - if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != SCAP_SUCCESS) - { + for(int j = 0; j < handle->ehdr.e_shnum; ++j) { + if(get_elf_section(handle->elf, j, &handle->ehdr, &shname, &shdr, &data) != SCAP_SUCCESS) { continue; } if(memcmp(shname, "tracepoint/", sizeof("tracepoint/") - 1) == 0 || - memcmp(shname, "raw_tracepoint/", sizeof("raw_tracepoint/") - 1) == 0) - { - - if(load_single_prog(handle, shname, data->d_buf, data->d_size) != SCAP_SUCCESS) - { + memcmp(shname, "raw_tracepoint/", sizeof("raw_tracepoint/") - 1) == 0) { + if(load_single_prog(handle, shname, data->d_buf, data->d_size) != SCAP_SUCCESS) { return SCAP_FAILURE; } } @@ -859,8 +831,10 @@ static int load_all_progs(struct bpf_engine *handle) return SCAP_SUCCESS; } -static void *perf_event_mmap(struct bpf_engine *handle, int fd, unsigned long *size, unsigned long buf_bytes_dim) -{ +static void *perf_event_mmap(struct bpf_engine *handle, + int fd, + unsigned long *size, + unsigned long buf_bytes_dim) { int page_size = getpagesize(); unsigned long ring_size = buf_bytes_dim; int header_size = page_size; @@ -873,17 +847,26 @@ static void *perf_event_mmap(struct bpf_engine *handle, int fd, unsigned long *s // void *tmp = mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); - if(tmp == MAP_FAILED) - { - scap_errprintf(handle->m_lasterr, errno, "mmap (1) failed (If you get memory allocation errors try to reduce the buffer dimension)"); + if(tmp == MAP_FAILED) { + scap_errprintf(handle->m_lasterr, + errno, + "mmap (1) failed (If you get memory allocation errors try to reduce the " + "buffer dimension)"); return MAP_FAILED; } // Map the second copy to allow us to handle the wrap case normally - void *p1 = mmap(tmp + ring_size, ring_size + header_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0); - if(p1 == MAP_FAILED) - { - scap_errprintf(handle->m_lasterr, errno, "mmap (2) failed (If you get memory allocation errors try to reduce the buffer dimension)"); + void *p1 = mmap(tmp + ring_size, + ring_size + header_size, + PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_FIXED, + fd, + 0); + if(p1 == MAP_FAILED) { + scap_errprintf(handle->m_lasterr, + errno, + "mmap (2) failed (If you get memory allocation errors try to reduce the " + "buffer dimension)"); munmap(tmp, total_size); return MAP_FAILED; } @@ -891,10 +874,17 @@ static void *perf_event_mmap(struct bpf_engine *handle, int fd, unsigned long *s ASSERT(p1 == tmp + ring_size); // Map the main copy - void *p2 = mmap(tmp, ring_size + header_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0); - if(p2 == MAP_FAILED) - { - scap_errprintf(handle->m_lasterr, errno, "mmap (3) failed (If you get memory allocation errors try to reduce the buffer dimension)"); + void *p2 = mmap(tmp, + ring_size + header_size, + PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_FIXED, + fd, + 0); + if(p2 == MAP_FAILED) { + scap_errprintf(handle->m_lasterr, + errno, + "mmap (3) failed (If you get memory allocation errors try to reduce the " + "buffer dimension)"); munmap(tmp, total_size); return MAP_FAILED; } @@ -906,61 +896,69 @@ static void *perf_event_mmap(struct bpf_engine *handle, int fd, unsigned long *s return tmp; } -static int32_t populate_syscall_table_map(struct bpf_engine *handle) -{ +static int32_t populate_syscall_table_map(struct bpf_engine *handle) { int j; int ret; - for(j = 0; j < SYSCALL_TABLE_SIZE; ++j) - { + for(j = 0; j < SYSCALL_TABLE_SIZE; ++j) { const struct syscall_evt_pair *p = &g_syscall_table[j]; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SYSCALL_TABLE], &j, p, BPF_ANY)) != 0) - { - return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SYSCALL_TABLE bpf_map_update_elem"); + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SYSCALL_TABLE], &j, p, BPF_ANY)) != + 0) { + return scap_errprintf(handle->m_lasterr, + -ret, + "SCAP_SYSCALL_TABLE bpf_map_update_elem"); } } return bpf_map_freeze(handle->m_bpf_map_fds[SCAP_SYSCALL_TABLE]); } -static int32_t set_single_syscall_of_interest(struct bpf_engine *handle, int syscall_id, bool interesting) -{ +static int32_t set_single_syscall_of_interest(struct bpf_engine *handle, + int syscall_id, + bool interesting) { int ret = 0; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_INTERESTING_SYSCALLS_TABLE], &syscall_id, &interesting, BPF_ANY)) != 0) - { - return scap_errprintf(handle->m_lasterr, -ret, "SCAP_INTERESTING_SYSCALLS_TABLE unable to update syscall: %d", syscall_id); + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_INTERESTING_SYSCALLS_TABLE], + &syscall_id, + &interesting, + BPF_ANY)) != 0) { + return scap_errprintf(handle->m_lasterr, + -ret, + "SCAP_INTERESTING_SYSCALLS_TABLE unable to update syscall: %d", + syscall_id); } return SCAP_SUCCESS; } -static int32_t populate_event_table_map(struct bpf_engine *handle) -{ +static int32_t populate_event_table_map(struct bpf_engine *handle) { int j; int ret; - for(j = 0; j < PPM_EVENT_MAX; ++j) - { + for(j = 0; j < PPM_EVENT_MAX; ++j) { const struct ppm_event_info *e = &g_event_info[j]; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_EVENT_INFO_TABLE], &j, e, BPF_ANY)) != 0) - { - return scap_errprintf(handle->m_lasterr, -ret, "SCAP_EVENT_INFO_TABLE bpf_map_update_elem"); + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_EVENT_INFO_TABLE], + &j, + e, + BPF_ANY)) != 0) { + return scap_errprintf(handle->m_lasterr, + -ret, + "SCAP_EVENT_INFO_TABLE bpf_map_update_elem"); } } return bpf_map_freeze(handle->m_bpf_map_fds[SCAP_EVENT_INFO_TABLE]); } -static int32_t populate_fillers_table_map(struct bpf_engine *handle) -{ +static int32_t populate_fillers_table_map(struct bpf_engine *handle) { int j; int ret; - for(j = 0; j < PPM_EVENT_MAX; ++j) - { + for(j = 0; j < PPM_EVENT_MAX; ++j) { const struct ppm_event_entry *e = &g_ppm_events[j]; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_FILLERS_TABLE], &j, e, BPF_ANY)) != 0) - { - return scap_errprintf(handle->m_lasterr, -ret, "SCAP_FILLERS_TABLE bpf_map_update_elem "); + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_FILLERS_TABLE], &j, e, BPF_ANY)) != + 0) { + return scap_errprintf(handle->m_lasterr, + -ret, + "SCAP_FILLERS_TABLE bpf_map_update_elem "); } } @@ -973,35 +971,33 @@ static int32_t populate_fillers_table_map(struct bpf_engine *handle) return bpf_map_freeze(handle->m_bpf_map_fds[SCAP_FILLERS_TABLE]); } -static int32_t populate_ia32_to_64_map(struct bpf_engine *handle) -{ +static int32_t populate_ia32_to_64_map(struct bpf_engine *handle) { int j; int ret; - for(j = 0; j < SYSCALL_TABLE_SIZE; ++j) - { + for(j = 0; j < SYSCALL_TABLE_SIZE; ++j) { // Note: we will map all syscalls from the upper limit of the ia32 table // up to SYSCALL_TABLE_SIZE to 0 (because they are not set in the g_ia32_64_map). // 0 is read on x86_64; this is not a problem though because // we will never receive a 32bit syscall above the upper limit, since it won't be existent const int *x64_val = &g_ia32_64_map[j]; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_IA32_64_MAP], &j, x64_val, - BPF_ANY)) != 0) - { - return scap_errprintf(handle->m_lasterr, -ret, - "SCAP_FILLERS_TABLE bpf_map_update_elem "); + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_IA32_64_MAP], + &j, + x64_val, + BPF_ANY)) != 0) { + return scap_errprintf(handle->m_lasterr, + -ret, + "SCAP_FILLERS_TABLE bpf_map_update_elem "); } } return bpf_map_freeze(handle->m_bpf_map_fds[SCAP_IA32_64_MAP]); } -static int enforce_sc_set(struct bpf_engine* handle) -{ +static int enforce_sc_set(struct bpf_engine *handle) { /* handle->capturing == false means that we want to disable the capture */ - bool* sc_set = handle->curr_sc_set.ppm_sc; + bool *sc_set = handle->curr_sc_set.ppm_sc; bool empty_sc_set[PPM_SC_MAX] = {0}; - if(!handle->capturing) - { + if(!handle->capturing) { /* empty set to erase all */ sc_set = empty_sc_set; } @@ -1016,21 +1012,16 @@ static int enforce_sc_set(struct bpf_engine* handle) bool sched_prog_exec = false; /* Enforce interesting syscalls */ - for(int sc = 0; sc < PPM_SC_MAX; sc++) - { + for(int sc = 0; sc < PPM_SC_MAX; sc++) { syscall_id = scap_ppm_sc_to_native_id(sc); /* if `syscall_id` is -1 this is not a syscall */ - if(syscall_id == -1) - { + if(syscall_id == -1) { continue; } - if(!sc_set[sc]) - { + if(!sc_set[sc]) { set_single_syscall_of_interest(handle, syscall_id, false); - } - else - { + } else { sys_enter = true; sys_exit = true; sched_prog_fork_move_args = true; @@ -1038,90 +1029,105 @@ static int enforce_sc_set(struct bpf_engine* handle) } } - if(sc_set[PPM_SC_FORK] || - sc_set[PPM_SC_VFORK] || - sc_set[PPM_SC_CLONE] || - sc_set[PPM_SC_CLONE3]) - { + if(sc_set[PPM_SC_FORK] || sc_set[PPM_SC_VFORK] || sc_set[PPM_SC_CLONE] || + sc_set[PPM_SC_CLONE3]) { sched_prog_fork_missing_child = true; } - if(sc_set[PPM_SC_EXECVE] || - sc_set[PPM_SC_EXECVEAT]) - { + if(sc_set[PPM_SC_EXECVE] || sc_set[PPM_SC_EXECVEAT]) { sched_prog_exec = true; } /* Enable desired tracepoints */ if(sys_enter) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SYS_ENTER]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SYS_ENTER]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SYS_ENTER])); if(sys_exit) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SYS_EXIT]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SYS_EXIT]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SYS_EXIT])); if(sched_prog_fork_move_args) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog( + &(handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MOVE_ARGS])); if(sched_prog_fork_missing_child) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs + [BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_FORK_MISSING_CHILD])); if(sched_prog_exec) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog( + &(handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXEC_MISSING_EXIT])); if(sc_set[PPM_SC_SCHED_PROCESS_EXIT]) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXIT]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXIT]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_PROC_EXIT])); if(sc_set[PPM_SC_SCHED_SWITCH]) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_SWITCH]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_SWITCH]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SCHED_SWITCH])); if(sc_set[PPM_SC_PAGE_FAULT_USER]) - ret = ret ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_PAGE_FAULT_USER]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_PAGE_FAULT_USER]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_PAGE_FAULT_USER])); if(sc_set[PPM_SC_PAGE_FAULT_KERNEL]) - ret = ret?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_PAGE_FAULT_KERNEL]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_PAGE_FAULT_KERNEL]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_PAGE_FAULT_KERNEL])); if(sc_set[PPM_SC_SIGNAL_DELIVER]) - ret = ret?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SIGNAL_DELIVER]), handle->m_lasterr); + ret = ret + ?: attach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SIGNAL_DELIVER]), + handle->m_lasterr); else detach_bpf_prog(&(handle->m_attached_progs[BPF_PROG_SIGNAL_DELIVER])); return ret; } -int32_t scap_bpf_start_capture(struct scap_engine_handle engine) -{ - struct bpf_engine* handle = engine.m_handle; +int32_t scap_bpf_start_capture(struct scap_engine_handle engine) { + struct bpf_engine *handle = engine.m_handle; int32_t rc = 0; /* Here we are covering the case in which some syscalls don't have an associated ppm_sc * and so we cannot set them as (un)interesting. For this reason, we default them to 0. - * Please note this is an extra check since our ppm_sc should already cover all possible syscalls. - * Ideally we should do this only once, but right now in our code we don't have a "right" place to do it. - * We need to move it, if `scap_start_capture` will be called frequently in our flow, right now in live mode, it - * should be called only once... + * Please note this is an extra check since our ppm_sc should already cover all possible + * syscalls. Ideally we should do this only once, but right now in our code we don't have a + * "right" place to do it. We need to move it, if `scap_start_capture` will be called frequently + * in our flow, right now in live mode, it should be called only once... */ - for(int i = 0; i < SYSCALL_TABLE_SIZE; i++) - { + for(int i = 0; i < SYSCALL_TABLE_SIZE; i++) { rc = set_single_syscall_of_interest(handle, i, false); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } } @@ -1129,9 +1135,8 @@ int32_t scap_bpf_start_capture(struct scap_engine_handle engine) return enforce_sc_set(handle); } -int32_t scap_bpf_stop_capture(struct scap_engine_handle engine) -{ - struct bpf_engine* handle = engine.m_handle; +int32_t scap_bpf_stop_capture(struct scap_engine_handle engine) { + struct bpf_engine *handle = engine.m_handle; handle->capturing = false; return enforce_sc_set(handle); } @@ -1142,189 +1147,191 @@ int32_t scap_bpf_stop_capture(struct scap_engine_handle engine) // at the beginning so the calibration will surely take place. // For more info, read the corresponding filler in kernel space. // -static int32_t calibrate_socket_file_ops(struct scap_engine_handle engine) -{ +static int32_t calibrate_socket_file_ops(struct scap_engine_handle engine) { /* We just need to enable the socket syscall for the socket calibration */ HANDLE(engine)->curr_sc_set.ppm_sc[PPM_SC_SOCKET] = 1; - if(scap_bpf_start_capture(engine) != SCAP_SUCCESS) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "unable to set the socket syscall for the calibration"); + if(scap_bpf_start_capture(engine) != SCAP_SUCCESS) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "unable to set the socket syscall for the calibration"); } int fd = socket(AF_INET, SOCK_DGRAM, 0); - if(fd == -1) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "unable to create a socket for the calibration"); + if(fd == -1) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "unable to create a socket for the calibration"); } close(fd); /* We need to stop the capture */ - if(scap_bpf_stop_capture(engine) != SCAP_SUCCESS) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "unable to stop the capture after the calibration"); + if(scap_bpf_stop_capture(engine) != SCAP_SUCCESS) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "unable to stop the capture after the calibration"); } return SCAP_SUCCESS; } -int32_t scap_bpf_set_snaplen(struct scap_engine_handle engine, uint32_t snaplen) -{ +int32_t scap_bpf_set_snaplen(struct scap_engine_handle engine, uint32_t snaplen) { struct scap_bpf_settings settings; struct bpf_engine *handle = engine.m_handle; int k = 0; int ret; - if(snaplen > SNAPLEN_MAX) - { + if(snaplen > SNAPLEN_MAX) { return scap_errprintf(handle->m_lasterr, 0, "snaplen can't exceed %d\n", SNAPLEN_MAX); } - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.snaplen = snaplen; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_set_fullcapture_port_range(struct scap_engine_handle engine, uint16_t range_start, uint16_t range_end) -{ +int32_t scap_bpf_set_fullcapture_port_range(struct scap_engine_handle engine, + uint16_t range_start, + uint16_t range_end) { struct scap_bpf_settings settings; struct bpf_engine *handle = engine.m_handle; int k = 0; int ret; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.fullcapture_port_range_start = range_start; settings.fullcapture_port_range_end = range_end; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_set_statsd_port(struct scap_engine_handle engine, const uint16_t port) -{ +int32_t scap_bpf_set_statsd_port(struct scap_engine_handle engine, const uint16_t port) { struct scap_bpf_settings settings = {}; struct bpf_engine *handle = engine.m_handle; int k = 0; int ret; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.statsd_port = port; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_disable_dynamic_snaplen(struct scap_engine_handle engine) -{ +int32_t scap_bpf_disable_dynamic_snaplen(struct scap_engine_handle engine) { struct scap_bpf_settings settings; struct bpf_engine *handle = engine.m_handle; int k = 0; int ret; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.do_dynamic_snaplen = false; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_start_dropping_mode(struct scap_engine_handle engine, uint32_t sampling_ratio) -{ +int32_t scap_bpf_start_dropping_mode(struct scap_engine_handle engine, uint32_t sampling_ratio) { struct bpf_engine *handle = engine.m_handle; struct scap_bpf_settings settings; int k = 0; int ret; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.sampling_ratio = sampling_ratio; settings.dropping_mode = true; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_stop_dropping_mode(struct scap_engine_handle engine) -{ +int32_t scap_bpf_stop_dropping_mode(struct scap_engine_handle engine) { struct scap_bpf_settings settings; struct bpf_engine *handle = engine.m_handle; int k = 0; int ret; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.sampling_ratio = 1; settings.dropping_mode = false; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_enable_dynamic_snaplen(struct scap_engine_handle engine) -{ +int32_t scap_bpf_enable_dynamic_snaplen(struct scap_engine_handle engine) { struct scap_bpf_settings settings; struct bpf_engine *handle = engine.m_handle; int k = 0; int ret; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.do_dynamic_snaplen = true; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_close(struct scap_engine_handle engine) -{ +int32_t scap_bpf_close(struct scap_engine_handle engine) { struct bpf_engine *handle = engine.m_handle; struct scap_device_set *devset = &handle->m_dev_set; @@ -1332,44 +1339,35 @@ int32_t scap_bpf_close(struct scap_engine_handle engine) devset_free(devset); /* Unload all tail called progs */ - for(int j = 0; j < BPF_PROGS_TAIL_CALLED_MAX; j++) - { - if(handle->m_tail_called_fds[j] != -1) - { + for(int j = 0; j < BPF_PROGS_TAIL_CALLED_MAX; j++) { + if(handle->m_tail_called_fds[j] != -1) { close(handle->m_tail_called_fds[j]); } } handle->m_tail_called_cnt = 0; - - for(int j = 0; j < BPF_PROG_ATTACHED_MAX; j++) - { + for(int j = 0; j < BPF_PROG_ATTACHED_MAX; j++) { detach_bpf_prog(&handle->m_attached_progs[j]); unload_bpf_prog(&handle->m_attached_progs[j]); } handle->m_bpf_prog_array_map_idx = -1; - if (handle->elf) - { + if(handle->elf) { elf_end(handle->elf); handle->elf = NULL; } - if (handle->m_stats) - { + if(handle->m_stats) { free(handle->m_stats); handle->m_stats = NULL; } - if (handle->program_fd > 0) - { + if(handle->program_fd > 0) { close(handle->program_fd); handle->program_fd = -1; } - for(int i = 0; i < BPF_MAPS_MAX; i++) - { - if(handle->m_bpf_map_fds[i] >= 0) - { + for(int i = 0; i < BPF_MAPS_MAX; i++) { + if(handle->m_bpf_map_fds[i] >= 0) { close(handle->m_bpf_map_fds[i]); handle->m_bpf_map_fds[i] = -1; } @@ -1378,61 +1376,63 @@ int32_t scap_bpf_close(struct scap_engine_handle engine) return SCAP_SUCCESS; } -static int32_t set_runtime_params(struct bpf_engine *handle) -{ +static int32_t set_runtime_params(struct bpf_engine *handle) { struct rlimit rl; rl.rlim_max = RLIM_INFINITY; rl.rlim_cur = rl.rlim_max; - if(setrlimit(RLIMIT_MEMLOCK, &rl)) - { + if(setrlimit(RLIMIT_MEMLOCK, &rl)) { return scap_errprintf(handle->m_lasterr, errno, "setrlimit failed"); } FILE *f = fopen("/proc/sys/net/core/bpf_jit_enable", "w"); - if(!f) - { - // snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "Can't open /proc/sys/net/core/bpf_jit_enable"); - // return SCAP_FAILURE; + if(!f) { + // snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "Can't open + // /proc/sys/net/core/bpf_jit_enable"); return SCAP_FAILURE; // Not every kernel has BPF_JIT enabled. Fix this after COS changes. return SCAP_SUCCESS; } - if(fprintf(f, "1") != 1) - { + if(fprintf(f, "1") != 1) { int err = errno; fclose(f); - return scap_errprintf(handle->m_lasterr, err, "Can't write to /proc/sys/net/core/bpf_jit_enable"); + return scap_errprintf(handle->m_lasterr, + err, + "Can't write to /proc/sys/net/core/bpf_jit_enable"); } fclose(f); f = fopen("/proc/sys/net/core/bpf_jit_harden", "w"); - if(!f) - { - return scap_errprintf(handle->m_lasterr, errno, "Can't open /proc/sys/net/core/bpf_jit_harden"); + if(!f) { + return scap_errprintf(handle->m_lasterr, + errno, + "Can't open /proc/sys/net/core/bpf_jit_harden"); } - if(fprintf(f, "0") != 1) - { + if(fprintf(f, "0") != 1) { int err = errno; fclose(f); - return scap_errprintf(handle->m_lasterr, err, "Can't write to /proc/sys/net/core/bpf_jit_harden"); + return scap_errprintf(handle->m_lasterr, + err, + "Can't write to /proc/sys/net/core/bpf_jit_harden"); } fclose(f); f = fopen("/proc/sys/net/core/bpf_jit_kallsyms", "w"); - if(!f) - { - return scap_errprintf(handle->m_lasterr, errno, "Can't open /proc/sys/net/core/bpf_jit_kallsyms"); + if(!f) { + return scap_errprintf(handle->m_lasterr, + errno, + "Can't open /proc/sys/net/core/bpf_jit_kallsyms"); } - if(fprintf(f, "1") != 1) - { + if(fprintf(f, "1") != 1) { int err = errno; fclose(f); - return scap_errprintf(handle->m_lasterr, err, "Can't write to /proc/sys/net/core/bpf_jit_kallsyms"); + return scap_errprintf(handle->m_lasterr, + err, + "Can't write to /proc/sys/net/core/bpf_jit_kallsyms"); } fclose(f); @@ -1440,13 +1440,11 @@ static int32_t set_runtime_params(struct bpf_engine *handle) return SCAP_SUCCESS; } -static int32_t set_default_settings(struct bpf_engine *handle) -{ +static int32_t set_default_settings(struct bpf_engine *handle) { struct scap_bpf_settings settings; uint64_t boot_time = 0; - if(scap_get_precise_boot_time(handle->m_lasterr, &boot_time) != SCAP_SUCCESS) - { + if(scap_get_precise_boot_time(handle->m_lasterr, &boot_time) != SCAP_SUCCESS) { return SCAP_FAILURE; } @@ -1465,64 +1463,54 @@ static int32_t set_default_settings(struct bpf_engine *handle) int k = 0; int ret; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -int32_t scap_bpf_load( - struct bpf_engine *handle, - const char *bpf_probe, - scap_open_args *oargs) -{ - struct scap_bpf_engine_params* bpf_args = oargs->engine_params; +int32_t scap_bpf_load(struct bpf_engine *handle, const char *bpf_probe, scap_open_args *oargs) { + struct scap_bpf_engine_params *bpf_args = oargs->engine_params; - if(set_runtime_params(handle) != SCAP_SUCCESS) - { + if(set_runtime_params(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } handle->m_bpf_prog_array_map_idx = -1; - if(!bpf_probe) - { + if(!bpf_probe) { ASSERT(false); return SCAP_FAILURE; } snprintf(handle->m_filepath, PATH_MAX, "%s", bpf_probe); - if(load_bpf_file(handle) != SCAP_SUCCESS) - { + if(load_bpf_file(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } /* load all progs but don't attach anything */ - if(load_all_progs(handle) != SCAP_SUCCESS) - { + if(load_all_progs(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } - if(populate_syscall_table_map(handle) != SCAP_SUCCESS) - { + if(populate_syscall_table_map(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } - if(populate_event_table_map(handle) != SCAP_SUCCESS) - { + if(populate_event_table_map(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } - if(populate_fillers_table_map(handle) != SCAP_SUCCESS) - { + if(populate_fillers_table_map(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } - if (populate_ia32_to_64_map(handle) != SCAP_SUCCESS) - { + if(populate_ia32_to_64_map(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } @@ -1533,19 +1521,18 @@ int32_t scap_bpf_load( uint32_t online_idx = 0; // devset->m_ndevs = online CPUs in the system. // handle->m_ncpus = available CPUs in the system. - for(uint32_t cpu_idx = 0; online_idx < devset->m_ndevs && cpu_idx < handle->m_ncpus; ++cpu_idx) - { + for(uint32_t cpu_idx = 0; online_idx < devset->m_ndevs && cpu_idx < handle->m_ncpus; + ++cpu_idx) { struct perf_event_attr attr = { - .sample_type = PERF_SAMPLE_RAW, - .type = PERF_TYPE_SOFTWARE, - .config = PERF_COUNT_SW_BPF_OUTPUT, + .sample_type = PERF_SAMPLE_RAW, + .type = PERF_TYPE_SOFTWARE, + .config = PERF_COUNT_SW_BPF_OUTPUT, }; int pmu_fd = 0; int ret = 0; /* We suppose that CPU 0 is always online, so we only check for cpu_idx > 0 */ - if(cpu_idx > 0) - { + if(cpu_idx > 0) { char filename[SCAP_MAX_PATH_SIZE]; FILE *fp; int online = 0; @@ -1553,26 +1540,21 @@ int32_t scap_bpf_load( snprintf(filename, sizeof(filename), "/sys/devices/system/cpu/cpu%d/online", cpu_idx); fp = fopen(filename, "r"); - if(fp == NULL) - { + if(fp == NULL) { // When missing NUMA properties, CPUs do not expose online information. // Fallback at considering them online if we can at least reach their folder. // This is useful for example for raspPi devices. // See: https://github.com/kubernetes/kubernetes/issues/95039 snprintf(filename, sizeof(filename), "/sys/devices/system/cpu/cpu%d/", cpu_idx); - if (access(filename, F_OK) == 0) - { + if(access(filename, F_OK) == 0) { online = 1; } // If we can't access the cpu, count it as offline. // Some VMs or hyperthreading systems export an high number of configured CPUs, - // even if they are not existing. See https://github.com/falcosecurity/falco/issues/2843 for example. - // Skip them. - } - else - { - if(fscanf(fp, "%d", &online) != 1) - { + // even if they are not existing. See + // https://github.com/falcosecurity/falco/issues/2843 for example. Skip them. + } else { + if(fscanf(fp, "%d", &online) != 1) { int err = errno; fclose(fp); @@ -1581,16 +1563,17 @@ int32_t scap_bpf_load( fclose(fp); } - if(!online) - { + if(!online) { continue; } } pmu_fd = sys_perf_event_open(&attr, -1, cpu_idx, -1, 0); - if(pmu_fd < 0) - { - return scap_errprintf(handle->m_lasterr, -pmu_fd, "unable to open the perf-buffer for cpu '%d'", cpu_idx); + if(pmu_fd < 0) { + return scap_errprintf(handle->m_lasterr, + -pmu_fd, + "unable to open the perf-buffer for cpu '%d'", + cpu_idx); } struct scap_device *dev = &devset->m_devs[online_idx]; @@ -1598,65 +1581,80 @@ int32_t scap_bpf_load( // if some CPUs are not online some entries of the `SCAP_PERF_MAP` buffer will be empty. // if the ebpf driver will try to access these empty entries it will face a `ENOENT`. - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_PERF_MAP], &cpu_idx, &pmu_fd, BPF_ANY)) != 0) - { - return scap_errprintf(handle->m_lasterr, -ret, "unable to update the SCAP_PERF_MAP map for cpu '%d'", cpu_idx); + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_PERF_MAP], + &cpu_idx, + &pmu_fd, + BPF_ANY)) != 0) { + return scap_errprintf(handle->m_lasterr, + -ret, + "unable to update the SCAP_PERF_MAP map for cpu '%d'", + cpu_idx); } - if(ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) - { - return scap_errprintf(handle->m_lasterr, errno, "unable to call PERF_EVENT_IOC_ENABLE on the fd for cpu '%d'", cpu_idx); + if(ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) { + return scap_errprintf(handle->m_lasterr, + errno, + "unable to call PERF_EVENT_IOC_ENABLE on the fd for cpu '%d'", + cpu_idx); } // // Map the ring buffer // - dev->m_buffer = perf_event_mmap(handle, pmu_fd, &dev->m_mmap_size, bpf_args->buffer_bytes_dim); + dev->m_buffer = + perf_event_mmap(handle, pmu_fd, &dev->m_mmap_size, bpf_args->buffer_bytes_dim); dev->m_buffer_size = bpf_args->buffer_bytes_dim; - if(dev->m_buffer == MAP_FAILED) - { - return scap_errprintf(handle->m_lasterr, errno, "unable to mmap the perf-buffer for cpu '%d'", cpu_idx); + if(dev->m_buffer == MAP_FAILED) { + return scap_errprintf(handle->m_lasterr, + errno, + "unable to mmap the perf-buffer for cpu '%d'", + cpu_idx); } online_idx++; } // Check that we parsed all online CPUs - if(online_idx != devset->m_ndevs) - { - return scap_errprintf(handle->m_lasterr, 0, "mismatch, processors online after the 'for' loop: %d, '_SC_NPROCESSORS_ONLN' before the 'for' loop: %d", online_idx, devset->m_ndevs); + if(online_idx != devset->m_ndevs) { + return scap_errprintf(handle->m_lasterr, + 0, + "mismatch, processors online after the 'for' loop: %d, " + "'_SC_NPROCESSORS_ONLN' before the 'for' loop: %d", + online_idx, + devset->m_ndevs); } // Check that no CPUs were hotplugged during the for loop uint32_t final_ndevs = sysconf(_SC_NPROCESSORS_ONLN); - if(final_ndevs == -1) - { - return scap_errprintf(handle->m_lasterr, errno, "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN' to check against the previous value"); - } - if (online_idx != final_ndevs) - { - return scap_errprintf(handle->m_lasterr, 0, "mismatch, processors online after the 'for' loop: %d, '_SC_NPROCESSORS_ONLN' after the 'for' loop: %d", online_idx, final_ndevs); - } - - - if(set_default_settings(handle) != SCAP_SUCCESS) - { + if(final_ndevs == -1) { + return scap_errprintf(handle->m_lasterr, + errno, + "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN' " + "to check against the previous value"); + } + if(online_idx != final_ndevs) { + return scap_errprintf(handle->m_lasterr, + 0, + "mismatch, processors online after the 'for' loop: %d, " + "'_SC_NPROCESSORS_ONLN' after the 'for' loop: %d", + online_idx, + final_ndevs); + } + + if(set_default_settings(handle) != SCAP_SUCCESS) { return SCAP_FAILURE; } return SCAP_SUCCESS; } -int32_t scap_bpf_get_stats(struct scap_engine_handle engine, scap_stats* stats) -{ +int32_t scap_bpf_get_stats(struct scap_engine_handle engine, scap_stats *stats) { struct bpf_engine *handle = engine.m_handle; int j; int ret; - for(j = 0; j < handle->m_ncpus; j++) - { + for(j = 0; j < handle->m_ncpus; j++) { struct scap_bpf_per_cpu_state v; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_LOCAL_STATE_MAP], &j, &v))) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_LOCAL_STATE_MAP], &j, &v))) { return scap_errprintf(handle->m_lasterr, -ret, "Error looking up local state %d", j); } @@ -1679,17 +1677,15 @@ int32_t scap_bpf_get_stats(struct scap_engine_handle engine, scap_stats* stats) stats->n_drops_scratch_map += v.n_drops_scratch_map; stats->n_drops_pf += v.n_drops_pf; stats->n_drops_bug += v.n_drops_bug; - stats->n_drops += v.n_drops_buffer + - v.n_drops_scratch_map + - v.n_drops_pf + - v.n_drops_bug; + stats->n_drops += v.n_drops_buffer + v.n_drops_scratch_map + v.n_drops_pf + v.n_drops_bug; } return SCAP_SUCCESS; } -static void set_u64_monotonic_kernel_counter(struct metrics_v2* m, uint64_t val, uint32_t metric_flag) -{ +static void set_u64_monotonic_kernel_counter(struct metrics_v2 *m, + uint64_t val, + uint32_t metric_flag) { m->type = METRIC_VALUE_TYPE_U64; m->flags = metric_flag; m->unit = METRIC_VALUE_UNIT_COUNT; @@ -1697,75 +1693,76 @@ static void set_u64_monotonic_kernel_counter(struct metrics_v2* m, uint64_t val, m->value.u64 = val; } -const struct metrics_v2* scap_bpf_get_stats_v2(struct scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc) -{ +const struct metrics_v2 *scap_bpf_get_stats_v2(struct scap_engine_handle engine, + uint32_t flags, + uint32_t *nstats, + int32_t *rc) { struct bpf_engine *handle = engine.m_handle; // we can't collect libbpf stats if bpf stats are not enabled - if (!(handle->m_flags & ENGINE_FLAG_BPF_STATS_ENABLED)) - { + if(!(handle->m_flags & ENGINE_FLAG_BPF_STATS_ENABLED)) { flags &= ~METRICS_V2_LIBBPF_STATS; } *rc = SCAP_FAILURE; *nstats = 0; - // If it is the first time we call this function, we allocate the stats - if(handle->m_stats == NULL) - { + // If it is the first time we call this function, we allocate the stats + if(handle->m_stats == NULL) { int nprogs_attached = 0; - for(int j=0; j < BPF_PROG_ATTACHED_MAX; j++) - { - if (handle->m_attached_progs[j].fd != -1) - { + for(int j = 0; j < BPF_PROG_ATTACHED_MAX; j++) { + if(handle->m_attached_progs[j].fd != -1) { nprogs_attached++; } } uint32_t per_cpu_stats = 0; - if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) - { + if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) { // At the moment for each available CPU we want: // - the number of events. // - the number of drops. - per_cpu_stats = handle->m_ncpus* 2; + per_cpu_stats = handle->m_ncpus * 2; } - - handle->m_nstats = BPF_MAX_KERNEL_COUNTERS_STATS + per_cpu_stats + (nprogs_attached * BPF_MAX_LIBBPF_STATS); - handle->m_stats = (metrics_v2*)calloc(handle->m_nstats, sizeof(metrics_v2)); - if(!handle->m_stats) - { + + handle->m_nstats = BPF_MAX_KERNEL_COUNTERS_STATS + per_cpu_stats + + (nprogs_attached * BPF_MAX_LIBBPF_STATS); + handle->m_stats = (metrics_v2 *)calloc(handle->m_nstats, sizeof(metrics_v2)); + if(!handle->m_stats) { handle->m_nstats = 0; - *rc = scap_errprintf(handle->m_lasterr, -1, "unable to allocate memory for 'metrics_v2' array"); + *rc = scap_errprintf(handle->m_lasterr, + -1, + "unable to allocate memory for 'metrics_v2' array"); return NULL; } } // offset in stats buffer int offset = 0; - metrics_v2* stats = handle->m_stats; + metrics_v2 *stats = handle->m_stats; /* KERNEL COUNTER STATS */ - if ((flags & METRICS_V2_KERNEL_COUNTERS)) - { - for(uint32_t stat = 0; stat < BPF_MAX_KERNEL_COUNTERS_STATS; stat++) - { + if((flags & METRICS_V2_KERNEL_COUNTERS)) { + for(uint32_t stat = 0; stat < BPF_MAX_KERNEL_COUNTERS_STATS; stat++) { set_u64_monotonic_kernel_counter(&(stats[stat]), 0, METRICS_V2_KERNEL_COUNTERS); - strlcpy(stats[stat].name, (char*)bpf_kernel_counters_stats_names[stat], METRIC_NAME_MAX); + strlcpy(stats[stat].name, + (char *)bpf_kernel_counters_stats_names[stat], + METRIC_NAME_MAX); } - + struct scap_bpf_per_cpu_state v = {}; uint32_t pos = BPF_MAX_KERNEL_COUNTERS_STATS; - for(int cpu = 0; cpu < handle->m_ncpus; cpu++) - { - if(bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_LOCAL_STATE_MAP], &cpu, &v) < 0) - { - *rc = scap_errprintf(handle->m_lasterr, errno, "Error looking up local state %d", cpu); + for(int cpu = 0; cpu < handle->m_ncpus; cpu++) { + if(bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_LOCAL_STATE_MAP], &cpu, &v) < 0) { + *rc = scap_errprintf(handle->m_lasterr, + errno, + "Error looking up local state %d", + cpu); return NULL; } stats[BPF_N_EVTS].value.u64 += v.n_evts; stats[BPF_N_DROPS_BUFFER_TOTAL].value.u64 += v.n_drops_buffer; - stats[BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER].value.u64 += v.n_drops_buffer_clone_fork_enter; + stats[BPF_N_DROPS_BUFFER_CLONE_FORK_ENTER].value.u64 += + v.n_drops_buffer_clone_fork_enter; stats[BPF_N_DROPS_BUFFER_CLONE_FORK_EXIT].value.u64 += v.n_drops_buffer_clone_fork_exit; stats[BPF_N_DROPS_BUFFER_EXECVE_ENTER].value.u64 += v.n_drops_buffer_execve_enter; stats[BPF_N_DROPS_BUFFER_EXECVE_EXIT].value.u64 += v.n_drops_buffer_execve_exit; @@ -1775,28 +1772,32 @@ const struct metrics_v2* scap_bpf_get_stats_v2(struct scap_engine_handle engine, stats[BPF_N_DROPS_BUFFER_OPEN_EXIT].value.u64 += v.n_drops_buffer_open_exit; stats[BPF_N_DROPS_BUFFER_DIR_FILE_ENTER].value.u64 += v.n_drops_buffer_dir_file_enter; stats[BPF_N_DROPS_BUFFER_DIR_FILE_EXIT].value.u64 += v.n_drops_buffer_dir_file_exit; - stats[BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER].value.u64 += v.n_drops_buffer_other_interest_enter; - stats[BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT].value.u64 += v.n_drops_buffer_other_interest_exit; + stats[BPF_N_DROPS_BUFFER_OTHER_INTEREST_ENTER].value.u64 += + v.n_drops_buffer_other_interest_enter; + stats[BPF_N_DROPS_BUFFER_OTHER_INTEREST_EXIT].value.u64 += + v.n_drops_buffer_other_interest_exit; stats[BPF_N_DROPS_BUFFER_CLOSE_EXIT].value.u64 += v.n_drops_buffer_close_exit; stats[BPF_N_DROPS_BUFFER_PROC_EXIT].value.u64 += v.n_drops_buffer_proc_exit; stats[BPF_N_DROPS_SCRATCH_MAP].value.u64 += v.n_drops_scratch_map; stats[BPF_N_DROPS_PAGE_FAULTS].value.u64 += v.n_drops_pf; stats[BPF_N_DROPS_BUG].value.u64 += v.n_drops_bug; - stats[BPF_N_DROPS].value.u64 += v.n_drops_buffer + \ - v.n_drops_scratch_map + \ - v.n_drops_pf + \ - v.n_drops_bug; + stats[BPF_N_DROPS].value.u64 += + v.n_drops_buffer + v.n_drops_scratch_map + v.n_drops_pf + v.n_drops_bug; - if((flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) - { + if((flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) { // We set the num events for that CPU. - set_u64_monotonic_kernel_counter(&(stats[pos]), v.n_evts, METRICS_V2_KERNEL_COUNTERS_PER_CPU); - snprintf(stats[pos].name, METRIC_NAME_MAX, N_EVENTS_PER_CPU_PREFIX"%d", cpu); + set_u64_monotonic_kernel_counter(&(stats[pos]), + v.n_evts, + METRICS_V2_KERNEL_COUNTERS_PER_CPU); + snprintf(stats[pos].name, METRIC_NAME_MAX, N_EVENTS_PER_CPU_PREFIX "%d", cpu); pos++; // We set the drops for that CPU. - set_u64_monotonic_kernel_counter(&(stats[pos]), v.n_drops_buffer + v.n_drops_scratch_map + v.n_drops_pf + v.n_drops_bug, METRICS_V2_KERNEL_COUNTERS_PER_CPU); - snprintf(stats[pos].name, METRIC_NAME_MAX, N_DROPS_PER_CPU_PREFIX"%d", cpu); + set_u64_monotonic_kernel_counter( + &(stats[pos]), + v.n_drops_buffer + v.n_drops_scratch_map + v.n_drops_pf + v.n_drops_bug, + METRICS_V2_KERNEL_COUNTERS_PER_CPU); + snprintf(stats[pos].name, METRIC_NAME_MAX, N_DROPS_PER_CPU_PREFIX "%d", cpu); pos++; } } @@ -1805,40 +1806,36 @@ const struct metrics_v2* scap_bpf_get_stats_v2(struct scap_engine_handle engine, /* LIBBPF STATS */ - /* At the time of writing (Apr 2, 2023) libbpf stats are only available on a per program granularity. - * This means we cannot measure the statistics for each filler / tail call individually. - * Hopefully someone upstreams such capabilities to libbpf one day :) - * Meanwhile, we can simulate perf comparisons between future LSM hooks and sys enter and exit tracepoints + /* At the time of writing (Apr 2, 2023) libbpf stats are only available on a per program + * granularity. This means we cannot measure the statistics for each filler / tail call + * individually. Hopefully someone upstreams such capabilities to libbpf one day :) Meanwhile, + * we can simulate perf comparisons between future LSM hooks and sys enter and exit tracepoints * via leveraging syscall selection mechanisms `handle->curr_sc_set`. * - * Please note that libbpf stats are available only on kernels >= 5.1, they could be backported but - * it's possible that in some of our supported kernels they won't be available. + * Please note that libbpf stats are available only on kernels >= 5.1, they could be backported + * but it's possible that in some of our supported kernels they won't be available. */ - if ((flags & METRICS_V2_LIBBPF_STATS)) - { + if((flags & METRICS_V2_LIBBPF_STATS)) { int fd = 0; - for(int bpf_prog = 0; bpf_prog < BPF_PROG_ATTACHED_MAX; bpf_prog++) - { + for(int bpf_prog = 0; bpf_prog < BPF_PROG_ATTACHED_MAX; bpf_prog++) { fd = handle->m_attached_progs[bpf_prog].fd; - if (fd < 0) - { + if(fd < 0) { // we loop through each possible prog, landing here means prog was not attached continue; } struct bpf_prog_info info = {}; __u32 len = sizeof(info); - if(bpf_obj_get_info_by_fd(fd, &info, &len)) - { + if(bpf_obj_get_info_by_fd(fd, &info, &len)) { /* no info for that prog, it seems like a bug but we can go on */ continue; } - for(int stat = 0; stat < BPF_MAX_LIBBPF_STATS; stat++) - { - if (offset >= handle->m_nstats) - { + for(int stat = 0; stat < BPF_MAX_LIBBPF_STATS; stat++) { + if(offset >= handle->m_nstats) { /* This should never happen, we are doing something wrong */ - *rc = scap_errprintf(handle->m_lasterr, -1, "no enough space for all the stats"); + *rc = scap_errprintf(handle->m_lasterr, + -1, + "no enough space for all the stats"); return NULL; } stats[offset].type = METRIC_VALUE_TYPE_U64; @@ -1847,18 +1844,18 @@ const struct metrics_v2* scap_bpf_get_stats_v2(struct scap_engine_handle engine, * https://github.com/torvalds/linux/commit/cb4d2b3f03d8eed90be3a194e5b54b734ec4bbe9 * So it's possible that in some of our supported kernels `info.name` will be "". */ - if(strlen(info.name) == 0) - { + if(strlen(info.name) == 0) { /* Fallback on the elf section name */ - strlcpy(stats[offset].name, handle->m_attached_progs[bpf_prog].name, METRIC_NAME_MAX); - } - else - { + strlcpy(stats[offset].name, + handle->m_attached_progs[bpf_prog].name, + METRIC_NAME_MAX); + } else { strlcpy(stats[offset].name, info.name, METRIC_NAME_MAX); } - strlcat(stats[offset].name, bpf_libbpf_stats_names[stat], sizeof(stats[offset].name)); - switch(stat) - { + strlcat(stats[offset].name, + bpf_libbpf_stats_names[stat], + sizeof(stats[offset].name)); + switch(stat) { case RUN_CNT: stats[offset].value.u64 = info.run_cnt; stats[offset].unit = METRIC_VALUE_UNIT_COUNT; @@ -1873,8 +1870,7 @@ const struct metrics_v2* scap_bpf_get_stats_v2(struct scap_engine_handle engine, stats[offset].value.u64 = 0; stats[offset].unit = METRIC_VALUE_UNIT_TIME_NS; stats[offset].metric_type = METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT; - if (info.run_cnt > 0) - { + if(info.run_cnt > 0) { stats[offset].value.u64 = info.run_time_ns / info.run_cnt; } break; @@ -1886,23 +1882,24 @@ const struct metrics_v2* scap_bpf_get_stats_v2(struct scap_engine_handle engine, } } } - *nstats = offset; // return true number of stats that were available as libbpf metrics are a function of attached progs + *nstats = offset; // return true number of stats that were available as libbpf metrics are a + // function of attached progs *rc = SCAP_SUCCESS; return stats; } -int32_t scap_bpf_get_n_tracepoint_hit(struct scap_engine_handle engine, long* ret) -{ +int32_t scap_bpf_get_n_tracepoint_hit(struct scap_engine_handle engine, long *ret) { struct bpf_engine *handle = engine.m_handle; int j; int sys_ret; - for(j = 0; j < handle->m_ncpus; j++) - { + for(j = 0; j < handle->m_ncpus; j++) { struct scap_bpf_per_cpu_state v; - if((sys_ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_LOCAL_STATE_MAP], &j, &v))) - { - return scap_errprintf(handle->m_lasterr, -sys_ret, "Error looking up local state %d\n", j); + if((sys_ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_LOCAL_STATE_MAP], &j, &v))) { + return scap_errprintf(handle->m_lasterr, + -sys_ret, + "Error looking up local state %d\n", + j); } ret[j] = v.n_evts; @@ -1911,65 +1908,62 @@ int32_t scap_bpf_get_n_tracepoint_hit(struct scap_engine_handle engine, long* re return SCAP_SUCCESS; } -static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) -{ +static int32_t next(struct scap_engine_handle engine, + scap_evt **pevent, + uint16_t *pdevid, + uint32_t *pflags) { return ringbuffer_next(&HANDLE(engine)->m_dev_set, pevent, pdevid, pflags); } -static int32_t unsupported_config(struct scap_engine_handle engine, const char* msg) -{ - struct bpf_engine* handle = engine.m_handle; +static int32_t unsupported_config(struct scap_engine_handle engine, const char *msg) { + struct bpf_engine *handle = engine.m_handle; strlcpy(handle->m_lasterr, msg, SCAP_LASTERR_SIZE); return SCAP_FAILURE; } -static int32_t scap_bpf_handle_dropfailed(struct scap_engine_handle engine, bool drop_failed) -{ +static int32_t scap_bpf_handle_dropfailed(struct scap_engine_handle engine, bool drop_failed) { struct bpf_engine *handle = engine.m_handle; struct scap_bpf_settings settings; int k = 0; int ret; - if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) - { + if((ret = bpf_map_lookup_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_lookup_elem"); } settings.drop_failed = drop_failed; - if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], &k, &settings, BPF_ANY)) != 0) - { + if((ret = bpf_map_update_elem(handle->m_bpf_map_fds[SCAP_SETTINGS_MAP], + &k, + &settings, + BPF_ANY)) != 0) { return scap_errprintf(handle->m_lasterr, -ret, "SCAP_SETTINGS_MAP bpf_map_update_elem"); } return SCAP_SUCCESS; } -static int32_t scap_bpf_handle_sc(struct scap_engine_handle engine, uint32_t op, uint32_t sc) -{ - struct bpf_engine* handle = engine.m_handle; +static int32_t scap_bpf_handle_sc(struct scap_engine_handle engine, uint32_t op, uint32_t sc) { + struct bpf_engine *handle = engine.m_handle; handle->curr_sc_set.ppm_sc[sc] = op == SCAP_PPM_SC_MASK_SET; /* We update the system state only if the capture is started * otherwise there is the risk to enable again tracepoints */ - if(handle->capturing) - { + if(handle->capturing) { return enforce_sc_set(handle); } return SCAP_SUCCESS; } -static int32_t configure(struct scap_engine_handle engine, enum scap_setting setting, unsigned long arg1, unsigned long arg2) -{ - switch(setting) - { +static int32_t configure(struct scap_engine_handle engine, + enum scap_setting setting, + unsigned long arg1, + unsigned long arg2) { + switch(setting) { case SCAP_SAMPLING_RATIO: - if(arg2 == 0) - { + if(arg2 == 0) { return scap_bpf_stop_dropping_mode(engine); - } - else - { + } else { return scap_bpf_start_dropping_mode(engine, arg1); } case SCAP_SNAPLEN: @@ -1979,20 +1973,16 @@ static int32_t configure(struct scap_engine_handle engine, enum scap_setting set case SCAP_DROP_FAILED: return scap_bpf_handle_dropfailed(engine, arg1); case SCAP_DYNAMIC_SNAPLEN: - if(arg1 == 0) - { + if(arg1 == 0) { return scap_bpf_disable_dynamic_snaplen(engine); - } - else - { + } else { return scap_bpf_enable_dynamic_snaplen(engine); } case SCAP_FULLCAPTURE_PORT_RANGE: return scap_bpf_set_fullcapture_port_range(engine, arg1, arg2); case SCAP_STATSD_PORT: return scap_bpf_set_statsd_port(engine, arg1); - default: - { + default: { char msg[SCAP_LASTERR_SIZE]; snprintf(msg, sizeof(msg), "Unsupported setting %d (args %lu, %lu)", setting, arg1, arg2); return unsupported_config(engine, msg); @@ -2000,16 +1990,15 @@ static int32_t configure(struct scap_engine_handle engine, enum scap_setting set } } -static int32_t init(scap_t* handle, scap_open_args *oargs) -{ +static int32_t init(scap_t *handle, scap_open_args *oargs) { int32_t rc = 0; char bpf_probe_buf[SCAP_MAX_PATH_SIZE] = {0}; struct scap_engine_handle engine = handle->m_engine; struct scap_bpf_engine_params *params = oargs->engine_params; strlcpy(bpf_probe_buf, params->bpf_probe, SCAP_MAX_PATH_SIZE); - if(check_buffer_bytes_dim(HANDLE(engine)->m_lasterr, params->buffer_bytes_dim) != SCAP_SUCCESS) - { + if(check_buffer_bytes_dim(HANDLE(engine)->m_lasterr, params->buffer_bytes_dim) != + SCAP_SUCCESS) { return SCAP_FAILURE; } @@ -2017,69 +2006,67 @@ static int32_t init(scap_t* handle, scap_open_args *oargs) // Find out how many devices we have to open, which equals to the number of online CPUs // ssize_t num_cpus = sysconf(_SC_NPROCESSORS_CONF); - if(num_cpus == -1) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "cannot obtain the number of available CPUs from '_SC_NPROCESSORS_CONF'"); + if(num_cpus == -1) { + return scap_errprintf( + HANDLE(engine)->m_lasterr, + errno, + "cannot obtain the number of available CPUs from '_SC_NPROCESSORS_CONF'"); } HANDLE(engine)->m_ncpus = num_cpus; ssize_t num_devs = sysconf(_SC_NPROCESSORS_ONLN); - if(num_devs == -1) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN'"); + if(num_devs == -1) { + return scap_errprintf( + HANDLE(engine)->m_lasterr, + errno, + "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN'"); } rc = devset_init(&HANDLE(engine)->m_dev_set, num_devs, HANDLE(engine)->m_lasterr); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } /* Here we need to load maps and progs but we shouldn't attach tracepoints */ rc = scap_bpf_load(engine.m_handle, bpf_probe_buf, oargs); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } /* Calibrate the socket at init time */ rc = calibrate_socket_file_ops(engine); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } /* Store interesting sc codes */ - memcpy(&HANDLE(engine)->curr_sc_set, &oargs->ppm_sc_of_interest, sizeof(interesting_ppm_sc_set)); + memcpy(&HANDLE(engine)->curr_sc_set, + &oargs->ppm_sc_of_interest, + sizeof(interesting_ppm_sc_set)); HANDLE(engine)->m_flags = 0; - if(scap_get_bpf_stats_enabled()) - { + if(scap_get_bpf_stats_enabled()) { HANDLE(engine)->m_flags |= ENGINE_FLAG_BPF_STATS_ENABLED; } return SCAP_SUCCESS; } -static uint64_t get_flags(struct scap_engine_handle engine) -{ +static uint64_t get_flags(struct scap_engine_handle engine) { return HANDLE(engine)->m_flags; } -static uint32_t get_n_devs(struct scap_engine_handle engine) -{ +static uint32_t get_n_devs(struct scap_engine_handle engine) { return HANDLE(engine)->m_dev_set.m_ndevs; } -static uint64_t get_max_buf_used(struct scap_engine_handle engine) -{ +static uint64_t get_max_buf_used(struct scap_engine_handle engine) { uint64_t i; uint64_t max = 0; struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; - for(i = 0; i < devset->m_ndevs; i++) - { + for(i = 0; i < devset->m_ndevs; i++) { uint64_t size = buf_size_used(&devset->m_devs[i]); max = size > max ? size : max; } @@ -2087,34 +2074,32 @@ static uint64_t get_max_buf_used(struct scap_engine_handle engine) return max; } -uint64_t scap_bpf_get_api_version(struct scap_engine_handle engine) -{ +uint64_t scap_bpf_get_api_version(struct scap_engine_handle engine) { return HANDLE(engine)->m_api_version; } -uint64_t scap_bpf_get_schema_version(struct scap_engine_handle engine) -{ +uint64_t scap_bpf_get_schema_version(struct scap_engine_handle engine) { return HANDLE(engine)->m_schema_version; } const struct scap_vtable scap_bpf_engine = { - .name = BPF_ENGINE, - .savefile_ops = NULL, - - .alloc_handle = alloc_handle, - .init = init, - .get_flags = get_flags, - .free_handle = free_handle, - .close = scap_bpf_close, - .next = next, - .start_capture = scap_bpf_start_capture, - .stop_capture = scap_bpf_stop_capture, - .configure = configure, - .get_stats = scap_bpf_get_stats, - .get_stats_v2 = scap_bpf_get_stats_v2, - .get_n_tracepoint_hit = scap_bpf_get_n_tracepoint_hit, - .get_n_devs = get_n_devs, - .get_max_buf_used = get_max_buf_used, - .get_api_version = scap_bpf_get_api_version, - .get_schema_version = scap_bpf_get_schema_version, + .name = BPF_ENGINE, + .savefile_ops = NULL, + + .alloc_handle = alloc_handle, + .init = init, + .get_flags = get_flags, + .free_handle = free_handle, + .close = scap_bpf_close, + .next = next, + .start_capture = scap_bpf_start_capture, + .stop_capture = scap_bpf_stop_capture, + .configure = configure, + .get_stats = scap_bpf_get_stats, + .get_stats_v2 = scap_bpf_get_stats_v2, + .get_n_tracepoint_hit = scap_bpf_get_n_tracepoint_hit, + .get_n_devs = get_n_devs, + .get_max_buf_used = get_max_buf_used, + .get_api_version = scap_bpf_get_api_version, + .get_schema_version = scap_bpf_get_schema_version, }; diff --git a/userspace/libscap/engine/bpf/scap_bpf.h b/userspace/libscap/engine/bpf/scap_bpf.h index cb1b54d499..6c454646fc 100644 --- a/userspace/libscap/engine/bpf/scap_bpf.h +++ b/userspace/libscap/engine/bpf/scap_bpf.h @@ -34,16 +34,17 @@ struct perf_lost_sample { }; /* Return only the raw data of the event skipping the header and the size. */ -static inline scap_evt *scap_bpf_evt_from_perf_sample(void *evt) -{ - struct perf_event_sample *perf_evt = (struct perf_event_sample *) evt; +static inline scap_evt *scap_bpf_evt_from_perf_sample(void *evt) { + struct perf_event_sample *perf_evt = (struct perf_event_sample *)evt; ASSERT(perf_evt->header.type == PERF_RECORD_SAMPLE); - return (scap_evt *) perf_evt->data; + return (scap_evt *)perf_evt->data; } -static inline void scap_bpf_get_buf_pointers(scap_device *dev, uint64_t *phead, uint64_t *ptail, uint64_t *pread_size) -{ - struct perf_event_mmap_page * header = (struct perf_event_mmap_page *) dev->m_buffer; +static inline void scap_bpf_get_buf_pointers(scap_device *dev, + uint64_t *phead, + uint64_t *ptail, + uint64_t *pread_size) { + struct perf_event_mmap_page *header = (struct perf_event_mmap_page *)dev->m_buffer; *phead = header->data_head; *ptail = header->data_tail; @@ -52,8 +53,8 @@ static inline void scap_bpf_get_buf_pointers(scap_device *dev, uint64_t *phead, asm volatile("" ::: "memory"); // clang-format on - uint64_t cons = *ptail % header->data_size; // consumer position - uint64_t prod = *phead % header->data_size; // producer position + uint64_t cons = *ptail % header->data_size; // consumer position + uint64_t prod = *phead % header->data_size; // producer position /* `pread_size` is the number of bytes our consumer has to read to reach the producer. * We want to obtain this information so we know how many bytes we can read. @@ -81,25 +82,24 @@ static inline void scap_bpf_get_buf_pointers(scap_device *dev, uint64_t *phead, * * We want to obtain the data space so we do `p - c`. */ - if(cons > prod) - { + if(cons > prod) { *pread_size = header->data_size - cons + prod; - } - else - { + } else { *pread_size = prod - cons; } } -static inline int32_t scap_bpf_advance_to_evt(struct scap_device *dev, bool skip_current, - char *cur_evt, char **next_evt, uint32_t *len) -{ +static inline int32_t scap_bpf_advance_to_evt(struct scap_device *dev, + bool skip_current, + char *cur_evt, + char **next_evt, + uint32_t *len) { void *base; void *begin; - struct perf_event_mmap_page *header = (struct perf_event_mmap_page *) dev->m_buffer; + struct perf_event_mmap_page *header = (struct perf_event_mmap_page *)dev->m_buffer; - base = ((char *) header) + header->data_offset; + base = ((char *)header) + header->data_offset; /* if `skip_current` is true it means that we need to increment the position * and this `begin` points to an event that we have already read. If `false` @@ -107,50 +107,37 @@ static inline int32_t scap_bpf_advance_to_evt(struct scap_device *dev, bool skip */ begin = cur_evt; - while(*len) - { + while(*len) { struct perf_event_header *e = begin; ASSERT(*len >= sizeof(*e)); ASSERT(*len >= e->size); - if(e->type == PERF_RECORD_SAMPLE) - { + if(e->type == PERF_RECORD_SAMPLE) { #ifdef _DEBUG - struct perf_event_sample *sample = (struct perf_event_sample *) e; + struct perf_event_sample *sample = (struct perf_event_sample *)e; #endif ASSERT(*len >= sizeof(*sample)); ASSERT(*len >= sample->size); ASSERT(e->size == sizeof(*e) + sizeof(sample->size) + sample->size); - ASSERT(((scap_evt *) sample->data)->len <= sample->size); + ASSERT(((scap_evt *)sample->data)->len <= sample->size); - if(skip_current) - { + if(skip_current) { skip_current = false; - } - else - { - *next_evt = (char *) e; + } else { + *next_evt = (char *)e; break; } - } - else if(e->type != PERF_RECORD_LOST) - { - printf("Unknown event type=%d size=%d\n", - e->type, e->size); + } else if(e->type != PERF_RECORD_LOST) { + printf("Unknown event type=%d size=%d\n", e->type, e->size); ASSERT(false); } /* Move the pointer inside the block to the next event */ - if(begin + e->size > base + header->data_size) - { + if(begin + e->size > base + header->data_size) { begin = begin + e->size - header->data_size; - } - else if(begin + e->size == base + header->data_size) - { + } else if(begin + e->size == base + header->data_size) { begin = base; - } - else - { + } else { begin += e->size; } @@ -162,8 +149,7 @@ static inline int32_t scap_bpf_advance_to_evt(struct scap_device *dev, bool skip } /* This helper increments the consumer position */ -static inline void scap_bpf_advance_tail(struct scap_device *dev) -{ +static inline void scap_bpf_advance_tail(struct scap_device *dev) { struct perf_event_mmap_page *header; header = (struct perf_event_mmap_page *)dev->m_buffer; @@ -178,25 +164,24 @@ static inline void scap_bpf_advance_tail(struct scap_device *dev) dev->m_lastreadsize = 0; } -static inline int32_t scap_bpf_readbuf(struct scap_device *dev, char **buf, uint32_t *len) -{ +static inline int32_t scap_bpf_readbuf(struct scap_device *dev, char **buf, uint32_t *len) { struct perf_event_mmap_page *header; uint64_t tail; uint64_t head; uint64_t read_size; char *p; - header = (struct perf_event_mmap_page *) dev->m_buffer; + header = (struct perf_event_mmap_page *)dev->m_buffer; ASSERT(dev->m_lastreadsize == 0); scap_bpf_get_buf_pointers(dev, &head, &tail, &read_size); - /* This contains the dimension of the block and it will be used to increment + /* This contains the dimension of the block and it will be used to increment * the consumer position in `scap_bpf_advance_tail`. */ dev->m_lastreadsize = read_size; /* position of the consumer */ - p = ((char *) header) + header->data_offset + tail % header->data_size; + p = ((char *)header) + header->data_offset + tail % header->data_size; *len = read_size; return scap_bpf_advance_to_evt(dev, false, p, buf, len); diff --git a/userspace/libscap/engine/bpf/scap_bpf_stats.h b/userspace/libscap/engine/bpf/scap_bpf_stats.h index 71a52b92af..a8d0c03019 100644 --- a/userspace/libscap/engine/bpf/scap_bpf_stats.h +++ b/userspace/libscap/engine/bpf/scap_bpf_stats.h @@ -40,7 +40,7 @@ typedef enum bpf_kernel_counters_stats { BPF_N_DROPS_BUG, BPF_N_DROPS, BPF_MAX_KERNEL_COUNTERS_STATS -}bpf_kernel_counters_stats; +} bpf_kernel_counters_stats; enum bpf_libbpf_stats { RUN_CNT = 0, diff --git a/userspace/libscap/engine/gvisor/CMakeLists.txt b/userspace/libscap/engine/gvisor/CMakeLists.txt index 6dfbafb146..7865656ffb 100644 --- a/userspace/libscap/engine/gvisor/CMakeLists.txt +++ b/userspace/libscap/engine/gvisor/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # include(protobuf) include(jsoncpp) @@ -20,83 +18,74 @@ include(jsoncpp) find_package(Threads) set(scap_engine_gvisor_sources - ${CMAKE_CURRENT_SOURCE_DIR}/parsers.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/fillers.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/gvisor.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/scap_gvisor.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/scap_gvisor_platform.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/runsc.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/parsers.cpp ${CMAKE_CURRENT_SOURCE_DIR}/fillers.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/gvisor.cpp ${CMAKE_CURRENT_SOURCE_DIR}/scap_gvisor.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/scap_gvisor_platform.cpp ${CMAKE_CURRENT_SOURCE_DIR}/runsc.cpp ) set(scap_engine_gvisor_generated_sources - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/common.pb.cc - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/container.pb.cc - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/sentry.pb.cc - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/syscall.pb.cc + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/common.pb.cc + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/container.pb.cc + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/sentry.pb.cc + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/syscall.pb.cc ) set(scap_engine_gvisor_generated_headers - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/common.pb.h - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/container.pb.h - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/sentry.pb.h - ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/syscall.pb.h + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/common.pb.h + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/container.pb.h + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/sentry.pb.h + ${CMAKE_CURRENT_BINARY_DIR}/pkg/sentry/seccheck/points/syscall.pb.h ) add_custom_command( - OUTPUT ${scap_engine_gvisor_generated_sources} ${scap_engine_gvisor_generated_headers} - COMMENT "Generate gVisor protobuf definitions" - DEPENDS protobuf - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/common.proto - COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/common.proto - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/container.proto - COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/container.proto - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/sentry.proto - COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/sentry.proto - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/syscall.proto - COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/syscall.proto - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + OUTPUT ${scap_engine_gvisor_generated_sources} ${scap_engine_gvisor_generated_headers} + COMMENT "Generate gVisor protobuf definitions" + DEPENDS protobuf + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/common.proto + COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. + ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/common.proto + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/container.proto + COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. + ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/container.proto + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/sentry.proto + COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. + ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/sentry.proto + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/syscall.proto + COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=. + ${CMAKE_CURRENT_SOURCE_DIR}/proto/pkg/sentry/seccheck/points/syscall.proto + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) if(USE_BUNDLED_JSONCPP) - add_dependencies(scap jsoncpp) + add_dependencies(scap jsoncpp) endif() -if (BUILD_SHARED_LIBS) - # Trying to build a shared scap_engine_gvisor will result in circular - # dependencies, so just add our sources to scap. - # Additionally, the GENERATED property doesn't propogate across directories, - # so enforce our dependency chain using an object library. - # https://gitlab.kitware.com/cmake/cmake/-/issues/18399 - add_library(scap_engine_gvisor_o OBJECT - ${scap_engine_gvisor_sources} - ${scap_engine_gvisor_generated_sources} - ) - set_property(TARGET scap_engine_gvisor_o PROPERTY POSITION_INDEPENDENT_CODE ON) +if(BUILD_SHARED_LIBS) + # Trying to build a shared scap_engine_gvisor will result in circular dependencies, so just add + # our sources to scap. Additionally, the GENERATED property doesn't propogate across + # directories, so enforce our dependency chain using an object library. + # https://gitlab.kitware.com/cmake/cmake/-/issues/18399 + add_library( + scap_engine_gvisor_o OBJECT ${scap_engine_gvisor_sources} + ${scap_engine_gvisor_generated_sources} + ) + set_property(TARGET scap_engine_gvisor_o PROPERTY POSITION_INDEPENDENT_CODE ON) - add_dependencies(scap_engine_gvisor_o uthash) - add_dependencies(scap scap_engine_gvisor_o) - target_sources(scap PRIVATE $) + add_dependencies(scap_engine_gvisor_o uthash) + add_dependencies(scap scap_engine_gvisor_o) + target_sources(scap PRIVATE $) else() - add_library(scap_engine_gvisor - ${scap_engine_gvisor_sources} - ${scap_engine_gvisor_generated_sources} - ) + add_library( + scap_engine_gvisor ${scap_engine_gvisor_sources} ${scap_engine_gvisor_generated_sources} + ) - add_dependencies(scap_engine_gvisor uthash) - target_link_libraries(scap_engine_gvisor - PRIVATE - scap - scap_platform_util - scap_error - ${CMAKE_THREAD_LIBS_INIT} - ${PROTOBUF_LIB} - ${JSONCPP_LIB} - ) + add_dependencies(scap_engine_gvisor uthash) + target_link_libraries( + scap_engine_gvisor PRIVATE scap scap_platform_util scap_error ${CMAKE_THREAD_LIBS_INIT} + ${PROTOBUF_LIB} ${JSONCPP_LIB} + ) - target_include_directories(scap_engine_gvisor - PRIVATE - ${CMAKE_CURRENT_BINARY_DIR} - ) + target_include_directories(scap_engine_gvisor PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) - set_scap_target_properties(scap_engine_gvisor) + set_scap_target_properties(scap_engine_gvisor) endif() diff --git a/userspace/libscap/engine/gvisor/fillers.cpp b/userspace/libscap/engine/gvisor/fillers.cpp index 5bffd3d39f..7cbafc280b 100644 --- a/userspace/libscap/engine/gvisor/fillers.cpp +++ b/userspace/libscap/engine/gvisor/fillers.cpp @@ -50,12 +50,8 @@ namespace fillers { // PPME_SYSCALL_CLONE_20_E // Event field validity issues: none -int32_t -fill_event_clone_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CLONE_20_E, 0); +int32_t fill_event_clone_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_CLONE_20_E, 0); } // PPME_SYSCALL_CLONE_20_X @@ -75,58 +71,56 @@ fill_event_clone_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap // - F15/flags -- some callers pass in hardcoded value of 0 // - F16/uid -- some callers pass in hardcoded value of 0 // - F17/gid -- some callers pass in hardcoded value of 0 -int32_t -fill_event_clone_20_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - scap_const_sized_buffer args, - uint64_t tid, - uint64_t pid, - uint64_t ptid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - uint32_t flags, - uint32_t uid, - uint32_t gid, - uint64_t vtid, - uint64_t vpid, - uint64_t pidns_init_start_ts) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CLONE_20_X, 21, - res, - exe, - args, - tid, - pid, - ptid, - cwd, - 75000, // fdlimit -- INVALID - 0, // pgft_maj -- INVALID - 0, // pgft_min -- INVALID - 0, // vm_size -- INVALID - 0, // vm_rss -- INVALID - 0, // vm_swap -- INVALID - comm, - cgroups, - flags, - uid, - gid, - vtid, - vpid, - pidns_init_start_ts); +int32_t fill_event_clone_20_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + scap_const_sized_buffer args, + uint64_t tid, + uint64_t pid, + uint64_t ptid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + uint32_t flags, + uint32_t uid, + uint32_t gid, + uint64_t vtid, + uint64_t vpid, + uint64_t pidns_init_start_ts) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_CLONE_20_X, + 21, + res, + exe, + args, + tid, + pid, + ptid, + cwd, + 75000, // fdlimit -- INVALID + 0, // pgft_maj -- INVALID + 0, // pgft_min -- INVALID + 0, // vm_size -- INVALID + 0, // vm_rss -- INVALID + 0, // vm_swap -- INVALID + comm, + cgroups, + flags, + uid, + gid, + vtid, + vpid, + pidns_init_start_ts); } // PPME_SYSCALL_FORK_20_E // Event field validity issues: none -int32_t -fill_event_fork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_FORK_20_E, 0); +int32_t fill_event_fork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_FORK_20_E, 0); } // PPME_SYSCALL_FORK_20_X @@ -140,56 +134,53 @@ fill_event_fork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_ // - F10/vm_size -- hardcoded to 0 // - F11/vm_rss -- hardcoded to 0 // - F12/vm_swap -- hardcoded to 0 -int32_t -fill_event_fork_20_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - uint32_t uid, - uint32_t gid, - uint64_t vtid, - uint64_t vpid, - uint64_t pidns_init_start_ts) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_FORK_20_X, 21, - res, - exe, - scap_const_sized_buffer{"", 0}, // args -- INVALID - tid, - pid, - 0, // ptid -- INVALID - cwd, - 75000, // fdlimit -- INVALID - 0, // pgft_maj -- INVALID - 0, // pgft_min -- INVALID - 0, // vm_size -- INVALID - 0, // vm_rss -- INVALID - 0, // vm_swap -- INVALID - comm, - cgroups, - 0, // flags, hardcoded to 0 just like drivers - uid, - gid, - vtid, - vpid, - pidns_init_start_ts); +int32_t fill_event_fork_20_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + uint32_t uid, + uint32_t gid, + uint64_t vtid, + uint64_t vpid, + uint64_t pidns_init_start_ts) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_FORK_20_X, + 21, + res, + exe, + scap_const_sized_buffer{"", 0}, // args -- INVALID + tid, + pid, + 0, // ptid -- INVALID + cwd, + 75000, // fdlimit -- INVALID + 0, // pgft_maj -- INVALID + 0, // pgft_min -- INVALID + 0, // vm_size -- INVALID + 0, // vm_rss -- INVALID + 0, // vm_swap -- INVALID + comm, + cgroups, + 0, // flags, hardcoded to 0 just like drivers + uid, + gid, + vtid, + vpid, + pidns_init_start_ts); } - // PPME_SYSCALL_VFORK_20_E // Event field validity issues: none -int32_t -fill_event_vfork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_VFORK_20_E, 0); +int32_t fill_event_vfork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_VFORK_20_E, 0); } // PPME_SYSCALL_VFORK_20_X @@ -203,60 +194,63 @@ fill_event_vfork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap // - F10/vm_size -- hardcoded to 0 // - F11/vm_rss -- hardcoded to 0 // - F12/vm_swap -- hardcoded to 0 -int32_t -fill_event_vfork_20_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - uint32_t uid, - uint32_t gid, - uint64_t vtid, - uint64_t vpid, - uint64_t pidns_init_start_ts) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_VFORK_20_X, 21, - res, - exe, - scap_const_sized_buffer{"", 0}, // args -- INVALID - tid, - pid, - 0, // ptid -- INVALID - cwd, - 75000, // fdlimit -- INVALID - 0, // pgft_maj -- INVALID - 0, // pgft_min -- INVALID - 0, // vm_size -- INVALID - 0, // vm_rss -- INVALID - 0, // vm_swap -- INVALID - comm, - cgroups, - 0, // flags, hardcoded to 0 just like drivers - uid, - gid, - vtid, - vpid, - pidns_init_start_ts); +int32_t fill_event_vfork_20_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + uint32_t uid, + uint32_t gid, + uint64_t vtid, + uint64_t vpid, + uint64_t pidns_init_start_ts) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_VFORK_20_X, + 21, + res, + exe, + scap_const_sized_buffer{"", 0}, // args -- INVALID + tid, + pid, + 0, // ptid -- INVALID + cwd, + 75000, // fdlimit -- INVALID + 0, // pgft_maj -- INVALID + 0, // pgft_min -- INVALID + 0, // vm_size -- INVALID + 0, // vm_rss -- INVALID + 0, // vm_swap -- INVALID + comm, + cgroups, + 0, // flags, hardcoded to 0 just like drivers + uid, + gid, + vtid, + vpid, + pidns_init_start_ts); } // PPME_SYSCALL_EXECVE_19_E // Event field validity issues: none -int32_t -fill_event_execve_19_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - const char* filename) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_EXECVE_19_E, 1, - filename); +int32_t fill_event_execve_19_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + const char* filename) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_EXECVE_19_E, + 1, + filename); } - // PPME_SYSCALL_EXECVE_19_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: @@ -281,65 +275,69 @@ fill_event_execve_19_e(scap_sized_buffer scap_buf, size_t* event_size, char* sca // B) Provided by caller, but caller sometimes specifies a hardcoded value // due to value not available in native gVisor event: // - F26/uid -- some callers pass in hardcoded value of 0 -int32_t -fill_event_execve_19_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - scap_const_sized_buffer args, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - scap_const_sized_buffer env, - uint32_t uid) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_EXECVE_19_X, 27, - res, - exe, - args, - tid, - pid, - -1, // ptid -- INVALID - cwd, // cwd - 75000, // fdlimit -- INVALID - 0, // pgft_maj -- INVALID - 0, // pgft_min -- INVALID - 0, // vm_size -- INVALID - 0, // vm_rss -- INVALID - 0, // vm_swap -- INVALID - comm, - cgroups, - env, - 0, // tty -- INVALID - 0, // pgid -- INVALID - UINT32_MAX, // loginuid -- INVALID - 0, // flags -- INVALID - 0, // cap_inheritable -- INVALID - 0, // cap_permitted -- INVALID - 0, // cap_effective -- INVALID - 0, // exe_ino -- INVALID - 0, // exe_ino_ctime -- INVALID - 0, // exe_ino_mtime -- INVALID - uid); // uid +int32_t fill_event_execve_19_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + scap_const_sized_buffer args, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + scap_const_sized_buffer env, + uint32_t uid) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_EXECVE_19_X, + 27, + res, + exe, + args, + tid, + pid, + -1, // ptid -- INVALID + cwd, // cwd + 75000, // fdlimit -- INVALID + 0, // pgft_maj -- INVALID + 0, // pgft_min -- INVALID + 0, // vm_size -- INVALID + 0, // vm_rss -- INVALID + 0, // vm_swap -- INVALID + comm, + cgroups, + env, + 0, // tty -- INVALID + 0, // pgid -- INVALID + UINT32_MAX, // loginuid -- INVALID + 0, // flags -- INVALID + 0, // cap_inheritable -- INVALID + 0, // cap_permitted -- INVALID + 0, // cap_effective -- INVALID + 0, // exe_ino -- INVALID + 0, // exe_ino_ctime -- INVALID + 0, // exe_ino_mtime -- INVALID + uid); // uid } // PPME_SYSCALL_EXECVEAT_E // Event field validity issues: none -int32_t -fill_event_execveat_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t dirfd, - const char* pathname, - uint32_t flags) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_EXECVEAT_E, 3, - dirfd, - pathname, - flags); +int32_t fill_event_execveat_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t dirfd, + const char* pathname, + uint32_t flags) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_EXECVEAT_E, + 3, + dirfd, + pathname, + flags); } // PPME_SYSCALL_EXECVEAT_X @@ -366,83 +364,89 @@ fill_event_execveat_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap // B) Provided by caller, but caller sometimes specifies a hardcoded value // due to value not available in native gVisor event: // - F26/uid -- some callers pass in hardcoded value of 0 -int32_t -fill_event_execveat_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - scap_const_sized_buffer args, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - scap_const_sized_buffer env, - uint32_t uid) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_EXECVEAT_X, 27, - res, - exe, - args, - tid, - pid, - -1, // ptid -- INVALID - cwd, // cwd - 75000, // fdlimit -- INVALID - 0, // pgft_maj -- INVALID - 0, // pgft_min -- INVALID - 0, // vm_size -- INVALID - 0, // vm_rss -- INVALID - 0, // vm_swap -- INVALID - comm, - cgroups, - env, - 0, // tty -- INVALID - 0, // pgid -- INVALID - UINT32_MAX, // loginuid -- INVALID - 0, // flags -- INVALID - 0, // cap_inheritable -- INVALID - 0, // cap_permitted -- INVALID - 0, // cap_effective -- INVALID - 0, // exe_ino -- INVALID - 0, // exe_ino_ctime -- INVALID - 0, // exe_ino_mtime -- INVALID - uid); // uid +int32_t fill_event_execveat_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + scap_const_sized_buffer args, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + scap_const_sized_buffer env, + uint32_t uid) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_EXECVEAT_X, + 27, + res, + exe, + args, + tid, + pid, + -1, // ptid -- INVALID + cwd, // cwd + 75000, // fdlimit -- INVALID + 0, // pgft_maj -- INVALID + 0, // pgft_min -- INVALID + 0, // vm_size -- INVALID + 0, // vm_rss -- INVALID + 0, // vm_swap -- INVALID + comm, + cgroups, + env, + 0, // tty -- INVALID + 0, // pgid -- INVALID + UINT32_MAX, // loginuid -- INVALID + 0, // flags -- INVALID + 0, // cap_inheritable -- INVALID + 0, // cap_permitted -- INVALID + 0, // cap_effective -- INVALID + 0, // exe_ino -- INVALID + 0, // exe_ino_ctime -- INVALID + 0, // exe_ino_mtime -- INVALID + uid); // uid } // PPME_SYSCALL_PROCEXIT_1_E // Event field validity issues: none -int32_t -fill_event_procexit_1_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t status, - uint32_t ret, - uint32_t sig, - uint32_t core) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_PROCEXIT_1_E, 4, - status, - ret, - sig, - core); +int32_t fill_event_procexit_1_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t status, + uint32_t ret, + uint32_t sig, + uint32_t core) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_PROCEXIT_1_E, + 4, + status, + ret, + sig, + core); } // PPME_SYSCALL_OPEN_E // Event field validity issues: none -int32_t -fill_event_open_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - const char* name, - uint32_t flags, - uint32_t mode) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_OPEN_E, 3, - name, - flags, - mode); +int32_t fill_event_open_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + const char* name, + uint32_t flags, + uint32_t mode) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_OPEN_E, + 3, + name, + flags, + mode); } // PPME_SYSCALL_OPEN_X @@ -450,40 +454,44 @@ fill_event_open_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err // A) Always hardcoded due to value not available in native gVisor event: // - F4/dev -- hardcoded to 0 // - F5/ino -- hardcoded to 0 -int32_t -fill_event_open_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - const char* name, - uint32_t flags, - uint32_t mode) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_OPEN_X, 6, - fd, - name, - flags, - mode, - 0, // dev -- INVALID - 0); // ino -- INVALID +int32_t fill_event_open_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + const char* name, + uint32_t flags, + uint32_t mode) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_OPEN_X, + 6, + fd, + name, + flags, + mode, + 0, // dev -- INVALID + 0); // ino -- INVALID } // PPME_SYSCALL_OPENAT_2_E // Event field validity issues: none -int32_t -fill_event_openat_2_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t dirfd, - const char* name, - uint32_t flags, - uint32_t mode) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_OPENAT_2_E, 4, - dirfd, - name, - flags, - mode); +int32_t fill_event_openat_2_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t dirfd, + const char* name, + uint32_t flags, + uint32_t mode) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_OPENAT_2_E, + 4, + dirfd, + name, + flags, + mode); } // PPME_SYSCALL_OPENAT_2_X @@ -491,38 +499,42 @@ fill_event_openat_2_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap // A) Always hardcoded due to value not available in native gVisor event: // - F5/dev -- hardcoded to 0 // - F6/ino -- hardcoded to 0 -int32_t -fill_event_openat_2_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - int64_t dirfd, - const char* name, - uint32_t flags, - uint32_t mode) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_OPENAT_2_X, 7, - fd, - dirfd, - name, - flags, - mode, - 0, // dev -- INVALID - 0); // ino -- INVALID +int32_t fill_event_openat_2_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + int64_t dirfd, + const char* name, + uint32_t flags, + uint32_t mode) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_OPENAT_2_X, + 7, + fd, + dirfd, + name, + flags, + mode, + 0, // dev -- INVALID + 0); // ino -- INVALID } // PPME_SYSCALL_CREAT_E // Event field validity issues: none -int32_t -fill_event_creat_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - const char* name, - uint32_t mode) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CREAT_E, 2, - name, - mode); +int32_t fill_event_creat_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + const char* name, + uint32_t mode) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_CREAT_E, + 2, + name, + mode); } // PPME_SYSCALL_CREAT_X @@ -530,685 +542,670 @@ fill_event_creat_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_er // A) Always hardcoded due to value not available in native gVisor event: // - F3/dev -- hardcoded to 0 // - F4/ino -- hardcoded to 0 -int32_t -fill_event_creat_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - const char* name, - uint32_t mode) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CREAT_X, 5, - fd, - name, - mode, - 0, // dev -- INVALID - 0); // ino -- INVALID +int32_t fill_event_creat_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + const char* name, + uint32_t mode) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_CREAT_X, + 5, + fd, + name, + mode, + 0, // dev -- INVALID + 0); // ino -- INVALID } // PPME_SYSCALL_CLOSE_E // Event field validity issues: none -int32_t -fill_event_close_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CLOSE_E, 1, - fd); +int32_t fill_event_close_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_CLOSE_E, 1, fd); } // PPME_SYSCALL_CLOSE_X // Event field validity issues: none -int32_t -fill_event_close_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CLOSE_X, 1, - res); +int32_t fill_event_close_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_CLOSE_X, 1, res); } // PPME_SYSCALL_READ_E // Event field validity issues: none -int32_t -fill_event_read_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_READ_E, 2, - fd, - size); +int32_t fill_event_read_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_READ_E, + 2, + fd, + size); } // PPME_SYSCALL_READ_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F1/data -- hardcoded to empty string -int32_t -fill_event_read_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_READ_X, 2, - res, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_read_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_READ_X, + 2, + res, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_PREAD_E // Event field validity issues: none -int32_t -fill_event_pread_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size, - uint64_t pos) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PREAD_E, 3, - fd, - size, - pos); +int32_t fill_event_pread_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size, + uint64_t pos) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PREAD_E, + 3, + fd, + size, + pos); } // PPME_SYSCALL_PREAD_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F1/data -- hardcoded to empty string -int32_t -fill_event_pread_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PREAD_X, 2, - res, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_pread_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PREAD_X, + 2, + res, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_READV_E // Event field validity issues: none -int32_t -fill_event_readv_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_READV_E, 1, - fd); +int32_t fill_event_readv_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_READV_E, 1, fd); } // PPME_SYSCALL_READV_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F2/data -- hardcoded to empty string -int32_t -fill_event_readv_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - uint32_t size) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_READV_X, 3, - res, - size, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_readv_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + uint32_t size) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_READV_X, + 3, + res, + size, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_PREADV_E // Event field validity issues: none -int32_t -fill_event_preadv_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint64_t pos) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PREADV_E, 2, - fd, - pos); +int32_t fill_event_preadv_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint64_t pos) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PREADV_E, + 2, + fd, + pos); } // PPME_SYSCALL_PREADV_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F2/data -- hardcoded to empty string -int32_t -fill_event_preadv_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - uint32_t size) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PREADV_X, 3, - res, - size, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_preadv_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + uint32_t size) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PREADV_X, + 3, + res, + size, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_CONNECT_E // Event field validity issues: none -int32_t -fill_event_connect_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - scap_const_sized_buffer addr) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_CONNECT_E, 2, - fd, - addr); +int32_t fill_event_connect_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + scap_const_sized_buffer addr) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_CONNECT_E, + 2, + fd, + addr); } // PPME_SYSCALL_CONNECT_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F2/tuple -- local address portion hardcoded to 0 -int32_t -fill_event_connect_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - scap_const_sized_buffer tuple, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_CONNECT_X, 3, - res, - tuple, // local addr hardcoded 0 -- INVALID - fd); +int32_t fill_event_connect_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + scap_const_sized_buffer tuple, + int64_t fd) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_CONNECT_X, + 3, + res, + tuple, // local addr hardcoded 0 -- INVALID + fd); } // PPME_SYSCALL_SOCKET_E // Event field validity issues: none -int32_t -fill_event_socket_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t domain, - uint32_t type, - uint32_t protocol) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_SOCKET_E, 3, - domain, - type, - protocol); +int32_t fill_event_socket_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t domain, + uint32_t type, + uint32_t protocol) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_SOCKET_E, + 3, + domain, + type, + protocol); } // PPME_SYSCALL_SOCKET_X // Event field validity issues: none -int32_t -fill_event_socket_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_SOCKET_X, 1, - fd); +int32_t fill_event_socket_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SOCKET_SOCKET_X, 1, fd); } // PPME_SYSCALL_CHDIR_E // Event field validity issues: none -int32_t -fill_event_chdir_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CHDIR_E, 0); +int32_t fill_event_chdir_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_CHDIR_E, 0); } // PPME_SYSCALL_CHDIR_X // Event field validity issues: none -int32_t -fill_event_chdir_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* path) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CHDIR_X, 2, - res, - path); +int32_t fill_event_chdir_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* path) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_CHDIR_X, + 2, + res, + path); } // PPME_SYSCALL_FCHDIR_E // Event field validity issues: none -int32_t -fill_event_fchdir_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_FCHDIR_E, 1, - fd); +int32_t fill_event_fchdir_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_FCHDIR_E, 1, fd); } // PPME_SYSCALL_FCHDIR_X // Event field validity issues: none -int32_t -fill_event_fchdir_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_FCHDIR_X, 1, - res); +int32_t fill_event_fchdir_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_FCHDIR_X, 1, res); } // PPME_SYSCALL_SETUID_E // Event field validity issues: none -int32_t -fill_event_setuid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t uid) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETUID_E, 1, - uid); +int32_t fill_event_setuid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t uid) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_SETUID_E, 1, uid); } // PPME_SYSCALL_SETUID_X // Event field validity issues: none -int32_t -fill_event_setuid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETUID_X, 1, - res); +int32_t fill_event_setuid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_SETUID_X, 1, res); } // PPME_SYSCALL_SETGID_E // Event field validity issues: none -int32_t -fill_event_setgid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t gid) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETGID_E, 1, - gid); +int32_t fill_event_setgid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t gid) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_SETGID_E, 1, gid); } // PPME_SYSCALL_SETGID_X // Event field validity issues: none -int32_t -fill_event_setgid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETGID_X, 1, - res); +int32_t fill_event_setgid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_SETGID_X, 1, res); } // PPME_SYSCALL_SETSID_E // Event field validity issues: none -int32_t -fill_event_setsid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETSID_E, 0); +int32_t fill_event_setsid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_SETSID_E, 0); } // PPME_SYSCALL_SETSID_X // Event field validity issues: none -int32_t -fill_event_setsid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETSID_X, 1, - res); +int32_t fill_event_setsid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_SETSID_X, 1, res); } // PPME_SYSCALL_SETRESUID_E // Event field validity issues: none -int32_t -fill_event_setresuid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t ruid, - uint32_t euid, - uint32_t suid) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETRESUID_E, 3, - ruid, - euid, - suid); +int32_t fill_event_setresuid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t ruid, + uint32_t euid, + uint32_t suid) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_SETRESUID_E, + 3, + ruid, + euid, + suid); } // PPME_SYSCALL_SETRESUID_X // Event field validity issues: none -int32_t -fill_event_setresuid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETRESUID_X, 1, - res); +int32_t fill_event_setresuid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_SETRESUID_X, + 1, + res); } // PPME_SYSCALL_SETRESGID_E // Event field validity issues: none -int32_t -fill_event_setresgid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t rgid, - uint32_t egid, - uint32_t sgid) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETRESGID_E, 3, - rgid, - egid, - sgid); +int32_t fill_event_setresgid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t rgid, + uint32_t egid, + uint32_t sgid) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_SETRESGID_E, + 3, + rgid, + egid, + sgid); } // PPME_SYSCALL_SETRESGID_X // Event field validity issues: none -int32_t -fill_event_setresgid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SETRESGID_X, 1, - res); +int32_t fill_event_setresgid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_SETRESGID_X, + 1, + res); } // PPME_SYSCALL_PRLIMIT_E // Event field validity issues: none -int32_t -fill_event_prlimit_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t pid, - uint8_t resource) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PRLIMIT_E, 2, - pid, - resource); +int32_t fill_event_prlimit_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t pid, + uint8_t resource) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PRLIMIT_E, + 2, + pid, + resource); } // PPME_SYSCALL_PRLIMIT_X // Event field validity issues: none -int32_t -fill_event_prlimit_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t newcur, - int64_t newmax, - int64_t oldcur, - int64_t oldmax) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PRLIMIT_X, 5, - res, - newcur, - newmax, - oldcur, - oldmax); +int32_t fill_event_prlimit_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t newcur, + int64_t newmax, + int64_t oldcur, + int64_t oldmax) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PRLIMIT_X, + 5, + res, + newcur, + newmax, + oldcur, + oldmax); } // PPME_SYSCALL_PIPE_E // Event field validity issues: none -int32_t -fill_event_pipe_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PIPE_E, 0); +int32_t fill_event_pipe_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_PIPE_E, 0); } // PPME_SYSCALL_PIPE_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F3/ino -- hardcoded to 0 -int32_t -fill_event_pipe_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t fd1, - int64_t fd2) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PIPE_X, 4, - res, - fd1, - fd2, - 0); // ino -- INVALID +int32_t fill_event_pipe_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t fd1, + int64_t fd2) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PIPE_X, + 4, + res, + fd1, + fd2, + 0); // ino -- INVALID } // PPME_SYSCALL_FCNTL_E // Event field validity issues: none -int32_t -fill_event_fcntl_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint8_t cmd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_FCNTL_E, 2, - fd, - cmd); +int32_t fill_event_fcntl_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint8_t cmd) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_FCNTL_E, + 2, + fd, + cmd); } // PPME_SYSCALL_FCNTL_X // Event field validity issues: none -int32_t -fill_event_fcntl_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_FCNTL_X, 1, - res); +int32_t fill_event_fcntl_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_FCNTL_X, 1, res); } // PPME_SYSCALL_DUP_1_E // Event field validity issues: none -int32_t -fill_event_dup_1_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_DUP_1_E, 1, - fd); +int32_t fill_event_dup_1_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_DUP_1_E, 1, fd); } // PPME_SYSCALL_DUP_1_X // Event field validity issues: none -int32_t -fill_event_dup_1_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t oldfd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_DUP_1_X, 2, - res, - oldfd); +int32_t fill_event_dup_1_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t oldfd) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_DUP_1_X, + 2, + res, + oldfd); } // PPME_SYSCALL_DUP2_E // Event field validity issues: none -int32_t -fill_event_dup2_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_DUP2_E, 1, - fd); +int32_t fill_event_dup2_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_DUP2_E, 1, fd); } // PPME_SYSCALL_DUP2_X // Event field validity issues: none -int32_t -fill_event_dup2_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t oldfd, - int64_t newfd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_DUP2_X, 3, - res, - oldfd, - newfd); +int32_t fill_event_dup2_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t oldfd, + int64_t newfd) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_DUP2_X, + 3, + res, + oldfd, + newfd); } // PPME_SYSCALL_DUP3_E // Event field validity issues: none -int32_t -fill_event_dup3_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_DUP3_E, 1, - fd); +int32_t fill_event_dup3_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_DUP3_E, 1, fd); } // PPME_SYSCALL_DUP3_X // Event field validity issues: none -int32_t -fill_event_dup3_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t oldfd, - int64_t newfd, - uint32_t flags) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_DUP3_X, 4, - res, - oldfd, - newfd, - flags); +int32_t fill_event_dup3_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t oldfd, + int64_t newfd, + uint32_t flags) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_DUP3_X, + 4, + res, + oldfd, + newfd, + flags); } // PPME_SYSCALL_SIGNALFD_E // Event field validity issues: none -int32_t -fill_event_signalfd_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t mask, - uint8_t flags) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SIGNALFD_E, 3, - fd, - mask, - flags); +int32_t fill_event_signalfd_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t mask, + uint8_t flags) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_SIGNALFD_E, + 3, + fd, + mask, + flags); } // PPME_SYSCALL_SIGNALFD_X // Event field validity issues: none -int32_t -fill_event_signalfd_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_SIGNALFD_X, 1, - res); +int32_t fill_event_signalfd_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_SIGNALFD_X, + 1, + res); } // PPME_SYSCALL_CHROOT_E // Event field validity issues: none -int32_t -fill_event_chroot_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CHROOT_E, 0); +int32_t fill_event_chroot_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_CHROOT_E, 0); } // PPME_SYSCALL_CHROOT_X // Event field validity issues: none -int32_t -fill_event_chroot_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* path) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_CHROOT_X, 2, - res, - path); +int32_t fill_event_chroot_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* path) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_CHROOT_X, + 2, + res, + path); } // PPME_SYSCALL_EVENTFD_E // Event field validity issues: none -int32_t -fill_event_eventfd_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint64_t initval, - uint32_t flags) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_EVENTFD_E, 2, - initval, - flags); +int32_t fill_event_eventfd_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint64_t initval, + uint32_t flags) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_EVENTFD_E, + 2, + initval, + flags); } // PPME_SYSCALL_EVENTFD_X // Event field validity issues: none -int32_t -fill_event_eventfd_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_EVENTFD_X, 1, - res); +int32_t fill_event_eventfd_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SYSCALL_EVENTFD_X, 1, res); } // PPME_SYSCALL_BIND_E // Event field validity issues: none -int32_t -fill_event_bind_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_BIND_E, 1, - fd); +int32_t fill_event_bind_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SOCKET_BIND_E, 1, fd); } // PPME_SYSCALL_BIND_X // Event field validity issues: none -int32_t -fill_event_bind_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - scap_const_sized_buffer addr) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_BIND_X, 2, - res, - addr); +int32_t fill_event_bind_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + scap_const_sized_buffer addr) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_BIND_X, + 2, + res, + addr); } // PPME_SYSCALL_ACCEPT_5_E // Event field validity issues: none -int32_t -fill_event_accept_5_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_ACCEPT_5_E, 0); +int32_t fill_event_accept_5_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err) { + return scap_event_encode_params(scap_buf, event_size, scap_err, PPME_SOCKET_ACCEPT_5_E, 0); } // PPME_SYSCALL_ACCEPT_5_X @@ -1218,31 +1215,35 @@ fill_event_accept_5_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap // - F2/queuepct -- hardcoded to 0 // - F3/queuelen -- hardcoded to 0 // - F4/queuemax -- hardcoded to 0 -int32_t -fill_event_accept_5_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - scap_const_sized_buffer tuple) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_ACCEPT_5_X, 5, - fd, - tuple, // local address portion hardcoded to 0 -- INVALID - 0, // queuepct -- INVALID - 0, // queuelen -- INVALID - 0); // queuemax -- INVALID +int32_t fill_event_accept_5_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + scap_const_sized_buffer tuple) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_ACCEPT_5_X, + 5, + fd, + tuple, // local address portion hardcoded to 0 -- INVALID + 0, // queuepct -- INVALID + 0, // queuelen -- INVALID + 0); // queuemax -- INVALID } // PPME_SYSCALL_ACCEPT4_6_E // Event field validity issues: none -int32_t -fill_event_accept4_6_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int32_t flags) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_ACCEPT4_6_E, 1, - flags); +int32_t fill_event_accept4_6_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int32_t flags) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_ACCEPT4_6_E, + 1, + flags); } // PPME_SYSCALL_ACCEPT4_6_X @@ -1252,85 +1253,97 @@ fill_event_accept4_6_e(scap_sized_buffer scap_buf, size_t* event_size, char* sca // - F2/queuepct -- hardcoded to 0 // - F3/queuelen -- hardcoded to 0 // - F4/queuemax -- hardcoded to 0 -int32_t -fill_event_accept4_6_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - scap_const_sized_buffer tuple) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_ACCEPT4_6_X, 5, - fd, - tuple, // local address portion hardcoded to 0 -- INVALID - 0, // queuepct -- INVALID - 0, // queuelen -- INVALID - 0); // queuemax -- INVALID +int32_t fill_event_accept4_6_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + scap_const_sized_buffer tuple) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_ACCEPT4_6_X, + 5, + fd, + tuple, // local address portion hardcoded to 0 -- INVALID + 0, // queuepct -- INVALID + 0, // queuelen -- INVALID + 0); // queuemax -- INVALID } // PPME_SYSCALL_TIMERFD_CREATE_E // Event field validity issues: none -int32_t -fill_event_timerfd_create_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint8_t clockid, - uint8_t flags) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_TIMERFD_CREATE_E, 2, - clockid, - flags); +int32_t fill_event_timerfd_create_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint8_t clockid, + uint8_t flags) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_TIMERFD_CREATE_E, + 2, + clockid, + flags); } // PPME_SYSCALL_TIMERFD_CREATE_X // Event field validity issues: none -int32_t -fill_event_timerfd_create_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_TIMERFD_CREATE_X, 1, - res); +int32_t fill_event_timerfd_create_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_TIMERFD_CREATE_X, + 1, + res); } // PPME_SYSCALL_INOTIFY_INIT_E // Event field validity issues: none -int32_t -fill_event_inotify_init_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint8_t flags) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_INOTIFY_INIT_E, 1, - flags); +int32_t fill_event_inotify_init_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint8_t flags) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_INOTIFY_INIT_E, + 1, + flags); } // PPME_SYSCALL_INOTIFY_INIT_X // Event field validity issues: none -int32_t -fill_event_inotify_init_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_INOTIFY_INIT_X, 1, - res); +int32_t fill_event_inotify_init_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_INOTIFY_INIT_X, + 1, + res); } // PPME_SYSCALL_SOCKETPAIR_E // Event field validity issues: none -int32_t -fill_event_socketpair_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t domain, - uint32_t type, - uint32_t proto) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_SOCKETPAIR_E, 3, - domain, - type, - proto); +int32_t fill_event_socketpair_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t domain, + uint32_t type, + uint32_t proto) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_SOCKETPAIR_E, + 3, + domain, + type, + proto); } // PPME_SYSCALL_SOCKETPAIR_X @@ -1338,163 +1351,182 @@ fill_event_socketpair_e(scap_sized_buffer scap_buf, size_t* event_size, char* sc // A) Always hardcoded due to value not available in native gVisor event: // - F3/source -- hardcoded to 0 // - F4/peer -- hardcoded to 0 -int32_t -fill_event_socketpair_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t fd1, - int64_t fd2) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SOCKET_SOCKETPAIR_X, 5, - res, - fd1, - fd2, - 0, // source -- INVALID - 0); // peer -- INVALID +int32_t fill_event_socketpair_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t fd1, + int64_t fd2) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SOCKET_SOCKETPAIR_X, + 5, + res, + fd1, + fd2, + 0, // source -- INVALID + 0); // peer -- INVALID } // PPME_SYSCALL_WRITE_E // Event field validity issues: none -int32_t -fill_event_write_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_WRITE_E, 2, - fd, - size); +int32_t fill_event_write_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_WRITE_E, + 2, + fd, + size); } // PPME_SYSCALL_WRITE_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F1/data -- hardcoded to empty string -int32_t -fill_event_write_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_WRITE_X, 2, - res, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_write_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_WRITE_X, + 2, + res, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_PWRITE_E // Event field validity issues: none -int32_t -fill_event_pwrite_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size, - uint64_t pos) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PWRITE_E, 3, - fd, - size, - pos); +int32_t fill_event_pwrite_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size, + uint64_t pos) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PWRITE_E, + 3, + fd, + size, + pos); } // PPME_SYSCALL_PWRITE_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F1/data -- hardcoded to empty string -int32_t -fill_event_pwrite_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PWRITE_X, 2, - res, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_pwrite_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PWRITE_X, + 2, + res, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_WRITEV_E // Event field validity issues: none -int32_t -fill_event_writev_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size) -{ - - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_WRITEV_E, 2, - fd, - size); +int32_t fill_event_writev_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_WRITEV_E, + 2, + fd, + size); } // PPME_SYSCALL_WRITEV_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F1/data -- hardcoded to empty string -int32_t -fill_event_writev_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_WRITEV_X, 2, - res, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_writev_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_WRITEV_X, + 2, + res, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_PWRITEV_E // Event field validity issues: none -int32_t -fill_event_pwritev_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size, - uint64_t pos) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PWRITEV_E, 3, - fd, - size, - pos); +int32_t fill_event_pwritev_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size, + uint64_t pos) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PWRITEV_E, + 3, + fd, + size, + pos); } // PPME_SYSCALL_PWRITEV_X // Event field validity issues: // A) Always hardcoded due to value not available in native gVisor event: // - F1/data -- hardcoded to empty string -int32_t -fill_event_pwritev_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_PWRITEV_X, 2, - res, - scap_const_sized_buffer{NULL, 0}); // data -- INVALID +int32_t fill_event_pwritev_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_PWRITEV_X, + 2, + res, + scap_const_sized_buffer{NULL, 0}); // data -- INVALID } // PPME_SYSCALL_MMAP_E // Event field validity issues: none -int32_t -fill_event_mmap_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint64_t addr, - uint64_t length, - uint32_t prot, - uint32_t flags, - int64_t fd, - uint64_t offset) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_MMAP_E, 6, - addr, - length, - prot, - flags, - fd, - offset); +int32_t fill_event_mmap_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint64_t addr, + uint64_t length, + uint32_t prot, + uint32_t flags, + int64_t fd, + uint64_t offset) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_MMAP_E, + 6, + addr, + length, + prot, + flags, + fd, + offset); } // PPME_SYSCALL_MMAP_X @@ -1503,31 +1535,35 @@ fill_event_mmap_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err // - F1/vm_size -- hardcoded to 0 // - F2/vm_rss -- hardcoded to 0 // - F3/vm_swap -- hardcoded to 0 -int32_t -fill_event_mmap_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_MMAP_X, 4, - res, - 0, // vm_size -- INVALID - 0, // vm_rss -- INVALID - 0); // vm_swap -- INVALID +int32_t fill_event_mmap_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_MMAP_X, + 4, + res, + 0, // vm_size -- INVALID + 0, // vm_rss -- INVALID + 0); // vm_swap -- INVALID } // PPME_SYSCALL_MUNMAP_E // Event field validity issues: none -int32_t -fill_event_munmap_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint64_t addr, - uint64_t length) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_MUNMAP_E, 6, - addr, - length); +int32_t fill_event_munmap_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint64_t addr, + uint64_t length) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_MUNMAP_E, + 6, + addr, + length); } // PPME_SYSCALL_MUNMAP_X @@ -1536,18 +1572,20 @@ fill_event_munmap_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_e // - F1/vm_size -- hardcoded to 0 // - F2/vm_rss -- hardcoded to 0 // - F3/vm_swap -- hardcoded to 0 -int32_t -fill_event_munmap_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res) -{ - return scap_event_encode_params( - scap_buf, event_size, scap_err, - PPME_SYSCALL_MUNMAP_X, 4, - res, - 0, // vm_size -- INVALID - 0, // vm_rss -- INVALID - 0); // vm_swap -- INVALID -} - -} // namespace fillers -} // namespace scap_gvisor +int32_t fill_event_munmap_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res) { + return scap_event_encode_params(scap_buf, + event_size, + scap_err, + PPME_SYSCALL_MUNMAP_X, + 4, + res, + 0, // vm_size -- INVALID + 0, // vm_rss -- INVALID + 0); // vm_swap -- INVALID +} + +} // namespace fillers +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/fillers.h b/userspace/libscap/engine/gvisor/fillers.h index e74b99091e..a25b14f88f 100644 --- a/userspace/libscap/engine/gvisor/fillers.h +++ b/userspace/libscap/engine/gvisor/fillers.h @@ -25,473 +25,544 @@ limitations under the License. namespace scap_gvisor { namespace fillers { -int32_t -fill_event_clone_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_clone_20_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - scap_const_sized_buffer args, - uint64_t tid, - uint64_t pid, - uint64_t ptid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - uint32_t flags, - uint32_t uid, - uint32_t gid, - uint64_t vtid, - uint64_t vpid, - uint64_t pidns_init_start_ts); - -int32_t -fill_event_fork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_fork_20_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - uint32_t uid, - uint32_t gid, - uint64_t vtid, - uint64_t vpid, - uint64_t pidns_init_start_ts); - -int32_t -fill_event_vfork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_vfork_20_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - uint32_t uid, - uint32_t gid, - uint64_t vtid, - uint64_t vpid, - uint64_t pidns_init_start_ts); - -int32_t -fill_event_execve_19_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - const char* filename); - -int32_t -fill_event_execve_19_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - scap_const_sized_buffer args, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - scap_const_sized_buffer env, - uint32_t uid); - -int32_t -fill_event_execveat_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t dirfd, - const char* pathname, - uint32_t flags); - -int32_t -fill_event_execveat_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* exe, - scap_const_sized_buffer args, - uint64_t tid, - uint64_t pid, - const char* cwd, - const char* comm, - scap_const_sized_buffer cgroups, - scap_const_sized_buffer env, - uint32_t uid); - -int32_t -fill_event_procexit_1_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t status, - uint32_t ret, - uint32_t sig, - uint32_t core); - -int32_t -fill_event_open_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - const char* name, - uint32_t flags, - uint32_t mode); - -int32_t -fill_event_open_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - const char* name, - uint32_t flags, - uint32_t mode); - -int32_t -fill_event_openat_2_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t dirfd, - const char* name, - uint32_t flags, - uint32_t mode); - -int32_t -fill_event_openat_2_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - int64_t dirfd, - const char* name, - uint32_t flags, - uint32_t mode); - -int32_t -fill_event_creat_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - const char* name, - uint32_t mode); - -int32_t -fill_event_creat_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - const char* name, - uint32_t mode); - -int32_t -fill_event_close_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_close_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_read_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size); - -int32_t -fill_event_read_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_pread_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size, - uint64_t pos); - -int32_t -fill_event_pread_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_readv_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_readv_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - uint32_t size); - -int32_t -fill_event_preadv_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint64_t pos); - -int32_t -fill_event_preadv_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - uint32_t size); - -int32_t -fill_event_connect_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - scap_const_sized_buffer addr); - -int32_t -fill_event_connect_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - scap_const_sized_buffer tuple, - int64_t fd); - -int32_t -fill_event_socket_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t domain, - uint32_t type, - uint32_t protocol); - -int32_t -fill_event_socket_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_chdir_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_chdir_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* path); - -int32_t -fill_event_fchdir_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_fchdir_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_setuid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t uid); - -int32_t -fill_event_setuid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_setgid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t gid); - -int32_t -fill_event_setgid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_setsid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_setsid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_setresuid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t ruid, - uint32_t euid, - uint32_t suid); - -int32_t -fill_event_setresuid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_setresgid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t rgid, - uint32_t egid, - uint32_t sgid); - -int32_t -fill_event_setresgid_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_prlimit_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t pid, - uint8_t resource); - -int32_t -fill_event_prlimit_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t newcur, - int64_t newmax, - int64_t oldcur, - int64_t oldmax); - -int32_t -fill_event_pipe_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_pipe_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t fd1, - int64_t fd2); - -int32_t -fill_event_fcntl_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint8_t cmd); - -int32_t -fill_event_fcntl_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_dup_1_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_dup_1_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t oldfd); - -int32_t -fill_event_dup2_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_dup2_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t oldfd, - int64_t newfd); - -int32_t -fill_event_dup3_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_dup3_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t oldfd, - int64_t newfd, - uint32_t flags); - -int32_t -fill_event_signalfd_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t mask, - uint8_t flags); - -int32_t -fill_event_signalfd_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_chroot_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_chroot_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - const char* path); - -int32_t -fill_event_eventfd_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint64_t initval, - uint32_t flags); - -int32_t -fill_event_eventfd_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_bind_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd); - -int32_t -fill_event_bind_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - scap_const_sized_buffer addr); - -int32_t -fill_event_accept_5_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); - -int32_t -fill_event_accept_5_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - scap_const_sized_buffer tuple); - -int32_t -fill_event_accept4_6_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int32_t flags); - -int32_t -fill_event_accept4_6_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - scap_const_sized_buffer tuple); - -int32_t -fill_event_timerfd_create_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint8_t clockid, - uint8_t flags); - -int32_t -fill_event_timerfd_create_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, +int32_t fill_event_clone_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_clone_20_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + scap_const_sized_buffer args, + uint64_t tid, + uint64_t pid, + uint64_t ptid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + uint32_t flags, + uint32_t uid, + uint32_t gid, + uint64_t vtid, + uint64_t vpid, + uint64_t pidns_init_start_ts); + +int32_t fill_event_fork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_fork_20_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + uint32_t uid, + uint32_t gid, + uint64_t vtid, + uint64_t vpid, + uint64_t pidns_init_start_ts); + +int32_t fill_event_vfork_20_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_vfork_20_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + uint32_t uid, + uint32_t gid, + uint64_t vtid, + uint64_t vpid, + uint64_t pidns_init_start_ts); + +int32_t fill_event_execve_19_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + const char* filename); + +int32_t fill_event_execve_19_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + scap_const_sized_buffer args, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + scap_const_sized_buffer env, + uint32_t uid); + +int32_t fill_event_execveat_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t dirfd, + const char* pathname, + uint32_t flags); + +int32_t fill_event_execveat_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* exe, + scap_const_sized_buffer args, + uint64_t tid, + uint64_t pid, + const char* cwd, + const char* comm, + scap_const_sized_buffer cgroups, + scap_const_sized_buffer env, + uint32_t uid); + +int32_t fill_event_procexit_1_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t status, + uint32_t ret, + uint32_t sig, + uint32_t core); + +int32_t fill_event_open_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + const char* name, + uint32_t flags, + uint32_t mode); + +int32_t fill_event_open_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + const char* name, + uint32_t flags, + uint32_t mode); + +int32_t fill_event_openat_2_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t dirfd, + const char* name, + uint32_t flags, + uint32_t mode); + +int32_t fill_event_openat_2_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + int64_t dirfd, + const char* name, + uint32_t flags, + uint32_t mode); + +int32_t fill_event_creat_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + const char* name, + uint32_t mode); + +int32_t fill_event_creat_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + const char* name, + uint32_t mode); + +int32_t fill_event_close_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_close_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_read_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size); + +int32_t fill_event_read_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_pread_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size, + uint64_t pos); + +int32_t fill_event_pread_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_readv_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_readv_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + uint32_t size); + +int32_t fill_event_preadv_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint64_t pos); + +int32_t fill_event_preadv_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + uint32_t size); + +int32_t fill_event_connect_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + scap_const_sized_buffer addr); + +int32_t fill_event_connect_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + scap_const_sized_buffer tuple, + int64_t fd); + +int32_t fill_event_socket_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t domain, + uint32_t type, + uint32_t protocol); + +int32_t fill_event_socket_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_chdir_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_chdir_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* path); + +int32_t fill_event_fchdir_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_fchdir_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_setuid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t uid); + +int32_t fill_event_setuid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_setgid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t gid); + +int32_t fill_event_setgid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_setsid_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_setsid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, int64_t res); -int32_t -fill_event_inotify_init_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint8_t flags); +int32_t fill_event_setresuid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t ruid, + uint32_t euid, + uint32_t suid); + +int32_t fill_event_setresuid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_setresgid_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t rgid, + uint32_t egid, + uint32_t sgid); + +int32_t fill_event_setresgid_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_prlimit_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t pid, + uint8_t resource); + +int32_t fill_event_prlimit_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t newcur, + int64_t newmax, + int64_t oldcur, + int64_t oldmax); + +int32_t fill_event_pipe_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_pipe_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t fd1, + int64_t fd2); + +int32_t fill_event_fcntl_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint8_t cmd); + +int32_t fill_event_fcntl_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_dup_1_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_dup_1_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t oldfd); + +int32_t fill_event_dup2_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_dup2_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t oldfd, + int64_t newfd); + +int32_t fill_event_dup3_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_dup3_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t oldfd, + int64_t newfd, + uint32_t flags); + +int32_t fill_event_signalfd_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t mask, + uint8_t flags); + +int32_t fill_event_signalfd_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_chroot_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_chroot_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + const char* path); + +int32_t fill_event_eventfd_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint64_t initval, + uint32_t flags); + +int32_t fill_event_eventfd_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_bind_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd); + +int32_t fill_event_bind_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + scap_const_sized_buffer addr); + +int32_t fill_event_accept_5_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err); + +int32_t fill_event_accept_5_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + scap_const_sized_buffer tuple); + +int32_t fill_event_accept4_6_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int32_t flags); + +int32_t fill_event_accept4_6_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + scap_const_sized_buffer tuple); + +int32_t fill_event_timerfd_create_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint8_t clockid, + uint8_t flags); + +int32_t fill_event_timerfd_create_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_inotify_init_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint8_t flags); + +int32_t fill_event_inotify_init_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_socketpair_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint32_t domain, + uint32_t type, + uint32_t proto); + +int32_t fill_event_socketpair_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res, + int64_t fd1, + int64_t fd2); + +int32_t fill_event_write_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size); + +int32_t fill_event_write_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_pwrite_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size, + uint64_t pos); + +int32_t fill_event_pwrite_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); -int32_t -fill_event_inotify_init_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, +int32_t fill_event_writev_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size); + +int32_t fill_event_writev_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_pwritev_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t fd, + uint32_t size, + uint64_t pos); + +int32_t fill_event_pwritev_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +int32_t fill_event_mmap_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint64_t addr, + uint64_t length, + uint32_t prot, + uint32_t flags, + int64_t fd, + uint64_t offset); + +int32_t fill_event_mmap_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, int64_t res); -int32_t -fill_event_socketpair_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint32_t domain, - uint32_t type, - uint32_t proto); - -int32_t -fill_event_socketpair_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res, - int64_t fd1, - int64_t fd2); - -int32_t -fill_event_write_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size); - -int32_t -fill_event_write_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_pwrite_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size, - uint64_t pos); - -int32_t -fill_event_pwrite_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_writev_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size); - -int32_t -fill_event_writev_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_pwritev_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t fd, - uint32_t size, - uint64_t pos); - -int32_t -fill_event_pwritev_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_mmap_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint64_t addr, - uint64_t length, - uint32_t prot, - uint32_t flags, - int64_t fd, - uint64_t offset); - -int32_t -fill_event_mmap_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -int32_t -fill_event_munmap_e(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - uint64_t addr, - uint64_t length); - -int32_t -fill_event_munmap_x(scap_sized_buffer scap_buf, size_t* event_size, char* scap_err, - int64_t res); - -} // namespace fillers -} // namespace scap_gvisor +int32_t fill_event_munmap_e(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + uint64_t addr, + uint64_t length); + +int32_t fill_event_munmap_x(scap_sized_buffer scap_buf, + size_t* event_size, + char* scap_err, + int64_t res); + +} // namespace fillers +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/gvisor.cpp b/userspace/libscap/engine/gvisor/gvisor.cpp index ac8e4e965c..f76bf7a023 100644 --- a/userspace/libscap/engine/gvisor/gvisor.cpp +++ b/userspace/libscap/engine/gvisor/gvisor.cpp @@ -40,31 +40,34 @@ extern "C" { namespace { -int32_t scap_gvisor_init_platform(scap_platform* platform, char* lasterr, scap_engine_handle engine, scap_open_args* oargs) -{ +int32_t scap_gvisor_init_platform(scap_platform* platform, + char* lasterr, + scap_engine_handle engine, + scap_open_args* oargs) { auto gvisor_platform = reinterpret_cast(platform); auto params = reinterpret_cast(oargs->engine_params); gvisor_platform->m_lasterr = lasterr; - gvisor_platform->m_platform = std::make_unique(gvisor_platform->m_lasterr, - params->gvisor_root_path); + gvisor_platform->m_platform = + std::make_unique(gvisor_platform->m_lasterr, + params->gvisor_root_path); return SCAP_SUCCESS; } -int32_t get_fdinfos(void* ctx, const scap_threadinfo* tinfo, uint64_t* n, const scap_fdinfo** fdinfos) -{ +int32_t get_fdinfos(void* ctx, + const scap_threadinfo* tinfo, + uint64_t* n, + const scap_fdinfo** fdinfos) { auto gv = reinterpret_cast(ctx); return gv->get_fdinfos(tinfo, n, fdinfos); } -int32_t scap_gvisor_refresh_proc_table(scap_platform* platform, scap_proclist* proclist) -{ +int32_t scap_gvisor_refresh_proc_table(scap_platform* platform, scap_proclist* proclist) { auto gvisor_platform = reinterpret_cast(platform); - scap_gvisor::platform *gv = gvisor_platform->m_platform.get(); + scap_gvisor::platform* gv = gvisor_platform->m_platform.get(); - if(gv == nullptr) - { + if(gv == nullptr) { return scap_errprintf(gvisor_platform->m_lasterr, 0, "Platform not initialized yet"); } @@ -72,36 +75,35 @@ int32_t scap_gvisor_refresh_proc_table(scap_platform* platform, scap_proclist* p const scap_threadinfo* tinfos; int ret = gv->get_threadinfos(&n, &tinfos); - if(ret != SCAP_SUCCESS) - { + if(ret != SCAP_SUCCESS) { return ret; } return scap_proc_scan_vtable(gvisor_platform->m_lasterr, proclist, n, tinfos, gv, get_fdinfos); } -int32_t scap_gvisor_close_platform(scap_platform* platform) -{ +int32_t scap_gvisor_close_platform(scap_platform* platform) { return SCAP_SUCCESS; } -void scap_gvisor_free_platform(scap_platform* platform) -{ +void scap_gvisor_free_platform(scap_platform* platform) { auto gvisor_platform = reinterpret_cast(platform); delete gvisor_platform; } -bool scap_gvisor_is_thread_alive(scap_platform* platform, int64_t pid, int64_t tid, const char* comm) -{ - return true; // TODO we actually need a real implementation +bool scap_gvisor_is_thread_alive(scap_platform* platform, + int64_t pid, + int64_t tid, + const char* comm) { + return true; // TODO we actually need a real implementation } -int32_t gvisor_get_threadlist(scap_platform* platform, ppm_proclist_info** procinfo_p, char* lasterr) -{ - if(*procinfo_p == NULL) - { - if(scap_alloc_proclist_info(procinfo_p, SCAP_DRIVER_PROCINFO_INITIAL_SIZE, lasterr) == false) - { +int32_t gvisor_get_threadlist(scap_platform* platform, + ppm_proclist_info** procinfo_p, + char* lasterr) { + if(*procinfo_p == NULL) { + if(scap_alloc_proclist_info(procinfo_p, SCAP_DRIVER_PROCINFO_INITIAL_SIZE, lasterr) == + false) { return SCAP_FAILURE; } } @@ -113,22 +115,22 @@ int32_t gvisor_get_threadlist(scap_platform* platform, ppm_proclist_info** proci } const scap_platform_vtable scap_gvisor_platform_vtable = { - .init_platform = scap_gvisor_init_platform, - .refresh_addr_list = NULL, - .get_device_by_mount_id = NULL, - .get_proc = NULL, - .refresh_proc_table = scap_gvisor_refresh_proc_table, - .is_thread_alive = scap_gvisor_is_thread_alive, - .get_global_pid = NULL, - .get_threadlist = gvisor_get_threadlist, - .get_fdlist = NULL, - - .close_platform = scap_gvisor_close_platform, - .free_platform = scap_gvisor_free_platform, + .init_platform = scap_gvisor_init_platform, + .refresh_addr_list = NULL, + .get_device_by_mount_id = NULL, + .get_proc = NULL, + .refresh_proc_table = scap_gvisor_refresh_proc_table, + .is_thread_alive = scap_gvisor_is_thread_alive, + .get_global_pid = NULL, + .get_threadlist = gvisor_get_threadlist, + .get_fdlist = NULL, + + .close_platform = scap_gvisor_close_platform, + .free_platform = scap_gvisor_free_platform, }; -scap_platform* scap_gvisor_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context) -{ +scap_platform* scap_gvisor_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context) { auto platform = new scap_gvisor_platform(); platform->m_generic.m_vtable = &scap_gvisor_platform_vtable; @@ -137,95 +139,93 @@ scap_platform* scap_gvisor_alloc_platform(proc_entry_callback proc_callback, voi return &platform->m_generic; } -void* gvisor_alloc_handle(scap_t* main_handle, char* lasterr_ptr) -{ +void* gvisor_alloc_handle(scap_t* main_handle, char* lasterr_ptr) { return new scap_gvisor::engine(lasterr_ptr); } -int32_t gvisor_init(scap_t* main_handle, scap_open_args* oargs) -{ +int32_t gvisor_init(scap_t* main_handle, scap_open_args* oargs) { auto gv = reinterpret_cast(main_handle->m_engine.m_handle); auto params = (scap_gvisor_engine_params*)oargs->engine_params; - return gv->init(params->gvisor_config_path, params->gvisor_root_path, params->no_events, params->gvisor_epoll_timeout, params->gvisor_platform); + return gv->init(params->gvisor_config_path, + params->gvisor_root_path, + params->no_events, + params->gvisor_epoll_timeout, + params->gvisor_platform); } -void gvisor_free_handle(scap_engine_handle engine) -{ +void gvisor_free_handle(scap_engine_handle engine) { delete reinterpret_cast(engine.m_handle); } -int32_t gvisor_start_capture(scap_engine_handle engine) -{ +int32_t gvisor_start_capture(scap_engine_handle engine) { return HANDLE(engine)->start_capture(); } -int32_t gvisor_close(scap_engine_handle engine) -{ +int32_t gvisor_close(scap_engine_handle engine) { return HANDLE(engine)->close(); } -int32_t gvisor_stop_capture(scap_engine_handle engine) -{ +int32_t gvisor_stop_capture(scap_engine_handle engine) { return HANDLE(engine)->stop_capture(); } -int32_t gvisor_next(scap_engine_handle engine, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags) -{ +int32_t gvisor_next(scap_engine_handle engine, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags) { return HANDLE(engine)->next(pevent, pdevid, pflags); } -int32_t gvisor_configure(scap_engine_handle engine, scap_setting setting, unsigned long arg1, unsigned long arg2) -{ +int32_t gvisor_configure(scap_engine_handle engine, + scap_setting setting, + unsigned long arg1, + unsigned long arg2) { return SCAP_SUCCESS; } -int32_t gvisor_get_stats(scap_engine_handle engine, scap_stats* stats) -{ +int32_t gvisor_get_stats(scap_engine_handle engine, scap_stats* stats) { return HANDLE(engine)->get_stats(stats); } -const metrics_v2* gvisor_get_stats_v2(scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc) -{ +const metrics_v2* gvisor_get_stats_v2(scap_engine_handle engine, + uint32_t flags, + uint32_t* nstats, + int32_t* rc) { return HANDLE(engine)->get_stats_v2(flags, nstats, rc); } -int32_t gvisor_get_n_tracepoint_hit(scap_engine_handle engine, long* ret) -{ +int32_t gvisor_get_n_tracepoint_hit(scap_engine_handle engine, long* ret) { return SCAP_NOT_SUPPORTED; } -uint32_t gvisor_get_n_devs(scap_engine_handle engine) -{ +uint32_t gvisor_get_n_devs(scap_engine_handle engine) { return 0; } -uint64_t gvisor_get_max_buf_used(scap_engine_handle engine) -{ +uint64_t gvisor_get_max_buf_used(scap_engine_handle engine) { return 0; } -} // anonymous namespace - -extern const scap_vtable scap_gvisor_engine = { - .name = GVISOR_ENGINE, - .savefile_ops = nullptr, - - .alloc_handle = gvisor_alloc_handle, - .init = gvisor_init, - .get_flags = nullptr, - .free_handle = gvisor_free_handle, - .close = gvisor_close, - .next = gvisor_next, - .start_capture = gvisor_start_capture, - .stop_capture = gvisor_stop_capture, - .configure = gvisor_configure, - .get_stats = gvisor_get_stats, - .get_stats_v2 = gvisor_get_stats_v2, - .get_n_tracepoint_hit = gvisor_get_n_tracepoint_hit, - .get_n_devs = gvisor_get_n_devs, - .get_max_buf_used = gvisor_get_max_buf_used, - .get_api_version = nullptr, - .get_schema_version = nullptr -}; - -} // extern "C" +} // anonymous namespace + +extern const scap_vtable scap_gvisor_engine = {.name = GVISOR_ENGINE, + .savefile_ops = nullptr, + + .alloc_handle = gvisor_alloc_handle, + .init = gvisor_init, + .get_flags = nullptr, + .free_handle = gvisor_free_handle, + .close = gvisor_close, + .next = gvisor_next, + .start_capture = gvisor_start_capture, + .stop_capture = gvisor_stop_capture, + .configure = gvisor_configure, + .get_stats = gvisor_get_stats, + .get_stats_v2 = gvisor_get_stats_v2, + .get_n_tracepoint_hit = gvisor_get_n_tracepoint_hit, + .get_n_devs = gvisor_get_n_devs, + .get_max_buf_used = gvisor_get_max_buf_used, + .get_api_version = nullptr, + .get_schema_version = nullptr}; + +} // extern "C" diff --git a/userspace/libscap/engine/gvisor/gvisor.h b/userspace/libscap/engine/gvisor/gvisor.h index 38bb3bba22..b1cb09192e 100644 --- a/userspace/libscap/engine/gvisor/gvisor.h +++ b/userspace/libscap/engine/gvisor/gvisor.h @@ -35,47 +35,46 @@ limitations under the License. namespace scap_gvisor { #pragma pack(push, 1) -struct header -{ - uint16_t header_size; - uint16_t message_type; - uint32_t dropped_count; +struct header { + uint16_t header_size; + uint16_t message_type; + uint32_t dropped_count; }; #pragma pack(pop) namespace parsers { struct parse_result { - // the scap status of the operation - uint32_t status = 0; - // description of the error in case of failure - std::string error; - // the total encoded event(s) size - size_t size = 0; - // pointers to each encoded event within the supplied output buffer - std::vector scap_events; - // number of events dropped by gVisor - uint32_t dropped_count = 0; + // the scap status of the operation + uint32_t status = 0; + // description of the error in case of failure + std::string error; + // the total encoded event(s) size + size_t size = 0; + // pointers to each encoded event within the supplied output buffer + std::vector scap_events; + // number of events dropped by gVisor + uint32_t dropped_count = 0; }; struct procfs_result { - // the scap status of the operation - uint32_t status = 0; - // description of the error in case of failure - std::string error; - // the resulting thread information - scap_threadinfo tinfo; - // the fdinfos associated with this thread - std::vector fdinfos; + // the scap status of the operation + uint32_t status = 0; + // description of the error in case of failure + std::string error; + // the resulting thread information + scap_threadinfo tinfo; + // the fdinfos associated with this thread + std::vector fdinfos; }; struct config_result { - // the scap status of the operation - uint32_t status; - // description of the error in case of failure - std::string error; - // the socket path - std::string socket_path; + // the scap status of the operation + uint32_t status; + // description of the error in case of failure + std::string error; + // the socket path + std::string socket_path; }; /*! @@ -86,16 +85,20 @@ struct config_result { \return a parse_result struct. If the encoding is successful: - the status field will be set as SCAP_SUCCESS - - the scap_events vector will contain pointers to each encoded event, all located within scap_buf's memory + - the scap_events vector will contain pointers to each encoded event, all located within + scap_buf's memory - the size field will indicate the total used size in scap_buf. If the buffer is too small to contain all encoded events: - the status field will be set as SCAP_INPUT_TOO_SMALL - - the size field will be set to the total required size to fully translate the supplied gVisor event - In case of any error: - - the status field will be set to SCAP_FAILURE for parsing errors, SCAP_NOT_SUPPORTED for unsupported events + - the size field will be set to the total required size to fully translate the supplied + gVisor event In case of any error: + - the status field will be set to SCAP_FAILURE for parsing errors, SCAP_NOT_SUPPORTED + for unsupported events - the error field will contain a string representation of the error */ -parse_result parse_gvisor_proto(uint32_t id, scap_const_sized_buffer gvisor_buf, scap_sized_buffer scap_buf); +parse_result parse_gvisor_proto(uint32_t id, + scap_const_sized_buffer gvisor_buf, + scap_sized_buffer scap_buf); /*! \brief Get the container ID from a gVisor seccheck protobuf @@ -110,119 +113,125 @@ uint64_t get_vxid(uint64_t vxid); config_result parse_config(std::string config); -} // namespace parsers +} // namespace parsers -namespace runsc -{ +namespace runsc { - struct result { - int error = 0; - std::vector output; - }; +struct result { + int error = 0; + std::vector output; +}; - result version(); - result list(const std::string &root_path); - result trace_create(const std::string &root_path, const std::string &trace_session_path, const std::string &sandbox_id, bool force); - result trace_delete(const std::string &root_path, const std::string &session_name, const std::string &sandbox_id); - result trace_procfs(const std::string &root_path, const std::string &sandbox_id); +result version(); +result list(const std::string &root_path); +result trace_create(const std::string &root_path, + const std::string &trace_session_path, + const std::string &sandbox_id, + bool force); +result trace_delete(const std::string &root_path, + const std::string &session_name, + const std::string &sandbox_id); +result trace_procfs(const std::string &root_path, const std::string &sandbox_id); -} // namespace runsc +} // namespace runsc // contains entries to store per-sandbox data and buffers to use to write events in class sandbox_entry { public: - sandbox_entry(); - ~sandbox_entry(); + sandbox_entry(); + ~sandbox_entry(); - int32_t expand_buffer(size_t size); + int32_t expand_buffer(size_t size); - scap_sized_buffer m_buf; - uint64_t m_last_dropped_count; - bool m_closing; - uint32_t m_id; - std::string m_container_id; + scap_sized_buffer m_buf; + uint64_t m_last_dropped_count; + bool m_closing; + uint32_t m_id; + std::string m_container_id; }; -class platform -{ +class platform { public: - platform(char *lasterr, std::string &&root_path) : - m_lasterr(lasterr), - m_root_path(std::move(root_path)) {} + platform(char *lasterr, std::string &&root_path): + m_lasterr(lasterr), + m_root_path(std::move(root_path)) {} - uint32_t get_threadinfos(uint64_t *n, const scap_threadinfo **tinfos); - uint32_t get_fdinfos(const scap_threadinfo *tinfo, uint64_t *n, const scap_fdinfo **fdinfos); + uint32_t get_threadinfos(uint64_t *n, const scap_threadinfo **tinfos); + uint32_t get_fdinfos(const scap_threadinfo *tinfo, uint64_t *n, const scap_fdinfo **fdinfos); - // obtains a unique ID for each active sandbox - uint32_t get_numeric_sandbox_id(std::string container_id); - void release_sandbox_id(std::string container_id); + // obtains a unique ID for each active sandbox + uint32_t get_numeric_sandbox_id(std::string container_id); + void release_sandbox_id(std::string container_id); private: - // the following two maps store and manage memory for thread information requested - // when get_threadinfos() is called. They are only updated upon get_threadinfos() - std::vector m_threadinfos_threads; - std::unordered_map> m_threadinfos_fds; + // the following two maps store and manage memory for thread information requested + // when get_threadinfos() is called. They are only updated upon get_threadinfos() + std::vector m_threadinfos_threads; + std::unordered_map> m_threadinfos_fds; - std::unordered_map m_sandbox_ids; + std::unordered_map m_sandbox_ids; - char* m_lasterr; - std::string m_root_path; + char *m_lasterr; + std::string m_root_path; }; class engine { public: - engine(char *lasterr); - ~engine(); - int32_t init(std::string config_path, std::string root_path, bool no_events, int epoll_timeout, scap_gvisor_platform *platform); - int32_t close(); + engine(char *lasterr); + ~engine(); + int32_t init(std::string config_path, + std::string root_path, + bool no_events, + int epoll_timeout, + scap_gvisor_platform *platform); + int32_t close(); + + int32_t start_capture(); + int32_t stop_capture(); - int32_t start_capture(); - int32_t stop_capture(); + int32_t next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags); - int32_t next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags); + uint32_t get_vxid(uint64_t pid) const; + int32_t get_stats(scap_stats *stats) const; + const struct metrics_v2 *get_stats_v2(uint32_t flags, uint32_t *nstats, int32_t *rc); - uint32_t get_vxid(uint64_t pid) const; - int32_t get_stats(scap_stats *stats) const; - const struct metrics_v2* get_stats_v2(uint32_t flags, uint32_t* nstats, int32_t* rc); private: - int32_t process_message_from_fd(int fd); - void free_sandbox_buffers(); - - char *m_lasterr = nullptr; - int m_listenfd = 0; - int m_epollfd = 0; - int m_epoll_timeout = -1; - bool m_capture_started = false; - bool m_no_events = false; - scap_gvisor_platform *m_platform = nullptr; - - std::string m_socket_path; - std::thread m_accept_thread; - - // contains pointers to parsed events to process - std::deque m_event_queue{}; - - // stores per-sandbox data. All buffers used to contain parsed event data are owned by this map - std::unordered_map m_sandbox_data; - - // the following two strings contains the path of the root dir used by the runsc command - // and the path the trace session configuration file used to set up traces, respectively - std::string m_root_path; - std::string m_trace_session_path; - - struct gvisor_stats - { - // total number of events received from gVisor - uint64_t n_evts; - // total number of drops due to parsig errors - uint64_t n_drops_parsing; - // total number of drops on gVisor side - uint64_t n_drops_gvisor; - } m_gvisor_stats; - - // Stats v2. - metrics_v2 m_stats[scap_gvisor::stats::MAX_GVISOR_COUNTERS_STATS]; + int32_t process_message_from_fd(int fd); + void free_sandbox_buffers(); + + char *m_lasterr = nullptr; + int m_listenfd = 0; + int m_epollfd = 0; + int m_epoll_timeout = -1; + bool m_capture_started = false; + bool m_no_events = false; + scap_gvisor_platform *m_platform = nullptr; + + std::string m_socket_path; + std::thread m_accept_thread; + + // contains pointers to parsed events to process + std::deque m_event_queue{}; + + // stores per-sandbox data. All buffers used to contain parsed event data are owned by this map + std::unordered_map m_sandbox_data; + + // the following two strings contains the path of the root dir used by the runsc command + // and the path the trace session configuration file used to set up traces, respectively + std::string m_root_path; + std::string m_trace_session_path; + + struct gvisor_stats { + // total number of events received from gVisor + uint64_t n_evts; + // total number of drops due to parsig errors + uint64_t n_drops_parsing; + // total number of drops on gVisor side + uint64_t n_drops_gvisor; + } m_gvisor_stats; + + // Stats v2. + metrics_v2 m_stats[scap_gvisor::stats::MAX_GVISOR_COUNTERS_STATS]; }; - -} // namespace scap_gvisor +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/gvisor_platform.h b/userspace/libscap/engine/gvisor/gvisor_platform.h index 9a61cf15a2..8da9a785af 100644 --- a/userspace/libscap/engine/gvisor/gvisor_platform.h +++ b/userspace/libscap/engine/gvisor/gvisor_platform.h @@ -21,13 +21,11 @@ limitations under the License. #include #include -namespace scap_gvisor -{ - class platform; +namespace scap_gvisor { +class platform; }; -struct scap_gvisor_platform -{ +struct scap_gvisor_platform { struct scap_platform m_generic; char* m_lasterr; std::unique_ptr m_platform; diff --git a/userspace/libscap/engine/gvisor/gvisor_public.h b/userspace/libscap/engine/gvisor/gvisor_public.h index e3ecf9f185..f85bc0aa11 100644 --- a/userspace/libscap/engine/gvisor/gvisor_public.h +++ b/userspace/libscap/engine/gvisor/gvisor_public.h @@ -19,22 +19,23 @@ limitations under the License. #define GVISOR_ENGINE "gvisor" #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - struct scap_gvisor_engine_params - { - const char* gvisor_root_path; ///< When using gvisor, the root path used by runsc commands - const char* gvisor_config_path; ///< When using gvisor, the path to the configuration file +struct scap_gvisor_engine_params { + const char* gvisor_root_path; ///< When using gvisor, the root path used by runsc commands + const char* gvisor_config_path; ///< When using gvisor, the path to the configuration file - bool no_events; //< Pinky swear we don't want any event from it (i.e. next will always fail, just have proc scan) - int gvisor_epoll_timeout; ///< When using gvisor, the timeout to wait for a new event - struct scap_gvisor_platform *gvisor_platform; ///< The gvisor engine and platform have a bit of shared state - }; + bool no_events; //< Pinky swear we don't want any event from it (i.e. next will always fail, + // just have proc scan) + int gvisor_epoll_timeout; ///< When using gvisor, the timeout to wait for a new event + struct scap_gvisor_platform* + gvisor_platform; ///< The gvisor engine and platform have a bit of shared state +}; - struct scap_platform; - struct scap_platform* scap_gvisor_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context); +struct scap_platform; +struct scap_platform* scap_gvisor_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context); #ifdef __cplusplus }; diff --git a/userspace/libscap/engine/gvisor/parsers.cpp b/userspace/libscap/engine/gvisor/parsers.cpp index 9ed993cc06..d3b2515d49 100644 --- a/userspace/libscap/engine/gvisor/parsers.cpp +++ b/userspace/libscap/engine/gvisor/parsers.cpp @@ -68,37 +68,32 @@ constexpr size_t socktuple_buffer_size = 1024; // In gVisor there's no concept of tid and tgid but only vtid and vtgid. // However, to fit into sinsp we do need values for tid and tgid. -static uint64_t generate_tid_field(uint64_t tid, uint32_t sandbox_id) -{ +static uint64_t generate_tid_field(uint64_t tid, uint32_t sandbox_id) { uint64_t tid_field = sandbox_id; tid_field = tid | (tid_field << 32); return tid_field; } // Perform conversion from pid/tid field to vpid/vtid -uint64_t get_vxid(uint64_t xid) -{ +uint64_t get_vxid(uint64_t xid) { return xid & 0xffffffff; } template -static void fill_context_data(scap_evt *evt, T& gvisor_evt, uint32_t id) -{ - auto& context_data = gvisor_evt.context_data(); +static void fill_context_data(scap_evt *evt, T &gvisor_evt, uint32_t id) { + auto &context_data = gvisor_evt.context_data(); evt->ts = context_data.time_ns(); evt->tid = generate_tid_field(context_data.thread_id(), id); } -static int32_t process_unhandled_syscall(uint64_t sysno, char* error_buf) -{ - snprintf(error_buf, SCAP_LASTERR_SIZE, - "Unhandled syscall: %s", - std::to_string(sysno).c_str()); +static int32_t process_unhandled_syscall(uint64_t sysno, char *error_buf) { + snprintf(error_buf, SCAP_LASTERR_SIZE, "Unhandled syscall: %s", std::to_string(sysno).c_str()); return SCAP_NOT_SUPPORTED; } -static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_container_start(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; ret.status = SCAP_SUCCESS; ret.size = 0; @@ -109,8 +104,7 @@ static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer p size_t event_size; gvisor::container::Start gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking container start protobuf message"; return ret; @@ -136,18 +130,15 @@ static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer p cgroups += container_id; std::string exe, comm; - exe = gvisor_evt.args(0).c_str(); // exe, best available info from gVisor evt + exe = gvisor_evt.args(0).c_str(); // exe, best available info from gVisor evt size_t pos = exe.find_last_of("/"); - if (pos != std::string::npos) - { + if(pos != std::string::npos) { comm = exe.substr(pos + 1); - } - else - { + } else { comm = exe; } - auto& context_data = gvisor_evt.context_data(); + auto &context_data = gvisor_evt.context_data(); std::string cwd = context_data.cwd(); @@ -155,21 +146,20 @@ static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer p uint64_t tgid_field = generate_tid_field(1, id); // encode clone entry - ret.status = scap_gvisor::fillers::fill_event_clone_20_e( - event_buf, &event_size, scap_err); - if (ret.status == SCAP_FAILURE) { + ret.status = scap_gvisor::fillers::fill_event_clone_20_e(event_buf, &event_size, scap_err); + if(ret.status == SCAP_FAILURE) { ret.error = scap_err; return ret; } ret.size += event_size; - if (ret.size <= scap_buf.size) { - scap_evt *evt = static_cast(event_buf.buf); + if(ret.size <= scap_buf.size) { + scap_evt *evt = static_cast(event_buf.buf); evt->ts = context_data.time_ns(); evt->tid = tid_field; ret.scap_events.push_back(evt); - event_buf.buf = (char*)scap_buf.buf + ret.size; + event_buf.buf = (char *)scap_buf.buf + ret.size; event_buf.size = scap_buf.size - ret.size; } else { event_buf.buf = nullptr; @@ -178,36 +168,38 @@ static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer p // encode clone exit ret.status = scap_gvisor::fillers::fill_event_clone_20_x( - event_buf, &event_size, scap_err, - 0, // res = 0 in the child thread - exe.c_str(), - scap_const_sized_buffer{args.data(), args.size()}, - tid_field, // tid - tgid_field, // pid - 1, // ptid for initial process - "", // cwd for initial process - comm.c_str(), - scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, - 0, // flags -- INVALID/not available in gVisor event - context_data.credentials().effective_uid(), // uid - context_data.credentials().effective_gid(), // gid - 1, // vtid - 1, // vpid - context_data.thread_start_time_ns()); // pidns_init_start_ts - - if (ret.status == SCAP_FAILURE) { + event_buf, + &event_size, + scap_err, + 0, // res = 0 in the child thread + exe.c_str(), + scap_const_sized_buffer{args.data(), args.size()}, + tid_field, // tid + tgid_field, // pid + 1, // ptid for initial process + "", // cwd for initial process + comm.c_str(), + scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, + 0, // flags -- INVALID/not available in gVisor event + context_data.credentials().effective_uid(), // uid + context_data.credentials().effective_gid(), // gid + 1, // vtid + 1, // vpid + context_data.thread_start_time_ns()); // pidns_init_start_ts + + if(ret.status == SCAP_FAILURE) { ret.error = scap_err; return ret; } ret.size += event_size; - if (ret.size <= scap_buf.size) { - scap_evt *evt = static_cast(event_buf.buf); + if(ret.size <= scap_buf.size) { + scap_evt *evt = static_cast(event_buf.buf); evt->ts = context_data.time_ns(); evt->tid = tid_field; ret.scap_events.push_back(evt); - event_buf.buf = (char*)scap_buf.buf + ret.size; + event_buf.buf = (char *)scap_buf.buf + ret.size; event_buf.size = scap_buf.size - ret.size; } else { event_buf.buf = nullptr; @@ -216,22 +208,24 @@ static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer p // encode execve entry ret.status = scap_gvisor::fillers::fill_event_execve_19_e( - event_buf, &event_size, scap_err, - gvisor_evt.args(0).c_str()); // TODO actual exe missing + event_buf, + &event_size, + scap_err, + gvisor_evt.args(0).c_str()); // TODO actual exe missing - if (ret.status == SCAP_FAILURE) { + if(ret.status == SCAP_FAILURE) { ret.error = scap_err; return ret; } ret.size += event_size; - if (ret.size <= scap_buf.size) { - scap_evt *evt = static_cast(event_buf.buf); + if(ret.size <= scap_buf.size) { + scap_evt *evt = static_cast(event_buf.buf); evt->ts = context_data.time_ns(); evt->tid = tid_field; ret.scap_events.push_back(evt); - event_buf.buf = (char*)scap_buf.buf + ret.size; + event_buf.buf = (char *)scap_buf.buf + ret.size; event_buf.size = scap_buf.size - ret.size; } else { event_buf.buf = nullptr; @@ -240,31 +234,33 @@ static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer p // encode execve exit ret.status = scap_gvisor::fillers::fill_event_execve_19_x( - event_buf, &event_size, scap_err, - 0, // res - exe.c_str(), - scap_const_sized_buffer{args.data(), args.size()}, - tid_field, // tid - tgid_field, // pid - cwd.c_str(), - comm.c_str(), - scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, - scap_const_sized_buffer{env.data(), env.size()}, - context_data.credentials().effective_uid()); // uid - - if (ret.status == SCAP_FAILURE) { + event_buf, + &event_size, + scap_err, + 0, // res + exe.c_str(), + scap_const_sized_buffer{args.data(), args.size()}, + tid_field, // tid + tgid_field, // pid + cwd.c_str(), + comm.c_str(), + scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, + scap_const_sized_buffer{env.data(), env.size()}, + context_data.credentials().effective_uid()); // uid + + if(ret.status == SCAP_FAILURE) { ret.error = scap_err; return ret; } ret.size += event_size; - if (ret.size <= scap_buf.size) { - scap_evt *evt = static_cast(event_buf.buf); + if(ret.size <= scap_buf.size) { + scap_evt *evt = static_cast(event_buf.buf); evt->ts = context_data.time_ns(); evt->tid = tid_field; ret.scap_events.push_back(evt); - event_buf.buf = (char*)scap_buf.buf + ret.size; + event_buf.buf = (char *)scap_buf.buf + ret.size; event_buf.size = scap_buf.size - ret.size; } else { event_buf.buf = nullptr; @@ -274,8 +270,9 @@ static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer p return ret; } -static parse_result parse_execve(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_execve(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; ret.status = SCAP_SUCCESS; ret.size = 0; @@ -283,8 +280,7 @@ static parse_result parse_execve(uint32_t id, scap_const_sized_buffer proto, sca scap_err[0] = '\0'; gvisor::syscall::Execve gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking execve protobuf message"; return ret; @@ -292,8 +288,7 @@ static parse_result parse_execve(uint32_t id, scap_const_sized_buffer proto, sca std::string pathname = gvisor_evt.pathname(); - if(gvisor_evt.has_exit()) - { + if(gvisor_evt.has_exit()) { std::string args; // skip argv[0] @@ -311,54 +306,52 @@ static parse_result parse_execve(uint32_t id, scap_const_sized_buffer proto, sca std::string comm; size_t pos = pathname.find_last_of("/"); - if (pos != std::string::npos) - { + if(pos != std::string::npos) { comm = pathname.substr(pos + 1); - } - else - { + } else { comm = pathname; } - auto& context_data = gvisor_evt.context_data(); + auto &context_data = gvisor_evt.context_data(); std::string cwd = context_data.cwd(); std::string cgroups = "gvisor_container_id=/"; cgroups += context_data.container_id(); - switch(gvisor_evt.sysno()) - { + switch(gvisor_evt.sysno()) { case __NR_execve: ret.status = scap_gvisor::fillers::fill_event_execve_19_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), // res - pathname.c_str(), // exe - scap_const_sized_buffer{args.data(), args.size()}, - generate_tid_field(context_data.thread_id(), id), // tid - generate_tid_field(context_data.thread_group_id(), id), // pid - cwd.c_str(), // cwd - comm.c_str(), // comm - scap_const_sized_buffer{cgroups.c_str(), - cgroups.length() + 1}, - scap_const_sized_buffer{env.data(), env.size()}, - 0); // uid -- INVALID/not available in gVisor evt + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), // res + pathname.c_str(), // exe + scap_const_sized_buffer{args.data(), args.size()}, + generate_tid_field(context_data.thread_id(), id), // tid + generate_tid_field(context_data.thread_group_id(), id), // pid + cwd.c_str(), // cwd + comm.c_str(), // comm + scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, + scap_const_sized_buffer{env.data(), env.size()}, + 0); // uid -- INVALID/not available in gVisor evt break; case __NR_execveat: ret.status = scap_gvisor::fillers::fill_event_execveat_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), // res - pathname.c_str(), // exe - scap_const_sized_buffer{args.data(), args.size()}, - generate_tid_field(context_data.thread_id(), id), // tid - generate_tid_field(context_data.thread_group_id(), id), // pid - cwd.c_str(), // cwd - comm.c_str(), // comm - scap_const_sized_buffer{cgroups.c_str(), - cgroups.length() + 1}, - scap_const_sized_buffer{env.data(), env.size()}, - 0); // uid -- INVALID/not available in gVisor evt + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), // res + pathname.c_str(), // exe + scap_const_sized_buffer{args.data(), args.size()}, + generate_tid_field(context_data.thread_id(), id), // tid + generate_tid_field(context_data.thread_group_id(), id), // pid + cwd.c_str(), // cwd + comm.c_str(), // comm + scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, + scap_const_sized_buffer{env.data(), env.size()}, + 0); // uid -- INVALID/not available in gVisor evt break; default: @@ -366,23 +359,23 @@ static parse_result parse_execve(uint32_t id, scap_const_sized_buffer proto, sca break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_execve: - ret.status = scap_gvisor::fillers::fill_event_execve_19_e( - scap_buf, &ret.size, scap_err, - pathname.c_str()); + ret.status = scap_gvisor::fillers::fill_event_execve_19_e(scap_buf, + &ret.size, + scap_err, + pathname.c_str()); break; case __NR_execveat: ret.status = scap_gvisor::fillers::fill_event_execveat_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - pathname.c_str(), - execveat_flags_to_scap(gvisor_evt.flags())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + pathname.c_str(), + execveat_flags_to_scap(gvisor_evt.flags())); break; default: @@ -391,20 +384,21 @@ static parse_result parse_execve(uint32_t id, scap_const_sized_buffer proto, sca } } - if (ret.status != SCAP_SUCCESS) { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_sentry_clone(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_sentry_clone(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; ret.status = SCAP_SUCCESS; ret.size = 0; @@ -412,14 +406,13 @@ static parse_result parse_sentry_clone(uint32_t id, scap_const_sized_buffer prot scap_err[0] = '\0'; gvisor::sentry::CloneInfo gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking sentry clone protobuf message"; return ret; } - auto& context_data = gvisor_evt.context_data(); + auto &context_data = gvisor_evt.context_data(); std::string cgroups = "gvisor_container_id=/"; cgroups += context_data.container_id(); @@ -427,29 +420,31 @@ static parse_result parse_sentry_clone(uint32_t id, scap_const_sized_buffer prot uint64_t tid_field = generate_tid_field(gvisor_evt.created_thread_id(), id); ret.status = scap_gvisor::fillers::fill_event_clone_20_x( - scap_buf, &ret.size, scap_err, - 0, // res for child thread - context_data.process_name().c_str(), // exe - scap_const_sized_buffer{"", 0}, // args -- INV/not available - tid_field, // tid - generate_tid_field(gvisor_evt.created_thread_group_id(), id), // pid - generate_tid_field(context_data.thread_id(), id), // ptid - context_data.cwd().c_str(), // cwd - context_data.process_name().c_str(), // comm - scap_const_sized_buffer{cgroups.c_str(), cgroups.size() + 1}, - 0, // flags -- INV/not available - 0, // uid -- INV/not available - 0, // gid -- INV/not available - gvisor_evt.created_thread_id(), // vtid - gvisor_evt.created_thread_group_id(), // vpid - context_data.thread_start_time_ns()); // pidns_init_start_ts - - if (ret.status != SCAP_SUCCESS) { + scap_buf, + &ret.size, + scap_err, + 0, // res for child thread + context_data.process_name().c_str(), // exe + scap_const_sized_buffer{"", 0}, // args -- INV/not available + tid_field, // tid + generate_tid_field(gvisor_evt.created_thread_group_id(), id), // pid + generate_tid_field(context_data.thread_id(), id), // ptid + context_data.cwd().c_str(), // cwd + context_data.process_name().c_str(), // comm + scap_const_sized_buffer{cgroups.c_str(), cgroups.size() + 1}, + 0, // flags -- INV/not available + 0, // uid -- INV/not available + 0, // gid -- INV/not available + gvisor_evt.created_thread_id(), // vtid + gvisor_evt.created_thread_group_id(), // vpid + context_data.thread_start_time_ns()); // pidns_init_start_ts + + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); evt->ts = context_data.time_ns(); evt->tid = tid_field; @@ -458,83 +453,86 @@ static parse_result parse_sentry_clone(uint32_t id, scap_const_sized_buffer prot return ret; } -static parse_result parse_read(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_read(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Read gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking read protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_read: - ret.status = scap_gvisor::fillers::fill_event_read_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_read_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_pread64: - ret.status = scap_gvisor::fillers::fill_event_pread_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_pread_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_readv: - ret.status = scap_gvisor::fillers::fill_event_readv_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.count()); + ret.status = scap_gvisor::fillers::fill_event_readv_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.count()); break; case __NR_preadv: - ret.status = scap_gvisor::fillers::fill_event_preadv_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.count()); + ret.status = scap_gvisor::fillers::fill_event_preadv_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.count()); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_read: - ret.status = scap_gvisor::fillers::fill_event_read_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.count()); + ret.status = scap_gvisor::fillers::fill_event_read_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.count()); break; case __NR_pread64: - ret.status = scap_gvisor::fillers::fill_event_pread_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.count(), - gvisor_evt.offset()); + ret.status = scap_gvisor::fillers::fill_event_pread_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.count(), + gvisor_evt.offset()); break; case __NR_readv: - ret.status = scap_gvisor::fillers::fill_event_readv_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd()); + ret.status = scap_gvisor::fillers::fill_event_readv_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd()); break; case __NR_preadv: - ret.status = scap_gvisor::fillers::fill_event_preadv_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.offset()); + ret.status = scap_gvisor::fillers::fill_event_preadv_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.offset()); break; default: @@ -543,12 +541,12 @@ static parse_result parse_read(uint32_t id, scap_const_sized_buffer proto, scap_ } } - if (ret.status != SCAP_SUCCESS) { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); @@ -558,70 +556,54 @@ static parse_result parse_read(uint32_t id, scap_const_sized_buffer proto, scap_ // Converts the address + port portion of a sockaddr in our representation // Providing a large enough buffer is responsibility of the caller. // Returns the number of bytes written -static inline size_t pack_addr_port(sockaddr *sa, char *targetbuf) -{ +static inline size_t pack_addr_port(sockaddr *sa, char *targetbuf) { size_t size = 0; - switch(sa->sa_family) - { - case AF_INET: - { - sockaddr_in *sa_in = (sockaddr_in *)sa; - uint16_t dport = ntohs(sa_in->sin_port); - memcpy(targetbuf, &sa_in->sin_addr.s_addr, sizeof(uint32_t)); - targetbuf += sizeof(uint32_t); - memcpy(targetbuf, &dport, sizeof(uint16_t)); - size = sizeof(uint32_t) + sizeof(uint16_t); - } - break; - - case AF_INET6: - { - sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; - uint16_t dport = ntohs(sa_in6->sin6_port); - memcpy(targetbuf, &sa_in6->sin6_addr, 2 * sizeof(uint64_t)); - targetbuf += 2 * sizeof(uint64_t); - memcpy(targetbuf, &dport, sizeof(uint16_t)); - size = 2 * sizeof(uint64_t) + sizeof(uint16_t); - } - break; - - case AF_UNIX: - { - sockaddr_un *sa_un = (sockaddr_un *)sa; - size_t len = strlcpy(targetbuf, sa_un->sun_path, UNIX_PATH_MAX); - size = len + 1; - } - break; + switch(sa->sa_family) { + case AF_INET: { + sockaddr_in *sa_in = (sockaddr_in *)sa; + uint16_t dport = ntohs(sa_in->sin_port); + memcpy(targetbuf, &sa_in->sin_addr.s_addr, sizeof(uint32_t)); + targetbuf += sizeof(uint32_t); + memcpy(targetbuf, &dport, sizeof(uint16_t)); + size = sizeof(uint32_t) + sizeof(uint16_t); + } break; + + case AF_INET6: { + sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; + uint16_t dport = ntohs(sa_in6->sin6_port); + memcpy(targetbuf, &sa_in6->sin6_addr, 2 * sizeof(uint64_t)); + targetbuf += 2 * sizeof(uint64_t); + memcpy(targetbuf, &dport, sizeof(uint16_t)); + size = 2 * sizeof(uint64_t) + sizeof(uint16_t); + } break; + + case AF_UNIX: { + sockaddr_un *sa_un = (sockaddr_un *)sa; + size_t len = strlcpy(targetbuf, sa_un->sun_path, UNIX_PATH_MAX); + size = len + 1; + } break; } return size; } -static inline size_t pack_sock_family(sockaddr *sa, char *targetbuf) -{ +static inline size_t pack_sock_family(sockaddr *sa, char *targetbuf) { uint8_t sock_family = 0; - switch(sa->sa_family) - { - case AF_INET: - { - sockaddr_in *sa_in = (sockaddr_in *)sa; - sock_family = socket_family_to_scap(sa_in->sin_family); - } - break; + switch(sa->sa_family) { + case AF_INET: { + sockaddr_in *sa_in = (sockaddr_in *)sa; + sock_family = socket_family_to_scap(sa_in->sin_family); + } break; - case AF_INET6: - { - sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; - sock_family = socket_family_to_scap(sa_in6->sin6_family); - } - break; + case AF_INET6: { + sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; + sock_family = socket_family_to_scap(sa_in6->sin6_family); + } break; - case AF_UNIX: - { - sockaddr_un *sa_un = (sockaddr_un *)sa; - sock_family = socket_family_to_scap(sa_un->sun_family); - } - break; + case AF_UNIX: { + sockaddr_un *sa_un = (sockaddr_un *)sa; + sock_family = socket_family_to_scap(sa_un->sun_family); + } break; } memcpy(targetbuf, &sock_family, sizeof(uint8_t)); @@ -629,52 +611,44 @@ static inline size_t pack_sock_family(sockaddr *sa, char *targetbuf) } // Converts a single address into a socktuple with a zeroed out local part and a remote counterpart -// Providing a large enough buffer is responsibility of the caller (socktuple_buffer_size is set for this reason) -static size_t pack_sockaddr_to_remote_tuple(sockaddr *sa, char *targetbuf) -{ +// Providing a large enough buffer is responsibility of the caller (socktuple_buffer_size is set for +// this reason) +static size_t pack_sockaddr_to_remote_tuple(sockaddr *sa, char *targetbuf) { char *buf = targetbuf; size_t size = 0; - switch(sa->sa_family) - { - case AF_INET: - { - size += pack_sock_family(sa, buf); - memset(targetbuf + 1, 0, sizeof(uint32_t)); - memset(targetbuf + 5, 0, sizeof(uint16_t)); - size += sizeof(uint32_t) + sizeof(uint16_t); - buf = targetbuf + size; - size += pack_addr_port(sa, buf); - } - break; - - case AF_INET6: - { - size += pack_sock_family(sa, buf); - memset(targetbuf + 1, 0, 2 * sizeof(uint64_t)); //saddr - memset(targetbuf + 17, 0, sizeof(uint16_t)); //sport - size += 2 * sizeof(uint64_t) + sizeof(uint16_t); - buf = targetbuf + size; - size += pack_addr_port(sa, buf); - } - break; - - case AF_UNIX: - { - size += pack_sock_family(sa, buf); - memset(targetbuf + 1, 0, sizeof(uint64_t)); // TODO: understand how to fill this - memset(targetbuf + 1 + 8, 0, sizeof(uint64_t)); - size += sizeof(uint64_t) + sizeof(uint64_t); - buf = targetbuf + size; - size += pack_addr_port(sa, buf); - } - break; + switch(sa->sa_family) { + case AF_INET: { + size += pack_sock_family(sa, buf); + memset(targetbuf + 1, 0, sizeof(uint32_t)); + memset(targetbuf + 5, 0, sizeof(uint16_t)); + size += sizeof(uint32_t) + sizeof(uint16_t); + buf = targetbuf + size; + size += pack_addr_port(sa, buf); + } break; + + case AF_INET6: { + size += pack_sock_family(sa, buf); + memset(targetbuf + 1, 0, 2 * sizeof(uint64_t)); // saddr + memset(targetbuf + 17, 0, sizeof(uint16_t)); // sport + size += 2 * sizeof(uint64_t) + sizeof(uint16_t); + buf = targetbuf + size; + size += pack_addr_port(sa, buf); + } break; + + case AF_UNIX: { + size += pack_sock_family(sa, buf); + memset(targetbuf + 1, 0, sizeof(uint64_t)); // TODO: understand how to fill this + memset(targetbuf + 1 + 8, 0, sizeof(uint64_t)); + size += sizeof(uint64_t) + sizeof(uint64_t); + buf = targetbuf + size; + size += pack_addr_port(sa, buf); + } break; } return size; } -static size_t pack_sockaddr(sockaddr *sa, char *targetbuf) -{ +static size_t pack_sockaddr(sockaddr *sa, char *targetbuf) { char *buf = targetbuf; size_t size = 0; size += pack_sock_family(sa, buf); @@ -684,168 +658,164 @@ static size_t pack_sockaddr(sockaddr *sa, char *targetbuf) return size; } -static parse_result parse_connect(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_connect(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Connect gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking connect protobuf message"; return ret; } - if(gvisor_evt.address().size() == 0) - { + if(gvisor_evt.address().size() == 0) { ret.status = SCAP_FAILURE; ret.error = "No address data received"; return ret; } - if(gvisor_evt.has_exit()) - { + if(gvisor_evt.has_exit()) { char targetbuf[socktuple_buffer_size]; sockaddr *addr = (sockaddr *)gvisor_evt.address().data(); size_t size = pack_sockaddr_to_remote_tuple(addr, targetbuf); - if (size == 0) - { + if(size == 0) { ret.status = SCAP_FAILURE; ret.error = "Could not parse received address"; return ret; } - ret.status = scap_gvisor::fillers::fill_event_connect_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - scap_const_sized_buffer{targetbuf, size}, - gvisor_evt.fd()); - } - else - { + ret.status = + scap_gvisor::fillers::fill_event_connect_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + scap_const_sized_buffer{targetbuf, size}, + gvisor_evt.fd()); + } else { char targetbuf[socktuple_buffer_size]; sockaddr *addr = (sockaddr *)gvisor_evt.address().data(); size_t size = pack_sockaddr(addr, targetbuf); - if (size == 0) - { + if(size == 0) { ret.status = SCAP_FAILURE; ret.error = "Could not parse received address"; return ret; } ret.status = scap_gvisor::fillers::fill_event_connect_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - scap_const_sized_buffer{targetbuf, size}); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + scap_const_sized_buffer{targetbuf, size}); } - if (ret.status != SCAP_SUCCESS) { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_socket(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_socket(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Socket gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking socket protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_socket_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); - } - else - { + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_socket_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); + } else { ret.status = scap_gvisor::fillers::fill_event_socket_e( - scap_buf, &ret.size, scap_err, - socket_family_to_scap(gvisor_evt.domain()), - gvisor_evt.type(), - gvisor_evt.protocol()); + scap_buf, + &ret.size, + scap_err, + socket_family_to_scap(gvisor_evt.domain()), + gvisor_evt.type(), + gvisor_evt.protocol()); } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_generic_syscall(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_generic_syscall(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Syscall gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking generic syscall protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_mmap: - ret.status = scap_gvisor::fillers::fill_event_mmap_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_mmap_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_munmap: - ret.status = scap_gvisor::fillers::fill_event_munmap_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_munmap_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_mmap: - ret.status = scap_gvisor::fillers::fill_event_mmap_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.arg1(), - gvisor_evt.arg2(), - gvisor_evt.arg3(), - gvisor_evt.arg4(), - gvisor_evt.arg5(), - gvisor_evt.arg6()); + ret.status = scap_gvisor::fillers::fill_event_mmap_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.arg1(), + gvisor_evt.arg2(), + gvisor_evt.arg3(), + gvisor_evt.arg4(), + gvisor_evt.arg5(), + gvisor_evt.arg6()); break; case __NR_munmap: - ret.status = scap_gvisor::fillers::fill_event_munmap_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.arg1(), - gvisor_evt.arg2()); + ret.status = scap_gvisor::fillers::fill_event_munmap_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.arg1(), + gvisor_evt.arg2()); break; default: @@ -859,30 +829,28 @@ static parse_result parse_generic_syscall(uint32_t id, scap_const_sized_buffer p return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_accept(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_accept(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Accept gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking accept protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { + if(gvisor_evt.has_exit()) { char targetbuf[socktuple_buffer_size]; - if(gvisor_evt.address().size() == 0) - { + if(gvisor_evt.address().size() == 0) { ret.status = SCAP_FAILURE; ret.error = "No address data received"; return ret; @@ -890,47 +858,46 @@ static parse_result parse_accept(uint32_t id, scap_const_sized_buffer proto, sca sockaddr *addr = (sockaddr *)gvisor_evt.address().data(); size_t size = pack_sockaddr_to_remote_tuple(addr, targetbuf); - if (size == 0) - { + if(size == 0) { ret.status = SCAP_FAILURE; ret.error = "Could not parse received address"; return ret; } - switch(gvisor_evt.sysno()) - { + switch(gvisor_evt.sysno()) { case __NR_accept4: ret.status = scap_gvisor::fillers::fill_event_accept4_6_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - scap_const_sized_buffer{targetbuf, size}); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + scap_const_sized_buffer{targetbuf, size}); break; case __NR_accept: ret.status = scap_gvisor::fillers::fill_event_accept_5_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - scap_const_sized_buffer{targetbuf, size}); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + scap_const_sized_buffer{targetbuf, size}); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_accept4: - ret.status = scap_gvisor::fillers::fill_event_accept4_6_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.flags()); + ret.status = scap_gvisor::fillers::fill_event_accept4_6_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.flags()); break; case __NR_accept: - ret.status = scap_gvisor::fillers::fill_event_accept_5_e( - scap_buf, &ret.size, scap_err); + ret.status = scap_gvisor::fillers::fill_event_accept_5_e(scap_buf, &ret.size, scap_err); break; default: @@ -944,37 +911,36 @@ static parse_result parse_accept(uint32_t id, scap_const_sized_buffer proto, sca return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_fcntl(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_fcntl(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Fcntl gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking fcntl protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_fcntl_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_fcntl_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - fcntl_cmd_to_scap(gvisor_evt.cmd())); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_fcntl_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); + } else { + ret.status = scap_gvisor::fillers::fill_event_fcntl_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + fcntl_cmd_to_scap(gvisor_evt.cmd())); } if(ret.status != SCAP_SUCCESS) { @@ -982,31 +948,29 @@ static parse_result parse_fcntl(uint32_t id, scap_const_sized_buffer proto, scap return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_bind(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_bind(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Bind gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking bind protobuf message"; return ret; } - char targetbuf[socktuple_buffer_size]; // XXX maybe a smaller version for addr + char targetbuf[socktuple_buffer_size]; // XXX maybe a smaller version for addr - if(gvisor_evt.has_exit()) - { - if(gvisor_evt.address().size() == 0) - { + if(gvisor_evt.has_exit()) { + if(gvisor_evt.address().size() == 0) { ret.status = SCAP_FAILURE; ret.error = "No address data received"; return ret; @@ -1014,23 +978,23 @@ static parse_result parse_bind(uint32_t id, scap_const_sized_buffer proto, scap_ sockaddr *addr = (sockaddr *)gvisor_evt.address().data(); size_t size = pack_sockaddr(addr, targetbuf); - if (size == 0) - { + if(size == 0) { ret.status = SCAP_FAILURE; ret.error = "Could not parse received address"; return ret; } - ret.status = scap_gvisor::fillers::fill_event_bind_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - scap_const_sized_buffer{targetbuf, size}); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_bind_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd()); + ret.status = + scap_gvisor::fillers::fill_event_bind_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + scap_const_sized_buffer{targetbuf, size}); + } else { + ret.status = scap_gvisor::fillers::fill_event_bind_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd()); } if(ret.status != SCAP_SUCCESS) { @@ -1038,37 +1002,34 @@ static parse_result parse_bind(uint32_t id, scap_const_sized_buffer proto, scap_ return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_pipe(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_pipe(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Pipe gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking pipe protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_pipe_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.reader(), - gvisor_evt.writer()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_pipe_e( - scap_buf, &ret.size, scap_err); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_pipe_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.reader(), + gvisor_evt.writer()); + } else { + ret.status = scap_gvisor::fillers::fill_event_pipe_e(scap_buf, &ret.size, scap_err); } if(ret.status != SCAP_SUCCESS) { @@ -1076,91 +1037,94 @@ static parse_result parse_pipe(uint32_t id, scap_const_sized_buffer proto, scap_ return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_open(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_open(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Open gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking open protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_open: ret.status = scap_gvisor::fillers::fill_event_open_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.pathname().c_str(), - open_flags_to_scap(gvisor_evt.flags()), - open_modes_to_scap(gvisor_evt.flags(), - gvisor_evt.mode())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.pathname().c_str(), + open_flags_to_scap(gvisor_evt.flags()), + open_modes_to_scap(gvisor_evt.flags(), gvisor_evt.mode())); break; case __NR_openat: ret.status = scap_gvisor::fillers::fill_event_openat_2_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.fd(), - gvisor_evt.pathname().c_str(), - open_flags_to_scap(gvisor_evt.flags()), - open_modes_to_scap(gvisor_evt.mode(), - gvisor_evt.flags())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.fd(), + gvisor_evt.pathname().c_str(), + open_flags_to_scap(gvisor_evt.flags()), + open_modes_to_scap(gvisor_evt.mode(), gvisor_evt.flags())); break; case __NR_creat: ret.status = scap_gvisor::fillers::fill_event_creat_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.pathname().c_str(), - open_modes_to_scap(O_CREAT, gvisor_evt.mode())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.pathname().c_str(), + open_modes_to_scap(O_CREAT, gvisor_evt.mode())); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_open: ret.status = scap_gvisor::fillers::fill_event_open_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.pathname().c_str(), - open_flags_to_scap(gvisor_evt.flags()), - open_modes_to_scap(gvisor_evt.mode(), - gvisor_evt.flags())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.pathname().c_str(), + open_flags_to_scap(gvisor_evt.flags()), + open_modes_to_scap(gvisor_evt.mode(), gvisor_evt.flags())); break; case __NR_openat: ret.status = scap_gvisor::fillers::fill_event_openat_2_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.pathname().c_str(), - open_flags_to_scap(gvisor_evt.flags()), - open_modes_to_scap(gvisor_evt.flags(), - gvisor_evt.mode())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.pathname().c_str(), + open_flags_to_scap(gvisor_evt.flags()), + open_modes_to_scap(gvisor_evt.flags(), gvisor_evt.mode())); break; case __NR_creat: ret.status = scap_gvisor::fillers::fill_event_creat_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.pathname().c_str(), - open_modes_to_scap(O_CREAT, gvisor_evt.mode())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.pathname().c_str(), + open_modes_to_scap(O_CREAT, gvisor_evt.mode())); break; default: @@ -1174,60 +1138,57 @@ static parse_result parse_open(uint32_t id, scap_const_sized_buffer proto, scap_ return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_chdir(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_chdir(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Chdir gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking chdir protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_chdir: - ret.status = scap_gvisor::fillers::fill_event_chdir_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.pathname().c_str()); + ret.status = scap_gvisor::fillers::fill_event_chdir_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.pathname().c_str()); break; case __NR_fchdir: - ret.status = scap_gvisor::fillers::fill_event_fchdir_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_fchdir_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_chdir: - ret.status = scap_gvisor::fillers::fill_event_chdir_e( - scap_buf, &ret.size, scap_err); + ret.status = scap_gvisor::fillers::fill_event_chdir_e(scap_buf, &ret.size, scap_err); break; case __NR_fchdir: - ret.status = scap_gvisor::fillers::fill_event_fchdir_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd()); + ret.status = scap_gvisor::fillers::fill_event_fchdir_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd()); break; default: @@ -1236,70 +1197,68 @@ static parse_result parse_chdir(uint32_t id, scap_const_sized_buffer proto, scap } } - if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_setresid(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_setresid(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Setresid gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking setresid protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_setresuid: - ret.status = scap_gvisor::fillers::fill_event_setresuid_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_setresuid_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_setresgid: - ret.status = scap_gvisor::fillers::fill_event_setresgid_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_setresgid_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_setresuid: - ret.status = scap_gvisor::fillers::fill_event_setresuid_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.rid(), - gvisor_evt.eid(), - gvisor_evt.sid()); + ret.status = scap_gvisor::fillers::fill_event_setresuid_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.rid(), + gvisor_evt.eid(), + gvisor_evt.sid()); break; case __NR_setresgid: - ret.status = scap_gvisor::fillers::fill_event_setresgid_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.rid(), - gvisor_evt.eid(), - gvisor_evt.sid()); + ret.status = scap_gvisor::fillers::fill_event_setresgid_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.rid(), + gvisor_evt.eid(), + gvisor_evt.sid()); break; default: @@ -1308,77 +1267,75 @@ static parse_result parse_setresid(uint32_t id, scap_const_sized_buffer proto, s } } - if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_setid(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_setid(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Setid gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking setid protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_setuid: - ret.status = scap_gvisor::fillers::fill_event_setuid_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_setuid_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_setgid: - ret.status = scap_gvisor::fillers::fill_event_setgid_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_setgid_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_setsid: - ret.status = scap_gvisor::fillers::fill_event_setsid_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_setsid_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_setuid: - ret.status = scap_gvisor::fillers::fill_event_setuid_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.id()); + ret.status = scap_gvisor::fillers::fill_event_setuid_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.id()); break; case __NR_setgid: - ret.status = scap_gvisor::fillers::fill_event_setgid_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.id()); + ret.status = scap_gvisor::fillers::fill_event_setgid_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.id()); break; case __NR_setsid: - ret.status = scap_gvisor::fillers::fill_event_setsid_e( - scap_buf, &ret.size, scap_err); + ret.status = scap_gvisor::fillers::fill_event_setsid_e(scap_buf, &ret.size, scap_err); break; default: @@ -1387,42 +1344,38 @@ static parse_result parse_setid(uint32_t id, scap_const_sized_buffer proto, scap } } - if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_chroot(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_chroot(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Chroot gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking chroot protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_chroot_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.pathname().c_str()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_chroot_e( - scap_buf, &ret.size, scap_err); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_chroot_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.pathname().c_str()); + } else { + ret.status = scap_gvisor::fillers::fill_event_chroot_e(scap_buf, &ret.size, scap_err); } if(ret.status != SCAP_SUCCESS) { @@ -1430,78 +1383,80 @@ static parse_result parse_chroot(uint32_t id, scap_const_sized_buffer proto, sca return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_dup(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_dup(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Dup gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking dup protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_dup: - ret.status = scap_gvisor::fillers::fill_event_dup_1_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.old_fd()); + ret.status = scap_gvisor::fillers::fill_event_dup_1_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.old_fd()); break; case __NR_dup2: - ret.status = scap_gvisor::fillers::fill_event_dup2_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.old_fd(), - gvisor_evt.new_fd()); + ret.status = scap_gvisor::fillers::fill_event_dup2_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.old_fd(), + gvisor_evt.new_fd()); break; case __NR_dup3: ret.status = scap_gvisor::fillers::fill_event_dup3_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.old_fd(), - gvisor_evt.new_fd(), - dup3_flags_to_scap((int) gvisor_evt.flags())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.old_fd(), + gvisor_evt.new_fd(), + dup3_flags_to_scap((int)gvisor_evt.flags())); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_dup: - ret.status = scap_gvisor::fillers::fill_event_dup_1_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.old_fd()); + ret.status = scap_gvisor::fillers::fill_event_dup_1_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.old_fd()); break; case __NR_dup2: - ret.status = scap_gvisor::fillers::fill_event_dup2_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.old_fd()); + ret.status = scap_gvisor::fillers::fill_event_dup2_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.old_fd()); break; case __NR_dup3: - ret.status = scap_gvisor::fillers::fill_event_dup3_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.old_fd()); + ret.status = scap_gvisor::fillers::fill_event_dup3_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.old_fd()); break; default: @@ -1510,8 +1465,7 @@ static parse_result parse_dup(uint32_t id, scap_const_sized_buffer proto, scap_s } } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1523,14 +1477,14 @@ static parse_result parse_dup(uint32_t id, scap_const_sized_buffer proto, scap_s return ret; } -static parse_result parse_sentry_task_exit(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_sentry_task_exit(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::sentry::TaskExit gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking task exit protobuf message"; return ret; @@ -1538,14 +1492,15 @@ static parse_result parse_sentry_task_exit(uint32_t id, scap_const_sized_buffer int32_t exit_status = gvisor_evt.exit_status(); ret.status = scap_gvisor::fillers::fill_event_procexit_1_e( - scap_buf, &ret.size, scap_err, - exit_status, - __WEXITSTATUS(exit_status), - ((__WIFSIGNALED(exit_status)) ? __WTERMSIG(exit_status): 0), - ((__WCOREDUMP(exit_status)) ? 1 : 0)); - - if(ret.status != SCAP_SUCCESS) - { + scap_buf, + &ret.size, + scap_err, + exit_status, + __WEXITSTATUS(exit_status), + ((__WIFSIGNALED(exit_status)) ? __WTERMSIG(exit_status) : 0), + ((__WCOREDUMP(exit_status)) ? 1 : 0)); + + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1557,38 +1512,37 @@ static parse_result parse_sentry_task_exit(uint32_t id, scap_const_sized_buffer return ret; } -static parse_result parse_prlimit64(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_prlimit64(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Prlimit gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking prlimit64 protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_prlimit_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.new_limit().cur(), - gvisor_evt.new_limit().max(), - gvisor_evt.old_limit().cur(), - gvisor_evt.old_limit().max()); - } - else - { + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_prlimit_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.new_limit().cur(), + gvisor_evt.new_limit().max(), + gvisor_evt.old_limit().cur(), + gvisor_evt.old_limit().max()); + } else { ret.status = scap_gvisor::fillers::fill_event_prlimit_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.pid(), - rlimit_resource_to_scap(gvisor_evt.resource())); + scap_buf, + &ret.size, + scap_err, + gvisor_evt.pid(), + rlimit_resource_to_scap(gvisor_evt.resource())); } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1600,35 +1554,33 @@ static parse_result parse_prlimit64(uint32_t id, scap_const_sized_buffer proto, return ret; } -static parse_result parse_signalfd(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_signalfd(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Signalfd gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking signalfd protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_signalfd_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_signalfd_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.sigset(), - gvisor_evt.flags()); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_signalfd_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); + } else { + ret.status = scap_gvisor::fillers::fill_event_signalfd_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.sigset(), + gvisor_evt.flags()); } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1640,34 +1592,33 @@ static parse_result parse_signalfd(uint32_t id, scap_const_sized_buffer proto, s return ret; } -static parse_result parse_eventfd(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_eventfd(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Eventfd gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking eventfd protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_eventfd_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); - } - else - { + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_eventfd_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); + } else { ret.status = scap_gvisor::fillers::fill_event_eventfd_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.val(), - 0); // hardcoded flags=0, matches driver behavior + scap_buf, + &ret.size, + scap_err, + gvisor_evt.val(), + 0); // hardcoded flags=0, matches driver behavior } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1679,88 +1630,84 @@ static parse_result parse_eventfd(uint32_t id, scap_const_sized_buffer proto, sc return ret; } -static parse_result parse_close(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_close(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Close gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking close protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_close_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_close_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd()); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_close_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); + } else { + ret.status = scap_gvisor::fillers::fill_event_close_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd()); } - if (ret.status != SCAP_SUCCESS) { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_clone(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_clone(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Clone gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking clone protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - auto& context_data = gvisor_evt.context_data(); + if(gvisor_evt.has_exit()) { + auto &context_data = gvisor_evt.context_data(); std::string cgroups = "gvisor_container_id=/"; cgroups += context_data.container_id(); ret.status = scap_gvisor::fillers::fill_event_clone_20_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - context_data.process_name().c_str(), // exe - scap_const_sized_buffer{"", 0}, // args -- INV/not available - generate_tid_field(context_data.thread_id(), id), // tid - generate_tid_field(context_data.thread_group_id(), id), // pid - 0, // ptid -- INV/not available - context_data.cwd().c_str(), - context_data.process_name().c_str(), // comm - scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, - clone_flags_to_scap((int) gvisor_evt.flags()), - context_data.credentials().effective_uid(), // uid - context_data.credentials().effective_gid(), // gid - context_data.thread_id(), // vtid - context_data.thread_group_id(), // vpid - context_data.thread_start_time_ns()); // pidns_init_start_ts - } - else - { - ret.status = scap_gvisor::fillers::fill_event_clone_20_e( - scap_buf, &ret.size, scap_err); - } - - if(ret.status != SCAP_SUCCESS) - { + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + context_data.process_name().c_str(), // exe + scap_const_sized_buffer{"", 0}, // args -- INV/not available + generate_tid_field(context_data.thread_id(), id), // tid + generate_tid_field(context_data.thread_group_id(), id), // pid + 0, // ptid -- INV/not available + context_data.cwd().c_str(), + context_data.process_name().c_str(), // comm + scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, + clone_flags_to_scap((int)gvisor_evt.flags()), + context_data.credentials().effective_uid(), // uid + context_data.credentials().effective_gid(), // gid + context_data.thread_id(), // vtid + context_data.thread_group_id(), // vpid + context_data.thread_start_time_ns()); // pidns_init_start_ts + } else { + ret.status = scap_gvisor::fillers::fill_event_clone_20_e(scap_buf, &ret.size, scap_err); + } + + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1772,34 +1719,32 @@ static parse_result parse_clone(uint32_t id, scap_const_sized_buffer proto, scap return ret; } -static parse_result parse_timerfd_create(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_timerfd_create(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::TimerfdCreate gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking timerfd_create protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_timerfd_create_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_timerfd_create_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.clock_id(), - gvisor_evt.flags()); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_timerfd_create_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); + } else { + ret.status = scap_gvisor::fillers::fill_event_timerfd_create_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.clock_id(), + gvisor_evt.flags()); } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1811,80 +1756,74 @@ static parse_result parse_timerfd_create(uint32_t id, scap_const_sized_buffer pr return ret; } -static parse_result parse_fork(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_fork(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Fork gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking fork protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - auto& context_data = gvisor_evt.context_data(); + if(gvisor_evt.has_exit()) { + auto &context_data = gvisor_evt.context_data(); std::string cgroups = "gvisor_container_id=/"; cgroups += context_data.container_id(); - switch(gvisor_evt.sysno()) - { + switch(gvisor_evt.sysno()) { case __NR_fork: ret.status = scap_gvisor::fillers::fill_event_fork_20_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - context_data.process_name().c_str(), // exe - generate_tid_field(context_data.thread_id(), id), // tid - generate_tid_field(context_data.thread_group_id(), id), // pid - context_data.cwd().c_str(), - context_data.process_name().c_str(), // comm - scap_const_sized_buffer{cgroups.c_str(), - cgroups.length() + 1}, - context_data.credentials().effective_uid(), // uid - context_data.credentials().effective_gid(), // gid - context_data.thread_id(), // vtid - context_data.thread_group_id(), // vpid - context_data.thread_start_time_ns()); // pidns_init_start_ts + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + context_data.process_name().c_str(), // exe + generate_tid_field(context_data.thread_id(), id), // tid + generate_tid_field(context_data.thread_group_id(), id), // pid + context_data.cwd().c_str(), + context_data.process_name().c_str(), // comm + scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, + context_data.credentials().effective_uid(), // uid + context_data.credentials().effective_gid(), // gid + context_data.thread_id(), // vtid + context_data.thread_group_id(), // vpid + context_data.thread_start_time_ns()); // pidns_init_start_ts case __NR_vfork: ret.status = scap_gvisor::fillers::fill_event_vfork_20_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - context_data.process_name().c_str(), // exe - generate_tid_field(context_data.thread_id(), id), // tid - generate_tid_field(context_data.thread_group_id(), id), // pid - context_data.cwd().c_str(), - context_data.process_name().c_str(), // comm - scap_const_sized_buffer{cgroups.c_str(), - cgroups.length() + 1}, - context_data.credentials().effective_uid(), // uid - context_data.credentials().effective_gid(), // gid - context_data.thread_id(), // vtid - context_data.thread_group_id(), // vpid - context_data.thread_start_time_ns()); // pidns_init_start_ts + scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + context_data.process_name().c_str(), // exe + generate_tid_field(context_data.thread_id(), id), // tid + generate_tid_field(context_data.thread_group_id(), id), // pid + context_data.cwd().c_str(), + context_data.process_name().c_str(), // comm + scap_const_sized_buffer{cgroups.c_str(), cgroups.length() + 1}, + context_data.credentials().effective_uid(), // uid + context_data.credentials().effective_gid(), // gid + context_data.thread_id(), // vtid + context_data.thread_group_id(), // vpid + context_data.thread_start_time_ns()); // pidns_init_start_ts break; - default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_fork: - ret.status = scap_gvisor::fillers::fill_event_fork_20_e( - scap_buf, &ret.size, scap_err); + ret.status = scap_gvisor::fillers::fill_event_fork_20_e(scap_buf, &ret.size, scap_err); break; case __NR_vfork: - ret.status = scap_gvisor::fillers::fill_event_vfork_20_e( - scap_buf, &ret.size, scap_err); + ret.status = scap_gvisor::fillers::fill_event_vfork_20_e(scap_buf, &ret.size, scap_err); break; default: @@ -1893,8 +1832,7 @@ static parse_result parse_fork(uint32_t id, scap_const_sized_buffer proto, scap_ } } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1906,33 +1844,31 @@ static parse_result parse_fork(uint32_t id, scap_const_sized_buffer proto, scap_ return ret; } -static parse_result parse_inotify_init(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_inotify_init(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Eventfd gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking inotify_init protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_inotify_init_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_inotify_init_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.flags()); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_inotify_init_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); + } else { + ret.status = scap_gvisor::fillers::fill_event_inotify_init_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.flags()); } - if(ret.status != SCAP_SUCCESS) - { + if(ret.status != SCAP_SUCCESS) { ret.error = scap_err; return ret; } @@ -1944,33 +1880,32 @@ static parse_result parse_inotify_init(uint32_t id, scap_const_sized_buffer prot return ret; } -static parse_result parse_socketpair(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_socketpair(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::SocketPair gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking socketpair protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - ret.status = scap_gvisor::fillers::fill_event_socketpair_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result(), - gvisor_evt.socket1(), - gvisor_evt.socket2()); - } - else - { - ret.status = scap_gvisor::fillers::fill_event_socketpair_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.domain(), - gvisor_evt.type(), - gvisor_evt.protocol()); + if(gvisor_evt.has_exit()) { + ret.status = scap_gvisor::fillers::fill_event_socketpair_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result(), + gvisor_evt.socket1(), + gvisor_evt.socket2()); + } else { + ret.status = scap_gvisor::fillers::fill_event_socketpair_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.domain(), + gvisor_evt.type(), + gvisor_evt.protocol()); } if(ret.status != SCAP_SUCCESS) { @@ -1978,90 +1913,93 @@ static parse_result parse_socketpair(uint32_t id, scap_const_sized_buffer proto, return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -static parse_result parse_write(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf) -{ +static parse_result parse_write(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf) { parse_result ret; char scap_err[SCAP_LASTERR_SIZE]; gvisor::syscall::Write gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { ret.status = SCAP_FAILURE; ret.error = "Error unpacking write protobuf message"; return ret; } - if(gvisor_evt.has_exit()) - { - switch(gvisor_evt.sysno()) - { + if(gvisor_evt.has_exit()) { + switch(gvisor_evt.sysno()) { case __NR_write: - ret.status = scap_gvisor::fillers::fill_event_write_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_write_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_pwrite64: - ret.status = scap_gvisor::fillers::fill_event_pwrite_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_pwrite_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_writev: - ret.status = scap_gvisor::fillers::fill_event_writev_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_writev_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; case __NR_pwritev: - ret.status = scap_gvisor::fillers::fill_event_pwritev_x( - scap_buf, &ret.size, scap_err, - gvisor_evt.exit().result()); + ret.status = scap_gvisor::fillers::fill_event_pwritev_x(scap_buf, + &ret.size, + scap_err, + gvisor_evt.exit().result()); break; default: ret.status = process_unhandled_syscall(gvisor_evt.sysno(), scap_err); break; } - } - else - { - switch(gvisor_evt.sysno()) - { + } else { + switch(gvisor_evt.sysno()) { case __NR_write: - ret.status = scap_gvisor::fillers::fill_event_write_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.count()); + ret.status = scap_gvisor::fillers::fill_event_write_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.count()); break; case __NR_pwrite64: - ret.status = scap_gvisor::fillers::fill_event_pwrite_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.count(), - gvisor_evt.offset()); + ret.status = scap_gvisor::fillers::fill_event_pwrite_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.count(), + gvisor_evt.offset()); break; case __NR_writev: - ret.status = scap_gvisor::fillers::fill_event_writev_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.count()); + ret.status = scap_gvisor::fillers::fill_event_writev_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.count()); break; case __NR_pwritev: - ret.status = scap_gvisor::fillers::fill_event_pwritev_e( - scap_buf, &ret.size, scap_err, - gvisor_evt.fd(), - gvisor_evt.count(), - gvisor_evt.offset()); + ret.status = scap_gvisor::fillers::fill_event_pwritev_e(scap_buf, + &ret.size, + scap_err, + gvisor_evt.fd(), + gvisor_evt.count(), + gvisor_evt.offset()); break; default: @@ -2075,29 +2013,29 @@ static parse_result parse_write(uint32_t id, scap_const_sized_buffer proto, scap return ret; } - scap_evt *evt = static_cast(scap_buf.buf); + scap_evt *evt = static_cast(scap_buf.buf); fill_context_data(evt, gvisor_evt, id); ret.scap_events.push_back(evt); return ret; } -parse_result parse_gvisor_proto(uint32_t id, scap_const_sized_buffer gvisor_buf, scap_sized_buffer scap_buf) -{ +parse_result parse_gvisor_proto(uint32_t id, + scap_const_sized_buffer gvisor_buf, + scap_sized_buffer scap_buf) { parse_result ret; - if(id == 0) - { + if(id == 0) { ret.error = "Invalid sandbox ID 0"; ret.status = SCAP_FAILURE; return ret; } - const char *buf = static_cast(gvisor_buf.buf); + const char *buf = static_cast(gvisor_buf.buf); const header *hdr = reinterpret_cast(buf); - if(hdr->header_size > gvisor_buf.size) - { - ret.error = std::string("Header size (") + std::to_string(hdr->header_size) + ") is larger than message " + std::to_string(gvisor_buf.size); + if(hdr->header_size > gvisor_buf.size) { + ret.error = std::string("Header size (") + std::to_string(hdr->header_size) + + ") is larger than message " + std::to_string(gvisor_buf.size); ret.status = SCAP_FAILURE; return ret; } @@ -2108,22 +2046,23 @@ parse_result parse_gvisor_proto(uint32_t id, scap_const_sized_buffer gvisor_buf, size_t proto_size = gvisor_buf.size - hdr->header_size; size_t message_type = hdr->message_type; - if (message_type == 0) { + if(message_type == 0) { ret.error = std::string("Invalid message type 0"); ret.status = SCAP_FAILURE; return ret; } - if (message_type >= dispatchers.size()) { - ret.error = std::string("No parser registered for message type: ") + std::to_string(message_type); + if(message_type >= dispatchers.size()) { + ret.error = std::string("No parser registered for message type: ") + + std::to_string(message_type); ret.status = SCAP_NOT_SUPPORTED; return ret; } event_parser parser = dispatchers[message_type]; - if(parser.parse_msg == nullptr) - { - ret.error = std::string("No parser registered for message type: ") + std::to_string(message_type); + if(parser.parse_msg == nullptr) { + ret.error = std::string("No parser registered for message type: ") + + std::to_string(message_type); ret.status = SCAP_NOT_SUPPORTED; return ret; } @@ -2131,12 +2070,10 @@ parse_result parse_gvisor_proto(uint32_t id, scap_const_sized_buffer gvisor_buf, return parser.parse_msg(id, scap_const_sized_buffer{proto, proto_size}, scap_buf); } -std::string parse_container_id(scap_const_sized_buffer gvisor_buf) -{ - const char *buf = static_cast(gvisor_buf.buf); +std::string parse_container_id(scap_const_sized_buffer gvisor_buf) { + const char *buf = static_cast(gvisor_buf.buf); const header *hdr = reinterpret_cast(buf); - if(hdr->header_size > gvisor_buf.size) - { + if(hdr->header_size > gvisor_buf.size) { return ""; } @@ -2144,25 +2081,23 @@ std::string parse_container_id(scap_const_sized_buffer gvisor_buf) size_t proto_size = gvisor_buf.size - hdr->header_size; size_t message_type = hdr->message_type; - if (message_type == 0) { + if(message_type == 0) { return ""; } - if (message_type >= dispatchers.size()) { + if(message_type >= dispatchers.size()) { return ""; } event_parser parser = dispatchers[message_type]; - if(parser.parse_container_id == nullptr) - { + if(parser.parse_container_id == nullptr) { return ""; } return parser.parse_container_id(scap_const_sized_buffer{proto, proto_size}); } -procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) -{ +procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) { procfs_result res; memset(&res.tinfo, 0, sizeof(res.tinfo)); Json::Value root; @@ -2171,8 +2106,7 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) const std::unique_ptr reader(builder.newCharReader()); bool json_parse = reader->parse(input.c_str(), input.c_str() + input.size(), &root, &err); - if(!json_parse) - { + if(!json_parse) { res.status = SCAP_FAILURE; res.error = "Malformed json string: cannot parse procfs entry: " + err; return res; @@ -2191,35 +2125,30 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) // Fill threadinfo // - if(!root.isMember("status")) - { + if(!root.isMember("status")) { return res; } Json::Value &status = root["status"]; - if(!root.isMember("stat")) - { + if(!root.isMember("stat")) { return res; } Json::Value &stat = root["stat"]; // tid - if(!status.isMember("pid") || !status["pid"].isUInt64()) - { + if(!status.isMember("pid") || !status["pid"].isUInt64()) { return res; } tinfo.tid = generate_tid_field(status["pid"].asUInt64(), sandbox_id); // pid - if(!stat.isMember("pgid") || !stat["pgid"].isUInt64()) - { + if(!stat.isMember("pgid") || !stat["pgid"].isUInt64()) { return res; } tinfo.pid = generate_tid_field(stat["pgid"].asUInt64(), sandbox_id); // sid - if(!stat.isMember("sid") || !stat["sid"].isUInt64()) - { + if(!stat.isMember("sid") || !stat["sid"].isUInt64()) { return res; } tinfo.sid = stat["sid"].asUInt64(); @@ -2228,34 +2157,29 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) tinfo.vpgid = stat["pgid"].asUInt64(); // comm - if(!status.isMember("comm") || !status["comm"].isString()) - { + if(!status.isMember("comm") || !status["comm"].isString()) { return res; } strlcpy(tinfo.comm, status["comm"].asCString(), SCAP_MAX_PATH_SIZE + 1); // exe - if(!root.isMember("args") || !root["args"].isArray() || !root["args"][0].isString()) - { + if(!root.isMember("args") || !root["args"].isArray() || !root["args"][0].isString()) { return res; } strlcpy(tinfo.exe, root["args"][0].asCString(), SCAP_MAX_PATH_SIZE + 1); // exepath - if(!root.isMember("exe") || !root["exe"].isString()) - { + if(!root.isMember("exe") || !root["exe"].isString()) { return res; } strlcpy(tinfo.exepath, root["exe"].asCString(), SCAP_MAX_PATH_SIZE + 1); // args - if(!root.isMember("args") || !root["args"].isArray()) - { + if(!root.isMember("args") || !root["args"].isArray()) { return res; } std::string args; - for(Json::Value::ArrayIndex i = 0; i < root["args"].size(); i++) - { + for(Json::Value::ArrayIndex i = 0; i < root["args"].size(); i++) { args += root["args"][i].asString(); args.push_back('\0'); } @@ -2265,13 +2189,11 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) tinfo.args[SCAP_MAX_ARGS_SIZE] = '\0'; // env - if(!root.isMember("env") || !root["env"].isArray()) - { + if(!root.isMember("env") || !root["env"].isArray()) { return res; } std::string env; - for(Json::Value::ArrayIndex i = 0; i < root["env"].size(); i++) - { + for(Json::Value::ArrayIndex i = 0; i < root["env"].size(); i++) { env += root["env"][i].asString(); env.push_back('\0'); } @@ -2281,24 +2203,21 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) tinfo.env[SCAP_MAX_ENV_SIZE] = '\0'; // cwd - if(!root.isMember("cwd") || !root["cwd"].isString()) - { + if(!root.isMember("cwd") || !root["cwd"].isString()) { return res; } strlcpy(tinfo.cwd, root["cwd"].asCString(), SCAP_MAX_PATH_SIZE + 1); // uid if(!status.isMember("uid") || !status["uid"].isMember("effective") || - !status["uid"]["effective"].isUInt64()) - { + !status["uid"]["effective"].isUInt64()) { return res; } tinfo.uid = status["uid"]["effective"].asUInt64(); // gid if(!status.isMember("gid") || !status["gid"].isMember("effective") || - !status["gid"]["effective"].isUInt64()) - { + !status["gid"]["effective"].isUInt64()) { return res; } tinfo.gid = status["gid"]["effective"].asUInt64(); @@ -2310,15 +2229,13 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) tinfo.vpid = status["pgid"].asUInt64(); // root - if(!root.isMember("root") || !root["root"].isString()) - { + if(!root.isMember("root") || !root["root"].isString()) { return res; } strlcpy(tinfo.root, root["root"].asCString(), SCAP_MAX_PATH_SIZE + 1); // clone_ts - if(!root.isMember("clone_ts") || !root["clone_ts"].isUInt64()) - { + if(!root.isMember("clone_ts") || !root["clone_ts"].isUInt64()) { return res; } tinfo.clone_ts = root["clone_ts"].asUInt64(); @@ -2329,40 +2246,32 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) res.error = "Error parsing fdlist"; std::vector &fds = res.fdinfos; - if(!root.isMember("fdlist") || !root["fdlist"].isArray()) - { + if(!root.isMember("fdlist") || !root["fdlist"].isArray()) { return res; } - for(Json::Value::ArrayIndex i = 0; i != root["fdlist"].size(); i++) - { + for(Json::Value::ArrayIndex i = 0; i != root["fdlist"].size(); i++) { Json::Value &entry = root["fdlist"][i]; scap_fdinfo fdinfo; - if(!entry.isMember("number") || !entry["number"].isUInt64()) - { + if(!entry.isMember("number") || !entry["number"].isUInt64()) { return res; } fdinfo.fd = entry["number"].asUInt64(); - if(!entry.isMember("mode") || !entry["mode"].isUInt64()) - { + if(!entry.isMember("mode") || !entry["mode"].isUInt64()) { return res; } - if(!entry.isMember("path") || !entry["path"].isString()) - { + if(!entry.isMember("path") || !entry["path"].isString()) { return res; } uint64_t mode = entry["mode"].asUInt64(); - if(S_ISREG(mode)) - { + if(S_ISREG(mode)) { fdinfo.type = SCAP_FD_FILE_V2; strlcpy(fdinfo.info.regularinfo.fname, entry["path"].asCString(), SCAP_MAX_PATH_SIZE); - } - else - { + } else { continue; } @@ -2374,8 +2283,7 @@ procfs_result parse_procfs_json(const std::string &input, uint32_t sandbox_id) return res; } -config_result parse_config(std::string config) -{ +config_result parse_config(std::string config) { config_result res; res.socket_path = ""; res.error = ""; @@ -2387,27 +2295,23 @@ config_result parse_config(std::string config) const std::unique_ptr reader(builder.newCharReader()); bool json_parse = reader->parse(config.c_str(), config.c_str() + config.size(), &root, &err); - if(!json_parse) - { + if(!json_parse) { res.error = "Could not parse configuration file contents: " + err; return res; } - if(!root.isMember("trace_session")) - { + if(!root.isMember("trace_session")) { res.error = "Could not find trace_session entry in configuration"; return res; } Json::Value &trace_session = root["trace_session"]; - if(!trace_session.isMember("sinks") || !trace_session["sinks"].isArray()) - { + if(!trace_session.isMember("sinks") || !trace_session["sinks"].isArray()) { res.error = "Could not find trace_session -> sinks array in configuration"; return res; } - if(trace_session["sinks"].size() == 0) - { + if(trace_session["sinks"].size() == 0) { res.error = "trace_session -> sinks array is empty"; return res; } @@ -2416,15 +2320,13 @@ config_result parse_config(std::string config) // we're taking the first for now but this can be tweaked if necessary. Json::Value &sink = trace_session["sinks"][0]; - if(!sink.isMember("config")) - { + if(!sink.isMember("config")) { res.error = "Could not find config in sink item"; return res; } Json::Value &sink_config = sink["config"]; - if(!sink_config.isMember("endpoint") || !sink_config["endpoint"].isString()) - { + if(!sink_config.isMember("endpoint") || !sink_config["endpoint"].isString()) { res.error = "Could not find endpoint in sink configuration"; return res; } @@ -2434,5 +2336,5 @@ config_result parse_config(std::string config) return res; } -} // namespace parsers -} // namespace scap_gvisor +} // namespace parsers +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/parsers.h b/userspace/libscap/engine/gvisor/parsers.h index 976985c9e7..d42d21ce1f 100644 --- a/userspace/libscap/engine/gvisor/parsers.h +++ b/userspace/libscap/engine/gvisor/parsers.h @@ -29,102 +29,155 @@ namespace scap_gvisor { namespace parsers { struct event_parser { - std::function parse_msg; + std::function< + parse_result(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf)> + parse_msg; std::function parse_container_id; }; template -static std::string container_id_from_context(scap_const_sized_buffer proto) -{ +static std::string container_id_from_context(scap_const_sized_buffer proto) { T gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { return ""; } - auto& context_data = gvisor_evt.context_data(); - return context_data.container_id(); + auto& context_data = gvisor_evt.context_data(); + return context_data.container_id(); } -static std::string container_id_from_container_start(scap_const_sized_buffer proto) -{ +static std::string container_id_from_container_start(scap_const_sized_buffer proto) { gvisor::container::Start gvisor_evt; - if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) - { + if(!gvisor_evt.ParseFromArray(proto.buf, proto.size)) { return ""; } return gvisor_evt.id(); } -static parse_result parse_container_start(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_sentry_clone(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_sentry_task_exit(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_generic_syscall(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_open(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_close(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_read(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_connect(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_execve(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_socket(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_chdir(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_setid(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_setresid(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_prlimit64(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_pipe(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_fcntl(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_dup(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_signalfd(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_chroot(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_eventfd(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_clone(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_bind(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_accept(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_timerfd_create(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_fork(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_inotify_init(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_socketpair(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); -static parse_result parse_write(uint32_t id, scap_const_sized_buffer proto, scap_sized_buffer scap_buf); +static parse_result parse_container_start(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_sentry_clone(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_sentry_task_exit(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_generic_syscall(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_open(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_close(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_read(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_connect(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_execve(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_socket(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_chdir(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_setid(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_setresid(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_prlimit64(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_pipe(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_fcntl(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_dup(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_signalfd(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_chroot(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_eventfd(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_clone(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_bind(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_accept(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_timerfd_create(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_fork(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_inotify_init(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_socketpair(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); +static parse_result parse_write(uint32_t id, + scap_const_sized_buffer proto, + scap_sized_buffer scap_buf); // List of parsers. Indexes are based on MessageType enum values std::vector dispatchers = { - {nullptr, nullptr}, // MESSAGE_UNKNOWN - {parse_container_start, container_id_from_container_start}, - {parse_sentry_clone, container_id_from_context}, - {nullptr, nullptr}, // MESSAGE_SENTRY_EXEC - {nullptr, nullptr}, // MESSAGE_SENTRY_EXIT_NOTIFY_PARENT - {parse_sentry_task_exit, container_id_from_context}, - {parse_generic_syscall, container_id_from_context}, - {parse_open, container_id_from_context}, - {parse_close, container_id_from_context}, - {parse_read, container_id_from_context}, - {parse_connect, container_id_from_context}, - {parse_execve, container_id_from_context}, - {parse_socket, container_id_from_context}, - {parse_chdir, container_id_from_context}, - {parse_setid, container_id_from_context}, - {parse_setresid, container_id_from_context}, - {parse_prlimit64, container_id_from_context}, - {parse_pipe, container_id_from_context}, - {parse_fcntl, container_id_from_context}, - {parse_dup, container_id_from_context}, - {parse_signalfd, container_id_from_context}, - {parse_chroot, container_id_from_context}, - {parse_eventfd, container_id_from_context}, - {parse_clone, container_id_from_context}, - {parse_bind, container_id_from_context}, - {parse_accept, container_id_from_context}, - {parse_timerfd_create, container_id_from_context}, - {nullptr, nullptr}, // MESSAGE_SYSCALL_TIMERFD_SETTIME - {nullptr, nullptr}, // MESSAGE_SYSCALL_TIMERFD_GETTIME - {parse_fork, container_id_from_context}, - {parse_inotify_init, container_id_from_context}, - {nullptr, nullptr}, // MESSAGE_SYSCALL_INOTIFY_ADD_WATCH - {nullptr, nullptr}, // MESSAGE_SYSCALL_INOTIFY_RM_WATCH - {parse_socketpair, container_id_from_context}, - {parse_write, container_id_from_context} -}; - -} // namespace parsers - -} // namespace scap_gvisor + {nullptr, nullptr}, // MESSAGE_UNKNOWN + {parse_container_start, container_id_from_container_start}, + {parse_sentry_clone, container_id_from_context}, + {nullptr, nullptr}, // MESSAGE_SENTRY_EXEC + {nullptr, nullptr}, // MESSAGE_SENTRY_EXIT_NOTIFY_PARENT + {parse_sentry_task_exit, container_id_from_context}, + {parse_generic_syscall, container_id_from_context}, + {parse_open, container_id_from_context}, + {parse_close, container_id_from_context}, + {parse_read, container_id_from_context}, + {parse_connect, container_id_from_context}, + {parse_execve, container_id_from_context}, + {parse_socket, container_id_from_context}, + {parse_chdir, container_id_from_context}, + {parse_setid, container_id_from_context}, + {parse_setresid, container_id_from_context}, + {parse_prlimit64, container_id_from_context}, + {parse_pipe, container_id_from_context}, + {parse_fcntl, container_id_from_context}, + {parse_dup, container_id_from_context}, + {parse_signalfd, container_id_from_context}, + {parse_chroot, container_id_from_context}, + {parse_eventfd, container_id_from_context}, + {parse_clone, container_id_from_context}, + {parse_bind, container_id_from_context}, + {parse_accept, container_id_from_context}, + {parse_timerfd_create, container_id_from_context}, + {nullptr, nullptr}, // MESSAGE_SYSCALL_TIMERFD_SETTIME + {nullptr, nullptr}, // MESSAGE_SYSCALL_TIMERFD_GETTIME + {parse_fork, container_id_from_context}, + {parse_inotify_init, container_id_from_context}, + {nullptr, nullptr}, // MESSAGE_SYSCALL_INOTIFY_ADD_WATCH + {nullptr, nullptr}, // MESSAGE_SYSCALL_INOTIFY_RM_WATCH + {parse_socketpair, container_id_from_context}, + {parse_write, container_id_from_context}}; + +} // namespace parsers + +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/runsc.cpp b/userspace/libscap/engine/gvisor/runsc.cpp index 314ac74fd2..bdedd4e245 100644 --- a/userspace/libscap/engine/gvisor/runsc.cpp +++ b/userspace/libscap/engine/gvisor/runsc.cpp @@ -28,26 +28,22 @@ namespace scap_gvisor { namespace runsc { -result runsc(char *argv[]) -{ +result runsc(char *argv[]) { result res; int pipefds[2]; int ret = pipe(pipefds); - if(ret) - { + if(ret) { return res; } pid_t pid = vfork(); - if(pid > 0) - { + if(pid > 0) { int status; close(pipefds[1]); wait(&status); - if(!WIFEXITED(status) || WEXITSTATUS(status) != 0) - { + if(!WIFEXITED(status) || WEXITSTATUS(status) != 0) { res.error = status; return res; } @@ -56,13 +52,10 @@ result runsc(char *argv[]) std::string line; std::istream is(&filebuf); - while(std::getline(is, line)) - { + while(std::getline(is, line)) { res.output.emplace_back(std::string(line)); } - } - else - { + } else { close(pipefds[0]); dup2(pipefds[1], STDOUT_FILENO); execvp("runsc", argv); @@ -72,40 +65,25 @@ result runsc(char *argv[]) return res; } -result version() -{ - const char *argv[] = { - "runsc", - "--version", - NULL - }; +result version() { + const char *argv[] = {"runsc", "--version", NULL}; return runsc((char **)argv); } -result list(const std::string &root_path) -{ +result list(const std::string &root_path) { result res; std::vector running_sandboxes; - const char *argv[] = { - "runsc", - "--root", - root_path.c_str(), - "list", - NULL - }; + const char *argv[] = {"runsc", "--root", root_path.c_str(), "list", NULL}; res = runsc((char **)argv); - if(res.error) - { + if(res.error) { return res; } - for(const auto &line : res.output) - { - if(line.find("running") != std::string::npos) - { + for(const auto &line : res.output) { + if(line.find("running") != std::string::npos) { std::string sandbox = line.substr(0, line.find_first_of(" ", 0)); running_sandboxes.emplace_back(sandbox); } @@ -115,56 +93,54 @@ result list(const std::string &root_path) return res; } -result trace_create(const std::string &root_path, const std::string &trace_session_path, const std::string &sandbox_id, bool force) -{ - const char *argv[] = { - "runsc", - "--root", - root_path.c_str(), - "trace", - "create", - force ? "--force" : "", - "--config", - trace_session_path.c_str(), - sandbox_id.c_str(), - NULL - }; +result trace_create(const std::string &root_path, + const std::string &trace_session_path, + const std::string &sandbox_id, + bool force) { + const char *argv[] = {"runsc", + "--root", + root_path.c_str(), + "trace", + "create", + force ? "--force" : "", + "--config", + trace_session_path.c_str(), + sandbox_id.c_str(), + NULL}; return runsc((char **)argv); } -result trace_delete(const std::string &root_path, const std::string &session_name, const std::string &sandbox_id) -{ - const char *argv[] = { - "runsc", - "--root", - root_path.c_str(), - "trace", - "delete", - "--name", - session_name.c_str(), - sandbox_id.c_str(), - NULL - }; +result trace_delete(const std::string &root_path, + const std::string &session_name, + const std::string &sandbox_id) { + const char *argv[] = {"runsc", + "--root", + root_path.c_str(), + "trace", + "delete", + "--name", + session_name.c_str(), + sandbox_id.c_str(), + NULL}; return runsc((char **)argv); } -result trace_procfs(const std::string &root_path, const std::string &sandbox_id) -{ +result trace_procfs(const std::string &root_path, const std::string &sandbox_id) { const char *argv[] = { - "runsc", - "--root", - root_path.c_str(), - "trace", - "procfs", - sandbox_id.c_str(), - NULL, + "runsc", + "--root", + root_path.c_str(), + "trace", + "procfs", + sandbox_id.c_str(), + NULL, }; return runsc((char **)argv); } -} // namespace runsc +} // namespace runsc -} // namespace scap_gvisor +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/scap_gvisor.cpp b/userspace/libscap/engine/gvisor/scap_gvisor.cpp index 19919f858d..8209efdfef 100644 --- a/userspace/libscap/engine/gvisor/scap_gvisor.cpp +++ b/userspace/libscap/engine/gvisor/scap_gvisor.cpp @@ -16,7 +16,6 @@ limitations under the License. */ - #include #include #include @@ -45,15 +44,14 @@ constexpr size_t initial_event_buffer_size = 32; constexpr int listen_backlog_size = 128; const std::string default_root_path = "/var/run/docker/runtime-runc/moby"; -static const char * const gvisor_counters_stats_names[] = { - [scap_gvisor::stats::GVISOR_N_EVTS] = "n_evts", - [scap_gvisor::stats::GVISOR_N_DROPS_BUG] = "n_drops_bug", - [scap_gvisor::stats::GVISOR_N_DROPS_BUFFER_TOTAL] ="n_drops_buffer_total", - [scap_gvisor::stats::GVISOR_N_DROPS] = "n_drops", +static const char *const gvisor_counters_stats_names[] = { + [scap_gvisor::stats::GVISOR_N_EVTS] = "n_evts", + [scap_gvisor::stats::GVISOR_N_DROPS_BUG] = "n_drops_bug", + [scap_gvisor::stats::GVISOR_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total", + [scap_gvisor::stats::GVISOR_N_DROPS] = "n_drops", }; -sandbox_entry::sandbox_entry() -{ +sandbox_entry::sandbox_entry() { m_buf.buf = nullptr; m_buf.size = 0; m_last_dropped_count = 0; @@ -61,28 +59,22 @@ sandbox_entry::sandbox_entry() m_id = 0xffffffff; } -sandbox_entry::~sandbox_entry() -{ - if (m_buf.buf != nullptr) - { +sandbox_entry::~sandbox_entry() { + if(m_buf.buf != nullptr) { free(m_buf.buf); } } -int32_t sandbox_entry::expand_buffer(size_t size) -{ - void* new_buf; +int32_t sandbox_entry::expand_buffer(size_t size) { + void *new_buf; - if (m_buf.buf == nullptr) - { + if(m_buf.buf == nullptr) { new_buf = malloc(size); - } else - { + } else { new_buf = realloc(m_buf.buf, size); } - if (new_buf == nullptr) - { + if(new_buf == nullptr) { // no need to clean up existing buffers in case of failed realloc // since they will be cleaned up by the destructor return SCAP_FAILURE; @@ -94,41 +86,33 @@ int32_t sandbox_entry::expand_buffer(size_t size) return SCAP_SUCCESS; } -engine::engine(char *lasterr) -{ - m_lasterr = lasterr; +engine::engine(char *lasterr) { + m_lasterr = lasterr; m_gvisor_stats.n_evts = 0; m_gvisor_stats.n_drops_parsing = 0; m_gvisor_stats.n_drops_gvisor = 0; } -engine::~engine() -{ - -} +engine::~engine() {} -int32_t engine::init(std::string config_path, std::string root_path, bool no_events, int epoll_timeout, scap_gvisor_platform *platform) -{ - if(root_path.empty()) - { +int32_t engine::init(std::string config_path, + std::string root_path, + bool no_events, + int epoll_timeout, + scap_gvisor_platform *platform) { + if(root_path.empty()) { m_root_path = default_root_path; - } - else - { + } else { m_root_path = root_path; } - if(epoll_timeout >= 0) - { + if(epoll_timeout >= 0) { m_epoll_timeout = epoll_timeout; - } - else - { + } else { m_epoll_timeout = -1; } - if(platform == nullptr) - { + if(platform == nullptr) { strlcpy(m_lasterr, "A platform is required for gVisor", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } @@ -137,49 +121,49 @@ int32_t engine::init(std::string config_path, std::string root_path, bool no_eve m_trace_session_path = config_path; std::ifstream config_file(config_path); - if (config_file.fail()) - { - snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Could not open gVisor configuration file %s", config_path.c_str()); + if(config_file.fail()) { + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "Could not open gVisor configuration file %s", + config_path.c_str()); return SCAP_FAILURE; } std::stringstream config_buf; config_buf << config_file.rdbuf(); parsers::config_result config_result = parsers::parse_config(config_buf.str()); - if(config_result.status != SCAP_SUCCESS) - { - snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Could not parse gVisor configuration file %s : %s", - config_path.c_str(), config_result.error.c_str()); + if(config_result.status != SCAP_SUCCESS) { + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "Could not parse gVisor configuration file %s : %s", + config_path.c_str(), + config_result.error.c_str()); return config_result.status; } // Check if runsc is installed in the system runsc::result version = runsc::version(); - if(version.error) - { + if(version.error) { strlcpy(m_lasterr, "Cannot find runsc binary", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } // Initialize the listen fd m_socket_path = config_result.socket_path; - if (m_socket_path.empty()) - { + if(m_socket_path.empty()) { strlcpy(m_lasterr, "Empty gVisor socket path", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } m_no_events = no_events; - if(no_events) - { + if(no_events) { return SCAP_SUCCESS; } unlink(m_socket_path.c_str()); int sock = socket(PF_UNIX, SOCK_SEQPACKET, 0); - if(sock == -1) - { + if(sock == -1) { snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Cannot create unix socket: %s", strerror(errno)); return SCAP_FAILURE; } @@ -190,18 +174,19 @@ int32_t engine::init(std::string config_path, std::string root_path, bool no_eve unsigned long old_umask = umask(0); int ret = bind(sock, (sockaddr *)&address, sizeof(address)); - if(ret == -1) - { + if(ret == -1) { snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Cannot bind unix socket: %s", strerror(errno)); umask(old_umask); return SCAP_FAILURE; } ret = listen(sock, listen_backlog_size); - if(ret == -1) - { + if(ret == -1) { umask(old_umask); - snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Cannot listen on gvisor unix socket: %s", strerror(errno)); + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "Cannot listen on gvisor unix socket: %s", + strerror(errno)); return SCAP_FAILURE; } @@ -210,83 +195,67 @@ int32_t engine::init(std::string config_path, std::string root_path, bool no_eve // Initialize the epoll fd m_epollfd = epoll_create(1); - if(m_epollfd == -1) - { + if(m_epollfd == -1) { snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Cannot create epollfd socket: %s", strerror(errno)); return SCAP_FAILURE; } - return SCAP_SUCCESS; + return SCAP_SUCCESS; } -int32_t engine::close() -{ - if(m_no_events) - { +int32_t engine::close() { + if(m_no_events) { return SCAP_SUCCESS; } stop_capture(); unlink(m_socket_path.c_str()); - return SCAP_SUCCESS; + return SCAP_SUCCESS; } -void engine::free_sandbox_buffers() -{ +void engine::free_sandbox_buffers() { m_sandbox_data.clear(); } -static bool handshake(int client) -{ +static bool handshake(int client) { std::vector buf(max_message_size); ssize_t bytes = read(client, buf.data(), buf.size()); - if(bytes < 0) - { + if(bytes < 0) { return false; - } - else if(static_cast(bytes) == buf.size()) - { + } else if(static_cast(bytes) == buf.size()) { return false; } gvisor::common::Handshake in = {}; - if(!in.ParseFromArray(buf.data(), bytes)) - { + if(!in.ParseFromArray(buf.data(), bytes)) { return false; } - if(in.version() < min_supported_version) - { + if(in.version() < min_supported_version) { return false; } gvisor::common::Handshake out; out.set_version(current_version); - if(!out.SerializeToFileDescriptor(client)) - { + if(!out.SerializeToFileDescriptor(client)) { return false; } return true; } -static void accept_thread(int listenfd, int epollfd) -{ - while(true) - { +static void accept_thread(int listenfd, int epollfd) { + while(true) { int client = accept(listenfd, NULL, NULL); - if (client < 0) - { - if (errno == EINTR) - { + if(client < 0) { + if(errno == EINTR) { continue; } // connection shutdown return; } - if(!handshake(client)) - { + if(!handshake(client)) { close(client); continue; } @@ -294,17 +263,14 @@ static void accept_thread(int listenfd, int epollfd) epoll_event evt; evt.data.fd = client; evt.events = EPOLLIN; - if(epoll_ctl(epollfd, EPOLL_CTL_ADD, client, &evt) < 0) - { + if(epoll_ctl(epollfd, EPOLL_CTL_ADD, client, &evt) < 0) { return; } } } -int32_t engine::start_capture() -{ - if(m_no_events) - { +int32_t engine::start_capture() { + if(m_no_events) { return SCAP_FAILURE; } // @@ -312,8 +278,7 @@ int32_t engine::start_capture() // We will need to recreate a session for each of them // runsc::result exisiting_sandboxes_res = runsc::list(m_root_path); - if(exisiting_sandboxes_res.error) - { + if(exisiting_sandboxes_res.error) { strlcpy(m_lasterr, "Error listing running sandboxes", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } @@ -325,12 +290,11 @@ int32_t engine::start_capture() m_capture_started = true; - for(const auto& sandbox : existing_sandboxes) - { + for(const auto &sandbox : existing_sandboxes) { // Since they were already running, we need to force the creation - runsc::result trace_create_res = runsc::trace_create(m_root_path, m_trace_session_path, sandbox, true); - if(trace_create_res.error) - { + runsc::result trace_create_res = + runsc::trace_create(m_root_path, m_trace_session_path, sandbox, true); + if(trace_create_res.error) { // some sandboxes may not be traced, we can skip them safely continue; } @@ -338,8 +302,7 @@ int32_t engine::start_capture() // Catch all sandboxes that might have been created in the meantime runsc::result new_sandboxes_res = runsc::list(m_root_path); - if(new_sandboxes_res.error) - { + if(new_sandboxes_res.error) { strlcpy(m_lasterr, "Error listing running sandboxes", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } @@ -347,34 +310,29 @@ int32_t engine::start_capture() // Remove the existing sandboxes (erase-remove idiom) new_sandboxes.erase( - remove_if( - new_sandboxes.begin(), - new_sandboxes.end(), - [&existing_sandboxes](const std::string &s) -> bool - { - auto res = find(existing_sandboxes.begin(), existing_sandboxes.end(), s); - return res != existing_sandboxes.end(); - }), - new_sandboxes.end()); + remove_if(new_sandboxes.begin(), + new_sandboxes.end(), + [&existing_sandboxes](const std::string &s) -> bool { + auto res = find(existing_sandboxes.begin(), existing_sandboxes.end(), s); + return res != existing_sandboxes.end(); + }), + new_sandboxes.end()); // Create new session for remaining sandboxes - for(const auto& sandbox : new_sandboxes) - { - runsc::result trace_create_res = runsc::trace_create(m_root_path, m_trace_session_path, sandbox, false); - if(trace_create_res.error) - { + for(const auto &sandbox : new_sandboxes) { + runsc::result trace_create_res = + runsc::trace_create(m_root_path, m_trace_session_path, sandbox, false); + if(trace_create_res.error) { // some sandboxes may not be traced, we can skip them safely continue; } } - return SCAP_SUCCESS; + return SCAP_SUCCESS; } -int32_t engine::stop_capture() -{ - if (!m_capture_started) - { +int32_t engine::stop_capture() { + if(!m_capture_started) { return SCAP_SUCCESS; } @@ -383,34 +341,32 @@ int32_t engine::stop_capture() free_sandbox_buffers(); runsc::result sandboxes_res = runsc::list(m_root_path); - if(sandboxes_res.error) - { + if(sandboxes_res.error) { strlcpy(m_lasterr, "Error listing running sandboxes", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } std::vector &sandboxes = sandboxes_res.output; - for(const auto &sandbox : sandboxes) - { + for(const auto &sandbox : sandboxes) { // todo(loresuso): change session name when gVisor will support it runsc::result trace_delete_res = runsc::trace_delete(m_root_path, "Default", sandbox); - if(trace_delete_res.error) - { - snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Cannot delete session for sandbox %s", sandbox.c_str()); + if(trace_delete_res.error) { + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "Cannot delete session for sandbox %s", + sandbox.c_str()); return SCAP_FAILURE; } } m_capture_started = false; - return SCAP_SUCCESS; + return SCAP_SUCCESS; } -uint32_t engine::get_vxid(uint64_t xid) const -{ +uint32_t engine::get_vxid(uint64_t xid) const { return parsers::get_vxid(xid); } -int32_t engine::get_stats(scap_stats *stats) const -{ +int32_t engine::get_stats(scap_stats *stats) const { stats->n_drops = m_gvisor_stats.n_drops_parsing + m_gvisor_stats.n_drops_gvisor; stats->n_drops_bug = m_gvisor_stats.n_drops_parsing; stats->n_drops_buffer = m_gvisor_stats.n_drops_gvisor; @@ -418,20 +374,17 @@ int32_t engine::get_stats(scap_stats *stats) const return SCAP_SUCCESS; } -const metrics_v2* engine::get_stats_v2(uint32_t flags, uint32_t* nstats, int32_t* rc) -{ +const metrics_v2 *engine::get_stats_v2(uint32_t flags, uint32_t *nstats, int32_t *rc) { *nstats = scap_gvisor::stats::MAX_GVISOR_COUNTERS_STATS; - metrics_v2* stats = engine::m_stats; - if (!stats) - { + metrics_v2 *stats = engine::m_stats; + if(!stats) { *nstats = 0; *rc = SCAP_FAILURE; return NULL; } /* GVISOR STATS COUNTERS */ - for(uint32_t stat = 0; stat < scap_gvisor::stats::MAX_GVISOR_COUNTERS_STATS; stat++) - { + for(uint32_t stat = 0; stat < scap_gvisor::stats::MAX_GVISOR_COUNTERS_STATS; stat++) { stats[stat].type = METRIC_VALUE_TYPE_U64; stats[stat].unit = METRIC_VALUE_UNIT_COUNT; stats[stat].metric_type = METRIC_VALUE_METRIC_TYPE_MONOTONIC; @@ -440,50 +393,57 @@ const metrics_v2* engine::get_stats_v2(uint32_t flags, uint32_t* nstats, int32_t } stats[scap_gvisor::stats::GVISOR_N_EVTS].value.u64 = m_gvisor_stats.n_evts; stats[scap_gvisor::stats::GVISOR_N_DROPS_BUG].value.u64 = m_gvisor_stats.n_drops_parsing; - stats[scap_gvisor::stats::GVISOR_N_DROPS_BUFFER_TOTAL].value.u64 = m_gvisor_stats.n_drops_parsing + m_gvisor_stats.n_drops_gvisor; + stats[scap_gvisor::stats::GVISOR_N_DROPS_BUFFER_TOTAL].value.u64 = + m_gvisor_stats.n_drops_parsing + m_gvisor_stats.n_drops_gvisor; stats[scap_gvisor::stats::GVISOR_N_DROPS].value.u64 = m_gvisor_stats.n_drops_gvisor; *rc = SCAP_SUCCESS; return stats; } -// Reads one gvisor message from the specified fd, stores the resulting events overwriting m_buffers and adds pointers to m_event_queue. -// Returns: +// Reads one gvisor message from the specified fd, stores the resulting events overwriting m_buffers +// and adds pointers to m_event_queue. Returns: // * SCAP_SUCCESS in case of success -// * SCAP_FAILURE in case of a fatal error while reading from the fd or allocating memory (m_lasterr is filled) +// * SCAP_FAILURE in case of a fatal error while reading from the fd or allocating memory (m_lasterr +// is filled) // * SCAP_NOT_SUPPORTED if the message type is not currently supported // * SCAP_ILLEGAL_INPUT in case of parsing errors (invalid message or parsing issue) // * SCAP_EOF if there is no more data to process from this fd -int32_t engine::process_message_from_fd(int fd) -{ +int32_t engine::process_message_from_fd(int fd) { char message[max_message_size]; ssize_t nbytes = read(fd, message, max_message_size); - if(nbytes == -1) - { - snprintf(m_lasterr, SCAP_LASTERR_SIZE, "Error reading from gvisor client: %s", strerror(errno)); + if(nbytes == -1) { + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "Error reading from gvisor client: %s", + strerror(errno)); return SCAP_FAILURE; - } - else if(nbytes == 0) - { + } else if(nbytes == 0) { return SCAP_EOF; } - scap_const_sized_buffer gvisor_msg = {.buf = static_cast(message), .size = static_cast(nbytes)}; + scap_const_sized_buffer gvisor_msg = {.buf = static_cast(message), + .size = static_cast(nbytes)}; // check if we need to create a new entry for this sandbox - if(m_sandbox_data.count(fd) != 1) - { + if(m_sandbox_data.count(fd) != 1) { m_sandbox_data.emplace(fd, sandbox_entry{}); - if (m_sandbox_data[fd].expand_buffer(initial_event_buffer_size) == SCAP_FAILURE) { - snprintf(m_lasterr, SCAP_LASTERR_SIZE, "could not initialize %zu bytes for gvisor sandbox on fd %d", initial_event_buffer_size, fd); + if(m_sandbox_data[fd].expand_buffer(initial_event_buffer_size) == SCAP_FAILURE) { + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "could not initialize %zu bytes for gvisor sandbox on fd %d", + initial_event_buffer_size, + fd); return SCAP_FAILURE; } std::string container_id = parsers::parse_container_id(gvisor_msg); - if (container_id == "") - { - snprintf(m_lasterr, SCAP_LASTERR_SIZE, "could not initialize sandbox on fd %d: could not parse container ID", fd); + if(container_id == "") { + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "could not initialize sandbox on fd %d: could not parse container ID", + fd); return SCAP_FAILURE; } @@ -492,25 +452,25 @@ int32_t engine::process_message_from_fd(int fd) } uint32_t id = m_sandbox_data[fd].m_id; - parsers::parse_result parse_result = parsers::parse_gvisor_proto(id, gvisor_msg, m_sandbox_data[fd].m_buf); - if(parse_result.status == SCAP_INPUT_TOO_SMALL) - { - if (m_sandbox_data[fd].expand_buffer(parse_result.size) == SCAP_FAILURE) - { - snprintf(m_lasterr, SCAP_LASTERR_SIZE,"Cannot realloc gvisor buffer to %zu", parse_result.size); + parsers::parse_result parse_result = + parsers::parse_gvisor_proto(id, gvisor_msg, m_sandbox_data[fd].m_buf); + if(parse_result.status == SCAP_INPUT_TOO_SMALL) { + if(m_sandbox_data[fd].expand_buffer(parse_result.size) == SCAP_FAILURE) { + snprintf(m_lasterr, + SCAP_LASTERR_SIZE, + "Cannot realloc gvisor buffer to %zu", + parse_result.size); return SCAP_FAILURE; } parse_result = parsers::parse_gvisor_proto(id, gvisor_msg, m_sandbox_data[fd].m_buf); } - if(parse_result.status == SCAP_NOT_SUPPORTED) - { + if(parse_result.status == SCAP_NOT_SUPPORTED) { strlcpy(m_lasterr, parse_result.error.c_str(), SCAP_LASTERR_SIZE); return SCAP_NOT_SUPPORTED; } - if(parse_result.status == SCAP_FAILURE) - { + if(parse_result.status == SCAP_FAILURE) { strlcpy(m_lasterr, parse_result.error.c_str(), SCAP_LASTERR_SIZE); return SCAP_ILLEGAL_INPUT; } @@ -519,18 +479,15 @@ int32_t engine::process_message_from_fd(int fd) m_sandbox_data[fd].m_last_dropped_count = parse_result.dropped_count; m_gvisor_stats.n_drops_gvisor += delta; - for(scap_evt *evt : parse_result.scap_events) - { + for(scap_evt *evt : parse_result.scap_events) { m_event_queue.push_back(evt); } return parse_result.status; } -int32_t engine::next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) -{ - if(m_no_events) - { +int32_t engine::next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) { + if(m_no_events) { return SCAP_FAILURE; } @@ -538,8 +495,7 @@ int32_t engine::next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) *pdevid = 0; // if there are still events to process do it before getting more - if(!m_event_queue.empty()) - { + if(!m_event_queue.empty()) { *pevent = m_event_queue.front(); m_event_queue.pop_front(); m_gvisor_stats.n_evts++; @@ -550,27 +506,22 @@ int32_t engine::next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) // for each sandbox: this is the right place to close fds and deallocate // buffers safely for all the sandboxes that are no longer connected. - for(auto it = m_sandbox_data.begin(); it != m_sandbox_data.end(); ) - { + for(auto it = m_sandbox_data.begin(); it != m_sandbox_data.end();) { sandbox_entry &sandbox = it->second; - if(sandbox.m_closing) - { + if(sandbox.m_closing) { std::string container_id = sandbox.m_container_id; ::close(it->first); it = m_sandbox_data.erase(it); m_platform->m_platform->release_sandbox_id(container_id); - } - else - { + } else { it++; } } int nfds = epoll_wait(m_epollfd, evts, max_ready_sandboxes, m_epoll_timeout); - if (nfds < 0) - { + if(nfds < 0) { snprintf(m_lasterr, SCAP_LASTERR_SIZE, "epoll_wait error: %s", strerror(errno)); - if (errno == EINTR) { + if(errno == EINTR) { // Syscall interrupted. return SCAP_TIMEOUT; } @@ -578,41 +529,36 @@ int32_t engine::next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) return SCAP_FAILURE; } - for (int i = 0; i < nfds; ++i) { + for(int i = 0; i < nfds; ++i) { int fd = evts[i].data.fd; - if (evts[i].events & EPOLLIN) { + if(evts[i].events & EPOLLIN) { uint32_t status = process_message_from_fd(fd); - if (status == SCAP_FAILURE) { + if(status == SCAP_FAILURE) { return SCAP_FAILURE; - } - else if (status == SCAP_EOF) - { + } else if(status == SCAP_EOF) { m_sandbox_data[fd].m_closing = true; } // ignore unsupported messages, we will simply discard them - if (status == SCAP_NOT_SUPPORTED) { + if(status == SCAP_NOT_SUPPORTED) { continue; } // ignore parsing errors, we will simply discard the message - if (status == SCAP_ILLEGAL_INPUT) { + if(status == SCAP_ILLEGAL_INPUT) { m_gvisor_stats.n_drops_parsing++; continue; } } - if ((evts[i].events & (EPOLLRDHUP | EPOLLHUP)) != 0) - { + if((evts[i].events & (EPOLLRDHUP | EPOLLHUP)) != 0) { m_sandbox_data[fd].m_closing = true; } - if (evts[i].events & EPOLLERR) - { + if(evts[i].events & EPOLLERR) { int socket_error = 0; socklen_t len = sizeof(socket_error); - if(getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &len)) - { + if(getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &len)) { snprintf(m_lasterr, SCAP_LASTERR_SIZE, "epoll error: %s", strerror(socket_error)); return SCAP_FAILURE; } @@ -620,8 +566,7 @@ int32_t engine::next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) } // check if any message has been processed and return the first - if(!m_event_queue.empty()) - { + if(!m_event_queue.empty()) { *pevent = m_event_queue.front(); *pflags = 0; m_event_queue.pop_front(); @@ -630,7 +575,7 @@ int32_t engine::next(scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) } // nothing to do - return SCAP_TIMEOUT; + return SCAP_TIMEOUT; } -} // namespace scap_gvisor +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/scap_gvisor_platform.cpp b/userspace/libscap/engine/gvisor/scap_gvisor_platform.cpp index 8afeb8d552..12b8fd76ce 100644 --- a/userspace/libscap/engine/gvisor/scap_gvisor_platform.cpp +++ b/userspace/libscap/engine/gvisor/scap_gvisor_platform.cpp @@ -24,38 +24,32 @@ limitations under the License. namespace scap_gvisor { -uint32_t platform::get_threadinfos(uint64_t *n, const scap_threadinfo **tinfos) -{ +uint32_t platform::get_threadinfos(uint64_t *n, const scap_threadinfo **tinfos) { runsc::result sandboxes_res = runsc::list(m_root_path); std::vector &sandboxes = sandboxes_res.output; m_threadinfos_threads.clear(); m_threadinfos_fds.clear(); - for(const auto &sandbox: sandboxes) - { + for(const auto &sandbox : sandboxes) { runsc::result procfs_res = runsc::trace_procfs(m_root_path, sandbox); - // We may be unable to read procfs for several reasons, e.g. the pause container on k8s or a sandbox that was - // being removed - if(procfs_res.error != 0) - { + // We may be unable to read procfs for several reasons, e.g. the pause container on k8s or a + // sandbox that was being removed + if(procfs_res.error != 0) { continue; } - for(const auto &line: procfs_res.output) - { + for(const auto &line : procfs_res.output) { // skip first line of the output and empty lines if(line.find("PROCFS DUMP") != std::string::npos || - std::all_of(line.begin(), line.end(), isspace)) - { + std::all_of(line.begin(), line.end(), isspace)) { continue; } uint32_t id = get_numeric_sandbox_id(sandbox); parsers::procfs_result res = parsers::parse_procfs_json(line, id); - if(res.status != SCAP_SUCCESS) - { + if(res.status != SCAP_SUCCESS) { *tinfos = NULL; *n = 0; snprintf(m_lasterr, SCAP_LASTERR_SIZE, "%s", res.error.c_str()); @@ -73,28 +67,25 @@ uint32_t platform::get_threadinfos(uint64_t *n, const scap_threadinfo **tinfos) return SCAP_SUCCESS; } -uint32_t platform::get_fdinfos(const scap_threadinfo *tinfo, uint64_t *n, const scap_fdinfo **fdinfos) -{ +uint32_t platform::get_fdinfos(const scap_threadinfo *tinfo, + uint64_t *n, + const scap_fdinfo **fdinfos) { *n = m_threadinfos_fds[tinfo->tid].size(); - if(*n != 0) - { + if(*n != 0) { *fdinfos = m_threadinfos_fds[tinfo->tid].data(); } return SCAP_SUCCESS; } -uint32_t platform::get_numeric_sandbox_id(std::string sandbox_id) -{ - if (auto it = m_sandbox_ids.find(sandbox_id); it != m_sandbox_ids.end()) - { +uint32_t platform::get_numeric_sandbox_id(std::string sandbox_id) { + if(auto it = m_sandbox_ids.find(sandbox_id); it != m_sandbox_ids.end()) { return it->second; } // If an entry does not exist we need to generate an unique numeric ID for the sandbox std::set ids_in_use; - for(auto const &it : m_sandbox_ids) - { + for(auto const &it : m_sandbox_ids) { ids_in_use.insert(it.second); } @@ -102,37 +93,32 @@ uint32_t platform::get_numeric_sandbox_id(std::string sandbox_id) // Create a "seed" initial number, this could be any number and it's an implementation detail // but having something that resembles the sandbox ID helps with debugging - try - { + try { // If it's a hex number take the 32 most significant bits - std::string container_id_32 = sandbox_id.length() > 8 ? sandbox_id.substr(0, 7) : sandbox_id; + std::string container_id_32 = + sandbox_id.length() > 8 ? sandbox_id.substr(0, 7) : sandbox_id; id = stoul(container_id_32, nullptr, 16); - } catch (...) - { + } catch(...) { // If not, take the character representation of the first 4 bytes // Ensure the string is at least 4 characters (meaning >= 4 bytes) - if (sandbox_id.size() < 4) - { + if(sandbox_id.size() < 4) { sandbox_id.append(std::string(4 - sandbox_id.size(), '0')); } const char *chars = sandbox_id.c_str(); id = chars[3] | chars[2] << 8 | chars[1] << 16 | chars[0] << 24; } - + // Ensure ID is not 0 - if (id == 0) - { + if(id == 0) { id = 1; } // Find the first available ID - while (ids_in_use.find(id) != ids_in_use.end()) - { + while(ids_in_use.find(id) != ids_in_use.end()) { id += 1; - if (id == 0) - { + if(id == 0) { id = 1; } } @@ -142,9 +128,8 @@ uint32_t platform::get_numeric_sandbox_id(std::string sandbox_id) return id; } -void platform::release_sandbox_id(std::string sandbox_id) -{ +void platform::release_sandbox_id(std::string sandbox_id) { m_sandbox_ids.erase(sandbox_id); } -} +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/gvisor/scap_gvisor_stats.h b/userspace/libscap/engine/gvisor/scap_gvisor_stats.h index 3aaa41bea1..a7fa65a3ba 100644 --- a/userspace/libscap/engine/gvisor/scap_gvisor_stats.h +++ b/userspace/libscap/engine/gvisor/scap_gvisor_stats.h @@ -20,13 +20,13 @@ limitations under the License. namespace scap_gvisor { namespace stats { - enum gvisor_counters_stats { - GVISOR_N_EVTS = 0, - GVISOR_N_DROPS_BUG, - GVISOR_N_DROPS_BUFFER_TOTAL, - GVISOR_N_DROPS, - MAX_GVISOR_COUNTERS_STATS - }; +enum gvisor_counters_stats { + GVISOR_N_EVTS = 0, + GVISOR_N_DROPS_BUG, + GVISOR_N_DROPS_BUFFER_TOTAL, + GVISOR_N_DROPS, + MAX_GVISOR_COUNTERS_STATS +}; -} // namespace stats -} // namespace scap_gvisor +} // namespace stats +} // namespace scap_gvisor diff --git a/userspace/libscap/engine/kmod/CMakeLists.txt b/userspace/libscap/engine/kmod/CMakeLists.txt index 494939444a..a315cdb996 100644 --- a/userspace/libscap/engine/kmod/CMakeLists.txt +++ b/userspace/libscap/engine/kmod/CMakeLists.txt @@ -2,18 +2,18 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # add_library(scap_engine_kmod scap_kmod.c) -target_link_libraries(scap_engine_kmod PRIVATE scap_event_schema scap_platform scap_engine_util scap_error) +target_link_libraries( + scap_engine_kmod PRIVATE scap_event_schema scap_platform scap_engine_util scap_error +) set_scap_target_properties(scap_engine_kmod) diff --git a/userspace/libscap/engine/kmod/kmod.h b/userspace/libscap/engine/kmod/kmod.h index c67df17860..27102e0273 100644 --- a/userspace/libscap/engine/kmod/kmod.h +++ b/userspace/libscap/engine/kmod/kmod.h @@ -23,9 +23,7 @@ limitations under the License. #include #include - -struct kmod_engine -{ +struct kmod_engine { struct scap_device_set m_dev_set; char* m_lasterr; interesting_ppm_sc_set curr_sc_set; diff --git a/userspace/libscap/engine/kmod/kmod_public.h b/userspace/libscap/engine/kmod/kmod_public.h index e16b45ba9a..334dfedbd6 100644 --- a/userspace/libscap/engine/kmod/kmod_public.h +++ b/userspace/libscap/engine/kmod/kmod_public.h @@ -19,17 +19,17 @@ limitations under the License. #define KMOD_ENGINE "kmod" #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - #include +#include - struct scap_kmod_engine_params - { - unsigned long buffer_bytes_dim; ///< Dimension of a single per-CPU buffer in bytes. Please note: this buffer will be mapped twice in the process virtual memory, so pay attention to its size. - }; +struct scap_kmod_engine_params { + unsigned long buffer_bytes_dim; ///< Dimension of a single per-CPU buffer in bytes. Please + ///< note: this buffer will be mapped twice in the process + ///< virtual memory, so pay attention to its size. +}; - extern const struct scap_linux_vtable scap_kmod_linux_vtable; +extern const struct scap_linux_vtable scap_kmod_linux_vtable; #ifdef __cplusplus }; #endif diff --git a/userspace/libscap/engine/kmod/scap_kmod.c b/userspace/libscap/engine/kmod/scap_kmod.c index 3622781987..f14bfd373a 100644 --- a/userspace/libscap/engine/kmod/scap_kmod.c +++ b/userspace/libscap/engine/kmod/scap_kmod.c @@ -23,7 +23,7 @@ limitations under the License. #include #include -#define HANDLE(engine) ((struct kmod_engine*)(engine.m_handle)) +#define HANDLE(engine) ((struct kmod_engine *)(engine.m_handle)) #include #include @@ -36,37 +36,35 @@ limitations under the License. #include #include -//#define NDEBUG +// #define NDEBUG #include -static const char * const kmod_kernel_counters_stats_names[] = { - [KMOD_N_EVTS] = N_EVENTS_PREFIX, - [KMOD_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total", - [KMOD_N_DROPS_BUFFER_CLONE_FORK_ENTER] = "n_drops_buffer_clone_fork_enter", - [KMOD_N_DROPS_BUFFER_CLONE_FORK_EXIT] = "n_drops_buffer_clone_fork_exit", - [KMOD_N_DROPS_BUFFER_EXECVE_ENTER] = "n_drops_buffer_execve_enter", - [KMOD_N_DROPS_BUFFER_EXECVE_EXIT] = "n_drops_buffer_execve_exit", - [KMOD_N_DROPS_BUFFER_CONNECT_ENTER] = "n_drops_buffer_connect_enter", - [KMOD_N_DROPS_BUFFER_CONNECT_EXIT] = "n_drops_buffer_connect_exit", - [KMOD_N_DROPS_BUFFER_OPEN_ENTER] = "n_drops_buffer_open_enter", - [KMOD_N_DROPS_BUFFER_OPEN_EXIT] = "n_drops_buffer_open_exit", - [KMOD_N_DROPS_BUFFER_DIR_FILE_ENTER] = "n_drops_buffer_dir_file_enter", - [KMOD_N_DROPS_BUFFER_DIR_FILE_EXIT] = "n_drops_buffer_dir_file_exit", - [KMOD_N_DROPS_BUFFER_OTHER_INTEREST_ENTER] = "n_drops_buffer_other_interest_enter", - [KMOD_N_DROPS_BUFFER_OTHER_INTEREST_EXIT] = "n_drops_buffer_other_interest_exit", - [KMOD_N_DROPS_BUFFER_CLOSE_EXIT] = "n_drops_buffer_close_exit", - [KMOD_N_DROPS_BUFFER_PROC_EXIT] = "n_drops_buffer_proc_exit", - [KMOD_N_DROPS_PAGE_FAULTS] = "n_drops_page_faults", - [KMOD_N_DROPS_BUG] = "n_drops_bug", - [KMOD_N_DROPS] = "n_drops", - [KMOD_N_PREEMPTIONS] = "n_preemptions", +static const char *const kmod_kernel_counters_stats_names[] = { + [KMOD_N_EVTS] = N_EVENTS_PREFIX, + [KMOD_N_DROPS_BUFFER_TOTAL] = "n_drops_buffer_total", + [KMOD_N_DROPS_BUFFER_CLONE_FORK_ENTER] = "n_drops_buffer_clone_fork_enter", + [KMOD_N_DROPS_BUFFER_CLONE_FORK_EXIT] = "n_drops_buffer_clone_fork_exit", + [KMOD_N_DROPS_BUFFER_EXECVE_ENTER] = "n_drops_buffer_execve_enter", + [KMOD_N_DROPS_BUFFER_EXECVE_EXIT] = "n_drops_buffer_execve_exit", + [KMOD_N_DROPS_BUFFER_CONNECT_ENTER] = "n_drops_buffer_connect_enter", + [KMOD_N_DROPS_BUFFER_CONNECT_EXIT] = "n_drops_buffer_connect_exit", + [KMOD_N_DROPS_BUFFER_OPEN_ENTER] = "n_drops_buffer_open_enter", + [KMOD_N_DROPS_BUFFER_OPEN_EXIT] = "n_drops_buffer_open_exit", + [KMOD_N_DROPS_BUFFER_DIR_FILE_ENTER] = "n_drops_buffer_dir_file_enter", + [KMOD_N_DROPS_BUFFER_DIR_FILE_EXIT] = "n_drops_buffer_dir_file_exit", + [KMOD_N_DROPS_BUFFER_OTHER_INTEREST_ENTER] = "n_drops_buffer_other_interest_enter", + [KMOD_N_DROPS_BUFFER_OTHER_INTEREST_EXIT] = "n_drops_buffer_other_interest_exit", + [KMOD_N_DROPS_BUFFER_CLOSE_EXIT] = "n_drops_buffer_close_exit", + [KMOD_N_DROPS_BUFFER_PROC_EXIT] = "n_drops_buffer_proc_exit", + [KMOD_N_DROPS_PAGE_FAULTS] = "n_drops_page_faults", + [KMOD_N_DROPS_BUG] = "n_drops_bug", + [KMOD_N_DROPS] = "n_drops", + [KMOD_N_PREEMPTIONS] = "n_preemptions", }; -static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) -{ +static void *alloc_handle(scap_t *main_handle, char *lasterr_ptr) { struct kmod_engine *engine = calloc(1, sizeof(struct kmod_engine)); - if(engine) - { + if(engine) { engine->m_lasterr = lasterr_ptr; engine->m_stats = NULL; engine->m_nstats = 0; @@ -74,20 +72,16 @@ static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) return engine; } -static void free_handle(struct scap_engine_handle engine) -{ +static void free_handle(struct scap_engine_handle engine) { free(engine.m_handle); } -static uint32_t get_max_consumers() -{ +static uint32_t get_max_consumers() { uint32_t max; FILE *pfile = fopen("/sys/module/" SCAP_KERNEL_MODULE_NAME "/parameters/max_consumers", "r"); - if(pfile != NULL) - { - int w = fscanf(pfile, "%"PRIu32, &max); - if(w == 0) - { + if(pfile != NULL) { + int w = fscanf(pfile, "%" PRIu32, &max); + if(w == 0) { fclose(pfile); return 0; } @@ -99,19 +93,16 @@ static uint32_t get_max_consumers() return 0; } -static int32_t enforce_into_kmod_buffer_bytes_dim(scap_t *handle, unsigned long buf_bytes_dim) -{ - const char* file_name = "/sys/module/" SCAP_KERNEL_MODULE_NAME "/parameters/g_buffer_bytes_dim"; +static int32_t enforce_into_kmod_buffer_bytes_dim(scap_t *handle, unsigned long buf_bytes_dim) { + const char *file_name = "/sys/module/" SCAP_KERNEL_MODULE_NAME "/parameters/g_buffer_bytes_dim"; errno = 0; - /* Here we check if the dimension provided by the kernel module is the same as the user-provided one. - * In this way we can avoid writing under the `/sys/module/...` file. + /* Here we check if the dimension provided by the kernel module is the same as the user-provided + * one. In this way we can avoid writing under the `/sys/module/...` file. */ FILE *read_file = fopen(file_name, "r"); - if(read_file == NULL) - { - if (errno == ENOENT) - { + if(read_file == NULL) { + if(errno == ENOENT) { // It is most probably a wrong API version of the driver; // let the issue be gracefully managed during the api version check against the driver. return SCAP_SUCCESS; @@ -121,69 +112,77 @@ static int32_t enforce_into_kmod_buffer_bytes_dim(scap_t *handle, unsigned long unsigned long kernel_buf_bytes_dim = 0; int ret = fscanf(read_file, "%lu", &kernel_buf_bytes_dim); - if(ret != 1) - { + if(ret != 1) { int err = errno; fclose(read_file); - return scap_errprintf(handle->m_lasterr, err, "unable to read the syscall buffer dim from '%s'", file_name); + return scap_errprintf(handle->m_lasterr, + err, + "unable to read the syscall buffer dim from '%s'", + file_name); } fclose(read_file); /* We have no to update the file writing on it, the dimension is the same. */ - if(kernel_buf_bytes_dim == buf_bytes_dim) - { + if(kernel_buf_bytes_dim == buf_bytes_dim) { return SCAP_SUCCESS; } /* Fallback to write on the file if the dim is different */ FILE *write_file = fopen(file_name, "w"); - if(write_file == NULL) - { - return scap_errprintf(handle->m_lasterr, errno, "unable to open '%s'. Probably the /sys/module filesystem is read-only", file_name); + if(write_file == NULL) { + return scap_errprintf( + handle->m_lasterr, + errno, + "unable to open '%s'. Probably the /sys/module filesystem is read-only", + file_name); } - if(fprintf(write_file, "%lu", buf_bytes_dim) < 0) - { + if(fprintf(write_file, "%lu", buf_bytes_dim) < 0) { int err = errno; fclose(write_file); - return scap_errprintf(handle->m_lasterr, err, "unable to write into /sys/module/" SCAP_KERNEL_MODULE_NAME "/parameters/g_buffer_bytes_dim"); + return scap_errprintf(handle->m_lasterr, + err, + "unable to write into /sys/module/" SCAP_KERNEL_MODULE_NAME + "/parameters/g_buffer_bytes_dim"); } fclose(write_file); return SCAP_SUCCESS; } -static int32_t mark_attached_prog(struct kmod_engine* handle, uint32_t ioctl_op, kmod_prog_codes tp) -{ +static int32_t mark_attached_prog(struct kmod_engine *handle, + uint32_t ioctl_op, + kmod_prog_codes tp) { struct scap_device_set *devset = &handle->m_dev_set; - if(ioctl(devset->m_devs[0].m_fd, ioctl_op, tp)) - { - return scap_errprintf(handle->m_lasterr, errno, - "%s(%d) failed for tp %d", - __FUNCTION__, ioctl_op, tp); + if(ioctl(devset->m_devs[0].m_fd, ioctl_op, tp)) { + return scap_errprintf(handle->m_lasterr, + errno, + "%s(%d) failed for tp %d", + __FUNCTION__, + ioctl_op, + tp); } return SCAP_SUCCESS; } -static int32_t mark_syscall(struct kmod_engine* handle, uint32_t ioctl_op, int syscall_id) -{ +static int32_t mark_syscall(struct kmod_engine *handle, uint32_t ioctl_op, int syscall_id) { struct scap_device_set *devset = &handle->m_dev_set; - if(ioctl(devset->m_devs[0].m_fd, ioctl_op, syscall_id)) - { - return scap_errprintf(handle->m_lasterr, errno, - "%s(%d) failed for syscall %d", - __FUNCTION__, ioctl_op, syscall_id); + if(ioctl(devset->m_devs[0].m_fd, ioctl_op, syscall_id)) { + return scap_errprintf(handle->m_lasterr, + errno, + "%s(%d) failed for syscall %d", + __FUNCTION__, + ioctl_op, + syscall_id); } return SCAP_SUCCESS; } -static int enforce_sc_set(struct kmod_engine* handle) -{ +static int enforce_sc_set(struct kmod_engine *handle) { /* handle->capturing == false means that we want to disable the capture */ - bool* sc_set = handle->curr_sc_set.ppm_sc; + bool *sc_set = handle->curr_sc_set.ppm_sc; bool empty_sc_set[PPM_SC_MAX] = {0}; - if(!handle->capturing) - { + if(!handle->capturing) { /* empty set to erase all */ sc_set = empty_sc_set; } @@ -199,51 +198,36 @@ static int enforce_sc_set(struct kmod_engine* handle) /* We need to enable the socketcall under the hood in case these syscalls are not * defined on the system but we just have the socketcall code. * See https://github.com/falcosecurity/libs/pull/1128 - */ - if(sc_set[PPM_SC_RECV] || - sc_set[PPM_SC_SEND] || - sc_set[PPM_SC_ACCEPT]) - { + */ + if(sc_set[PPM_SC_RECV] || sc_set[PPM_SC_SEND] || sc_set[PPM_SC_ACCEPT]) { sc_set[PPM_SC_SOCKETCALL] = true; - } - else - { + } else { sc_set[PPM_SC_SOCKETCALL] = false; } /* Enforce interesting syscalls */ - for(int sc = 0; sc < PPM_SC_MAX; sc++) - { + for(int sc = 0; sc < PPM_SC_MAX; sc++) { syscall_id = scap_ppm_sc_to_native_id(sc); /* if `syscall_id` is -1 this is not a syscall */ - if(syscall_id == -1) - { + if(syscall_id == -1) { continue; } - if(!sc_set[sc]) - { + if(!sc_set[sc]) { ret = ret ?: mark_syscall(handle, PPM_IOCTL_DISABLE_SYSCALL, syscall_id); - } - else - { + } else { sys_enter = true; sys_exit = true; ret = ret ?: mark_syscall(handle, PPM_IOCTL_ENABLE_SYSCALL, syscall_id); } } - if(sc_set[PPM_SC_FORK] || - sc_set[PPM_SC_VFORK] || - sc_set[PPM_SC_CLONE] || - sc_set[PPM_SC_CLONE3]) - { + if(sc_set[PPM_SC_FORK] || sc_set[PPM_SC_VFORK] || sc_set[PPM_SC_CLONE] || + sc_set[PPM_SC_CLONE3]) { sched_prog_fork = true; } - if(sc_set[PPM_SC_EXECVE] || - sc_set[PPM_SC_EXECVEAT]) - { + if(sc_set[PPM_SC_EXECVE] || sc_set[PPM_SC_EXECVEAT]) { sched_prog_exec = true; } @@ -296,22 +280,19 @@ static int enforce_sc_set(struct kmod_engine* handle) return ret; } -static int32_t scap_kmod_handle_sc(struct scap_engine_handle engine, uint32_t op, uint32_t sc) -{ - struct kmod_engine* handle = engine.m_handle; +static int32_t scap_kmod_handle_sc(struct scap_engine_handle engine, uint32_t op, uint32_t sc) { + struct kmod_engine *handle = engine.m_handle; handle->curr_sc_set.ppm_sc[sc] = op == SCAP_PPM_SC_MASK_SET; /* We update the system state only if the capture is started */ - if(handle->capturing) - { + if(handle->capturing) { return enforce_sc_set(handle); } return SCAP_SUCCESS; } -int32_t scap_kmod_init(scap_t *handle, scap_open_args *oargs) -{ +int32_t scap_kmod_init(scap_t *handle, scap_open_args *oargs) { struct scap_engine_handle engine = handle->m_engine; - struct scap_kmod_engine_params* params = oargs->engine_params; + struct scap_kmod_engine_params *params = oargs->engine_params; char filename[SCAP_MAX_PATH_SIZE] = {0}; uint32_t ndevs = 0; uint32_t ncpus; @@ -322,37 +303,38 @@ int32_t scap_kmod_init(scap_t *handle, scap_open_args *oargs) uint64_t schema_version = 0; unsigned long single_buffer_dim = params->buffer_bytes_dim; - if(check_buffer_bytes_dim(handle->m_lasterr, single_buffer_dim) != SCAP_SUCCESS) - { + if(check_buffer_bytes_dim(handle->m_lasterr, single_buffer_dim) != SCAP_SUCCESS) { return SCAP_FAILURE; } /* We need to enforce the buffer dim before opening the devices * otherwise this dimension will be not set during the opening phase! */ - if(enforce_into_kmod_buffer_bytes_dim(handle, single_buffer_dim) != SCAP_SUCCESS) - { + if(enforce_into_kmod_buffer_bytes_dim(handle, single_buffer_dim) != SCAP_SUCCESS) { return SCAP_FAILURE; } ncpus = sysconf(_SC_NPROCESSORS_CONF); - if(ncpus == -1) - { - return scap_errprintf(handle->m_lasterr, errno, "cannot obtain the number of available CPUs from '_SC_NPROCESSORS_CONF'"); + if(ncpus == -1) { + return scap_errprintf( + handle->m_lasterr, + errno, + "cannot obtain the number of available CPUs from '_SC_NPROCESSORS_CONF'"); } // // Find out how many devices we have to open, which equals to the number of CPUs // ndevs = sysconf(_SC_NPROCESSORS_ONLN); - if(ndevs == -1) - { - return scap_errprintf(handle->m_lasterr, errno, "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN'"); + if(ndevs == -1) { + return scap_errprintf( + handle->m_lasterr, + errno, + "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN'"); } rc = devset_init(&HANDLE(engine)->m_dev_set, ndevs, handle->m_lasterr); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } @@ -365,87 +347,102 @@ int32_t scap_kmod_init(scap_t *handle, scap_open_args *oargs) uint32_t online_idx = 0; // devset->m_ndevs = online CPUs in the system. // ncpus = available CPUs in the system. - for(uint32_t cpu_idx = 0; online_idx < devset->m_ndevs && cpu_idx < ncpus; ++cpu_idx) - { + for(uint32_t cpu_idx = 0; online_idx < devset->m_ndevs && cpu_idx < ncpus; ++cpu_idx) { struct scap_device *dev = &devset->m_devs[online_idx]; // // Open the device // - snprintf(filename, sizeof(filename), "%s/dev/" DRIVER_DEVICE_NAME "%d", scap_get_host_root(), cpu_idx); - - if((dev->m_fd = open(filename, O_RDWR | O_SYNC)) < 0) - { - if(errno == ENODEV) - { + snprintf(filename, + sizeof(filename), + "%s/dev/" DRIVER_DEVICE_NAME "%d", + scap_get_host_root(), + cpu_idx); + + if((dev->m_fd = open(filename, O_RDWR | O_SYNC)) < 0) { + if(errno == ENODEV) { // // This CPU is offline, so we just skip it // continue; - } - else if(errno == EBUSY) - { + } else if(errno == EBUSY) { uint32_t curr_max_consumers = get_max_consumers(); - return scap_errprintf(handle->m_lasterr, 0, "Too many consumers attached to device %s. Current value for /sys/module/" SCAP_KERNEL_MODULE_NAME "/parameters/max_consumers is '%"PRIu32"'.", filename, curr_max_consumers); - } - else - { - return scap_errprintf(handle->m_lasterr, errno, "error opening device %s. Make sure you have root credentials and that the " DRIVER_NAME " module is loaded", filename); + return scap_errprintf(handle->m_lasterr, + 0, + "Too many consumers attached to device %s. Current value for " + "/sys/module/" SCAP_KERNEL_MODULE_NAME + "/parameters/max_consumers is '%" PRIu32 "'.", + filename, + curr_max_consumers); + } else { + return scap_errprintf(handle->m_lasterr, + errno, + "error opening device %s. Make sure you have root " + "credentials and that the " DRIVER_NAME " module is loaded", + filename); } } // Set close-on-exec for the fd - if (fcntl(dev->m_fd, F_SETFD, FD_CLOEXEC) == -1) { + if(fcntl(dev->m_fd, F_SETFD, FD_CLOEXEC) == -1) { int err = errno; close(dev->m_fd); - return scap_errprintf(handle->m_lasterr, err, "Can not set close-on-exec flag for fd for device %s", filename); + return scap_errprintf(handle->m_lasterr, + err, + "Can not set close-on-exec flag for fd for device %s", + filename); } // Check the API version reported - if (ioctl(dev->m_fd, PPM_IOCTL_GET_API_VERSION, &api_version) < 0) - { + if(ioctl(dev->m_fd, PPM_IOCTL_GET_API_VERSION, &api_version) < 0) { int err = errno; close(dev->m_fd); - return scap_errprintf(handle->m_lasterr, err, "Kernel module does not support PPM_IOCTL_GET_API_VERSION"); + return scap_errprintf(handle->m_lasterr, + err, + "Kernel module does not support PPM_IOCTL_GET_API_VERSION"); } // Make sure all devices report the same API version - if (HANDLE(engine)->m_api_version != 0 && HANDLE(engine)->m_api_version != api_version) - { + if(HANDLE(engine)->m_api_version != 0 && HANDLE(engine)->m_api_version != api_version) { int err = errno; close(dev->m_fd); - return scap_errprintf(handle->m_lasterr, err, "API version mismatch: device %s reports API version %llu.%llu.%llu, expected %llu.%llu.%llu", - filename, - PPM_API_VERSION_MAJOR(api_version), - PPM_API_VERSION_MINOR(api_version), - PPM_API_VERSION_PATCH(api_version), - PPM_API_VERSION_MAJOR(HANDLE(engine)->m_api_version), - PPM_API_VERSION_MINOR(HANDLE(engine)->m_api_version), - PPM_API_VERSION_PATCH(HANDLE(engine)->m_api_version) - ); + return scap_errprintf(handle->m_lasterr, + err, + "API version mismatch: device %s reports API version " + "%llu.%llu.%llu, expected %llu.%llu.%llu", + filename, + PPM_API_VERSION_MAJOR(api_version), + PPM_API_VERSION_MINOR(api_version), + PPM_API_VERSION_PATCH(api_version), + PPM_API_VERSION_MAJOR(HANDLE(engine)->m_api_version), + PPM_API_VERSION_MINOR(HANDLE(engine)->m_api_version), + PPM_API_VERSION_PATCH(HANDLE(engine)->m_api_version)); } // Set the API version from the first device // (for subsequent devices it's a no-op thanks to the check above) HANDLE(engine)->m_api_version = api_version; // Check the schema version reported - if (ioctl(dev->m_fd, PPM_IOCTL_GET_SCHEMA_VERSION, &schema_version) < 0) - { + if(ioctl(dev->m_fd, PPM_IOCTL_GET_SCHEMA_VERSION, &schema_version) < 0) { int err = errno; close(dev->m_fd); - return scap_errprintf(handle->m_lasterr, err, "Kernel module does not support PPM_IOCTL_GET_SCHEMA_VERSION"); + return scap_errprintf(handle->m_lasterr, + err, + "Kernel module does not support PPM_IOCTL_GET_SCHEMA_VERSION"); } // Make sure all devices report the same schema version - if (HANDLE(engine)->m_schema_version != 0 && HANDLE(engine)->m_schema_version != schema_version) - { - return scap_errprintf(handle->m_lasterr, 0, "Schema version mismatch: device %s reports schema version %llu.%llu.%llu, expected %llu.%llu.%llu", - filename, - PPM_API_VERSION_MAJOR(schema_version), - PPM_API_VERSION_MINOR(schema_version), - PPM_API_VERSION_PATCH(schema_version), - PPM_API_VERSION_MAJOR(HANDLE(engine)->m_schema_version), - PPM_API_VERSION_MINOR(HANDLE(engine)->m_schema_version), - PPM_API_VERSION_PATCH(HANDLE(engine)->m_schema_version) - ); + if(HANDLE(engine)->m_schema_version != 0 && + HANDLE(engine)->m_schema_version != schema_version) { + return scap_errprintf(handle->m_lasterr, + 0, + "Schema version mismatch: device %s reports schema version " + "%llu.%llu.%llu, expected %llu.%llu.%llu", + filename, + PPM_API_VERSION_MAJOR(schema_version), + PPM_API_VERSION_MINOR(schema_version), + PPM_API_VERSION_PATCH(schema_version), + PPM_API_VERSION_MAJOR(HANDLE(engine)->m_schema_version), + PPM_API_VERSION_MINOR(HANDLE(engine)->m_schema_version), + PPM_API_VERSION_PATCH(HANDLE(engine)->m_schema_version)); } // Set the schema version from the first device // (for subsequent devices it's a no-op thanks to the check above) @@ -454,20 +451,18 @@ int32_t scap_kmod_init(scap_t *handle, scap_open_args *oargs) // // Map the ring buffer // - dev->m_buffer = (char*)mmap(0, - mapped_len, - PROT_READ, - MAP_SHARED, - dev->m_fd, - 0); - - if(dev->m_buffer == MAP_FAILED) - { + dev->m_buffer = (char *)mmap(0, mapped_len, PROT_READ, MAP_SHARED, dev->m_fd, 0); + + if(dev->m_buffer == MAP_FAILED) { int err = errno; // we cleanup this fd and then we let scap_close() take care of the other ones close(dev->m_fd); - return scap_errprintf(handle->m_lasterr, err, "error mapping the ring buffer for device %s. (If you get memory allocation errors try to reduce the buffer dimension)", filename); + return scap_errprintf(handle->m_lasterr, + err, + "error mapping the ring buffer for device %s. (If you get memory " + "allocation errors try to reduce the buffer dimension)", + filename); } dev->m_buffer_size = single_buffer_dim; dev->m_mmap_size = mapped_len; @@ -475,22 +470,25 @@ int32_t scap_kmod_init(scap_t *handle, scap_open_args *oargs) // // Map the ppm_ring_buffer_info that contains the buffer pointers // - dev->m_bufinfo = (struct ppm_ring_buffer_info*)mmap(0, - sizeof(struct ppm_ring_buffer_info), - PROT_READ | PROT_WRITE, - MAP_SHARED, - dev->m_fd, - 0); - - if(dev->m_bufinfo == MAP_FAILED) - { + dev->m_bufinfo = (struct ppm_ring_buffer_info *)mmap(0, + sizeof(struct ppm_ring_buffer_info), + PROT_READ | PROT_WRITE, + MAP_SHARED, + dev->m_fd, + 0); + + if(dev->m_bufinfo == MAP_FAILED) { int err = errno; // we cleanup this fd and then we let scap_close() take care of the other ones munmap(dev->m_buffer, mapped_len); close(dev->m_fd); - return scap_errprintf(handle->m_lasterr, err, "error mapping the ring buffer info for device %s. (If you get memory allocation errors try to reduce the buffer dimension)", filename); + return scap_errprintf(handle->m_lasterr, + err, + "error mapping the ring buffer info for device %s. (If you get " + "memory allocation errors try to reduce the buffer dimension)", + filename); } dev->m_bufinfo_size = sizeof(struct ppm_ring_buffer_info); @@ -498,68 +496,75 @@ int32_t scap_kmod_init(scap_t *handle, scap_open_args *oargs) } // Check that we parsed all online CPUs - if(online_idx != devset->m_ndevs) - { - return scap_errprintf(handle->m_lasterr, 0, "mismatch, processors online after the 'for' loop: %d, '_SC_NPROCESSORS_ONLN' before the 'for' loop: %d", online_idx, devset->m_ndevs); + if(online_idx != devset->m_ndevs) { + return scap_errprintf(handle->m_lasterr, + 0, + "mismatch, processors online after the 'for' loop: %d, " + "'_SC_NPROCESSORS_ONLN' before the 'for' loop: %d", + online_idx, + devset->m_ndevs); } // Check that no CPUs were hotplugged during the for loop uint32_t final_ndevs = sysconf(_SC_NPROCESSORS_ONLN); - if(final_ndevs == -1) - { - return scap_errprintf(handle->m_lasterr, errno, "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN' to check against the previous value"); + if(final_ndevs == -1) { + return scap_errprintf(handle->m_lasterr, + errno, + "cannot obtain the number of online CPUs from '_SC_NPROCESSORS_ONLN' " + "to check against the previous value"); } - if (online_idx != final_ndevs) - { - return scap_errprintf(handle->m_lasterr, 0, "mismatch, processors online after the 'for' loop: %d, '_SC_NPROCESSORS_ONLN' after the 'for' loop: %d", online_idx, final_ndevs); + if(online_idx != final_ndevs) { + return scap_errprintf(handle->m_lasterr, + 0, + "mismatch, processors online after the 'for' loop: %d, " + "'_SC_NPROCESSORS_ONLN' after the 'for' loop: %d", + online_idx, + final_ndevs); } /* Store interesting sc codes */ - memcpy(&HANDLE(engine)->curr_sc_set, &oargs->ppm_sc_of_interest, sizeof(interesting_ppm_sc_set)); + memcpy(&HANDLE(engine)->curr_sc_set, + &oargs->ppm_sc_of_interest, + sizeof(interesting_ppm_sc_set)); return SCAP_SUCCESS; } -int32_t scap_kmod_close(struct scap_engine_handle engine) -{ +int32_t scap_kmod_close(struct scap_engine_handle engine) { struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; devset_free(devset); - - if(HANDLE(engine)->m_stats) - { + + if(HANDLE(engine)->m_stats) { free(HANDLE(engine)->m_stats); HANDLE(engine)->m_stats = NULL; } return SCAP_SUCCESS; } -int32_t scap_kmod_next(struct scap_engine_handle engine, scap_evt **pevent, uint16_t *pdevid, - uint32_t *pflags) -{ +int32_t scap_kmod_next(struct scap_engine_handle engine, + scap_evt **pevent, + uint16_t *pdevid, + uint32_t *pflags) { return ringbuffer_next(&HANDLE(engine)->m_dev_set, pevent, pdevid, pflags); } -uint32_t scap_kmod_get_n_devs(struct scap_engine_handle engine) -{ +uint32_t scap_kmod_get_n_devs(struct scap_engine_handle engine) { return HANDLE(engine)->m_dev_set.m_ndevs; } -uint64_t scap_kmod_get_max_buf_used(struct scap_engine_handle engine) -{ +uint64_t scap_kmod_get_max_buf_used(struct scap_engine_handle engine) { return ringbuffer_get_max_buf_used(&HANDLE(engine)->m_dev_set); } // // Return the number of dropped events for the given handle // -int32_t scap_kmod_get_stats(struct scap_engine_handle engine, scap_stats* stats) -{ +int32_t scap_kmod_get_stats(struct scap_engine_handle engine, scap_stats *stats) { struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; uint32_t j; - for(j = 0; j < devset->m_ndevs; j++) - { + for(j = 0; j < devset->m_ndevs; j++) { struct scap_device *dev = &devset->m_devs[j]; stats->n_evts += dev->m_bufinfo->n_evts; stats->n_drops_buffer += dev->m_bufinfo->n_drops_buffer; @@ -573,21 +578,23 @@ int32_t scap_kmod_get_stats(struct scap_engine_handle engine, scap_stats* stats) stats->n_drops_buffer_open_exit += dev->m_bufinfo->n_drops_buffer_open_exit; stats->n_drops_buffer_dir_file_enter += dev->m_bufinfo->n_drops_buffer_dir_file_enter; stats->n_drops_buffer_dir_file_exit += dev->m_bufinfo->n_drops_buffer_dir_file_exit; - stats->n_drops_buffer_other_interest_enter += dev->m_bufinfo->n_drops_buffer_other_interest_enter; - stats->n_drops_buffer_other_interest_exit += dev->m_bufinfo->n_drops_buffer_other_interest_exit; + stats->n_drops_buffer_other_interest_enter += + dev->m_bufinfo->n_drops_buffer_other_interest_enter; + stats->n_drops_buffer_other_interest_exit += + dev->m_bufinfo->n_drops_buffer_other_interest_exit; stats->n_drops_buffer_close_exit += dev->m_bufinfo->n_drops_buffer_close_exit; stats->n_drops_buffer_proc_exit += dev->m_bufinfo->n_drops_buffer_proc_exit; stats->n_drops_pf += dev->m_bufinfo->n_drops_pf; - stats->n_drops += dev->m_bufinfo->n_drops_buffer + - dev->m_bufinfo->n_drops_pf; + stats->n_drops += dev->m_bufinfo->n_drops_buffer + dev->m_bufinfo->n_drops_pf; stats->n_preemptions += dev->m_bufinfo->n_preemptions; } return SCAP_SUCCESS; } -static void set_u64_monotonic_kernel_counter(struct metrics_v2* m, uint64_t val, uint32_t metric_flag) -{ +static void set_u64_monotonic_kernel_counter(struct metrics_v2 *m, + uint64_t val, + uint32_t metric_flag) { m->type = METRIC_VALUE_TYPE_U64; m->flags = metric_flag; m->unit = METRIC_VALUE_UNIT_COUNT; @@ -595,8 +602,10 @@ static void set_u64_monotonic_kernel_counter(struct metrics_v2* m, uint64_t val, m->value.u64 = val; } -const struct metrics_v2* scap_kmod_get_stats_v2(struct scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc) -{ +const struct metrics_v2 *scap_kmod_get_stats_v2(struct scap_engine_handle engine, + uint32_t flags, + uint32_t *nstats, + int32_t *rc) { struct kmod_engine *handle = engine.m_handle; struct scap_device_set *devset = &handle->m_dev_set; @@ -604,78 +613,94 @@ const struct metrics_v2* scap_kmod_get_stats_v2(struct scap_engine_handle engine *nstats = 0; // If it is the first time we call this function, we allocate the stats - if(handle->m_stats == NULL) - { + if(handle->m_stats == NULL) { // We don't allocate space for per-cpu stats, if we don't enable them at init time. // At the moment we don't support dynamic metrics selection at runtime. uint32_t per_dev_stats = 0; - if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) - { - // The difference with other drivers is that here we consider only ONLINE CPUs and not the AVILABLE ones. - // At the moment for each ONLINE CPU we want: + if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) { + // The difference with other drivers is that here we consider only ONLINE CPUs and not + // the AVILABLE ones. At the moment for each ONLINE CPU we want: // - the number of events. // - the number of drops. - per_dev_stats = devset->m_ndevs* 2; + per_dev_stats = devset->m_ndevs * 2; } handle->m_nstats = KMOD_MAX_KERNEL_COUNTERS_STATS + per_dev_stats; - handle->m_stats = (metrics_v2*)calloc(handle->m_nstats, sizeof(metrics_v2)); - if(!handle->m_stats) - { + handle->m_stats = (metrics_v2 *)calloc(handle->m_nstats, sizeof(metrics_v2)); + if(!handle->m_stats) { handle->m_nstats = 0; - *rc = scap_errprintf(handle->m_lasterr, -1, "unable to allocate memory for 'metrics_v2' array"); + *rc = scap_errprintf(handle->m_lasterr, + -1, + "unable to allocate memory for 'metrics_v2' array"); return NULL; } } // offset in stats buffer int offset = 0; - metrics_v2* stats = handle->m_stats; + metrics_v2 *stats = handle->m_stats; /* KERNEL COUNTER STATS */ - if ((flags & METRICS_V2_KERNEL_COUNTERS)) - { - for(uint32_t stat = 0; stat < KMOD_MAX_KERNEL_COUNTERS_STATS; stat++) - { + if((flags & METRICS_V2_KERNEL_COUNTERS)) { + for(uint32_t stat = 0; stat < KMOD_MAX_KERNEL_COUNTERS_STATS; stat++) { set_u64_monotonic_kernel_counter(&(stats[stat]), 0, METRICS_V2_KERNEL_COUNTERS); - strlcpy(stats[stat].name, (char*)kmod_kernel_counters_stats_names[stat], METRIC_NAME_MAX); + strlcpy(stats[stat].name, + (char *)kmod_kernel_counters_stats_names[stat], + METRIC_NAME_MAX); } uint32_t pos = KMOD_MAX_KERNEL_COUNTERS_STATS; - for(uint32_t j = 0; j < devset->m_ndevs; j++) - { + for(uint32_t j = 0; j < devset->m_ndevs; j++) { struct scap_device *dev = &devset->m_devs[j]; stats[KMOD_N_EVTS].value.u64 += dev->m_bufinfo->n_evts; stats[KMOD_N_DROPS_BUFFER_TOTAL].value.u64 += dev->m_bufinfo->n_drops_buffer; - stats[KMOD_N_DROPS_BUFFER_CLONE_FORK_ENTER].value.u64 += dev->m_bufinfo->n_drops_buffer_clone_fork_enter; - stats[KMOD_N_DROPS_BUFFER_CLONE_FORK_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_clone_fork_exit; - stats[KMOD_N_DROPS_BUFFER_EXECVE_ENTER].value.u64 += dev->m_bufinfo->n_drops_buffer_execve_enter; - stats[KMOD_N_DROPS_BUFFER_EXECVE_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_execve_exit; - stats[KMOD_N_DROPS_BUFFER_CONNECT_ENTER].value.u64 += dev->m_bufinfo->n_drops_buffer_connect_enter; - stats[KMOD_N_DROPS_BUFFER_CONNECT_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_connect_exit; - stats[KMOD_N_DROPS_BUFFER_OPEN_ENTER].value.u64 += dev->m_bufinfo->n_drops_buffer_open_enter; - stats[KMOD_N_DROPS_BUFFER_OPEN_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_open_exit; - stats[KMOD_N_DROPS_BUFFER_DIR_FILE_ENTER].value.u64 += dev->m_bufinfo->n_drops_buffer_dir_file_enter; - stats[KMOD_N_DROPS_BUFFER_DIR_FILE_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_dir_file_exit; - stats[KMOD_N_DROPS_BUFFER_OTHER_INTEREST_ENTER].value.u64 += dev->m_bufinfo->n_drops_buffer_other_interest_enter; - stats[KMOD_N_DROPS_BUFFER_OTHER_INTEREST_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_other_interest_exit; - stats[KMOD_N_DROPS_BUFFER_CLOSE_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_close_exit; - stats[KMOD_N_DROPS_BUFFER_PROC_EXIT].value.u64 += dev->m_bufinfo->n_drops_buffer_proc_exit; + stats[KMOD_N_DROPS_BUFFER_CLONE_FORK_ENTER].value.u64 += + dev->m_bufinfo->n_drops_buffer_clone_fork_enter; + stats[KMOD_N_DROPS_BUFFER_CLONE_FORK_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_clone_fork_exit; + stats[KMOD_N_DROPS_BUFFER_EXECVE_ENTER].value.u64 += + dev->m_bufinfo->n_drops_buffer_execve_enter; + stats[KMOD_N_DROPS_BUFFER_EXECVE_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_execve_exit; + stats[KMOD_N_DROPS_BUFFER_CONNECT_ENTER].value.u64 += + dev->m_bufinfo->n_drops_buffer_connect_enter; + stats[KMOD_N_DROPS_BUFFER_CONNECT_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_connect_exit; + stats[KMOD_N_DROPS_BUFFER_OPEN_ENTER].value.u64 += + dev->m_bufinfo->n_drops_buffer_open_enter; + stats[KMOD_N_DROPS_BUFFER_OPEN_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_open_exit; + stats[KMOD_N_DROPS_BUFFER_DIR_FILE_ENTER].value.u64 += + dev->m_bufinfo->n_drops_buffer_dir_file_enter; + stats[KMOD_N_DROPS_BUFFER_DIR_FILE_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_dir_file_exit; + stats[KMOD_N_DROPS_BUFFER_OTHER_INTEREST_ENTER].value.u64 += + dev->m_bufinfo->n_drops_buffer_other_interest_enter; + stats[KMOD_N_DROPS_BUFFER_OTHER_INTEREST_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_other_interest_exit; + stats[KMOD_N_DROPS_BUFFER_CLOSE_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_close_exit; + stats[KMOD_N_DROPS_BUFFER_PROC_EXIT].value.u64 += + dev->m_bufinfo->n_drops_buffer_proc_exit; stats[KMOD_N_DROPS_PAGE_FAULTS].value.u64 += dev->m_bufinfo->n_drops_pf; - stats[KMOD_N_DROPS].value.u64 += dev->m_bufinfo->n_drops_buffer + - dev->m_bufinfo->n_drops_pf; + stats[KMOD_N_DROPS].value.u64 += + dev->m_bufinfo->n_drops_buffer + dev->m_bufinfo->n_drops_pf; stats[KMOD_N_PREEMPTIONS].value.u64 += dev->m_bufinfo->n_preemptions; - if((flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) - { + if((flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) { // We set the num events for that CPU. - set_u64_monotonic_kernel_counter(&(stats[pos]), dev->m_bufinfo->n_evts, METRICS_V2_KERNEL_COUNTERS_PER_CPU); - snprintf(stats[pos].name, METRIC_NAME_MAX, N_EVENTS_PER_DEVICE_PREFIX"%d", j); + set_u64_monotonic_kernel_counter(&(stats[pos]), + dev->m_bufinfo->n_evts, + METRICS_V2_KERNEL_COUNTERS_PER_CPU); + snprintf(stats[pos].name, METRIC_NAME_MAX, N_EVENTS_PER_DEVICE_PREFIX "%d", j); pos++; // We set the drops for that CPU. - set_u64_monotonic_kernel_counter(&(stats[pos]), dev->m_bufinfo->n_drops_buffer + dev->m_bufinfo->n_drops_pf, METRICS_V2_KERNEL_COUNTERS_PER_CPU); - snprintf(stats[pos].name, METRIC_NAME_MAX, N_DROPS_PER_DEVICE_PREFIX"%d", j); + set_u64_monotonic_kernel_counter( + &(stats[pos]), + dev->m_bufinfo->n_drops_buffer + dev->m_bufinfo->n_drops_pf, + METRICS_V2_KERNEL_COUNTERS_PER_CPU); + snprintf(stats[pos].name, METRIC_NAME_MAX, N_DROPS_PER_DEVICE_PREFIX "%d", j); pos++; } } @@ -690,15 +715,13 @@ const struct metrics_v2* scap_kmod_get_stats_v2(struct scap_engine_handle engine // // Stop capturing the events // -int32_t scap_kmod_stop_capture(struct scap_engine_handle engine) -{ - struct kmod_engine* handle = engine.m_handle; +int32_t scap_kmod_stop_capture(struct scap_engine_handle engine) { + struct kmod_engine *handle = engine.m_handle; handle->capturing = false; /* This could happen if we fail to instantiate `m_devs` in the init method */ struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; - if(devset->m_devs == NULL) - { + if(devset->m_devs == NULL) { return SCAP_SUCCESS; } return enforce_sc_set(handle); @@ -707,22 +730,19 @@ int32_t scap_kmod_stop_capture(struct scap_engine_handle engine) // // Start capturing the events // -int32_t scap_kmod_start_capture(struct scap_engine_handle engine) -{ - struct kmod_engine* handle = engine.m_handle; +int32_t scap_kmod_start_capture(struct scap_engine_handle engine) { + struct kmod_engine *handle = engine.m_handle; int32_t rc = 0; /* Here we are covering the case in which some syscalls don't have an associated ppm_sc * and so we cannot set them as (un)interesting. For this reason, we default them to 0. - * Please note this is an extra check since our ppm_sc should already cover all possible syscalls. - * Ideally we should do this only once, but right now in our code we don't have a "right" place to do it. - * We need to move it, if `scap_start_capture` will be called frequently in our flow, right now in live mode, it - * should be called only once... + * Please note this is an extra check since our ppm_sc should already cover all possible + * syscalls. Ideally we should do this only once, but right now in our code we don't have a + * "right" place to do it. We need to move it, if `scap_start_capture` will be called frequently + * in our flow, right now in live mode, it should be called only once... */ - for(int i = 0; i < SYSCALL_TABLE_SIZE; i++) - { + for(int i = 0; i < SYSCALL_TABLE_SIZE; i++) { rc = mark_syscall(handle, PPM_IOCTL_DISABLE_SYSCALL, i); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } } @@ -730,48 +750,43 @@ int32_t scap_kmod_start_capture(struct scap_engine_handle engine) return enforce_sc_set(handle); } -static int32_t scap_kmod_set_dropping_mode(struct scap_engine_handle engine, int request, uint32_t sampling_ratio) -{ +static int32_t scap_kmod_set_dropping_mode(struct scap_engine_handle engine, + int request, + uint32_t sampling_ratio) { struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; - if(devset->m_ndevs) - { + if(devset->m_ndevs) { ASSERT((request == PPM_IOCTL_ENABLE_DROPPING_MODE && - ((sampling_ratio == 1) || - (sampling_ratio == 2) || - (sampling_ratio == 4) || - (sampling_ratio == 8) || - (sampling_ratio == 16) || - (sampling_ratio == 32) || - (sampling_ratio == 64) || - (sampling_ratio == 128))) || (request == PPM_IOCTL_DISABLE_DROPPING_MODE)); - - if(ioctl(devset->m_devs[0].m_fd, request, sampling_ratio)) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "%s, request %d for sampling ratio %u", - __FUNCTION__, request, sampling_ratio); + ((sampling_ratio == 1) || (sampling_ratio == 2) || (sampling_ratio == 4) || + (sampling_ratio == 8) || (sampling_ratio == 16) || (sampling_ratio == 32) || + (sampling_ratio == 64) || (sampling_ratio == 128))) || + (request == PPM_IOCTL_DISABLE_DROPPING_MODE)); + + if(ioctl(devset->m_devs[0].m_fd, request, sampling_ratio)) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "%s, request %d for sampling ratio %u", + __FUNCTION__, + request, + sampling_ratio); } } return SCAP_SUCCESS; } -int32_t scap_kmod_stop_dropping_mode(struct scap_engine_handle engine) -{ +int32_t scap_kmod_stop_dropping_mode(struct scap_engine_handle engine) { return scap_kmod_set_dropping_mode(engine, PPM_IOCTL_DISABLE_DROPPING_MODE, 0); } -int32_t scap_kmod_start_dropping_mode(struct scap_engine_handle engine, uint32_t sampling_ratio) -{ +int32_t scap_kmod_start_dropping_mode(struct scap_engine_handle engine, uint32_t sampling_ratio) { return scap_kmod_set_dropping_mode(engine, PPM_IOCTL_ENABLE_DROPPING_MODE, sampling_ratio); } -int32_t scap_kmod_set_snaplen(struct scap_engine_handle engine, uint32_t snaplen) -{ +int32_t scap_kmod_set_snaplen(struct scap_engine_handle engine, uint32_t snaplen) { struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; // // Tell the driver to change the snaplen // - if(ioctl(devset->m_devs[0].m_fd, PPM_IOCTL_SET_SNAPLEN, snaplen)) - { + if(ioctl(devset->m_devs[0].m_fd, PPM_IOCTL_SET_SNAPLEN, snaplen)) { return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "scap_set_snaplen failed"); } @@ -780,52 +795,50 @@ int32_t scap_kmod_set_snaplen(struct scap_engine_handle engine, uint32_t snaplen // // Force a flush of the read buffers, so we don't capture events with the old snaplen // - for(j = 0; j < devset->m_ndevs; j++) - { + for(j = 0; j < devset->m_ndevs; j++) { ringbuffer_readbuf(&devset->m_devs[j], - &devset->m_devs[j].m_sn_next_event, - &devset->m_devs[j].m_sn_len); + &devset->m_devs[j].m_sn_next_event, + &devset->m_devs[j].m_sn_len); devset->m_devs[j].m_sn_len = 0; } return SCAP_SUCCESS; } -int32_t scap_kmod_handle_dropfailed(struct scap_engine_handle engine, bool enable) -{ +int32_t scap_kmod_handle_dropfailed(struct scap_engine_handle engine, bool enable) { int req = enable ? PPM_IOCTL_ENABLE_DROPFAILED : PPM_IOCTL_DISABLE_DROPFAILED; - if(ioctl(HANDLE(engine)->m_dev_set.m_devs[0].m_fd, req)) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "scap_enable_dynamic_snaplen failed"); + if(ioctl(HANDLE(engine)->m_dev_set.m_devs[0].m_fd, req)) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "scap_enable_dynamic_snaplen failed"); } return SCAP_SUCCESS; } -int32_t scap_kmod_handle_dynamic_snaplen(struct scap_engine_handle engine, bool enable) -{ +int32_t scap_kmod_handle_dynamic_snaplen(struct scap_engine_handle engine, bool enable) { // // Tell the driver to change the snaplen // int req = enable ? PPM_IOCTL_ENABLE_DYNAMIC_SNAPLEN : PPM_IOCTL_DISABLE_DYNAMIC_SNAPLEN; - if(ioctl(HANDLE(engine)->m_dev_set.m_devs[0].m_fd, req)) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "scap_enable_dynamic_snaplen failed"); + if(ioctl(HANDLE(engine)->m_dev_set.m_devs[0].m_fd, req)) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "scap_enable_dynamic_snaplen failed"); } return SCAP_SUCCESS; } -int32_t scap_kmod_get_n_tracepoint_hit(struct scap_engine_handle engine, long* ret) -{ - if(ioctl(HANDLE(engine)->m_dev_set.m_devs[0].m_fd, PPM_IOCTL_GET_N_TRACEPOINT_HIT, ret)) - { +int32_t scap_kmod_get_n_tracepoint_hit(struct scap_engine_handle engine, long *ret) { + if(ioctl(HANDLE(engine)->m_dev_set.m_devs[0].m_fd, PPM_IOCTL_GET_N_TRACEPOINT_HIT, ret)) { return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "scap_get_n_tracepoint_hit failed"); } return SCAP_SUCCESS; } -int32_t scap_kmod_set_fullcapture_port_range(struct scap_engine_handle engine, uint16_t range_start, uint16_t range_end) -{ +int32_t scap_kmod_set_fullcapture_port_range(struct scap_engine_handle engine, + uint16_t range_start, + uint16_t range_end) { struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; // // Encode the port range @@ -835,9 +848,10 @@ int32_t scap_kmod_set_fullcapture_port_range(struct scap_engine_handle engine, u // // Beam the value down to the module // - if(ioctl(devset->m_devs[0].m_fd, PPM_IOCTL_SET_FULLCAPTURE_PORT_RANGE, arg)) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "scap_set_fullcapture_port_range failed"); + if(ioctl(devset->m_devs[0].m_fd, PPM_IOCTL_SET_FULLCAPTURE_PORT_RANGE, arg)) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "scap_set_fullcapture_port_range failed"); } uint32_t j; @@ -845,11 +859,10 @@ int32_t scap_kmod_set_fullcapture_port_range(struct scap_engine_handle engine, u // // Force a flush of the read buffers, so we don't capture events with the old snaplen // - for(j = 0; j < devset->m_ndevs; j++) - { + for(j = 0; j < devset->m_ndevs; j++) { ringbuffer_readbuf(&devset->m_devs[j], - &devset->m_devs[j].m_sn_next_event, - &devset->m_devs[j].m_sn_len); + &devset->m_devs[j].m_sn_next_event, + &devset->m_devs[j].m_sn_len); devset->m_devs[j].m_sn_len = 0; } @@ -857,16 +870,15 @@ int32_t scap_kmod_set_fullcapture_port_range(struct scap_engine_handle engine, u return SCAP_SUCCESS; } -int32_t scap_kmod_set_statsd_port(struct scap_engine_handle engine, const uint16_t port) -{ +int32_t scap_kmod_set_statsd_port(struct scap_engine_handle engine, const uint16_t port) { struct scap_device_set *devset = &HANDLE(engine)->m_dev_set; // // Beam the value down to the module // - if(ioctl(devset->m_devs[0].m_fd, PPM_IOCTL_SET_STATSD_PORT, port)) - { + if(ioctl(devset->m_devs[0].m_fd, PPM_IOCTL_SET_STATSD_PORT, port)) { return scap_errprintf(HANDLE(engine)->m_lasterr, - errno, "scap_set_statsd_port: ioctl failed"); + errno, + "scap_set_statsd_port: ioctl failed"); } uint32_t j; @@ -875,11 +887,10 @@ int32_t scap_kmod_set_statsd_port(struct scap_engine_handle engine, const uint16 // Force a flush of the read buffers, so we don't // capture events with the old snaplen // - for(j = 0; j < devset->m_ndevs; j++) - { + for(j = 0; j < devset->m_ndevs; j++) { ringbuffer_readbuf(&devset->m_devs[j], - &devset->m_devs[j].m_sn_next_event, - &devset->m_devs[j].m_sn_len); + &devset->m_devs[j].m_sn_next_event, + &devset->m_devs[j].m_sn_len); devset->m_devs[j].m_sn_len = 0; } @@ -887,25 +898,22 @@ int32_t scap_kmod_set_statsd_port(struct scap_engine_handle engine, const uint16 return SCAP_SUCCESS; } -static int32_t unsupported_config(struct scap_engine_handle engine, const char* msg) -{ - struct kmod_engine* handle = engine.m_handle; +static int32_t unsupported_config(struct scap_engine_handle engine, const char *msg) { + struct kmod_engine *handle = engine.m_handle; strlcpy(handle->m_lasterr, msg, SCAP_LASTERR_SIZE); return SCAP_FAILURE; } -static int32_t configure(struct scap_engine_handle engine, enum scap_setting setting, unsigned long arg1, unsigned long arg2) -{ - switch(setting) - { +static int32_t configure(struct scap_engine_handle engine, + enum scap_setting setting, + unsigned long arg1, + unsigned long arg2) { + switch(setting) { case SCAP_SAMPLING_RATIO: - if(arg2 == 0) - { + if(arg2 == 0) { return scap_kmod_stop_dropping_mode(engine); - } - else - { + } else { return scap_kmod_start_dropping_mode(engine, arg1); } case SCAP_SNAPLEN: @@ -920,8 +928,7 @@ static int32_t configure(struct scap_engine_handle engine, enum scap_setting set return scap_kmod_set_fullcapture_port_range(engine, arg1, arg2); case SCAP_STATSD_PORT: return scap_kmod_set_statsd_port(engine, arg1); - default: - { + default: { char msg[256]; snprintf(msg, sizeof(msg), "Unsupported setting %d (args %lu, %lu)", setting, arg1, arg2); return unsupported_config(engine, msg); @@ -929,113 +936,102 @@ static int32_t configure(struct scap_engine_handle engine, enum scap_setting set } } -static int32_t scap_kmod_get_threadlist(struct scap_engine_handle engine, struct ppm_proclist_info **procinfo_p, char *lasterr) -{ - struct kmod_engine* kmod_engine = engine.m_handle; - if(*procinfo_p == NULL) - { - if(scap_alloc_proclist_info(procinfo_p, SCAP_DRIVER_PROCINFO_INITIAL_SIZE, lasterr) == false) - { +static int32_t scap_kmod_get_threadlist(struct scap_engine_handle engine, + struct ppm_proclist_info **procinfo_p, + char *lasterr) { + struct kmod_engine *kmod_engine = engine.m_handle; + if(*procinfo_p == NULL) { + if(scap_alloc_proclist_info(procinfo_p, SCAP_DRIVER_PROCINFO_INITIAL_SIZE, lasterr) == + false) { return SCAP_FAILURE; } } - int ioctlres = ioctl(kmod_engine->m_dev_set.m_devs[0].m_fd, PPM_IOCTL_GET_PROCLIST, *procinfo_p); - if(ioctlres) - { - if(errno == ENOSPC) - { - if(scap_alloc_proclist_info(procinfo_p, (*procinfo_p)->n_entries + 256, kmod_engine->m_lasterr) == false) - { + int ioctlres = + ioctl(kmod_engine->m_dev_set.m_devs[0].m_fd, PPM_IOCTL_GET_PROCLIST, *procinfo_p); + if(ioctlres) { + if(errno == ENOSPC) { + if(scap_alloc_proclist_info(procinfo_p, + (*procinfo_p)->n_entries + 256, + kmod_engine->m_lasterr) == false) { return SCAP_FAILURE; - } - else - { + } else { return scap_kmod_get_threadlist(engine, procinfo_p, lasterr); } - } - else - { - return scap_errprintf(kmod_engine->m_lasterr, errno, "Error calling PPM_IOCTL_GET_PROCLIST"); + } else { + return scap_errprintf(kmod_engine->m_lasterr, + errno, + "Error calling PPM_IOCTL_GET_PROCLIST"); } } return SCAP_SUCCESS; } - -static int32_t scap_kmod_get_vpid(struct scap_engine_handle engine, uint64_t pid, int64_t* vpid) -{ +static int32_t scap_kmod_get_vpid(struct scap_engine_handle engine, uint64_t pid, int64_t *vpid) { struct kmod_engine *kmod_engine = engine.m_handle; *vpid = ioctl(kmod_engine->m_dev_set.m_devs[0].m_fd, PPM_IOCTL_GET_VPID, pid); - if(*vpid == -1) - { + if(*vpid == -1) { return scap_errprintf(kmod_engine->m_lasterr, errno, "ioctl to get vpid failed"); } return SCAP_SUCCESS; } -static int32_t scap_kmod_get_vtid(struct scap_engine_handle engine, uint64_t tid, int64_t* vtid) -{ +static int32_t scap_kmod_get_vtid(struct scap_engine_handle engine, uint64_t tid, int64_t *vtid) { struct kmod_engine *kmod_engine = engine.m_handle; *vtid = ioctl(kmod_engine->m_dev_set.m_devs[0].m_fd, PPM_IOCTL_GET_VTID, tid); - if(*vtid == -1) - { + if(*vtid == -1) { return scap_errprintf(kmod_engine->m_lasterr, errno, "ioctl to get vtid failed"); } return SCAP_SUCCESS; } -int32_t scap_kmod_getpid_global(struct scap_engine_handle engine, int64_t* pid, char* error) -{ +int32_t scap_kmod_getpid_global(struct scap_engine_handle engine, int64_t *pid, char *error) { struct kmod_engine *kmod_engine = engine.m_handle; *pid = ioctl(kmod_engine->m_dev_set.m_devs[0].m_fd, PPM_IOCTL_GET_CURRENT_PID); - if(*pid == -1) - { + if(*pid == -1) { return scap_errprintf(kmod_engine->m_lasterr, errno, "ioctl to get pid failed"); } return SCAP_SUCCESS; } -uint64_t scap_kmod_get_api_version(struct scap_engine_handle engine) -{ +uint64_t scap_kmod_get_api_version(struct scap_engine_handle engine) { return HANDLE(engine)->m_api_version; } -uint64_t scap_kmod_get_schema_version(struct scap_engine_handle engine) -{ +uint64_t scap_kmod_get_schema_version(struct scap_engine_handle engine) { return HANDLE(engine)->m_schema_version; } const struct scap_linux_vtable scap_kmod_linux_vtable = { - .get_vpid = scap_kmod_get_vpid, - .get_vtid = scap_kmod_get_vtid, - .getpid_global = scap_kmod_getpid_global, - .get_threadlist = scap_kmod_get_threadlist, + .get_vpid = scap_kmod_get_vpid, + .get_vtid = scap_kmod_get_vtid, + .getpid_global = scap_kmod_getpid_global, + .get_threadlist = scap_kmod_get_threadlist, }; struct scap_vtable scap_kmod_engine = { - .name = KMOD_ENGINE, - .savefile_ops = NULL, - - .alloc_handle = alloc_handle, - .init = scap_kmod_init, - .free_handle = free_handle, - .close = scap_kmod_close, - .next = scap_kmod_next, - .start_capture = scap_kmod_start_capture, - .stop_capture = scap_kmod_stop_capture, - .configure = configure, - .get_stats = scap_kmod_get_stats, - .get_stats_v2 = scap_kmod_get_stats_v2, - .get_n_tracepoint_hit = scap_kmod_get_n_tracepoint_hit, - .get_n_devs = scap_kmod_get_n_devs, - .get_max_buf_used = scap_kmod_get_max_buf_used, - .get_api_version = scap_kmod_get_api_version, - .get_schema_version = scap_kmod_get_schema_version, + .name = KMOD_ENGINE, + .savefile_ops = NULL, + + .alloc_handle = alloc_handle, + .init = scap_kmod_init, + .free_handle = free_handle, + .close = scap_kmod_close, + .next = scap_kmod_next, + .start_capture = scap_kmod_start_capture, + .stop_capture = scap_kmod_stop_capture, + .configure = configure, + .get_stats = scap_kmod_get_stats, + .get_stats_v2 = scap_kmod_get_stats_v2, + .get_n_tracepoint_hit = scap_kmod_get_n_tracepoint_hit, + .get_n_devs = scap_kmod_get_n_devs, + .get_max_buf_used = scap_kmod_get_max_buf_used, + .get_api_version = scap_kmod_get_api_version, + .get_schema_version = scap_kmod_get_schema_version, }; diff --git a/userspace/libscap/engine/kmod/scap_kmod_stats.h b/userspace/libscap/engine/kmod/scap_kmod_stats.h index bd2b531e1f..c65214b172 100644 --- a/userspace/libscap/engine/kmod/scap_kmod_stats.h +++ b/userspace/libscap/engine/kmod/scap_kmod_stats.h @@ -40,4 +40,4 @@ typedef enum kmod_kernel_counters_stats { KMOD_N_DROPS, KMOD_N_PREEMPTIONS, KMOD_MAX_KERNEL_COUNTERS_STATS -}kmod_kernel_counters_stats; +} kmod_kernel_counters_stats; diff --git a/userspace/libscap/engine/modern_bpf/CMakeLists.txt b/userspace/libscap/engine/modern_bpf/CMakeLists.txt index 3817e68c53..991fcdc7ab 100644 --- a/userspace/libscap/engine/modern_bpf/CMakeLists.txt +++ b/userspace/libscap/engine/modern_bpf/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # message(STATUS "Build modern BPF engine") option(USE_BUNDLED_MODERN_BPF "use bundled modern BPF" ON) @@ -21,40 +19,42 @@ set(MODERN_BPF_LOG_PREFIX "[MODERN BPF]") # Include `libbpf` library. include(libbpf RESULT_VARIABLE RESULT) if(RESULT STREQUAL NOTFOUND) - message(FATAL_ERROR "problem with libbpf.cmake in ${CMAKE_MODULE_PATH}") + message(FATAL_ERROR "problem with libbpf.cmake in ${CMAKE_MODULE_PATH}") endif() -# This will be the name of the final `bpf.o` file. We put it here this way -# we can log it even if `USE_BUNDLED_MODERN_BPF` is `OFF` +# This will be the name of the final `bpf.o` file. We put it here this way we can log it even if +# `USE_BUNDLED_MODERN_BPF` is `OFF` set(UNIQUE_BPF_O_FILE_NAME bpf_probe) # This must be a dir because we use it as an include path if(NOT MODERN_BPF_SKEL_DIR) - # Directory in which the BPF skeleton will be built - set(MODERN_BPF_SKEL_DIR "${CMAKE_BINARY_DIR}/skel_dir") - file(MAKE_DIRECTORY ${MODERN_BPF_SKEL_DIR}) - # Build the BPF skeleton as custom target. - add_subdirectory(${LIBS_DIR}/driver/modern_bpf ${CMAKE_BINARY_DIR}/driver/modern_bpf) + # Directory in which the BPF skeleton will be built + set(MODERN_BPF_SKEL_DIR "${CMAKE_BINARY_DIR}/skel_dir") + file(MAKE_DIRECTORY ${MODERN_BPF_SKEL_DIR}) + # Build the BPF skeleton as custom target. + add_subdirectory(${LIBS_DIR}/driver/modern_bpf ${CMAKE_BINARY_DIR}/driver/modern_bpf) else() - set(USE_BUNDLED_MODERN_BPF OFF) - # If it is a relative path we convert it to an absolute one relative to the root source directory. - get_filename_component(MODERN_BPF_SKEL_DIR "${MODERN_BPF_SKEL_DIR}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}") + set(USE_BUNDLED_MODERN_BPF OFF) + # If it is a relative path we convert it to an absolute one relative to the root source + # directory. + get_filename_component( + MODERN_BPF_SKEL_DIR "${MODERN_BPF_SKEL_DIR}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}" + ) endif() -message(STATUS "${MODERN_BPF_LOG_PREFIX} USE_BUNDLED_MODERN_BPF: ${USE_BUNDLED_MODERN_BPF}, using skeleton dir: ${MODERN_BPF_SKEL_DIR}") -message(STATUS "${MODERN_BPF_LOG_PREFIX} full skeleton path: ${MODERN_BPF_SKEL_DIR}/${UNIQUE_BPF_O_FILE_NAME}.skel.h") +message( + STATUS + "${MODERN_BPF_LOG_PREFIX} USE_BUNDLED_MODERN_BPF: ${USE_BUNDLED_MODERN_BPF}, using skeleton dir: ${MODERN_BPF_SKEL_DIR}" +) +message( + STATUS + "${MODERN_BPF_LOG_PREFIX} full skeleton path: ${MODERN_BPF_SKEL_DIR}/${UNIQUE_BPF_O_FILE_NAME}.skel.h" +) # Build `libpman` library. add_subdirectory(${LIBS_DIR}/userspace/libpman ${CMAKE_BINARY_DIR}/libpman) -add_library(scap_engine_modern_bpf - scap_modern_bpf.c -) +add_library(scap_engine_modern_bpf scap_modern_bpf.c) -target_link_libraries(scap_engine_modern_bpf -PRIVATE - pman - scap_engine_util - scap_engine_noop -) +target_link_libraries(scap_engine_modern_bpf PRIVATE pman scap_engine_util scap_engine_noop) set_scap_target_properties(scap_engine_modern_bpf) diff --git a/userspace/libscap/engine/modern_bpf/modern_bpf_public.h b/userspace/libscap/engine/modern_bpf/modern_bpf_public.h index 66c8a1226b..e45f1a9070 100644 --- a/userspace/libscap/engine/modern_bpf/modern_bpf_public.h +++ b/userspace/libscap/engine/modern_bpf/modern_bpf_public.h @@ -20,16 +20,24 @@ limitations under the License. #define DEFAULT_CPU_FOR_EACH_BUFFER 1 #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - struct scap_modern_bpf_engine_params - { - uint16_t cpus_for_each_buffer; ///< [EXPERIMENTAL] We will allocate a ring buffer every `cpus_for_each_buffer` CPUs. `0` is a special value and means a single ring buffer shared between all the CPUs. - bool allocate_online_only; ///< [EXPERIMENTAL] Allocate ring buffers only for online CPUs. The number of ring buffers allocated changes according to the `cpus_for_each_buffer` param. Please note: this buffer will be mapped twice both kernel and userspace-side, so pay attention to its size. - unsigned long buffer_bytes_dim; ///< Dimension of a ring buffer in bytes. The number of ring buffers allocated changes according to the `cpus_for_each_buffer` param. Please note: this buffer will be mapped twice both kernel and userspace-side, so pay attention to its size. - }; +struct scap_modern_bpf_engine_params { + uint16_t cpus_for_each_buffer; ///< [EXPERIMENTAL] We will allocate a ring buffer every + ///< `cpus_for_each_buffer` CPUs. `0` is a special value and + ///< means a single ring buffer shared between all the CPUs. + bool allocate_online_only; ///< [EXPERIMENTAL] Allocate ring buffers only for online CPUs. The + ///< number of ring buffers allocated changes according to the + ///< `cpus_for_each_buffer` param. Please note: this buffer will be + ///< mapped twice both kernel and userspace-side, so pay attention + ///< to its size. + unsigned long + buffer_bytes_dim; ///< Dimension of a ring buffer in bytes. The number of ring buffers + ///< allocated changes according to the `cpus_for_each_buffer` param. + ///< Please note: this buffer will be mapped twice both kernel and + ///< userspace-side, so pay attention to its size. +}; #ifdef __cplusplus }; diff --git a/userspace/libscap/engine/modern_bpf/scap_modern_bpf.c b/userspace/libscap/engine/modern_bpf/scap_modern_bpf.c index 5de44d58a3..55b4876385 100644 --- a/userspace/libscap/engine/modern_bpf/scap_modern_bpf.c +++ b/userspace/libscap/engine/modern_bpf/scap_modern_bpf.c @@ -35,81 +35,76 @@ limitations under the License. #include #include -static void* scap_modern_bpf__alloc_engine(scap_t* main_handle, char* lasterr_ptr) -{ +static void* scap_modern_bpf__alloc_engine(scap_t* main_handle, char* lasterr_ptr) { struct modern_bpf_engine* engine = calloc(1, sizeof(struct modern_bpf_engine)); - if(engine) - { + if(engine) { engine->m_lasterr = lasterr_ptr; } return engine; } -static void scap_modern_bpf__free_engine(struct scap_engine_handle engine) -{ +static void scap_modern_bpf__free_engine(struct scap_engine_handle engine) { free(engine.m_handle); } -/* The third parameter is not the CPU number from which we extract the event but the ring buffer number. - * For the old BPF probe and the kernel module the number of CPUs is equal to the number of buffers since we always use a per-CPU approach. +/* The third parameter is not the CPU number from which we extract the event but the ring buffer + * number. For the old BPF probe and the kernel module the number of CPUs is equal to the number of + * buffers since we always use a per-CPU approach. */ -static int32_t scap_modern_bpf__next(struct scap_engine_handle engine, scap_evt** pevent, uint16_t* buffer_id, - uint32_t* pflags) -{ +static int32_t scap_modern_bpf__next(struct scap_engine_handle engine, + scap_evt** pevent, + uint16_t* buffer_id, + uint32_t* pflags) { pman_consume_first_event((void**)pevent, (int16_t*)buffer_id); - if((*pevent) == NULL) - { - /* The first time we sleep 500 us, if we have consecutive timeouts we can reach also 30 ms. */ + if((*pevent) == NULL) { + /* The first time we sleep 500 us, if we have consecutive timeouts we can reach also 30 ms. + */ usleep(HANDLE(engine)->m_retry_us); - HANDLE(engine)->m_retry_us = MIN(HANDLE(engine)->m_retry_us * 2, BUFFER_EMPTY_WAIT_TIME_US_MAX); + HANDLE(engine)->m_retry_us = + MIN(HANDLE(engine)->m_retry_us * 2, BUFFER_EMPTY_WAIT_TIME_US_MAX); return SCAP_TIMEOUT; - } - else - { + } else { HANDLE(engine)->m_retry_us = BUFFER_EMPTY_WAIT_TIME_US_START; } *pflags = 0; return SCAP_SUCCESS; } -static int32_t scap_modern_bpf_start_dropping_mode(struct scap_engine_handle engine, uint32_t sampling_ratio) -{ +static int32_t scap_modern_bpf_start_dropping_mode(struct scap_engine_handle engine, + uint32_t sampling_ratio) { pman_set_sampling_ratio(sampling_ratio); pman_set_dropping_mode(true); return SCAP_SUCCESS; } -int32_t scap_modern_bpf_stop_dropping_mode() -{ +int32_t scap_modern_bpf_stop_dropping_mode() { pman_set_sampling_ratio(1); pman_set_dropping_mode(false); return SCAP_SUCCESS; } -static int32_t scap_modern_bpf_handle_sc(struct scap_engine_handle engine, uint32_t op, uint32_t sc) -{ +static int32_t scap_modern_bpf_handle_sc(struct scap_engine_handle engine, + uint32_t op, + uint32_t sc) { struct modern_bpf_engine* handle = engine.m_handle; handle->curr_sc_set.ppm_sc[sc] = op == SCAP_PPM_SC_MASK_SET; /* We update the system state only if the capture is started */ - if(handle->capturing) - { + if(handle->capturing) { return pman_enforce_sc_set(handle->curr_sc_set.ppm_sc); } return SCAP_SUCCESS; } -static int32_t scap_modern_bpf__configure(struct scap_engine_handle engine, enum scap_setting setting, unsigned long arg1, unsigned long arg2) -{ - switch(setting) - { +static int32_t scap_modern_bpf__configure(struct scap_engine_handle engine, + enum scap_setting setting, + unsigned long arg1, + unsigned long arg2) { + switch(setting) { case SCAP_SAMPLING_RATIO: - if(arg2 == 0) - { + if(arg2 == 0) { return scap_modern_bpf_stop_dropping_mode(); - } - else - { + } else { return scap_modern_bpf_start_dropping_mode(engine, arg1); } case SCAP_SNAPLEN: @@ -129,8 +124,7 @@ static int32_t scap_modern_bpf__configure(struct scap_engine_handle engine, enum case SCAP_STATSD_PORT: pman_set_statsd_port(arg1); break; - default: - { + default: { char msg[SCAP_LASTERR_SIZE]; snprintf(msg, sizeof(msg), "Unsupported setting %d (args %lu, %lu)", setting, arg1, arg2); struct modern_bpf_engine* handle = engine.m_handle; @@ -142,34 +136,30 @@ static int32_t scap_modern_bpf__configure(struct scap_engine_handle engine, enum return SCAP_SUCCESS; } -int32_t scap_modern_bpf__start_capture(struct scap_engine_handle engine) -{ +int32_t scap_modern_bpf__start_capture(struct scap_engine_handle engine) { struct modern_bpf_engine* handle = engine.m_handle; /* Here we are covering the case in which some syscalls don't have an associated ppm_sc * and so we cannot set them as (un)interesting. For this reason, we default them to 0. - * Please note this is an extra check since our ppm_sc should already cover all possible syscalls. - * Ideally we should do this only once, but right now in our code we don't have a "right" place to do it. - * We need to move it, if `scap_start_capture` will be called frequently in our flow, right now in live mode, it - * should be called only once... + * Please note this is an extra check since our ppm_sc should already cover all possible + * syscalls. Ideally we should do this only once, but right now in our code we don't have a + * "right" place to do it. We need to move it, if `scap_start_capture` will be called frequently + * in our flow, right now in live mode, it should be called only once... */ - for(int i = 0; i < SYSCALL_TABLE_SIZE; i++) - { + for(int i = 0; i < SYSCALL_TABLE_SIZE; i++) { pman_mark_single_64bit_syscall(i, false); } handle->capturing = true; return pman_enforce_sc_set(handle->curr_sc_set.ppm_sc); } -int32_t scap_modern_bpf__stop_capture(struct scap_engine_handle engine) -{ +int32_t scap_modern_bpf__stop_capture(struct scap_engine_handle engine) { struct modern_bpf_engine* handle = engine.m_handle; handle->capturing = false; /* NULL is equivalent to an empty array */ return pman_enforce_sc_set(NULL); } -static int32_t calibrate_socket_file_ops(struct scap_engine_handle engine) -{ +static int32_t calibrate_socket_file_ops(struct scap_engine_handle engine) { /* Set the scap_tid for the socket calibration. * If we are in a container this is the virtual tid. */ @@ -178,22 +168,25 @@ static int32_t calibrate_socket_file_ops(struct scap_engine_handle engine) /* We just need to enable the socket syscall for the socket calibration */ HANDLE(engine)->curr_sc_set.ppm_sc[PPM_SC_SOCKET] = 1; - if(scap_modern_bpf__start_capture(engine) != SCAP_SUCCESS) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "unable to start the capture for the socket calibration"); + if(scap_modern_bpf__start_capture(engine) != SCAP_SUCCESS) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "unable to start the capture for the socket calibration"); } int fd = socket(AF_INET, SOCK_DGRAM, 0); - if(fd == -1) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "unable to create a socket for the calibration"); + if(fd == -1) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "unable to create a socket for the calibration"); } close(fd); /* We need to stop the capture */ - if(scap_modern_bpf__stop_capture(engine) != SCAP_SUCCESS) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, errno, "unable to stop the capture after the calibration"); + if(scap_modern_bpf__stop_capture(engine) != SCAP_SUCCESS) { + return scap_errprintf(HANDLE(engine)->m_lasterr, + errno, + "unable to stop the capture after the calibration"); } /* We need to read the socket event from the buffer */ @@ -204,40 +197,36 @@ static int32_t calibrate_socket_file_ops(struct scap_engine_handle engine) int32_t res = 0; bool found = false; - while(attempts <= 1) - { + while(attempts <= 1) { res = scap_modern_bpf__next(engine, &pevent, &buffer_id, &flags); - if(res == SCAP_SUCCESS && pevent != NULL) - { + if(res == SCAP_SUCCESS && pevent != NULL) { /* This is not a socket event or this is not our socket event */ - if(pevent->type != PPME_SOCKET_SOCKET_X || pevent->tid != scap_tid) - { + if(pevent->type != PPME_SOCKET_SOCKET_X || pevent->tid != scap_tid) { continue; } /* BPF side we send this special event with nparams = 0 */ - if(pevent->nparams == 0) - { + if(pevent->nparams == 0) { /* We don't want to stop here because we want to clean all the buffers. */ found = true; } - } - else if(res == SCAP_TIMEOUT) - { - /* We need more than one attempt because the first time we just need to read the producers' positions. */ + } else if(res == SCAP_TIMEOUT) { + /* We need more than one attempt because the first time we just need to read the + * producers' positions. */ attempts++; } } - if(!found) - { - return scap_errprintf(HANDLE(engine)->m_lasterr, 0, "unable to find the socket event for the calibration in the ringbuffers"); + if(!found) { + return scap_errprintf( + HANDLE(engine)->m_lasterr, + 0, + "unable to find the socket event for the calibration in the ringbuffers"); } return SCAP_SUCCESS; } -int32_t scap_modern_bpf__init(scap_t* handle, scap_open_args* oargs) -{ +int32_t scap_modern_bpf__init(scap_t* handle, scap_open_args* oargs) { int ret = 0; struct scap_engine_handle engine = handle->m_engine; struct scap_modern_bpf_engine_params* params = oargs->engine_params; @@ -248,13 +237,11 @@ int32_t scap_modern_bpf__init(scap_t* handle, scap_open_args* oargs) * - check the ring-buffer dimension in bytes. * - check the presence of ring buffer and of BTF. */ - if(check_buffer_bytes_dim(handle->m_lasterr, params->buffer_bytes_dim) != SCAP_SUCCESS) - { + if(check_buffer_bytes_dim(handle->m_lasterr, params->buffer_bytes_dim) != SCAP_SUCCESS) { return ENOTSUP; } - if(!pman_check_support()) - { + if(!pman_check_support()) { return ENOTSUP; } @@ -262,8 +249,10 @@ int32_t scap_modern_bpf__init(scap_t* handle, scap_open_args* oargs) * Validation of `cpus_for_each_buffer` is made inside libpman * since this is the unique place where we have the number of CPUs */ - if(pman_init_state(oargs->log_fn, params->buffer_bytes_dim, params->cpus_for_each_buffer, params->allocate_online_only)) - { + if(pman_init_state(oargs->log_fn, + params->buffer_bytes_dim, + params->cpus_for_each_buffer, + params->allocate_online_only)) { snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "unable to configure the libpman state."); return SCAP_FAILURE; } @@ -278,113 +267,103 @@ int32_t scap_modern_bpf__init(scap_t* handle, scap_open_args* oargs) ret = ret ?: pman_load_probe(); ret = ret ?: pman_finalize_maps_after_loading(); ret = ret ?: pman_finalize_ringbuf_array_after_loading(); - if(ret != SCAP_SUCCESS) - { + if(ret != SCAP_SUCCESS) { return ret; } /* Set the boot time */ uint64_t boot_time = 0; - if(scap_get_precise_boot_time(handle->m_lasterr, &boot_time) != SCAP_SUCCESS) - { + if(scap_get_precise_boot_time(handle->m_lasterr, &boot_time) != SCAP_SUCCESS) { return SCAP_FAILURE; } pman_set_boot_time(boot_time); /* Calibrate the socket at init time */ - if(calibrate_socket_file_ops(engine) != SCAP_SUCCESS) - { + if(calibrate_socket_file_ops(engine) != SCAP_SUCCESS) { return SCAP_FAILURE; } /* Store interesting sc codes */ - memcpy(&HANDLE(engine)->curr_sc_set, &oargs->ppm_sc_of_interest, sizeof(interesting_ppm_sc_set)); + memcpy(&HANDLE(engine)->curr_sc_set, + &oargs->ppm_sc_of_interest, + sizeof(interesting_ppm_sc_set)); HANDLE(engine)->m_api_version = pman_get_probe_api_ver(); HANDLE(engine)->m_schema_version = pman_get_probe_schema_ver(); HANDLE(engine)->m_flags = 0; - if(scap_get_bpf_stats_enabled()) - { + if(scap_get_bpf_stats_enabled()) { HANDLE(engine)->m_flags |= ENGINE_FLAG_BPF_STATS_ENABLED; } return SCAP_SUCCESS; } -static uint64_t scap_modern_bpf__get_flags(struct scap_engine_handle engine) -{ +static uint64_t scap_modern_bpf__get_flags(struct scap_engine_handle engine) { return HANDLE(engine)->m_flags; } -int32_t scap_modern_bpf__close(struct scap_engine_handle engine) -{ +int32_t scap_modern_bpf__close(struct scap_engine_handle engine) { pman_close_probe(); return SCAP_SUCCESS; } -static uint32_t scap_modern_bpf__get_n_devs(struct scap_engine_handle engine) -{ +static uint32_t scap_modern_bpf__get_n_devs(struct scap_engine_handle engine) { return pman_get_required_buffers(); } -int32_t scap_modern_bpf__get_stats(struct scap_engine_handle engine, scap_stats* stats) -{ - if(pman_get_scap_stats(stats)) - { +int32_t scap_modern_bpf__get_stats(struct scap_engine_handle engine, scap_stats* stats) { + if(pman_get_scap_stats(stats)) { return SCAP_FAILURE; } return SCAP_SUCCESS; } -const struct metrics_v2* scap_modern_bpf__get_stats_v2(struct scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc) -{ +const struct metrics_v2* scap_modern_bpf__get_stats_v2(struct scap_engine_handle engine, + uint32_t flags, + uint32_t* nstats, + int32_t* rc) { struct modern_bpf_engine* handle = engine.m_handle; - if (!(handle->m_flags & ENGINE_FLAG_BPF_STATS_ENABLED)) - { + if(!(handle->m_flags & ENGINE_FLAG_BPF_STATS_ENABLED)) { // we can't collect libbpf stats if bpf stats are not enabled flags &= ~METRICS_V2_LIBBPF_STATS; } return pman_get_metrics_v2(flags, nstats, rc); } -int32_t scap_modern_bpf__get_n_tracepoint_hit(struct scap_engine_handle engine, long* ret) -{ - if(pman_get_n_tracepoint_hit(ret)) - { +int32_t scap_modern_bpf__get_n_tracepoint_hit(struct scap_engine_handle engine, long* ret) { + if(pman_get_n_tracepoint_hit(ret)) { return SCAP_FAILURE; } return SCAP_SUCCESS; } -uint64_t scap_modern_bpf__get_api_version(struct scap_engine_handle engine) -{ +uint64_t scap_modern_bpf__get_api_version(struct scap_engine_handle engine) { return HANDLE(engine)->m_api_version; } -uint64_t scap_modern_bpf__get_schema_version(struct scap_engine_handle engine) -{ +uint64_t scap_modern_bpf__get_schema_version(struct scap_engine_handle engine) { return HANDLE(engine)->m_schema_version; } struct scap_vtable scap_modern_bpf_engine = { - .name = MODERN_BPF_ENGINE, - .savefile_ops = NULL, - - .alloc_handle = scap_modern_bpf__alloc_engine, - .init = scap_modern_bpf__init, - .get_flags = scap_modern_bpf__get_flags, - .free_handle = scap_modern_bpf__free_engine, - .close = scap_modern_bpf__close, - .next = scap_modern_bpf__next, - .start_capture = scap_modern_bpf__start_capture, - .stop_capture = scap_modern_bpf__stop_capture, - .configure = scap_modern_bpf__configure, - .get_stats = scap_modern_bpf__get_stats, - .get_stats_v2 = scap_modern_bpf__get_stats_v2, - .get_n_tracepoint_hit = scap_modern_bpf__get_n_tracepoint_hit, - .get_n_devs = scap_modern_bpf__get_n_devs, - .get_max_buf_used = noop_get_max_buf_used, - .get_api_version = scap_modern_bpf__get_api_version, - .get_schema_version = scap_modern_bpf__get_schema_version, + .name = MODERN_BPF_ENGINE, + .savefile_ops = NULL, + + .alloc_handle = scap_modern_bpf__alloc_engine, + .init = scap_modern_bpf__init, + .get_flags = scap_modern_bpf__get_flags, + .free_handle = scap_modern_bpf__free_engine, + .close = scap_modern_bpf__close, + .next = scap_modern_bpf__next, + .start_capture = scap_modern_bpf__start_capture, + .stop_capture = scap_modern_bpf__stop_capture, + .configure = scap_modern_bpf__configure, + .get_stats = scap_modern_bpf__get_stats, + .get_stats_v2 = scap_modern_bpf__get_stats_v2, + .get_n_tracepoint_hit = scap_modern_bpf__get_n_tracepoint_hit, + .get_n_devs = scap_modern_bpf__get_n_devs, + .get_max_buf_used = noop_get_max_buf_used, + .get_api_version = scap_modern_bpf__get_api_version, + .get_schema_version = scap_modern_bpf__get_schema_version, }; diff --git a/userspace/libscap/engine/modern_bpf/scap_modern_bpf.h b/userspace/libscap/engine/modern_bpf/scap_modern_bpf.h index 2f3130a52c..7ab4688b7c 100644 --- a/userspace/libscap/engine/modern_bpf/scap_modern_bpf.h +++ b/userspace/libscap/engine/modern_bpf/scap_modern_bpf.h @@ -26,10 +26,9 @@ limitations under the License. struct scap; -struct modern_bpf_engine -{ - unsigned long m_retry_us; /* Microseconds to wait if all ring buffers are empty */ - char* m_lasterr; /* Last error caught by the engine */ +struct modern_bpf_engine { + unsigned long m_retry_us; /* Microseconds to wait if all ring buffers are empty */ + char* m_lasterr; /* Last error caught by the engine */ interesting_ppm_sc_set curr_sc_set; /* current ppm_sc */ uint64_t m_api_version; uint64_t m_schema_version; diff --git a/userspace/libscap/engine/nodriver/CMakeLists.txt b/userspace/libscap/engine/nodriver/CMakeLists.txt index 6de050fb15..302011d08a 100644 --- a/userspace/libscap/engine/nodriver/CMakeLists.txt +++ b/userspace/libscap/engine/nodriver/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # add_library(scap_engine_nodriver nodriver.c) target_link_libraries(scap_engine_nodriver PRIVATE scap_engine_noop) diff --git a/userspace/libscap/engine/nodriver/nodriver.c b/userspace/libscap/engine/nodriver/nodriver.c index 81d51b47cb..32bfe0f575 100644 --- a/userspace/libscap/engine/nodriver/nodriver.c +++ b/userspace/libscap/engine/nodriver/nodriver.c @@ -29,23 +29,22 @@ limitations under the License. #include #include -static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) -{ - struct nodriver_engine *engine = calloc(1, sizeof(struct nodriver_engine)); - if(engine) - { +static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) { + struct nodriver_engine* engine = calloc(1, sizeof(struct nodriver_engine)); + if(engine) { engine->m_lasterr = lasterr_ptr; } return engine; } -static int32_t init(scap_t* handle, scap_open_args *oargs) -{ +static int32_t init(scap_t* handle, scap_open_args* oargs) { return SCAP_SUCCESS; } -static int32_t next(struct scap_engine_handle handle, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags) -{ +static int32_t next(struct scap_engine_handle handle, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags) { static scap_evt evt; evt.len = 0; evt.tid = -1; @@ -62,22 +61,22 @@ static int32_t next(struct scap_engine_handle handle, scap_evt** pevent, uint16_ } const struct scap_vtable scap_nodriver_engine = { - .name = NODRIVER_ENGINE, - .savefile_ops = NULL, + .name = NODRIVER_ENGINE, + .savefile_ops = NULL, - .alloc_handle = alloc_handle, - .init = init, - .free_handle = noop_free_handle, - .close = noop_close_engine, - .next = next, - .start_capture = noop_start_capture, - .stop_capture = noop_stop_capture, - .configure = noop_configure, - .get_stats = noop_get_stats, - .get_stats_v2 = noop_get_stats_v2, - .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, - .get_n_devs = noop_get_n_devs, - .get_max_buf_used = noop_get_max_buf_used, - .get_api_version = NULL, - .get_schema_version = NULL, + .alloc_handle = alloc_handle, + .init = init, + .free_handle = noop_free_handle, + .close = noop_close_engine, + .next = next, + .start_capture = noop_start_capture, + .stop_capture = noop_stop_capture, + .configure = noop_configure, + .get_stats = noop_get_stats, + .get_stats_v2 = noop_get_stats_v2, + .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, + .get_n_devs = noop_get_n_devs, + .get_max_buf_used = noop_get_max_buf_used, + .get_api_version = NULL, + .get_schema_version = NULL, }; diff --git a/userspace/libscap/engine/nodriver/nodriver.h b/userspace/libscap/engine/nodriver/nodriver.h index 3ae3928212..d167d2cdd7 100644 --- a/userspace/libscap/engine/nodriver/nodriver.h +++ b/userspace/libscap/engine/nodriver/nodriver.h @@ -21,7 +21,6 @@ limitations under the License. struct scap; -struct nodriver_engine -{ +struct nodriver_engine { char* m_lasterr; }; diff --git a/userspace/libscap/engine/noop/CMakeLists.txt b/userspace/libscap/engine/noop/CMakeLists.txt index a1b379f8ed..3bb2bfee4c 100644 --- a/userspace/libscap/engine/noop/CMakeLists.txt +++ b/userspace/libscap/engine/noop/CMakeLists.txt @@ -2,27 +2,23 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # add_library(scap_engine_noop STATIC noop.c) -target_include_directories(scap_engine_noop -PUBLIC - $ - $ - $ -INTERFACE - $ +target_include_directories( + scap_engine_noop + PUBLIC $ $ + $ + INTERFACE $ ) add_dependencies(scap_engine_noop uthash) diff --git a/userspace/libscap/engine/noop/noop.c b/userspace/libscap/engine/noop/noop.c index 12d5a61fbc..5a0f998ac1 100644 --- a/userspace/libscap/engine/noop/noop.c +++ b/userspace/libscap/engine/noop/noop.c @@ -19,9 +19,8 @@ limitations under the License. #include #include -struct noop_engine -{ - char *m_lasterr; +struct noop_engine { + char* m_lasterr; }; #define HANDLE(engine) ((struct noop_engine*)(engine.m_handle)) @@ -30,102 +29,96 @@ struct noop_engine #include #include -void* noop_alloc_handle(scap_t* main_handle, char* lasterr_ptr) -{ - struct noop_engine *engine = calloc(1, sizeof(struct noop_engine)); - if(engine) - { +void* noop_alloc_handle(scap_t* main_handle, char* lasterr_ptr) { + struct noop_engine* engine = calloc(1, sizeof(struct noop_engine)); + if(engine) { engine->m_lasterr = lasterr_ptr; } return engine; } -void noop_free_handle(struct scap_engine_handle engine) -{ +void noop_free_handle(struct scap_engine_handle engine) { free(engine.m_handle); } -int noop_close_engine(struct scap_engine_handle engine) -{ +int noop_close_engine(struct scap_engine_handle engine) { return SCAP_SUCCESS; } -int32_t noop_next(struct scap_engine_handle handle, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags) -{ +int32_t noop_next(struct scap_engine_handle handle, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags) { return SCAP_EOF; } -int32_t noop_start_capture(struct scap_engine_handle engine) -{ +int32_t noop_start_capture(struct scap_engine_handle engine) { return SCAP_SUCCESS; } -int32_t noop_stop_capture(struct scap_engine_handle engine) -{ +int32_t noop_stop_capture(struct scap_engine_handle engine) { return SCAP_SUCCESS; } -int32_t unimplemented_op(char* err, size_t err_size) -{ +int32_t unimplemented_op(char* err, size_t err_size) { strlcpy(err, "Operation not implemented", err_size); return SCAP_FAILURE; } -int32_t noop_configure(struct scap_engine_handle engine, enum scap_setting setting, unsigned long arg1, unsigned long arg2) -{ +int32_t noop_configure(struct scap_engine_handle engine, + enum scap_setting setting, + unsigned long arg1, + unsigned long arg2) { // the open path disables dropping mode so report success even if we // don't really support it - if(setting == SCAP_SAMPLING_RATIO && arg2 == 0) - { + if(setting == SCAP_SAMPLING_RATIO && arg2 == 0) { return SCAP_SUCCESS; } return unimplemented_op(HANDLE(engine)->m_lasterr, SCAP_LASTERR_SIZE); } -int32_t noop_get_stats(struct scap_engine_handle engine, scap_stats* stats) -{ +int32_t noop_get_stats(struct scap_engine_handle engine, scap_stats* stats) { return SCAP_SUCCESS; } -const struct metrics_v2* noop_get_stats_v2(struct scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc) -{ +const struct metrics_v2* noop_get_stats_v2(struct scap_engine_handle engine, + uint32_t flags, + uint32_t* nstats, + int32_t* rc) { *rc = SCAP_SUCCESS; *nstats = 0; return NULL; } -int32_t noop_get_n_tracepoint_hit(struct scap_engine_handle engine, long* ret) -{ +int32_t noop_get_n_tracepoint_hit(struct scap_engine_handle engine, long* ret) { return SCAP_NOT_SUPPORTED; } -uint32_t noop_get_n_devs(struct scap_engine_handle engine) -{ +uint32_t noop_get_n_devs(struct scap_engine_handle engine) { return SCAP_SUCCESS; } -uint64_t noop_get_max_buf_used(struct scap_engine_handle engine) -{ +uint64_t noop_get_max_buf_used(struct scap_engine_handle engine) { return SCAP_SUCCESS; } const struct scap_vtable scap_noop_engine = { - .name = "noop", - .savefile_ops = NULL, - - .alloc_handle = noop_alloc_handle, - .init = NULL, - .free_handle = noop_free_handle, - .close = noop_close_engine, - .next = noop_next, - .start_capture = noop_start_capture, - .stop_capture = noop_stop_capture, - .configure = noop_configure, - .get_stats = noop_get_stats, - .get_stats_v2 = noop_get_stats_v2, - .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, - .get_n_devs = noop_get_n_devs, - .get_max_buf_used = noop_get_max_buf_used, - .get_api_version = NULL, - .get_schema_version = NULL, + .name = "noop", + .savefile_ops = NULL, + + .alloc_handle = noop_alloc_handle, + .init = NULL, + .free_handle = noop_free_handle, + .close = noop_close_engine, + .next = noop_next, + .start_capture = noop_start_capture, + .stop_capture = noop_stop_capture, + .configure = noop_configure, + .get_stats = noop_get_stats, + .get_stats_v2 = noop_get_stats_v2, + .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, + .get_n_devs = noop_get_n_devs, + .get_max_buf_used = noop_get_max_buf_used, + .get_api_version = NULL, + .get_schema_version = NULL, }; diff --git a/userspace/libscap/engine/noop/noop.h b/userspace/libscap/engine/noop/noop.h index 4e62505a66..9c05fabd56 100644 --- a/userspace/libscap/engine/noop/noop.h +++ b/userspace/libscap/engine/noop/noop.h @@ -29,13 +29,22 @@ typedef struct metrics_v2 metrics_v2; void* noop_alloc_handle(scap_t* main_handle, char* lasterr_ptr); void noop_free_handle(struct scap_engine_handle engine); int noop_close_engine(struct scap_engine_handle engine); -int32_t noop_next(struct scap_engine_handle handle, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags); +int32_t noop_next(struct scap_engine_handle handle, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags); int32_t noop_start_capture(struct scap_engine_handle engine); int32_t noop_stop_capture(struct scap_engine_handle engine); int32_t unimplemented_op(char* err, size_t err_size); -int32_t noop_configure(struct scap_engine_handle engine, enum scap_setting setting, unsigned long arg1, unsigned long arg2); +int32_t noop_configure(struct scap_engine_handle engine, + enum scap_setting setting, + unsigned long arg1, + unsigned long arg2); int32_t noop_get_stats(struct scap_engine_handle engine, scap_stats* stats); -const struct metrics_v2* noop_get_stats_v2(struct scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc); +const struct metrics_v2* noop_get_stats_v2(struct scap_engine_handle engine, + uint32_t flags, + uint32_t* nstats, + int32_t* rc); int32_t noop_get_n_tracepoint_hit(struct scap_engine_handle engine, long* ret); uint32_t noop_get_n_devs(struct scap_engine_handle engine); uint64_t noop_get_max_buf_used(struct scap_engine_handle engine); diff --git a/userspace/libscap/engine/savefile/CMakeLists.txt b/userspace/libscap/engine/savefile/CMakeLists.txt index 37d5ae6074..66c03778c5 100644 --- a/userspace/libscap/engine/savefile/CMakeLists.txt +++ b/userspace/libscap/engine/savefile/CMakeLists.txt @@ -2,30 +2,19 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -# Since we have circular dependencies between libscap and the savefile engine, -# make this library always static (directly linked into libscap) -add_library(scap_engine_savefile STATIC - scap_savefile.c - scap_reader_gzfile.c - scap_reader_buffered.c -) +# Since we have circular dependencies between libscap and the savefile engine, make this library +# always static (directly linked into libscap) +add_library(scap_engine_savefile STATIC scap_savefile.c scap_reader_gzfile.c scap_reader_buffered.c) add_dependencies(scap_engine_savefile zlib) -target_link_libraries(scap_engine_savefile -PRIVATE - scap_engine_noop - scap_platform_util - ${ZLIB_LIB} -) +target_link_libraries(scap_engine_savefile PRIVATE scap_engine_noop scap_platform_util ${ZLIB_LIB}) diff --git a/userspace/libscap/engine/savefile/savefile.h b/userspace/libscap/engine/savefile/savefile.h index 7067f147b6..d68c43bf63 100644 --- a/userspace/libscap/engine/savefile/savefile.h +++ b/userspace/libscap/engine/savefile/savefile.h @@ -24,37 +24,43 @@ limitations under the License. #include #include -#define READER_BUF_SIZE (1 << 16) // UINT16_MAX + 1, ie: 65536 - -#define CHECK_READ_SIZE_ERR(read_size, expected_size, error) if(read_size != expected_size) \ - {\ - snprintf(error, SCAP_LASTERR_SIZE, "expecting %d bytes, read %d at %s, line %d. Is the file truncated?",\ - (int)expected_size,\ - (int)read_size,\ - __FILE__,\ - __LINE__);\ - return SCAP_FAILURE;\ +#define READER_BUF_SIZE (1 << 16) // UINT16_MAX + 1, ie: 65536 + +#define CHECK_READ_SIZE_ERR(read_size, expected_size, error) \ + if(read_size != expected_size) { \ + snprintf(error, \ + SCAP_LASTERR_SIZE, \ + "expecting %d bytes, read %d at %s, line %d. Is the file truncated?", \ + (int)expected_size, \ + (int)read_size, \ + __FILE__, \ + __LINE__); \ + return SCAP_FAILURE; \ } -#define CHECK_READ_SIZE(read_size, expected_size) if(read_size != expected_size) \ - {\ - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "expecting %d bytes, read %d at %s, line %d. Is the file truncated?",\ - (int)expected_size,\ - (int)read_size,\ - __FILE__,\ - __LINE__);\ - return SCAP_FAILURE;\ +#define CHECK_READ_SIZE(read_size, expected_size) \ + if(read_size != expected_size) { \ + snprintf(handle->m_lasterr, \ + SCAP_LASTERR_SIZE, \ + "expecting %d bytes, read %d at %s, line %d. Is the file truncated?", \ + (int)expected_size, \ + (int)read_size, \ + __FILE__, \ + __LINE__); \ + return SCAP_FAILURE; \ } -#define CHECK_READ_SIZE_WITH_FREE_ERR(alloc_buffer, read_size, expected_size, error) if(read_size != expected_size) \ - {\ - snprintf(error, SCAP_LASTERR_SIZE, "expecting %d bytes, read %d at %s, line %d. Is the file truncated?",\ - (int)expected_size,\ - (int)read_size,\ - __FILE__,\ - __LINE__);\ - free(alloc_buffer);\ - return SCAP_FAILURE;\ +#define CHECK_READ_SIZE_WITH_FREE_ERR(alloc_buffer, read_size, expected_size, error) \ + if(read_size != expected_size) { \ + snprintf(error, \ + SCAP_LASTERR_SIZE, \ + "expecting %d bytes, read %d at %s, line %d. Is the file truncated?", \ + (int)expected_size, \ + (int)read_size, \ + __FILE__, \ + __LINE__); \ + free(alloc_buffer); \ + return SCAP_FAILURE; \ } // @@ -70,35 +76,32 @@ limitations under the License. /*! \brief For backward compatibility only */ -typedef struct scap_ifinfo_ipv4_nolinkspeed -{ +typedef struct scap_ifinfo_ipv4_nolinkspeed { uint16_t type; uint16_t ifnamelen; uint32_t addr; uint32_t netmask; uint32_t bcast; char ifname[SCAP_MAX_PATH_SIZE]; -}scap_ifinfo_ipv4_nolinkspeed; +} scap_ifinfo_ipv4_nolinkspeed; /*! \brief For backword compatibility only */ -typedef struct scap_ifinfo_ipv6_nolinkspeed -{ +typedef struct scap_ifinfo_ipv6_nolinkspeed { uint16_t type; uint16_t ifnamelen; char addr[SCAP_IPV6_ADDR_LEN]; char netmask[SCAP_IPV6_ADDR_LEN]; char bcast[SCAP_IPV6_ADDR_LEN]; char ifname[SCAP_MAX_PATH_SIZE]; -}scap_ifinfo_ipv6_nolinkspeed; +} scap_ifinfo_ipv6_nolinkspeed; #pragma pack(pop) struct scap_platform; -struct savefile_engine -{ +struct savefile_engine { char* m_lasterr; scap_reader_t* m_reader; block_header m_last_block_header; @@ -108,4 +111,3 @@ struct savefile_engine uint32_t m_last_evt_dump_flags; struct scap_platform* m_platform; }; - diff --git a/userspace/libscap/engine/savefile/savefile_platform.h b/userspace/libscap/engine/savefile/savefile_platform.h index 80d04a626e..f056613c97 100644 --- a/userspace/libscap/engine/savefile/savefile_platform.h +++ b/userspace/libscap/engine/savefile/savefile_platform.h @@ -20,7 +20,6 @@ limitations under the License. #include -struct scap_savefile_platform -{ +struct scap_savefile_platform { struct scap_platform m_generic; }; diff --git a/userspace/libscap/engine/savefile/savefile_public.h b/userspace/libscap/engine/savefile/savefile_public.h index f1471e464d..c2a6a0c1ad 100644 --- a/userspace/libscap/engine/savefile/savefile_public.h +++ b/userspace/libscap/engine/savefile/savefile_public.h @@ -20,23 +20,23 @@ limitations under the License. #define SAVEFILE_ENGINE "savefile" #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - struct scap_platform; +struct scap_platform; - struct scap_savefile_engine_params - { - int fd; ///< If non-zero, will be used instead of fname. - const char* fname; ///< The name of the file to open. - uint64_t start_offset; ///< Used to start reading a capture file from an arbitrary offset. This is leveraged when opening merged files. - uint32_t fbuffer_size; ///< If non-zero, offline captures will read from file using a buffer of this size. +struct scap_savefile_engine_params { + int fd; ///< If non-zero, will be used instead of fname. + const char* fname; ///< The name of the file to open. + uint64_t start_offset; ///< Used to start reading a capture file from an arbitrary offset. This + ///< is leveraged when opening merged files. + uint32_t fbuffer_size; ///< If non-zero, offline captures will read from file using a buffer of + ///< this size. - struct scap_platform* platform; - }; + struct scap_platform* platform; +}; - struct scap_platform* scap_savefile_alloc_platform(proc_entry_callback proc_callback, - void* proc_callback_context); +struct scap_platform* scap_savefile_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context); #ifdef __cplusplus }; diff --git a/userspace/libscap/engine/savefile/scap_reader.h b/userspace/libscap/engine/savefile/scap_reader.h index 22dd0e3200..bb83c65ac4 100644 --- a/userspace/libscap/engine/savefile/scap_reader.h +++ b/userspace/libscap/engine/savefile/scap_reader.h @@ -29,59 +29,57 @@ limitations under the License. extern "C" { #endif - /** * @brief Represents a reader for data in SCAP format */ -typedef struct scap_reader -{ - /** - * @brief The internal state of each implementation. - */ - void* handle; - - /** - * @brief Reads at most len bytes into buf from the given reader. - * On success, returns the number of bytes read. On failure, - * returns 0 or a negative value, and error() can be used to - * retrieve the error. - */ - int (*read)(struct scap_reader *r, void* buf, uint32_t len); - - /** - * @brief Returns the current offset in the data being read. - * On error, returns a negative value and error() can be used to - * retrieve the error. - */ - int64_t (*offset)(struct scap_reader *r); - - /** - * @brief Returns the starting position for the next read(). - * On error, returns a negative value and error() can be used to - * retrieve the error. - */ - int64_t (*tell)(struct scap_reader *r); - - /** - * @brief Sets the starting position for the next read(). - * The whence parameter is defined as in lseek(2) and the support - * to each whence type is implementation-specific. - * On error, returns a negative value and error() can be used to - * retrieve the error. - */ - int64_t (*seek)(struct scap_reader *r, int64_t offset, int whence); - - /** - * @brief Returns the message and number for the last error occurred. - * If there is no error, errnum is set to 0. The message and the - * error number representations are implementation-specific. - */ - const char* (*error)(struct scap_reader *r, int *errnum); - - /** - * @brief Closes the reader and de-allocates it. - */ - int (*close)(struct scap_reader *r); +typedef struct scap_reader { + /** + * @brief The internal state of each implementation. + */ + void *handle; + + /** + * @brief Reads at most len bytes into buf from the given reader. + * On success, returns the number of bytes read. On failure, + * returns 0 or a negative value, and error() can be used to + * retrieve the error. + */ + int (*read)(struct scap_reader *r, void *buf, uint32_t len); + + /** + * @brief Returns the current offset in the data being read. + * On error, returns a negative value and error() can be used to + * retrieve the error. + */ + int64_t (*offset)(struct scap_reader *r); + + /** + * @brief Returns the starting position for the next read(). + * On error, returns a negative value and error() can be used to + * retrieve the error. + */ + int64_t (*tell)(struct scap_reader *r); + + /** + * @brief Sets the starting position for the next read(). + * The whence parameter is defined as in lseek(2) and the support + * to each whence type is implementation-specific. + * On error, returns a negative value and error() can be used to + * retrieve the error. + */ + int64_t (*seek)(struct scap_reader *r, int64_t offset, int whence); + + /** + * @brief Returns the message and number for the last error occurred. + * If there is no error, errnum is set to 0. The message and the + * error number representations are implementation-specific. + */ + const char *(*error)(struct scap_reader *r, int *errnum); + + /** + * @brief Closes the reader and de-allocates it. + */ + int (*close)(struct scap_reader *r); } scap_reader_t; /** @@ -97,8 +95,7 @@ scap_reader_t *scap_reader_open_gzfile(gzFile file); * @param own_reader if true, the wrapped reader will be closed and de-allocated * using its close() function when the buffered reader gets closed. */ -scap_reader_t *scap_reader_open_buffered(scap_reader_t* reader, uint32_t bufsize, bool own_reader); - +scap_reader_t *scap_reader_open_buffered(scap_reader_t *reader, uint32_t bufsize, bool own_reader); #ifdef __cplusplus } diff --git a/userspace/libscap/engine/savefile/scap_reader_buffered.c b/userspace/libscap/engine/savefile/scap_reader_buffered.c index a2692ed832..bddd76f29b 100644 --- a/userspace/libscap/engine/savefile/scap_reader_buffered.c +++ b/userspace/libscap/engine/savefile/scap_reader_buffered.c @@ -19,129 +19,112 @@ limitations under the License. #include #include -typedef struct reader_handle -{ - bool m_close_reader; ///< Whether the reader should be closed - bool m_has_err; ///< True if the most recent m_reader operation had an error - uint8_t* m_buffer; ///< The buffer used to read data from m_reader - uint32_t m_buffer_cap; ///< The physical size of the buffer - uint32_t m_buffer_len; ///< The number of bytes used in the buffer - uint32_t m_buffer_off; ///< The cursor position in the buffer - int64_t m_offset; ///< The cursor position in the underlying reader - scap_reader_t* m_reader; ///< The reader to read from in buffered mode +typedef struct reader_handle { + bool m_close_reader; ///< Whether the reader should be closed + bool m_has_err; ///< True if the most recent m_reader operation had an error + uint8_t* m_buffer; ///< The buffer used to read data from m_reader + uint32_t m_buffer_cap; ///< The physical size of the buffer + uint32_t m_buffer_len; ///< The number of bytes used in the buffer + uint32_t m_buffer_off; ///< The cursor position in the buffer + int64_t m_offset; ///< The cursor position in the underlying reader + scap_reader_t* m_reader; ///< The reader to read from in buffered mode } reader_handle_t; -static int buffered_read(scap_reader_t *r, void* buf, uint32_t len) -{ - ASSERT(r != NULL); - reader_handle_t* h = (reader_handle_t*) r->handle; - uint8_t* buf_bytes = (uint8_t*) buf; - uint32_t size = 0; - uint32_t buffer_len = 0; - while (len > 0 && !h->m_has_err) - { - if (h->m_buffer_off >= h->m_buffer_len) - { - int nread = h->m_reader->read(h->m_reader, h->m_buffer, h->m_buffer_cap); - if (nread <= 0) - { - // invalidate next read - h->m_has_err = true; - return buf_bytes - (uint8_t*) buf; - } - h->m_offset += nread; - h->m_buffer_off = 0; - h->m_buffer_len = (uint32_t) nread; - } - buffer_len = h->m_buffer_len - h->m_buffer_off; - size = len < buffer_len ? len : buffer_len; - memcpy(buf_bytes, h->m_buffer + h->m_buffer_off, size); - buf_bytes += size; - h->m_buffer_off += size; - len -= size; - } - return buf_bytes - (uint8_t*) buf; +static int buffered_read(scap_reader_t* r, void* buf, uint32_t len) { + ASSERT(r != NULL); + reader_handle_t* h = (reader_handle_t*)r->handle; + uint8_t* buf_bytes = (uint8_t*)buf; + uint32_t size = 0; + uint32_t buffer_len = 0; + while(len > 0 && !h->m_has_err) { + if(h->m_buffer_off >= h->m_buffer_len) { + int nread = h->m_reader->read(h->m_reader, h->m_buffer, h->m_buffer_cap); + if(nread <= 0) { + // invalidate next read + h->m_has_err = true; + return buf_bytes - (uint8_t*)buf; + } + h->m_offset += nread; + h->m_buffer_off = 0; + h->m_buffer_len = (uint32_t)nread; + } + buffer_len = h->m_buffer_len - h->m_buffer_off; + size = len < buffer_len ? len : buffer_len; + memcpy(buf_bytes, h->m_buffer + h->m_buffer_off, size); + buf_bytes += size; + h->m_buffer_off += size; + len -= size; + } + return buf_bytes - (uint8_t*)buf; } -static int64_t buffered_offset(scap_reader_t *r) -{ - ASSERT(r != NULL); - reader_handle_t* h = (reader_handle_t*) r->handle; - return h->m_offset; +static int64_t buffered_offset(scap_reader_t* r) { + ASSERT(r != NULL); + reader_handle_t* h = (reader_handle_t*)r->handle; + return h->m_offset; } -static int64_t buffered_tell(scap_reader_t *r) -{ - ASSERT(r != NULL); - reader_handle_t* h = (reader_handle_t*) r->handle; - return h->m_offset - h->m_buffer_len + h->m_buffer_off; +static int64_t buffered_tell(scap_reader_t* r) { + ASSERT(r != NULL); + reader_handle_t* h = (reader_handle_t*)r->handle; + return h->m_offset - h->m_buffer_len + h->m_buffer_off; } -static int64_t buffered_seek(scap_reader_t *r, int64_t offset, int whence) -{ - ASSERT(r != NULL); - reader_handle_t* h = (reader_handle_t*) r->handle; - if (whence == SEEK_CUR) - { - if (offset < 0 && h->m_buffer_off >= (uint32_t) (offset * -1)) - { - h->m_buffer_off -= (uint32_t) (offset * -1); - return r->tell(r); - } - else if (offset > 0 && h->m_buffer_len >= h->m_buffer_off + (uint32_t) offset) - { - h->m_buffer_off += (uint32_t) offset; - return r->tell(r); - } - } - h->m_buffer_off = 0; - h->m_buffer_len = 0; - h->m_offset = h->m_reader->seek(h->m_reader, offset, whence); - return h->m_offset; +static int64_t buffered_seek(scap_reader_t* r, int64_t offset, int whence) { + ASSERT(r != NULL); + reader_handle_t* h = (reader_handle_t*)r->handle; + if(whence == SEEK_CUR) { + if(offset < 0 && h->m_buffer_off >= (uint32_t)(offset * -1)) { + h->m_buffer_off -= (uint32_t)(offset * -1); + return r->tell(r); + } else if(offset > 0 && h->m_buffer_len >= h->m_buffer_off + (uint32_t)offset) { + h->m_buffer_off += (uint32_t)offset; + return r->tell(r); + } + } + h->m_buffer_off = 0; + h->m_buffer_len = 0; + h->m_offset = h->m_reader->seek(h->m_reader, offset, whence); + return h->m_offset; } -static const char* buffered_error(scap_reader_t *r, int *errnum) -{ - ASSERT(r != NULL); - reader_handle_t* h = (reader_handle_t*) r->handle; - return h->m_reader->error(h->m_reader, errnum); +static const char* buffered_error(scap_reader_t* r, int* errnum) { + ASSERT(r != NULL); + reader_handle_t* h = (reader_handle_t*)r->handle; + return h->m_reader->error(h->m_reader, errnum); } -static int buffered_close(scap_reader_t *r) -{ - ASSERT(r != NULL); - reader_handle_t* h = (reader_handle_t*) r->handle; - int res = 0; - if (h->m_close_reader) - { - res = h->m_reader->close(h->m_reader); - } - free(h->m_buffer); - free(h); - free(r); - return res; +static int buffered_close(scap_reader_t* r) { + ASSERT(r != NULL); + reader_handle_t* h = (reader_handle_t*)r->handle; + int res = 0; + if(h->m_close_reader) { + res = h->m_reader->close(h->m_reader); + } + free(h->m_buffer); + free(h); + free(r); + return res; } -scap_reader_t *scap_reader_open_buffered(scap_reader_t* reader, uint32_t bufsize, bool own_reader) -{ - if (reader == NULL || bufsize == 0) - { - return NULL; - } +scap_reader_t* scap_reader_open_buffered(scap_reader_t* reader, uint32_t bufsize, bool own_reader) { + if(reader == NULL || bufsize == 0) { + return NULL; + } - reader_handle_t* h = (reader_handle_t *) calloc (1, sizeof (reader_handle_t)); - h->m_close_reader = own_reader; - h->m_reader = reader; - h->m_buffer = (uint8_t*) malloc (sizeof(uint8_t) * bufsize); - h->m_buffer_cap = bufsize; + reader_handle_t* h = (reader_handle_t*)calloc(1, sizeof(reader_handle_t)); + h->m_close_reader = own_reader; + h->m_reader = reader; + h->m_buffer = (uint8_t*)malloc(sizeof(uint8_t) * bufsize); + h->m_buffer_cap = bufsize; - scap_reader_t* r = (scap_reader_t *) malloc (sizeof (scap_reader_t)); - r->handle = h; - r->read = &buffered_read; - r->offset = &buffered_offset; - r->tell = &buffered_tell; - r->seek = &buffered_seek; - r->error = &buffered_error; - r->close = &buffered_close; - return r; + scap_reader_t* r = (scap_reader_t*)malloc(sizeof(scap_reader_t)); + r->handle = h; + r->read = &buffered_read; + r->offset = &buffered_offset; + r->tell = &buffered_tell; + r->seek = &buffered_seek; + r->error = &buffered_error; + r->close = &buffered_close; + return r; } diff --git a/userspace/libscap/engine/savefile/scap_reader_gzfile.c b/userspace/libscap/engine/savefile/scap_reader_gzfile.c index add7e2ecdf..c73357a8f9 100644 --- a/userspace/libscap/engine/savefile/scap_reader_gzfile.c +++ b/userspace/libscap/engine/savefile/scap_reader_gzfile.c @@ -18,82 +18,71 @@ limitations under the License. #include -typedef struct reader_handle -{ - gzFile m_file; ///< The file to read data from +typedef struct reader_handle { + gzFile m_file; ///< The file to read data from } reader_handle_t; -static int gzfile_read(scap_reader_t *r, void* buf, uint32_t len) -{ - ASSERT(r != NULL); - int readsize = gzread(((reader_handle_t*)r->handle)->m_file, buf, len); - - if (readsize < (int)len && readsize != -1) - { - int errnum; - gzerror(((reader_handle_t*)r->handle)->m_file, &errnum); - if (errnum == Z_OK || errnum == Z_BUF_ERROR) - { - // We've reached the end of input. This isn't necessarily an - // error, e.g. if we're tailing a file that's being written by - // another process, so allow for retries. - gzclearerr(((reader_handle_t*)r->handle)->m_file); - } - } - - return readsize; +static int gzfile_read(scap_reader_t *r, void *buf, uint32_t len) { + ASSERT(r != NULL); + int readsize = gzread(((reader_handle_t *)r->handle)->m_file, buf, len); + + if(readsize < (int)len && readsize != -1) { + int errnum; + gzerror(((reader_handle_t *)r->handle)->m_file, &errnum); + if(errnum == Z_OK || errnum == Z_BUF_ERROR) { + // We've reached the end of input. This isn't necessarily an + // error, e.g. if we're tailing a file that's being written by + // another process, so allow for retries. + gzclearerr(((reader_handle_t *)r->handle)->m_file); + } + } + + return readsize; } -static int64_t gzfile_offset(scap_reader_t *r) -{ - ASSERT(r != NULL); - return gzoffset(((reader_handle_t*)r->handle)->m_file); +static int64_t gzfile_offset(scap_reader_t *r) { + ASSERT(r != NULL); + return gzoffset(((reader_handle_t *)r->handle)->m_file); } -static int64_t gzfile_tell(scap_reader_t *r) -{ - ASSERT(r != NULL); - return gztell(((reader_handle_t*)r->handle)->m_file); +static int64_t gzfile_tell(scap_reader_t *r) { + ASSERT(r != NULL); + return gztell(((reader_handle_t *)r->handle)->m_file); } -static int64_t gzfile_seek(scap_reader_t *r, int64_t offset, int whence) -{ - ASSERT(r != NULL); - return gzseek(((reader_handle_t*)r->handle)->m_file, offset, whence); +static int64_t gzfile_seek(scap_reader_t *r, int64_t offset, int whence) { + ASSERT(r != NULL); + return gzseek(((reader_handle_t *)r->handle)->m_file, offset, whence); } -static const char* gzfile_error(scap_reader_t *r, int *errnum) -{ - ASSERT(r != NULL); - return gzerror(((reader_handle_t*)r->handle)->m_file, errnum); +static const char *gzfile_error(scap_reader_t *r, int *errnum) { + ASSERT(r != NULL); + return gzerror(((reader_handle_t *)r->handle)->m_file, errnum); } -static int gzfile_close(scap_reader_t *r) -{ - ASSERT(r != NULL); - int res = gzclose(((reader_handle_t*)r->handle)->m_file); - free(r->handle); - free(r); - return res; +static int gzfile_close(scap_reader_t *r) { + ASSERT(r != NULL); + int res = gzclose(((reader_handle_t *)r->handle)->m_file); + free(r->handle); + free(r); + return res; } -scap_reader_t *scap_reader_open_gzfile(gzFile file) -{ - if (file == NULL) - { - return NULL; - } - - reader_handle_t* h = (reader_handle_t *) malloc (sizeof (reader_handle_t)); - h->m_file = file; - - scap_reader_t* r = (scap_reader_t *) malloc (sizeof (scap_reader_t)); - r->handle = h; - r->read = &gzfile_read; - r->offset = &gzfile_offset; - r->tell = &gzfile_tell; - r->seek = &gzfile_seek; - r->error = &gzfile_error; - r->close = &gzfile_close; - return r; +scap_reader_t *scap_reader_open_gzfile(gzFile file) { + if(file == NULL) { + return NULL; + } + + reader_handle_t *h = (reader_handle_t *)malloc(sizeof(reader_handle_t)); + h->m_file = file; + + scap_reader_t *r = (scap_reader_t *)malloc(sizeof(scap_reader_t)); + r->handle = h; + r->read = &gzfile_read; + r->offset = &gzfile_offset; + r->tell = &gzfile_tell; + r->seek = &gzfile_seek; + r->error = &gzfile_error; + r->close = &gzfile_close; + return r; } diff --git a/userspace/libscap/engine/savefile/scap_savefile.c b/userspace/libscap/engine/savefile/scap_savefile.c index 1fbb0eae4e..4cc444b8dc 100644 --- a/userspace/libscap/engine/savefile/scap_savefile.c +++ b/userspace/libscap/engine/savefile/scap_savefile.c @@ -16,7 +16,6 @@ limitations under the License. */ - #include #include @@ -25,12 +24,12 @@ limitations under the License. #include #else struct iovec { - void *iov_base; /* Starting address */ - size_t iov_len; /* Number of bytes to transfer */ + void *iov_base; /* Starting address */ + size_t iov_len; /* Number of bytes to transfer */ }; #endif -#define HANDLE(engine) ((struct savefile_engine*)(engine.m_handle)) +#define HANDLE(engine) ((struct savefile_engine *)(engine.m_handle)) #include #include @@ -46,11 +45,11 @@ struct iovec { // // Read the section header block // -inline static int read_block_header(struct savefile_engine* handle, struct scap_reader *r, block_header* h) -{ +inline static int read_block_header(struct savefile_engine *handle, + struct scap_reader *r, + block_header *h) { int res = sizeof(block_header); - if (!handle->m_use_last_block_header) - { + if(!handle->m_use_last_block_header) { res = r->read(r, &handle->m_last_block_header, sizeof(block_header)); } memcpy(h, &handle->m_last_block_header, sizeof(block_header)); @@ -61,14 +60,14 @@ inline static int read_block_header(struct savefile_engine* handle, struct scap_ // // Load the machine info block // -static int32_t scap_read_machine_info(scap_reader_t* r, scap_machine_info* machine_info, char* error, uint32_t block_length) -{ +static int32_t scap_read_machine_info(scap_reader_t *r, + scap_machine_info *machine_info, + char *error, + uint32_t block_length) { // // Read the section header block // - if(r->read(r, machine_info, sizeof(*machine_info)) != - sizeof(*machine_info)) - { + if(r->read(r, machine_info, sizeof(*machine_info)) != sizeof(*machine_info)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading from file (1)"); return SCAP_FAILURE; } @@ -79,8 +78,11 @@ static int32_t scap_read_machine_info(scap_reader_t* r, scap_machine_info* machi // // Parse a process list block // -static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint32_t block_type, struct scap_proclist *proclist, char *error) -{ +static int32_t scap_read_proclist(scap_reader_t *r, + uint32_t block_length, + uint32_t block_type, + struct scap_proclist *proclist, + char *error) { size_t readsize; size_t subreadsize = 0; size_t totreadsize = 0; @@ -90,8 +92,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 uint32_t toread; int fseekres; - while(((int32_t)block_length - (int32_t)totreadsize) >= 4) - { + while(((int32_t)block_length - (int32_t)totreadsize) >= 4) { struct scap_threadinfo tinfo; tinfo.fdlist = NULL; @@ -129,8 +130,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // len // uint32_t sub_len = 0; - switch(block_type) - { + switch(block_type) { case PL_BLOCK_TYPE_V1: case PL_BLOCK_TYPE_V1_INT: case PL_BLOCK_TYPE_V2: @@ -179,8 +179,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 subreadsize += readsize; - switch(block_type) - { + switch(block_type) { case PL_BLOCK_TYPE_V1: case PL_BLOCK_TYPE_V1_INT: case PL_BLOCK_TYPE_V2: @@ -208,8 +207,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // vpgid // - switch(block_type) - { + switch(block_type) { case PL_BLOCK_TYPE_V1: case PL_BLOCK_TYPE_V1_INT: case PL_BLOCK_TYPE_V2: @@ -240,8 +238,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_PATH_SIZE) - { + if(stlen > SCAP_MAX_PATH_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid commlen %d", stlen); return SCAP_FAILURE; } @@ -262,8 +259,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_PATH_SIZE) - { + if(stlen > SCAP_MAX_PATH_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid exelen %d", stlen); return SCAP_FAILURE; } @@ -278,8 +274,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 subreadsize += readsize; - switch(block_type) - { + switch(block_type) { case PL_BLOCK_TYPE_V1: case PL_BLOCK_TYPE_V1_INT: case PL_BLOCK_TYPE_V2: @@ -299,8 +294,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_PATH_SIZE) - { + if(stlen > SCAP_MAX_PATH_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid exepathlen %d", stlen); return SCAP_FAILURE; } @@ -328,8 +322,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_ARGS_SIZE) - { + if(stlen > SCAP_MAX_ARGS_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid argslen %d", stlen); return SCAP_FAILURE; } @@ -340,8 +333,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 CHECK_READ_SIZE_ERR(readsize, stlen, error); // the string is sometimes not null-terminated on file - if(stlen > 0 && tinfo.args[stlen - 1] != '\0') - { + if(stlen > 0 && tinfo.args[stlen - 1] != '\0') { tinfo.args[stlen] = '\0'; stlen++; } @@ -355,8 +347,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_PATH_SIZE) - { + if(stlen > SCAP_MAX_PATH_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid cwdlen %d", stlen); return SCAP_FAILURE; } @@ -403,8 +394,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 subreadsize += readsize; - switch(block_type) - { + switch(block_type) { case PL_BLOCK_TYPE_V1: case PL_BLOCK_TYPE_V1_INT: break; @@ -458,23 +448,17 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 subreadsize += readsize; - if(block_type == PL_BLOCK_TYPE_V3 || - block_type == PL_BLOCK_TYPE_V3_INT || - block_type == PL_BLOCK_TYPE_V4 || - block_type == PL_BLOCK_TYPE_V5 || - block_type == PL_BLOCK_TYPE_V6 || - block_type == PL_BLOCK_TYPE_V7 || - block_type == PL_BLOCK_TYPE_V8 || - block_type == PL_BLOCK_TYPE_V9) - { + if(block_type == PL_BLOCK_TYPE_V3 || block_type == PL_BLOCK_TYPE_V3_INT || + block_type == PL_BLOCK_TYPE_V4 || block_type == PL_BLOCK_TYPE_V5 || + block_type == PL_BLOCK_TYPE_V6 || block_type == PL_BLOCK_TYPE_V7 || + block_type == PL_BLOCK_TYPE_V8 || block_type == PL_BLOCK_TYPE_V9) { // // env // readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_ENV_SIZE) - { + if(stlen > SCAP_MAX_ENV_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid envlen %d", stlen); return SCAP_FAILURE; } @@ -485,8 +469,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 CHECK_READ_SIZE_ERR(readsize, stlen, error); // the string is sometimes not null-terminated on file - if(stlen > 0 && tinfo.env[stlen - 1] != '\0') - { + if(stlen > 0 && tinfo.env[stlen - 1] != '\0') { tinfo.env[stlen] = '\0'; stlen++; } @@ -495,13 +478,9 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 subreadsize += readsize; } - if(block_type == PL_BLOCK_TYPE_V4 || - block_type == PL_BLOCK_TYPE_V5 || - block_type == PL_BLOCK_TYPE_V6 || - block_type == PL_BLOCK_TYPE_V7 || - block_type == PL_BLOCK_TYPE_V8 || - block_type == PL_BLOCK_TYPE_V9) - { + if(block_type == PL_BLOCK_TYPE_V4 || block_type == PL_BLOCK_TYPE_V5 || + block_type == PL_BLOCK_TYPE_V6 || block_type == PL_BLOCK_TYPE_V7 || + block_type == PL_BLOCK_TYPE_V8 || block_type == PL_BLOCK_TYPE_V9) { // // vtid // @@ -524,8 +503,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_CGROUPS_SIZE) - { + if(stlen > SCAP_MAX_CGROUPS_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid cgroupslen %d", stlen); return SCAP_FAILURE; } @@ -538,17 +516,13 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 subreadsize += readsize; - if(block_type == PL_BLOCK_TYPE_V5 || - block_type == PL_BLOCK_TYPE_V6 || - block_type == PL_BLOCK_TYPE_V7 || - block_type == PL_BLOCK_TYPE_V8 || - block_type == PL_BLOCK_TYPE_V9) - { + if(block_type == PL_BLOCK_TYPE_V5 || block_type == PL_BLOCK_TYPE_V6 || + block_type == PL_BLOCK_TYPE_V7 || block_type == PL_BLOCK_TYPE_V8 || + block_type == PL_BLOCK_TYPE_V9) { readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen > SCAP_MAX_PATH_SIZE) - { + if(stlen > SCAP_MAX_PATH_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid rootlen %d", stlen); return SCAP_FAILURE; } @@ -601,21 +575,18 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // * cap_effective (8B) // TOTAL: 29B bool pre_0_10_0 = false; - if (sub_len - subreadsize <= 29) - { + if(sub_len - subreadsize <= 29) { pre_0_10_0 = true; } - if (!pre_0_10_0) - { + if(!pre_0_10_0) { // Ok we are in libs >= 0.10.x; read the fields that // were added interleaved in libs 0.10.0 // // pidns_init_start_ts // - if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) { readsize = r->read(r, &(tinfo.pidns_init_start_ts), sizeof(uint64_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint64_t), error); subreadsize += readsize; @@ -624,8 +595,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // tty // - if(sub_len && (subreadsize + sizeof(uint32_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint32_t)) <= sub_len) { readsize = r->read(r, &(tinfo.tty), sizeof(uint32_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint32_t), error); subreadsize += readsize; @@ -635,8 +605,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // loginuid (auid) // - if(sub_len && (subreadsize + sizeof(uint32_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint32_t)) <= sub_len) { readsize = r->read(r, &(tinfo.loginuid), sizeof(uint32_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint32_t), error); subreadsize += readsize; @@ -645,8 +614,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // exe_writable // - if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) { readsize = r->read(r, &(tinfo.exe_writable), sizeof(uint8_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint8_t), error); subreadsize += readsize; @@ -655,62 +623,54 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // Capabilities // - if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) { readsize = r->read(r, &(tinfo.cap_inheritable), sizeof(uint64_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint64_t), error); subreadsize += readsize; } - if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) { readsize = r->read(r, &(tinfo.cap_permitted), sizeof(uint64_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint64_t), error); subreadsize += readsize; } - if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) { readsize = r->read(r, &(tinfo.cap_effective), sizeof(uint64_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint64_t), error); subreadsize += readsize; } // exe_upper_layer - if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) { readsize = r->read(r, &(tinfo.exe_upper_layer), sizeof(uint8_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint8_t), error); subreadsize += readsize; } // exe_ino - if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) { readsize = r->read(r, &(tinfo.exe_ino), sizeof(uint64_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint64_t), error); subreadsize += readsize; } // exe_ino_ctime - if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) { readsize = r->read(r, &(tinfo.exe_ino_ctime), sizeof(uint64_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint64_t), error); subreadsize += readsize; } // exe_ino_mtime - if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint64_t)) <= sub_len) { readsize = r->read(r, &(tinfo.exe_ino_mtime), sizeof(uint64_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint64_t), error); subreadsize += readsize; } // exe_from_memfd - if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) { uint8_t exe_from_memfd = 0; readsize = r->read(r, &exe_from_memfd, sizeof(uint8_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint8_t), error); @@ -719,8 +679,7 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 } // exe_lower_layer - if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) - { + if(sub_len && (subreadsize + sizeof(uint8_t)) <= sub_len) { readsize = r->read(r, &(tinfo.exe_lower_layer), sizeof(uint8_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint8_t), error); subreadsize += readsize; @@ -729,21 +688,29 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // All parsed. Add the entry to the table, or fire the notification callback // - proclist->m_proc_callback(proclist->m_proc_callback_context, error, tinfo.tid, &tinfo, NULL, NULL); - - if(sub_len && subreadsize != sub_len) - { - if(subreadsize > sub_len) - { - snprintf(error, SCAP_LASTERR_SIZE, "corrupted input file. Had read %lu bytes, but proclist entry have length %u.", - subreadsize, sub_len); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + tinfo.tid, + &tinfo, + NULL, + NULL); + + if(sub_len && subreadsize != sub_len) { + if(subreadsize > sub_len) { + snprintf(error, + SCAP_LASTERR_SIZE, + "corrupted input file. Had read %lu bytes, but proclist entry have length " + "%u.", + subreadsize, + sub_len); return SCAP_FAILURE; } toread = sub_len - subreadsize; - fseekres = (int) r->seek(r, (long)toread, SEEK_CUR); - if(fseekres == -1) - { - snprintf(error, SCAP_LASTERR_SIZE, "corrupted input file. Can't skip %u bytes.", + fseekres = (int)r->seek(r, (long)toread, SEEK_CUR); + if(fseekres == -1) { + snprintf(error, + SCAP_LASTERR_SIZE, + "corrupted input file. Can't skip %u bytes.", (unsigned int)toread); return SCAP_FAILURE; } @@ -757,9 +724,12 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // Read the padding bytes so we properly align to the end of the data // - if(totreadsize > block_length) - { - snprintf(error, SCAP_LASTERR_SIZE, "scap_read_proclist read more %lu than a block %u", totreadsize, block_length); + if(totreadsize > block_length) { + snprintf(error, + SCAP_LASTERR_SIZE, + "scap_read_proclist read more %lu than a block %u", + totreadsize, + block_length); ASSERT(false); return SCAP_FAILURE; } @@ -774,8 +744,11 @@ static int32_t scap_read_proclist(scap_reader_t* r, uint32_t block_length, uint3 // // Parse an interface list block // -static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_t block_type, scap_addrlist** addrlist_p, char* error) -{ +static int32_t scap_read_iflist(scap_reader_t *r, + uint32_t block_length, + uint32_t block_type, + scap_addrlist **addrlist_p, + char *error) { int32_t res = SCAP_SUCCESS; size_t readsize; size_t totreadsize; @@ -792,8 +765,7 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ // If the list of interfaces was already allocated for this handle (for example because this is // not the first interface list block), free it // - if((*addrlist_p) != NULL) - { + if((*addrlist_p) != NULL) { scap_free_iflist((*addrlist_p)); (*addrlist_p) = NULL; } @@ -803,8 +775,7 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ // We assume that this block is always small enough that we can read it in a single shot // readbuf = (char *)malloc(block_length); - if(!readbuf) - { + if(!readbuf) { snprintf(error, SCAP_LASTERR_SIZE, "memory allocation error in scap_read_iflist"); return SCAP_FAILURE; } @@ -818,54 +789,43 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ pif = readbuf; totreadsize = 0; - while(true) - { + while(true) { toread = (int32_t)block_length - (int32_t)totreadsize; - if(toread < 4) - { + if(toread < 4) { break; } - if(block_type != IL_BLOCK_TYPE_V2) - { + if(block_type != IL_BLOCK_TYPE_V2) { memcpy(&iftype, pif, sizeof(iftype)); memcpy(&ifnamlen, pif + 2, sizeof(ifnamlen)); - if(iftype == SCAP_II_IPV4) - { + if(iftype == SCAP_II_IPV4) { entrysize = sizeof(scap_ifinfo_ipv4) + ifnamlen - SCAP_MAX_PATH_SIZE; - } - else if(iftype == SCAP_II_IPV6) - { + } else if(iftype == SCAP_II_IPV6) { entrysize = sizeof(scap_ifinfo_ipv6) + ifnamlen - SCAP_MAX_PATH_SIZE; - } - else if(iftype == SCAP_II_IPV4_NOLINKSPEED) - { + } else if(iftype == SCAP_II_IPV4_NOLINKSPEED) { entrysize = sizeof(scap_ifinfo_ipv4_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE; - } - else if(iftype == SCAP_II_IPV6_NOLINKSPEED) - { + } else if(iftype == SCAP_II_IPV6_NOLINKSPEED) { entrysize = sizeof(scap_ifinfo_ipv6_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE; - } - else - { + } else { snprintf(error, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(1)"); res = SCAP_FAILURE; goto scap_read_iflist_error; } - } - else - { + } else { memcpy(&entrysize, pif, sizeof(entrysize)); entrysize += sizeof(uint32_t); memcpy(&iftype, pif + 4, sizeof(iftype)); memcpy(&ifnamlen, pif + 4 + 2, sizeof(ifnamlen)); } - if(toread < entrysize) - { - snprintf(error, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(2) toread=%u, entrysize=%u", toread, entrysize); + if(toread < entrysize) { + snprintf(error, + SCAP_LASTERR_SIZE, + "trace file has corrupted interface list(2) toread=%u, entrysize=%u", + toread, + entrysize); res = SCAP_FAILURE; goto scap_read_iflist_error; } @@ -873,16 +833,11 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ pif += entrysize; totreadsize += entrysize; - if(iftype == SCAP_II_IPV4 || iftype == SCAP_II_IPV4_NOLINKSPEED) - { + if(iftype == SCAP_II_IPV4 || iftype == SCAP_II_IPV4_NOLINKSPEED) { ifcnt4++; - } - else if(iftype == SCAP_II_IPV6 || iftype == SCAP_II_IPV6_NOLINKSPEED) - { + } else if(iftype == SCAP_II_IPV6 || iftype == SCAP_II_IPV6_NOLINKSPEED) { ifcnt6++; - } - else - { + } else { snprintf(error, SCAP_LASTERR_SIZE, "unknown interface type %d", (int)iftype); res = SCAP_FAILURE; goto scap_read_iflist_error; @@ -893,8 +848,7 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ // Allocate the handle and the arrays // (*addrlist_p) = (scap_addrlist *)malloc(sizeof(scap_addrlist)); - if(!(*addrlist_p)) - { + if(!(*addrlist_p)) { snprintf(error, SCAP_LASTERR_SIZE, "scap_read_iflist allocation failed(1)"); res = SCAP_FAILURE; goto scap_read_iflist_error; @@ -906,33 +860,25 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ (*addrlist_p)->v6list = NULL; (*addrlist_p)->totlen = block_length - (ifcnt4 + ifcnt6) * sizeof(uint32_t); - if(ifcnt4 != 0) - { + if(ifcnt4 != 0) { (*addrlist_p)->v4list = (scap_ifinfo_ipv4 *)malloc(ifcnt4 * sizeof(scap_ifinfo_ipv4)); - if(!(*addrlist_p)->v4list) - { + if(!(*addrlist_p)->v4list) { snprintf(error, SCAP_LASTERR_SIZE, "scap_read_iflist allocation failed(2)"); res = SCAP_FAILURE; goto scap_read_iflist_error; } - } - else - { + } else { (*addrlist_p)->v4list = NULL; } - if(ifcnt6 != 0) - { + if(ifcnt6 != 0) { (*addrlist_p)->v6list = (scap_ifinfo_ipv6 *)malloc(ifcnt6 * sizeof(scap_ifinfo_ipv6)); - if(!(*addrlist_p)->v6list) - { + if(!(*addrlist_p)->v6list) { snprintf(error, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(3)"); res = SCAP_FAILURE; goto scap_read_iflist_error; } - } - else - { + } else { (*addrlist_p)->v6list = NULL; } @@ -947,18 +893,15 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ pif = readbuf; totreadsize = 0; - while(true) - { + while(true) { toread = (int32_t)block_length - (int32_t)totreadsize; entrysize = 0; - if(toread < 4) - { + if(toread < 4) { break; } - if(block_type == IL_BLOCK_TYPE_V2) - { + if(block_type == IL_BLOCK_TYPE_V2) { memcpy(&entrysize, pif, sizeof(entrysize)); totreadsize += sizeof(uint32_t); pif += sizeof(uint32_t); @@ -967,8 +910,7 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ memcpy(&iftype, pif, sizeof(iftype)); memcpy(&ifnamlen, pif + 2, sizeof(ifnamlen)); - if(ifnamlen >= SCAP_MAX_PATH_SIZE) - { + if(ifnamlen >= SCAP_MAX_PATH_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(0)"); res = SCAP_FAILURE; goto scap_read_iflist_error; @@ -985,18 +927,16 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ // } uint32_t ifsize; - if(iftype == SCAP_II_IPV4) - { - ifsize = sizeof(uint16_t) + // type - sizeof(uint16_t) + // ifnamelen - sizeof(uint32_t) + // addr - sizeof(uint32_t) + // netmask - sizeof(uint32_t) + // bcast - sizeof(uint64_t) + // linkspeed - ifnamlen; - - if(toread < ifsize) - { + if(iftype == SCAP_II_IPV4) { + ifsize = sizeof(uint16_t) + // type + sizeof(uint16_t) + // ifnamelen + sizeof(uint32_t) + // addr + sizeof(uint32_t) + // netmask + sizeof(uint32_t) + // bcast + sizeof(uint64_t) + // linkspeed + ifnamlen; + + if(toread < ifsize) { snprintf(error, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(3)"); res = SCAP_FAILURE; goto scap_read_iflist_error; @@ -1011,23 +951,20 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ *((char *)((*addrlist_p)->v4list + ifcnt4) + ifsize) = 0; ifcnt4++; - } - else if(iftype == SCAP_II_IPV4_NOLINKSPEED) - { - scap_ifinfo_ipv4_nolinkspeed* src; - scap_ifinfo_ipv4* dst; + } else if(iftype == SCAP_II_IPV4_NOLINKSPEED) { + scap_ifinfo_ipv4_nolinkspeed *src; + scap_ifinfo_ipv4 *dst; ifsize = sizeof(scap_ifinfo_ipv4_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE; - if(toread < ifsize) - { + if(toread < ifsize) { snprintf(error, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(4)"); res = SCAP_FAILURE; goto scap_read_iflist_error; } // Copy the entry - src = (scap_ifinfo_ipv4_nolinkspeed*)pif; + src = (scap_ifinfo_ipv4_nolinkspeed *)pif; dst = (*addrlist_p)->v4list + ifcnt4; dst->type = src->type; @@ -1042,19 +979,16 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ *((char *)(dst->ifname + MIN(dst->ifnamelen, SCAP_MAX_PATH_SIZE - 1))) = 0; ifcnt4++; - } - else if(iftype == SCAP_II_IPV6) - { - ifsize = sizeof(uint16_t) + // type - sizeof(uint16_t) + // ifnamelen - SCAP_IPV6_ADDR_LEN + // addr - SCAP_IPV6_ADDR_LEN + // netmask - SCAP_IPV6_ADDR_LEN + // bcast - sizeof(uint64_t) + // linkspeed - ifnamlen; - - if(toread < ifsize) - { + } else if(iftype == SCAP_II_IPV6) { + ifsize = sizeof(uint16_t) + // type + sizeof(uint16_t) + // ifnamelen + SCAP_IPV6_ADDR_LEN + // addr + SCAP_IPV6_ADDR_LEN + // netmask + SCAP_IPV6_ADDR_LEN + // bcast + sizeof(uint64_t) + // linkspeed + ifnamlen; + + if(toread < ifsize) { snprintf(error, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(5)"); res = SCAP_FAILURE; goto scap_read_iflist_error; @@ -1069,22 +1003,19 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ *((char *)((*addrlist_p)->v6list + ifcnt6) + ifsize) = 0; ifcnt6++; - } - else if(iftype == SCAP_II_IPV6_NOLINKSPEED) - { - scap_ifinfo_ipv6_nolinkspeed* src; - scap_ifinfo_ipv6* dst; + } else if(iftype == SCAP_II_IPV6_NOLINKSPEED) { + scap_ifinfo_ipv6_nolinkspeed *src; + scap_ifinfo_ipv6 *dst; ifsize = sizeof(scap_ifinfo_ipv6_nolinkspeed) + ifnamlen - SCAP_MAX_PATH_SIZE; - if(toread < ifsize) - { + if(toread < ifsize) { snprintf(error, SCAP_LASTERR_SIZE, "trace file has corrupted interface list(6)"); res = SCAP_FAILURE; goto scap_read_iflist_error; } // Copy the entry - src = (scap_ifinfo_ipv6_nolinkspeed*)pif; + src = (scap_ifinfo_ipv6_nolinkspeed *)pif; dst = (*addrlist_p)->v6list + ifcnt6; dst->type = src->type; @@ -1099,9 +1030,7 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ *((char *)(dst->ifname + MIN(dst->ifnamelen, SCAP_MAX_PATH_SIZE - 1))) = 0; ifcnt6++; - } - else - { + } else { ASSERT(false); snprintf(error, SCAP_LASTERR_SIZE, "unknown interface type %d", (int)iftype); res = SCAP_FAILURE; @@ -1125,8 +1054,7 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ scap_free_iflist((*addrlist_p)); (*addrlist_p) = NULL; - if(readbuf) - { + if(readbuf) { free(readbuf); } @@ -1136,8 +1064,11 @@ static int32_t scap_read_iflist(scap_reader_t* r, uint32_t block_length, uint32_ // // Parse a user list block // -static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint32_t block_type, scap_userlist** userlist_p, char* error) -{ +static int32_t scap_read_userlist(scap_reader_t *r, + uint32_t block_length, + uint32_t block_type, + scap_userlist **userlist_p, + char *error) { size_t readsize; size_t totreadsize = 0; size_t subreadsize = 0; @@ -1152,8 +1083,7 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 // If the list of users was already allocated for this handle (for example because this is // not the first user list block), free it // - if((*userlist_p) != NULL) - { + if((*userlist_p) != NULL) { scap_free_userlist((*userlist_p)); (*userlist_p) = NULL; } @@ -1161,10 +1091,9 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 // // Allocate and initialize the handle info // - (*userlist_p) = (scap_userlist*)malloc(sizeof(scap_userlist)); - if((*userlist_p) == NULL) - { - snprintf(error, SCAP_LASTERR_SIZE, "userlist allocation failed(2)"); + (*userlist_p) = (scap_userlist *)malloc(sizeof(scap_userlist)); + if((*userlist_p) == NULL) { + snprintf(error, SCAP_LASTERR_SIZE, "userlist allocation failed(2)"); return SCAP_FAILURE; } @@ -1177,11 +1106,9 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 // // Import the blocks // - while(((int32_t)block_length - (int32_t)totreadsize) >= 4) - { + while(((int32_t)block_length - (int32_t)totreadsize) >= 4) { uint32_t sub_len = 0; - if(block_type == UL_BLOCK_TYPE_V2) - { + if(block_type == UL_BLOCK_TYPE_V2) { // // len // @@ -1199,22 +1126,24 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 subreadsize += readsize; - if(type == USERBLOCK_TYPE_USER) - { - scap_userinfo* puser; + if(type == USERBLOCK_TYPE_USER) { + scap_userinfo *puser; (*userlist_p)->nusers++; - scap_userinfo *new_userlist = (scap_userinfo*)realloc((*userlist_p)->users, (*userlist_p)->nusers * sizeof(scap_userinfo)); - if(new_userlist == NULL) - { + scap_userinfo *new_userlist = + (scap_userinfo *)realloc((*userlist_p)->users, + (*userlist_p)->nusers * sizeof(scap_userinfo)); + if(new_userlist == NULL) { free((*userlist_p)->users); (*userlist_p)->users = NULL; - snprintf(error, SCAP_LASTERR_SIZE, "memory allocation error in scap_read_userlist(1)"); + snprintf(error, + SCAP_LASTERR_SIZE, + "memory allocation error in scap_read_userlist(1)"); return SCAP_FAILURE; } (*userlist_p)->users = new_userlist; - puser = &(*userlist_p)->users[(*userlist_p)->nusers -1]; + puser = &(*userlist_p)->users[(*userlist_p)->nusers - 1]; // // uid @@ -1238,8 +1167,7 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen >= MAX_CREDENTIALS_STR_LEN) - { + if(stlen >= MAX_CREDENTIALS_STR_LEN) { snprintf(error, SCAP_LASTERR_SIZE, "invalid user name len %d", stlen); return SCAP_FAILURE; } @@ -1260,8 +1188,7 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen >= MAX_CREDENTIALS_STR_LEN) - { + if(stlen >= MAX_CREDENTIALS_STR_LEN) { snprintf(error, SCAP_LASTERR_SIZE, "invalid user homedir len %d", stlen); return SCAP_FAILURE; } @@ -1282,8 +1209,7 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen >= MAX_CREDENTIALS_STR_LEN) - { + if(stlen >= MAX_CREDENTIALS_STR_LEN) { snprintf(error, SCAP_LASTERR_SIZE, "invalid user shell len %d", stlen); return SCAP_FAILURE; } @@ -1306,23 +1232,24 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 // { // ... // } - } - else - { - scap_groupinfo* pgroup; + } else { + scap_groupinfo *pgroup; (*userlist_p)->ngroups++; - scap_groupinfo *new_grouplist = (scap_groupinfo*)realloc((*userlist_p)->groups, (*userlist_p)->ngroups * sizeof(scap_groupinfo)); - if(new_grouplist == NULL) - { + scap_groupinfo *new_grouplist = + (scap_groupinfo *)realloc((*userlist_p)->groups, + (*userlist_p)->ngroups * sizeof(scap_groupinfo)); + if(new_grouplist == NULL) { free((*userlist_p)->groups); (*userlist_p)->groups = NULL; - snprintf(error, SCAP_LASTERR_SIZE, "memory allocation error in scap_read_userlist(2)"); + snprintf(error, + SCAP_LASTERR_SIZE, + "memory allocation error in scap_read_userlist(2)"); return SCAP_FAILURE; } (*userlist_p)->groups = new_grouplist; - pgroup = &(*userlist_p)->groups[(*userlist_p)->ngroups -1]; + pgroup = &(*userlist_p)->groups[(*userlist_p)->ngroups - 1]; // // gid @@ -1338,8 +1265,7 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen >= MAX_CREDENTIALS_STR_LEN) - { + if(stlen >= MAX_CREDENTIALS_STR_LEN) { snprintf(error, SCAP_LASTERR_SIZE, "invalid group name len %d", stlen); return SCAP_FAILURE; } @@ -1364,19 +1290,22 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 // } } - if(sub_len && subreadsize != sub_len) - { - if(subreadsize > sub_len) - { - snprintf(error, SCAP_LASTERR_SIZE, "corrupted input file. Had read %lu bytes, but userlist entry have length %u.", - subreadsize, sub_len); + if(sub_len && subreadsize != sub_len) { + if(subreadsize > sub_len) { + snprintf(error, + SCAP_LASTERR_SIZE, + "corrupted input file. Had read %lu bytes, but userlist entry have length " + "%u.", + subreadsize, + sub_len); return SCAP_FAILURE; } toread = sub_len - subreadsize; - fseekres = (int) r->seek(r, (long)toread, SEEK_CUR); - if(fseekres == -1) - { - snprintf(error, SCAP_LASTERR_SIZE, "corrupted input file. Can't skip %u bytes.", + fseekres = (int)r->seek(r, (long)toread, SEEK_CUR); + if(fseekres == -1) { + snprintf(error, + SCAP_LASTERR_SIZE, + "corrupted input file. Can't skip %u bytes.", (unsigned int)toread); return SCAP_FAILURE; } @@ -1390,10 +1319,13 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 // // Read the padding bytes so we properly align to the end of the data // - if(totreadsize > block_length) - { + if(totreadsize > block_length) { ASSERT(false); - snprintf(error, SCAP_LASTERR_SIZE, "scap_read_userlist read more %lu than a block %u", totreadsize, block_length); + snprintf(error, + SCAP_LASTERR_SIZE, + "scap_read_userlist read more %lu than a block %u", + totreadsize, + block_length); return SCAP_FAILURE; } padding_len = block_length - totreadsize; @@ -1404,8 +1336,11 @@ static int32_t scap_read_userlist(scap_reader_t* r, uint32_t block_length, uint3 return SCAP_SUCCESS; } -static uint32_t scap_fd_read_prop_from_disk(void *target, size_t expected_size, size_t *nbytes, scap_reader_t *r, char *error) -{ +static uint32_t scap_fd_read_prop_from_disk(void *target, + size_t expected_size, + size_t *nbytes, + scap_reader_t *r, + char *error) { size_t readsize; readsize = r->read(r, target, (unsigned int)expected_size); CHECK_READ_SIZE_ERR(readsize, expected_size, error); @@ -1413,16 +1348,17 @@ static uint32_t scap_fd_read_prop_from_disk(void *target, size_t expected_size, return SCAP_SUCCESS; } -static uint32_t scap_fd_read_fname_from_disk(char *fname, size_t *nbytes, scap_reader_t *r, char *error) -{ +static uint32_t scap_fd_read_fname_from_disk(char *fname, + size_t *nbytes, + scap_reader_t *r, + char *error) { size_t readsize; uint16_t stlen; readsize = r->read(r, &(stlen), sizeof(uint16_t)); CHECK_READ_SIZE_ERR(readsize, sizeof(uint16_t), error); - if(stlen >= SCAP_MAX_PATH_SIZE) - { + if(stlen >= SCAP_MAX_PATH_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid filename len %" PRId32, stlen); return SCAP_FAILURE; } @@ -1443,8 +1379,11 @@ static uint32_t scap_fd_read_fname_from_disk(char *fname, size_t *nbytes, scap_r // Populate the given fd by reading the info from disk // Returns the number of read bytes. // -static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, size_t *nbytes, uint32_t block_type, scap_reader_t *r, char *error) -{ +static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, + size_t *nbytes, + uint32_t block_type, + scap_reader_t *r, + char *error) { uint8_t type; uint32_t toread; int fseekres; @@ -1456,8 +1395,7 @@ static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, size_t *nbytes, uint32_ scap_fd_read_prop_from_disk(&sub_len, sizeof(uint32_t), nbytes, r, error)) || scap_fd_read_prop_from_disk(&(fdi->fd), sizeof(fdi->fd), nbytes, r, error) || scap_fd_read_prop_from_disk(&(fdi->ino), sizeof(fdi->ino), nbytes, r, error) || - scap_fd_read_prop_from_disk(&type, sizeof(uint8_t), nbytes, r, error)) - { + scap_fd_read_prop_from_disk(&type, sizeof(uint8_t), nbytes, r, error)) { snprintf(error, SCAP_LASTERR_SIZE, "Could not read prop block for fd"); return SCAP_FAILURE; } @@ -1473,27 +1411,25 @@ static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, size_t *nbytes, uint32_ fdi->type = (scap_fd_type)type; - switch(fdi->type) - { + switch(fdi->type) { case SCAP_FD_IPV4_SOCK: if(r->read(r, &(fdi->info.ipv4info.sip), sizeof(uint32_t)) != sizeof(uint32_t) || r->read(r, &(fdi->info.ipv4info.dip), sizeof(uint32_t)) != sizeof(uint32_t) || r->read(r, &(fdi->info.ipv4info.sport), sizeof(uint16_t)) != sizeof(uint16_t) || r->read(r, &(fdi->info.ipv4info.dport), sizeof(uint16_t)) != sizeof(uint16_t) || - r->read(r, &(fdi->info.ipv4info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + r->read(r, &(fdi->info.ipv4info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading the fd info from file (1)"); return SCAP_FAILURE; } - (*nbytes) += (sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint8_t)); + (*nbytes) += (sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t) + + sizeof(uint8_t)); break; case SCAP_FD_IPV4_SERVSOCK: if(r->read(r, &(fdi->info.ipv4serverinfo.ip), sizeof(uint32_t)) != sizeof(uint32_t) || r->read(r, &(fdi->info.ipv4serverinfo.port), sizeof(uint16_t)) != sizeof(uint16_t) || - r->read(r, &(fdi->info.ipv4serverinfo.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + r->read(r, &(fdi->info.ipv4serverinfo.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading the fd info from file (2)"); return SCAP_FAILURE; } @@ -1501,35 +1437,36 @@ static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, size_t *nbytes, uint32_ (*nbytes) += (sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint8_t)); break; case SCAP_FD_IPV6_SOCK: - if(r->read(r, (char *)fdi->info.ipv6info.sip, sizeof(uint32_t) * 4) != sizeof(uint32_t) * 4 || - r->read(r, (char *)fdi->info.ipv6info.dip, sizeof(uint32_t) * 4) != sizeof(uint32_t) * 4 || + if(r->read(r, (char *)fdi->info.ipv6info.sip, sizeof(uint32_t) * 4) != + sizeof(uint32_t) * 4 || + r->read(r, (char *)fdi->info.ipv6info.dip, sizeof(uint32_t) * 4) != + sizeof(uint32_t) * 4 || r->read(r, &(fdi->info.ipv6info.sport), sizeof(uint16_t)) != sizeof(uint16_t) || r->read(r, &(fdi->info.ipv6info.dport), sizeof(uint16_t)) != sizeof(uint16_t) || - r->read(r, &(fdi->info.ipv6info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + r->read(r, &(fdi->info.ipv6info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(error, SCAP_LASTERR_SIZE, "error writing to file (fi3)"); } - (*nbytes) += (sizeof(uint32_t) * 4 + // sip - sizeof(uint32_t) * 4 + // dip - sizeof(uint16_t) + // sport - sizeof(uint16_t) + // dport - sizeof(uint8_t)); // l4proto + (*nbytes) += (sizeof(uint32_t) * 4 + // sip + sizeof(uint32_t) * 4 + // dip + sizeof(uint16_t) + // sport + sizeof(uint16_t) + // dport + sizeof(uint8_t)); // l4proto break; case SCAP_FD_IPV6_SERVSOCK: - if(r->read(r, (char *)fdi->info.ipv6serverinfo.ip, sizeof(uint32_t) * 4) != sizeof(uint32_t) * 4 || + if(r->read(r, (char *)fdi->info.ipv6serverinfo.ip, sizeof(uint32_t) * 4) != + sizeof(uint32_t) * 4 || r->read(r, &(fdi->info.ipv6serverinfo.port), sizeof(uint16_t)) != sizeof(uint16_t) || - r->read(r, &(fdi->info.ipv6serverinfo.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + r->read(r, &(fdi->info.ipv6serverinfo.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(error, SCAP_LASTERR_SIZE, "error writing to file (fi4)"); } - (*nbytes) += (sizeof(uint32_t) * 4 + // ip - sizeof(uint16_t) + // port - sizeof(uint8_t)); // l4proto + (*nbytes) += (sizeof(uint32_t) * 4 + // ip + sizeof(uint16_t) + // port + sizeof(uint8_t)); // l4proto break; case SCAP_FD_UNIX_SOCK: if(r->read(r, &(fdi->info.unix_socket_info.source), sizeof(uint64_t)) != sizeof(uint64_t) || - r->read(r, &(fdi->info.unix_socket_info.destination), sizeof(uint64_t)) != sizeof(uint64_t)) - { + r->read(r, &(fdi->info.unix_socket_info.destination), sizeof(uint64_t)) != + sizeof(uint64_t)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading the fd info from file (fi5)"); return SCAP_FAILURE; } @@ -1538,20 +1475,17 @@ static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, size_t *nbytes, uint32_ res = scap_fd_read_fname_from_disk(fdi->info.unix_socket_info.fname, nbytes, r, error); break; case SCAP_FD_FILE_V2: - if(r->read(r, &(fdi->info.regularinfo.open_flags), sizeof(uint32_t)) != sizeof(uint32_t)) - { + if(r->read(r, &(fdi->info.regularinfo.open_flags), sizeof(uint32_t)) != sizeof(uint32_t)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading the fd info from file (fi1)"); return SCAP_FAILURE; } (*nbytes) += sizeof(uint32_t); res = scap_fd_read_fname_from_disk(fdi->info.regularinfo.fname, nbytes, r, error); - if(!sub_len || (sub_len < *nbytes + sizeof(uint32_t))) - { + if(!sub_len || (sub_len < *nbytes + sizeof(uint32_t))) { break; } - if(r->read(r, &(fdi->info.regularinfo.dev), sizeof(uint32_t)) != sizeof(uint32_t)) - { + if(r->read(r, &(fdi->info.regularinfo.dev), sizeof(uint32_t)) != sizeof(uint32_t)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading the fd info from file (dev)"); return SCAP_FAILURE; } @@ -1584,20 +1518,22 @@ static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, size_t *nbytes, uint32_ break; } - if(sub_len && *nbytes != sub_len) - { - if(*nbytes > sub_len) - { - snprintf(error, SCAP_LASTERR_SIZE, "corrupted input file. Had read %zu bytes, but fdlist entry have length %u.", - *nbytes, sub_len); + if(sub_len && *nbytes != sub_len) { + if(*nbytes > sub_len) { + snprintf(error, + SCAP_LASTERR_SIZE, + "corrupted input file. Had read %zu bytes, but fdlist entry have length %u.", + *nbytes, + sub_len); return SCAP_FAILURE; } toread = (uint32_t)(sub_len - *nbytes); - fseekres = (int) r->seek(r, (long)toread, SEEK_CUR); - if(fseekres == -1) - { - snprintf(error, SCAP_LASTERR_SIZE, "corrupted input file. Can't skip %u bytes.", - (unsigned int)toread); + fseekres = (int)r->seek(r, (long)toread, SEEK_CUR); + if(fseekres == -1) { + snprintf(error, + SCAP_LASTERR_SIZE, + "corrupted input file. Can't skip %u bytes.", + (unsigned int)toread); return SCAP_FAILURE; } *nbytes = sub_len; @@ -1609,8 +1545,11 @@ static uint32_t scap_fd_read_from_disk(scap_fdinfo *fdi, size_t *nbytes, uint32_ // // Parse a file descriptor list block // -static int32_t scap_read_fdlist(scap_reader_t* r, uint32_t block_length, uint32_t block_type, struct scap_proclist* proclist, char* error) -{ +static int32_t scap_read_fdlist(scap_reader_t *r, + uint32_t block_length, + uint32_t block_type, + struct scap_proclist *proclist, + char *error) { size_t readsize; size_t totreadsize = 0; size_t padding_len; @@ -1626,10 +1565,8 @@ static int32_t scap_read_fdlist(scap_reader_t* r, uint32_t block_length, uint32_ CHECK_READ_SIZE_ERR(readsize, sizeof(tid), error); totreadsize += readsize; - while(((int32_t)block_length - (int32_t)totreadsize) >= 4) - { - if(scap_fd_read_from_disk(&fdi, &readsize, block_type, r, error) != SCAP_SUCCESS) - { + while(((int32_t)block_length - (int32_t)totreadsize) >= 4) { + if(scap_fd_read_from_disk(&fdi, &readsize, block_type, r, error) != SCAP_SUCCESS) { return SCAP_FAILURE; } totreadsize += readsize; @@ -1642,10 +1579,13 @@ static int32_t scap_read_fdlist(scap_reader_t* r, uint32_t block_length, uint32_ // // Read the padding bytes so we properly align to the end of the data // - if(totreadsize > block_length) - { + if(totreadsize > block_length) { ASSERT(false); - snprintf(error, SCAP_LASTERR_SIZE, "scap_read_fdlist read more %lu than a block %u", totreadsize, block_length); + snprintf(error, + SCAP_LASTERR_SIZE, + "scap_read_fdlist read more %lu than a block %u", + totreadsize, + block_length); return SCAP_FAILURE; } padding_len = block_length - totreadsize; @@ -1656,31 +1596,27 @@ static int32_t scap_read_fdlist(scap_reader_t* r, uint32_t block_length, uint32_ return SCAP_SUCCESS; } -static int32_t scap_read_section_header(scap_reader_t* r, char* error) -{ +static int32_t scap_read_section_header(scap_reader_t *r, char *error) { section_header_block sh; uint32_t bt; // // Read the section header block // - if(r->read(r, &sh, sizeof(sh)) != sizeof(sh) || - r->read(r, &bt, sizeof(bt)) != sizeof(bt)) - { + if(r->read(r, &sh, sizeof(sh)) != sizeof(sh) || r->read(r, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading from file (1)"); return SCAP_FAILURE; } - if(sh.byte_order_magic != 0x1a2b3c4d) - { + if(sh.byte_order_magic != 0x1a2b3c4d) { snprintf(error, SCAP_LASTERR_SIZE, "invalid magic number"); return SCAP_FAILURE; } - if(sh.major_version > CURRENT_MAJOR_VERSION) - { - snprintf(error, SCAP_LASTERR_SIZE, - "cannot correctly parse the capture. Upgrade your version."); + if(sh.major_version > CURRENT_MAJOR_VERSION) { + snprintf(error, + SCAP_LASTERR_SIZE, + "cannot correctly parse the capture. Upgrade your version."); return SCAP_VERSION_MISMATCH; } @@ -1690,8 +1626,13 @@ static int32_t scap_read_section_header(scap_reader_t* r, char* error) // // Parse the headers of a trace file and load the tables // -static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, scap_machine_info* machine_info_p, struct scap_proclist* proclist_p, scap_addrlist** addrlist_p, scap_userlist** userlist_p, char* error) -{ +static int32_t scap_read_init(struct savefile_engine *handle, + scap_reader_t *r, + scap_machine_info *machine_info_p, + struct scap_proclist *proclist_p, + scap_addrlist **addrlist_p, + scap_userlist **userlist_p, + char *error) { block_header bh; uint32_t bt; size_t readsize; @@ -1703,53 +1644,46 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, // // Read the section header block // - if(read_block_header(handle, r, &bh) != sizeof(bh)) - { + if(read_block_header(handle, r, &bh) != sizeof(bh)) { snprintf(error, SCAP_LASTERR_SIZE, "error reading from file (1)"); return SCAP_FAILURE; } - if(bh.block_type != SHB_BLOCK_TYPE) - { + if(bh.block_type != SHB_BLOCK_TYPE) { snprintf(error, SCAP_LASTERR_SIZE, "invalid block type"); return SCAP_FAILURE; } - if((rc = scap_read_section_header(r, error)) != SCAP_SUCCESS) - { + if((rc = scap_read_section_header(r, error)) != SCAP_SUCCESS) { return rc; } // // Read the metadata blocks (processes, FDs, etc.) // - while(true) - { + while(true) { readsize = read_block_header(handle, r, &bh); // // If we don't find the event block header, // it means there is no event in the file. // - if (readsize == 0 && !found_ev) - { + if(readsize == 0 && !found_ev) { snprintf(error, SCAP_LASTERR_SIZE, "no events in file"); return SCAP_FAILURE; } CHECK_READ_SIZE_ERR(readsize, sizeof(bh), error); - switch(bh.block_type) - { + switch(bh.block_type) { case MI_BLOCK_TYPE: case MI_BLOCK_TYPE_INT: - if(scap_read_machine_info( - r, - machine_info_p, - error, - bh.block_total_length - sizeof(block_header) - 4) != SCAP_SUCCESS) - { + if(scap_read_machine_info(r, + machine_info_p, + error, + bh.block_total_length - sizeof(block_header) - 4) != + SCAP_SUCCESS) { return SCAP_FAILURE; } break; @@ -1766,8 +1700,11 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, case PL_BLOCK_TYPE_V2_INT: case PL_BLOCK_TYPE_V3_INT: - if(scap_read_proclist(r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type, proclist_p, error) != SCAP_SUCCESS) - { + if(scap_read_proclist(r, + bh.block_total_length - sizeof(block_header) - 4, + bh.block_type, + proclist_p, + error) != SCAP_SUCCESS) { return SCAP_FAILURE; } break; @@ -1775,8 +1712,11 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, case FDL_BLOCK_TYPE_INT: case FDL_BLOCK_TYPE_V2: - if(scap_read_fdlist(r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type, proclist_p, error) != SCAP_SUCCESS) - { + if(scap_read_fdlist(r, + bh.block_total_length - sizeof(block_header) - 4, + bh.block_type, + proclist_p, + error) != SCAP_SUCCESS) { return SCAP_FAILURE; } break; @@ -1797,8 +1737,11 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, case IL_BLOCK_TYPE_INT: case IL_BLOCK_TYPE_V2: - if(scap_read_iflist(r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type, addrlist_p, error) != SCAP_SUCCESS) - { + if(scap_read_iflist(r, + bh.block_total_length - sizeof(block_header) - 4, + bh.block_type, + addrlist_p, + error) != SCAP_SUCCESS) { return SCAP_FAILURE; } break; @@ -1806,8 +1749,11 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, case UL_BLOCK_TYPE_INT: case UL_BLOCK_TYPE_V2: - if(scap_read_userlist(r, bh.block_total_length - sizeof(block_header) - 4, bh.block_type, userlist_p, error) != SCAP_SUCCESS) - { + if(scap_read_userlist(r, + bh.block_total_length - sizeof(block_header) - 4, + bh.block_type, + userlist_p, + error) != SCAP_SUCCESS) { return SCAP_FAILURE; } break; @@ -1816,10 +1762,11 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, // Unknown block type. Skip the block. // toread = bh.block_total_length - sizeof(block_header) - 4; - fseekres = (int) r->seek(r, (long)toread, SEEK_CUR); - if(fseekres == -1) - { - snprintf(error, SCAP_LASTERR_SIZE, "corrupted input file. Can't skip block of type %x and size %u.", + fseekres = (int)r->seek(r, (long)toread, SEEK_CUR); + if(fseekres == -1) { + snprintf(error, + SCAP_LASTERR_SIZE, + "corrupted input file. Can't skip block of type %x and size %u.", (int)bh.block_type, (unsigned int)toread); return SCAP_FAILURE; @@ -1827,8 +1774,7 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, break; } - if(found_ev) - { + if(found_ev) { break; } @@ -1838,9 +1784,10 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, readsize = r->read(r, &bt, sizeof(bt)); CHECK_READ_SIZE_ERR(readsize, sizeof(bt), error); - if(bt != bh.block_total_length) - { - snprintf(error, SCAP_LASTERR_SIZE, "wrong block total length, header=%u, trailer=%u", + if(bt != bh.block_total_length) { + snprintf(error, + SCAP_LASTERR_SIZE, + "wrong block total length, header=%u, trailer=%u", bh.block_total_length, bt); return SCAP_FAILURE; @@ -1859,14 +1806,16 @@ static int32_t scap_read_init(struct savefile_engine *handle, scap_reader_t* r, // // Read an event from disk // -static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_t *pdevid, uint32_t *pflags) -{ - struct savefile_engine* handle = engine.m_handle; +static int32_t next(struct scap_engine_handle engine, + scap_evt **pevent, + uint16_t *pdevid, + uint32_t *pflags) { + struct savefile_engine *handle = engine.m_handle; block_header bh; size_t readsize; uint32_t readlen; size_t hdr_len; - scap_reader_t* r = handle->m_reader; + scap_reader_t *r = handle->m_reader; ASSERT(r != NULL); @@ -1874,65 +1823,61 @@ static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_ // We may have to repeat the whole process // if the capture contains new syscalls // - while(true) - { + while(true) { // // Read the block header // readsize = read_block_header(handle, r, &bh); - if(readsize != sizeof(bh)) - { + if(readsize != sizeof(bh)) { int err_no = 0; #ifdef _WIN32 - const char* err_str = "read error"; + const char *err_str = "read error"; #else - const char* err_str = r->error(r, &err_no); + const char *err_str = r->error(r, &err_no); #endif - if(err_no) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error reading file: %s, ernum=%d", err_str, err_no); + if(err_no) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "error reading file: %s, ernum=%d", + err_str, + err_no); return SCAP_FAILURE; } - if(readsize == 0) - { + if(readsize == 0) { // // We read exactly 0 bytes. This indicates a correct end of file. // return SCAP_EOF; - } - else - { + } else { CHECK_READ_SIZE(readsize, sizeof(bh)); } } - if(bh.block_type != EV_BLOCK_TYPE && - bh.block_type != EV_BLOCK_TYPE_V2 && - bh.block_type != EV_BLOCK_TYPE_V2_LARGE && - bh.block_type != EV_BLOCK_TYPE_INT && - bh.block_type != EVF_BLOCK_TYPE && - bh.block_type != EVF_BLOCK_TYPE_V2 && - bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "unexpected block type %u", (uint32_t)bh.block_type); + if(bh.block_type != EV_BLOCK_TYPE && bh.block_type != EV_BLOCK_TYPE_V2 && + bh.block_type != EV_BLOCK_TYPE_V2_LARGE && bh.block_type != EV_BLOCK_TYPE_INT && + bh.block_type != EVF_BLOCK_TYPE && bh.block_type != EVF_BLOCK_TYPE_V2 && + bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "unexpected block type %u", + (uint32_t)bh.block_type); handle->m_use_last_block_header = true; return SCAP_UNEXPECTED_BLOCK; } hdr_len = sizeof(struct ppm_evt_hdr); - if(bh.block_type != EV_BLOCK_TYPE_V2 && - bh.block_type != EV_BLOCK_TYPE_V2_LARGE && - bh.block_type != EVF_BLOCK_TYPE_V2 && - bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) - { + if(bh.block_type != EV_BLOCK_TYPE_V2 && bh.block_type != EV_BLOCK_TYPE_V2_LARGE && + bh.block_type != EVF_BLOCK_TYPE_V2 && bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) { hdr_len -= 4; } - if(bh.block_total_length < sizeof(bh) + hdr_len + 4) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "block length too short %u", (uint32_t)bh.block_total_length); + if(bh.block_total_length < sizeof(bh) + hdr_len + 4) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "block length too short %u", + (uint32_t)bh.block_total_length); return SCAP_FAILURE; } @@ -1941,22 +1886,26 @@ static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_ // readlen = bh.block_total_length - sizeof(bh); // Non-large block types have an uint16_max maximum size - if (bh.block_type != EV_BLOCK_TYPE_V2_LARGE && bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) { + if(bh.block_type != EV_BLOCK_TYPE_V2_LARGE && bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) { if(readlen > READER_BUF_SIZE) { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "event block length %u greater than NON-LARGE read buffer size %u", - readlen, - READER_BUF_SIZE); + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "event block length %u greater than NON-LARGE read buffer size %u", + readlen, + READER_BUF_SIZE); return SCAP_FAILURE; } - } else if (readlen > handle->m_reader_evt_buf_size) { + } else if(readlen > handle->m_reader_evt_buf_size) { // Try to allocate a buffer large enough char *tmp = realloc(handle->m_reader_evt_buf, readlen); - if (!tmp) { + if(!tmp) { free(handle->m_reader_evt_buf); handle->m_reader_evt_buf = NULL; - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "event block length %u greater than read buffer size %zu", - readlen, - handle->m_reader_evt_buf_size); + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "event block length %u greater than read buffer size %zu", + readlen, + handle->m_reader_evt_buf_size); return SCAP_FAILURE; } handle->m_reader_evt_buf = tmp; @@ -1971,19 +1920,17 @@ static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_ // *pdevid = *(uint16_t *)handle->m_reader_evt_buf; - if(bh.block_type == EVF_BLOCK_TYPE || bh.block_type == EVF_BLOCK_TYPE_V2 || bh.block_type == EVF_BLOCK_TYPE_V2_LARGE) - { + if(bh.block_type == EVF_BLOCK_TYPE || bh.block_type == EVF_BLOCK_TYPE_V2 || + bh.block_type == EVF_BLOCK_TYPE_V2_LARGE) { memcpy(pflags, handle->m_reader_evt_buf + sizeof(uint16_t), sizeof(uint32_t)); - *pevent = (struct ppm_evt_hdr *)(handle->m_reader_evt_buf + sizeof(uint16_t) + sizeof(uint32_t)); - } - else - { + *pevent = (struct ppm_evt_hdr *)(handle->m_reader_evt_buf + sizeof(uint16_t) + + sizeof(uint32_t)); + } else { *pflags = 0; *pevent = (struct ppm_evt_hdr *)(handle->m_reader_evt_buf + sizeof(uint16_t)); } - if((*pevent)->type >= PPM_EVENT_MAX) - { + if((*pevent)->type >= PPM_EVENT_MAX) { // // We're reading a capture that contains new syscalls. // We can't do anything else that skips them. @@ -1991,32 +1938,32 @@ static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_ continue; } - if(bh.block_type != EV_BLOCK_TYPE_V2 && - bh.block_type != EV_BLOCK_TYPE_V2_LARGE && - bh.block_type != EVF_BLOCK_TYPE_V2 && - bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) - { + if(bh.block_type != EV_BLOCK_TYPE_V2 && bh.block_type != EV_BLOCK_TYPE_V2_LARGE && + bh.block_type != EVF_BLOCK_TYPE_V2 && bh.block_type != EVF_BLOCK_TYPE_V2_LARGE) { // // We're reading an old capture whose events don't have nparams in the header. // Convert it to the current version. // - if((readlen + sizeof(uint32_t)) > READER_BUF_SIZE) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "cannot convert v1 event block to v2 (%lu greater than read buffer size %u)", - readlen + sizeof(uint32_t), - READER_BUF_SIZE); + if((readlen + sizeof(uint32_t)) > READER_BUF_SIZE) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "cannot convert v1 event block to v2 (%lu greater than read buffer size " + "%u)", + readlen + sizeof(uint32_t), + READER_BUF_SIZE); return SCAP_FAILURE; } memmove((char *)*pevent + sizeof(struct ppm_evt_hdr), - (char *)*pevent + sizeof(struct ppm_evt_hdr) - sizeof(uint32_t), - readlen - ((char *)*pevent - handle->m_reader_evt_buf) - (sizeof(struct ppm_evt_hdr) - sizeof(uint32_t))); + (char *)*pevent + sizeof(struct ppm_evt_hdr) - sizeof(uint32_t), + readlen - ((char *)*pevent - handle->m_reader_evt_buf) - + (sizeof(struct ppm_evt_hdr) - sizeof(uint32_t))); (*pevent)->len += sizeof(uint32_t); // In old captures, the length of PPME_NOTIFICATION_E and PPME_INFRASTRUCTURE_EVENT_E // is not correct. Adjust it, otherwise the following code will never find a match - if((*pevent)->type == PPME_NOTIFICATION_E || (*pevent)->type == PPME_INFRASTRUCTURE_EVENT_E) - { + if((*pevent)->type == PPME_NOTIFICATION_E || + (*pevent)->type == PPME_INFRASTRUCTURE_EVENT_E) { (*pevent)->len -= 3; } @@ -2029,33 +1976,33 @@ static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_ uint16_t *lens = (uint16_t *)((char *)*pevent + sizeof(struct ppm_evt_hdr)); uint32_t nparams; bool done = false; - for(nparams = g_event_info[(*pevent)->type].nparams; (int)nparams >= 0; nparams--) - { + for(nparams = g_event_info[(*pevent)->type].nparams; (int)nparams >= 0; nparams--) { char *valptr = (char *)lens + nparams * sizeof(uint16_t); - if(valptr > end) - { + if(valptr > end) { continue; } uint32_t i; - for(i = 0; i < nparams; i++) - { + for(i = 0; i < nparams; i++) { valptr += lens[i]; } - if(valptr < end) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "cannot convert v1 event block to v2 (corrupted trace file - can't calculate nparams)."); + if(valptr < end) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "cannot convert v1 event block to v2 (corrupted trace file - can't " + "calculate nparams)."); return SCAP_FAILURE; } ASSERT(valptr >= end); - if(valptr == end) - { + if(valptr == end) { done = true; break; } } - if(!done) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "cannot convert v1 event block to v2 (corrupted trace file - can't calculate nparams) (2)."); + if(!done) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "cannot convert v1 event block to v2 (corrupted trace file - can't " + "calculate nparams) (2)."); return SCAP_FAILURE; } (*pevent)->nparams = nparams; @@ -2067,53 +2014,50 @@ static int32_t next(struct scap_engine_handle engine, scap_evt **pevent, uint16_ return SCAP_SUCCESS; } -uint64_t scap_savefile_ftell(struct scap_engine_handle engine) -{ - scap_reader_t* reader = HANDLE(engine)->m_reader; +uint64_t scap_savefile_ftell(struct scap_engine_handle engine) { + scap_reader_t *reader = HANDLE(engine)->m_reader; return reader->tell(reader); } -void scap_savefile_fseek(struct scap_engine_handle engine, uint64_t off) -{ - scap_reader_t* reader = HANDLE(engine)->m_reader; +void scap_savefile_fseek(struct scap_engine_handle engine, uint64_t off) { + scap_reader_t *reader = HANDLE(engine)->m_reader; reader->seek(reader, off, SEEK_SET); } -static int32_t -scap_savefile_init_platform(struct scap_platform *platform, char *lasterr, struct scap_engine_handle engine, - struct scap_open_args *oargs) -{ +static int32_t scap_savefile_init_platform(struct scap_platform *platform, + char *lasterr, + struct scap_engine_handle engine, + struct scap_open_args *oargs) { return SCAP_SUCCESS; } -static int32_t scap_savefile_close_platform(struct scap_platform* platform) -{ +static int32_t scap_savefile_close_platform(struct scap_platform *platform) { return SCAP_SUCCESS; } -static void scap_savefile_free_platform(struct scap_platform* platform) -{ +static void scap_savefile_free_platform(struct scap_platform *platform) { free(platform); } -bool scap_savefile_is_thread_alive(struct scap_platform* platform, int64_t pid, int64_t tid, const char* comm) -{ +bool scap_savefile_is_thread_alive(struct scap_platform *platform, + int64_t pid, + int64_t tid, + const char *comm) { return false; } static const struct scap_platform_vtable scap_savefile_platform_vtable = { - .init_platform = scap_savefile_init_platform, - .is_thread_alive = scap_savefile_is_thread_alive, - .close_platform = scap_savefile_close_platform, - .free_platform = scap_savefile_free_platform, + .init_platform = scap_savefile_init_platform, + .is_thread_alive = scap_savefile_is_thread_alive, + .close_platform = scap_savefile_close_platform, + .free_platform = scap_savefile_free_platform, }; -struct scap_platform *scap_savefile_alloc_platform(proc_entry_callback proc_callback, void *proc_callback_context) -{ +struct scap_platform *scap_savefile_alloc_platform(proc_entry_callback proc_callback, + void *proc_callback_context) { struct scap_savefile_platform *platform = calloc(1, sizeof(*platform)); - if(platform == NULL) - { + if(platform == NULL) { return NULL; } @@ -2125,65 +2069,51 @@ struct scap_platform *scap_savefile_alloc_platform(proc_entry_callback proc_call return &platform->m_generic; } -static void* alloc_handle(struct scap* main_handle, char* lasterr_ptr) -{ +static void *alloc_handle(struct scap *main_handle, char *lasterr_ptr) { struct savefile_engine *engine = calloc(1, sizeof(struct savefile_engine)); - if(engine) - { + if(engine) { engine->m_lasterr = lasterr_ptr; } return engine; - } -static int32_t init(struct scap* main_handle, struct scap_open_args* oargs) -{ +static int32_t init(struct scap *main_handle, struct scap_open_args *oargs) { gzFile gzfile; int res; struct savefile_engine *handle = main_handle->m_engine.m_handle; - struct scap_savefile_engine_params* params = oargs->engine_params; + struct scap_savefile_engine_params *params = oargs->engine_params; int fd = params->fd; - const char* fname = params->fname; + const char *fname = params->fname; uint64_t start_offset = params->start_offset; uint32_t fbuffer_size = params->fbuffer_size; struct scap_platform *platform = params->platform; handle->m_platform = params->platform; - if(fd != 0) - { + if(fd != 0) { gzfile = gzdopen(fd, "rb"); - } - else - { + } else { gzfile = gzopen(fname, "rb"); } - if(gzfile == NULL) - { - if(fd != 0) - { + if(gzfile == NULL) { + if(fd != 0) { snprintf(main_handle->m_lasterr, SCAP_LASTERR_SIZE, "can't open fd %d", fd); - } - else - { + } else { snprintf(main_handle->m_lasterr, SCAP_LASTERR_SIZE, "can't open file %s", fname); } return SCAP_FAILURE; } - scap_reader_t* reader = scap_reader_open_gzfile(gzfile); - if(!reader) - { + scap_reader_t *reader = scap_reader_open_gzfile(gzfile); + if(!reader) { gzclose(gzfile); return SCAP_FAILURE; } - if (fbuffer_size > 0) - { - scap_reader_t* buffered_reader = scap_reader_open_buffered(reader, fbuffer_size, true); - if(!buffered_reader) - { + if(fbuffer_size > 0) { + scap_reader_t *buffered_reader = scap_reader_open_buffered(reader, fbuffer_size, true); + if(!buffered_reader) { reader->close(reader); return SCAP_FAILURE; } @@ -2193,42 +2123,35 @@ static int32_t init(struct scap* main_handle, struct scap_open_args* oargs) // // If this is a merged file, we might have to move the read offset to the next section // - if(start_offset != 0) - { + if(start_offset != 0) { scap_fseek(main_handle, start_offset); } handle->m_use_last_block_header = false; - res = scap_read_init( - handle, - reader, - &platform->m_machine_info, - &platform->m_proclist, - &platform->m_addrlist, - &platform->m_userlist, - main_handle->m_lasterr - ); - - if(res != SCAP_SUCCESS) - { + res = scap_read_init(handle, + reader, + &platform->m_machine_info, + &platform->m_proclist, + &platform->m_addrlist, + &platform->m_userlist, + main_handle->m_lasterr); + + if(res != SCAP_SUCCESS) { reader->close(reader); return res; } - handle->m_reader_evt_buf = (char*)malloc(READER_BUF_SIZE); - if(!handle->m_reader_evt_buf) - { + handle->m_reader_evt_buf = (char *)malloc(READER_BUF_SIZE); + if(!handle->m_reader_evt_buf) { snprintf(main_handle->m_lasterr, SCAP_LASTERR_SIZE, "error allocating the read buffer"); return SCAP_FAILURE; } handle->m_reader_evt_buf_size = READER_BUF_SIZE; handle->m_reader = reader; - if(!oargs->import_users) - { - if(platform->m_userlist != NULL) - { + if(!oargs->import_users) { + if(platform->m_userlist != NULL) { scap_free_userlist(platform->m_userlist); platform->m_userlist = NULL; } @@ -2237,22 +2160,18 @@ static int32_t init(struct scap* main_handle, struct scap_open_args* oargs) return SCAP_SUCCESS; } -static void free_handle(struct scap_engine_handle engine) -{ +static void free_handle(struct scap_engine_handle engine) { free(engine.m_handle); } -static int32_t scap_savefile_close(struct scap_engine_handle engine) -{ - struct savefile_engine* handle = engine.m_handle; - if (handle->m_reader) - { +static int32_t scap_savefile_close(struct scap_engine_handle engine) { + struct savefile_engine *handle = engine.m_handle; + if(handle->m_reader) { handle->m_reader->close(handle->m_reader); handle->m_reader = NULL; } - if(handle->m_reader_evt_buf) - { + if(handle->m_reader_evt_buf) { free(handle->m_reader_evt_buf); handle->m_reader_evt_buf = NULL; } @@ -2260,60 +2179,59 @@ static int32_t scap_savefile_close(struct scap_engine_handle engine) return SCAP_SUCCESS; } -static int32_t scap_savefile_restart_capture(scap_t* handle) -{ +static int32_t scap_savefile_restart_capture(scap_t *handle) { struct savefile_engine *engine = handle->m_engine.m_handle; struct scap_platform *platform = engine->m_platform; int32_t res; scap_platform_close(platform); - if((res = scap_read_init( - engine, - engine->m_reader, - &platform->m_machine_info, - &platform->m_proclist, - &platform->m_addrlist, - &platform->m_userlist, - handle->m_lasterr)) != SCAP_SUCCESS) - { + if((res = scap_read_init(engine, + engine->m_reader, + &platform->m_machine_info, + &platform->m_proclist, + &platform->m_addrlist, + &platform->m_userlist, + handle->m_lasterr)) != SCAP_SUCCESS) { char error[SCAP_LASTERR_SIZE]; - snprintf(error, SCAP_LASTERR_SIZE, "could not restart capture: %s", scap_getlasterr(handle)); + snprintf(error, + SCAP_LASTERR_SIZE, + "could not restart capture: %s", + scap_getlasterr(handle)); strlcpy(handle->m_lasterr, error, SCAP_LASTERR_SIZE); } return res; } -static int64_t get_readfile_offset(struct scap_engine_handle engine) -{ +static int64_t get_readfile_offset(struct scap_engine_handle engine) { return HANDLE(engine)->m_reader->offset(HANDLE(engine)->m_reader); } static struct scap_savefile_vtable savefile_ops = { - .ftell_capture = scap_savefile_ftell, - .fseek_capture = scap_savefile_fseek, + .ftell_capture = scap_savefile_ftell, + .fseek_capture = scap_savefile_fseek, - .restart_capture = scap_savefile_restart_capture, - .get_readfile_offset = get_readfile_offset, + .restart_capture = scap_savefile_restart_capture, + .get_readfile_offset = get_readfile_offset, }; struct scap_vtable scap_savefile_engine = { - .name = SAVEFILE_ENGINE, - .savefile_ops = &savefile_ops, - - .alloc_handle = alloc_handle, - .init = init, - .free_handle = free_handle, - .close = scap_savefile_close, - .next = next, - .start_capture = noop_start_capture, - .stop_capture = noop_stop_capture, - .configure = noop_configure, - .get_stats = noop_get_stats, - .get_stats_v2 = noop_get_stats_v2, - .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, - .get_n_devs = noop_get_n_devs, - .get_max_buf_used = noop_get_max_buf_used, - .get_api_version = NULL, - .get_schema_version = NULL, + .name = SAVEFILE_ENGINE, + .savefile_ops = &savefile_ops, + + .alloc_handle = alloc_handle, + .init = init, + .free_handle = free_handle, + .close = scap_savefile_close, + .next = next, + .start_capture = noop_start_capture, + .stop_capture = noop_stop_capture, + .configure = noop_configure, + .get_stats = noop_get_stats, + .get_stats_v2 = noop_get_stats_v2, + .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, + .get_n_devs = noop_get_n_devs, + .get_max_buf_used = noop_get_max_buf_used, + .get_api_version = NULL, + .get_schema_version = NULL, }; diff --git a/userspace/libscap/engine/source_plugin/CMakeLists.txt b/userspace/libscap/engine/source_plugin/CMakeLists.txt index d12c5f1831..d7f05f73cd 100644 --- a/userspace/libscap/engine/source_plugin/CMakeLists.txt +++ b/userspace/libscap/engine/source_plugin/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # add_library(scap_engine_source_plugin source_plugin.c) target_link_libraries(scap_engine_source_plugin PRIVATE scap_engine_noop) diff --git a/userspace/libscap/engine/source_plugin/plugin_info.h b/userspace/libscap/engine/source_plugin/plugin_info.h index 5b49b16575..c57421b464 100644 --- a/userspace/libscap/engine/source_plugin/plugin_info.h +++ b/userspace/libscap/engine/source_plugin/plugin_info.h @@ -24,15 +24,17 @@ limitations under the License. // Small C interface that is passed down to libscap // and is used as a plugin event source. // -typedef struct -{ +typedef struct { uint32_t id; - const char *name; - ss_plugin_t *state; - ss_instance_t *handle; + const char* name; + ss_plugin_t* state; + ss_instance_t* handle; ss_instance_t* (*open)(ss_plugin_t* s, const char* params, ss_plugin_rc* rc); void (*close)(ss_plugin_t* s, ss_instance_t* h); - ss_plugin_rc (*next_batch)(ss_plugin_t* s, ss_instance_t* h, uint32_t *nevts, ss_plugin_event ***evts); - const char *(*get_last_error)(ss_plugin_t *s); + ss_plugin_rc (*next_batch)(ss_plugin_t* s, + ss_instance_t* h, + uint32_t* nevts, + ss_plugin_event*** evts); + const char* (*get_last_error)(ss_plugin_t* s); } scap_source_plugin; diff --git a/userspace/libscap/engine/source_plugin/source_plugin.c b/userspace/libscap/engine/source_plugin/source_plugin.c index ab6ba8b9a4..9039bef5ac 100644 --- a/userspace/libscap/engine/source_plugin/source_plugin.c +++ b/userspace/libscap/engine/source_plugin/source_plugin.c @@ -31,8 +31,8 @@ limitations under the License. #include #include -static const char * const source_plugin_counters_stats_names[] = { - [N_EVTS] = "n_evts", +static const char* const source_plugin_counters_stats_names[] = { + [N_EVTS] = "n_evts", }; // We need to check that ppm_evt_hdr and ss_plugin_event are the same struct @@ -41,42 +41,40 @@ static const char * const source_plugin_counters_stats_names[] = { // same time not sharing the same headers. #if defined __GNUC__ || __STDC_VERSION__ >= 201112L _Static_assert(sizeof(struct ppm_evt_hdr) == sizeof(ss_plugin_event), - "structs ppm_evt_hdr and ss_plugin_event are out of sync"); + "structs ppm_evt_hdr and ss_plugin_event are out of sync"); _Static_assert(offsetof(struct ppm_evt_hdr, ts) == offsetof(ss_plugin_event, ts), - "structs ppm_evt_hdr and ss_plugin_event are out of sync (ts)"); + "structs ppm_evt_hdr and ss_plugin_event are out of sync (ts)"); _Static_assert(offsetof(struct ppm_evt_hdr, tid) == offsetof(ss_plugin_event, tid), - "structs ppm_evt_hdr and ss_plugin_event are out of sync (tid)"); + "structs ppm_evt_hdr and ss_plugin_event are out of sync (tid)"); _Static_assert(offsetof(struct ppm_evt_hdr, len) == offsetof(ss_plugin_event, len), - "structs ppm_evt_hdr and ss_plugin_event are out of sync (len)"); + "structs ppm_evt_hdr and ss_plugin_event are out of sync (len)"); _Static_assert(offsetof(struct ppm_evt_hdr, type) == offsetof(ss_plugin_event, type), - "structs ppm_evt_hdr and ss_plugin_event are out of sync (type)"); + "structs ppm_evt_hdr and ss_plugin_event are out of sync (type)"); _Static_assert(offsetof(struct ppm_evt_hdr, nparams) == offsetof(ss_plugin_event, nparams), - "structs ppm_evt_hdr and ss_plugin_event are out of sync (nparams)"); + "structs ppm_evt_hdr and ss_plugin_event are out of sync (nparams)"); #endif // We need to check that ppm_param_type and ss_plugin_field_type follow // the same enumeratives at compile-time. #if defined __GNUC__ || __STDC_VERSION__ >= 201112L -_Static_assert((uint32_t) FTYPE_UINT64 == (uint32_t) PT_UINT64, - "ss_plugin_field_type and ppm_param_type are out of sync (UINT64)"); -_Static_assert((uint32_t) FTYPE_STRING == (uint32_t) PT_CHARBUF, - "ss_plugin_field_type and ppm_param_type are out of sync (STRING)"); -_Static_assert((uint32_t) FTYPE_RELTIME == (uint32_t) PT_RELTIME, - "ss_plugin_field_type and ppm_param_type are out of sync (RELTIME)"); -_Static_assert((uint32_t) FTYPE_ABSTIME == (uint32_t) PT_ABSTIME, - "ss_plugin_field_type and ppm_param_type are out of sync (ABSTIME)"); -_Static_assert((uint32_t) FTYPE_BOOL == (uint32_t) PT_BOOL, - "ss_plugin_field_type and ppm_param_type are out of sync (BOOL)"); -_Static_assert((uint32_t) FTYPE_IPADDR == (uint32_t) PT_IPADDR, - "ss_plugin_field_type and ppm_param_type are out of sync (IPADDR)"); -_Static_assert((uint32_t) FTYPE_IPNET == (uint32_t) PT_IPNET, - "ss_plugin_field_type and ppm_param_type are out of sync (IPNET)"); +_Static_assert((uint32_t)FTYPE_UINT64 == (uint32_t)PT_UINT64, + "ss_plugin_field_type and ppm_param_type are out of sync (UINT64)"); +_Static_assert((uint32_t)FTYPE_STRING == (uint32_t)PT_CHARBUF, + "ss_plugin_field_type and ppm_param_type are out of sync (STRING)"); +_Static_assert((uint32_t)FTYPE_RELTIME == (uint32_t)PT_RELTIME, + "ss_plugin_field_type and ppm_param_type are out of sync (RELTIME)"); +_Static_assert((uint32_t)FTYPE_ABSTIME == (uint32_t)PT_ABSTIME, + "ss_plugin_field_type and ppm_param_type are out of sync (ABSTIME)"); +_Static_assert((uint32_t)FTYPE_BOOL == (uint32_t)PT_BOOL, + "ss_plugin_field_type and ppm_param_type are out of sync (BOOL)"); +_Static_assert((uint32_t)FTYPE_IPADDR == (uint32_t)PT_IPADDR, + "ss_plugin_field_type and ppm_param_type are out of sync (IPADDR)"); +_Static_assert((uint32_t)FTYPE_IPNET == (uint32_t)PT_IPNET, + "ss_plugin_field_type and ppm_param_type are out of sync (IPNET)"); #endif -static int32_t plugin_rc_to_scap_rc(ss_plugin_rc plugin_rc) -{ - switch(plugin_rc) - { +static int32_t plugin_rc_to_scap_rc(ss_plugin_rc plugin_rc) { + switch(plugin_rc) { case SS_PLUGIN_SUCCESS: return SCAP_SUCCESS; break; @@ -101,21 +99,18 @@ static int32_t plugin_rc_to_scap_rc(ss_plugin_rc plugin_rc) return SCAP_FAILURE; } -static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) -{ - struct source_plugin_engine *engine = calloc(1, sizeof(struct source_plugin_engine)); - if(engine) - { +static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) { + struct source_plugin_engine* engine = calloc(1, sizeof(struct source_plugin_engine)); + if(engine) { engine->m_lasterr = lasterr_ptr; } return engine; } -static int32_t init(scap_t* main_handle, scap_open_args* oargs) -{ +static int32_t init(scap_t* main_handle, scap_open_args* oargs) { int32_t rc; - struct source_plugin_engine *handle = main_handle->m_engine.m_handle; - struct scap_source_plugin_engine_params *params = oargs->engine_params; + struct source_plugin_engine* handle = main_handle->m_engine.m_handle; + struct scap_source_plugin_engine_params* params = oargs->engine_params; handle->m_input_plugin = params->input_plugin; // Set the rc to SCAP_FAILURE now, so in the unlikely event @@ -134,41 +129,40 @@ static int32_t init(scap_t* main_handle, scap_open_args* oargs) handle->m_input_plugin_batch_idx = 0; handle->m_input_plugin_last_batch_res = SCAP_SUCCESS; - if(rc != SCAP_SUCCESS) - { - const char *errstr = handle->m_input_plugin->get_last_error(handle->m_input_plugin->state); + if(rc != SCAP_SUCCESS) { + const char* errstr = handle->m_input_plugin->get_last_error(handle->m_input_plugin->state); snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "%s", errstr); } return rc; } -static int close_engine(struct scap_engine_handle engine) -{ - struct source_plugin_engine *handle = engine.m_handle; +static int close_engine(struct scap_engine_handle engine) { + struct source_plugin_engine* handle = engine.m_handle; // We could arrive here without having initialized 'm_input_plugin'. - if(handle->m_input_plugin != NULL) - { - handle->m_input_plugin->close(handle->m_input_plugin->state, handle->m_input_plugin->handle); + if(handle->m_input_plugin != NULL) { + handle->m_input_plugin->close(handle->m_input_plugin->state, + handle->m_input_plugin->handle); handle->m_input_plugin->handle = NULL; } return SCAP_SUCCESS; } -static int32_t next(struct scap_engine_handle engine, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags) -{ - struct source_plugin_engine *handle = engine.m_handle; - char *lasterr = HANDLE(engine)->m_lasterr; +static int32_t next(struct scap_engine_handle engine, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags) { + struct source_plugin_engine* handle = engine.m_handle; + char* lasterr = HANDLE(engine)->m_lasterr; /* we have to read a new batch */ - if(handle->m_input_plugin_batch_idx >= handle->m_input_plugin_batch_nevts) - { - if(handle->m_input_plugin_last_batch_res != SS_PLUGIN_SUCCESS) - { - if(handle->m_input_plugin_last_batch_res != SCAP_TIMEOUT && handle->m_input_plugin_last_batch_res != SCAP_EOF) - { - const char *errstr = handle->m_input_plugin->get_last_error(handle->m_input_plugin->state); + if(handle->m_input_plugin_batch_idx >= handle->m_input_plugin_batch_nevts) { + if(handle->m_input_plugin_last_batch_res != SS_PLUGIN_SUCCESS) { + if(handle->m_input_plugin_last_batch_res != SCAP_TIMEOUT && + handle->m_input_plugin_last_batch_res != SCAP_EOF) { + const char* errstr = + handle->m_input_plugin->get_last_error(handle->m_input_plugin->state); strlcpy(lasterr, errstr, SCAP_LASTERR_SIZE); } int32_t tres = handle->m_input_plugin_last_batch_res; @@ -176,25 +170,26 @@ static int32_t next(struct scap_engine_handle engine, scap_evt** pevent, uint16_ return tres; } - int32_t plugin_res = handle->m_input_plugin->next_batch(handle->m_input_plugin->state, - handle->m_input_plugin->handle, - &(handle->m_input_plugin_batch_nevts), - &(handle->m_input_plugin_batch_evts)); + int32_t plugin_res = + handle->m_input_plugin->next_batch(handle->m_input_plugin->state, + handle->m_input_plugin->handle, + &(handle->m_input_plugin_batch_nevts), + &(handle->m_input_plugin_batch_evts)); handle->m_input_plugin_last_batch_res = plugin_rc_to_scap_rc(plugin_res); - if(handle->m_input_plugin_batch_nevts == 0) - { - if(handle->m_input_plugin_last_batch_res == SCAP_SUCCESS) - { - snprintf(lasterr, SCAP_LASTERR_SIZE, "unexpected 0 size event returned by plugin %s", handle->m_input_plugin->name); + if(handle->m_input_plugin_batch_nevts == 0) { + if(handle->m_input_plugin_last_batch_res == SCAP_SUCCESS) { + snprintf(lasterr, + SCAP_LASTERR_SIZE, + "unexpected 0 size event returned by plugin %s", + handle->m_input_plugin->name); ASSERT(false); return SCAP_FAILURE; - } - else - { - if(handle->m_input_plugin_last_batch_res != SCAP_TIMEOUT && handle->m_input_plugin_last_batch_res != SCAP_EOF) - { - const char *errstr = handle->m_input_plugin->get_last_error(handle->m_input_plugin->state); + } else { + if(handle->m_input_plugin_last_batch_res != SCAP_TIMEOUT && + handle->m_input_plugin_last_batch_res != SCAP_EOF) { + const char* errstr = + handle->m_input_plugin->get_last_error(handle->m_input_plugin->state); snprintf(lasterr, SCAP_LASTERR_SIZE, "%s", errstr); } return handle->m_input_plugin_last_batch_res; @@ -205,57 +200,61 @@ static int32_t next(struct scap_engine_handle engine, scap_evt** pevent, uint16_ } uint32_t pos = handle->m_input_plugin_batch_idx; - scap_evt* evt = (scap_evt*) handle->m_input_plugin_batch_evts[pos]; + scap_evt* evt = (scap_evt*)handle->m_input_plugin_batch_evts[pos]; // Sanity checks in case a plugin implements a non-syscall event source. // If a plugin has event sourcing capability and has a specific ID, then // it is allowed to produce only plugin events of its own event source. - uint8_t* pplugin_id = (uint8_t*) evt + sizeof(scap_evt) + sizeof(uint32_t) + sizeof(uint32_t); + uint8_t* pplugin_id = (uint8_t*)evt + sizeof(scap_evt) + sizeof(uint32_t) + sizeof(uint32_t); uint32_t plugin_id; memcpy(&plugin_id, pplugin_id, sizeof(plugin_id)); - if (handle->m_input_plugin->id != 0) - { + if(handle->m_input_plugin->id != 0) { /* - * | scap_evt | len_id (4B) | len_pl (4B) | id | payload | - * Note: we need to use 4B for len_id too because the - * PPME_PLUGINEVENT_E has EF_LARGE_PAYLOAD flag! - */ - if (evt->type != PPME_PLUGINEVENT_E || evt->nparams != 2) - { - snprintf(lasterr, SCAP_LASTERR_SIZE, "malformed plugin event produced by plugin: '%s'", handle->m_input_plugin->name); + * | scap_evt | len_id (4B) | len_pl (4B) | id | payload | + * Note: we need to use 4B for len_id too because the + * PPME_PLUGINEVENT_E has EF_LARGE_PAYLOAD flag! + */ + if(evt->type != PPME_PLUGINEVENT_E || evt->nparams != 2) { + snprintf(lasterr, + SCAP_LASTERR_SIZE, + "malformed plugin event produced by plugin: '%s'", + handle->m_input_plugin->name); return SCAP_FAILURE; } // forcely setting plugin ID with the one of the open plugin - if (plugin_id == 0) - { + if(plugin_id == 0) { plugin_id = handle->m_input_plugin->id; memcpy(pplugin_id, &plugin_id, sizeof(plugin_id)); - } - else if (plugin_id != handle->m_input_plugin->id) - { - snprintf(lasterr, SCAP_LASTERR_SIZE, "unexpected plugin ID in plugin event: plugin='%s', expected_id=%d, actual_id=%d", handle->m_input_plugin->name, handle->m_input_plugin->id, plugin_id); + } else if(plugin_id != handle->m_input_plugin->id) { + snprintf(lasterr, + SCAP_LASTERR_SIZE, + "unexpected plugin ID in plugin event: plugin='%s', expected_id=%d, " + "actual_id=%d", + handle->m_input_plugin->name, + handle->m_input_plugin->id, + plugin_id); return SCAP_FAILURE; } } - if (evt->type == PPME_PLUGINEVENT_E) - { + if(evt->type == PPME_PLUGINEVENT_E) { // a zero plugin ID is not allowed for PPME_PLUGINEVENT_E - if (plugin_id == 0) - { - snprintf(lasterr, SCAP_LASTERR_SIZE, "malformed plugin event produced by plugin (no ID): '%s'", handle->m_input_plugin->name); + if(plugin_id == 0) { + snprintf(lasterr, + SCAP_LASTERR_SIZE, + "malformed plugin event produced by plugin (no ID): '%s'", + handle->m_input_plugin->name); return SCAP_FAILURE; } // plugin events have no thread associated - evt->tid = (uint64_t) -1; + evt->tid = (uint64_t)-1; } // automatically set timestamp if none was specified - if(evt->ts == UINT64_MAX) - { + if(evt->ts == UINT64_MAX) { evt->ts = get_timestamp_ns(); } @@ -267,28 +266,27 @@ static int32_t next(struct scap_engine_handle engine, scap_evt** pevent, uint16_ return SCAP_SUCCESS; } -static int32_t get_stats(struct scap_engine_handle engine, scap_stats* stats) -{ - struct source_plugin_engine *handle = engine.m_handle; +static int32_t get_stats(struct scap_engine_handle engine, scap_stats* stats) { + struct source_plugin_engine* handle = engine.m_handle; stats->n_evts = handle->m_nevts; return SCAP_SUCCESS; } -const struct metrics_v2* get_source_plugin_stats_v2(struct scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc) -{ - struct source_plugin_engine *handle = engine.m_handle; +const struct metrics_v2* get_source_plugin_stats_v2(struct scap_engine_handle engine, + uint32_t flags, + uint32_t* nstats, + int32_t* rc) { + struct source_plugin_engine* handle = engine.m_handle; *nstats = MAX_SOURCE_PLUGIN_COUNTERS_STATS; metrics_v2* stats = handle->m_stats; - if (!stats) - { + if(!stats) { *nstats = 0; *rc = SCAP_FAILURE; return NULL; } /* SOURCE PLUGIN STATS COUNTERS */ - for(uint32_t stat = 0; stat < MAX_SOURCE_PLUGIN_COUNTERS_STATS; stat++) - { + for(uint32_t stat = 0; stat < MAX_SOURCE_PLUGIN_COUNTERS_STATS; stat++) { stats[stat].type = METRIC_VALUE_TYPE_U64; stats[stat].value.u64 = 0; stats[stat].unit = METRIC_VALUE_UNIT_COUNT; @@ -302,22 +300,22 @@ const struct metrics_v2* get_source_plugin_stats_v2(struct scap_engine_handle en } const struct scap_vtable scap_source_plugin_engine = { - .name = SOURCE_PLUGIN_ENGINE, - .savefile_ops = NULL, - - .alloc_handle = alloc_handle, - .init = init, - .free_handle = noop_free_handle, - .close = close_engine, - .next = next, - .start_capture = noop_start_capture, - .stop_capture = noop_stop_capture, - .configure = noop_configure, - .get_stats = get_stats, - .get_stats_v2 = get_source_plugin_stats_v2, - .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, - .get_n_devs = noop_get_n_devs, - .get_max_buf_used = noop_get_max_buf_used, - .get_api_version = NULL, - .get_schema_version = NULL, + .name = SOURCE_PLUGIN_ENGINE, + .savefile_ops = NULL, + + .alloc_handle = alloc_handle, + .init = init, + .free_handle = noop_free_handle, + .close = close_engine, + .next = next, + .start_capture = noop_start_capture, + .stop_capture = noop_stop_capture, + .configure = noop_configure, + .get_stats = get_stats, + .get_stats_v2 = get_source_plugin_stats_v2, + .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, + .get_n_devs = noop_get_n_devs, + .get_max_buf_used = noop_get_max_buf_used, + .get_api_version = NULL, + .get_schema_version = NULL, }; diff --git a/userspace/libscap/engine/source_plugin/source_plugin.h b/userspace/libscap/engine/source_plugin/source_plugin.h index 8b871e08df..9e836b3b73 100644 --- a/userspace/libscap/engine/source_plugin/source_plugin.h +++ b/userspace/libscap/engine/source_plugin/source_plugin.h @@ -24,8 +24,7 @@ limitations under the License. struct scap; -struct source_plugin_engine -{ +struct source_plugin_engine { char* m_lasterr; // Total number of events sourced by the plugin @@ -50,5 +49,4 @@ struct source_plugin_engine // Stats v2. metrics_v2 m_stats[MAX_SOURCE_PLUGIN_COUNTERS_STATS]; - }; diff --git a/userspace/libscap/engine/source_plugin/source_plugin_public.h b/userspace/libscap/engine/source_plugin/source_plugin_public.h index 4cfdde500d..7b0ab4a237 100644 --- a/userspace/libscap/engine/source_plugin/source_plugin_public.h +++ b/userspace/libscap/engine/source_plugin/source_plugin_public.h @@ -19,15 +19,15 @@ limitations under the License. #define SOURCE_PLUGIN_ENGINE "source_plugin" #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - struct scap_source_plugin_engine_params - { - scap_source_plugin* input_plugin; ///< use this to configure a source plugin that will produce the events for this capture - char* input_plugin_params; ///< optional parameters string for the source plugin pointed by src_plugin - }; +struct scap_source_plugin_engine_params { + scap_source_plugin* input_plugin; ///< use this to configure a source plugin that will produce + ///< the events for this capture + char* input_plugin_params; ///< optional parameters string for the source plugin pointed by + ///< src_plugin +}; #ifdef __cplusplus }; diff --git a/userspace/libscap/engine/source_plugin/source_plugin_stats.h b/userspace/libscap/engine/source_plugin/source_plugin_stats.h index 852d5797ed..934bdfa8bd 100644 --- a/userspace/libscap/engine/source_plugin/source_plugin_stats.h +++ b/userspace/libscap/engine/source_plugin/source_plugin_stats.h @@ -21,4 +21,4 @@ limitations under the License. typedef enum source_plugin_counters_stats { N_EVTS = 0, MAX_SOURCE_PLUGIN_COUNTERS_STATS, -}source_plugin_counters_stats; +} source_plugin_counters_stats; diff --git a/userspace/libscap/engine/test_input/CMakeLists.txt b/userspace/libscap/engine/test_input/CMakeLists.txt index 1f0f57d6ad..33f3152190 100644 --- a/userspace/libscap/engine/test_input/CMakeLists.txt +++ b/userspace/libscap/engine/test_input/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # add_library(scap_engine_test_input test_input.c test_input_platform.c) target_link_libraries(scap_engine_test_input PRIVATE scap_engine_noop scap_platform_util) diff --git a/userspace/libscap/engine/test_input/scap_test.h b/userspace/libscap/engine/test_input/scap_test.h index 31ae964c02..9afd0298b1 100644 --- a/userspace/libscap/engine/test_input/scap_test.h +++ b/userspace/libscap/engine/test_input/scap_test.h @@ -29,20 +29,20 @@ struct scap_threadinfo; struct scap_fdinfo; struct scap_test_fdinfo_data { - const struct scap_fdinfo *fdinfos; - size_t fdinfo_count; + const struct scap_fdinfo *fdinfos; + size_t fdinfo_count; }; typedef struct scap_test_thread_data scap_test_thread_data; struct scap_test_input_data { - struct ppm_evt_hdr** events; - size_t event_count; + struct ppm_evt_hdr **events; + size_t event_count; - struct scap_threadinfo *threads; - size_t thread_count; + struct scap_threadinfo *threads; + size_t thread_count; - struct scap_test_fdinfo_data *fdinfo_data; + struct scap_test_fdinfo_data *fdinfo_data; }; typedef struct scap_test_input_data scap_test_input_data; diff --git a/userspace/libscap/engine/test_input/test_input.c b/userspace/libscap/engine/test_input/test_input.c index 1488398359..93bedae35d 100644 --- a/userspace/libscap/engine/test_input/test_input.c +++ b/userspace/libscap/engine/test_input/test_input.c @@ -22,10 +22,9 @@ limitations under the License. struct scap; struct scap_test_input_data; -struct test_input_engine -{ +struct test_input_engine { char* m_lasterr; - struct scap_test_input_data *m_data; + struct scap_test_input_data* m_data; }; typedef struct test_input_engine test_input_engine; @@ -39,11 +38,9 @@ typedef struct test_input_engine test_input_engine; #include #include -static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) -{ - struct test_input_engine *engine = calloc(1, sizeof(struct test_input_engine)); - if(engine == NULL) - { +static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) { + struct test_input_engine* engine = calloc(1, sizeof(struct test_input_engine)); + if(engine == NULL) { return NULL; } @@ -52,13 +49,14 @@ static void* alloc_handle(scap_t* main_handle, char* lasterr_ptr) return engine; } -static int32_t next(struct scap_engine_handle handle, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags) -{ - test_input_engine *engine = handle.m_handle; - scap_test_input_data *data = engine->m_data; +static int32_t next(struct scap_engine_handle handle, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags) { + test_input_engine* engine = handle.m_handle; + scap_test_input_data* data = engine->m_data; - if (!data->events || data->event_count == 0) - { + if(!data->events || data->event_count == 0) { return SCAP_TIMEOUT; } @@ -70,13 +68,12 @@ static int32_t next(struct scap_engine_handle handle, scap_evt** pevent, uint16_ return SCAP_SUCCESS; } -static int32_t init(scap_t* main_handle, scap_open_args* oargs) -{ - test_input_engine *engine = main_handle->m_engine.m_handle; - struct scap_test_input_engine_params *params = oargs->engine_params; +static int32_t init(scap_t* main_handle, scap_open_args* oargs) { + test_input_engine* engine = main_handle->m_engine.m_handle; + struct scap_test_input_engine_params* params = oargs->engine_params; engine->m_data = params->test_input_data; - if (engine->m_data == NULL) { + if(engine->m_data == NULL) { strlcpy(engine->m_lasterr, "No test input data provided", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } @@ -85,22 +82,22 @@ static int32_t init(scap_t* main_handle, scap_open_args* oargs) } const struct scap_vtable scap_test_input_engine = { - .name = TEST_INPUT_ENGINE, - .savefile_ops = NULL, - - .alloc_handle = alloc_handle, - .init = init, - .free_handle = noop_free_handle, - .close = noop_close_engine, - .next = next, - .start_capture = noop_start_capture, - .stop_capture = noop_stop_capture, - .configure = noop_configure, - .get_stats = noop_get_stats, - .get_stats_v2 = noop_get_stats_v2, - .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, - .get_n_devs = noop_get_n_devs, - .get_max_buf_used = noop_get_max_buf_used, - .get_api_version = NULL, - .get_schema_version = NULL, + .name = TEST_INPUT_ENGINE, + .savefile_ops = NULL, + + .alloc_handle = alloc_handle, + .init = init, + .free_handle = noop_free_handle, + .close = noop_close_engine, + .next = next, + .start_capture = noop_start_capture, + .stop_capture = noop_stop_capture, + .configure = noop_configure, + .get_stats = noop_get_stats, + .get_stats_v2 = noop_get_stats_v2, + .get_n_tracepoint_hit = noop_get_n_tracepoint_hit, + .get_n_devs = noop_get_n_devs, + .get_max_buf_used = noop_get_max_buf_used, + .get_api_version = NULL, + .get_schema_version = NULL, }; diff --git a/userspace/libscap/engine/test_input/test_input_platform.c b/userspace/libscap/engine/test_input/test_input_platform.c index 51161cda78..78116cce04 100644 --- a/userspace/libscap/engine/test_input/test_input_platform.c +++ b/userspace/libscap/engine/test_input/test_input_platform.c @@ -18,21 +18,22 @@ limitations under the License. #include #include -#include // for scap_threadinfo +#include // for scap_threadinfo #include #include #include #include #include -static int32_t get_fdinfos(void* ctx, const scap_threadinfo *tinfo, uint64_t *n, const scap_fdinfo **fdinfos) -{ - struct scap_test_input_platform * platform = ctx; - scap_test_input_data *data = platform->m_data; +static int32_t get_fdinfos(void* ctx, + const scap_threadinfo* tinfo, + uint64_t* n, + const scap_fdinfo** fdinfos) { + struct scap_test_input_platform* platform = ctx; + scap_test_input_data* data = platform->m_data; size_t i; - for (i = 0; i < data->thread_count; i++) - { + for(i = 0; i < data->thread_count; i++) { if(data->threads[i].tid == tinfo->tid) { *fdinfos = data->fdinfo_data[i].fdinfos; *n = data->fdinfo_data[i].fdinfo_count; @@ -40,55 +41,59 @@ static int32_t get_fdinfos(void* ctx, const scap_threadinfo *tinfo, uint64_t *n, } } - snprintf(platform->m_lasterr, SCAP_LASTERR_SIZE, "Could not find thread info for tid %lu", tinfo->tid); + snprintf(platform->m_lasterr, + SCAP_LASTERR_SIZE, + "Could not find thread info for tid %lu", + tinfo->tid); return SCAP_FAILURE; } -int32_t scap_test_input_init_platform(struct scap_platform* platform, char* lasterr, struct scap_engine_handle engine, struct scap_open_args* oargs) -{ - struct scap_test_input_engine_params *params = oargs->engine_params; - struct scap_test_input_platform* test_input_platform = (struct scap_test_input_platform*)platform; +int32_t scap_test_input_init_platform(struct scap_platform* platform, + char* lasterr, + struct scap_engine_handle engine, + struct scap_open_args* oargs) { + struct scap_test_input_engine_params* params = oargs->engine_params; + struct scap_test_input_platform* test_input_platform = + (struct scap_test_input_platform*)platform; test_input_platform->m_data = params->test_input_data; test_input_platform->m_lasterr = lasterr; - if (test_input_platform->m_data == NULL) - { + if(test_input_platform->m_data == NULL) { strlcpy(lasterr, "No test input data provided", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } - return scap_proc_scan_vtable( - lasterr, - &platform->m_proclist, - params->test_input_data->thread_count, - params->test_input_data->threads, - test_input_platform, - get_fdinfos); + return scap_proc_scan_vtable(lasterr, + &platform->m_proclist, + params->test_input_data->thread_count, + params->test_input_data->threads, + test_input_platform, + get_fdinfos); } -static void scap_test_input_free_platform(struct scap_platform* platform) -{ +static void scap_test_input_free_platform(struct scap_platform* platform) { free(platform); } -static bool scap_test_input_is_thread_alive(struct scap_platform* platform, int64_t pid, int64_t tid, const char* comm) -{ +static bool scap_test_input_is_thread_alive(struct scap_platform* platform, + int64_t pid, + int64_t tid, + const char* comm) { return false; } static const struct scap_platform_vtable scap_test_input_platform = { - .init_platform = scap_test_input_init_platform, - .free_platform = scap_test_input_free_platform, - .is_thread_alive = scap_test_input_is_thread_alive, + .init_platform = scap_test_input_init_platform, + .free_platform = scap_test_input_free_platform, + .is_thread_alive = scap_test_input_is_thread_alive, }; -struct scap_platform* scap_test_input_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context) -{ +struct scap_platform* scap_test_input_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context) { struct scap_test_input_platform* platform = calloc(1, sizeof(*platform)); - if(platform == NULL) - { + if(platform == NULL) { return NULL; } diff --git a/userspace/libscap/engine/test_input/test_input_platform.h b/userspace/libscap/engine/test_input/test_input_platform.h index 6585b9d747..d96eae1028 100644 --- a/userspace/libscap/engine/test_input/test_input_platform.h +++ b/userspace/libscap/engine/test_input/test_input_platform.h @@ -26,8 +26,7 @@ extern "C" { struct scap_test_input_data; -struct scap_test_input_platform -{ +struct scap_test_input_platform { struct scap_platform m_generic; struct scap_test_input_data* m_data; char* m_lasterr; @@ -36,4 +35,3 @@ struct scap_test_input_platform #ifdef __cplusplus }; #endif - diff --git a/userspace/libscap/engine/test_input/test_input_public.h b/userspace/libscap/engine/test_input/test_input_public.h index df20d10bfc..807f3b1590 100644 --- a/userspace/libscap/engine/test_input/test_input_public.h +++ b/userspace/libscap/engine/test_input/test_input_public.h @@ -20,18 +20,17 @@ limitations under the License. #define TEST_INPUT_ENGINE "test_input" #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - struct scap_test_input_engine_params - { - scap_test_input_data* test_input_data; ///< only used for testing scap consumers by supplying arbitrary test data. - }; +struct scap_test_input_engine_params { + scap_test_input_data* test_input_data; ///< only used for testing scap consumers by supplying + ///< arbitrary test data. +}; - struct scap_platform; - struct scap_platform* scap_test_input_alloc_platform(proc_entry_callback proc_callback, - void* proc_callback_context); +struct scap_platform; +struct scap_platform* scap_test_input_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context); #ifdef __cplusplus }; #endif diff --git a/userspace/libscap/examples/01-open/CMakeLists.txt b/userspace/libscap/examples/01-open/CMakeLists.txt index 9fa8804070..5487bc2019 100644 --- a/userspace/libscap/examples/01-open/CMakeLists.txt +++ b/userspace/libscap/examples/01-open/CMakeLists.txt @@ -2,21 +2,17 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -add_executable(scap-open - scap_open.c) +add_executable(scap-open scap_open.c) -target_link_libraries(scap-open - scap) +target_link_libraries(scap-open scap) diff --git a/userspace/libscap/examples/01-open/scap_open.c b/userspace/libscap/examples/01-open/scap_open.c index c38f228420..9794606ebd 100644 --- a/userspace/libscap/examples/01-open/scap_open.c +++ b/userspace/libscap/examples/01-open/scap_open.c @@ -60,128 +60,126 @@ static struct scap_savefile_engine_params savefile_params = {}; /* Configuration variables set through CLI. */ static uint64_t num_events = UINT64_MAX; /* max number of events to catch. */ -static int evt_type = -1; /* event type to print. */ +static int evt_type = -1; /* event type to print. */ static bool ppm_sc_is_set = 0; static unsigned long buffer_bytes_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM; static bool drop_failed = false; static enum falcosecurity_log_severity severity_level = FALCOSECURITY_LOG_SEV_WARNING; -static int simple_set[] = { - PPM_SC_ACCEPT, - PPM_SC_ACCEPT4, - PPM_SC_BIND, - PPM_SC_BPF, - PPM_SC_CAPSET, - PPM_SC_CHDIR, - PPM_SC_CHMOD, - PPM_SC_CHROOT, - PPM_SC_CLONE, - PPM_SC_CLONE3, - PPM_SC_CLOSE, - PPM_SC_CONNECT, - PPM_SC_COPY_FILE_RANGE, - PPM_SC_CREAT, - PPM_SC_DUP, - PPM_SC_DUP2, - PPM_SC_DUP3, - PPM_SC_EVENTFD, - PPM_SC_EVENTFD2, - PPM_SC_EXECVE, - PPM_SC_EXECVEAT, - PPM_SC_FCHDIR, - PPM_SC_FCHMOD, - PPM_SC_FCHMODAT, - PPM_SC_FCNTL, - PPM_SC_FLOCK, - PPM_SC_FORK, - PPM_SC_INOTIFY_INIT, - PPM_SC_INOTIFY_INIT1, - PPM_SC_IOCTL, - PPM_SC_KILL, - PPM_SC_LINK, - PPM_SC_LINKAT, - PPM_SC_LISTEN, - PPM_SC_MKDIR, - PPM_SC_MKDIRAT, - PPM_SC_MOUNT, - PPM_SC_OPEN, - PPM_SC_OPEN_BY_HANDLE_AT, - PPM_SC_OPENAT, - PPM_SC_OPENAT2, - PPM_SC_PIPE, - PPM_SC_PIPE2, - PPM_SC_PRLIMIT64, - PPM_SC_PTRACE, - PPM_SC_QUOTACTL, - PPM_SC_RECVFROM, - PPM_SC_RECVMSG, - PPM_SC_RENAME, - PPM_SC_RENAMEAT, - PPM_SC_RENAMEAT2, - PPM_SC_RMDIR, - PPM_SC_SECCOMP, - PPM_SC_SENDMMSG, - PPM_SC_SENDTO, - PPM_SC_SETGID, - PPM_SC_SETNS, - PPM_SC_SETPGID, - PPM_SC_SETRESGID, - PPM_SC_SETRESUID, - PPM_SC_SETRLIMIT, - PPM_SC_SETSID, - PPM_SC_SETSOCKOPT, - PPM_SC_SETUID, - PPM_SC_SHUTDOWN, - PPM_SC_SIGNALFD, - PPM_SC_SIGNALFD4, - PPM_SC_SOCKET, - PPM_SC_SOCKETPAIR, - PPM_SC_SYMLINK, - PPM_SC_SYMLINKAT, - PPM_SC_TGKILL, - PPM_SC_TIMERFD_CREATE, - PPM_SC_TKILL, - PPM_SC_UMOUNT2, - PPM_SC_UNLINK, - PPM_SC_UNLINKAT, - PPM_SC_UNSHARE, - PPM_SC_USERFAULTFD, - PPM_SC_VFORK, - -1 -}; - -typedef struct ppm_sc_counter{ +static int simple_set[] = {PPM_SC_ACCEPT, + PPM_SC_ACCEPT4, + PPM_SC_BIND, + PPM_SC_BPF, + PPM_SC_CAPSET, + PPM_SC_CHDIR, + PPM_SC_CHMOD, + PPM_SC_CHROOT, + PPM_SC_CLONE, + PPM_SC_CLONE3, + PPM_SC_CLOSE, + PPM_SC_CONNECT, + PPM_SC_COPY_FILE_RANGE, + PPM_SC_CREAT, + PPM_SC_DUP, + PPM_SC_DUP2, + PPM_SC_DUP3, + PPM_SC_EVENTFD, + PPM_SC_EVENTFD2, + PPM_SC_EXECVE, + PPM_SC_EXECVEAT, + PPM_SC_FCHDIR, + PPM_SC_FCHMOD, + PPM_SC_FCHMODAT, + PPM_SC_FCNTL, + PPM_SC_FLOCK, + PPM_SC_FORK, + PPM_SC_INOTIFY_INIT, + PPM_SC_INOTIFY_INIT1, + PPM_SC_IOCTL, + PPM_SC_KILL, + PPM_SC_LINK, + PPM_SC_LINKAT, + PPM_SC_LISTEN, + PPM_SC_MKDIR, + PPM_SC_MKDIRAT, + PPM_SC_MOUNT, + PPM_SC_OPEN, + PPM_SC_OPEN_BY_HANDLE_AT, + PPM_SC_OPENAT, + PPM_SC_OPENAT2, + PPM_SC_PIPE, + PPM_SC_PIPE2, + PPM_SC_PRLIMIT64, + PPM_SC_PTRACE, + PPM_SC_QUOTACTL, + PPM_SC_RECVFROM, + PPM_SC_RECVMSG, + PPM_SC_RENAME, + PPM_SC_RENAMEAT, + PPM_SC_RENAMEAT2, + PPM_SC_RMDIR, + PPM_SC_SECCOMP, + PPM_SC_SENDMMSG, + PPM_SC_SENDTO, + PPM_SC_SETGID, + PPM_SC_SETNS, + PPM_SC_SETPGID, + PPM_SC_SETRESGID, + PPM_SC_SETRESUID, + PPM_SC_SETRLIMIT, + PPM_SC_SETSID, + PPM_SC_SETSOCKOPT, + PPM_SC_SETUID, + PPM_SC_SHUTDOWN, + PPM_SC_SIGNALFD, + PPM_SC_SIGNALFD4, + PPM_SC_SOCKET, + PPM_SC_SOCKETPAIR, + PPM_SC_SYMLINK, + PPM_SC_SYMLINKAT, + PPM_SC_TGKILL, + PPM_SC_TIMERFD_CREATE, + PPM_SC_TKILL, + PPM_SC_UMOUNT2, + PPM_SC_UNLINK, + PPM_SC_UNLINKAT, + PPM_SC_UNSHARE, + PPM_SC_USERFAULTFD, + PPM_SC_VFORK, + -1}; + +typedef struct ppm_sc_counter { uint64_t counter; ppm_sc_code code; /* we need the code also here because at the end we will sort */ } ppm_sc_counter; /* Generic global variables. */ -static scap_open_args oargs = {}; /* scap oargs used in `scap_open`. */ +static scap_open_args oargs = {}; /* scap oargs used in `scap_open`. */ static const struct scap_vtable* vtable = NULL; -static uint64_t g_nevts = 0; /* total number of events captured. */ -static uint64_t g_total_number_of_bytes = 0; /* total dimension of events in bytes. */ -static scap_t* g_h = NULL; /* global scap handler. */ -static uint16_t* lens16 = NULL; /* pointer used to print the length of event params. */ -static char* valptr = NULL; /* pointer used to print the value of event params. */ /* pointer used to print the value of event params. */ +static uint64_t g_nevts = 0; /* total number of events captured. */ +static uint64_t g_total_number_of_bytes = 0; /* total dimension of events in bytes. */ +static scap_t* g_h = NULL; /* global scap handler. */ +static uint16_t* lens16 = NULL; /* pointer used to print the length of event params. */ +static char* valptr = NULL; +/* pointer used to print the value of event params. */ /* pointer used to print the value of + event params. */ static struct timeval tval_start, tval_end, tval_result; -static unsigned long number_of_timeouts; /* Times in which there were no events in the buffer. */ +static unsigned long number_of_timeouts; /* Times in which there were no events in the buffer. */ static unsigned long number_of_scap_next; /* Times in which the 'scap-next' method is called. */ -static ppm_sc_counter ppm_sc_count[PPM_SC_MAX*2] = {0}; /* Number of times a syscall is called. We want the `*2` because we store the enter and the exit count separately */ +static ppm_sc_counter ppm_sc_count[PPM_SC_MAX * 2] = { + 0}; /* Number of times a syscall is called. We want the `*2` because we store the enter and + the exit count separately */ /*=============================== PRINT SUPPORTED SYSCALLS ===========================*/ -void print_sorted_syscalls(char string_vector[SYSCALL_TABLE_SIZE][SYSCALL_NAME_MAX_LEN], int dim) -{ +void print_sorted_syscalls(char string_vector[SYSCALL_TABLE_SIZE][SYSCALL_NAME_MAX_LEN], int dim) { char temp[SYSCALL_NAME_MAX_LEN]; /* storing strings in the lexicographical order */ - for(int i = 0; i < dim; ++i) - { - for(int j = i + 1; j < dim; ++j) - { + for(int i = 0; i < dim; ++i) { + for(int j = i + 1; j < dim; ++j) { /* swapping strings if they are not in the lexicographical order */ - if(strcmp(string_vector[i], string_vector[j]) > 0) - { + if(strcmp(string_vector[i], string_vector[j]) > 0) { strlcpy(temp, string_vector[i], SYSCALL_NAME_MAX_LEN); strlcpy(string_vector[i], string_vector[j], SYSCALL_NAME_MAX_LEN); strlcpy(string_vector[j], temp, SYSCALL_NAME_MAX_LEN); @@ -190,58 +188,49 @@ void print_sorted_syscalls(char string_vector[SYSCALL_TABLE_SIZE][SYSCALL_NAME_M } printf("\nSyscalls in the lexicographical order: \n"); - for(int i = 0; i < dim; i++) - { + for(int i = 0; i < dim; i++) { printf("[%d] %s\n", i, string_vector[i]); } printf("Interesting syscalls: %d\n", dim); } -void print_supported_sc() -{ +void print_supported_sc() { printf("\n------- Print supported ppm_sc: \n"); // Skip PPM_SC_UNKNOWN - for (int i = 1; i < PPM_SC_MAX; i++) - { - if (scap_get_ppm_sc_name(i)[0] != '\0') - { + for(int i = 1; i < PPM_SC_MAX; i++) { + if(scap_get_ppm_sc_name(i)[0] != '\0') { int native_id = scap_ppm_sc_to_native_id(i); - if (native_id != -1) - { - printf("- PPM_SC > %-25s system_code: (%d) ppm_code: (%d)\n", scap_get_ppm_sc_name(i), native_id, i); - } - else - { + if(native_id != -1) { + printf("- PPM_SC > %-25s system_code: (%d) ppm_code: (%d)\n", + scap_get_ppm_sc_name(i), + native_id, + i); + } else { printf("- PPM_SC > %-25s ppm_code: (%d)\n", scap_get_ppm_sc_name(i), i); } } } } - /*=============================== PRINT SUPPORTED SYSCALLS ===========================*/ /*=============================== SYSCALLS/TRACEPOINTS ===========================*/ -void enable_single_ppm_sc(int ppm_sc_code) -{ - if(ppm_sc_code == -1) - { +void enable_single_ppm_sc(int ppm_sc_code) { + if(ppm_sc_code == -1) { /* In this case we won't have any syscall enabled. */ ppm_sc_is_set = true; return; } - if(ppm_sc_code < 0 || ppm_sc_code >= PPM_SC_MAX) - { + if(ppm_sc_code < 0 || ppm_sc_code >= PPM_SC_MAX) { fprintf(stderr, "Unexistent ppm_sc code: %d. Wrong parameter?\n", ppm_sc_code); print_supported_sc(); exit(EXIT_FAILURE); } - if (scap_get_ppm_sc_name(ppm_sc_code)[0] == '\0') - { + if(scap_get_ppm_sc_name(ppm_sc_code)[0] == '\0') { fprintf(stderr, "Unmapped ppm_sc code: %d. Wrong parameter?\n", ppm_sc_code); print_supported_sc(); exit(EXIT_FAILURE); @@ -250,35 +239,26 @@ void enable_single_ppm_sc(int ppm_sc_code) ppm_sc_is_set = true; } -void enable_sc_and_print() -{ +void enable_sc_and_print() { printf("\n---------------------- INTERESTING SYSCALLS ----------------------\n"); - if(ppm_sc_is_set) - { + if(ppm_sc_is_set) { printf("* sc codes enabled:\n"); - for(int j = 0; j < PPM_SC_MAX; j++) - { - if(oargs.ppm_sc_of_interest.ppm_sc[j]) - { + for(int j = 0; j < PPM_SC_MAX; j++) { + if(oargs.ppm_sc_of_interest.ppm_sc[j]) { printf("- %s\n", scap_get_ppm_sc_name(j)); } } - } - else - { + } else { printf("* All sc codes are enabled!\n"); - for(int j = 0; j < PPM_SC_MAX; j++) - { + for(int j = 0; j < PPM_SC_MAX; j++) { oargs.ppm_sc_of_interest.ppm_sc[j] = true; } } printf("------------------------------------------------------------------\n\n"); } -void enable_simple_set() -{ - for (int i = 0; simple_set[i] != -1; i++) - { +void enable_simple_set() { + for(int i = 0; simple_set[i] != -1; i++) { oargs.ppm_sc_of_interest.ppm_sc[simple_set[i]] = true; } ppm_sc_is_set = true; @@ -288,16 +268,14 @@ void enable_simple_set() /*=============================== PRINT EVENT PARAMS ===========================*/ -void print_ipv4(int starting_index) -{ +void print_ipv4(int starting_index) { char ipv4_string[50]; uint8_t* ipv4 = (uint8_t*)(valptr + starting_index); snprintf(ipv4_string, sizeof(ipv4_string), "%d.%d.%d.%d", ipv4[0], ipv4[1], ipv4[2], ipv4[3]); printf("- ipv4: %s\n", ipv4_string); } -void print_ipv6(int starting_index) -{ +void print_ipv6(int starting_index) { uint32_t ipv6[4] = {0, 0, 0, 0}; ipv6[0] = *(uint32_t*)(valptr + starting_index); ipv6[1] = *(uint32_t*)(valptr + starting_index + 4); @@ -309,30 +287,24 @@ void print_ipv6(int starting_index) printf("- ipv6: %s\n", ipv6_string); } -void print_unix_path(int starting_index) -{ +void print_unix_path(int starting_index) { printf("- unix path: %s\n", (char*)(valptr + starting_index)); } -void print_port(int starting_index) -{ +void print_port(int starting_index) { printf("- port: %d\n", *(uint16_t*)(valptr + starting_index)); } -void print_parameter(int16_t num_param) -{ +void print_parameter(int16_t num_param) { int16_t param_type = g_event_info[evt_type].params[num_param].type; int16_t len = lens16[num_param]; - if(len == 0) - { + if(len == 0) { printf("PARAM %d: is empty\n", num_param); return; } - switch(param_type) - { - + switch(param_type) { case PT_FLAGS8: printf("PARAM %d: %X\n", num_param, *(uint8_t*)(valptr)); break; @@ -394,14 +366,11 @@ void print_parameter(int16_t num_param) printf("PARAM %d: %d\n", num_param, *(int32_t*)(valptr)); break; - case PT_SOCKADDR: - { + case PT_SOCKADDR: { printf("PARAM %d:\n", num_param); uint8_t sock_family = *(uint8_t*)(valptr); printf("- sock_family: %d\n", sock_family); - switch(sock_family) - { - + switch(sock_family) { case PPM_AF_INET: /* ipv4 dest. */ print_ipv4(1); @@ -430,13 +399,11 @@ void print_parameter(int16_t num_param) break; } - case PT_SOCKTUPLE: - { + case PT_SOCKTUPLE: { printf("PARAM %d:\n", num_param); uint8_t sock_family = *(uint8_t*)(valptr); printf("- sock_family: %d\n", sock_family); - switch(sock_family) - { + switch(sock_family) { case PPM_AF_INET: /* ipv4 src. */ print_ipv4(1); @@ -488,8 +455,7 @@ void print_parameter(int16_t num_param) case PT_CHARBUFARRAY: case PT_FSRELPATH: printf("PARAM %d: ", num_param); - for(int j = 0; j < len; j++) - { + for(int j = 0; j < len; j++) { printf("%c", *(char*)(valptr + j)); } printf("\n"); @@ -502,8 +468,7 @@ void print_parameter(int16_t num_param) valptr += len; } -void print_event(scap_evt* ev) -{ +void print_event(scap_evt* ev) { lens16 = (uint16_t*)((char*)ev + sizeof(struct ppm_evt_hdr)); valptr = (char*)lens16 + ev->nparams * sizeof(uint16_t); printf("\n------------------ EVENT: %d TID:%lu\n", evt_type, ev->tid); @@ -517,12 +482,10 @@ void print_event(scap_evt* ev) printf("------\n"); printf("------ PARAMS\n"); - for(int i = 0; i < ev->nparams; i++) - { + for(int i = 0; i < ev->nparams; i++) { print_parameter(i); } - if(ev->nparams == 0) - { + if(ev->nparams == 0) { printf("- This event has no parameter\n"); } @@ -534,8 +497,7 @@ void print_event(scap_evt* ev) /*=============================== PRINT CAPTURE INFO ===========================*/ -void print_help() -{ +void print_help() { printf("\n------------------------------ MENU ------------------------------\n"); printf("------> SCAP SOURCES\n"); printf("'%s': enable the kernel module.\n", KMOD_OPTION); @@ -543,56 +505,61 @@ void print_help() printf("'%s': enable modern BPF probe.\n", MODERN_BPF_OPTION); printf("'%s ': read events from scap file.\n", SCAP_FILE_OPTION); printf("\n------> CONFIGURATIONS OPTIONS\n"); - printf("'%s ': enable only requested scap code (this is an internal code that wraps both syscalls and tracepoints). Can be passed multiple times.\n", PPM_SC_OPTION); - printf("'%s ': number of events to catch before terminating. (default: UINT64_MAX)\n", NUM_EVENTS_OPTION); - printf("'%s ': every event of this type will be printed to console. (default: -1, no print)\n", EVENT_TYPE_OPTION); + printf("'%s ': enable only requested scap code (this is an internal code that " + "wraps both syscalls and tracepoints). Can be passed multiple times.\n", + PPM_SC_OPTION); + printf("'%s ': number of events to catch before terminating. (default: " + "UINT64_MAX)\n", + NUM_EVENTS_OPTION); + printf("'%s ': every event of this type will be printed to console. (default: -1, " + "no print)\n", + EVENT_TYPE_OPTION); printf("'%s ': dimension in bytes of a single per CPU buffer.\n", BUFFER_OPTION); printf("[MODERN PROBE ONLY, EXPERIMENTAL]\n"); - printf("'%s ': allocate a ring buffer for every `cpus_for_each_buffer` CPUs.\n", CPUS_FOR_EACH_BUFFER_MODE); - printf("'%s': allocate ring buffers for all available CPUs. Default: allocate ring buffers for online CPUs only.\n", ALL_AVAILABLE_CPUS_MODE); + printf("'%s ': allocate a ring buffer for every `cpus_for_each_buffer` " + "CPUs.\n", + CPUS_FOR_EACH_BUFFER_MODE); + printf("'%s': allocate ring buffers for all available CPUs. Default: allocate ring buffers for " + "online CPUs only.\n", + ALL_AVAILABLE_CPUS_MODE); printf("'%s': instrument drivers to drop failed syscalls (exit) events.\n", DROP_FAILED); - printf("'%s ': print all available logs. Default level is WARNING (4)\n", VERBOSE_OPTION); + printf("'%s ': print all available logs. Default level is WARNING (4)\n", + VERBOSE_OPTION); printf("\n------> PRINT OPTIONS\n"); - printf("'%s': print all supported syscalls with different sources and configurations.\n", PRINT_SYSCALLS_OPTION); + printf("'%s': print all supported syscalls with different sources and configurations.\n", + PRINT_SYSCALLS_OPTION); printf("'%s': print this menu.\n", PRINT_HELP_OPTION); printf("\n------------------------------------------------------------------\n\n"); } -void print_scap_source() -{ +void print_scap_source() { printf("\n--------------------------- SCAP SOURCE --------------------------\n"); - if(false) - { + if(false) { } #ifdef HAS_ENGINE_KMOD - else if(vtable == &scap_kmod_engine) - { + else if(vtable == &scap_kmod_engine) { printf("* Kernel module.\n"); } #endif #ifdef HAS_ENGINE_BPF - else if(vtable == &scap_bpf_engine) - { + else if(vtable == &scap_bpf_engine) { struct scap_bpf_engine_params* params = oargs.engine_params; printf("* BPF probe: '%s'\n", params->bpf_probe); } #endif #ifdef HAS_ENGINE_MODERN_BPF - else if(vtable == &scap_modern_bpf_engine) - { + else if(vtable == &scap_modern_bpf_engine) { struct scap_modern_bpf_engine_params* params = oargs.engine_params; printf("* Modern BPF probe, 1 ring buffer every %d CPUs\n", params->cpus_for_each_buffer); } #endif #ifdef HAS_ENGINE_SAVEFILE - else if(vtable == &scap_savefile_engine) - { + else if(vtable == &scap_savefile_engine) { struct scap_savefile_engine_params* params = oargs.engine_params; printf("* Scap file: '%s'.\n", params->fname); } #endif - else - { + else { printf("* Unknown scap source! Bye!\n"); print_help(); exit(EXIT_FAILURE); @@ -600,47 +567,39 @@ void print_scap_source() printf("------------------------------------------------------------------\n\n"); } -void print_configurations() -{ +void print_configurations() { printf("\n------------------------- CONFIGURATIONS -------------------------\n"); printf("* Print single event type: %d (`-1` means no event to print).\n", evt_type); printf("* Run until '%lu' events are catched.\n", num_events); printf("------------------------------------------------------------------\n\n"); } -void print_start_capture() -{ - if(false) - { +void print_start_capture() { + if(false) { } #ifdef HAS_ENGINE_KMOD - else if(vtable == &scap_kmod_engine) - { + else if(vtable == &scap_kmod_engine) { printf("* OK! Kernel module correctly loaded.\n"); } #endif #ifdef HAS_ENGINE_BPF - else if(vtable == &scap_bpf_engine) - { + else if(vtable == &scap_bpf_engine) { printf("* OK! BPF probe correctly loaded: NO VERIFIER ISSUES :)\n"); } #endif #ifdef HAS_ENGINE_MODERN_BPF - else if(vtable == &scap_modern_bpf_engine) - { + else if(vtable == &scap_modern_bpf_engine) { printf("* OK! modern BPF probe correctly loaded: NO VERIFIER ISSUES :)\n"); } #endif #ifdef HAS_ENGINE_SAVEFILE - else if(vtable == &scap_savefile_engine) - { + else if(vtable == &scap_savefile_engine) { printf("* OK! Ready to read from scap file.\n"); printf("\n* Reading from scap file...\n"); return; } #endif - else - { + else { printf("Cannot start the capture! Bye\n"); exit(EXIT_FAILURE); } @@ -648,25 +607,20 @@ void print_start_capture() printf("* Press CTRL+C to stop the capture\n"); } -void parse_CLI_options(int argc, char** argv) -{ - for(int i = 0; i < argc; i++) - { +void parse_CLI_options(int argc, char** argv) { + for(int i = 0; i < argc; i++) { /*=============================== SCAP SOURCES ===========================*/ #ifdef HAS_ENGINE_KMOD - if(!strcmp(argv[i], KMOD_OPTION)) - { + if(!strcmp(argv[i], KMOD_OPTION)) { vtable = &scap_kmod_engine; kmod_params.buffer_bytes_dim = buffer_bytes_dim; oargs.engine_params = &kmod_params; } #endif #ifdef HAS_ENGINE_BPF - if(!strcmp(argv[i], BPF_OPTION)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], BPF_OPTION)) { + if(!(i + 1 < argc)) { printf("\nYou need to specify also the BPF probe path! Bye!\n"); exit(EXIT_FAILURE); } @@ -677,8 +631,7 @@ void parse_CLI_options(int argc, char** argv) } #endif #ifdef HAS_ENGINE_MODERN_BPF - if(!strcmp(argv[i], MODERN_BPF_OPTION)) - { + if(!strcmp(argv[i], MODERN_BPF_OPTION)) { vtable = &scap_modern_bpf_engine; modern_bpf_params.buffer_bytes_dim = buffer_bytes_dim; modern_bpf_params.cpus_for_each_buffer = DEFAULT_CPU_FOR_EACH_BUFFER; @@ -687,10 +640,8 @@ void parse_CLI_options(int argc, char** argv) } #endif #ifdef HAS_ENGINE_SAVEFILE - if(!strcmp(argv[i], SCAP_FILE_OPTION)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], SCAP_FILE_OPTION)) { + if(!(i + 1 < argc)) { printf("\nYou need to specify also the scap file path! Bye!\n"); exit(EXIT_FAILURE); } @@ -704,10 +655,8 @@ void parse_CLI_options(int argc, char** argv) /*=============================== CONFIGURATIONS ===========================*/ - if(!strcmp(argv[i], BUFFER_OPTION)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], BUFFER_OPTION)) { + if(!(i + 1 < argc)) { printf("\nYou need to specify also the dimension of buffer in bytes! Bye!\n"); exit(EXIT_FAILURE); } @@ -716,69 +665,55 @@ void parse_CLI_options(int argc, char** argv) bpf_params.buffer_bytes_dim = buffer_bytes_dim; modern_bpf_params.buffer_bytes_dim = buffer_bytes_dim; } - if(!strcmp(argv[i], PPM_SC_OPTION)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], PPM_SC_OPTION)) { + if(!(i + 1 < argc)) { print_supported_sc(); printf("\nYou need to specify also the ppm_sc code! Bye!\n"); exit(EXIT_FAILURE); } enable_single_ppm_sc(atoi(argv[++i])); } - if(!strcmp(argv[i], NUM_EVENTS_OPTION)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], NUM_EVENTS_OPTION)) { + if(!(i + 1 < argc)) { printf("\nYou need to specify also the number of events to catch! Bye!\n"); exit(EXIT_FAILURE); } num_events = strtoul(argv[++i], NULL, 10); } - if(!strcmp(argv[i], EVENT_TYPE_OPTION)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], EVENT_TYPE_OPTION)) { + if(!(i + 1 < argc)) { printf("\nYou need to specify also the event type number! Bye!\n"); exit(EXIT_FAILURE); } evt_type = strtoul(argv[++i], NULL, 10); } - if(!strcmp(argv[i], SIMPLE_SET_OPTION)) - { + if(!strcmp(argv[i], SIMPLE_SET_OPTION)) { enable_simple_set(); } /* This should be used only with the modern probe */ - if(!strcmp(argv[i], CPUS_FOR_EACH_BUFFER_MODE)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], CPUS_FOR_EACH_BUFFER_MODE)) { + if(!(i + 1 < argc)) { printf("\nYou need to specify also the number of CPUs. Bye!\n"); exit(EXIT_FAILURE); } modern_bpf_params.cpus_for_each_buffer = atoi(argv[++i]); } /* This should be used only with the modern probe */ - if(!strcmp(argv[i], ALL_AVAILABLE_CPUS_MODE)) - { + if(!strcmp(argv[i], ALL_AVAILABLE_CPUS_MODE)) { modern_bpf_params.allocate_online_only = false; } - if(!strcmp(argv[i], DROP_FAILED)) - { + if(!strcmp(argv[i], DROP_FAILED)) { drop_failed = true; } - if(!strcmp(argv[i], VERBOSE_OPTION)) - { - if(!(i + 1 < argc)) - { + if(!strcmp(argv[i], VERBOSE_OPTION)) { + if(!(i + 1 < argc)) { printf("\nYou need to specify also the logging level! Bye!\n"); exit(EXIT_FAILURE); } unsigned long level = strtoul(argv[++i], NULL, 10); - if(level < FALCOSECURITY_LOG_SEV_FATAL || level > FALCOSECURITY_LOG_SEV_TRACE) - { + if(level < FALCOSECURITY_LOG_SEV_FATAL || level > FALCOSECURITY_LOG_SEV_TRACE) { printf("\nInvalid log level! Bye!\n"); exit(EXIT_FAILURE); } @@ -789,13 +724,11 @@ void parse_CLI_options(int argc, char** argv) /*=============================== PRINT ===========================*/ - if(!strcmp(argv[i], PRINT_SYSCALLS_OPTION)) - { + if(!strcmp(argv[i], PRINT_SYSCALLS_OPTION)) { print_supported_sc(); exit(EXIT_SUCCESS); } - if(!strcmp(argv[i], PRINT_HELP_OPTION)) - { + if(!strcmp(argv[i], PRINT_HELP_OPTION)) { print_help(); exit(EXIT_SUCCESS); } @@ -803,47 +736,37 @@ void parse_CLI_options(int argc, char** argv) /*=============================== PRINT ===========================*/ } - if(!vtable) - { + if(!vtable) { printf("\nSource not specified! Bye!\n"); exit(EXIT_FAILURE); } } -static inline bool engine_uses_bpf() -{ +static inline bool engine_uses_bpf() { #ifdef HAS_ENGINE_BPF - if(vtable == &scap_bpf_engine) - { + if(vtable == &scap_bpf_engine) { return true; } #endif #ifdef HAS_ENGINE_MODERN_BPF - if(vtable == &scap_modern_bpf_engine) - { + if(vtable == &scap_modern_bpf_engine) { return true; } #endif return false; } -void print_syscalls_stats() -{ +void print_syscalls_stats() { // ppm_sc_count will become out of order so we save the code - for(int i = 0; i < PPM_SC_MAX*2; ++i) - { + for(int i = 0; i < PPM_SC_MAX * 2; ++i) { ppm_sc_count[i].code = i; } - // sort them + // sort them ppm_sc_counter tmp; - for(int i = 0; i < PPM_SC_MAX*2; ++i) - { - for(int j = i + 1; j < PPM_SC_MAX*2; ++j) - { - - if(ppm_sc_count[i].counter < ppm_sc_count[j].counter) - { + for(int i = 0; i < PPM_SC_MAX * 2; ++i) { + for(int j = i + 1; j < PPM_SC_MAX * 2; ++j) { + if(ppm_sc_count[i].counter < ppm_sc_count[j].counter) { tmp = ppm_sc_count[i]; ppm_sc_count[i] = ppm_sc_count[j]; ppm_sc_count[j] = tmp; @@ -852,33 +775,32 @@ void print_syscalls_stats() } // print them - for(int i = 0; i < PPM_SC_MAX*2; i++) - { + for(int i = 0; i < PPM_SC_MAX * 2; i++) { // if `0` we don't print anything - if(ppm_sc_count[i].counter) - { - printf("- [%s__%s]: %lu\n", scap_get_ppm_sc_name(ppm_sc_count[i].code % PPM_SC_MAX), ppm_sc_count[i].code >=PPM_SC_MAX ? "exit": "enter", ppm_sc_count[i].counter); + if(ppm_sc_count[i].counter) { + printf("- [%s__%s]: %lu\n", + scap_get_ppm_sc_name(ppm_sc_count[i].code % PPM_SC_MAX), + ppm_sc_count[i].code >= PPM_SC_MAX ? "exit" : "enter", + ppm_sc_count[i].counter); } } } -void print_stats() -{ +void print_stats() { gettimeofday(&tval_end, NULL); timersub(&tval_end, &tval_start, &tval_result); - uint32_t flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | METRICS_V2_KERNEL_COUNTERS_PER_CPU; + uint32_t flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | + METRICS_V2_KERNEL_COUNTERS_PER_CPU; uint32_t nstats; int32_t rc; const metrics_v2* stats_v2; stats_v2 = scap_get_stats_v2(g_h, flags, &nstats, &rc); uint64_t engine_flags = scap_get_engine_flags(g_h); uint64_t n_evts = 0; - if (stats_v2 && nstats > 0) - { - for(int stat = 0; stat < nstats; stat++) - { - if ((strncmp(stats_v2[stat].name, "n_evts", 6) == 0) && stats_v2[0].type == METRIC_VALUE_TYPE_U64) - { + if(stats_v2 && nstats > 0) { + for(int stat = 0; stat < nstats; stat++) { + if((strncmp(stats_v2[stat].name, "n_evts", 6) == 0) && + stats_v2[0].type == METRIC_VALUE_TYPE_U64) { n_evts = stats_v2[stat].value.u64; break; } @@ -893,35 +815,29 @@ void print_stats() printf("\n------------> Kernel stats\n"); printf("Seen by driver (kernel side events): %" PRIu64 "\n", n_evts); - if(tval_result.tv_sec != 0) - { + if(tval_result.tv_sec != 0) { printf("Rate of kernel side events (events/second): %ld\n", n_evts / tval_result.tv_sec); } printf("Stats v2: %u metrics in total\n", nstats); - if(engine_uses_bpf()) - { + if(engine_uses_bpf()) { printf("[1] kernel-side counters\n"); - if (!(engine_flags & ENGINE_FLAG_BPF_STATS_ENABLED)) - { - printf("[Notice]: `/proc/sys/kernel/bpf_stats_enabled` not enabled, no `libbpf` stats retrieved.\n"); - } - else - { + if(!(engine_flags & ENGINE_FLAG_BPF_STATS_ENABLED)) { + printf("[Notice]: `/proc/sys/kernel/bpf_stats_enabled` not enabled, no `libbpf` stats " + "retrieved.\n"); + } else { printf("[2] libbpf stats (compare to `bpftool prog show` CLI)\n"); } - } - else - { + } else { printf("[1] kernel-side counters.\n\n"); } - if (stats_v2 && nstats > 0) - { - for(int stat = 0; stat < nstats; stat++) - { - if (stats_v2[stat].type == METRIC_VALUE_TYPE_U64) - { - printf("[%u] %s: %lu\n", stats_v2[stat].flags, stats_v2[stat].name, stats_v2[stat].value.u64); + if(stats_v2 && nstats > 0) { + for(int stat = 0; stat < nstats; stat++) { + if(stats_v2[stat].type == METRIC_VALUE_TYPE_U64) { + printf("[%u] %s: %lu\n", + stats_v2[stat].flags, + stats_v2[stat].name, + stats_v2[stat].value.u64); } } } @@ -935,13 +851,12 @@ void print_stats() printf("Number of `SCAP_TIMEOUTS`: %ld\n", number_of_timeouts); printf("Number of `scap_next` calls: %ld\n", number_of_scap_next); printf("Number of bytes received: %" PRIu64 " bytes\n", g_total_number_of_bytes); - if(g_nevts!=0) - { - printf("Average dimension of events: %" PRIu64 " bytes\n", g_total_number_of_bytes/g_nevts); + if(g_nevts != 0) { + printf("Average dimension of events: %" PRIu64 " bytes\n", + g_total_number_of_bytes / g_nevts); } printf("Time elapsed: %ld s\n", tval_result.tv_sec); - if(tval_result.tv_sec != 0) - { + if(tval_result.tv_sec != 0) { printf("Rate of userspace events (events/second): %ld\n", g_nevts / tval_result.tv_sec); } printf("Syscall stats (userspace-side):\n"); @@ -952,44 +867,36 @@ void print_stats() /*=============================== PRINT CAPTURE INFO ===========================*/ -static void signal_callback(int signal) -{ +static void signal_callback(int signal) { scap_stop_capture(g_h); print_stats(); scap_close(g_h); exit(EXIT_SUCCESS); } -void scap_open_log_fn(const char* component, const char* msg, const enum falcosecurity_log_severity sev) -{ - if(sev <= severity_level) - { - if(component!= NULL) - { +void scap_open_log_fn(const char* component, + const char* msg, + const enum falcosecurity_log_severity sev) { + if(sev <= severity_level) { + if(component != NULL) { printf("%s: %s", component, msg); - } - else - { + } else { // libbpf logs have no components printf("%s", msg); } } } -void count_syscalls(scap_evt* ev) -{ +void count_syscalls(scap_evt* ev) { uint16_t type = ev->type; // If the event is generic, we need to read the ppm_sc inside the event - if(type == PPME_GENERIC_E || type == PPME_GENERIC_X) - { - uint16_t ppm_sc_code = *(uint16_t*)((char*)ev + sizeof(struct ppm_evt_hdr) + ev->nparams * sizeof(uint16_t)); + if(type == PPME_GENERIC_E || type == PPME_GENERIC_X) { + uint16_t ppm_sc_code = *(uint16_t*)((char*)ev + sizeof(struct ppm_evt_hdr) + + ev->nparams * sizeof(uint16_t)); - if(PPME_IS_ENTER(type)) - { + if(PPME_IS_ENTER(type)) { ppm_sc_count[ppm_sc_code].counter++; - } - else - { + } else { ppm_sc_count[ppm_sc_code + PPM_SC_MAX].counter++; } return; @@ -1002,25 +909,19 @@ void count_syscalls(scap_evt* ev) events_array[type] = 1; // This will always return `SCAP_SUCCESS` - if(scap_get_ppm_sc_from_events(events_array, ppm_sc_array) != SCAP_SUCCESS) - { + if(scap_get_ppm_sc_from_events(events_array, ppm_sc_array) != SCAP_SUCCESS) { exit(EXIT_FAILURE); } - - // In our case even if we have more than one PPM_SC associated with our event we just want the first one - // because we don't want to count the syscall twice. - // For example in the case of `PPME_SYSCALL_FCNTL_X` (`[PPME_SYSCALL_FCNTL_X] = (ppm_sc_code[]){PPM_SC_FCNTL, PPM_SC_FCNTL64, -1}`) - // we just want `PPM_SC_FCNTL` and not also `PPM_SC_FCNTL64` - for(int i = 0; i < PPM_SC_MAX; i++) - { - if(ppm_sc_array[i]) - { - if(PPME_IS_ENTER(type)) - { + + // In our case even if we have more than one PPM_SC associated with our event we just want the + // first one because we don't want to count the syscall twice. For example in the case of + // `PPME_SYSCALL_FCNTL_X` (`[PPME_SYSCALL_FCNTL_X] = (ppm_sc_code[]){PPM_SC_FCNTL, + // PPM_SC_FCNTL64, -1}`) we just want `PPM_SC_FCNTL` and not also `PPM_SC_FCNTL64` + for(int i = 0; i < PPM_SC_MAX; i++) { + if(ppm_sc_array[i]) { + if(PPME_IS_ENTER(type)) { ppm_sc_count[i].counter++; - } - else - { + } else { ppm_sc_count[i + PPM_SC_MAX].counter++; } return; @@ -1028,8 +929,7 @@ void count_syscalls(scap_evt* ev) } } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { char error[SCAP_LASTERR_SIZE] = {0}; int32_t res = 0; scap_evt* ev = NULL; @@ -1037,8 +937,7 @@ int main(int argc, char** argv) uint32_t flags = 0; printf("\n[SCAP-OPEN]: Hello!\n"); - if(signal(SIGINT, signal_callback) == SIG_ERR) - { + if(signal(SIGINT, signal_callback) == SIG_ERR) { fprintf(stderr, "An error occurred while setting SIGINT signal handler.\n"); return EXIT_FAILURE; } @@ -1053,8 +952,7 @@ int main(int argc, char** argv) oargs.log_fn = scap_open_log_fn; g_h = scap_open(&oargs, vtable, error, &res); - if(g_h == NULL || res != SCAP_SUCCESS) - { + if(g_h == NULL || res != SCAP_SUCCESS) { fprintf(stderr, "%s (%d)\n", error, res); return res; } @@ -1065,41 +963,31 @@ int main(int argc, char** argv) scap_start_capture(g_h); - if (drop_failed) - { + if(drop_failed) { scap_set_dropfailed(g_h, true); } - while(g_nevts != num_events) - { + while(g_nevts != num_events) { res = scap_next(g_h, &ev, &cpuid, &flags); number_of_scap_next++; - if(res == SCAP_UNEXPECTED_BLOCK) - { + if(res == SCAP_UNEXPECTED_BLOCK) { res = scap_restart_capture(g_h); - if(res == SCAP_SUCCESS) - { + if(res == SCAP_SUCCESS) { continue; } } - if(res == SCAP_TIMEOUT || res == SCAP_FILTERED_EVENT) - { + if(res == SCAP_TIMEOUT || res == SCAP_FILTERED_EVENT) { number_of_timeouts++; continue; - } - else if(res == SCAP_EOF) - { + } else if(res == SCAP_EOF) { break; - } - else if(res != SCAP_SUCCESS) - { + } else if(res != SCAP_SUCCESS) { scap_close(g_h); fprintf(stderr, "%s (%d)\n", scap_getlasterr(g_h), res); return -1; } - if(ev->type == evt_type) - { + if(ev->type == evt_type) { print_event(ev); } count_syscalls(ev); diff --git a/userspace/libscap/examples/02-validatebuffer/CMakeLists.txt b/userspace/libscap/examples/02-validatebuffer/CMakeLists.txt index 072698b0db..1a655ebf45 100644 --- a/userspace/libscap/examples/02-validatebuffer/CMakeLists.txt +++ b/userspace/libscap/examples/02-validatebuffer/CMakeLists.txt @@ -2,21 +2,17 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -add_executable(scap-validatebuffer - test.c) +add_executable(scap-validatebuffer test.c) -target_link_libraries(scap-validatebuffer - scap) +target_link_libraries(scap-validatebuffer scap) diff --git a/userspace/libscap/examples/02-validatebuffer/test.c b/userspace/libscap/examples/02-validatebuffer/test.c index bc2fec556e..d042d7bcb3 100644 --- a/userspace/libscap/examples/02-validatebuffer/test.c +++ b/userspace/libscap/examples/02-validatebuffer/test.c @@ -28,14 +28,11 @@ limitations under the License. extern const struct ppm_event_info g_event_info[]; - -size_t g_get_event_size(ppm_event_code event_type, uint16_t* lens) -{ +size_t g_get_event_size(ppm_event_code event_type, uint16_t* lens) { uint32_t j; int32_t res = 0; - for(j = 0; j < g_event_info[event_type].nparams; j++) - { + for(j = 0; j < g_event_info[event_type].nparams; j++) { res += lens[j]; } @@ -46,13 +43,11 @@ size_t g_get_event_size(ppm_event_code event_type, uint16_t* lens) #endif } -int32_t g_check_integrity(uint32_t* cur_event, char* copy_buffer, int buf_len, uint32_t* nevents) -{ +int32_t g_check_integrity(uint32_t* cur_event, char* copy_buffer, int buf_len, uint32_t* nevents) { uint32_t offset = 0; *nevents = 0; - while(buf_len) - { + while(buf_len) { #ifdef PPM_ENABLE_SENTINEL uint32_t sentinel_begin; uint32_t sentinel_end; @@ -60,9 +55,9 @@ int32_t g_check_integrity(uint32_t* cur_event, char* copy_buffer, int buf_len, u struct ppm_evt_hdr* hdr; size_t event_size; - if(buf_len < sizeof(struct ppm_evt_hdr)) - { - fprintf(stderr, "Error: event not on buffer boundary, offset %x, data to read %d\n", + if(buf_len < sizeof(struct ppm_evt_hdr)) { + fprintf(stderr, + "Error: event not on buffer boundary, offset %x, data to read %d\n", offset, buf_len); return SCAP_FAILURE; @@ -71,30 +66,33 @@ int32_t g_check_integrity(uint32_t* cur_event, char* copy_buffer, int buf_len, u hdr = (struct ppm_evt_hdr*)(copy_buffer + offset); uint16_t type = hdr->type; - if(buf_len < sizeof(struct ppm_evt_hdr) + g_event_info[type].nparams * sizeof(uint16_t)) - { - fprintf(stderr, "Error: event not on buffer boundary, offset %x, data to read %d\n", + if(buf_len < sizeof(struct ppm_evt_hdr) + g_event_info[type].nparams * sizeof(uint16_t)) { + fprintf(stderr, + "Error: event not on buffer boundary, offset %x, data to read %d\n", offset, buf_len); return SCAP_FAILURE; } - event_size = g_get_event_size(hdr->type, (uint16_t*)(copy_buffer + offset + sizeof(struct ppm_evt_hdr))); + event_size = + g_get_event_size(hdr->type, + (uint16_t*)(copy_buffer + offset + sizeof(struct ppm_evt_hdr))); - if(event_size == -1) - { - fprintf(stderr, "Error: unrecognized event %u, cnt %u, offset %x\n", + if(event_size == -1) { + fprintf(stderr, + "Error: unrecognized event %u, cnt %u, offset %x\n", (uint32_t)(hdr->type), - (*cur_event == -1)?0:*cur_event, + (*cur_event == -1) ? 0 : *cur_event, offset); return SCAP_FAILURE; } - if(event_size < sizeof(struct ppm_evt_hdr) + g_event_info[hdr->type].nparams * sizeof(uint16_t)) - { - fprintf(stderr, "Error: event size too short %u, cnt %u, offset %x\n", + if(event_size < + sizeof(struct ppm_evt_hdr) + g_event_info[hdr->type].nparams * sizeof(uint16_t)) { + fprintf(stderr, + "Error: event size too short %u, cnt %u, offset %x\n", (unsigned int)event_size, - (*cur_event == -1)?0:*cur_event, + (*cur_event == -1) ? 0 : *cur_event, offset); return SCAP_FAILURE; } @@ -103,27 +101,27 @@ int32_t g_check_integrity(uint32_t* cur_event, char* copy_buffer, int buf_len, u sentinel_begin = ((struct ppm_evt_hdr*)(copy_buffer + offset))->sentinel_begin; sentinel_end = *(uint32_t*)(copy_buffer + offset + event_size - sizeof(uint32_t)); - if(sentinel_begin != sentinel_end) - { - fprintf(stderr, "Error: sentinel begin %d, sentinel end %d, evt_type %u, evt_size %zu, cnt %u, offset %x, remaining %u\n", + if(sentinel_begin != sentinel_end) { + fprintf(stderr, + "Error: sentinel begin %d, sentinel end %d, evt_type %u, evt_size %zu, cnt %u, " + "offset %x, remaining %u\n", sentinel_begin, sentinel_end, (uint32_t)hdr->type, event_size, - (*cur_event == -1)?0:*cur_event, + (*cur_event == -1) ? 0 : *cur_event, offset, buf_len); return SCAP_FAILURE; } - if(*cur_event == -1) - { + if(*cur_event == -1) { *cur_event = sentinel_begin; } - if(sentinel_begin != *cur_event) - { - fprintf(stderr, "Error1: sentinel begin %d, sentinel end %d, cnt %u, offset %x, remaining %u\n", + if(sentinel_begin != *cur_event) { + fprintf(stderr, + "Error1: sentinel begin %d, sentinel end %d, cnt %u, offset %x, remaining %u\n", sentinel_begin, sentinel_end, *cur_event, @@ -143,8 +141,7 @@ int32_t g_check_integrity(uint32_t* cur_event, char* copy_buffer, int buf_len, u return 0; } -int main() -{ +int main() { uint32_t j; char error[SCAP_LASTERR_SIZE]; int32_t ret; @@ -163,47 +160,41 @@ int main() uint64_t olddeviceevents[256]; /* - unsigned long new_mask = 1 << (1); - sched_setaffinity(0, - sizeof(unsigned long), - &new_mask); + unsigned long new_mask = 1 << (1); + sched_setaffinity(0, + sizeof(unsigned long), + &new_mask); */ scap_open_args args = {}; scap_t* h = scap_open(&args, &scap_kmod_engine, error, &ret); - if(h == NULL) - { + if(h == NULL) { fprintf(stderr, "%s (%d)\n", error, ret); return ret; } ndevs = scap_get_ndevs(h); - if(ndevs > sizeof(cur_evts)/sizeof(cur_evts[0])) - { + if(ndevs > sizeof(cur_evts) / sizeof(cur_evts[0])) { fprintf(stderr, "too many devices %u\n", ndevs); return -1; } - for(j = 0; j < ndevs; j++) - { + for(j = 0; j < ndevs; j++) { devicebytes[j] = 0; deviceevents[j] = 0; olddevicebytes[j] = 0; olddeviceevents[j] = 0; } - while(1) - { - for(j = 0; j < ndevs; j++) - { + while(1) { + for(j = 0; j < ndevs; j++) { uint32_t nevents; ret = scap_readbuf(h, j, &buf, &buflen); - if(ret != SCAP_SUCCESS) - { + if(ret != SCAP_SUCCESS) { fprintf(stderr, "%s\n", scap_getlasterr(h)); scap_close(h); return -1; @@ -211,13 +202,13 @@ int main() cur_evts[j] = -1; - if(g_check_integrity(&(cur_evts[j]), buf, buflen, &nevents) != SCAP_SUCCESS) - { - fprintf(stderr, "Integrity check failure at event %u.\nDumping buffer to dump.bin\n", - (cur_evts[j] == -1)?0:cur_evts[j]); + if(g_check_integrity(&(cur_evts[j]), buf, buflen, &nevents) != SCAP_SUCCESS) { + fprintf(stderr, + "Integrity check failure at event %u.\nDumping buffer to dump.bin\n", + (cur_evts[j] == -1) ? 0 : cur_evts[j]); FILE* f; - f= fopen("dump.bin", "w"); + f = fopen("dump.bin", "w"); fwrite(buf, buflen, 1, f); fclose(f); exit(-1); @@ -228,9 +219,9 @@ int main() devicebytes[j] += buflen; deviceevents[j] += nevents; - if(nloops == 1000) - { - printf(" %u)bps:%" PRIu64 " totbytes:%" PRIu64 " - evts/s:%" PRIu64 " totevs:%" PRIu64 " \n", + if(nloops == 1000) { + printf(" %u)bps:%" PRIu64 " totbytes:%" PRIu64 " - evts/s:%" PRIu64 + " totevs:%" PRIu64 " \n", j, (devicebytes[j] - olddevicebytes[j]), devicebytes[j], @@ -248,18 +239,17 @@ int main() // usleep(1000); - if(nloops == 1000) - { + if(nloops == 1000) { scap_stats stats; - if(scap_get_stats(h, &stats) != SCAP_SUCCESS) - { + if(scap_get_stats(h, &stats) != SCAP_SUCCESS) { fprintf(stderr, "%s\n", scap_getlasterr(h)); scap_close(h); return -1; } - printf("bps:%" PRIu64 " totbytes:%" PRIu64 " - evts/s:%" PRIu64 " totevs:%" PRIu64 " drops:%" PRIu64 "\n", + printf("bps:%" PRIu64 " totbytes:%" PRIu64 " - evts/s:%" PRIu64 " totevs:%" PRIu64 + " drops:%" PRIu64 "\n", totbytes - oldtotbytes, totbytes, totevents - oldtotevents, diff --git a/userspace/libscap/linux/CMakeLists.txt b/userspace/libscap/linux/CMakeLists.txt index 4d51534ca0..435c8546c0 100644 --- a/userspace/libscap/linux/CMakeLists.txt +++ b/userspace/libscap/linux/CMakeLists.txt @@ -2,20 +2,18 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -add_library(scap_platform - STATIC +add_library( + scap_platform STATIC scap_linux_platform.c scap_linux_hostinfo_platform.c scap_procs.c @@ -23,7 +21,8 @@ add_library(scap_platform scap_userlist.c scap_iflist.c scap_cgroup.c - scap_machine_info.c) + scap_machine_info.c +) target_include_directories(scap_platform PUBLIC $) target_link_libraries(scap_platform PRIVATE scap_error scap_platform_util) add_dependencies(scap_platform uthash) diff --git a/userspace/libscap/linux/gettimeofday.h b/userspace/libscap/linux/gettimeofday.h index 58af1b8064..21c6fc8841 100644 --- a/userspace/libscap/linux/gettimeofday.h +++ b/userspace/libscap/linux/gettimeofday.h @@ -21,14 +21,12 @@ limitations under the License. #include #include -static inline uint64_t get_timestamp_ns() -{ +static inline uint64_t get_timestamp_ns() { uint64_t ts; struct timeval tv; gettimeofday(&tv, NULL); - ts = tv.tv_sec * (uint64_t) 1000000000 + tv.tv_usec * 1000; + ts = tv.tv_sec * (uint64_t)1000000000 + tv.tv_usec * 1000; return ts; } - diff --git a/userspace/libscap/linux/scap_cgroup.c b/userspace/libscap/linux/scap_cgroup.c index 9b03bcb735..e8961ddabd 100644 --- a/userspace/libscap/linux/scap_cgroup.c +++ b/userspace/libscap/linux/scap_cgroup.c @@ -32,8 +32,7 @@ limitations under the License. #include #include -struct scap_cgroup_cache -{ +struct scap_cgroup_cache { char path[SCAP_MAX_PATH_SIZE]; struct scap_cgroup_set subsystems; @@ -41,13 +40,11 @@ struct scap_cgroup_cache }; static int32_t __attribute__((format(printf, 2, 3))) -scap_cgroup_printf(struct scap_cgroup_set* cgset, const char* fmt, ...) -{ +scap_cgroup_printf(struct scap_cgroup_set* cgset, const char* fmt, ...) { va_list va; int max_space = SCAP_MAX_CGROUPS_SIZE - cgset->len; - if(max_space <= 0) - { + if(max_space <= 0) { // no room in the buffer return SCAP_FAILURE; } @@ -56,8 +53,7 @@ scap_cgroup_printf(struct scap_cgroup_set* cgset, const char* fmt, ...) int nwritten = vsnprintf(cgset->path + cgset->len, max_space, fmt, va); va_end(va); - if(nwritten > max_space) - { + if(nwritten > max_space) { // output truncated return SCAP_FAILURE; } @@ -66,8 +62,7 @@ scap_cgroup_printf(struct scap_cgroup_set* cgset, const char* fmt, ...) return SCAP_SUCCESS; } -static int32_t scap_grep_cgroups(char* path, char* path_end, const char* pid_str) -{ +static int32_t scap_grep_cgroups(char* path, char* path_end, const char* pid_str) { char line[SCAP_MAX_PATH_SIZE]; // we reuse the `path` buffer (containing the path to the cgroup) to store @@ -90,15 +85,12 @@ static int32_t scap_grep_cgroups(char* path, char* path_end, const char* pid_str FILE* cg = fopen(path, "r"); *path_end = 0; - if(!cg) - { + if(!cg) { return SCAP_FAILURE; } - while(fgets(line, sizeof(line), cg) != NULL) - { - if(strcmp(line, pid_str) == 0) - { + while(fgets(line, sizeof(line), cg) != NULL) { + if(strcmp(line, pid_str) == 0) { fclose(cg); return SCAP_SUCCESS; } @@ -115,49 +107,41 @@ static int32_t scap_find_my_cgroup(char* path, const char* pid_str); // `path_end` points to NUL terminator of the path (inside `path`) // `pid_str` is the current pid, formatted as a string with a newline appended // (this is what we're looking for in .../cgroup.procs) -static int32_t scap_cgroup_descend(char* path, char* path_end, const char* pid_str) -{ +static int32_t scap_cgroup_descend(char* path, char* path_end, const char* pid_str) { DIR* cg; struct dirent* pde; struct stat s; cg = opendir(path); - if(!cg) - { + if(!cg) { return SCAP_FAILURE; } *path_end = '/'; - while(1) - { + while(1) { // For all directories in `path`, append the directory name and call scap_find_my_cgroup // (which calls scap_cgroup_descend recursively if `pid_str` is not found in the directory). // // This results in a depth-first search across all cgroups. pde = readdir(cg); - if(pde == NULL) - { + if(pde == NULL) { closedir(cg); break; } - if(pde->d_name[0] == '.') - { + if(pde->d_name[0] == '.') { continue; } snprintf(path_end + 1, SCAP_MAX_PATH_SIZE - (path_end + 1 - path), "%s", pde->d_name); - if(lstat(path, &s) != 0) - { + if(lstat(path, &s) != 0) { continue; } - if(S_ISDIR(s.st_mode)) - { + if(S_ISDIR(s.st_mode)) { int ret = scap_find_my_cgroup(path, pid_str); - if(ret == SCAP_SUCCESS) - { + if(ret == SCAP_SUCCESS) { closedir(cg); return ret; } @@ -174,15 +158,13 @@ static int32_t scap_cgroup_descend(char* path, char* path_end, const char* pid_s // on exit: // - if ret == SCAP_SUCCESS, path contains the full path to the cgroup found // - otherwise, the content of path is unspecified -static int32_t scap_find_my_cgroup(char* path, const char* pid_str) -{ +static int32_t scap_find_my_cgroup(char* path, const char* pid_str) { int32_t ret; char* path_end = path + strlen(path); // first, try the current directory ret = scap_grep_cgroups(path, path_end, pid_str); - if(ret != SCAP_NOTFOUND) - { + if(ret != SCAP_NOTFOUND) { return ret; } @@ -194,21 +176,14 @@ static int32_t scap_find_my_cgroup(char* path, const char* pid_str) // an important difference: strrchr starts looking for the character // at str+strlen(str)-1, while scan_back starts the search at // an arbitrary point in the string -static const char* scan_back(const char* start, const char* end) -{ +static const char* scan_back(const char* start, const char* end) { const char* q = end; - while(1) - { - if(*q == '/') - { + while(1) { + if(*q == '/') { return q; - } - else if(q == start) - { + } else if(q == start) { return NULL; - } - else - { + } else { q--; } } @@ -258,32 +233,30 @@ static const char* scan_back(const char* start, const char* end) // // Note: we have a special case when path is just a bunch of `/../../../`s: we strip the remaining // slash so that we don't end up with doubled slashes (one from the prefix, one from the path) -static int32_t scap_cgroup_prefix_path(const char* prefix, const char* path, size_t* prefix_len, size_t* path_strip_len) -{ +static int32_t scap_cgroup_prefix_path(const char* prefix, + const char* path, + size_t* prefix_len, + size_t* path_strip_len) { ASSERT(prefix != NULL); ASSERT(path != NULL); const char* prefix_p = prefix + strlen(prefix); const char* path_p = path; - while(strncmp(path_p, "/..", 3) == 0) - { + while(strncmp(path_p, "/..", 3) == 0) { // If there's a trailing slash, remove it before scanning. - if (*prefix_p == '/' && prefix_p != prefix) - { + if(*prefix_p == '/' && prefix_p != prefix) { prefix_p--; } path_p += 3; prefix_p = scan_back(prefix, prefix_p); - if(prefix_p == NULL) - { + if(prefix_p == NULL) { return SCAP_FAILURE; } } - if(!strcmp(path_p, "/")) - { + if(!strcmp(path_p, "/")) { path_p++; } @@ -326,25 +299,22 @@ static int32_t scap_cgroup_prefix_path(const char* prefix, const char* path, siz // - cpuset // - name=systemd // -// (we skip the empty one since it's either v2, or an empty subsys list without a name, i.e. generally useless) -static int32_t get_cgroup_subsystems_v1(struct scap_cgroup_set* subsystems) -{ +// (we skip the empty one since it's either v2, or an empty subsys list without a name, i.e. +// generally useless) +static int32_t get_cgroup_subsystems_v1(struct scap_cgroup_set* subsystems) { char line[SCAP_MAX_PATH_SIZE]; subsystems->len = 0; FILE* cgroups = fopen("/proc/self/cgroup", "r"); - if(!cgroups) - { + if(!cgroups) { return SCAP_FAILURE; } - while(fgets(line, sizeof(line), cgroups) != NULL) - { + while(fgets(line, sizeof(line), cgroups) != NULL) { // 3:cpu,cpuacct:/user.slice/user-0.slice/session-13542.scope // ^p char* p = strchr(line, ':'); - if(!p) - { + if(!p) { fclose(cgroups); return SCAP_FAILURE; } @@ -353,8 +323,7 @@ static int32_t get_cgroup_subsystems_v1(struct scap_cgroup_set* subsystems) // ^p ^q p += 1; char* q = strchr(p, ':'); - if(!q) - { + if(!q) { fclose(cgroups); return SCAP_FAILURE; } @@ -362,29 +331,24 @@ static int32_t get_cgroup_subsystems_v1(struct scap_cgroup_set* subsystems) // 3:cpu,cpuacct // ^p ^q *q = 0; - if(strlen(p) == 0) - { + if(strlen(p) == 0) { continue; } - while(1) - { + while(1) { // 3:cpu\0cpuacct // ^p ^q char* comma = strchr(p, ','); - if(comma) - { + if(comma) { *comma = 0; } - if(scap_cgroup_printf(subsystems, "%s", p) == SCAP_FAILURE) - { + if(scap_cgroup_printf(subsystems, "%s", p) == SCAP_FAILURE) { fclose(cgroups); return SCAP_FAILURE; } - if(!comma) - { + if(!comma) { break; } @@ -400,28 +364,28 @@ static int32_t get_cgroup_subsystems_v1(struct scap_cgroup_set* subsystems) // Get mount points for all cgroup v1 subsystems // -// Note: some v1 subsystems can be mounted together (e.g. cpu,cpuacct): we don't care and remember them separately -// This needs to be called for each mount entry when looping over `getmntent_r` +// Note: some v1 subsystems can be mounted together (e.g. cpu,cpuacct): we don't care and remember +// them separately This needs to be called for each mount entry when looping over `getmntent_r` // // To bypass cgroup namespaces, we always access the host's cgroup filesystem via /proc/1/root/ -static int32_t scap_get_cgroup_mount_v1(struct mntent* de, struct scap_cgroup_set* mounts, struct scap_cgroup_set* cg_subsystems, const char* host_root, char* error) -{ - if(cg_subsystems->len == 0 && get_cgroup_subsystems_v1(cg_subsystems) == SCAP_FAILURE) - { +static int32_t scap_get_cgroup_mount_v1(struct mntent* de, + struct scap_cgroup_set* mounts, + struct scap_cgroup_set* cg_subsystems, + const char* host_root, + char* error) { + if(cg_subsystems->len == 0 && get_cgroup_subsystems_v1(cg_subsystems) == SCAP_FAILURE) { return scap_errprintf(error, 0, "failed to parse /proc/self/cgroup"); } - FOR_EACH_SUBSYS(cg_subsystems, cg_subsys) - { + FOR_EACH_SUBSYS(cg_subsystems, cg_subsys) { // hasmntopt is smart enough to match comma-delimited strings, so e.g. // "cpuset,cpuacct" won't match "cpu" but "cpu,cpuacct" will - if(!hasmntopt(de, cg_subsys)) - { + if(!hasmntopt(de, cg_subsys)) { continue; } - if(scap_cgroup_printf(mounts, "%s=%s/proc/1/root%s", cg_subsys, host_root, de->mnt_dir) != SCAP_SUCCESS) - { + if(scap_cgroup_printf(mounts, "%s=%s/proc/1/root%s", cg_subsys, host_root, de->mnt_dir) != + SCAP_SUCCESS) { ASSERT(false); return SCAP_FAILURE; } @@ -432,20 +396,21 @@ static int32_t scap_get_cgroup_mount_v1(struct mntent* de, struct scap_cgroup_se // Get the (v1) cgroups of the current process, bypassing cgroup namespace restrictions // -// We can't simply read them from /proc/self/cgroup, since these names will be relative to the cgroup -// namespace root (i.e. probably just "/"). Instead, we do a recursive grep of all cgroup.procs files -// under each mountpoint for our process id. -static int32_t scap_get_cgroup_self_v1_cgroupns(struct mntent* de, struct scap_cgroup_set* self, struct scap_cgroup_set* cg_subsystems, const char* host_root, char* pid_str, char* error) -{ - if(cg_subsystems->len == 0 && get_cgroup_subsystems_v1(cg_subsystems) == SCAP_FAILURE) - { +// We can't simply read them from /proc/self/cgroup, since these names will be relative to the +// cgroup namespace root (i.e. probably just "/"). Instead, we do a recursive grep of all +// cgroup.procs files under each mountpoint for our process id. +static int32_t scap_get_cgroup_self_v1_cgroupns(struct mntent* de, + struct scap_cgroup_set* self, + struct scap_cgroup_set* cg_subsystems, + const char* host_root, + char* pid_str, + char* error) { + if(cg_subsystems->len == 0 && get_cgroup_subsystems_v1(cg_subsystems) == SCAP_FAILURE) { return scap_errprintf(error, 0, "failed to parse /proc/self/cgroup"); } - FOR_EACH_SUBSYS(cg_subsystems, cgset_subsys) - { - if(!hasmntopt(de, cgset_subsys)) - { + FOR_EACH_SUBSYS(cg_subsystems, cgset_subsys) { + if(!hasmntopt(de, cgset_subsys)) { continue; } @@ -453,8 +418,7 @@ static int32_t scap_get_cgroup_self_v1_cgroupns(struct mntent* de, struct scap_c snprintf(my_cg, sizeof(my_cg), "%s/proc/1/root%s", host_root, de->mnt_dir); char* p = my_cg + strlen(my_cg); - if(scap_find_my_cgroup(my_cg, pid_str) != SCAP_SUCCESS) - { + if(scap_find_my_cgroup(my_cg, pid_str) != SCAP_SUCCESS) { return SCAP_FAILURE; } @@ -478,15 +442,14 @@ static int32_t scap_get_cgroup_self_v1_cgroupns(struct mntent* de, struct scap_c // We need to walk up the directory tree when looking for subsystems, // so we will end up calling this function repeatedly for the same directory. // To minimize the overhead, we use a simple cache. -static int32_t get_cgroup_subsystems_v2(struct scap_cgroup_interface* cgi, struct scap_cgroup_set* subsystems, const char* cgroup_mount) -{ - if(cgi->m_use_cache) - { +static int32_t get_cgroup_subsystems_v2(struct scap_cgroup_interface* cgi, + struct scap_cgroup_set* subsystems, + const char* cgroup_mount) { + if(cgi->m_use_cache) { struct scap_cgroup_cache* cached; HASH_FIND_STR(cgi->m_cache, cgroup_mount, cached); - if(cached != NULL) - { + if(cached != NULL) { *subsystems = cached->subsystems; return SCAP_SUCCESS; } @@ -496,19 +459,17 @@ static int32_t get_cgroup_subsystems_v2(struct scap_cgroup_interface* cgi, struc char line[SCAP_MAX_PATH_SIZE]; snprintf(line, sizeof(line), "%s/cgroup.controllers", cgroup_mount); - if (access(line, F_OK) == -1) { - // If the file does not exist, return success. Skip - return SCAP_SUCCESS; - } + if(access(line, F_OK) == -1) { + // If the file does not exist, return success. Skip + return SCAP_SUCCESS; + } FILE* cgroup_controllers = fopen(line, "r"); - if(!cgroup_controllers) - { + if(!cgroup_controllers) { return SCAP_FAILURE; } - if(fgets(line, sizeof(line), cgroup_controllers) == NULL) - { + if(fgets(line, sizeof(line), cgroup_controllers) == NULL) { // no subsystems, report an empty set line[0] = 0; } @@ -517,21 +478,18 @@ static int32_t get_cgroup_subsystems_v2(struct scap_cgroup_interface* cgi, struc // cpuset cpu io memory hugetlb pids rdma misc // ^p char* p = line; - while(1) - { + while(1) { // cpuset cpu io memory hugetlb pids rdma misc // ^p size_t pos = strcspn(p, " \n"); - if(pos == 0) - { + if(pos == 0) { break; } // cpuset\0cpu io memory hugetlb pids rdma misc // ^p[pos] p[pos] = 0; - if(scap_cgroup_printf(subsystems, "%s", p) == SCAP_FAILURE) - { + if(scap_cgroup_printf(subsystems, "%s", p) == SCAP_FAILURE) { return SCAP_FAILURE; } @@ -540,18 +498,15 @@ static int32_t get_cgroup_subsystems_v2(struct scap_cgroup_interface* cgi, struc // ^p } - if(cgi->m_use_cache) - { + if(cgi->m_use_cache) { struct scap_cgroup_cache* cached = (struct scap_cgroup_cache*)malloc(sizeof(*cached)); - if(cached) - { + if(cached) { int uth_status = SCAP_SUCCESS; snprintf(cached->path, sizeof(cached->path), "%s", cgroup_mount); memcpy(&cached->subsystems, subsystems, sizeof(cached->subsystems)); HASH_ADD_STR(cgi->m_cache, path, cached); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { free(cached); } } @@ -563,8 +518,9 @@ static int32_t get_cgroup_subsystems_v2(struct scap_cgroup_interface* cgi, struc // Get the v2 cgroup mount // // Since there is just one, we don't need to do anything fancy here, just glue the pieces together -static int32_t scap_get_cgroup_mount_v2(struct mntent* de, char* mountpoint, const char* host_root) -{ +static int32_t scap_get_cgroup_mount_v2(struct mntent* de, + char* mountpoint, + const char* host_root) { snprintf(mountpoint, SCAP_MAX_PATH_SIZE, "%s/proc/1/root%s", host_root, de->mnt_dir); return SCAP_SUCCESS; } @@ -572,18 +528,18 @@ static int32_t scap_get_cgroup_mount_v2(struct mntent* de, char* mountpoint, con // Get the (v2) cgroup of the current process, bypassing cgroup namespace restrictions // // We can't simply read it from /proc/self/cgroup, since the name will be relative to the cgroup -// namespace root (i.e. probably just "/"). Instead, we do a recursive grep of all cgroup.procs files -// under the v2 mountpoint for our process id. -static int32_t scap_get_cgroup_self_v2_cgroupns(struct mntent* de, char* self, const char* host_root, char* pid_str) -{ +// namespace root (i.e. probably just "/"). Instead, we do a recursive grep of all cgroup.procs +// files under the v2 mountpoint for our process id. +static int32_t scap_get_cgroup_self_v2_cgroupns(struct mntent* de, + char* self, + const char* host_root, + char* pid_str) { char my_cg[SCAP_MAX_PATH_SIZE]; size_t my_cg_len = snprintf(my_cg, sizeof(my_cg), "%s/proc/1/root%s", host_root, de->mnt_dir); - if(my_cg_len >= sizeof(my_cg)) - { + if(my_cg_len >= sizeof(my_cg)) { return SCAP_FAILURE; } - if(scap_find_my_cgroup(my_cg, pid_str) != SCAP_SUCCESS) - { + if(scap_find_my_cgroup(my_cg, pid_str) != SCAP_SUCCESS) { return SCAP_FAILURE; } @@ -591,8 +547,7 @@ static int32_t scap_get_cgroup_self_v2_cgroupns(struct mntent* de, char* self, c return SCAP_SUCCESS; } -static bool scap_in_cgroupns(const char* host_root) -{ +static bool scap_in_cgroupns(const char* host_root) { // compare our cgroup ns id with init's (pid 1) // when running in a container, we need access to the host's /proc directory // for two reasons: @@ -610,8 +565,7 @@ static bool scap_in_cgroupns(const char* host_root) snprintf(filename, sizeof(filename), "%s/proc/self/ns/cgroup", host_root); link_len = readlink(filename, our_cgroupns, sizeof(our_cgroupns)); - if(link_len < 0 || link_len >= sizeof(our_cgroupns)) - { + if(link_len < 0 || link_len >= sizeof(our_cgroupns)) { // < 0 means couldn't get the link; assuming cgroupns not available // otherwise cgroupns link is too long, which is surprising since it has a fixed, // fairly short length @@ -621,14 +575,12 @@ static bool scap_in_cgroupns(const char* host_root) snprintf(filename, sizeof(filename), "%s/proc/1/ns/cgroup", host_root); link_len = readlink(filename, init_cgroupns, sizeof(init_cgroupns)); - if(link_len < 0 || link_len >= sizeof(our_cgroupns)) - { + if(link_len < 0 || link_len >= sizeof(our_cgroupns)) { return false; } init_cgroupns[link_len] = 0; - if(strcmp(init_cgroupns, our_cgroupns) == 0) - { + if(strcmp(init_cgroupns, our_cgroupns) == 0) { // we're in the root cgroup ns, no hacks necessary return false; } @@ -636,8 +588,10 @@ static bool scap_in_cgroupns(const char* host_root) return true; } -int32_t scap_cgroup_interface_init(struct scap_cgroup_interface* cgi, const char* host_root, char* error, bool with_self_cg) -{ +int32_t scap_cgroup_interface_init(struct scap_cgroup_interface* cgi, + const char* host_root, + char* error, + bool with_self_cg) { char filename[SCAP_MAX_PATH_SIZE]; char pid_str[40]; @@ -651,44 +605,45 @@ int32_t scap_cgroup_interface_init(struct scap_cgroup_interface* cgi, const char cgi->m_self_v2[0] = 0; cgi->m_in_cgroupns = false; - // if we don't need our cgroup name (will just use the mountpoints, with the full cgroup names coming - // from elsewhere), we can simply assume we're not in a cgroup namespace (the result is the same) - if(with_self_cg) - { + // if we don't need our cgroup name (will just use the mountpoints, with the full cgroup names + // coming from elsewhere), we can simply assume we're not in a cgroup namespace (the result is + // the same) + if(with_self_cg) { cgi->m_in_cgroupns = scap_in_cgroupns(host_root); } - if(cgi->m_in_cgroupns) - { + if(cgi->m_in_cgroupns) { snprintf(pid_str, sizeof(pid_str), "%d\n", getpid()); } snprintf(filename, sizeof(filename), "%s/proc/1/mounts", host_root); FILE* mounts = setmntent(filename, "r"); - if(mounts == NULL) - { + if(mounts == NULL) { return scap_errprintf(error, errno, "failed to open %s", filename); } struct mntent entry, *de; char mntent_buf[4096]; - while((de = getmntent_r(mounts, &entry, mntent_buf, sizeof(mntent_buf))) != NULL) - { - if(strcmp(de->mnt_type, "cgroup") == 0) - { - scap_get_cgroup_mount_v1(de, &cgi->m_mounts_v1, &cgi->m_subsystems_v1, host_root, error); - if(cgi->m_in_cgroupns) - { - scap_get_cgroup_self_v1_cgroupns(de, &cgi->m_self_v1, &cgi->m_subsystems_v1, host_root, pid_str, error); + while((de = getmntent_r(mounts, &entry, mntent_buf, sizeof(mntent_buf))) != NULL) { + if(strcmp(de->mnt_type, "cgroup") == 0) { + scap_get_cgroup_mount_v1(de, + &cgi->m_mounts_v1, + &cgi->m_subsystems_v1, + host_root, + error); + if(cgi->m_in_cgroupns) { + scap_get_cgroup_self_v1_cgroupns(de, + &cgi->m_self_v1, + &cgi->m_subsystems_v1, + host_root, + pid_str, + error); } - } - else if(strcmp(de->mnt_type, "cgroup2") == 0) - { + } else if(strcmp(de->mnt_type, "cgroup2") == 0) { scap_get_cgroup_mount_v2(de, cgi->m_mount_v2, host_root); get_cgroup_subsystems_v2(cgi, &cgi->m_subsystems_v2, cgi->m_mount_v2); - if(cgi->m_in_cgroupns) - { + if(cgi->m_in_cgroupns) { scap_get_cgroup_self_v2_cgroupns(de, cgi->m_self_v2, host_root, pid_str); } } @@ -700,12 +655,9 @@ int32_t scap_cgroup_interface_init(struct scap_cgroup_interface* cgi, const char } // does `subsys` exist in the `cg` set? -static bool scap_cgroup_find_subsys(const struct scap_cgroup_set* cg, const char* subsys) -{ - FOR_EACH_SUBSYS(cg, cgset_subsys) - { - if(strcmp(cgset_subsys, subsys) == 0) - { +static bool scap_cgroup_find_subsys(const struct scap_cgroup_set* cg, const char* subsys) { + FOR_EACH_SUBSYS(cg, cgset_subsys) { + if(strcmp(cgset_subsys, subsys) == 0) { return true; } } @@ -714,12 +666,10 @@ static bool scap_cgroup_find_subsys(const struct scap_cgroup_set* cg, const char } // does `smaller` contain all the entries in `larger`? -static bool scap_cgroup_set_contains_all(const struct scap_cgroup_set* larger, const struct scap_cgroup_set* smaller) -{ - FOR_EACH_SUBSYS(larger, cgset_subsys) - { - if(!scap_cgroup_find_subsys(smaller, cgset_subsys)) - { +static bool scap_cgroup_set_contains_all(const struct scap_cgroup_set* larger, + const struct scap_cgroup_set* smaller) { + FOR_EACH_SUBSYS(larger, cgset_subsys) { + if(!scap_cgroup_find_subsys(smaller, cgset_subsys)) { return false; } } @@ -734,9 +684,11 @@ static bool scap_cgroup_set_contains_all(const struct scap_cgroup_set* larger, c // // $ cat /proc/self/cgroup // 0::/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-5344486b-2f3a-4de3-85d7-4cab5f76db2b.scope -// $ cat /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-5344486b-2f3a-4de3-85d7-4cab5f76db2b.scope/cgroup.controllers +// $ cat +// /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-5344486b-2f3a-4de3-85d7-4cab5f76db2b.scope/cgroup.controllers // memory pids -// $ cat /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/cgroup.controllers +// $ cat +// /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/cgroup.controllers // memory pids // $ cat /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/app.slice/cgroup.controllers // memory pids @@ -755,88 +707,81 @@ static bool scap_cgroup_set_contains_all(const struct scap_cgroup_set* larger, c // 3:hugetlb,rdma,misc:/ // // To find the above cgroups, we need to walk up the directory tree, starting at the process cgroup, -// looking at cgroup.controllers at each level. For every level, we see if there are any new subsystems enabled -// and if so, add them to the cgroup set. +// looking at cgroup.controllers at each level. For every level, we see if there are any new +// subsystems enabled and if so, add them to the cgroup set. // -// We walk the tree upwards until we either reach the cgroup mount point, or we find all the subsystems -static int32_t scap_cgroup_resolve_v2(struct scap_cgroup_interface* cgi, const char* cgroup, struct scap_cgroup_set* cg) -{ +// We walk the tree upwards until we either reach the cgroup mount point, or we find all the +// subsystems +static int32_t scap_cgroup_resolve_v2(struct scap_cgroup_interface* cgi, + const char* cgroup, + struct scap_cgroup_set* cg) { char full_cgroup[SCAP_MAX_PATH_SIZE]; char cgroup_path[SCAP_MAX_PATH_SIZE]; int nwritten; - if(cgi->m_self_v2[0]) - { + if(cgi->m_self_v2[0]) { size_t prefix_len; size_t suffix_skip_len; if(scap_cgroup_prefix_path(cgi->m_self_v2, cgroup, &prefix_len, &suffix_skip_len) != - SCAP_SUCCESS) - { + SCAP_SUCCESS) { return SCAP_FAILURE; } - nwritten = snprintf(full_cgroup, sizeof(full_cgroup), "%.*s%s", (int)prefix_len, cgi->m_self_v2, cgroup + suffix_skip_len); - } - else - { + nwritten = snprintf(full_cgroup, + sizeof(full_cgroup), + "%.*s%s", + (int)prefix_len, + cgi->m_self_v2, + cgroup + suffix_skip_len); + } else { nwritten = snprintf(full_cgroup, sizeof(full_cgroup), "%s", cgroup); } - if(nwritten >= sizeof(full_cgroup)) - { + if(nwritten >= sizeof(full_cgroup)) { return SCAP_FAILURE; } nwritten = snprintf(cgroup_path, sizeof(cgroup_path), "%s%s", cgi->m_mount_v2, full_cgroup); - if(nwritten >= sizeof(cgroup_path)) - { + if(nwritten >= sizeof(cgroup_path)) { return SCAP_FAILURE; } struct scap_cgroup_set found_subsystems = {.len = 0, {'\0'}}; - while(1) // not reached cgroup mountpoint yet + while(1) // not reached cgroup mountpoint yet { struct scap_cgroup_set current_subsystems; - if(get_cgroup_subsystems_v2(cgi, ¤t_subsystems, cgroup_path) != SCAP_SUCCESS) - { + if(get_cgroup_subsystems_v2(cgi, ¤t_subsystems, cgroup_path) != SCAP_SUCCESS) { return SCAP_FAILURE; } - FOR_EACH_SUBSYS(¤t_subsystems, cgset_subsys) - { - if(!scap_cgroup_find_subsys(&found_subsystems, cgset_subsys)) - { - if(scap_cgroup_printf(cg, "%s=%s", cgset_subsys, full_cgroup) != SCAP_SUCCESS) - { + FOR_EACH_SUBSYS(¤t_subsystems, cgset_subsys) { + if(!scap_cgroup_find_subsys(&found_subsystems, cgset_subsys)) { + if(scap_cgroup_printf(cg, "%s=%s", cgset_subsys, full_cgroup) != SCAP_SUCCESS) { return SCAP_FAILURE; } - if(scap_cgroup_printf(&found_subsystems, "%s", cgset_subsys) != SCAP_SUCCESS) - { + if(scap_cgroup_printf(&found_subsystems, "%s", cgset_subsys) != SCAP_SUCCESS) { return SCAP_FAILURE; } } } - if(full_cgroup[1] == 0) // i.e. full_cgroup is just "/" + if(full_cgroup[1] == 0) // i.e. full_cgroup is just "/" { // reached the root, bail out break; } - if(scap_cgroup_set_contains_all(&cgi->m_subsystems_v2, &found_subsystems)) - { + if(scap_cgroup_set_contains_all(&cgi->m_subsystems_v2, &found_subsystems)) { break; } char* q; q = strrchr(full_cgroup, '/'); - if(!q) - { + if(!q) { break; } - if(q == full_cgroup) - { + if(q == full_cgroup) { // leave the initial '/' in q++; } @@ -850,8 +795,10 @@ static int32_t scap_cgroup_resolve_v2(struct scap_cgroup_interface* cgi, const c } // Get all cgroups (v1 and v2) for a thread whose /proc directory is `procdirname` -int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* procdirname, struct scap_cgroup_set* cg, char* error) -{ +int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, + const char* procdirname, + struct scap_cgroup_set* cg, + char* error) { char filename[SCAP_MAX_PATH_SIZE]; char line[SCAP_MAX_CGROUPS_SIZE]; @@ -859,10 +806,8 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr snprintf(filename, sizeof(filename), "%scgroup", procdirname); FILE* f = fopen(filename, "r"); - if(f == NULL) - { - if(errno == ENOENT || errno == EACCES) - { + if(f == NULL) { + if(errno == ENOENT || errno == EACCES) { return SCAP_SUCCESS; } @@ -870,8 +815,7 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr return scap_errprintf(error, errno, "open cgroup file %s failed", filename); } - while(fgets(line, sizeof(line), f) != NULL) - { + while(fgets(line, sizeof(line), f) != NULL) { char* token; char* subsys_list; char* cgroup; @@ -879,8 +823,7 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr // id token = strtok_r(line, ":", &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); fclose(f); return scap_errprintf(error, 0, "Did not find id in cgroup file %s", filename); @@ -888,8 +831,7 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr // subsys subsys_list = strtok_r(NULL, ":", &scratch); - if(subsys_list == NULL) - { + if(subsys_list == NULL) { ASSERT(false); fclose(f); return scap_errprintf(error, 0, "Did not find subsys in cgroup file %s", filename); @@ -898,8 +840,7 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr // Hack to detect empty fields, because strtok does not support it // strsep() should be used to fix this but it's not available // on CentOS 6 (has been added from Glibc 2.19) - if(subsys_list - token - strlen(token) > 1) - { + if(subsys_list - token - strlen(token) > 1) { // Subsys list empty (ie: it contains cgroup path instead)! // // See https://man7.org/linux/man-pages/man7/cgroups.7.html: @@ -922,37 +863,31 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr // pathname is relative to the mount point of the // hierarchy. // - // -> for cgroup2: id is always 0 and subsys list is always empty (single unified hierarchy) - // -> for cgroup1: skip subsys empty because it means controller is not mounted on any hierarchy - if(cgi->m_mount_v2[0] != 0 && strcmp(token, "0") == 0) - { + // -> for cgroup2: id is always 0 and subsys list is always empty (single unified + // hierarchy) + // -> for cgroup1: skip subsys empty because it means controller is not mounted on any + // hierarchy + if(cgi->m_mount_v2[0] != 0 && strcmp(token, "0") == 0) { cgroup = subsys_list; size_t cgroup_len = strlen(cgroup); - if(cgroup_len != 0 && cgroup[cgroup_len - 1] == '\n') - { + if(cgroup_len != 0 && cgroup[cgroup_len - 1] == '\n') { cgroup[cgroup_len - 1] = '\0'; } - if(scap_cgroup_resolve_v2(cgi, cgroup, cg) != SCAP_SUCCESS) - { + if(scap_cgroup_resolve_v2(cgi, cgroup, cg) != SCAP_SUCCESS) { fclose(f); return scap_errprintf(error, 0, "Cannot resolve v2 cgroups"); } continue; - } - else - { + } else { // skip cgroups like this: // 0::/init.scope continue; } - } - else - { + } else { // cgroup should be the only thing remaining so use newline as the delimiter. cgroup = strtok_r(NULL, "\n", &scratch); - if(cgroup == NULL) - { + if(cgroup == NULL) { ASSERT(false); fclose(f); return scap_errprintf(error, 0, "Did not find cgroup in cgroup file %s", filename); @@ -961,40 +896,36 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr const char* self_path = NULL; size_t len = strlen(subsys_list); - FOR_EACH_SUBSYS(&cgi->m_self_v1, cgset_subsys) - { - if(strncmp(cgset_subsys, subsys_list, len) == 0 && cgset_subsys[len] == '=') - { + FOR_EACH_SUBSYS(&cgi->m_self_v1, cgset_subsys) { + if(strncmp(cgset_subsys, subsys_list, len) == 0 && cgset_subsys[len] == '=') { self_path = cgset_subsys + len + 1; } } - while((token = strtok_r(subsys_list, ",", &scratch)) != NULL) - { + while((token = strtok_r(subsys_list, ",", &scratch)) != NULL) { subsys_list = NULL; int ret; - if(self_path) - { + if(self_path) { size_t prefix_len; size_t suffix_skip_len; if(scap_cgroup_prefix_path(self_path, cgroup, &prefix_len, &suffix_skip_len) != - SCAP_SUCCESS) - { + SCAP_SUCCESS) { ASSERT(false); fclose(f); return SCAP_SUCCESS; } - ret = scap_cgroup_printf(cg, "%s=%.*s%s", token, (int)prefix_len, self_path, - cgroup + suffix_skip_len); - } - else - { + ret = scap_cgroup_printf(cg, + "%s=%.*s%s", + token, + (int)prefix_len, + self_path, + cgroup + suffix_skip_len); + } else { ret = scap_cgroup_printf(cg, "%s=%s", token, cgroup); } - if(ret == SCAP_FAILURE) - { + if(ret == SCAP_FAILURE) { ASSERT(false); fclose(f); return SCAP_SUCCESS; @@ -1011,20 +942,18 @@ int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* pr // Note: there's no notion of a system-wide cgroup version: each subsystem can be mounted // either as v1 or v2 (but once mounted, it stays there; you can't have a subsystem mounted // both ways) -const char* scap_cgroup_get_subsys_mount(const struct scap_cgroup_interface* cgi, const char* subsys, int* version) -{ +const char* scap_cgroup_get_subsys_mount(const struct scap_cgroup_interface* cgi, + const char* subsys, + int* version) { size_t subsys_len = strlen(subsys); - FOR_EACH_SUBSYS(&cgi->m_mounts_v1, cgset_subsys) - { - if(strncmp(cgset_subsys, subsys, subsys_len) == 0 && cgset_subsys[subsys_len] == '=') - { + FOR_EACH_SUBSYS(&cgi->m_mounts_v1, cgset_subsys) { + if(strncmp(cgset_subsys, subsys, subsys_len) == 0 && cgset_subsys[subsys_len] == '=') { *version = 1; return cgset_subsys + subsys_len + 1; } } - if(cgi->m_mount_v2[0]) - { + if(cgi->m_mount_v2[0]) { *version = 2; return cgi->m_mount_v2; } @@ -1034,16 +963,13 @@ const char* scap_cgroup_get_subsys_mount(const struct scap_cgroup_interface* cgi return NULL; } -void scap_cgroup_clear_cache(struct scap_cgroup_interface* cgi) -{ +void scap_cgroup_clear_cache(struct scap_cgroup_interface* cgi) { cgi->m_use_cache = false; - if(cgi->m_cache) - { + if(cgi->m_cache) { struct scap_cgroup_cache* cache; struct scap_cgroup_cache* tcache; - HASH_ITER(hh, cgi->m_cache, cache, tcache) - { + HASH_ITER(hh, cgi->m_cache, cache, tcache) { HASH_DEL(cgi->m_cache, cache); free(cache); } @@ -1052,8 +978,7 @@ void scap_cgroup_clear_cache(struct scap_cgroup_interface* cgi) } } -void scap_cgroup_enable_cache(struct scap_cgroup_interface* cgi) -{ +void scap_cgroup_enable_cache(struct scap_cgroup_interface* cgi) { scap_cgroup_clear_cache(cgi); cgi->m_use_cache = true; } diff --git a/userspace/libscap/linux/scap_cgroup.h b/userspace/libscap/linux/scap_cgroup.h index c2e46e9024..e1e8b65ddc 100644 --- a/userspace/libscap/linux/scap_cgroup.h +++ b/userspace/libscap/linux/scap_cgroup.h @@ -23,51 +23,56 @@ limitations under the License. #include -#define FOR_EACH_SUBSYS(cgset, subsys) for( \ - const char *subsys = (cgset)->path, *_end = (cgset)->path + (cgset)->len; \ - subsys < _end; \ - subsys += strlen(subsys) + 1) +#define FOR_EACH_SUBSYS(cgset, subsys) \ + for(const char *subsys = (cgset)->path, *_end = (cgset)->path + (cgset)->len; subsys < _end; \ + subsys += strlen(subsys) + 1) #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - struct scap_cgroup_cache; - struct scap_threadinfo; - - struct scap_cgroup_interface - { - // cgroup subsystems available for v1 and v2 - struct scap_cgroup_set m_subsystems_v1; - struct scap_cgroup_set m_subsystems_v2; - - // cgroupfs mount points - struct scap_cgroup_set m_mounts_v1; - char m_mount_v2[SCAP_MAX_PATH_SIZE]; - - bool m_use_cache; - struct scap_cgroup_cache* m_cache; - - // the cgroups of the current process, as seen from the host cgroupns - // empty if: - // - we're not running in a cgroupns - // - we can't escape the cgroupns - // - the `scap_cgroup_interface` was created `with_self_cg=false` - struct scap_cgroup_set m_self_v1; - char m_self_v2[SCAP_MAX_PATH_SIZE]; - - bool m_in_cgroupns; - }; +struct scap_cgroup_cache; +struct scap_threadinfo; + +struct scap_cgroup_interface { + // cgroup subsystems available for v1 and v2 + struct scap_cgroup_set m_subsystems_v1; + struct scap_cgroup_set m_subsystems_v2; + + // cgroupfs mount points + struct scap_cgroup_set m_mounts_v1; + char m_mount_v2[SCAP_MAX_PATH_SIZE]; + + bool m_use_cache; + struct scap_cgroup_cache* m_cache; + + // the cgroups of the current process, as seen from the host cgroupns + // empty if: + // - we're not running in a cgroupns + // - we can't escape the cgroupns + // - the `scap_cgroup_interface` was created `with_self_cg=false` + struct scap_cgroup_set m_self_v1; + char m_self_v2[SCAP_MAX_PATH_SIZE]; + + bool m_in_cgroupns; +}; - int32_t scap_cgroup_interface_init(struct scap_cgroup_interface* cgi, const char* host_root, char* error, bool with_self_cg); +int32_t scap_cgroup_interface_init(struct scap_cgroup_interface* cgi, + const char* host_root, + char* error, + bool with_self_cg); - int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, const char* procdirname, struct scap_cgroup_set* cg, char* error); +int32_t scap_cgroup_get_thread(struct scap_cgroup_interface* cgi, + const char* procdirname, + struct scap_cgroup_set* cg, + char* error); - const char* scap_cgroup_get_subsys_mount(const struct scap_cgroup_interface* cgi, const char* subsys, int* version); +const char* scap_cgroup_get_subsys_mount(const struct scap_cgroup_interface* cgi, + const char* subsys, + int* version); - void scap_cgroup_enable_cache(struct scap_cgroup_interface* cgi); +void scap_cgroup_enable_cache(struct scap_cgroup_interface* cgi); - void scap_cgroup_clear_cache(struct scap_cgroup_interface* cgi); +void scap_cgroup_clear_cache(struct scap_cgroup_interface* cgi); #ifdef __cplusplus }; #endif diff --git a/userspace/libscap/linux/scap_fds.c b/userspace/libscap/linux/scap_fds.c index 01cffc0b56..2d7b7aaa69 100644 --- a/userspace/libscap/linux/scap_fds.c +++ b/userspace/libscap/linux/scap_fds.c @@ -48,20 +48,17 @@ limitations under the License. #endif #include #include -//#include -//#include +// #include +// #include #define SOCKET_SCAN_BUFFER_SIZE 1024 * 1024 -void scap_fd_free_ns_sockets_list(struct scap_ns_socket_list **sockets) -{ +void scap_fd_free_ns_sockets_list(struct scap_ns_socket_list **sockets) { struct scap_ns_socket_list *fdi; struct scap_ns_socket_list *tfdi; - if(*sockets) - { - HASH_ITER(hh, *sockets, fdi, tfdi) - { + if(*sockets) { + HASH_ITER(hh, *sockets, fdi, tfdi) { HASH_DEL(*sockets, fdi); scap_fd_free_table(&fdi->sockets); free(fdi); @@ -70,25 +67,25 @@ void scap_fd_free_ns_sockets_list(struct scap_ns_socket_list **sockets) } } -int32_t scap_fd_handle_pipe(struct scap_proclist* proclist, char *fname, scap_threadinfo *tinfo, scap_fdinfo *fdi, char *error) -{ +int32_t scap_fd_handle_pipe(struct scap_proclist *proclist, + char *fname, + scap_threadinfo *tinfo, + scap_fdinfo *fdi, + char *error) { char link_name[SCAP_MAX_PATH_SIZE]; ssize_t r; uint64_t ino; struct stat sb; r = readlink(fname, link_name, SCAP_MAX_PATH_SIZE - 1); - if (r <= 0) - { + if(r <= 0) { return scap_errprintf(error, errno, "Could not read link %s", fname); } link_name[r] = '\0'; - if(1 != sscanf(link_name, "pipe:[%"PRIi64"]", &ino)) - { + if(1 != sscanf(link_name, "pipe:[%" PRIi64 "]", &ino)) { // in this case we've got a named pipe // and we've got to call stat on the link name - if(-1 == stat(link_name, &sb)) - { + if(-1 == stat(link_name, &sb)) { return SCAP_SUCCESS; } ino = sb.st_ino; @@ -96,15 +93,19 @@ int32_t scap_fd_handle_pipe(struct scap_proclist* proclist, char *fname, scap_th strlcpy(fdi->info.fname, link_name, sizeof(fdi->info.fname)); fdi->ino = ino; - proclist->m_proc_callback(proclist->m_proc_callback_context, error, tinfo->tid, tinfo, fdi, NULL); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + tinfo->tid, + tinfo, + fdi, + NULL); return SCAP_SUCCESS; } -static inline uint32_t open_flags_to_scap(unsigned long flags) -{ +static inline uint32_t open_flags_to_scap(unsigned long flags) { uint32_t res = 0; - switch (flags & (O_RDONLY | O_WRONLY | O_RDWR)) { + switch(flags & (O_RDONLY | O_WRONLY | O_RDWR)) { case O_WRONLY: res |= PPM_O_WRONLY; break; @@ -116,57 +117,58 @@ static inline uint32_t open_flags_to_scap(unsigned long flags) break; } - if (flags & O_CREAT) + if(flags & O_CREAT) res |= PPM_O_CREAT; - - if (flags & O_TMPFILE) + + if(flags & O_TMPFILE) res |= PPM_O_TMPFILE; - if (flags & O_APPEND) + if(flags & O_APPEND) res |= PPM_O_APPEND; #ifdef O_DSYNC - if (flags & O_DSYNC) + if(flags & O_DSYNC) res |= PPM_O_DSYNC; #endif - if (flags & O_EXCL) + if(flags & O_EXCL) res |= PPM_O_EXCL; - if (flags & O_NONBLOCK) + if(flags & O_NONBLOCK) res |= PPM_O_NONBLOCK; - if (flags & O_SYNC) + if(flags & O_SYNC) res |= PPM_O_SYNC; - if (flags & O_TRUNC) + if(flags & O_TRUNC) res |= PPM_O_TRUNC; #ifdef O_DIRECT - if (flags & O_DIRECT) + if(flags & O_DIRECT) res |= PPM_O_DIRECT; #endif #ifdef O_DIRECTORY - if (flags & O_DIRECTORY) + if(flags & O_DIRECTORY) res |= PPM_O_DIRECTORY; #endif #ifdef O_LARGEFILE - if (flags & O_LARGEFILE) + if(flags & O_LARGEFILE) res |= PPM_O_LARGEFILE; #endif #ifdef O_CLOEXEC - if (flags & O_CLOEXEC) + if(flags & O_CLOEXEC) res |= PPM_O_CLOEXEC; #endif return res; } -uint32_t scap_linux_get_device_by_mount_id(struct scap_platform *platform, const char *procdir, unsigned long requested_mount_id) -{ +uint32_t scap_linux_get_device_by_mount_id(struct scap_platform *platform, + const char *procdir, + unsigned long requested_mount_id) { char fd_dir_name[SCAP_MAX_PATH_SIZE]; char line[SCAP_MAX_PATH_SIZE]; FILE *finfo; @@ -174,38 +176,31 @@ uint32_t scap_linux_get_device_by_mount_id(struct scap_platform *platform, const struct scap_linux_platform *linux_platform = (struct scap_linux_platform *)platform; HASH_FIND_INT64(linux_platform->m_dev_list, &requested_mount_id, mountinfo); - if(mountinfo != NULL) - { + if(mountinfo != NULL) { return mountinfo->dev; } snprintf(fd_dir_name, SCAP_MAX_PATH_SIZE, "%smountinfo", procdir); finfo = fopen(fd_dir_name, "r"); - if(finfo == NULL) - { + if(finfo == NULL) { return 0; } - while(fgets(line, sizeof(line), finfo) != NULL) - { + while(fgets(line, sizeof(line), finfo) != NULL) { uint32_t mount_id, major, minor; - if(sscanf(line, "%u %*u %u:%u", &mount_id, &major, &minor) != 3) - { + if(sscanf(line, "%u %*u %u:%u", &mount_id, &major, &minor) != 3) { continue; } - if(mount_id == requested_mount_id) - { + if(mount_id == requested_mount_id) { uint32_t dev = makedev(major, minor); mountinfo = malloc(sizeof(*mountinfo)); - if(mountinfo) - { + if(mountinfo) { int32_t uth_status = SCAP_SUCCESS; mountinfo->mount_id = mount_id; mountinfo->dev = dev; HASH_ADD_INT64(linux_platform->m_dev_list, mount_id, mountinfo); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { free(mountinfo); } } @@ -217,23 +212,20 @@ uint32_t scap_linux_get_device_by_mount_id(struct scap_platform *platform, const return 0; } -void scap_fd_flags_file(scap_fdinfo *fdi, const char *procdir) -{ +void scap_fd_flags_file(scap_fdinfo *fdi, const char *procdir) { char fd_dir_name[SCAP_MAX_PATH_SIZE]; char line[SCAP_MAX_PATH_SIZE]; FILE *finfo; snprintf(fd_dir_name, SCAP_MAX_PATH_SIZE, "%sfdinfo/%" PRId64, procdir, fdi->fd); finfo = fopen(fd_dir_name, "r"); - if(finfo == NULL) - { + if(finfo == NULL) { return; } fdi->info.regularinfo.mount_id = 0; fdi->info.regularinfo.dev = 0; - while(fgets(line, sizeof(line), finfo) != NULL) - { + while(fgets(line, sizeof(line), finfo) != NULL) { // We are interested in the flags and the mnt_id. // // The format of the file is: @@ -241,30 +233,23 @@ void scap_fd_flags_file(scap_fdinfo *fdi, const char *procdir) // flags: YYYYYYYY // mnt_id: ZZZ - if(!strncmp(line, "flags:\t", sizeof("flags:\t") - 1)) - { + if(!strncmp(line, "flags:\t", sizeof("flags:\t") - 1)) { uint32_t open_flags; errno = 0; unsigned long flags = strtoul(line + sizeof("flags:\t") - 1, NULL, 8); - if(errno == ERANGE) - { + if(errno == ERANGE) { open_flags = PPM_O_NONE; - } - else - { + } else { open_flags = open_flags_to_scap(flags); } fdi->info.regularinfo.open_flags = open_flags; - } - else if(!strncmp(line, "mnt_id:\t", sizeof("mnt_id:\t") - 1)) - { + } else if(!strncmp(line, "mnt_id:\t", sizeof("mnt_id:\t") - 1)) { errno = 0; unsigned long mount_id = strtoul(line + sizeof("mnt_id:\t") - 1, NULL, 10); - if(errno != ERANGE) - { + if(errno != ERANGE) { fdi->info.regularinfo.mount_id = mount_id; } } @@ -273,113 +258,97 @@ void scap_fd_flags_file(scap_fdinfo *fdi, const char *procdir) fclose(finfo); } -int32_t scap_fd_handle_regular_file(struct scap_proclist *proclist, char *fname, scap_threadinfo *tinfo, scap_fdinfo *fdi, const char *procdir, char *error) -{ +int32_t scap_fd_handle_regular_file(struct scap_proclist *proclist, + char *fname, + scap_threadinfo *tinfo, + scap_fdinfo *fdi, + const char *procdir, + char *error) { char link_name[SCAP_MAX_PATH_SIZE]; ssize_t r; r = readlink(fname, link_name, SCAP_MAX_PATH_SIZE - 1); - if (r <= 0) - { + if(r <= 0) { return SCAP_SUCCESS; } link_name[r] = '\0'; - if(SCAP_FD_UNSUPPORTED == fdi->type) - { + if(SCAP_FD_UNSUPPORTED == fdi->type) { // try to classify by link name - if(0 == strcmp(link_name,"anon_inode:[eventfd]")) - { + if(0 == strcmp(link_name, "anon_inode:[eventfd]")) { fdi->type = SCAP_FD_EVENT; - } - else if(0 == strcmp(link_name,"anon_inode:[signalfd]")) - { + } else if(0 == strcmp(link_name, "anon_inode:[signalfd]")) { fdi->type = SCAP_FD_SIGNALFD; - } - else if(0 == strcmp(link_name,"anon_inode:[eventpoll]")) - { + } else if(0 == strcmp(link_name, "anon_inode:[eventpoll]")) { fdi->type = SCAP_FD_EVENTPOLL; - } - else if(0 == strcmp(link_name,"anon_inode:inotify")) - { + } else if(0 == strcmp(link_name, "anon_inode:inotify")) { fdi->type = SCAP_FD_INOTIFY; - } - else if(0 == strcmp(link_name,"anon_inode:[timerfd]")) - { + } else if(0 == strcmp(link_name, "anon_inode:[timerfd]")) { fdi->type = SCAP_FD_TIMERFD; - } - else if (0 == strcmp(link_name, "anon_inode:[io_uring]")) - { + } else if(0 == strcmp(link_name, "anon_inode:[io_uring]")) { fdi->type = SCAP_FD_IOURING; - } - else if (0 == strcmp(link_name, "anon_inode:[userfaultfd]")) - { + } else if(0 == strcmp(link_name, "anon_inode:[userfaultfd]")) { fdi->type = SCAP_FD_USERFAULTFD; } // anon_inode:bpf-map // anon_inode:bpf_link // anon_inode:bpf-prog // anon_inode:bpf_iter - else if (0 == strncmp(link_name, "anon_inode:[bpf", strlen("anon_inode:[bpf"))) - { + else if(0 == strncmp(link_name, "anon_inode:[bpf", strlen("anon_inode:[bpf"))) { fdi->type = SCAP_FD_BPF; - } - else if (0 == strcmp(link_name, "anon_inode:[pidfd]")) - { + } else if(0 == strcmp(link_name, "anon_inode:[pidfd]")) { fdi->type = SCAP_FD_PIDFD; } - if(SCAP_FD_UNSUPPORTED == fdi->type) - { + if(SCAP_FD_UNSUPPORTED == fdi->type) { // still not able to classify // printf("unsupported %s -> %s\n",fname,link_name); } fdi->info.fname[0] = '\0'; - } - else if(fdi->type == SCAP_FD_FILE_V2) - { - if (0 == strncmp(link_name, "/memfd:", strlen("/memfd:"))) - { + } else if(fdi->type == SCAP_FD_FILE_V2) { + if(0 == strncmp(link_name, "/memfd:", strlen("/memfd:"))) { fdi->type = SCAP_FD_MEMFD; strlcpy(fdi->info.fname, link_name, sizeof(fdi->info.fname)); - } - else - { + } else { scap_fd_flags_file(fdi, procdir); strlcpy(fdi->info.regularinfo.fname, link_name, sizeof(fdi->info.regularinfo.fname)); } - } - else - { + } else { strlcpy(fdi->info.fname, link_name, sizeof(fdi->info.fname)); } - proclist->m_proc_callback(proclist->m_proc_callback_context, error, tinfo->tid, tinfo, fdi, NULL); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + tinfo->tid, + tinfo, + fdi, + NULL); return SCAP_SUCCESS; } -int32_t scap_fd_handle_socket(struct scap_proclist *proclist, char *fname, scap_threadinfo *tinfo, scap_fdinfo *fdi, char* procdir, uint64_t net_ns, struct scap_ns_socket_list **sockets_by_ns, char *error) -{ +int32_t scap_fd_handle_socket(struct scap_proclist *proclist, + char *fname, + scap_threadinfo *tinfo, + scap_fdinfo *fdi, + char *procdir, + uint64_t net_ns, + struct scap_ns_socket_list **sockets_by_ns, + char *error) { char link_name[SCAP_MAX_PATH_SIZE]; ssize_t r; scap_fdinfo *tfdi; uint64_t ino; - struct scap_ns_socket_list* sockets = NULL; + struct scap_ns_socket_list *sockets = NULL; int32_t uth_status = SCAP_SUCCESS; - if(*sockets_by_ns == (void*)-1) - { + if(*sockets_by_ns == (void *)-1) { return SCAP_SUCCESS; - } - else - { + } else { HASH_FIND_INT64(*sockets_by_ns, &net_ns, sockets); - if(sockets == NULL) - { + if(sockets == NULL) { sockets = malloc(sizeof(struct scap_ns_socket_list)); - if(sockets == NULL) - { + if(sockets == NULL) { snprintf(error, SCAP_LASTERR_SIZE, "sockets allocation error"); return SCAP_FAILURE; } @@ -388,15 +357,13 @@ int32_t scap_fd_handle_socket(struct scap_proclist *proclist, char *fname, scap_ char fd_error[SCAP_LASTERR_SIZE]; HASH_ADD_INT64(*sockets_by_ns, net_ns, sockets); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { snprintf(error, SCAP_LASTERR_SIZE, "socket list allocation error"); free(sockets); return SCAP_FAILURE; } - if(scap_fd_read_sockets(procdir, sockets, fd_error) == SCAP_FAILURE) - { + if(scap_fd_read_sockets(procdir, sockets, fd_error) == SCAP_FAILURE) { snprintf(error, SCAP_LASTERR_SIZE, "Cannot read sockets (%s)", fd_error); sockets->sockets = NULL; return SCAP_FAILURE; @@ -405,8 +372,7 @@ int32_t scap_fd_handle_socket(struct scap_proclist *proclist, char *fname, scap_ } r = readlink(fname, link_name, SCAP_MAX_PATH_SIZE - 1); - if(r <= 0) - { + if(r <= 0) { return SCAP_SUCCESS; } @@ -415,11 +381,15 @@ int32_t scap_fd_handle_socket(struct scap_proclist *proclist, char *fname, scap_ strlcpy(fdi->info.fname, link_name, sizeof(fdi->info.fname)); // link name for sockets should be of the format socket:[ino] - if(1 != sscanf(link_name, "socket:[%"PRIi64"]", &ino)) - { + if(1 != sscanf(link_name, "socket:[%" PRIi64 "]", &ino)) { // it's a kind of socket, but we don't support it right now fdi->type = SCAP_FD_UNSUPPORTED; - proclist->m_proc_callback(proclist->m_proc_callback_context, error, tinfo->tid, tinfo, fdi, NULL); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + tinfo->tid, + tinfo, + fdi, + NULL); return SCAP_SUCCESS; } @@ -427,18 +397,23 @@ int32_t scap_fd_handle_socket(struct scap_proclist *proclist, char *fname, scap_ // Lookup ino in the list of sockets // HASH_FIND_INT64(sockets->sockets, &ino, tfdi); - if(tfdi != NULL) - { + if(tfdi != NULL) { memcpy(&(fdi->info), &(tfdi->info), sizeof(fdi->info)); fdi->ino = ino; fdi->type = tfdi->type; - proclist->m_proc_callback(proclist->m_proc_callback_context, error, tinfo->tid, tinfo, fdi, NULL); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + tinfo->tid, + tinfo, + fdi, + NULL); } return SCAP_SUCCESS; } -int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo **sockets, char *error) -{ +int32_t scap_fd_read_unix_sockets_from_proc_fs(const char *filename, + scap_fdinfo **sockets, + char *error) { FILE *f; char line[SCAP_MAX_PATH_SIZE]; int first_line = false; @@ -447,38 +422,32 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo int32_t uth_status = SCAP_SUCCESS; f = fopen(filename, "r"); - if(NULL == f) - { + if(NULL == f) { ASSERT(false); return scap_errprintf(error, errno, "Could not open sockets file %s", filename); } - while(NULL != fgets(line, sizeof(line), f)) - { + while(NULL != fgets(line, sizeof(line), f)) { char *scratch; // skip the first line ... contains field names - if(!first_line) - { + if(!first_line) { first_line = true; continue; } scap_fdinfo *fdinfo = malloc(sizeof(scap_fdinfo)); - if(fdinfo == NULL) - { + if(fdinfo == NULL) { snprintf(error, SCAP_LASTERR_SIZE, "fdinfo allocation error"); fclose(f); return SCAP_FAILURE; } fdinfo->type = SCAP_FD_UNIX_SOCK; - // // parse the fields // // 1. Num token = strtok_r(line, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -489,8 +458,7 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo // 2. RefCount token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -498,8 +466,7 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo // 3. Protocol token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -507,8 +474,7 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo // 4. Flags token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -516,8 +482,7 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo // 5. Type token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -525,8 +490,7 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo // 6. St token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -534,29 +498,26 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo // 7. Inode token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; } - sscanf(token, "%"PRIu64, &(fdinfo->ino)); + sscanf(token, "%" PRIu64, &(fdinfo->ino)); // 8. Path token = strtok_r(NULL, delimiters, &scratch); - if(NULL != token) - { - strlcpy(fdinfo->info.unix_socket_info.fname, token, sizeof(fdinfo->info.unix_socket_info.fname)); - } - else - { + if(NULL != token) { + strlcpy(fdinfo->info.unix_socket_info.fname, + token, + sizeof(fdinfo->info.unix_socket_info.fname)); + } else { fdinfo->info.unix_socket_info.fname[0] = '\0'; } HASH_ADD_INT64((*sockets), ino, fdinfo); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { snprintf(error, SCAP_LASTERR_SIZE, "unix socket allocation error"); fclose(f); free(fdinfo); @@ -567,11 +528,12 @@ int32_t scap_fd_read_unix_sockets_from_proc_fs(const char* filename, scap_fdinfo return uth_status; } -//sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode -//ffff88011abfb000 0 0 00000000 0 0 0 2 0 13 +// sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode +// ffff88011abfb000 0 0 00000000 0 0 0 2 0 13 -int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdinfo **sockets, char *error) -{ +int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char *filename, + scap_fdinfo **sockets, + char *error) { FILE *f; char line[SCAP_MAX_PATH_SIZE]; int first_line = false; @@ -580,23 +542,19 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi int32_t uth_status = SCAP_SUCCESS; f = fopen(filename, "r"); - if(NULL == f) - { + if(NULL == f) { return scap_errprintf(error, errno, "Could not open netlink sockets file %s", filename); } - while(NULL != fgets(line, sizeof(line), f)) - { + while(NULL != fgets(line, sizeof(line), f)) { char *scratch; // skip the first line ... contains field names - if(!first_line) - { + if(!first_line) { first_line = true; continue; } scap_fdinfo *fdinfo = malloc(sizeof(scap_fdinfo)); - if(fdinfo == NULL) - { + if(fdinfo == NULL) { snprintf(error, SCAP_LASTERR_SIZE, "fdinfo allocation error"); fclose(f); return SCAP_FAILURE; @@ -604,14 +562,12 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi memset(fdinfo, 0, sizeof(scap_fdinfo)); fdinfo->type = SCAP_FD_UNIX_SOCK; - // // parse the fields // // 1. Num token = strtok_r(line, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -619,8 +575,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 2. Eth token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -628,8 +583,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 3. Pid token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -637,8 +591,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 4. Groups token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -646,8 +599,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 5. Rmem token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -655,8 +607,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 6. Wmem token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -664,8 +615,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 7. Dump token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -673,8 +623,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 8. Locks token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -682,8 +631,7 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 9. Drops token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; @@ -691,18 +639,16 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi // 10. Inode token = strtok_r(NULL, delimiters, &scratch); - if(token == NULL) - { + if(token == NULL) { ASSERT(false); free(fdinfo); continue; } - sscanf(token, "%"PRIu64, &(fdinfo->ino)); + sscanf(token, "%" PRIu64, &(fdinfo->ino)); HASH_ADD_INT64((*sockets), ino, fdinfo); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { snprintf(error, SCAP_LASTERR_SIZE, "netlink socket allocation error"); fclose(f); free(fdinfo); @@ -713,67 +659,64 @@ int32_t scap_fd_read_netlink_sockets_from_proc_fs(const char* filename, scap_fdi return uth_status; } -int32_t scap_fd_read_ipv4_sockets_from_proc_fs(const char *dir, int l4proto, scap_fdinfo **sockets, char *error) -{ +int32_t scap_fd_read_ipv4_sockets_from_proc_fs(const char *dir, + int l4proto, + scap_fdinfo **sockets, + char *error) { FILE *f; int32_t uth_status = SCAP_SUCCESS; - char* scan_buf; - char* scan_pos; - char* tmp_pos; + char *scan_buf; + char *scan_pos; + char *tmp_pos; uint32_t rsize; - char* end; + char *end; char tc; uint32_t j; - scan_buf = (char*)malloc(SOCKET_SCAN_BUFFER_SIZE); - if(scan_buf == NULL) - { + scan_buf = (char *)malloc(SOCKET_SCAN_BUFFER_SIZE); + if(scan_buf == NULL) { snprintf(error, SCAP_LASTERR_SIZE, "scan_buf allocation error"); return SCAP_FAILURE; } f = fopen(dir, "r"); - if(NULL == f) - { + if(NULL == f) { free(scan_buf); return scap_errprintf(error, errno, "Could not open ipv4 sockets dir %s", dir); } - while((rsize = fread(scan_buf, 1, SOCKET_SCAN_BUFFER_SIZE, f)) != 0) - { - char* scan_end = scan_buf + rsize; + while((rsize = fread(scan_buf, 1, SOCKET_SCAN_BUFFER_SIZE, f)) != 0) { + char *scan_end = scan_buf + rsize; scan_pos = scan_buf; - while(scan_pos <= scan_end) - { + while(scan_pos <= scan_end) { scan_pos = memchr(scan_pos, '\n', scan_end - scan_pos); - if(scan_pos == NULL) - { + if(scan_pos == NULL) { break; } scap_fdinfo *fdinfo = malloc(sizeof(scap_fdinfo)); - if(fdinfo == NULL) - { + if(fdinfo == NULL) { fclose(f); free(scan_buf); - return scap_errprintf(error, errno, "memory allocation error in scap_fd_read_ipv4_sockets_from_proc_fs"); + return scap_errprintf( + error, + errno, + "memory allocation error in scap_fd_read_ipv4_sockets_from_proc_fs"); } // // Skip the sl field // scan_pos = memchr(scan_pos, ':', scan_end - scan_pos); - if(scan_pos == NULL) - { + if(scan_pos == NULL) { free(fdinfo); break; } scan_pos += 2; - if(scan_pos + 80 >= scan_end) - { + if(scan_pos + 80 >= scan_end) { free(fdinfo); break; } @@ -815,37 +758,31 @@ int32_t scap_fd_read_ipv4_sockets_from_proc_fs(const char *dir, int l4proto, sca // scan_pos += 4; - for(j = 0; j < 6; j++) - { + for(j = 0; j < 6; j++) { scan_pos++; scan_pos = memchr(scan_pos, ' ', scan_end - scan_pos); - if(scan_pos == NULL) - { + if(scan_pos == NULL) { break; } - while(*scan_pos == ' ' && scan_pos < scan_end) - { + while(*scan_pos == ' ' && scan_pos < scan_end) { scan_pos++; } - if(scan_pos >= scan_end) - { + if(scan_pos >= scan_end) { break; } } - if(j < 6) - { + if(j < 6) { free(fdinfo); break; } tmp_pos = scan_pos; scan_pos = memchr(scan_pos, ' ', scan_end - scan_pos); - if(scan_pos == NULL || scan_pos >= scan_end) - { + if(scan_pos == NULL || scan_pos >= scan_end) { free(fdinfo); break; } @@ -859,23 +796,19 @@ int32_t scap_fd_read_ipv4_sockets_from_proc_fs(const char *dir, int l4proto, sca // // Add to the table // - if(fdinfo->info.ipv4info.dip == 0) - { + if(fdinfo->info.ipv4info.dip == 0) { fdinfo->type = SCAP_FD_IPV4_SERVSOCK; fdinfo->info.ipv4serverinfo.l4proto = l4proto; fdinfo->info.ipv4serverinfo.port = fdinfo->info.ipv4info.sport; fdinfo->info.ipv4serverinfo.ip = fdinfo->info.ipv4info.sip; - } - else - { + } else { fdinfo->type = SCAP_FD_IPV4_SOCK; fdinfo->info.ipv4info.l4proto = l4proto; } HASH_ADD_INT64((*sockets), ino, fdinfo); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { uth_status = SCAP_FAILURE; snprintf(error, SCAP_LASTERR_SIZE, "ipv4 socket allocation error"); free(fdinfo); @@ -891,73 +824,69 @@ int32_t scap_fd_read_ipv4_sockets_from_proc_fs(const char *dir, int l4proto, sca return uth_status; } -int32_t scap_fd_is_ipv6_server_socket(uint32_t ip6_addr[4]) -{ +int32_t scap_fd_is_ipv6_server_socket(uint32_t ip6_addr[4]) { return 0 == ip6_addr[0] && 0 == ip6_addr[1] && 0 == ip6_addr[2] && 0 == ip6_addr[3]; } -int32_t scap_fd_read_ipv6_sockets_from_proc_fs(char *dir, int l4proto, scap_fdinfo **sockets, char *error) -{ +int32_t scap_fd_read_ipv6_sockets_from_proc_fs(char *dir, + int l4proto, + scap_fdinfo **sockets, + char *error) { FILE *f; int32_t uth_status = SCAP_SUCCESS; - char* scan_buf; - char* scan_pos; - char* tmp_pos; + char *scan_buf; + char *scan_pos; + char *tmp_pos; uint32_t rsize; - char* end; + char *end; char tc; uint32_t j; - scan_buf = (char*)malloc(SOCKET_SCAN_BUFFER_SIZE); - if(scan_buf == NULL) - { + scan_buf = (char *)malloc(SOCKET_SCAN_BUFFER_SIZE); + if(scan_buf == NULL) { snprintf(error, SCAP_LASTERR_SIZE, "scan_buf allocation error"); return SCAP_FAILURE; } f = fopen(dir, "r"); - if(NULL == f) - { + if(NULL == f) { free(scan_buf); return scap_errprintf(error, errno, "Could not open ipv6 sockets dir %s", dir); } - while((rsize = fread(scan_buf, 1, SOCKET_SCAN_BUFFER_SIZE, f)) != 0) - { - char* scan_end = scan_buf + rsize; + while((rsize = fread(scan_buf, 1, SOCKET_SCAN_BUFFER_SIZE, f)) != 0) { + char *scan_end = scan_buf + rsize; scan_pos = scan_buf; - while(scan_pos <= scan_end) - { + while(scan_pos <= scan_end) { scan_pos = memchr(scan_pos, '\n', scan_end - scan_pos); - if(scan_pos == NULL) - { + if(scan_pos == NULL) { break; } scap_fdinfo *fdinfo = malloc(sizeof(scap_fdinfo)); - if(fdinfo == NULL) - { + if(fdinfo == NULL) { fclose(f); free(scan_buf); - return scap_errprintf(error, errno, "memory allocation error in scap_fd_read_ipv6_sockets_from_proc_fs"); + return scap_errprintf( + error, + errno, + "memory allocation error in scap_fd_read_ipv6_sockets_from_proc_fs"); } // // Skip the sl field // scan_pos = memchr(scan_pos, ':', scan_end - scan_pos); - if(scan_pos == NULL) - { + if(scan_pos == NULL) { free(fdinfo); break; } scan_pos += 2; - if(scan_pos + 80 >= scan_end) - { + if(scan_pos + 80 >= scan_end) { free(fdinfo); break; } @@ -1037,37 +966,31 @@ int32_t scap_fd_read_ipv6_sockets_from_proc_fs(char *dir, int l4proto, scap_fdin // scan_pos += 4; - for(j = 0; j < 6; j++) - { + for(j = 0; j < 6; j++) { scan_pos++; scan_pos = memchr(scan_pos, ' ', scan_end - scan_pos); - if(scan_pos == NULL) - { + if(scan_pos == NULL) { break; } - while(*scan_pos == ' ' && scan_pos < scan_end) - { + while(*scan_pos == ' ' && scan_pos < scan_end) { scan_pos++; } - if(scan_pos >= scan_end) - { + if(scan_pos >= scan_end) { break; } } - if(j < 6) - { + if(j < 6) { free(fdinfo); break; } tmp_pos = scan_pos; scan_pos = memchr(scan_pos, ' ', scan_end - scan_pos); - if(scan_pos == NULL || scan_pos >= scan_end) - { + if(scan_pos == NULL || scan_pos >= scan_end) { free(fdinfo); break; } @@ -1081,8 +1004,7 @@ int32_t scap_fd_read_ipv6_sockets_from_proc_fs(char *dir, int l4proto, scap_fdin // // Add to the table // - if(scap_fd_is_ipv6_server_socket(fdinfo->info.ipv6info.dip)) - { + if(scap_fd_is_ipv6_server_socket(fdinfo->info.ipv6info.dip)) { fdinfo->type = SCAP_FD_IPV6_SERVSOCK; fdinfo->info.ipv6serverinfo.l4proto = l4proto; fdinfo->info.ipv6serverinfo.port = fdinfo->info.ipv6info.sport; @@ -1090,17 +1012,14 @@ int32_t scap_fd_read_ipv6_sockets_from_proc_fs(char *dir, int l4proto, scap_fdin fdinfo->info.ipv6serverinfo.ip[1] = fdinfo->info.ipv6info.sip[1]; fdinfo->info.ipv6serverinfo.ip[2] = fdinfo->info.ipv6info.sip[2]; fdinfo->info.ipv6serverinfo.ip[3] = fdinfo->info.ipv6info.sip[3]; - } - else - { + } else { fdinfo->type = SCAP_FD_IPV6_SOCK; fdinfo->info.ipv6info.l4proto = l4proto; } HASH_ADD_INT64((*sockets), ino, fdinfo); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { uth_status = SCAP_FAILURE; snprintf(error, SCAP_LASTERR_SIZE, "ipv6 socket allocation error"); break; @@ -1116,21 +1035,17 @@ int32_t scap_fd_read_ipv6_sockets_from_proc_fs(char *dir, int l4proto, scap_fdin return uth_status; } -int32_t scap_fd_read_sockets(char* procdir, struct scap_ns_socket_list *sockets, char *error) -{ +int32_t scap_fd_read_sockets(char *procdir, struct scap_ns_socket_list *sockets, char *error) { char filename[SCAP_MAX_PATH_SIZE]; char netroot[SCAP_MAX_PATH_SIZE]; char err_buf[SCAP_LASTERR_SIZE]; - if(sockets->net_ns) - { + if(sockets->net_ns) { // // Namespace support, look in /proc/PID/net/ // snprintf(netroot, sizeof(netroot), "%snet/", procdir); - } - else - { + } else { // // No namespace support, look in the base /proc // @@ -1138,111 +1053,119 @@ int32_t scap_fd_read_sockets(char* procdir, struct scap_ns_socket_list *sockets, } snprintf(filename, sizeof(filename), "%stcp", netroot); - if(scap_fd_read_ipv4_sockets_from_proc_fs(filename, SCAP_L4_TCP, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + if(scap_fd_read_ipv4_sockets_from_proc_fs(filename, SCAP_L4_TCP, &sockets->sockets, err_buf) == + SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read ipv4 tcp sockets (%s)", err_buf); return SCAP_FAILURE; } snprintf(filename, sizeof(filename), "%sudp", netroot); - if(scap_fd_read_ipv4_sockets_from_proc_fs(filename, SCAP_L4_UDP, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + if(scap_fd_read_ipv4_sockets_from_proc_fs(filename, SCAP_L4_UDP, &sockets->sockets, err_buf) == + SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read ipv4 udp sockets (%s)", err_buf); return SCAP_FAILURE; } snprintf(filename, sizeof(filename), "%sraw", netroot); - if(scap_fd_read_ipv4_sockets_from_proc_fs(filename, SCAP_L4_RAW, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + if(scap_fd_read_ipv4_sockets_from_proc_fs(filename, SCAP_L4_RAW, &sockets->sockets, err_buf) == + SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read ipv4 raw sockets (%s)", err_buf); return SCAP_FAILURE; } snprintf(filename, sizeof(filename), "%sunix", netroot); - if(scap_fd_read_unix_sockets_from_proc_fs(filename, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + if(scap_fd_read_unix_sockets_from_proc_fs(filename, &sockets->sockets, err_buf) == + SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read unix sockets (%s)", err_buf); return SCAP_FAILURE; } snprintf(filename, sizeof(filename), "%snetlink", netroot); - if(scap_fd_read_netlink_sockets_from_proc_fs(filename, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + if(scap_fd_read_netlink_sockets_from_proc_fs(filename, &sockets->sockets, err_buf) == + SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read netlink sockets (%s)", err_buf); return SCAP_FAILURE; } snprintf(filename, sizeof(filename), "%stcp6", netroot); - /* We assume if there is /proc/net/tcp6 that ipv6 is available */ - if(access(filename, R_OK) == 0) - { - if(scap_fd_read_ipv6_sockets_from_proc_fs(filename, SCAP_L4_TCP, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + /* We assume if there is /proc/net/tcp6 that ipv6 is available */ + if(access(filename, R_OK) == 0) { + if(scap_fd_read_ipv6_sockets_from_proc_fs(filename, + SCAP_L4_TCP, + &sockets->sockets, + err_buf) == SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read ipv6 tcp sockets (%s)", err_buf); return SCAP_FAILURE; } snprintf(filename, sizeof(filename), "%sudp6", netroot); - if(scap_fd_read_ipv6_sockets_from_proc_fs(filename, SCAP_L4_UDP, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + if(scap_fd_read_ipv6_sockets_from_proc_fs(filename, + SCAP_L4_UDP, + &sockets->sockets, + err_buf) == SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read ipv6 udp sockets (%s)", err_buf); return SCAP_FAILURE; } snprintf(filename, sizeof(filename), "%sraw6", netroot); - if(scap_fd_read_ipv6_sockets_from_proc_fs(filename, SCAP_L4_RAW, &sockets->sockets, err_buf) == SCAP_FAILURE) - { + if(scap_fd_read_ipv6_sockets_from_proc_fs(filename, + SCAP_L4_RAW, + &sockets->sockets, + err_buf) == SCAP_FAILURE) { scap_fd_free_table(&sockets->sockets); snprintf(error, SCAP_LASTERR_SIZE, "Could not read ipv6 raw sockets (%s)", err_buf); return SCAP_FAILURE; } - } + } return SCAP_SUCCESS; } - -char * decode_st_mode(struct stat* sb) -{ +char *decode_st_mode(struct stat *sb) { switch(sb->st_mode & S_IFMT) { - case S_IFBLK: - return "block device"; - break; - case S_IFCHR: - return "character device"; - break; - case S_IFDIR: - return "directory"; - break; - case S_IFIFO: - return "FIFO/pipe"; - break; - case S_IFLNK: - return "symlink"; - break; - case S_IFREG: - return "regular file"; - break; - case S_IFSOCK: - return "socket"; - break; - default: - return "unknown?"; - break; - } + case S_IFBLK: + return "block device"; + break; + case S_IFCHR: + return "character device"; + break; + case S_IFDIR: + return "directory"; + break; + case S_IFIFO: + return "FIFO/pipe"; + break; + case S_IFLNK: + return "symlink"; + break; + case S_IFREG: + return "regular file"; + break; + case S_IFSOCK: + return "socket"; + break; + default: + return "unknown?"; + break; + } } // // Scan the directory containing the fd's of a proc /proc/x/fd // -int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, struct scap_proclist *proclist, char *procdir, scap_threadinfo *tinfo, struct scap_ns_socket_list **sockets_by_ns, uint64_t* num_fds_ret, char *error) -{ +int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, + struct scap_proclist *proclist, + char *procdir, + scap_threadinfo *tinfo, + struct scap_ns_socket_list **sockets_by_ns, + uint64_t *num_fds_ret, + char *error) { DIR *dir_p; struct dirent *dir_entry_p; int32_t res = SCAP_SUCCESS; @@ -1256,15 +1179,13 @@ int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, struct s ssize_t r; uint32_t fd_added = 0; - if (num_fds_ret != NULL) - { + if(num_fds_ret != NULL) { *num_fds_ret = 0; } snprintf(fd_dir_name, SCAP_MAX_PATH_SIZE, "%sfd", procdir); dir_p = opendir(fd_dir_name); - if(dir_p == NULL) - { + if(dir_p == NULL) { snprintf(error, SCAP_LASTERR_SIZE, "error opening the directory %s", fd_dir_name); return SCAP_NOTFOUND; } @@ -1274,39 +1195,33 @@ int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, struct s // snprintf(f_name, sizeof(f_name), "%sns/net", procdir); r = readlink(f_name, link_name, sizeof(link_name) - 1); - if(r <= 0) - { + if(r <= 0) { // // No network namespace available. Assume global // net_ns = 0; - } - else - { + } else { link_name[r] = '\0'; - sscanf(link_name, "net:[%"PRIi64"]", &net_ns); + sscanf(link_name, "net:[%" PRIi64 "]", &net_ns); } while((dir_entry_p = readdir(dir_p)) != NULL && - (linux_platform->m_fd_lookup_limit == 0 || fd_added < linux_platform->m_fd_lookup_limit)) - { + (linux_platform->m_fd_lookup_limit == 0 || + fd_added < linux_platform->m_fd_lookup_limit)) { snprintf(f_name, SCAP_MAX_PATH_SIZE, "%s/%s", fd_dir_name, dir_entry_p->d_name); - if(-1 == stat(f_name, &sb) || 1 != sscanf(dir_entry_p->d_name, "%"PRIu64, &fd)) - { + if(-1 == stat(f_name, &sb) || 1 != sscanf(dir_entry_p->d_name, "%" PRIu64, &fd)) { continue; } fdi.fd = fd; // In no driver mode to limit cpu usage we just parse sockets // because we are interested only on them - if(linux_platform->m_minimal_scan && !S_ISSOCK(sb.st_mode)) - { + if(linux_platform->m_minimal_scan && !S_ISSOCK(sb.st_mode)) { continue; } - switch(sb.st_mode & S_IFMT) - { + switch(sb.st_mode & S_IFMT) { case S_IFIFO: fdi.type = SCAP_FD_FIFO; res = scap_fd_handle_pipe(proclist, f_name, tinfo, &fdi, error); @@ -1326,7 +1241,14 @@ int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, struct s break; case S_IFSOCK: fdi.type = SCAP_FD_UNKNOWN; - res = scap_fd_handle_socket(proclist, f_name, tinfo, &fdi, procdir, net_ns, sockets_by_ns, error); + res = scap_fd_handle_socket(proclist, + f_name, + tinfo, + &fdi, + procdir, + net_ns, + sockets_by_ns, + error); break; default: fdi.type = SCAP_FD_UNSUPPORTED; @@ -1335,8 +1257,7 @@ int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, struct s break; } - if(SCAP_SUCCESS != res) - { + if(SCAP_SUCCESS != res) { break; } else { ++fd_added; @@ -1344,8 +1265,7 @@ int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, struct s } closedir(dir_p); - if (num_fds_ret != NULL) - { + if(num_fds_ret != NULL) { *num_fds_ret = fd_added; } diff --git a/userspace/libscap/linux/scap_iflist.c b/userspace/libscap/linux/scap_iflist.c index 4916120b4c..26c103fa7e 100644 --- a/userspace/libscap/linux/scap_iflist.c +++ b/userspace/libscap/linux/scap_iflist.c @@ -34,50 +34,42 @@ limitations under the License. // // Allocate and return the list of interfaces on this system // -int32_t scap_linux_create_iflist(struct scap_platform* platform) -{ - struct scap_linux_platform* handle = (struct scap_linux_platform*)platform; +int32_t scap_linux_create_iflist(struct scap_platform *platform) { + struct scap_linux_platform *handle = (struct scap_linux_platform *)platform; struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL; void *tempAddrPtr = NULL; int rc = 0; uint32_t ifcnt4 = 0; uint32_t ifcnt6 = 0; - scap_addrlist* addrlist; + scap_addrlist *addrlist; // // If the list of interfaces was already allocated for this handle (for example because this is // not the first interface list block), free it // - if(platform->m_addrlist != NULL) - { + if(platform->m_addrlist != NULL) { scap_free_iflist(platform->m_addrlist); platform->m_addrlist = NULL; } - rc = getifaddrs(&interfaceArray); /* retrieve the current interfaces */ - if(rc != 0) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs failed"); + rc = getifaddrs(&interfaceArray); /* retrieve the current interfaces */ + if(rc != 0) { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs failed"); return SCAP_FAILURE; } // // First pass: count the number of interfaces // - for(tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) - { - if(tempIfAddr->ifa_addr == NULL) - { + for(tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) { + if(tempIfAddr->ifa_addr == NULL) { // "eql" interface like on EC2 continue; } - - if(tempIfAddr->ifa_addr->sa_family == AF_INET) - { + + if(tempIfAddr->ifa_addr->sa_family == AF_INET) { ifcnt4++; - } - else if(tempIfAddr->ifa_addr->sa_family == AF_INET6) - { + } else if(tempIfAddr->ifa_addr->sa_family == AF_INET6) { ifcnt6++; } } @@ -85,45 +77,35 @@ int32_t scap_linux_create_iflist(struct scap_platform* platform) // // Allocate the handle and the arrays // - platform->m_addrlist = (scap_addrlist*)malloc(sizeof(scap_addrlist)); - if(!platform->m_addrlist) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(1)"); + platform->m_addrlist = (scap_addrlist *)malloc(sizeof(scap_addrlist)); + if(!platform->m_addrlist) { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(1)"); return SCAP_FAILURE; } addrlist = platform->m_addrlist; - if(ifcnt4 != 0) - { - addrlist->v4list = (scap_ifinfo_ipv4*)malloc(ifcnt4 * sizeof(scap_ifinfo_ipv4)); - if(!addrlist->v4list) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(2)"); + if(ifcnt4 != 0) { + addrlist->v4list = (scap_ifinfo_ipv4 *)malloc(ifcnt4 * sizeof(scap_ifinfo_ipv4)); + if(!addrlist->v4list) { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(2)"); free(addrlist); return SCAP_FAILURE; } - } - else - { + } else { addrlist->v4list = NULL; } - if(ifcnt6 != 0) - { - addrlist->v6list = (scap_ifinfo_ipv6*)malloc(ifcnt6 * sizeof(scap_ifinfo_ipv6)); - if(!addrlist->v6list) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(3)"); - if(addrlist->v4list) - { + if(ifcnt6 != 0) { + addrlist->v6list = (scap_ifinfo_ipv6 *)malloc(ifcnt6 * sizeof(scap_ifinfo_ipv6)); + if(!addrlist->v6list) { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "getifaddrs allocation failed(3)"); + if(addrlist->v4list) { free(addrlist->v4list); } free(addrlist); return SCAP_FAILURE; } - } - else - { + } else { addrlist->v6list = NULL; } @@ -137,86 +119,75 @@ int32_t scap_linux_create_iflist(struct scap_platform* platform) ifcnt4 = 0; ifcnt6 = 0; - for(tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) - { - if(tempIfAddr->ifa_addr == NULL) - { + for(tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) { + if(tempIfAddr->ifa_addr == NULL) { // "eql" interface like on EC2 continue; } - if(tempIfAddr->ifa_addr->sa_family == AF_INET) - { + if(tempIfAddr->ifa_addr->sa_family == AF_INET) { addrlist->v4list[ifcnt4].type = SCAP_II_IPV4; tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr; - addrlist->v4list[ifcnt4].addr = *(uint32_t*)tempAddrPtr; + addrlist->v4list[ifcnt4].addr = *(uint32_t *)tempAddrPtr; - if(tempIfAddr->ifa_netmask != NULL) - { - addrlist->v4list[ifcnt4].netmask = *(uint32_t*)&(((struct sockaddr_in *)tempIfAddr->ifa_netmask)->sin_addr); - } - else - { + if(tempIfAddr->ifa_netmask != NULL) { + addrlist->v4list[ifcnt4].netmask = + *(uint32_t *)&(((struct sockaddr_in *)tempIfAddr->ifa_netmask)->sin_addr); + } else { addrlist->v4list[ifcnt4].netmask = 0; } - if(tempIfAddr->ifa_ifu.ifu_broadaddr != NULL) - { - addrlist->v4list[ifcnt4].bcast = *(uint32_t*)&(((struct sockaddr_in *)tempIfAddr->ifa_ifu.ifu_broadaddr)->sin_addr); - } - else - { + if(tempIfAddr->ifa_ifu.ifu_broadaddr != NULL) { + addrlist->v4list[ifcnt4].bcast = *(uint32_t *)&( + ((struct sockaddr_in *)tempIfAddr->ifa_ifu.ifu_broadaddr)->sin_addr); + } else { addrlist->v4list[ifcnt4].bcast = 0; } - strlcpy(addrlist->v4list[ifcnt4].ifname, tempIfAddr->ifa_name, sizeof(addrlist->v4list[ifcnt4].ifname)); + strlcpy(addrlist->v4list[ifcnt4].ifname, + tempIfAddr->ifa_name, + sizeof(addrlist->v4list[ifcnt4].ifname)); addrlist->v4list[ifcnt4].ifnamelen = strlen(tempIfAddr->ifa_name); addrlist->v4list[ifcnt4].linkspeed = 0; - addrlist->totlen += (sizeof(scap_ifinfo_ipv4) + addrlist->v4list[ifcnt4].ifnamelen - SCAP_MAX_PATH_SIZE); + addrlist->totlen += (sizeof(scap_ifinfo_ipv4) + addrlist->v4list[ifcnt4].ifnamelen - + SCAP_MAX_PATH_SIZE); ifcnt4++; - } - else if(tempIfAddr->ifa_addr->sa_family == AF_INET6) - { + } else if(tempIfAddr->ifa_addr->sa_family == AF_INET6) { addrlist->v6list[ifcnt6].type = SCAP_II_IPV6; tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr; memcpy(addrlist->v6list[ifcnt6].addr, tempAddrPtr, 16); - if(tempIfAddr->ifa_netmask != NULL) - { + if(tempIfAddr->ifa_netmask != NULL) { memcpy(addrlist->v6list[ifcnt6].netmask, - &(((struct sockaddr_in6 *)tempIfAddr->ifa_netmask)->sin6_addr), - 16); - } - else - { + &(((struct sockaddr_in6 *)tempIfAddr->ifa_netmask)->sin6_addr), + 16); + } else { memset(addrlist->v6list[ifcnt6].netmask, 0, 16); } - if(tempIfAddr->ifa_ifu.ifu_broadaddr != NULL) - { + if(tempIfAddr->ifa_ifu.ifu_broadaddr != NULL) { memcpy(addrlist->v6list[ifcnt6].bcast, - &(((struct sockaddr_in6 *)tempIfAddr->ifa_ifu.ifu_broadaddr)->sin6_addr), - 16); - } - else - { + &(((struct sockaddr_in6 *)tempIfAddr->ifa_ifu.ifu_broadaddr)->sin6_addr), + 16); + } else { memset(addrlist->v6list[ifcnt6].bcast, 0, 16); } - strlcpy(addrlist->v6list[ifcnt6].ifname, tempIfAddr->ifa_name, sizeof(addrlist->v6list[ifcnt6].ifname)); + strlcpy(addrlist->v6list[ifcnt6].ifname, + tempIfAddr->ifa_name, + sizeof(addrlist->v6list[ifcnt6].ifname)); addrlist->v6list[ifcnt6].ifnamelen = strlen(tempIfAddr->ifa_name); addrlist->v6list[ifcnt6].linkspeed = 0; - addrlist->totlen += (sizeof(scap_ifinfo_ipv6) + addrlist->v6list[ifcnt6].ifnamelen - SCAP_MAX_PATH_SIZE); + addrlist->totlen += (sizeof(scap_ifinfo_ipv6) + addrlist->v6list[ifcnt6].ifnamelen - + SCAP_MAX_PATH_SIZE); ifcnt6++; - } - else - { + } else { continue; } } diff --git a/userspace/libscap/linux/scap_linux_hostinfo_platform.c b/userspace/libscap/linux/scap_linux_hostinfo_platform.c index 258d591919..1be05cda9a 100644 --- a/userspace/libscap/linux/scap_linux_hostinfo_platform.c +++ b/userspace/libscap/linux/scap_linux_hostinfo_platform.c @@ -25,25 +25,24 @@ limitations under the License. #include #include -static void scap_linux_hostinfo_free_platform(struct scap_platform* platform) -{ +static void scap_linux_hostinfo_free_platform(struct scap_platform* platform) { free(platform); } -int32_t scap_linux_hostinfo_init_platform(struct scap_platform* platform, char* lasterr, struct scap_engine_handle engine, struct scap_open_args* oargs) -{ +int32_t scap_linux_hostinfo_init_platform(struct scap_platform* platform, + char* lasterr, + struct scap_engine_handle engine, + struct scap_open_args* oargs) { int rc; - if(scap_os_get_machine_info(&platform->m_machine_info, lasterr) != SCAP_SUCCESS) - { + if(scap_os_get_machine_info(&platform->m_machine_info, lasterr) != SCAP_SUCCESS) { return SCAP_FAILURE; } scap_os_get_agent_info(&platform->m_agent_info); rc = scap_linux_create_iflist(platform); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { scap_linux_hostinfo_free_platform(platform); return rc; } @@ -52,17 +51,15 @@ int32_t scap_linux_hostinfo_init_platform(struct scap_platform* platform, char* } static const struct scap_platform_vtable scap_linux_hostinfo_platform_vtable = { - .init_platform = scap_linux_hostinfo_init_platform, - .refresh_addr_list = scap_linux_create_iflist, - .free_platform = scap_linux_hostinfo_free_platform, + .init_platform = scap_linux_hostinfo_init_platform, + .refresh_addr_list = scap_linux_create_iflist, + .free_platform = scap_linux_hostinfo_free_platform, }; -struct scap_platform* scap_linux_hostinfo_alloc_platform() -{ +struct scap_platform* scap_linux_hostinfo_alloc_platform() { struct scap_linux_platform* platform = calloc(1, sizeof(*platform)); - if(platform == NULL) - { + if(platform == NULL) { return NULL; } diff --git a/userspace/libscap/linux/scap_linux_int.h b/userspace/libscap/linux/scap_linux_int.h index f67104468f..d0fe2897d3 100644 --- a/userspace/libscap/linux/scap_linux_int.h +++ b/userspace/libscap/linux/scap_linux_int.h @@ -25,8 +25,7 @@ limitations under the License. typedef struct scap_fdinfo scap_fdinfo; -struct scap_ns_socket_list -{ +struct scap_ns_socket_list { int64_t net_ns; scap_fdinfo* sockets; UT_hash_handle hh; @@ -46,17 +45,35 @@ int32_t scap_os_get_machine_info(scap_machine_info* machine_info, char* lasterr) int32_t scap_linux_create_iflist(struct scap_platform* platform); int32_t scap_linux_create_userlist(struct scap_platform* platform); -uint32_t scap_linux_get_device_by_mount_id(struct scap_platform* platform, const char *procdir, unsigned long requested_mount_id); -int32_t scap_linux_proc_get(struct scap_platform* platform, int64_t tid, - struct scap_threadinfo* tinfo, bool scan_sockets); -int32_t scap_linux_refresh_proc_table(struct scap_platform* platform, struct scap_proclist* proclist); -bool scap_linux_is_thread_alive(struct scap_platform* platform, int64_t pid, int64_t tid, const char* comm); -int32_t scap_linux_getpid_global(struct scap_platform* platform, int64_t *pid, char* error); -int32_t scap_linux_get_threadlist(struct scap_platform* platform, struct ppm_proclist_info **procinfo_p, char *lasterr); -int32_t scap_linux_get_fdlist(struct scap_platform* platform, struct scap_threadinfo *tinfo, char *lasterr); +uint32_t scap_linux_get_device_by_mount_id(struct scap_platform* platform, + const char* procdir, + unsigned long requested_mount_id); +int32_t scap_linux_proc_get(struct scap_platform* platform, + int64_t tid, + struct scap_threadinfo* tinfo, + bool scan_sockets); +int32_t scap_linux_refresh_proc_table(struct scap_platform* platform, + struct scap_proclist* proclist); +bool scap_linux_is_thread_alive(struct scap_platform* platform, + int64_t pid, + int64_t tid, + const char* comm); +int32_t scap_linux_getpid_global(struct scap_platform* platform, int64_t* pid, char* error); +int32_t scap_linux_get_threadlist(struct scap_platform* platform, + struct ppm_proclist_info** procinfo_p, + char* lasterr); +int32_t scap_linux_get_fdlist(struct scap_platform* platform, + struct scap_threadinfo* tinfo, + char* lasterr); // read all sockets and add them to the socket table hashed by their ino -int32_t scap_fd_read_sockets(char* procdir, struct scap_ns_socket_list* sockets, char *error); +int32_t scap_fd_read_sockets(char* procdir, struct scap_ns_socket_list* sockets, char* error); void scap_fd_free_ns_sockets_list(struct scap_ns_socket_list** sockets); // read the file descriptors for a given process directory -int32_t scap_fd_scan_fd_dir(struct scap_linux_platform *linux_platform, struct scap_proclist *proclist, char * procdir, scap_threadinfo* pi, struct scap_ns_socket_list** sockets_by_ns, uint64_t* num_fds_ret, char *error); +int32_t scap_fd_scan_fd_dir(struct scap_linux_platform* linux_platform, + struct scap_proclist* proclist, + char* procdir, + scap_threadinfo* pi, + struct scap_ns_socket_list** sockets_by_ns, + uint64_t* num_fds_ret, + char* error); diff --git a/userspace/libscap/linux/scap_linux_platform.c b/userspace/libscap/linux/scap_linux_platform.c index 80b70ae734..aeff697197 100644 --- a/userspace/libscap/linux/scap_linux_platform.c +++ b/userspace/libscap/linux/scap_linux_platform.c @@ -32,13 +32,11 @@ limitations under the License. #include #include -static int32_t scap_linux_close_platform(struct scap_platform* platform) -{ +static int32_t scap_linux_close_platform(struct scap_platform* platform) { struct scap_linux_platform* linux_platform = (struct scap_linux_platform*)platform; // Free the device table - if(linux_platform->m_dev_list != NULL) - { + if(linux_platform->m_dev_list != NULL) { scap_free_device_table(linux_platform->m_dev_list); linux_platform->m_dev_list = NULL; } @@ -48,13 +46,14 @@ static int32_t scap_linux_close_platform(struct scap_platform* platform) return SCAP_SUCCESS; } -static void scap_linux_free_platform(struct scap_platform* platform) -{ +static void scap_linux_free_platform(struct scap_platform* platform) { free(platform); } -int32_t scap_linux_init_platform(struct scap_platform* platform, char* lasterr, struct scap_engine_handle engine, struct scap_open_args* oargs) -{ +int32_t scap_linux_init_platform(struct scap_platform* platform, + char* lasterr, + struct scap_engine_handle engine, + struct scap_open_args* oargs) { int rc; struct scap_linux_platform* linux_platform = (struct scap_linux_platform*)platform; linux_platform->m_lasterr = lasterr; @@ -63,33 +62,31 @@ int32_t scap_linux_init_platform(struct scap_platform* platform, char* lasterr, linux_platform->m_proc_scan_log_interval_ms = oargs->proc_scan_log_interval_ms; linux_platform->m_log_fn = oargs->log_fn; - if(scap_os_get_machine_info(&platform->m_machine_info, lasterr) != SCAP_SUCCESS) - { + if(scap_os_get_machine_info(&platform->m_machine_info, lasterr) != SCAP_SUCCESS) { return SCAP_FAILURE; } scap_os_get_agent_info(&platform->m_agent_info); rc = scap_linux_create_iflist(platform); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { scap_linux_free_platform(platform); return rc; } - if(oargs->import_users) - { + if(oargs->import_users) { rc = scap_linux_create_userlist(platform); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { scap_linux_free_platform(platform); return rc; } } - rc = scap_cgroup_interface_init(&linux_platform->m_cgroups, scap_get_host_root(), lasterr, true); - if(rc != SCAP_SUCCESS) - { + rc = scap_cgroup_interface_init(&linux_platform->m_cgroups, + scap_get_host_root(), + lasterr, + true); + if(rc != SCAP_SUCCESS) { scap_linux_free_platform(platform); return rc; } @@ -97,9 +94,12 @@ int32_t scap_linux_init_platform(struct scap_platform* platform, char* lasterr, linux_platform->m_lasterr[0] = '\0'; char proc_scan_err[SCAP_LASTERR_SIZE]; rc = scap_linux_refresh_proc_table(platform, &platform->m_proclist); - if(rc != SCAP_SUCCESS) - { - snprintf(linux_platform->m_lasterr, SCAP_LASTERR_SIZE, "scap_open_live_int() error creating the process list: %s. Make sure you have root credentials.", proc_scan_err); + if(rc != SCAP_SUCCESS) { + snprintf(linux_platform->m_lasterr, + SCAP_LASTERR_SIZE, + "scap_open_live_int() error creating the process list: %s. Make sure you have " + "root credentials.", + proc_scan_err); scap_linux_free_platform(platform); return rc; } @@ -108,25 +108,24 @@ int32_t scap_linux_init_platform(struct scap_platform* platform, char* lasterr, } static const struct scap_platform_vtable scap_linux_platform_vtable = { - .init_platform = scap_linux_init_platform, - .refresh_addr_list = scap_linux_create_iflist, - .get_device_by_mount_id = scap_linux_get_device_by_mount_id, - .get_proc = scap_linux_proc_get, - .refresh_proc_table = scap_linux_refresh_proc_table, - .is_thread_alive = scap_linux_is_thread_alive, - .get_global_pid = scap_linux_getpid_global, - .get_threadlist = scap_linux_get_threadlist, - .get_fdlist = scap_linux_get_fdlist, - .close_platform = scap_linux_close_platform, - .free_platform = scap_linux_free_platform, + .init_platform = scap_linux_init_platform, + .refresh_addr_list = scap_linux_create_iflist, + .get_device_by_mount_id = scap_linux_get_device_by_mount_id, + .get_proc = scap_linux_proc_get, + .refresh_proc_table = scap_linux_refresh_proc_table, + .is_thread_alive = scap_linux_is_thread_alive, + .get_global_pid = scap_linux_getpid_global, + .get_threadlist = scap_linux_get_threadlist, + .get_fdlist = scap_linux_get_fdlist, + .close_platform = scap_linux_close_platform, + .free_platform = scap_linux_free_platform, }; -struct scap_platform* scap_linux_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context) -{ +struct scap_platform* scap_linux_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context) { struct scap_linux_platform* platform = calloc(1, sizeof(*platform)); - if(platform == NULL) - { + if(platform == NULL) { return NULL; } diff --git a/userspace/libscap/linux/scap_linux_platform.h b/userspace/libscap/linux/scap_linux_platform.h index c0bc92eb16..1982649bb7 100644 --- a/userspace/libscap/linux/scap_linux_platform.h +++ b/userspace/libscap/linux/scap_linux_platform.h @@ -27,7 +27,7 @@ extern "C" { #include #include - struct scap_mountinfo; +struct scap_mountinfo; struct scap_linux_vtable { /** @@ -40,7 +40,7 @@ struct scap_linux_vtable { * `vpid` is the pid as seen by the process itself, i.e. within its * PID namespace */ - int32_t (*get_vpid)(struct scap_engine_handle engine, uint64_t pid, int64_t *vpid); + int32_t (*get_vpid)(struct scap_engine_handle engine, uint64_t pid, int64_t* vpid); /** * @brief get the vtid of a process @@ -52,7 +52,7 @@ struct scap_linux_vtable { * `vtid` is the tid as seen by the process itself, i.e. within its * PID namespace */ - int32_t (*get_vtid)(struct scap_engine_handle engine, uint64_t tid, int64_t *vtid); + int32_t (*get_vtid)(struct scap_engine_handle engine, uint64_t tid, int64_t* vtid); /** * @brief get the current process id in the init pid namespace @@ -74,11 +74,12 @@ struct scap_linux_vtable { * `procinfo_p` must not be NULL, but `*procinfo_p` may be; the returned * list will be (re)allocated on demand */ - int32_t (*get_threadlist)(struct scap_engine_handle engine, struct ppm_proclist_info **procinfo_p, char *lasterr); + int32_t (*get_threadlist)(struct scap_engine_handle engine, + struct ppm_proclist_info** procinfo_p, + char* lasterr); }; -struct scap_linux_platform -{ +struct scap_linux_platform { struct scap_platform m_generic; char* m_lasterr; @@ -91,13 +92,14 @@ struct scap_linux_platform uint64_t m_proc_scan_timeout_ms; uint64_t m_proc_scan_log_interval_ms; - falcosecurity_log_fn m_log_fn; + falcosecurity_log_fn m_log_fn; struct scap_engine_handle m_engine; const struct scap_linux_vtable* m_linux_vtable; }; -struct scap_platform* scap_linux_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context); +struct scap_platform* scap_linux_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context); /** * @brief A lightweight Linux platform that only collects static host information @@ -108,8 +110,7 @@ struct scap_platform* scap_linux_alloc_platform(proc_entry_callback proc_callbac * - agent info * - interface list */ -struct scap_linux_hostinfo_platform -{ +struct scap_linux_hostinfo_platform { struct scap_platform m_generic; }; diff --git a/userspace/libscap/linux/scap_machine_info.c b/userspace/libscap/linux/scap_machine_info.c index b2c002f1bc..9da88dd1b3 100644 --- a/userspace/libscap/linux/scap_machine_info.c +++ b/userspace/libscap/linux/scap_machine_info.c @@ -30,41 +30,42 @@ limitations under the License. #define SECOND_TO_NS 1000000000ULL -void scap_os_get_agent_info(scap_agent_info* agent_info) -{ +void scap_os_get_agent_info(scap_agent_info* agent_info) { agent_info->start_ts_epoch = 0; agent_info->start_time = 0; /* Info 1: * - * Get epoch timestamp based on procfs stat, only used for (constant) agent start time reporting. + * Get epoch timestamp based on procfs stat, only used for (constant) agent start time + * reporting. */ struct stat st = {0}; - if(stat("/proc/self/cmdline", &st) == 0) - { + if(stat("/proc/self/cmdline", &st) == 0) { agent_info->start_ts_epoch = st.st_ctim.tv_sec * SECOND_TO_NS + st.st_ctim.tv_nsec; } /* Info 2: * - * Get /proc/self/stat start_time (22nd item) to calculate subsequent snapshots of the elapsed time - * of the agent for CPU usage calculations, e.g. sysinfo uptime - /proc/self/stat start_time. + * Get /proc/self/stat start_time (22nd item) to calculate subsequent snapshots of the elapsed + * time of the agent for CPU usage calculations, e.g. sysinfo uptime - /proc/self/stat + * start_time. */ FILE* f; - if((f = fopen("/proc/self/stat", "r"))) - { - unsigned long long stat_start_time = 0; // unit: USER_HZ / jiffies / clock ticks + if((f = fopen("/proc/self/stat", "r"))) { + unsigned long long stat_start_time = 0; // unit: USER_HZ / jiffies / clock ticks long hz = 100; #ifdef _SC_CLK_TCK - if ((hz = sysconf(_SC_CLK_TCK)) < 0) - { + if((hz = sysconf(_SC_CLK_TCK)) < 0) { hz = 100; ASSERT(false); } #endif - if(fscanf(f, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*u %llu", &stat_start_time)) - { - agent_info->start_time = (double)stat_start_time / hz; // unit: seconds as type (double) + if(fscanf(f, + "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d " + "%*u %llu", + &stat_start_time)) { + agent_info->start_time = + (double)stat_start_time / hz; // unit: seconds as type (double) } fclose(f); } @@ -79,8 +80,7 @@ void scap_os_get_agent_info(scap_agent_info* agent_info) snprintf(agent_info->uname_r, sizeof(agent_info->uname_r), "%s", uts.release); } -static uint64_t scap_linux_get_host_boot_time_ns(char* last_err) -{ +static uint64_t scap_linux_get_host_boot_time_ns(char* last_err) { uint64_t btime = 0; char proc_stat[SCAP_MAX_PATH_SIZE]; char line[512]; @@ -105,15 +105,12 @@ static uint64_t scap_linux_get_host_boot_time_ns(char* last_err) */ snprintf(proc_stat, sizeof(proc_stat), "%s/proc/stat", scap_get_host_root()); FILE* f = fopen(proc_stat, "r"); - if (f == NULL) - { + if(f == NULL) { return 0; } - while(fgets(line, sizeof(line), f) != NULL) - { - if(sscanf(line, "btime %" PRIu64, &btime) == 1) - { + while(fgets(line, sizeof(line), f) != NULL) { + if(sscanf(line, "btime %" PRIu64, &btime) == 1) { fclose(f); return btime * SECOND_TO_NS; } @@ -122,39 +119,36 @@ static uint64_t scap_linux_get_host_boot_time_ns(char* last_err) return 0; } -static void scap_gethostname(char* buf, size_t size) -{ - char *env_hostname = getenv(SCAP_HOSTNAME_ENV_VAR); - if(env_hostname != NULL) - { +static void scap_gethostname(char* buf, size_t size) { + char* env_hostname = getenv(SCAP_HOSTNAME_ENV_VAR); + if(env_hostname != NULL) { snprintf(buf, size, "%s", env_hostname); - } - else - { + } else { gethostname(buf, size); } } -int32_t scap_os_get_machine_info(scap_machine_info* machine_info, char* lasterr) -{ +int32_t scap_os_get_machine_info(scap_machine_info* machine_info, char* lasterr) { // Check that we can read under '/proc'. // A wrong usage of the env variable 'HOST_ROOT' can be detected here. char filename[SCAP_MAX_PATH_SIZE] = {0}; - if(snprintf(filename, sizeof(filename), "%s/proc/", scap_get_host_root()) < 0) - { - if(lasterr != NULL) - { - snprintf(lasterr, SCAP_LASTERR_SIZE, "unable to build the `/proc` path with 'snprintf'\n"); + if(snprintf(filename, sizeof(filename), "%s/proc/", scap_get_host_root()) < 0) { + if(lasterr != NULL) { + snprintf(lasterr, + SCAP_LASTERR_SIZE, + "unable to build the `/proc` path with 'snprintf'\n"); } return SCAP_FAILURE; } struct stat targetstat = {0}; - if(stat(filename, &targetstat) != 0) - { - if(lasterr != NULL) - { - snprintf(lasterr, SCAP_LASTERR_SIZE, "the directory '%s' doesn't exist on the system. Check the usage of the 'HOST_ROOT' env variable.", filename); + if(stat(filename, &targetstat) != 0) { + if(lasterr != NULL) { + snprintf(lasterr, + SCAP_LASTERR_SIZE, + "the directory '%s' doesn't exist on the system. Check the usage of the " + "'HOST_ROOT' env variable.", + filename); } return SCAP_FAILURE; } @@ -163,8 +157,7 @@ int32_t scap_os_get_machine_info(scap_machine_info* machine_info, char* lasterr) machine_info->memory_size_bytes = (uint64_t)sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE); scap_gethostname(machine_info->hostname, sizeof(machine_info->hostname)); machine_info->boot_ts_epoch = scap_linux_get_host_boot_time_ns(lasterr); - if(machine_info->boot_ts_epoch == 0) - { + if(machine_info->boot_ts_epoch == 0) { return SCAP_FAILURE; } diff --git a/userspace/libscap/linux/scap_ppm_sc.c b/userspace/libscap/linux/scap_ppm_sc.c index 881197f2f7..62f00cbba9 100644 --- a/userspace/libscap/linux/scap_ppm_sc.c +++ b/userspace/libscap/linux/scap_ppm_sc.c @@ -21,8 +21,9 @@ limitations under the License. #include /* - * When adding a new event, a new line should be added with the list of ppm_sc codes mapping that event. - * Events that are not mapped to any ppm_sc (ie: "container", "useradded"..., have NULL entries. + * When adding a new event, a new line should be added with the list of ppm_sc codes mapping that + * event. Events that are not mapped to any ppm_sc (ie: "container", "useradded"..., have NULL + * entries. * * If adding a specific event mapping an existing generic event, remember to * remove the generic events from the first 2 lines. @@ -30,446 +31,975 @@ limitations under the License. * NOTE: first 2 lines are automatically bumped by syscalls-bumper. */ static const ppm_sc_code *g_events_to_sc_map[] = { - [PPME_GENERIC_E] = (ppm_sc_code[]){ PPM_SC_RESTART_SYSCALL, PPM_SC_EXIT, PPM_SC_TIME, PPM_SC_GETPID, PPM_SC_SYNC, PPM_SC_TIMES, PPM_SC_ACCT, PPM_SC_UMASK, PPM_SC_USTAT, PPM_SC_GETPPID, PPM_SC_GETPGRP, PPM_SC_SETHOSTNAME, PPM_SC_GETRUSAGE, PPM_SC_GETTIMEOFDAY, PPM_SC_SETTIMEOFDAY, PPM_SC_READLINK, PPM_SC_SWAPON, PPM_SC_REBOOT, PPM_SC_TRUNCATE, PPM_SC_FTRUNCATE, PPM_SC_GETPRIORITY, PPM_SC_SETPRIORITY, PPM_SC_STATFS, PPM_SC_FSTATFS, PPM_SC_SETITIMER, PPM_SC_GETITIMER, PPM_SC_UNAME, PPM_SC_VHANGUP, PPM_SC_WAIT4, PPM_SC_SWAPOFF, PPM_SC_SYSINFO, PPM_SC_FSYNC, PPM_SC_SETDOMAINNAME, PPM_SC_ADJTIMEX, PPM_SC_GETPGID, PPM_SC_SYSFS, PPM_SC_PERSONALITY, PPM_SC_MSYNC, PPM_SC_GETSID, PPM_SC_FDATASYNC, PPM_SC_SCHED_SETSCHEDULER, PPM_SC_SCHED_GETSCHEDULER, PPM_SC_SCHED_YIELD, PPM_SC_SCHED_GET_PRIORITY_MAX, PPM_SC_SCHED_GET_PRIORITY_MIN, PPM_SC_SCHED_RR_GET_INTERVAL, PPM_SC_MREMAP, PPM_SC_ARCH_PRCTL, PPM_SC_RT_SIGACTION, PPM_SC_RT_SIGPROCMASK, PPM_SC_RT_SIGPENDING, PPM_SC_RT_SIGTIMEDWAIT, PPM_SC_RT_SIGQUEUEINFO, PPM_SC_RT_SIGSUSPEND, PPM_SC_CAPGET, PPM_SC_GETGROUPS, PPM_SC_SETGROUPS, PPM_SC_SETFSUID, PPM_SC_SETFSGID, PPM_SC_PIVOT_ROOT, PPM_SC_MINCORE, PPM_SC_MADVISE, PPM_SC_GETTID, PPM_SC_SETXATTR, PPM_SC_LSETXATTR, PPM_SC_FSETXATTR, PPM_SC_GETXATTR, PPM_SC_LGETXATTR, PPM_SC_FGETXATTR, PPM_SC_LISTXATTR, PPM_SC_LLISTXATTR, PPM_SC_FLISTXATTR, PPM_SC_REMOVEXATTR, PPM_SC_LREMOVEXATTR, PPM_SC_FREMOVEXATTR,PPM_SC_SCHED_SETAFFINITY, PPM_SC_SCHED_GETAFFINITY, PPM_SC_SET_THREAD_AREA, PPM_SC_GET_THREAD_AREA, PPM_SC_IO_SETUP, PPM_SC_IO_DESTROY, PPM_SC_IO_GETEVENTS, PPM_SC_IO_SUBMIT, PPM_SC_IO_CANCEL, PPM_SC_EXIT_GROUP, PPM_SC_REMAP_FILE_PAGES, PPM_SC_SET_TID_ADDRESS, PPM_SC_TIMER_CREATE, PPM_SC_TIMER_SETTIME, PPM_SC_TIMER_GETTIME, PPM_SC_TIMER_GETOVERRUN, PPM_SC_TIMER_DELETE, PPM_SC_CLOCK_SETTIME, PPM_SC_CLOCK_GETTIME, PPM_SC_CLOCK_GETRES, PPM_SC_CLOCK_NANOSLEEP,PPM_SC_UTIMES, PPM_SC_MQ_OPEN, PPM_SC_MQ_UNLINK, PPM_SC_MQ_TIMEDSEND, PPM_SC_MQ_TIMEDRECEIVE, PPM_SC_MQ_NOTIFY, PPM_SC_MQ_GETSETATTR, PPM_SC_KEXEC_LOAD, PPM_SC_WAITID, PPM_SC_ADD_KEY, PPM_SC_REQUEST_KEY, PPM_SC_KEYCTL, PPM_SC_IOPRIO_SET, PPM_SC_IOPRIO_GET, PPM_SC_INOTIFY_ADD_WATCH, PPM_SC_INOTIFY_RM_WATCH, PPM_SC_FUTIMESAT, PPM_SC_READLINKAT, PPM_SC_FACCESSAT, PPM_SC_SET_ROBUST_LIST, PPM_SC_GET_ROBUST_LIST, PPM_SC_TEE, PPM_SC_VMSPLICE, PPM_SC_GETCPU, PPM_SC_EPOLL_PWAIT, PPM_SC_UTIMENSAT, PPM_SC_TIMERFD_SETTIME, PPM_SC_TIMERFD_GETTIME, PPM_SC_RT_TGSIGQUEUEINFO, PPM_SC_PERF_EVENT_OPEN, PPM_SC_FANOTIFY_INIT, PPM_SC_CLOCK_ADJTIME, PPM_SC_SYNCFS, PPM_SC_MSGSND, PPM_SC_MSGRCV, PPM_SC_MSGGET, PPM_SC_MSGCTL, PPM_SC_SHMDT, PPM_SC_SHMGET, PPM_SC_SHMCTL, PPM_SC_STATFS64, PPM_SC_FSTATFS64, PPM_SC_FSTATAT64, PPM_SC_BDFLUSH, PPM_SC_SIGPROCMASK, PPM_SC_IPC, PPM_SC__NEWSELECT, PPM_SC_SGETMASK, PPM_SC_SSETMASK, PPM_SC_SIGPENDING, PPM_SC_OLDUNAME, PPM_SC_SIGNAL, PPM_SC_NICE, PPM_SC_STIME, PPM_SC_WAITPID, PPM_SC_SHMAT, PPM_SC_RT_SIGRETURN, PPM_SC_FALLOCATE, PPM_SC_SIGALTSTACK, PPM_SC_GETRANDOM, PPM_SC_FADVISE64, PPM_SC_SOCKETCALL, PPM_SC_FSPICK, PPM_SC_FSMOUNT, PPM_SC_FSOPEN, PPM_SC_OPEN_TREE, PPM_SC_MOVE_MOUNT, PPM_SC_MOUNT_SETATTR, PPM_SC_MEMFD_SECRET, PPM_SC_IOPERM, PPM_SC_KEXEC_FILE_LOAD, PPM_SC_PIDFD_SEND_SIGNAL, PPM_SC_PKEY_ALLOC, PPM_SC_PKEY_MPROTECT, PPM_SC_PKEY_FREE, PPM_SC_LANDLOCK_CREATE_RULESET, PPM_SC_QUOTACTL_FD, PPM_SC_LANDLOCK_RESTRICT_SELF, PPM_SC_LANDLOCK_ADD_RULE, PPM_SC_EPOLL_PWAIT2, PPM_SC_MIGRATE_PAGES, PPM_SC_MOVE_PAGES, PPM_SC_PREADV2, PPM_SC_PWRITEV2, PPM_SC_QUERY_MODULE, PPM_SC_STATX, PPM_SC_SET_MEMPOLICY, PPM_SC_FANOTIFY_MARK, PPM_SC_SYNC_FILE_RANGE, PPM_SC_READAHEAD, PPM_SC_PROCESS_MRELEASE, PPM_SC_MBIND, PPM_SC_PROCESS_MADVISE, PPM_SC_MEMBARRIER, PPM_SC_MODIFY_LDT, PPM_SC_SEMTIMEDOP, PPM_SC_NAME_TO_HANDLE_AT, PPM_SC_KCMP, PPM_SC_EPOLL_CTL_OLD, PPM_SC_EPOLL_WAIT_OLD, PPM_SC_FUTEX_WAITV, PPM_SC_CREATE_MODULE, PPM_SC__SYSCTL, PPM_SC_LOOKUP_DCOOKIE, PPM_SC_IOPL, PPM_SC_IO_PGETEVENTS, PPM_SC_GETPMSG, PPM_SC_SCHED_SETATTR, PPM_SC_GET_KERNEL_SYMS, PPM_SC_RSEQ, PPM_SC_CLOSE_RANGE, PPM_SC_GET_MEMPOLICY, PPM_SC_SCHED_GETATTR, PPM_SC_NFSSERVCTL, PPM_SC_SET_MEMPOLICY_HOME_NODE, PPM_SC_FACCESSAT2, PPM_SC_EPOLL_CTL, PPM_SC_SCHED_GETPARAM, PPM_SC_PSELECT6, PPM_SC_SCHED_SETPARAM, PPM_SC_PAUSE, PPM_SC_UTIME, PPM_SC_SYSLOG, PPM_SC_USELIB, PPM_SC_ALARM, PPM_SC_SIGSUSPEND, PPM_SC_IDLE, PPM_SC_S390_RUNTIME_INSTR, PPM_SC_SIGRETURN, PPM_SC_S390_GUARDED_STORAGE, PPM_SC_TIMERFD, PPM_SC_S390_PCI_MMIO_READ, PPM_SC_SIGACTION, PPM_SC_S390_PCI_MMIO_WRITE, PPM_SC_READDIR, PPM_SC_S390_STHYI, PPM_SC_CACHESTAT, PPM_SC_FCHMODAT2, PPM_SC_MAP_SHADOW_STACK, PPM_SC_RISCV_FLUSH_ICACHE, PPM_SC_RISCV_HWPROBE, PPM_SC_FUTEX_WAKE, PPM_SC_FUTEX_REQUEUE, PPM_SC_FUTEX_WAIT, PPM_SC_SYNC_FILE_RANGE2, PPM_SC_OLDFSTAT, PPM_SC_SPU_RUN, PPM_SC_SWAPCONTEXT, PPM_SC_OLDLSTAT, PPM_SC_SPU_CREATE, PPM_SC_PCICONFIG_READ, PPM_SC_SYS_DEBUG_SETCONTEXT, PPM_SC_VM86, PPM_SC_PCICONFIG_WRITE, PPM_SC_RTAS, PPM_SC_PCICONFIG_IOBASE, PPM_SC_OLDOLDUNAME, PPM_SC_SUBPAGE_PROT, PPM_SC_MULTIPLEXER, PPM_SC_OLDSTAT, PPM_SC_SWITCH_ENDIAN, PPM_SC_LISTMOUNT, PPM_SC_STATMOUNT, PPM_SC_LSM_GET_SELF_ATTR, PPM_SC_LSM_SET_SELF_ATTR, PPM_SC_LSM_LIST_MODULES, PPM_SC_MSEAL, PPM_SC_URETPROBE, -1}, - [PPME_GENERIC_X] = (ppm_sc_code[]){ PPM_SC_RESTART_SYSCALL, PPM_SC_EXIT, PPM_SC_TIME, PPM_SC_GETPID, PPM_SC_SYNC, PPM_SC_TIMES, PPM_SC_ACCT, PPM_SC_UMASK, PPM_SC_USTAT, PPM_SC_GETPPID, PPM_SC_GETPGRP, PPM_SC_SETHOSTNAME, PPM_SC_GETRUSAGE, PPM_SC_GETTIMEOFDAY, PPM_SC_SETTIMEOFDAY, PPM_SC_READLINK, PPM_SC_SWAPON, PPM_SC_REBOOT, PPM_SC_TRUNCATE, PPM_SC_FTRUNCATE, PPM_SC_GETPRIORITY, PPM_SC_SETPRIORITY, PPM_SC_STATFS, PPM_SC_FSTATFS, PPM_SC_SETITIMER, PPM_SC_GETITIMER, PPM_SC_UNAME, PPM_SC_VHANGUP, PPM_SC_WAIT4, PPM_SC_SWAPOFF, PPM_SC_SYSINFO, PPM_SC_FSYNC, PPM_SC_SETDOMAINNAME, PPM_SC_ADJTIMEX, PPM_SC_GETPGID, PPM_SC_SYSFS, PPM_SC_PERSONALITY, PPM_SC_MSYNC, PPM_SC_GETSID, PPM_SC_FDATASYNC, PPM_SC_SCHED_SETSCHEDULER, PPM_SC_SCHED_GETSCHEDULER, PPM_SC_SCHED_YIELD, PPM_SC_SCHED_GET_PRIORITY_MAX, PPM_SC_SCHED_GET_PRIORITY_MIN, PPM_SC_SCHED_RR_GET_INTERVAL, PPM_SC_MREMAP, PPM_SC_ARCH_PRCTL, PPM_SC_RT_SIGACTION, PPM_SC_RT_SIGPROCMASK, PPM_SC_RT_SIGPENDING, PPM_SC_RT_SIGTIMEDWAIT, PPM_SC_RT_SIGQUEUEINFO, PPM_SC_RT_SIGSUSPEND, PPM_SC_CAPGET, PPM_SC_GETGROUPS, PPM_SC_SETGROUPS, PPM_SC_SETFSUID, PPM_SC_SETFSGID, PPM_SC_PIVOT_ROOT, PPM_SC_MINCORE, PPM_SC_MADVISE, PPM_SC_GETTID, PPM_SC_SETXATTR, PPM_SC_LSETXATTR, PPM_SC_FSETXATTR, PPM_SC_GETXATTR, PPM_SC_LGETXATTR, PPM_SC_FGETXATTR, PPM_SC_LISTXATTR, PPM_SC_LLISTXATTR, PPM_SC_FLISTXATTR, PPM_SC_REMOVEXATTR, PPM_SC_LREMOVEXATTR, PPM_SC_FREMOVEXATTR,PPM_SC_SCHED_SETAFFINITY, PPM_SC_SCHED_GETAFFINITY, PPM_SC_SET_THREAD_AREA, PPM_SC_GET_THREAD_AREA, PPM_SC_IO_SETUP, PPM_SC_IO_DESTROY, PPM_SC_IO_GETEVENTS, PPM_SC_IO_SUBMIT, PPM_SC_IO_CANCEL, PPM_SC_EXIT_GROUP, PPM_SC_REMAP_FILE_PAGES, PPM_SC_SET_TID_ADDRESS, PPM_SC_TIMER_CREATE, PPM_SC_TIMER_SETTIME, PPM_SC_TIMER_GETTIME, PPM_SC_TIMER_GETOVERRUN, PPM_SC_TIMER_DELETE, PPM_SC_CLOCK_SETTIME, PPM_SC_CLOCK_GETTIME, PPM_SC_CLOCK_GETRES, PPM_SC_CLOCK_NANOSLEEP,PPM_SC_UTIMES, PPM_SC_MQ_OPEN, PPM_SC_MQ_UNLINK, PPM_SC_MQ_TIMEDSEND, PPM_SC_MQ_TIMEDRECEIVE, PPM_SC_MQ_NOTIFY, PPM_SC_MQ_GETSETATTR, PPM_SC_KEXEC_LOAD, PPM_SC_WAITID, PPM_SC_ADD_KEY, PPM_SC_REQUEST_KEY, PPM_SC_KEYCTL, PPM_SC_IOPRIO_SET, PPM_SC_IOPRIO_GET, PPM_SC_INOTIFY_ADD_WATCH, PPM_SC_INOTIFY_RM_WATCH, PPM_SC_FUTIMESAT, PPM_SC_READLINKAT, PPM_SC_FACCESSAT, PPM_SC_SET_ROBUST_LIST, PPM_SC_GET_ROBUST_LIST, PPM_SC_TEE, PPM_SC_VMSPLICE, PPM_SC_GETCPU, PPM_SC_EPOLL_PWAIT, PPM_SC_UTIMENSAT, PPM_SC_TIMERFD_SETTIME, PPM_SC_TIMERFD_GETTIME, PPM_SC_RT_TGSIGQUEUEINFO, PPM_SC_PERF_EVENT_OPEN, PPM_SC_FANOTIFY_INIT, PPM_SC_CLOCK_ADJTIME, PPM_SC_SYNCFS, PPM_SC_MSGSND, PPM_SC_MSGRCV, PPM_SC_MSGGET, PPM_SC_MSGCTL, PPM_SC_SHMDT, PPM_SC_SHMGET, PPM_SC_SHMCTL, PPM_SC_STATFS64, PPM_SC_FSTATFS64, PPM_SC_FSTATAT64, PPM_SC_BDFLUSH, PPM_SC_SIGPROCMASK, PPM_SC_IPC, PPM_SC__NEWSELECT, PPM_SC_SGETMASK, PPM_SC_SSETMASK, PPM_SC_SIGPENDING, PPM_SC_OLDUNAME, PPM_SC_SIGNAL, PPM_SC_NICE, PPM_SC_STIME, PPM_SC_WAITPID, PPM_SC_SHMAT, PPM_SC_RT_SIGRETURN, PPM_SC_FALLOCATE, PPM_SC_SIGALTSTACK, PPM_SC_GETRANDOM, PPM_SC_FADVISE64, PPM_SC_SOCKETCALL, PPM_SC_FSPICK, PPM_SC_FSMOUNT, PPM_SC_FSOPEN, PPM_SC_OPEN_TREE, PPM_SC_MOVE_MOUNT, PPM_SC_MOUNT_SETATTR, PPM_SC_MEMFD_SECRET, PPM_SC_IOPERM, PPM_SC_KEXEC_FILE_LOAD, PPM_SC_PIDFD_SEND_SIGNAL, PPM_SC_PKEY_ALLOC, PPM_SC_PKEY_MPROTECT, PPM_SC_PKEY_FREE, PPM_SC_LANDLOCK_CREATE_RULESET, PPM_SC_QUOTACTL_FD, PPM_SC_LANDLOCK_RESTRICT_SELF, PPM_SC_LANDLOCK_ADD_RULE, PPM_SC_EPOLL_PWAIT2, PPM_SC_MIGRATE_PAGES, PPM_SC_MOVE_PAGES, PPM_SC_PREADV2, PPM_SC_PWRITEV2, PPM_SC_QUERY_MODULE, PPM_SC_STATX, PPM_SC_SET_MEMPOLICY, PPM_SC_FANOTIFY_MARK, PPM_SC_SYNC_FILE_RANGE, PPM_SC_READAHEAD, PPM_SC_PROCESS_MRELEASE, PPM_SC_MBIND, PPM_SC_PROCESS_MADVISE, PPM_SC_MEMBARRIER, PPM_SC_MODIFY_LDT, PPM_SC_SEMTIMEDOP, PPM_SC_NAME_TO_HANDLE_AT, PPM_SC_KCMP, PPM_SC_EPOLL_CTL_OLD, PPM_SC_EPOLL_WAIT_OLD, PPM_SC_FUTEX_WAITV, PPM_SC_CREATE_MODULE, PPM_SC__SYSCTL, PPM_SC_LOOKUP_DCOOKIE, PPM_SC_IOPL, PPM_SC_IO_PGETEVENTS, PPM_SC_GETPMSG, PPM_SC_SCHED_SETATTR, PPM_SC_GET_KERNEL_SYMS, PPM_SC_RSEQ, PPM_SC_CLOSE_RANGE, PPM_SC_GET_MEMPOLICY, PPM_SC_SCHED_GETATTR, PPM_SC_NFSSERVCTL, PPM_SC_SET_MEMPOLICY_HOME_NODE, PPM_SC_FACCESSAT2, PPM_SC_EPOLL_CTL, PPM_SC_SCHED_GETPARAM, PPM_SC_PSELECT6, PPM_SC_SCHED_SETPARAM, PPM_SC_PAUSE, PPM_SC_UTIME, PPM_SC_SYSLOG, PPM_SC_USELIB, PPM_SC_ALARM, PPM_SC_TIMERFD, PPM_SC_S390_PCI_MMIO_READ, PPM_SC_SIGACTION, PPM_SC_S390_PCI_MMIO_WRITE, PPM_SC_READDIR, PPM_SC_S390_STHYI, PPM_SC_SIGSUSPEND, PPM_SC_IDLE, PPM_SC_S390_RUNTIME_INSTR, PPM_SC_SIGRETURN, PPM_SC_S390_GUARDED_STORAGE, PPM_SC_CACHESTAT, PPM_SC_FCHMODAT2, PPM_SC_MAP_SHADOW_STACK, PPM_SC_RISCV_FLUSH_ICACHE, PPM_SC_RISCV_HWPROBE, PPM_SC_FUTEX_WAKE, PPM_SC_FUTEX_REQUEUE, PPM_SC_FUTEX_WAIT, PPM_SC_OLDOLDUNAME, PPM_SC_SUBPAGE_PROT, PPM_SC_PCICONFIG_IOBASE, PPM_SC_OLDSTAT, PPM_SC_SWITCH_ENDIAN, PPM_SC_MULTIPLEXER, PPM_SC_OLDLSTAT, PPM_SC_SPU_CREATE, PPM_SC_SYNC_FILE_RANGE2, PPM_SC_OLDFSTAT, PPM_SC_SPU_RUN, PPM_SC_SWAPCONTEXT, PPM_SC_PCICONFIG_WRITE, PPM_SC_RTAS, PPM_SC_PCICONFIG_READ, PPM_SC_SYS_DEBUG_SETCONTEXT, PPM_SC_VM86, PPM_SC_LSM_SET_SELF_ATTR, PPM_SC_LSM_LIST_MODULES, PPM_SC_LISTMOUNT, PPM_SC_STATMOUNT, PPM_SC_LSM_GET_SELF_ATTR, PPM_SC_MSEAL, PPM_SC_URETPROBE, -1}, - [PPME_SYSCALL_OPEN_E] = (ppm_sc_code[]){PPM_SC_OPEN, -1}, - [PPME_SYSCALL_OPEN_X] = (ppm_sc_code[]){PPM_SC_OPEN, -1}, - [PPME_SYSCALL_CLOSE_E] = (ppm_sc_code[]){PPM_SC_CLOSE, -1}, - [PPME_SYSCALL_CLOSE_X] = (ppm_sc_code[]){PPM_SC_CLOSE, -1}, - [PPME_SYSCALL_READ_E] = (ppm_sc_code[]){PPM_SC_READ, -1}, - [PPME_SYSCALL_READ_X] = (ppm_sc_code[]){PPM_SC_READ, -1}, - [PPME_SYSCALL_WRITE_E] = (ppm_sc_code[]){PPM_SC_WRITE, -1}, - [PPME_SYSCALL_WRITE_X] = (ppm_sc_code[]){PPM_SC_WRITE, -1}, - [PPME_SYSCALL_BRK_1_E] = (ppm_sc_code[]){PPM_SC_BRK, -1}, - [PPME_SYSCALL_BRK_1_X] = (ppm_sc_code[]){PPM_SC_BRK, -1}, - [PPME_SYSCALL_EXECVE_8_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_8_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_CLONE_11_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_CLONE_11_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_PRCTL_E] = (ppm_sc_code[]){PPM_SC_PRCTL, -1}, - [PPME_SYSCALL_PRCTL_X] = (ppm_sc_code[]){PPM_SC_PRCTL, -1}, - [PPME_PROCEXIT_E] = (ppm_sc_code[]){PPM_SC_SCHED_PROCESS_EXIT, -1}, - [PPME_PROCEXIT_X] = NULL, - [PPME_SOCKET_SOCKET_E] = (ppm_sc_code[]){PPM_SC_SOCKET, -1}, - [PPME_SOCKET_SOCKET_X] = (ppm_sc_code[]){PPM_SC_SOCKET, -1}, - [PPME_SOCKET_BIND_E] = (ppm_sc_code[]){PPM_SC_BIND, -1}, - [PPME_SOCKET_BIND_X] = (ppm_sc_code[]){PPM_SC_BIND, -1}, - [PPME_SOCKET_CONNECT_E] = (ppm_sc_code[]){PPM_SC_CONNECT, -1}, - [PPME_SOCKET_CONNECT_X] = (ppm_sc_code[]){PPM_SC_CONNECT, -1}, - [PPME_SOCKET_LISTEN_E] = (ppm_sc_code[]){PPM_SC_LISTEN, -1}, - [PPME_SOCKET_LISTEN_X] = (ppm_sc_code[]){PPM_SC_LISTEN, -1}, - [PPME_SOCKET_ACCEPT_E] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, - [PPME_SOCKET_ACCEPT_X] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, - [PPME_SOCKET_SEND_E] = (ppm_sc_code[]){PPM_SC_SEND, -1}, - [PPME_SOCKET_SEND_X] = (ppm_sc_code[]){PPM_SC_SEND, -1}, - [PPME_SOCKET_SENDTO_E] = (ppm_sc_code[]){PPM_SC_SENDTO, -1}, - [PPME_SOCKET_SENDTO_X] = (ppm_sc_code[]){PPM_SC_SENDTO, -1}, - [PPME_SOCKET_RECV_E] = (ppm_sc_code[]){PPM_SC_RECV, -1}, - [PPME_SOCKET_RECV_X] = (ppm_sc_code[]){PPM_SC_RECV, -1}, - [PPME_SOCKET_RECVFROM_E] = (ppm_sc_code[]){PPM_SC_RECVFROM, -1}, - [PPME_SOCKET_RECVFROM_X] = (ppm_sc_code[]){PPM_SC_RECVFROM, -1}, - [PPME_SOCKET_SHUTDOWN_E] = (ppm_sc_code[]){PPM_SC_SHUTDOWN, -1}, - [PPME_SOCKET_SHUTDOWN_X] = (ppm_sc_code[]){PPM_SC_SHUTDOWN, -1}, - [PPME_SOCKET_GETSOCKNAME_E] = (ppm_sc_code[]){PPM_SC_GETSOCKNAME, -1}, - [PPME_SOCKET_GETSOCKNAME_X] = (ppm_sc_code[]){PPM_SC_GETSOCKNAME, -1}, - [PPME_SOCKET_GETPEERNAME_E] = (ppm_sc_code[]){PPM_SC_GETPEERNAME, -1}, - [PPME_SOCKET_GETPEERNAME_X] = (ppm_sc_code[]){PPM_SC_GETPEERNAME, -1}, - [PPME_SOCKET_SOCKETPAIR_E] = (ppm_sc_code[]){PPM_SC_SOCKETPAIR, -1}, - [PPME_SOCKET_SOCKETPAIR_X] = (ppm_sc_code[]){PPM_SC_SOCKETPAIR, -1}, - [PPME_SOCKET_SETSOCKOPT_E] = (ppm_sc_code[]){PPM_SC_SETSOCKOPT, -1}, - [PPME_SOCKET_SETSOCKOPT_X] = (ppm_sc_code[]){PPM_SC_SETSOCKOPT, -1}, - [PPME_SOCKET_GETSOCKOPT_E] = (ppm_sc_code[]){PPM_SC_GETSOCKOPT, -1}, - [PPME_SOCKET_GETSOCKOPT_X] = (ppm_sc_code[]){PPM_SC_GETSOCKOPT, -1}, - [PPME_SOCKET_SENDMSG_E] = (ppm_sc_code[]){PPM_SC_SENDMSG, -1}, - [PPME_SOCKET_SENDMSG_X] = (ppm_sc_code[]){PPM_SC_SENDMSG, -1}, - [PPME_SOCKET_SENDMMSG_E] = (ppm_sc_code[]){PPM_SC_SENDMMSG, -1}, - [PPME_SOCKET_SENDMMSG_X] = (ppm_sc_code[]){PPM_SC_SENDMMSG, -1}, - [PPME_SOCKET_RECVMSG_E] = (ppm_sc_code[]){PPM_SC_RECVMSG, -1}, - [PPME_SOCKET_RECVMSG_X] = (ppm_sc_code[]){PPM_SC_RECVMSG, -1}, - [PPME_SOCKET_RECVMMSG_E] = (ppm_sc_code[]){PPM_SC_RECVMMSG, -1}, - [PPME_SOCKET_RECVMMSG_X] = (ppm_sc_code[]){PPM_SC_RECVMMSG, -1}, - [PPME_SOCKET_ACCEPT4_E] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, - [PPME_SOCKET_ACCEPT4_X] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, - [PPME_SYSCALL_CREAT_E] = (ppm_sc_code[]){PPM_SC_CREAT, -1}, - [PPME_SYSCALL_CREAT_X] = (ppm_sc_code[]){PPM_SC_CREAT, -1}, - [PPME_SYSCALL_PIPE_E] = (ppm_sc_code[]){PPM_SC_PIPE, -1}, - [PPME_SYSCALL_PIPE_X] = (ppm_sc_code[]){PPM_SC_PIPE, -1}, - [PPME_SYSCALL_EVENTFD_E] = (ppm_sc_code[]){PPM_SC_EVENTFD, -1}, - [PPME_SYSCALL_EVENTFD_X] = (ppm_sc_code[]){PPM_SC_EVENTFD, -1}, - [PPME_SYSCALL_FUTEX_E] = (ppm_sc_code[]){PPM_SC_FUTEX, -1}, - [PPME_SYSCALL_FUTEX_X] = (ppm_sc_code[]){PPM_SC_FUTEX, -1}, - [PPME_SYSCALL_STAT_E] = (ppm_sc_code[]){PPM_SC_STAT, -1}, - [PPME_SYSCALL_STAT_X] = (ppm_sc_code[]){PPM_SC_STAT, -1}, - [PPME_SYSCALL_LSTAT_E] = (ppm_sc_code[]){PPM_SC_LSTAT, -1}, - [PPME_SYSCALL_LSTAT_X] = (ppm_sc_code[]){PPM_SC_LSTAT, -1}, - [PPME_SYSCALL_FSTAT_E] = (ppm_sc_code[]){PPM_SC_FSTAT, -1}, - [PPME_SYSCALL_FSTAT_X] = (ppm_sc_code[]){PPM_SC_FSTAT, -1}, - [PPME_SYSCALL_STAT64_E] = (ppm_sc_code[]){PPM_SC_STAT64, -1}, - [PPME_SYSCALL_STAT64_X] = (ppm_sc_code[]){PPM_SC_STAT64, -1}, - [PPME_SYSCALL_LSTAT64_E] = (ppm_sc_code[]){PPM_SC_LSTAT64, -1}, // lstat64 -> is not impl by supported archs - [PPME_SYSCALL_LSTAT64_X] = (ppm_sc_code[]){PPM_SC_LSTAT64, -1}, // lstat64 -> is not impl by supported archs - [PPME_SYSCALL_FSTAT64_E] = (ppm_sc_code[]){PPM_SC_FSTAT64, -1}, - [PPME_SYSCALL_FSTAT64_X] = (ppm_sc_code[]){PPM_SC_FSTAT64, -1}, - [PPME_SYSCALL_EPOLLWAIT_E] = (ppm_sc_code[]){PPM_SC_EPOLL_WAIT, -1}, - [PPME_SYSCALL_EPOLLWAIT_X] = (ppm_sc_code[]){PPM_SC_EPOLL_WAIT, -1}, - [PPME_SYSCALL_POLL_E] = (ppm_sc_code[]){PPM_SC_POLL, -1}, - [PPME_SYSCALL_POLL_X] = (ppm_sc_code[]){PPM_SC_POLL, -1}, - [PPME_SYSCALL_SELECT_E] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, - [PPME_SYSCALL_SELECT_X] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, - [PPME_SYSCALL_NEWSELECT_E] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, - [PPME_SYSCALL_NEWSELECT_X] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, - [PPME_SYSCALL_LSEEK_E] = (ppm_sc_code[]){PPM_SC_LSEEK, -1}, - [PPME_SYSCALL_LSEEK_X] = (ppm_sc_code[]){PPM_SC_LSEEK, -1}, - [PPME_SYSCALL_LLSEEK_E] = (ppm_sc_code[]){PPM_SC__LLSEEK, -1}, - [PPME_SYSCALL_LLSEEK_X] = (ppm_sc_code[]){PPM_SC__LLSEEK, -1}, - [PPME_SYSCALL_IOCTL_2_E] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, - [PPME_SYSCALL_IOCTL_2_X] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, - [PPME_SYSCALL_GETCWD_E] = (ppm_sc_code[]){PPM_SC_GETCWD, -1}, - [PPME_SYSCALL_GETCWD_X] = (ppm_sc_code[]){PPM_SC_GETCWD, -1}, - [PPME_SYSCALL_CHDIR_E] = (ppm_sc_code[]){PPM_SC_CHDIR, -1}, - [PPME_SYSCALL_CHDIR_X] = (ppm_sc_code[]){PPM_SC_CHDIR, -1}, - [PPME_SYSCALL_FCHDIR_E] = (ppm_sc_code[]){PPM_SC_FCHDIR, -1}, - [PPME_SYSCALL_FCHDIR_X] = (ppm_sc_code[]){PPM_SC_FCHDIR, -1}, - [PPME_SYSCALL_MKDIR_E] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, - [PPME_SYSCALL_MKDIR_X] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, - [PPME_SYSCALL_RMDIR_E] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, - [PPME_SYSCALL_RMDIR_X] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, - [PPME_SYSCALL_OPENAT_E] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, - [PPME_SYSCALL_OPENAT_X] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, - [PPME_SYSCALL_LINK_E] = (ppm_sc_code[]){PPM_SC_LINK, -1}, - [PPME_SYSCALL_LINK_X] = (ppm_sc_code[]){PPM_SC_LINK, -1}, - [PPME_SYSCALL_LINKAT_E] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, - [PPME_SYSCALL_LINKAT_X] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, - [PPME_SYSCALL_UNLINK_E] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, - [PPME_SYSCALL_UNLINK_X] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, - [PPME_SYSCALL_UNLINKAT_E] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, - [PPME_SYSCALL_UNLINKAT_X] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, - [PPME_SYSCALL_PREAD_E] = (ppm_sc_code[]){PPM_SC_PREAD64, -1}, - [PPME_SYSCALL_PREAD_X] = (ppm_sc_code[]){PPM_SC_PREAD64, -1}, - [PPME_SYSCALL_PWRITE_E] = (ppm_sc_code[]){PPM_SC_PWRITE64, -1}, - [PPME_SYSCALL_PWRITE_X] = (ppm_sc_code[]){PPM_SC_PWRITE64, -1}, - [PPME_SYSCALL_READV_E] = (ppm_sc_code[]){PPM_SC_READV, -1}, - [PPME_SYSCALL_READV_X] = (ppm_sc_code[]){PPM_SC_READV, -1}, - [PPME_SYSCALL_WRITEV_E] = (ppm_sc_code[]){PPM_SC_WRITEV, -1}, - [PPME_SYSCALL_WRITEV_X] = (ppm_sc_code[]){PPM_SC_WRITEV, -1}, - [PPME_SYSCALL_PREADV_E] = (ppm_sc_code[]){PPM_SC_PREADV, -1}, - [PPME_SYSCALL_PREADV_X] = (ppm_sc_code[]){PPM_SC_PREADV, -1}, - [PPME_SYSCALL_PWRITEV_E] = (ppm_sc_code[]){PPM_SC_PWRITEV, -1}, - [PPME_SYSCALL_PWRITEV_X] = (ppm_sc_code[]){PPM_SC_PWRITEV, -1}, - [PPME_SYSCALL_DUP_E] = (ppm_sc_code[]){PPM_SC_DUP, -1}, - [PPME_SYSCALL_DUP_X] = (ppm_sc_code[]){PPM_SC_DUP, -1}, - [PPME_SYSCALL_SIGNALFD_E] = (ppm_sc_code[]){PPM_SC_SIGNALFD, -1}, - [PPME_SYSCALL_SIGNALFD_X] = (ppm_sc_code[]){PPM_SC_SIGNALFD, -1}, - [PPME_SYSCALL_KILL_E] = (ppm_sc_code[]){PPM_SC_KILL, -1}, - [PPME_SYSCALL_KILL_X] = (ppm_sc_code[]){PPM_SC_KILL, -1}, - [PPME_SYSCALL_TKILL_E] = (ppm_sc_code[]){PPM_SC_TKILL, -1}, - [PPME_SYSCALL_TKILL_X] = (ppm_sc_code[]){PPM_SC_TKILL, -1}, - [PPME_SYSCALL_TGKILL_E] = (ppm_sc_code[]){PPM_SC_TGKILL, -1}, - [PPME_SYSCALL_TGKILL_X] = (ppm_sc_code[]){PPM_SC_TGKILL, -1}, - [PPME_SYSCALL_NANOSLEEP_E] = (ppm_sc_code[]){PPM_SC_NANOSLEEP, -1}, - [PPME_SYSCALL_NANOSLEEP_X] = (ppm_sc_code[]){PPM_SC_NANOSLEEP, -1}, - [PPME_SYSCALL_TIMERFD_CREATE_E] = (ppm_sc_code[]){PPM_SC_TIMERFD_CREATE, -1}, - [PPME_SYSCALL_TIMERFD_CREATE_X] = (ppm_sc_code[]){PPM_SC_TIMERFD_CREATE, -1}, - [PPME_SYSCALL_INOTIFY_INIT_E] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT, -1}, - [PPME_SYSCALL_INOTIFY_INIT_X] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT, -1}, - [PPME_SYSCALL_GETRLIMIT_E] = (ppm_sc_code[]){PPM_SC_GETRLIMIT, PPM_SC_UGETRLIMIT, -1}, - [PPME_SYSCALL_GETRLIMIT_X] = (ppm_sc_code[]){PPM_SC_GETRLIMIT, PPM_SC_UGETRLIMIT, -1}, - [PPME_SYSCALL_SETRLIMIT_E] = (ppm_sc_code[]){PPM_SC_SETRLIMIT, -1}, - [PPME_SYSCALL_SETRLIMIT_X] = (ppm_sc_code[]){PPM_SC_SETRLIMIT, -1}, - [PPME_SYSCALL_PRLIMIT_E] = (ppm_sc_code[]){PPM_SC_PRLIMIT64, -1}, - [PPME_SYSCALL_PRLIMIT_X] = (ppm_sc_code[]){PPM_SC_PRLIMIT64, -1}, - [PPME_SCHEDSWITCH_1_E] = (ppm_sc_code[]){PPM_SC_SCHED_SWITCH, -1}, - [PPME_SCHEDSWITCH_1_X] = NULL, - [PPME_DROP_E] = NULL, - [PPME_DROP_X] = NULL, - [PPME_SYSCALL_FCNTL_E] = (ppm_sc_code[]){PPM_SC_FCNTL, PPM_SC_FCNTL64, -1}, - [PPME_SYSCALL_FCNTL_X] = (ppm_sc_code[]){PPM_SC_FCNTL, PPM_SC_FCNTL64, -1}, - [PPME_SCHEDSWITCH_6_E] = (ppm_sc_code[]){PPM_SC_SCHED_SWITCH, -1}, - [PPME_SCHEDSWITCH_6_X] = NULL, - [PPME_SYSCALL_EXECVE_13_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_13_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_CLONE_16_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_CLONE_16_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_BRK_4_E] = (ppm_sc_code[]){PPM_SC_BRK, -1}, - [PPME_SYSCALL_BRK_4_X] = (ppm_sc_code[]){PPM_SC_BRK, -1}, - [PPME_SYSCALL_MMAP_E] = (ppm_sc_code[]){PPM_SC_MMAP, -1}, - [PPME_SYSCALL_MMAP_X] = (ppm_sc_code[]){PPM_SC_MMAP, -1}, - [PPME_SYSCALL_MMAP2_E] = (ppm_sc_code[]){PPM_SC_MMAP2, -1}, - [PPME_SYSCALL_MMAP2_X] = (ppm_sc_code[]){PPM_SC_MMAP2, -1}, - [PPME_SYSCALL_MUNMAP_E] = (ppm_sc_code[]){PPM_SC_MUNMAP, -1}, - [PPME_SYSCALL_MUNMAP_X] = (ppm_sc_code[]){PPM_SC_MUNMAP, -1}, - [PPME_SYSCALL_SPLICE_E] = (ppm_sc_code[]){PPM_SC_SPLICE, -1}, - [PPME_SYSCALL_SPLICE_X] = (ppm_sc_code[]){PPM_SC_SPLICE, -1}, - [PPME_SYSCALL_PTRACE_E] = (ppm_sc_code[]){PPM_SC_PTRACE, -1}, - [PPME_SYSCALL_PTRACE_X] = (ppm_sc_code[]){PPM_SC_PTRACE, -1}, - [PPME_SYSCALL_IOCTL_3_E] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, - [PPME_SYSCALL_IOCTL_3_X] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, - [PPME_SYSCALL_EXECVE_14_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_14_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_RENAME_E] = (ppm_sc_code[]){PPM_SC_RENAME, -1}, - [PPME_SYSCALL_RENAME_X] = (ppm_sc_code[]){PPM_SC_RENAME, -1}, - [PPME_SYSCALL_RENAMEAT_E] = (ppm_sc_code[]){PPM_SC_RENAMEAT, -1}, - [PPME_SYSCALL_RENAMEAT_X] = (ppm_sc_code[]){PPM_SC_RENAMEAT, -1}, - [PPME_SYSCALL_SYMLINK_E] = (ppm_sc_code[]){PPM_SC_SYMLINK, -1}, - [PPME_SYSCALL_SYMLINK_X] = (ppm_sc_code[]){PPM_SC_SYMLINK, -1}, - [PPME_SYSCALL_SYMLINKAT_E] = (ppm_sc_code[]){PPM_SC_SYMLINKAT, -1}, - [PPME_SYSCALL_SYMLINKAT_X] = (ppm_sc_code[]){PPM_SC_SYMLINKAT, -1}, - [PPME_SYSCALL_FORK_E] = (ppm_sc_code[]){PPM_SC_FORK, -1}, - [PPME_SYSCALL_FORK_X] = (ppm_sc_code[]){PPM_SC_FORK, -1}, - [PPME_SYSCALL_VFORK_E] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, - [PPME_SYSCALL_VFORK_X] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, - [PPME_PROCEXIT_1_E] = (ppm_sc_code[]){PPM_SC_SCHED_PROCESS_EXIT, -1}, - [PPME_PROCEXIT_1_X] = NULL, - [PPME_SYSCALL_SENDFILE_E] = (ppm_sc_code[]){PPM_SC_SENDFILE, PPM_SC_SENDFILE64, -1}, - [PPME_SYSCALL_SENDFILE_X] = (ppm_sc_code[]){PPM_SC_SENDFILE, PPM_SC_SENDFILE64, -1}, - [PPME_SYSCALL_QUOTACTL_E] = (ppm_sc_code[]){PPM_SC_QUOTACTL, -1}, - [PPME_SYSCALL_QUOTACTL_X] = (ppm_sc_code[]){PPM_SC_QUOTACTL, -1}, - [PPME_SYSCALL_SETRESUID_E] = (ppm_sc_code[]){PPM_SC_SETRESUID, PPM_SC_SETRESUID32, -1}, - [PPME_SYSCALL_SETRESUID_X] = (ppm_sc_code[]){PPM_SC_SETRESUID, PPM_SC_SETRESUID32, -1}, - [PPME_SYSCALL_SETRESGID_E] = (ppm_sc_code[]){PPM_SC_SETRESGID, PPM_SC_SETRESGID32, -1}, - [PPME_SYSCALL_SETRESGID_X] = (ppm_sc_code[]){PPM_SC_SETRESGID, PPM_SC_SETRESGID32, -1}, - [PPME_SCAPEVENT_E] = NULL, - [PPME_SCAPEVENT_X] = NULL, - [PPME_SYSCALL_SETUID_E] = (ppm_sc_code[]){PPM_SC_SETUID, PPM_SC_SETUID32, -1}, - [PPME_SYSCALL_SETUID_X] = (ppm_sc_code[]){PPM_SC_SETUID, PPM_SC_SETUID32, -1}, - [PPME_SYSCALL_SETGID_E] = (ppm_sc_code[]){PPM_SC_SETGID, PPM_SC_SETGID32, -1}, - [PPME_SYSCALL_SETGID_X] = (ppm_sc_code[]){PPM_SC_SETGID, PPM_SC_SETGID32, -1}, - [PPME_SYSCALL_GETUID_E] = (ppm_sc_code[]){PPM_SC_GETUID, PPM_SC_GETUID32, -1}, - [PPME_SYSCALL_GETUID_X] = (ppm_sc_code[]){PPM_SC_GETUID, PPM_SC_GETUID32, -1}, - [PPME_SYSCALL_GETEUID_E] = (ppm_sc_code[]){PPM_SC_GETEUID, PPM_SC_GETEUID32, -1}, - [PPME_SYSCALL_GETEUID_X] = (ppm_sc_code[]){PPM_SC_GETEUID, PPM_SC_GETEUID32, -1}, - [PPME_SYSCALL_GETGID_E] = (ppm_sc_code[]){PPM_SC_GETGID, PPM_SC_GETGID32, -1}, - [PPME_SYSCALL_GETGID_X] = (ppm_sc_code[]){PPM_SC_GETGID, PPM_SC_GETGID32, -1}, - [PPME_SYSCALL_GETEGID_E] = (ppm_sc_code[]){PPM_SC_GETEGID, PPM_SC_GETEGID32, -1}, - [PPME_SYSCALL_GETEGID_X] = (ppm_sc_code[]){PPM_SC_GETEGID, PPM_SC_GETEGID32, -1}, - [PPME_SYSCALL_GETRESUID_E] = (ppm_sc_code[]){PPM_SC_GETRESUID, PPM_SC_GETRESUID32, -1}, - [PPME_SYSCALL_GETRESUID_X] = (ppm_sc_code[]){PPM_SC_GETRESUID, PPM_SC_GETRESUID32, -1}, - [PPME_SYSCALL_GETRESGID_E] = (ppm_sc_code[]){PPM_SC_GETRESGID, PPM_SC_GETRESGID32, -1}, - [PPME_SYSCALL_GETRESGID_X] = (ppm_sc_code[]){PPM_SC_GETRESGID, PPM_SC_GETRESGID32, -1}, - [PPME_SYSCALL_EXECVE_15_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_15_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_CLONE_17_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_CLONE_17_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_FORK_17_E] = (ppm_sc_code[]){PPM_SC_FORK, -1}, - [PPME_SYSCALL_FORK_17_X] = (ppm_sc_code[]){PPM_SC_FORK, -1}, - [PPME_SYSCALL_VFORK_17_E] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, - [PPME_SYSCALL_VFORK_17_X] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, - [PPME_SYSCALL_CLONE_20_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_CLONE_20_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, - [PPME_SYSCALL_FORK_20_E] = (ppm_sc_code[]){PPM_SC_FORK, -1}, - [PPME_SYSCALL_FORK_20_X] = (ppm_sc_code[]){PPM_SC_FORK, -1}, - [PPME_SYSCALL_VFORK_20_E] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, - [PPME_SYSCALL_VFORK_20_X] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, - [PPME_CONTAINER_E] = NULL, - [PPME_CONTAINER_X] = NULL, - [PPME_SYSCALL_EXECVE_16_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_16_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SIGNALDELIVER_E] = (ppm_sc_code[]){PPM_SC_SIGNAL_DELIVER, -1}, - [PPME_SIGNALDELIVER_X] = NULL, - [PPME_PROCINFO_E] = NULL, - [PPME_PROCINFO_X] = NULL, - [PPME_SYSCALL_GETDENTS_E] = (ppm_sc_code[]){PPM_SC_GETDENTS, -1}, - [PPME_SYSCALL_GETDENTS_X] = (ppm_sc_code[]){PPM_SC_GETDENTS, -1}, - [PPME_SYSCALL_GETDENTS64_E] = (ppm_sc_code[]){PPM_SC_GETDENTS64, -1}, - [PPME_SYSCALL_GETDENTS64_X] = (ppm_sc_code[]){PPM_SC_GETDENTS64, -1}, - [PPME_SYSCALL_SETNS_E] = (ppm_sc_code[]){PPM_SC_SETNS, -1}, - [PPME_SYSCALL_SETNS_X] = (ppm_sc_code[]){PPM_SC_SETNS, -1}, - [PPME_SYSCALL_FLOCK_E] = (ppm_sc_code[]){PPM_SC_FLOCK, -1}, - [PPME_SYSCALL_FLOCK_X] = (ppm_sc_code[]){PPM_SC_FLOCK, -1}, - [PPME_CPU_HOTPLUG_E] = NULL, - [PPME_CPU_HOTPLUG_X] = NULL, - [PPME_SOCKET_ACCEPT_5_E] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, - [PPME_SOCKET_ACCEPT_5_X] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, - [PPME_SOCKET_ACCEPT4_5_E] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, - [PPME_SOCKET_ACCEPT4_5_X] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, - [PPME_SYSCALL_SEMOP_E] = (ppm_sc_code[]){PPM_SC_SEMOP, -1}, - [PPME_SYSCALL_SEMOP_X] = (ppm_sc_code[]){PPM_SC_SEMOP, -1}, - [PPME_SYSCALL_SEMCTL_E] = (ppm_sc_code[]){PPM_SC_SEMCTL, -1}, - [PPME_SYSCALL_SEMCTL_X] = (ppm_sc_code[]){PPM_SC_SEMCTL, -1}, - [PPME_SYSCALL_PPOLL_E] = (ppm_sc_code[]){PPM_SC_PPOLL, -1}, - [PPME_SYSCALL_PPOLL_X] = (ppm_sc_code[]){PPM_SC_PPOLL, -1}, - [PPME_SYSCALL_MOUNT_E] = (ppm_sc_code[]){PPM_SC_MOUNT, -1}, - [PPME_SYSCALL_MOUNT_X] = (ppm_sc_code[]){PPM_SC_MOUNT, -1}, - [PPME_SYSCALL_UMOUNT_E] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, - [PPME_SYSCALL_UMOUNT_X] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, - [PPME_K8S_E] = NULL, - [PPME_K8S_X] = NULL, - [PPME_SYSCALL_SEMGET_E] = (ppm_sc_code[]){PPM_SC_SEMGET, -1}, - [PPME_SYSCALL_SEMGET_X] = (ppm_sc_code[]){PPM_SC_SEMGET, -1}, - [PPME_SYSCALL_ACCESS_E] = (ppm_sc_code[]){PPM_SC_ACCESS, -1}, - [PPME_SYSCALL_ACCESS_X] = (ppm_sc_code[]){PPM_SC_ACCESS, -1}, - [PPME_SYSCALL_CHROOT_E] = (ppm_sc_code[]){PPM_SC_CHROOT, -1}, - [PPME_SYSCALL_CHROOT_X] = (ppm_sc_code[]){PPM_SC_CHROOT, -1}, - [PPME_TRACER_E] = NULL, - [PPME_TRACER_X] = NULL, - [PPME_MESOS_E] = NULL, - [PPME_MESOS_X] = NULL, - [PPME_CONTAINER_JSON_E] = NULL, - [PPME_CONTAINER_JSON_X] = NULL, - [PPME_SYSCALL_SETSID_E] = (ppm_sc_code[]){PPM_SC_SETSID, -1}, - [PPME_SYSCALL_SETSID_X] = (ppm_sc_code[]){PPM_SC_SETSID, -1}, - [PPME_SYSCALL_MKDIR_2_E] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, - [PPME_SYSCALL_MKDIR_2_X] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, - [PPME_SYSCALL_RMDIR_2_E] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, - [PPME_SYSCALL_RMDIR_2_X] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, - [PPME_NOTIFICATION_E] = NULL, - [PPME_NOTIFICATION_X] = NULL, - [PPME_SYSCALL_EXECVE_17_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_17_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_UNSHARE_E] = (ppm_sc_code[]){PPM_SC_UNSHARE, -1}, - [PPME_SYSCALL_UNSHARE_X] = (ppm_sc_code[]){PPM_SC_UNSHARE, -1}, - [PPME_INFRASTRUCTURE_EVENT_E] = NULL, - [PPME_INFRASTRUCTURE_EVENT_X] = NULL, - [PPME_SYSCALL_EXECVE_18_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_18_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_PAGE_FAULT_E] = (ppm_sc_code[]){PPM_SC_PAGE_FAULT_USER, PPM_SC_PAGE_FAULT_KERNEL, -1}, - [PPME_PAGE_FAULT_X] = NULL, - [PPME_SYSCALL_EXECVE_19_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_EXECVE_19_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, - [PPME_SYSCALL_SETPGID_E] = (ppm_sc_code[]){PPM_SC_SETPGID, -1}, - [PPME_SYSCALL_SETPGID_X] = (ppm_sc_code[]){PPM_SC_SETPGID, -1}, - [PPME_SYSCALL_BPF_E] = (ppm_sc_code[]){PPM_SC_BPF, -1}, - [PPME_SYSCALL_BPF_X] = (ppm_sc_code[]){PPM_SC_BPF, -1}, - [PPME_SYSCALL_SECCOMP_E] = (ppm_sc_code[]){PPM_SC_SECCOMP, -1}, - [PPME_SYSCALL_SECCOMP_X] = (ppm_sc_code[]){PPM_SC_SECCOMP, -1}, - [PPME_SYSCALL_UNLINK_2_E] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, - [PPME_SYSCALL_UNLINK_2_X] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, - [PPME_SYSCALL_UNLINKAT_2_E] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, - [PPME_SYSCALL_UNLINKAT_2_X] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, - [PPME_SYSCALL_MKDIRAT_E] = (ppm_sc_code[]){PPM_SC_MKDIRAT, -1}, - [PPME_SYSCALL_MKDIRAT_X] = (ppm_sc_code[]){PPM_SC_MKDIRAT, -1}, - [PPME_SYSCALL_OPENAT_2_E] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, - [PPME_SYSCALL_OPENAT_2_X] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, - [PPME_SYSCALL_LINK_2_E] = (ppm_sc_code[]){PPM_SC_LINK, -1}, - [PPME_SYSCALL_LINK_2_X] = (ppm_sc_code[]){PPM_SC_LINK, -1}, - [PPME_SYSCALL_LINKAT_2_E] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, - [PPME_SYSCALL_LINKAT_2_X] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, - [PPME_SYSCALL_FCHMODAT_E] = (ppm_sc_code[]){PPM_SC_FCHMODAT, -1}, - [PPME_SYSCALL_FCHMODAT_X] = (ppm_sc_code[]){PPM_SC_FCHMODAT, -1}, - [PPME_SYSCALL_CHMOD_E] = (ppm_sc_code[]){PPM_SC_CHMOD, -1}, - [PPME_SYSCALL_CHMOD_X] = (ppm_sc_code[]){PPM_SC_CHMOD, -1}, - [PPME_SYSCALL_FCHMOD_E] = (ppm_sc_code[]){PPM_SC_FCHMOD, -1}, - [PPME_SYSCALL_FCHMOD_X] = (ppm_sc_code[]){PPM_SC_FCHMOD, -1}, - [PPME_SYSCALL_RENAMEAT2_E] = (ppm_sc_code[]){PPM_SC_RENAMEAT2, -1}, - [PPME_SYSCALL_RENAMEAT2_X] = (ppm_sc_code[]){PPM_SC_RENAMEAT2, -1}, - [PPME_SYSCALL_USERFAULTFD_E] = (ppm_sc_code[]){PPM_SC_USERFAULTFD, -1}, - [PPME_SYSCALL_USERFAULTFD_X] = (ppm_sc_code[]){PPM_SC_USERFAULTFD, -1}, - [PPME_PLUGINEVENT_E] = NULL, - [PPME_PLUGINEVENT_X] = NULL, - [PPME_CONTAINER_JSON_2_E] = NULL, - [PPME_CONTAINER_JSON_2_X] = NULL, - [PPME_SYSCALL_OPENAT2_E] = (ppm_sc_code[]){PPM_SC_OPENAT2, -1}, - [PPME_SYSCALL_OPENAT2_X] = (ppm_sc_code[]){PPM_SC_OPENAT2, -1}, - [PPME_SYSCALL_MPROTECT_E] = (ppm_sc_code[]){PPM_SC_MPROTECT, -1}, - [PPME_SYSCALL_MPROTECT_X] = (ppm_sc_code[]){PPM_SC_MPROTECT, -1}, - [PPME_SYSCALL_EXECVEAT_E] = (ppm_sc_code[]){PPM_SC_EXECVEAT, -1}, - [PPME_SYSCALL_EXECVEAT_X] = (ppm_sc_code[]){PPM_SC_EXECVEAT, -1}, - [PPME_SYSCALL_COPY_FILE_RANGE_E] = (ppm_sc_code[]){PPM_SC_COPY_FILE_RANGE, -1}, - [PPME_SYSCALL_COPY_FILE_RANGE_X] = (ppm_sc_code[]){PPM_SC_COPY_FILE_RANGE, -1}, - [PPME_SYSCALL_CLONE3_E] = (ppm_sc_code[]){PPM_SC_CLONE3, -1}, - [PPME_SYSCALL_CLONE3_X] = (ppm_sc_code[]){PPM_SC_CLONE3, -1}, - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = (ppm_sc_code[]){PPM_SC_OPEN_BY_HANDLE_AT, -1}, - [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = (ppm_sc_code[]){PPM_SC_OPEN_BY_HANDLE_AT, -1}, - [PPME_SYSCALL_IO_URING_SETUP_E] = (ppm_sc_code[]){PPM_SC_IO_URING_SETUP, -1}, - [PPME_SYSCALL_IO_URING_SETUP_X] = (ppm_sc_code[]){PPM_SC_IO_URING_SETUP, -1}, - [PPME_SYSCALL_IO_URING_ENTER_E] = (ppm_sc_code[]){PPM_SC_IO_URING_ENTER, -1}, - [PPME_SYSCALL_IO_URING_ENTER_X] = (ppm_sc_code[]){PPM_SC_IO_URING_ENTER, -1}, - [PPME_SYSCALL_IO_URING_REGISTER_E] = (ppm_sc_code[]){PPM_SC_IO_URING_REGISTER, -1}, - [PPME_SYSCALL_IO_URING_REGISTER_X] = (ppm_sc_code[]){PPM_SC_IO_URING_REGISTER, -1}, - [PPME_SYSCALL_MLOCK_E] = (ppm_sc_code[]){PPM_SC_MLOCK, -1}, - [PPME_SYSCALL_MLOCK_X] = (ppm_sc_code[]){PPM_SC_MLOCK, -1}, - [PPME_SYSCALL_MUNLOCK_E] = (ppm_sc_code[]){PPM_SC_MUNLOCK, -1}, - [PPME_SYSCALL_MUNLOCK_X] = (ppm_sc_code[]){PPM_SC_MUNLOCK, -1}, - [PPME_SYSCALL_MLOCKALL_E] = (ppm_sc_code[]){PPM_SC_MLOCKALL, -1}, - [PPME_SYSCALL_MLOCKALL_X] = (ppm_sc_code[]){PPM_SC_MLOCKALL, -1}, - [PPME_SYSCALL_MUNLOCKALL_E] = (ppm_sc_code[]){PPM_SC_MUNLOCKALL, -1}, - [PPME_SYSCALL_MUNLOCKALL_X] = (ppm_sc_code[]){PPM_SC_MUNLOCKALL, -1}, - [PPME_SYSCALL_CAPSET_E] = (ppm_sc_code[]){PPM_SC_CAPSET, -1}, - [PPME_SYSCALL_CAPSET_X] = (ppm_sc_code[]){PPM_SC_CAPSET, -1}, - [PPME_USER_ADDED_E] = NULL, - [PPME_USER_ADDED_X] = NULL, - [PPME_USER_DELETED_E] = NULL, - [PPME_USER_DELETED_X] = NULL, - [PPME_GROUP_ADDED_E] = NULL, - [PPME_GROUP_ADDED_X] = NULL, - [PPME_GROUP_DELETED_E] = NULL, - [PPME_GROUP_DELETED_X] = NULL, - [PPME_SYSCALL_DUP2_E] = (ppm_sc_code[]){PPM_SC_DUP2, -1}, - [PPME_SYSCALL_DUP2_X] = (ppm_sc_code[]){PPM_SC_DUP2, -1}, - [PPME_SYSCALL_DUP3_E] = (ppm_sc_code[]){PPM_SC_DUP3, -1}, - [PPME_SYSCALL_DUP3_X] = (ppm_sc_code[]){PPM_SC_DUP3, -1}, - [PPME_SYSCALL_DUP_1_E] = (ppm_sc_code[]){PPM_SC_DUP, -1}, - [PPME_SYSCALL_DUP_1_X] = (ppm_sc_code[]){PPM_SC_DUP, -1}, - [PPME_SYSCALL_BPF_2_E] = (ppm_sc_code[]){PPM_SC_BPF, -1}, - [PPME_SYSCALL_BPF_2_X] = (ppm_sc_code[]){PPM_SC_BPF, -1}, - [PPME_SYSCALL_MLOCK2_E] = (ppm_sc_code[]){PPM_SC_MLOCK2, -1}, - [PPME_SYSCALL_MLOCK2_X] = (ppm_sc_code[]){PPM_SC_MLOCK2, -1}, - [PPME_SYSCALL_FSCONFIG_E] = (ppm_sc_code[]){PPM_SC_FSCONFIG, -1}, - [PPME_SYSCALL_FSCONFIG_X] = (ppm_sc_code[]){PPM_SC_FSCONFIG, -1}, - [PPME_SYSCALL_EPOLL_CREATE_E] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE, -1}, - [PPME_SYSCALL_EPOLL_CREATE_X] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE, -1}, - [PPME_SYSCALL_EPOLL_CREATE1_E] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE1, -1}, - [PPME_SYSCALL_EPOLL_CREATE1_X] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE1, -1}, - [PPME_SYSCALL_CHOWN_E] = (ppm_sc_code[]){PPM_SC_CHOWN, -1}, - [PPME_SYSCALL_CHOWN_X] = (ppm_sc_code[]){PPM_SC_CHOWN, -1}, - [PPME_SYSCALL_LCHOWN_E] = (ppm_sc_code[]){PPM_SC_LCHOWN, -1}, - [PPME_SYSCALL_LCHOWN_X] = (ppm_sc_code[]){PPM_SC_LCHOWN, -1}, - [PPME_SYSCALL_FCHOWN_E] = (ppm_sc_code[]){PPM_SC_FCHOWN, -1}, - [PPME_SYSCALL_FCHOWN_X] = (ppm_sc_code[]){PPM_SC_FCHOWN, -1}, - [PPME_SYSCALL_FCHOWNAT_E] = (ppm_sc_code[]){PPM_SC_FCHOWNAT, -1}, - [PPME_SYSCALL_FCHOWNAT_X] = (ppm_sc_code[]){PPM_SC_FCHOWNAT, -1}, - [PPME_SYSCALL_UMOUNT_1_E] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, - [PPME_SYSCALL_UMOUNT_1_X] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, - [PPME_SOCKET_ACCEPT4_6_E] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, - [PPME_SOCKET_ACCEPT4_6_X] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, - [PPME_SYSCALL_UMOUNT2_E] = (ppm_sc_code[]){PPM_SC_UMOUNT2, -1}, - [PPME_SYSCALL_UMOUNT2_X] = (ppm_sc_code[]){PPM_SC_UMOUNT2, -1}, - [PPME_SYSCALL_PIPE2_E] = (ppm_sc_code[]){PPM_SC_PIPE2, -1}, - [PPME_SYSCALL_PIPE2_X] = (ppm_sc_code[]){PPM_SC_PIPE2, -1}, - [PPME_SYSCALL_INOTIFY_INIT1_E] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT1, -1}, - [PPME_SYSCALL_INOTIFY_INIT1_X] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT1, -1}, - [PPME_SYSCALL_EVENTFD2_E] = (ppm_sc_code[]){PPM_SC_EVENTFD2, -1}, - [PPME_SYSCALL_EVENTFD2_X] = (ppm_sc_code[]){PPM_SC_EVENTFD2, -1}, - [PPME_SYSCALL_SIGNALFD4_E] = (ppm_sc_code[]){PPM_SC_SIGNALFD4, -1}, - [PPME_SYSCALL_SIGNALFD4_X] = (ppm_sc_code[]){PPM_SC_SIGNALFD4, -1}, - [PPME_ASYNCEVENT_E] = NULL, - [PPME_ASYNCEVENT_X] = NULL, - [PPME_SYSCALL_MEMFD_CREATE_E] = (ppm_sc_code[]){PPM_SC_MEMFD_CREATE,-1}, - [PPME_SYSCALL_MEMFD_CREATE_X] = (ppm_sc_code[]){PPM_SC_MEMFD_CREATE, -1}, - [PPME_SYSCALL_PIDFD_GETFD_E] = (ppm_sc_code[]){PPM_SC_PIDFD_GETFD, -1}, - [PPME_SYSCALL_PIDFD_GETFD_X] = (ppm_sc_code[]){PPM_SC_PIDFD_GETFD, -1}, - [PPME_SYSCALL_PIDFD_OPEN_E] = (ppm_sc_code[]){PPM_SC_PIDFD_OPEN, -1}, - [PPME_SYSCALL_PIDFD_OPEN_X] = (ppm_sc_code[]){PPM_SC_PIDFD_OPEN, -1}, - [PPME_SYSCALL_INIT_MODULE_E] = (ppm_sc_code[]){PPM_SC_INIT_MODULE, -1}, - [PPME_SYSCALL_INIT_MODULE_X] = (ppm_sc_code[]){PPM_SC_INIT_MODULE, -1}, - [PPME_SYSCALL_FINIT_MODULE_E] = (ppm_sc_code[]){PPM_SC_FINIT_MODULE, -1}, - [PPME_SYSCALL_FINIT_MODULE_X] = (ppm_sc_code[]){PPM_SC_FINIT_MODULE, -1}, - [PPME_SYSCALL_MKNOD_E] = (ppm_sc_code[]){PPM_SC_MKNOD, -1}, - [PPME_SYSCALL_MKNOD_X] = (ppm_sc_code[]){PPM_SC_MKNOD, -1}, - [PPME_SYSCALL_MKNODAT_E] = (ppm_sc_code[]){PPM_SC_MKNODAT, -1}, - [PPME_SYSCALL_MKNODAT_X] = (ppm_sc_code[]){PPM_SC_MKNODAT, -1}, - [PPME_SYSCALL_NEWFSTATAT_E] = (ppm_sc_code[]){PPM_SC_NEWFSTATAT, -1}, - [PPME_SYSCALL_NEWFSTATAT_X] = (ppm_sc_code[]){PPM_SC_NEWFSTATAT, -1}, - [PPME_SYSCALL_PROCESS_VM_READV_E] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_READV, -1}, - [PPME_SYSCALL_PROCESS_VM_READV_X] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_READV, -1}, - [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_WRITEV, -1}, - [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_WRITEV, -1}, - [PPME_SYSCALL_DELETE_MODULE_E] = (ppm_sc_code[]){PPM_SC_DELETE_MODULE, -1}, - [PPME_SYSCALL_DELETE_MODULE_X] = (ppm_sc_code[]){PPM_SC_DELETE_MODULE, -1}, - [PPME_SYSCALL_SETREUID_E] = (ppm_sc_code[]){PPM_SC_SETREUID, -1}, - [PPME_SYSCALL_SETREUID_X] = (ppm_sc_code[]){PPM_SC_SETREUID, -1}, - [PPME_SYSCALL_SETREGID_E] = (ppm_sc_code[]){PPM_SC_SETREGID, -1}, - [PPME_SYSCALL_SETREGID_X] = (ppm_sc_code[]){PPM_SC_SETREGID, -1}, + [PPME_GENERIC_E] = (ppm_sc_code[]){PPM_SC_RESTART_SYSCALL, + PPM_SC_EXIT, + PPM_SC_TIME, + PPM_SC_GETPID, + PPM_SC_SYNC, + PPM_SC_TIMES, + PPM_SC_ACCT, + PPM_SC_UMASK, + PPM_SC_USTAT, + PPM_SC_GETPPID, + PPM_SC_GETPGRP, + PPM_SC_SETHOSTNAME, + PPM_SC_GETRUSAGE, + PPM_SC_GETTIMEOFDAY, + PPM_SC_SETTIMEOFDAY, + PPM_SC_READLINK, + PPM_SC_SWAPON, + PPM_SC_REBOOT, + PPM_SC_TRUNCATE, + PPM_SC_FTRUNCATE, + PPM_SC_GETPRIORITY, + PPM_SC_SETPRIORITY, + PPM_SC_STATFS, + PPM_SC_FSTATFS, + PPM_SC_SETITIMER, + PPM_SC_GETITIMER, + PPM_SC_UNAME, + PPM_SC_VHANGUP, + PPM_SC_WAIT4, + PPM_SC_SWAPOFF, + PPM_SC_SYSINFO, + PPM_SC_FSYNC, + PPM_SC_SETDOMAINNAME, + PPM_SC_ADJTIMEX, + PPM_SC_GETPGID, + PPM_SC_SYSFS, + PPM_SC_PERSONALITY, + PPM_SC_MSYNC, + PPM_SC_GETSID, + PPM_SC_FDATASYNC, + PPM_SC_SCHED_SETSCHEDULER, + PPM_SC_SCHED_GETSCHEDULER, + PPM_SC_SCHED_YIELD, + PPM_SC_SCHED_GET_PRIORITY_MAX, + PPM_SC_SCHED_GET_PRIORITY_MIN, + PPM_SC_SCHED_RR_GET_INTERVAL, + PPM_SC_MREMAP, + PPM_SC_ARCH_PRCTL, + PPM_SC_RT_SIGACTION, + PPM_SC_RT_SIGPROCMASK, + PPM_SC_RT_SIGPENDING, + PPM_SC_RT_SIGTIMEDWAIT, + PPM_SC_RT_SIGQUEUEINFO, + PPM_SC_RT_SIGSUSPEND, + PPM_SC_CAPGET, + PPM_SC_GETGROUPS, + PPM_SC_SETGROUPS, + PPM_SC_SETFSUID, + PPM_SC_SETFSGID, + PPM_SC_PIVOT_ROOT, + PPM_SC_MINCORE, + PPM_SC_MADVISE, + PPM_SC_GETTID, + PPM_SC_SETXATTR, + PPM_SC_LSETXATTR, + PPM_SC_FSETXATTR, + PPM_SC_GETXATTR, + PPM_SC_LGETXATTR, + PPM_SC_FGETXATTR, + PPM_SC_LISTXATTR, + PPM_SC_LLISTXATTR, + PPM_SC_FLISTXATTR, + PPM_SC_REMOVEXATTR, + PPM_SC_LREMOVEXATTR, + PPM_SC_FREMOVEXATTR, + PPM_SC_SCHED_SETAFFINITY, + PPM_SC_SCHED_GETAFFINITY, + PPM_SC_SET_THREAD_AREA, + PPM_SC_GET_THREAD_AREA, + PPM_SC_IO_SETUP, + PPM_SC_IO_DESTROY, + PPM_SC_IO_GETEVENTS, + PPM_SC_IO_SUBMIT, + PPM_SC_IO_CANCEL, + PPM_SC_EXIT_GROUP, + PPM_SC_REMAP_FILE_PAGES, + PPM_SC_SET_TID_ADDRESS, + PPM_SC_TIMER_CREATE, + PPM_SC_TIMER_SETTIME, + PPM_SC_TIMER_GETTIME, + PPM_SC_TIMER_GETOVERRUN, + PPM_SC_TIMER_DELETE, + PPM_SC_CLOCK_SETTIME, + PPM_SC_CLOCK_GETTIME, + PPM_SC_CLOCK_GETRES, + PPM_SC_CLOCK_NANOSLEEP, + PPM_SC_UTIMES, + PPM_SC_MQ_OPEN, + PPM_SC_MQ_UNLINK, + PPM_SC_MQ_TIMEDSEND, + PPM_SC_MQ_TIMEDRECEIVE, + PPM_SC_MQ_NOTIFY, + PPM_SC_MQ_GETSETATTR, + PPM_SC_KEXEC_LOAD, + PPM_SC_WAITID, + PPM_SC_ADD_KEY, + PPM_SC_REQUEST_KEY, + PPM_SC_KEYCTL, + PPM_SC_IOPRIO_SET, + PPM_SC_IOPRIO_GET, + PPM_SC_INOTIFY_ADD_WATCH, + PPM_SC_INOTIFY_RM_WATCH, + PPM_SC_FUTIMESAT, + PPM_SC_READLINKAT, + PPM_SC_FACCESSAT, + PPM_SC_SET_ROBUST_LIST, + PPM_SC_GET_ROBUST_LIST, + PPM_SC_TEE, + PPM_SC_VMSPLICE, + PPM_SC_GETCPU, + PPM_SC_EPOLL_PWAIT, + PPM_SC_UTIMENSAT, + PPM_SC_TIMERFD_SETTIME, + PPM_SC_TIMERFD_GETTIME, + PPM_SC_RT_TGSIGQUEUEINFO, + PPM_SC_PERF_EVENT_OPEN, + PPM_SC_FANOTIFY_INIT, + PPM_SC_CLOCK_ADJTIME, + PPM_SC_SYNCFS, + PPM_SC_MSGSND, + PPM_SC_MSGRCV, + PPM_SC_MSGGET, + PPM_SC_MSGCTL, + PPM_SC_SHMDT, + PPM_SC_SHMGET, + PPM_SC_SHMCTL, + PPM_SC_STATFS64, + PPM_SC_FSTATFS64, + PPM_SC_FSTATAT64, + PPM_SC_BDFLUSH, + PPM_SC_SIGPROCMASK, + PPM_SC_IPC, + PPM_SC__NEWSELECT, + PPM_SC_SGETMASK, + PPM_SC_SSETMASK, + PPM_SC_SIGPENDING, + PPM_SC_OLDUNAME, + PPM_SC_SIGNAL, + PPM_SC_NICE, + PPM_SC_STIME, + PPM_SC_WAITPID, + PPM_SC_SHMAT, + PPM_SC_RT_SIGRETURN, + PPM_SC_FALLOCATE, + PPM_SC_SIGALTSTACK, + PPM_SC_GETRANDOM, + PPM_SC_FADVISE64, + PPM_SC_SOCKETCALL, + PPM_SC_FSPICK, + PPM_SC_FSMOUNT, + PPM_SC_FSOPEN, + PPM_SC_OPEN_TREE, + PPM_SC_MOVE_MOUNT, + PPM_SC_MOUNT_SETATTR, + PPM_SC_MEMFD_SECRET, + PPM_SC_IOPERM, + PPM_SC_KEXEC_FILE_LOAD, + PPM_SC_PIDFD_SEND_SIGNAL, + PPM_SC_PKEY_ALLOC, + PPM_SC_PKEY_MPROTECT, + PPM_SC_PKEY_FREE, + PPM_SC_LANDLOCK_CREATE_RULESET, + PPM_SC_QUOTACTL_FD, + PPM_SC_LANDLOCK_RESTRICT_SELF, + PPM_SC_LANDLOCK_ADD_RULE, + PPM_SC_EPOLL_PWAIT2, + PPM_SC_MIGRATE_PAGES, + PPM_SC_MOVE_PAGES, + PPM_SC_PREADV2, + PPM_SC_PWRITEV2, + PPM_SC_QUERY_MODULE, + PPM_SC_STATX, + PPM_SC_SET_MEMPOLICY, + PPM_SC_FANOTIFY_MARK, + PPM_SC_SYNC_FILE_RANGE, + PPM_SC_READAHEAD, + PPM_SC_PROCESS_MRELEASE, + PPM_SC_MBIND, + PPM_SC_PROCESS_MADVISE, + PPM_SC_MEMBARRIER, + PPM_SC_MODIFY_LDT, + PPM_SC_SEMTIMEDOP, + PPM_SC_NAME_TO_HANDLE_AT, + PPM_SC_KCMP, + PPM_SC_EPOLL_CTL_OLD, + PPM_SC_EPOLL_WAIT_OLD, + PPM_SC_FUTEX_WAITV, + PPM_SC_CREATE_MODULE, + PPM_SC__SYSCTL, + PPM_SC_LOOKUP_DCOOKIE, + PPM_SC_IOPL, + PPM_SC_IO_PGETEVENTS, + PPM_SC_GETPMSG, + PPM_SC_SCHED_SETATTR, + PPM_SC_GET_KERNEL_SYMS, + PPM_SC_RSEQ, + PPM_SC_CLOSE_RANGE, + PPM_SC_GET_MEMPOLICY, + PPM_SC_SCHED_GETATTR, + PPM_SC_NFSSERVCTL, + PPM_SC_SET_MEMPOLICY_HOME_NODE, + PPM_SC_FACCESSAT2, + PPM_SC_EPOLL_CTL, + PPM_SC_SCHED_GETPARAM, + PPM_SC_PSELECT6, + PPM_SC_SCHED_SETPARAM, + PPM_SC_PAUSE, + PPM_SC_UTIME, + PPM_SC_SYSLOG, + PPM_SC_USELIB, + PPM_SC_ALARM, + PPM_SC_SIGSUSPEND, + PPM_SC_IDLE, + PPM_SC_S390_RUNTIME_INSTR, + PPM_SC_SIGRETURN, + PPM_SC_S390_GUARDED_STORAGE, + PPM_SC_TIMERFD, + PPM_SC_S390_PCI_MMIO_READ, + PPM_SC_SIGACTION, + PPM_SC_S390_PCI_MMIO_WRITE, + PPM_SC_READDIR, + PPM_SC_S390_STHYI, + PPM_SC_CACHESTAT, + PPM_SC_FCHMODAT2, + PPM_SC_MAP_SHADOW_STACK, + PPM_SC_RISCV_FLUSH_ICACHE, + PPM_SC_RISCV_HWPROBE, + PPM_SC_FUTEX_WAKE, + PPM_SC_FUTEX_REQUEUE, + PPM_SC_FUTEX_WAIT, + PPM_SC_SYNC_FILE_RANGE2, + PPM_SC_OLDFSTAT, + PPM_SC_SPU_RUN, + PPM_SC_SWAPCONTEXT, + PPM_SC_OLDLSTAT, + PPM_SC_SPU_CREATE, + PPM_SC_PCICONFIG_READ, + PPM_SC_SYS_DEBUG_SETCONTEXT, + PPM_SC_VM86, + PPM_SC_PCICONFIG_WRITE, + PPM_SC_RTAS, + PPM_SC_PCICONFIG_IOBASE, + PPM_SC_OLDOLDUNAME, + PPM_SC_SUBPAGE_PROT, + PPM_SC_MULTIPLEXER, + PPM_SC_OLDSTAT, + PPM_SC_SWITCH_ENDIAN, + PPM_SC_LISTMOUNT, + PPM_SC_STATMOUNT, + PPM_SC_LSM_GET_SELF_ATTR, + PPM_SC_LSM_SET_SELF_ATTR, + PPM_SC_LSM_LIST_MODULES, + PPM_SC_MSEAL, + PPM_SC_URETPROBE, + -1}, + [PPME_GENERIC_X] = (ppm_sc_code[]){PPM_SC_RESTART_SYSCALL, + PPM_SC_EXIT, + PPM_SC_TIME, + PPM_SC_GETPID, + PPM_SC_SYNC, + PPM_SC_TIMES, + PPM_SC_ACCT, + PPM_SC_UMASK, + PPM_SC_USTAT, + PPM_SC_GETPPID, + PPM_SC_GETPGRP, + PPM_SC_SETHOSTNAME, + PPM_SC_GETRUSAGE, + PPM_SC_GETTIMEOFDAY, + PPM_SC_SETTIMEOFDAY, + PPM_SC_READLINK, + PPM_SC_SWAPON, + PPM_SC_REBOOT, + PPM_SC_TRUNCATE, + PPM_SC_FTRUNCATE, + PPM_SC_GETPRIORITY, + PPM_SC_SETPRIORITY, + PPM_SC_STATFS, + PPM_SC_FSTATFS, + PPM_SC_SETITIMER, + PPM_SC_GETITIMER, + PPM_SC_UNAME, + PPM_SC_VHANGUP, + PPM_SC_WAIT4, + PPM_SC_SWAPOFF, + PPM_SC_SYSINFO, + PPM_SC_FSYNC, + PPM_SC_SETDOMAINNAME, + PPM_SC_ADJTIMEX, + PPM_SC_GETPGID, + PPM_SC_SYSFS, + PPM_SC_PERSONALITY, + PPM_SC_MSYNC, + PPM_SC_GETSID, + PPM_SC_FDATASYNC, + PPM_SC_SCHED_SETSCHEDULER, + PPM_SC_SCHED_GETSCHEDULER, + PPM_SC_SCHED_YIELD, + PPM_SC_SCHED_GET_PRIORITY_MAX, + PPM_SC_SCHED_GET_PRIORITY_MIN, + PPM_SC_SCHED_RR_GET_INTERVAL, + PPM_SC_MREMAP, + PPM_SC_ARCH_PRCTL, + PPM_SC_RT_SIGACTION, + PPM_SC_RT_SIGPROCMASK, + PPM_SC_RT_SIGPENDING, + PPM_SC_RT_SIGTIMEDWAIT, + PPM_SC_RT_SIGQUEUEINFO, + PPM_SC_RT_SIGSUSPEND, + PPM_SC_CAPGET, + PPM_SC_GETGROUPS, + PPM_SC_SETGROUPS, + PPM_SC_SETFSUID, + PPM_SC_SETFSGID, + PPM_SC_PIVOT_ROOT, + PPM_SC_MINCORE, + PPM_SC_MADVISE, + PPM_SC_GETTID, + PPM_SC_SETXATTR, + PPM_SC_LSETXATTR, + PPM_SC_FSETXATTR, + PPM_SC_GETXATTR, + PPM_SC_LGETXATTR, + PPM_SC_FGETXATTR, + PPM_SC_LISTXATTR, + PPM_SC_LLISTXATTR, + PPM_SC_FLISTXATTR, + PPM_SC_REMOVEXATTR, + PPM_SC_LREMOVEXATTR, + PPM_SC_FREMOVEXATTR, + PPM_SC_SCHED_SETAFFINITY, + PPM_SC_SCHED_GETAFFINITY, + PPM_SC_SET_THREAD_AREA, + PPM_SC_GET_THREAD_AREA, + PPM_SC_IO_SETUP, + PPM_SC_IO_DESTROY, + PPM_SC_IO_GETEVENTS, + PPM_SC_IO_SUBMIT, + PPM_SC_IO_CANCEL, + PPM_SC_EXIT_GROUP, + PPM_SC_REMAP_FILE_PAGES, + PPM_SC_SET_TID_ADDRESS, + PPM_SC_TIMER_CREATE, + PPM_SC_TIMER_SETTIME, + PPM_SC_TIMER_GETTIME, + PPM_SC_TIMER_GETOVERRUN, + PPM_SC_TIMER_DELETE, + PPM_SC_CLOCK_SETTIME, + PPM_SC_CLOCK_GETTIME, + PPM_SC_CLOCK_GETRES, + PPM_SC_CLOCK_NANOSLEEP, + PPM_SC_UTIMES, + PPM_SC_MQ_OPEN, + PPM_SC_MQ_UNLINK, + PPM_SC_MQ_TIMEDSEND, + PPM_SC_MQ_TIMEDRECEIVE, + PPM_SC_MQ_NOTIFY, + PPM_SC_MQ_GETSETATTR, + PPM_SC_KEXEC_LOAD, + PPM_SC_WAITID, + PPM_SC_ADD_KEY, + PPM_SC_REQUEST_KEY, + PPM_SC_KEYCTL, + PPM_SC_IOPRIO_SET, + PPM_SC_IOPRIO_GET, + PPM_SC_INOTIFY_ADD_WATCH, + PPM_SC_INOTIFY_RM_WATCH, + PPM_SC_FUTIMESAT, + PPM_SC_READLINKAT, + PPM_SC_FACCESSAT, + PPM_SC_SET_ROBUST_LIST, + PPM_SC_GET_ROBUST_LIST, + PPM_SC_TEE, + PPM_SC_VMSPLICE, + PPM_SC_GETCPU, + PPM_SC_EPOLL_PWAIT, + PPM_SC_UTIMENSAT, + PPM_SC_TIMERFD_SETTIME, + PPM_SC_TIMERFD_GETTIME, + PPM_SC_RT_TGSIGQUEUEINFO, + PPM_SC_PERF_EVENT_OPEN, + PPM_SC_FANOTIFY_INIT, + PPM_SC_CLOCK_ADJTIME, + PPM_SC_SYNCFS, + PPM_SC_MSGSND, + PPM_SC_MSGRCV, + PPM_SC_MSGGET, + PPM_SC_MSGCTL, + PPM_SC_SHMDT, + PPM_SC_SHMGET, + PPM_SC_SHMCTL, + PPM_SC_STATFS64, + PPM_SC_FSTATFS64, + PPM_SC_FSTATAT64, + PPM_SC_BDFLUSH, + PPM_SC_SIGPROCMASK, + PPM_SC_IPC, + PPM_SC__NEWSELECT, + PPM_SC_SGETMASK, + PPM_SC_SSETMASK, + PPM_SC_SIGPENDING, + PPM_SC_OLDUNAME, + PPM_SC_SIGNAL, + PPM_SC_NICE, + PPM_SC_STIME, + PPM_SC_WAITPID, + PPM_SC_SHMAT, + PPM_SC_RT_SIGRETURN, + PPM_SC_FALLOCATE, + PPM_SC_SIGALTSTACK, + PPM_SC_GETRANDOM, + PPM_SC_FADVISE64, + PPM_SC_SOCKETCALL, + PPM_SC_FSPICK, + PPM_SC_FSMOUNT, + PPM_SC_FSOPEN, + PPM_SC_OPEN_TREE, + PPM_SC_MOVE_MOUNT, + PPM_SC_MOUNT_SETATTR, + PPM_SC_MEMFD_SECRET, + PPM_SC_IOPERM, + PPM_SC_KEXEC_FILE_LOAD, + PPM_SC_PIDFD_SEND_SIGNAL, + PPM_SC_PKEY_ALLOC, + PPM_SC_PKEY_MPROTECT, + PPM_SC_PKEY_FREE, + PPM_SC_LANDLOCK_CREATE_RULESET, + PPM_SC_QUOTACTL_FD, + PPM_SC_LANDLOCK_RESTRICT_SELF, + PPM_SC_LANDLOCK_ADD_RULE, + PPM_SC_EPOLL_PWAIT2, + PPM_SC_MIGRATE_PAGES, + PPM_SC_MOVE_PAGES, + PPM_SC_PREADV2, + PPM_SC_PWRITEV2, + PPM_SC_QUERY_MODULE, + PPM_SC_STATX, + PPM_SC_SET_MEMPOLICY, + PPM_SC_FANOTIFY_MARK, + PPM_SC_SYNC_FILE_RANGE, + PPM_SC_READAHEAD, + PPM_SC_PROCESS_MRELEASE, + PPM_SC_MBIND, + PPM_SC_PROCESS_MADVISE, + PPM_SC_MEMBARRIER, + PPM_SC_MODIFY_LDT, + PPM_SC_SEMTIMEDOP, + PPM_SC_NAME_TO_HANDLE_AT, + PPM_SC_KCMP, + PPM_SC_EPOLL_CTL_OLD, + PPM_SC_EPOLL_WAIT_OLD, + PPM_SC_FUTEX_WAITV, + PPM_SC_CREATE_MODULE, + PPM_SC__SYSCTL, + PPM_SC_LOOKUP_DCOOKIE, + PPM_SC_IOPL, + PPM_SC_IO_PGETEVENTS, + PPM_SC_GETPMSG, + PPM_SC_SCHED_SETATTR, + PPM_SC_GET_KERNEL_SYMS, + PPM_SC_RSEQ, + PPM_SC_CLOSE_RANGE, + PPM_SC_GET_MEMPOLICY, + PPM_SC_SCHED_GETATTR, + PPM_SC_NFSSERVCTL, + PPM_SC_SET_MEMPOLICY_HOME_NODE, + PPM_SC_FACCESSAT2, + PPM_SC_EPOLL_CTL, + PPM_SC_SCHED_GETPARAM, + PPM_SC_PSELECT6, + PPM_SC_SCHED_SETPARAM, + PPM_SC_PAUSE, + PPM_SC_UTIME, + PPM_SC_SYSLOG, + PPM_SC_USELIB, + PPM_SC_ALARM, + PPM_SC_TIMERFD, + PPM_SC_S390_PCI_MMIO_READ, + PPM_SC_SIGACTION, + PPM_SC_S390_PCI_MMIO_WRITE, + PPM_SC_READDIR, + PPM_SC_S390_STHYI, + PPM_SC_SIGSUSPEND, + PPM_SC_IDLE, + PPM_SC_S390_RUNTIME_INSTR, + PPM_SC_SIGRETURN, + PPM_SC_S390_GUARDED_STORAGE, + PPM_SC_CACHESTAT, + PPM_SC_FCHMODAT2, + PPM_SC_MAP_SHADOW_STACK, + PPM_SC_RISCV_FLUSH_ICACHE, + PPM_SC_RISCV_HWPROBE, + PPM_SC_FUTEX_WAKE, + PPM_SC_FUTEX_REQUEUE, + PPM_SC_FUTEX_WAIT, + PPM_SC_OLDOLDUNAME, + PPM_SC_SUBPAGE_PROT, + PPM_SC_PCICONFIG_IOBASE, + PPM_SC_OLDSTAT, + PPM_SC_SWITCH_ENDIAN, + PPM_SC_MULTIPLEXER, + PPM_SC_OLDLSTAT, + PPM_SC_SPU_CREATE, + PPM_SC_SYNC_FILE_RANGE2, + PPM_SC_OLDFSTAT, + PPM_SC_SPU_RUN, + PPM_SC_SWAPCONTEXT, + PPM_SC_PCICONFIG_WRITE, + PPM_SC_RTAS, + PPM_SC_PCICONFIG_READ, + PPM_SC_SYS_DEBUG_SETCONTEXT, + PPM_SC_VM86, + PPM_SC_LSM_SET_SELF_ATTR, + PPM_SC_LSM_LIST_MODULES, + PPM_SC_LISTMOUNT, + PPM_SC_STATMOUNT, + PPM_SC_LSM_GET_SELF_ATTR, + PPM_SC_MSEAL, + PPM_SC_URETPROBE, + -1}, + [PPME_SYSCALL_OPEN_E] = (ppm_sc_code[]){PPM_SC_OPEN, -1}, + [PPME_SYSCALL_OPEN_X] = (ppm_sc_code[]){PPM_SC_OPEN, -1}, + [PPME_SYSCALL_CLOSE_E] = (ppm_sc_code[]){PPM_SC_CLOSE, -1}, + [PPME_SYSCALL_CLOSE_X] = (ppm_sc_code[]){PPM_SC_CLOSE, -1}, + [PPME_SYSCALL_READ_E] = (ppm_sc_code[]){PPM_SC_READ, -1}, + [PPME_SYSCALL_READ_X] = (ppm_sc_code[]){PPM_SC_READ, -1}, + [PPME_SYSCALL_WRITE_E] = (ppm_sc_code[]){PPM_SC_WRITE, -1}, + [PPME_SYSCALL_WRITE_X] = (ppm_sc_code[]){PPM_SC_WRITE, -1}, + [PPME_SYSCALL_BRK_1_E] = (ppm_sc_code[]){PPM_SC_BRK, -1}, + [PPME_SYSCALL_BRK_1_X] = (ppm_sc_code[]){PPM_SC_BRK, -1}, + [PPME_SYSCALL_EXECVE_8_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_8_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_CLONE_11_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_CLONE_11_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_PRCTL_E] = (ppm_sc_code[]){PPM_SC_PRCTL, -1}, + [PPME_SYSCALL_PRCTL_X] = (ppm_sc_code[]){PPM_SC_PRCTL, -1}, + [PPME_PROCEXIT_E] = (ppm_sc_code[]){PPM_SC_SCHED_PROCESS_EXIT, -1}, + [PPME_PROCEXIT_X] = NULL, + [PPME_SOCKET_SOCKET_E] = (ppm_sc_code[]){PPM_SC_SOCKET, -1}, + [PPME_SOCKET_SOCKET_X] = (ppm_sc_code[]){PPM_SC_SOCKET, -1}, + [PPME_SOCKET_BIND_E] = (ppm_sc_code[]){PPM_SC_BIND, -1}, + [PPME_SOCKET_BIND_X] = (ppm_sc_code[]){PPM_SC_BIND, -1}, + [PPME_SOCKET_CONNECT_E] = (ppm_sc_code[]){PPM_SC_CONNECT, -1}, + [PPME_SOCKET_CONNECT_X] = (ppm_sc_code[]){PPM_SC_CONNECT, -1}, + [PPME_SOCKET_LISTEN_E] = (ppm_sc_code[]){PPM_SC_LISTEN, -1}, + [PPME_SOCKET_LISTEN_X] = (ppm_sc_code[]){PPM_SC_LISTEN, -1}, + [PPME_SOCKET_ACCEPT_E] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, + [PPME_SOCKET_ACCEPT_X] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, + [PPME_SOCKET_SEND_E] = (ppm_sc_code[]){PPM_SC_SEND, -1}, + [PPME_SOCKET_SEND_X] = (ppm_sc_code[]){PPM_SC_SEND, -1}, + [PPME_SOCKET_SENDTO_E] = (ppm_sc_code[]){PPM_SC_SENDTO, -1}, + [PPME_SOCKET_SENDTO_X] = (ppm_sc_code[]){PPM_SC_SENDTO, -1}, + [PPME_SOCKET_RECV_E] = (ppm_sc_code[]){PPM_SC_RECV, -1}, + [PPME_SOCKET_RECV_X] = (ppm_sc_code[]){PPM_SC_RECV, -1}, + [PPME_SOCKET_RECVFROM_E] = (ppm_sc_code[]){PPM_SC_RECVFROM, -1}, + [PPME_SOCKET_RECVFROM_X] = (ppm_sc_code[]){PPM_SC_RECVFROM, -1}, + [PPME_SOCKET_SHUTDOWN_E] = (ppm_sc_code[]){PPM_SC_SHUTDOWN, -1}, + [PPME_SOCKET_SHUTDOWN_X] = (ppm_sc_code[]){PPM_SC_SHUTDOWN, -1}, + [PPME_SOCKET_GETSOCKNAME_E] = (ppm_sc_code[]){PPM_SC_GETSOCKNAME, -1}, + [PPME_SOCKET_GETSOCKNAME_X] = (ppm_sc_code[]){PPM_SC_GETSOCKNAME, -1}, + [PPME_SOCKET_GETPEERNAME_E] = (ppm_sc_code[]){PPM_SC_GETPEERNAME, -1}, + [PPME_SOCKET_GETPEERNAME_X] = (ppm_sc_code[]){PPM_SC_GETPEERNAME, -1}, + [PPME_SOCKET_SOCKETPAIR_E] = (ppm_sc_code[]){PPM_SC_SOCKETPAIR, -1}, + [PPME_SOCKET_SOCKETPAIR_X] = (ppm_sc_code[]){PPM_SC_SOCKETPAIR, -1}, + [PPME_SOCKET_SETSOCKOPT_E] = (ppm_sc_code[]){PPM_SC_SETSOCKOPT, -1}, + [PPME_SOCKET_SETSOCKOPT_X] = (ppm_sc_code[]){PPM_SC_SETSOCKOPT, -1}, + [PPME_SOCKET_GETSOCKOPT_E] = (ppm_sc_code[]){PPM_SC_GETSOCKOPT, -1}, + [PPME_SOCKET_GETSOCKOPT_X] = (ppm_sc_code[]){PPM_SC_GETSOCKOPT, -1}, + [PPME_SOCKET_SENDMSG_E] = (ppm_sc_code[]){PPM_SC_SENDMSG, -1}, + [PPME_SOCKET_SENDMSG_X] = (ppm_sc_code[]){PPM_SC_SENDMSG, -1}, + [PPME_SOCKET_SENDMMSG_E] = (ppm_sc_code[]){PPM_SC_SENDMMSG, -1}, + [PPME_SOCKET_SENDMMSG_X] = (ppm_sc_code[]){PPM_SC_SENDMMSG, -1}, + [PPME_SOCKET_RECVMSG_E] = (ppm_sc_code[]){PPM_SC_RECVMSG, -1}, + [PPME_SOCKET_RECVMSG_X] = (ppm_sc_code[]){PPM_SC_RECVMSG, -1}, + [PPME_SOCKET_RECVMMSG_E] = (ppm_sc_code[]){PPM_SC_RECVMMSG, -1}, + [PPME_SOCKET_RECVMMSG_X] = (ppm_sc_code[]){PPM_SC_RECVMMSG, -1}, + [PPME_SOCKET_ACCEPT4_E] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, + [PPME_SOCKET_ACCEPT4_X] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, + [PPME_SYSCALL_CREAT_E] = (ppm_sc_code[]){PPM_SC_CREAT, -1}, + [PPME_SYSCALL_CREAT_X] = (ppm_sc_code[]){PPM_SC_CREAT, -1}, + [PPME_SYSCALL_PIPE_E] = (ppm_sc_code[]){PPM_SC_PIPE, -1}, + [PPME_SYSCALL_PIPE_X] = (ppm_sc_code[]){PPM_SC_PIPE, -1}, + [PPME_SYSCALL_EVENTFD_E] = (ppm_sc_code[]){PPM_SC_EVENTFD, -1}, + [PPME_SYSCALL_EVENTFD_X] = (ppm_sc_code[]){PPM_SC_EVENTFD, -1}, + [PPME_SYSCALL_FUTEX_E] = (ppm_sc_code[]){PPM_SC_FUTEX, -1}, + [PPME_SYSCALL_FUTEX_X] = (ppm_sc_code[]){PPM_SC_FUTEX, -1}, + [PPME_SYSCALL_STAT_E] = (ppm_sc_code[]){PPM_SC_STAT, -1}, + [PPME_SYSCALL_STAT_X] = (ppm_sc_code[]){PPM_SC_STAT, -1}, + [PPME_SYSCALL_LSTAT_E] = (ppm_sc_code[]){PPM_SC_LSTAT, -1}, + [PPME_SYSCALL_LSTAT_X] = (ppm_sc_code[]){PPM_SC_LSTAT, -1}, + [PPME_SYSCALL_FSTAT_E] = (ppm_sc_code[]){PPM_SC_FSTAT, -1}, + [PPME_SYSCALL_FSTAT_X] = (ppm_sc_code[]){PPM_SC_FSTAT, -1}, + [PPME_SYSCALL_STAT64_E] = (ppm_sc_code[]){PPM_SC_STAT64, -1}, + [PPME_SYSCALL_STAT64_X] = (ppm_sc_code[]){PPM_SC_STAT64, -1}, + [PPME_SYSCALL_LSTAT64_E] = + (ppm_sc_code[]){PPM_SC_LSTAT64, -1}, // lstat64 -> is not impl by supported archs + [PPME_SYSCALL_LSTAT64_X] = + (ppm_sc_code[]){PPM_SC_LSTAT64, -1}, // lstat64 -> is not impl by supported archs + [PPME_SYSCALL_FSTAT64_E] = (ppm_sc_code[]){PPM_SC_FSTAT64, -1}, + [PPME_SYSCALL_FSTAT64_X] = (ppm_sc_code[]){PPM_SC_FSTAT64, -1}, + [PPME_SYSCALL_EPOLLWAIT_E] = (ppm_sc_code[]){PPM_SC_EPOLL_WAIT, -1}, + [PPME_SYSCALL_EPOLLWAIT_X] = (ppm_sc_code[]){PPM_SC_EPOLL_WAIT, -1}, + [PPME_SYSCALL_POLL_E] = (ppm_sc_code[]){PPM_SC_POLL, -1}, + [PPME_SYSCALL_POLL_X] = (ppm_sc_code[]){PPM_SC_POLL, -1}, + [PPME_SYSCALL_SELECT_E] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, + [PPME_SYSCALL_SELECT_X] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, + [PPME_SYSCALL_NEWSELECT_E] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, + [PPME_SYSCALL_NEWSELECT_X] = (ppm_sc_code[]){PPM_SC_SELECT, -1}, + [PPME_SYSCALL_LSEEK_E] = (ppm_sc_code[]){PPM_SC_LSEEK, -1}, + [PPME_SYSCALL_LSEEK_X] = (ppm_sc_code[]){PPM_SC_LSEEK, -1}, + [PPME_SYSCALL_LLSEEK_E] = (ppm_sc_code[]){PPM_SC__LLSEEK, -1}, + [PPME_SYSCALL_LLSEEK_X] = (ppm_sc_code[]){PPM_SC__LLSEEK, -1}, + [PPME_SYSCALL_IOCTL_2_E] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, + [PPME_SYSCALL_IOCTL_2_X] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, + [PPME_SYSCALL_GETCWD_E] = (ppm_sc_code[]){PPM_SC_GETCWD, -1}, + [PPME_SYSCALL_GETCWD_X] = (ppm_sc_code[]){PPM_SC_GETCWD, -1}, + [PPME_SYSCALL_CHDIR_E] = (ppm_sc_code[]){PPM_SC_CHDIR, -1}, + [PPME_SYSCALL_CHDIR_X] = (ppm_sc_code[]){PPM_SC_CHDIR, -1}, + [PPME_SYSCALL_FCHDIR_E] = (ppm_sc_code[]){PPM_SC_FCHDIR, -1}, + [PPME_SYSCALL_FCHDIR_X] = (ppm_sc_code[]){PPM_SC_FCHDIR, -1}, + [PPME_SYSCALL_MKDIR_E] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, + [PPME_SYSCALL_MKDIR_X] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, + [PPME_SYSCALL_RMDIR_E] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, + [PPME_SYSCALL_RMDIR_X] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, + [PPME_SYSCALL_OPENAT_E] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, + [PPME_SYSCALL_OPENAT_X] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, + [PPME_SYSCALL_LINK_E] = (ppm_sc_code[]){PPM_SC_LINK, -1}, + [PPME_SYSCALL_LINK_X] = (ppm_sc_code[]){PPM_SC_LINK, -1}, + [PPME_SYSCALL_LINKAT_E] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, + [PPME_SYSCALL_LINKAT_X] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, + [PPME_SYSCALL_UNLINK_E] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, + [PPME_SYSCALL_UNLINK_X] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, + [PPME_SYSCALL_UNLINKAT_E] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, + [PPME_SYSCALL_UNLINKAT_X] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, + [PPME_SYSCALL_PREAD_E] = (ppm_sc_code[]){PPM_SC_PREAD64, -1}, + [PPME_SYSCALL_PREAD_X] = (ppm_sc_code[]){PPM_SC_PREAD64, -1}, + [PPME_SYSCALL_PWRITE_E] = (ppm_sc_code[]){PPM_SC_PWRITE64, -1}, + [PPME_SYSCALL_PWRITE_X] = (ppm_sc_code[]){PPM_SC_PWRITE64, -1}, + [PPME_SYSCALL_READV_E] = (ppm_sc_code[]){PPM_SC_READV, -1}, + [PPME_SYSCALL_READV_X] = (ppm_sc_code[]){PPM_SC_READV, -1}, + [PPME_SYSCALL_WRITEV_E] = (ppm_sc_code[]){PPM_SC_WRITEV, -1}, + [PPME_SYSCALL_WRITEV_X] = (ppm_sc_code[]){PPM_SC_WRITEV, -1}, + [PPME_SYSCALL_PREADV_E] = (ppm_sc_code[]){PPM_SC_PREADV, -1}, + [PPME_SYSCALL_PREADV_X] = (ppm_sc_code[]){PPM_SC_PREADV, -1}, + [PPME_SYSCALL_PWRITEV_E] = (ppm_sc_code[]){PPM_SC_PWRITEV, -1}, + [PPME_SYSCALL_PWRITEV_X] = (ppm_sc_code[]){PPM_SC_PWRITEV, -1}, + [PPME_SYSCALL_DUP_E] = (ppm_sc_code[]){PPM_SC_DUP, -1}, + [PPME_SYSCALL_DUP_X] = (ppm_sc_code[]){PPM_SC_DUP, -1}, + [PPME_SYSCALL_SIGNALFD_E] = (ppm_sc_code[]){PPM_SC_SIGNALFD, -1}, + [PPME_SYSCALL_SIGNALFD_X] = (ppm_sc_code[]){PPM_SC_SIGNALFD, -1}, + [PPME_SYSCALL_KILL_E] = (ppm_sc_code[]){PPM_SC_KILL, -1}, + [PPME_SYSCALL_KILL_X] = (ppm_sc_code[]){PPM_SC_KILL, -1}, + [PPME_SYSCALL_TKILL_E] = (ppm_sc_code[]){PPM_SC_TKILL, -1}, + [PPME_SYSCALL_TKILL_X] = (ppm_sc_code[]){PPM_SC_TKILL, -1}, + [PPME_SYSCALL_TGKILL_E] = (ppm_sc_code[]){PPM_SC_TGKILL, -1}, + [PPME_SYSCALL_TGKILL_X] = (ppm_sc_code[]){PPM_SC_TGKILL, -1}, + [PPME_SYSCALL_NANOSLEEP_E] = (ppm_sc_code[]){PPM_SC_NANOSLEEP, -1}, + [PPME_SYSCALL_NANOSLEEP_X] = (ppm_sc_code[]){PPM_SC_NANOSLEEP, -1}, + [PPME_SYSCALL_TIMERFD_CREATE_E] = (ppm_sc_code[]){PPM_SC_TIMERFD_CREATE, -1}, + [PPME_SYSCALL_TIMERFD_CREATE_X] = (ppm_sc_code[]){PPM_SC_TIMERFD_CREATE, -1}, + [PPME_SYSCALL_INOTIFY_INIT_E] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT, -1}, + [PPME_SYSCALL_INOTIFY_INIT_X] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT, -1}, + [PPME_SYSCALL_GETRLIMIT_E] = (ppm_sc_code[]){PPM_SC_GETRLIMIT, PPM_SC_UGETRLIMIT, -1}, + [PPME_SYSCALL_GETRLIMIT_X] = (ppm_sc_code[]){PPM_SC_GETRLIMIT, PPM_SC_UGETRLIMIT, -1}, + [PPME_SYSCALL_SETRLIMIT_E] = (ppm_sc_code[]){PPM_SC_SETRLIMIT, -1}, + [PPME_SYSCALL_SETRLIMIT_X] = (ppm_sc_code[]){PPM_SC_SETRLIMIT, -1}, + [PPME_SYSCALL_PRLIMIT_E] = (ppm_sc_code[]){PPM_SC_PRLIMIT64, -1}, + [PPME_SYSCALL_PRLIMIT_X] = (ppm_sc_code[]){PPM_SC_PRLIMIT64, -1}, + [PPME_SCHEDSWITCH_1_E] = (ppm_sc_code[]){PPM_SC_SCHED_SWITCH, -1}, + [PPME_SCHEDSWITCH_1_X] = NULL, + [PPME_DROP_E] = NULL, + [PPME_DROP_X] = NULL, + [PPME_SYSCALL_FCNTL_E] = (ppm_sc_code[]){PPM_SC_FCNTL, PPM_SC_FCNTL64, -1}, + [PPME_SYSCALL_FCNTL_X] = (ppm_sc_code[]){PPM_SC_FCNTL, PPM_SC_FCNTL64, -1}, + [PPME_SCHEDSWITCH_6_E] = (ppm_sc_code[]){PPM_SC_SCHED_SWITCH, -1}, + [PPME_SCHEDSWITCH_6_X] = NULL, + [PPME_SYSCALL_EXECVE_13_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_13_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_CLONE_16_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_CLONE_16_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_BRK_4_E] = (ppm_sc_code[]){PPM_SC_BRK, -1}, + [PPME_SYSCALL_BRK_4_X] = (ppm_sc_code[]){PPM_SC_BRK, -1}, + [PPME_SYSCALL_MMAP_E] = (ppm_sc_code[]){PPM_SC_MMAP, -1}, + [PPME_SYSCALL_MMAP_X] = (ppm_sc_code[]){PPM_SC_MMAP, -1}, + [PPME_SYSCALL_MMAP2_E] = (ppm_sc_code[]){PPM_SC_MMAP2, -1}, + [PPME_SYSCALL_MMAP2_X] = (ppm_sc_code[]){PPM_SC_MMAP2, -1}, + [PPME_SYSCALL_MUNMAP_E] = (ppm_sc_code[]){PPM_SC_MUNMAP, -1}, + [PPME_SYSCALL_MUNMAP_X] = (ppm_sc_code[]){PPM_SC_MUNMAP, -1}, + [PPME_SYSCALL_SPLICE_E] = (ppm_sc_code[]){PPM_SC_SPLICE, -1}, + [PPME_SYSCALL_SPLICE_X] = (ppm_sc_code[]){PPM_SC_SPLICE, -1}, + [PPME_SYSCALL_PTRACE_E] = (ppm_sc_code[]){PPM_SC_PTRACE, -1}, + [PPME_SYSCALL_PTRACE_X] = (ppm_sc_code[]){PPM_SC_PTRACE, -1}, + [PPME_SYSCALL_IOCTL_3_E] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, + [PPME_SYSCALL_IOCTL_3_X] = (ppm_sc_code[]){PPM_SC_IOCTL, -1}, + [PPME_SYSCALL_EXECVE_14_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_14_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_RENAME_E] = (ppm_sc_code[]){PPM_SC_RENAME, -1}, + [PPME_SYSCALL_RENAME_X] = (ppm_sc_code[]){PPM_SC_RENAME, -1}, + [PPME_SYSCALL_RENAMEAT_E] = (ppm_sc_code[]){PPM_SC_RENAMEAT, -1}, + [PPME_SYSCALL_RENAMEAT_X] = (ppm_sc_code[]){PPM_SC_RENAMEAT, -1}, + [PPME_SYSCALL_SYMLINK_E] = (ppm_sc_code[]){PPM_SC_SYMLINK, -1}, + [PPME_SYSCALL_SYMLINK_X] = (ppm_sc_code[]){PPM_SC_SYMLINK, -1}, + [PPME_SYSCALL_SYMLINKAT_E] = (ppm_sc_code[]){PPM_SC_SYMLINKAT, -1}, + [PPME_SYSCALL_SYMLINKAT_X] = (ppm_sc_code[]){PPM_SC_SYMLINKAT, -1}, + [PPME_SYSCALL_FORK_E] = (ppm_sc_code[]){PPM_SC_FORK, -1}, + [PPME_SYSCALL_FORK_X] = (ppm_sc_code[]){PPM_SC_FORK, -1}, + [PPME_SYSCALL_VFORK_E] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, + [PPME_SYSCALL_VFORK_X] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, + [PPME_PROCEXIT_1_E] = (ppm_sc_code[]){PPM_SC_SCHED_PROCESS_EXIT, -1}, + [PPME_PROCEXIT_1_X] = NULL, + [PPME_SYSCALL_SENDFILE_E] = (ppm_sc_code[]){PPM_SC_SENDFILE, PPM_SC_SENDFILE64, -1}, + [PPME_SYSCALL_SENDFILE_X] = (ppm_sc_code[]){PPM_SC_SENDFILE, PPM_SC_SENDFILE64, -1}, + [PPME_SYSCALL_QUOTACTL_E] = (ppm_sc_code[]){PPM_SC_QUOTACTL, -1}, + [PPME_SYSCALL_QUOTACTL_X] = (ppm_sc_code[]){PPM_SC_QUOTACTL, -1}, + [PPME_SYSCALL_SETRESUID_E] = (ppm_sc_code[]){PPM_SC_SETRESUID, PPM_SC_SETRESUID32, -1}, + [PPME_SYSCALL_SETRESUID_X] = (ppm_sc_code[]){PPM_SC_SETRESUID, PPM_SC_SETRESUID32, -1}, + [PPME_SYSCALL_SETRESGID_E] = (ppm_sc_code[]){PPM_SC_SETRESGID, PPM_SC_SETRESGID32, -1}, + [PPME_SYSCALL_SETRESGID_X] = (ppm_sc_code[]){PPM_SC_SETRESGID, PPM_SC_SETRESGID32, -1}, + [PPME_SCAPEVENT_E] = NULL, + [PPME_SCAPEVENT_X] = NULL, + [PPME_SYSCALL_SETUID_E] = (ppm_sc_code[]){PPM_SC_SETUID, PPM_SC_SETUID32, -1}, + [PPME_SYSCALL_SETUID_X] = (ppm_sc_code[]){PPM_SC_SETUID, PPM_SC_SETUID32, -1}, + [PPME_SYSCALL_SETGID_E] = (ppm_sc_code[]){PPM_SC_SETGID, PPM_SC_SETGID32, -1}, + [PPME_SYSCALL_SETGID_X] = (ppm_sc_code[]){PPM_SC_SETGID, PPM_SC_SETGID32, -1}, + [PPME_SYSCALL_GETUID_E] = (ppm_sc_code[]){PPM_SC_GETUID, PPM_SC_GETUID32, -1}, + [PPME_SYSCALL_GETUID_X] = (ppm_sc_code[]){PPM_SC_GETUID, PPM_SC_GETUID32, -1}, + [PPME_SYSCALL_GETEUID_E] = (ppm_sc_code[]){PPM_SC_GETEUID, PPM_SC_GETEUID32, -1}, + [PPME_SYSCALL_GETEUID_X] = (ppm_sc_code[]){PPM_SC_GETEUID, PPM_SC_GETEUID32, -1}, + [PPME_SYSCALL_GETGID_E] = (ppm_sc_code[]){PPM_SC_GETGID, PPM_SC_GETGID32, -1}, + [PPME_SYSCALL_GETGID_X] = (ppm_sc_code[]){PPM_SC_GETGID, PPM_SC_GETGID32, -1}, + [PPME_SYSCALL_GETEGID_E] = (ppm_sc_code[]){PPM_SC_GETEGID, PPM_SC_GETEGID32, -1}, + [PPME_SYSCALL_GETEGID_X] = (ppm_sc_code[]){PPM_SC_GETEGID, PPM_SC_GETEGID32, -1}, + [PPME_SYSCALL_GETRESUID_E] = (ppm_sc_code[]){PPM_SC_GETRESUID, PPM_SC_GETRESUID32, -1}, + [PPME_SYSCALL_GETRESUID_X] = (ppm_sc_code[]){PPM_SC_GETRESUID, PPM_SC_GETRESUID32, -1}, + [PPME_SYSCALL_GETRESGID_E] = (ppm_sc_code[]){PPM_SC_GETRESGID, PPM_SC_GETRESGID32, -1}, + [PPME_SYSCALL_GETRESGID_X] = (ppm_sc_code[]){PPM_SC_GETRESGID, PPM_SC_GETRESGID32, -1}, + [PPME_SYSCALL_EXECVE_15_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_15_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_CLONE_17_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_CLONE_17_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_FORK_17_E] = (ppm_sc_code[]){PPM_SC_FORK, -1}, + [PPME_SYSCALL_FORK_17_X] = (ppm_sc_code[]){PPM_SC_FORK, -1}, + [PPME_SYSCALL_VFORK_17_E] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, + [PPME_SYSCALL_VFORK_17_X] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, + [PPME_SYSCALL_CLONE_20_E] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_CLONE_20_X] = (ppm_sc_code[]){PPM_SC_CLONE, -1}, + [PPME_SYSCALL_FORK_20_E] = (ppm_sc_code[]){PPM_SC_FORK, -1}, + [PPME_SYSCALL_FORK_20_X] = (ppm_sc_code[]){PPM_SC_FORK, -1}, + [PPME_SYSCALL_VFORK_20_E] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, + [PPME_SYSCALL_VFORK_20_X] = (ppm_sc_code[]){PPM_SC_VFORK, -1}, + [PPME_CONTAINER_E] = NULL, + [PPME_CONTAINER_X] = NULL, + [PPME_SYSCALL_EXECVE_16_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_16_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SIGNALDELIVER_E] = (ppm_sc_code[]){PPM_SC_SIGNAL_DELIVER, -1}, + [PPME_SIGNALDELIVER_X] = NULL, + [PPME_PROCINFO_E] = NULL, + [PPME_PROCINFO_X] = NULL, + [PPME_SYSCALL_GETDENTS_E] = (ppm_sc_code[]){PPM_SC_GETDENTS, -1}, + [PPME_SYSCALL_GETDENTS_X] = (ppm_sc_code[]){PPM_SC_GETDENTS, -1}, + [PPME_SYSCALL_GETDENTS64_E] = (ppm_sc_code[]){PPM_SC_GETDENTS64, -1}, + [PPME_SYSCALL_GETDENTS64_X] = (ppm_sc_code[]){PPM_SC_GETDENTS64, -1}, + [PPME_SYSCALL_SETNS_E] = (ppm_sc_code[]){PPM_SC_SETNS, -1}, + [PPME_SYSCALL_SETNS_X] = (ppm_sc_code[]){PPM_SC_SETNS, -1}, + [PPME_SYSCALL_FLOCK_E] = (ppm_sc_code[]){PPM_SC_FLOCK, -1}, + [PPME_SYSCALL_FLOCK_X] = (ppm_sc_code[]){PPM_SC_FLOCK, -1}, + [PPME_CPU_HOTPLUG_E] = NULL, + [PPME_CPU_HOTPLUG_X] = NULL, + [PPME_SOCKET_ACCEPT_5_E] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, + [PPME_SOCKET_ACCEPT_5_X] = (ppm_sc_code[]){PPM_SC_ACCEPT, -1}, + [PPME_SOCKET_ACCEPT4_5_E] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, + [PPME_SOCKET_ACCEPT4_5_X] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, + [PPME_SYSCALL_SEMOP_E] = (ppm_sc_code[]){PPM_SC_SEMOP, -1}, + [PPME_SYSCALL_SEMOP_X] = (ppm_sc_code[]){PPM_SC_SEMOP, -1}, + [PPME_SYSCALL_SEMCTL_E] = (ppm_sc_code[]){PPM_SC_SEMCTL, -1}, + [PPME_SYSCALL_SEMCTL_X] = (ppm_sc_code[]){PPM_SC_SEMCTL, -1}, + [PPME_SYSCALL_PPOLL_E] = (ppm_sc_code[]){PPM_SC_PPOLL, -1}, + [PPME_SYSCALL_PPOLL_X] = (ppm_sc_code[]){PPM_SC_PPOLL, -1}, + [PPME_SYSCALL_MOUNT_E] = (ppm_sc_code[]){PPM_SC_MOUNT, -1}, + [PPME_SYSCALL_MOUNT_X] = (ppm_sc_code[]){PPM_SC_MOUNT, -1}, + [PPME_SYSCALL_UMOUNT_E] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, + [PPME_SYSCALL_UMOUNT_X] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, + [PPME_K8S_E] = NULL, + [PPME_K8S_X] = NULL, + [PPME_SYSCALL_SEMGET_E] = (ppm_sc_code[]){PPM_SC_SEMGET, -1}, + [PPME_SYSCALL_SEMGET_X] = (ppm_sc_code[]){PPM_SC_SEMGET, -1}, + [PPME_SYSCALL_ACCESS_E] = (ppm_sc_code[]){PPM_SC_ACCESS, -1}, + [PPME_SYSCALL_ACCESS_X] = (ppm_sc_code[]){PPM_SC_ACCESS, -1}, + [PPME_SYSCALL_CHROOT_E] = (ppm_sc_code[]){PPM_SC_CHROOT, -1}, + [PPME_SYSCALL_CHROOT_X] = (ppm_sc_code[]){PPM_SC_CHROOT, -1}, + [PPME_TRACER_E] = NULL, + [PPME_TRACER_X] = NULL, + [PPME_MESOS_E] = NULL, + [PPME_MESOS_X] = NULL, + [PPME_CONTAINER_JSON_E] = NULL, + [PPME_CONTAINER_JSON_X] = NULL, + [PPME_SYSCALL_SETSID_E] = (ppm_sc_code[]){PPM_SC_SETSID, -1}, + [PPME_SYSCALL_SETSID_X] = (ppm_sc_code[]){PPM_SC_SETSID, -1}, + [PPME_SYSCALL_MKDIR_2_E] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, + [PPME_SYSCALL_MKDIR_2_X] = (ppm_sc_code[]){PPM_SC_MKDIR, -1}, + [PPME_SYSCALL_RMDIR_2_E] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, + [PPME_SYSCALL_RMDIR_2_X] = (ppm_sc_code[]){PPM_SC_RMDIR, -1}, + [PPME_NOTIFICATION_E] = NULL, + [PPME_NOTIFICATION_X] = NULL, + [PPME_SYSCALL_EXECVE_17_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_17_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_UNSHARE_E] = (ppm_sc_code[]){PPM_SC_UNSHARE, -1}, + [PPME_SYSCALL_UNSHARE_X] = (ppm_sc_code[]){PPM_SC_UNSHARE, -1}, + [PPME_INFRASTRUCTURE_EVENT_E] = NULL, + [PPME_INFRASTRUCTURE_EVENT_X] = NULL, + [PPME_SYSCALL_EXECVE_18_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_18_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_PAGE_FAULT_E] = (ppm_sc_code[]){PPM_SC_PAGE_FAULT_USER, PPM_SC_PAGE_FAULT_KERNEL, -1}, + [PPME_PAGE_FAULT_X] = NULL, + [PPME_SYSCALL_EXECVE_19_E] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_EXECVE_19_X] = (ppm_sc_code[]){PPM_SC_EXECVE, -1}, + [PPME_SYSCALL_SETPGID_E] = (ppm_sc_code[]){PPM_SC_SETPGID, -1}, + [PPME_SYSCALL_SETPGID_X] = (ppm_sc_code[]){PPM_SC_SETPGID, -1}, + [PPME_SYSCALL_BPF_E] = (ppm_sc_code[]){PPM_SC_BPF, -1}, + [PPME_SYSCALL_BPF_X] = (ppm_sc_code[]){PPM_SC_BPF, -1}, + [PPME_SYSCALL_SECCOMP_E] = (ppm_sc_code[]){PPM_SC_SECCOMP, -1}, + [PPME_SYSCALL_SECCOMP_X] = (ppm_sc_code[]){PPM_SC_SECCOMP, -1}, + [PPME_SYSCALL_UNLINK_2_E] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, + [PPME_SYSCALL_UNLINK_2_X] = (ppm_sc_code[]){PPM_SC_UNLINK, -1}, + [PPME_SYSCALL_UNLINKAT_2_E] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, + [PPME_SYSCALL_UNLINKAT_2_X] = (ppm_sc_code[]){PPM_SC_UNLINKAT, -1}, + [PPME_SYSCALL_MKDIRAT_E] = (ppm_sc_code[]){PPM_SC_MKDIRAT, -1}, + [PPME_SYSCALL_MKDIRAT_X] = (ppm_sc_code[]){PPM_SC_MKDIRAT, -1}, + [PPME_SYSCALL_OPENAT_2_E] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, + [PPME_SYSCALL_OPENAT_2_X] = (ppm_sc_code[]){PPM_SC_OPENAT, -1}, + [PPME_SYSCALL_LINK_2_E] = (ppm_sc_code[]){PPM_SC_LINK, -1}, + [PPME_SYSCALL_LINK_2_X] = (ppm_sc_code[]){PPM_SC_LINK, -1}, + [PPME_SYSCALL_LINKAT_2_E] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, + [PPME_SYSCALL_LINKAT_2_X] = (ppm_sc_code[]){PPM_SC_LINKAT, -1}, + [PPME_SYSCALL_FCHMODAT_E] = (ppm_sc_code[]){PPM_SC_FCHMODAT, -1}, + [PPME_SYSCALL_FCHMODAT_X] = (ppm_sc_code[]){PPM_SC_FCHMODAT, -1}, + [PPME_SYSCALL_CHMOD_E] = (ppm_sc_code[]){PPM_SC_CHMOD, -1}, + [PPME_SYSCALL_CHMOD_X] = (ppm_sc_code[]){PPM_SC_CHMOD, -1}, + [PPME_SYSCALL_FCHMOD_E] = (ppm_sc_code[]){PPM_SC_FCHMOD, -1}, + [PPME_SYSCALL_FCHMOD_X] = (ppm_sc_code[]){PPM_SC_FCHMOD, -1}, + [PPME_SYSCALL_RENAMEAT2_E] = (ppm_sc_code[]){PPM_SC_RENAMEAT2, -1}, + [PPME_SYSCALL_RENAMEAT2_X] = (ppm_sc_code[]){PPM_SC_RENAMEAT2, -1}, + [PPME_SYSCALL_USERFAULTFD_E] = (ppm_sc_code[]){PPM_SC_USERFAULTFD, -1}, + [PPME_SYSCALL_USERFAULTFD_X] = (ppm_sc_code[]){PPM_SC_USERFAULTFD, -1}, + [PPME_PLUGINEVENT_E] = NULL, + [PPME_PLUGINEVENT_X] = NULL, + [PPME_CONTAINER_JSON_2_E] = NULL, + [PPME_CONTAINER_JSON_2_X] = NULL, + [PPME_SYSCALL_OPENAT2_E] = (ppm_sc_code[]){PPM_SC_OPENAT2, -1}, + [PPME_SYSCALL_OPENAT2_X] = (ppm_sc_code[]){PPM_SC_OPENAT2, -1}, + [PPME_SYSCALL_MPROTECT_E] = (ppm_sc_code[]){PPM_SC_MPROTECT, -1}, + [PPME_SYSCALL_MPROTECT_X] = (ppm_sc_code[]){PPM_SC_MPROTECT, -1}, + [PPME_SYSCALL_EXECVEAT_E] = (ppm_sc_code[]){PPM_SC_EXECVEAT, -1}, + [PPME_SYSCALL_EXECVEAT_X] = (ppm_sc_code[]){PPM_SC_EXECVEAT, -1}, + [PPME_SYSCALL_COPY_FILE_RANGE_E] = (ppm_sc_code[]){PPM_SC_COPY_FILE_RANGE, -1}, + [PPME_SYSCALL_COPY_FILE_RANGE_X] = (ppm_sc_code[]){PPM_SC_COPY_FILE_RANGE, -1}, + [PPME_SYSCALL_CLONE3_E] = (ppm_sc_code[]){PPM_SC_CLONE3, -1}, + [PPME_SYSCALL_CLONE3_X] = (ppm_sc_code[]){PPM_SC_CLONE3, -1}, + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_E] = (ppm_sc_code[]){PPM_SC_OPEN_BY_HANDLE_AT, -1}, + [PPME_SYSCALL_OPEN_BY_HANDLE_AT_X] = (ppm_sc_code[]){PPM_SC_OPEN_BY_HANDLE_AT, -1}, + [PPME_SYSCALL_IO_URING_SETUP_E] = (ppm_sc_code[]){PPM_SC_IO_URING_SETUP, -1}, + [PPME_SYSCALL_IO_URING_SETUP_X] = (ppm_sc_code[]){PPM_SC_IO_URING_SETUP, -1}, + [PPME_SYSCALL_IO_URING_ENTER_E] = (ppm_sc_code[]){PPM_SC_IO_URING_ENTER, -1}, + [PPME_SYSCALL_IO_URING_ENTER_X] = (ppm_sc_code[]){PPM_SC_IO_URING_ENTER, -1}, + [PPME_SYSCALL_IO_URING_REGISTER_E] = (ppm_sc_code[]){PPM_SC_IO_URING_REGISTER, -1}, + [PPME_SYSCALL_IO_URING_REGISTER_X] = (ppm_sc_code[]){PPM_SC_IO_URING_REGISTER, -1}, + [PPME_SYSCALL_MLOCK_E] = (ppm_sc_code[]){PPM_SC_MLOCK, -1}, + [PPME_SYSCALL_MLOCK_X] = (ppm_sc_code[]){PPM_SC_MLOCK, -1}, + [PPME_SYSCALL_MUNLOCK_E] = (ppm_sc_code[]){PPM_SC_MUNLOCK, -1}, + [PPME_SYSCALL_MUNLOCK_X] = (ppm_sc_code[]){PPM_SC_MUNLOCK, -1}, + [PPME_SYSCALL_MLOCKALL_E] = (ppm_sc_code[]){PPM_SC_MLOCKALL, -1}, + [PPME_SYSCALL_MLOCKALL_X] = (ppm_sc_code[]){PPM_SC_MLOCKALL, -1}, + [PPME_SYSCALL_MUNLOCKALL_E] = (ppm_sc_code[]){PPM_SC_MUNLOCKALL, -1}, + [PPME_SYSCALL_MUNLOCKALL_X] = (ppm_sc_code[]){PPM_SC_MUNLOCKALL, -1}, + [PPME_SYSCALL_CAPSET_E] = (ppm_sc_code[]){PPM_SC_CAPSET, -1}, + [PPME_SYSCALL_CAPSET_X] = (ppm_sc_code[]){PPM_SC_CAPSET, -1}, + [PPME_USER_ADDED_E] = NULL, + [PPME_USER_ADDED_X] = NULL, + [PPME_USER_DELETED_E] = NULL, + [PPME_USER_DELETED_X] = NULL, + [PPME_GROUP_ADDED_E] = NULL, + [PPME_GROUP_ADDED_X] = NULL, + [PPME_GROUP_DELETED_E] = NULL, + [PPME_GROUP_DELETED_X] = NULL, + [PPME_SYSCALL_DUP2_E] = (ppm_sc_code[]){PPM_SC_DUP2, -1}, + [PPME_SYSCALL_DUP2_X] = (ppm_sc_code[]){PPM_SC_DUP2, -1}, + [PPME_SYSCALL_DUP3_E] = (ppm_sc_code[]){PPM_SC_DUP3, -1}, + [PPME_SYSCALL_DUP3_X] = (ppm_sc_code[]){PPM_SC_DUP3, -1}, + [PPME_SYSCALL_DUP_1_E] = (ppm_sc_code[]){PPM_SC_DUP, -1}, + [PPME_SYSCALL_DUP_1_X] = (ppm_sc_code[]){PPM_SC_DUP, -1}, + [PPME_SYSCALL_BPF_2_E] = (ppm_sc_code[]){PPM_SC_BPF, -1}, + [PPME_SYSCALL_BPF_2_X] = (ppm_sc_code[]){PPM_SC_BPF, -1}, + [PPME_SYSCALL_MLOCK2_E] = (ppm_sc_code[]){PPM_SC_MLOCK2, -1}, + [PPME_SYSCALL_MLOCK2_X] = (ppm_sc_code[]){PPM_SC_MLOCK2, -1}, + [PPME_SYSCALL_FSCONFIG_E] = (ppm_sc_code[]){PPM_SC_FSCONFIG, -1}, + [PPME_SYSCALL_FSCONFIG_X] = (ppm_sc_code[]){PPM_SC_FSCONFIG, -1}, + [PPME_SYSCALL_EPOLL_CREATE_E] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE, -1}, + [PPME_SYSCALL_EPOLL_CREATE_X] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE, -1}, + [PPME_SYSCALL_EPOLL_CREATE1_E] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE1, -1}, + [PPME_SYSCALL_EPOLL_CREATE1_X] = (ppm_sc_code[]){PPM_SC_EPOLL_CREATE1, -1}, + [PPME_SYSCALL_CHOWN_E] = (ppm_sc_code[]){PPM_SC_CHOWN, -1}, + [PPME_SYSCALL_CHOWN_X] = (ppm_sc_code[]){PPM_SC_CHOWN, -1}, + [PPME_SYSCALL_LCHOWN_E] = (ppm_sc_code[]){PPM_SC_LCHOWN, -1}, + [PPME_SYSCALL_LCHOWN_X] = (ppm_sc_code[]){PPM_SC_LCHOWN, -1}, + [PPME_SYSCALL_FCHOWN_E] = (ppm_sc_code[]){PPM_SC_FCHOWN, -1}, + [PPME_SYSCALL_FCHOWN_X] = (ppm_sc_code[]){PPM_SC_FCHOWN, -1}, + [PPME_SYSCALL_FCHOWNAT_E] = (ppm_sc_code[]){PPM_SC_FCHOWNAT, -1}, + [PPME_SYSCALL_FCHOWNAT_X] = (ppm_sc_code[]){PPM_SC_FCHOWNAT, -1}, + [PPME_SYSCALL_UMOUNT_1_E] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, + [PPME_SYSCALL_UMOUNT_1_X] = (ppm_sc_code[]){PPM_SC_UMOUNT, -1}, + [PPME_SOCKET_ACCEPT4_6_E] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, + [PPME_SOCKET_ACCEPT4_6_X] = (ppm_sc_code[]){PPM_SC_ACCEPT4, -1}, + [PPME_SYSCALL_UMOUNT2_E] = (ppm_sc_code[]){PPM_SC_UMOUNT2, -1}, + [PPME_SYSCALL_UMOUNT2_X] = (ppm_sc_code[]){PPM_SC_UMOUNT2, -1}, + [PPME_SYSCALL_PIPE2_E] = (ppm_sc_code[]){PPM_SC_PIPE2, -1}, + [PPME_SYSCALL_PIPE2_X] = (ppm_sc_code[]){PPM_SC_PIPE2, -1}, + [PPME_SYSCALL_INOTIFY_INIT1_E] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT1, -1}, + [PPME_SYSCALL_INOTIFY_INIT1_X] = (ppm_sc_code[]){PPM_SC_INOTIFY_INIT1, -1}, + [PPME_SYSCALL_EVENTFD2_E] = (ppm_sc_code[]){PPM_SC_EVENTFD2, -1}, + [PPME_SYSCALL_EVENTFD2_X] = (ppm_sc_code[]){PPM_SC_EVENTFD2, -1}, + [PPME_SYSCALL_SIGNALFD4_E] = (ppm_sc_code[]){PPM_SC_SIGNALFD4, -1}, + [PPME_SYSCALL_SIGNALFD4_X] = (ppm_sc_code[]){PPM_SC_SIGNALFD4, -1}, + [PPME_ASYNCEVENT_E] = NULL, + [PPME_ASYNCEVENT_X] = NULL, + [PPME_SYSCALL_MEMFD_CREATE_E] = (ppm_sc_code[]){PPM_SC_MEMFD_CREATE, -1}, + [PPME_SYSCALL_MEMFD_CREATE_X] = (ppm_sc_code[]){PPM_SC_MEMFD_CREATE, -1}, + [PPME_SYSCALL_PIDFD_GETFD_E] = (ppm_sc_code[]){PPM_SC_PIDFD_GETFD, -1}, + [PPME_SYSCALL_PIDFD_GETFD_X] = (ppm_sc_code[]){PPM_SC_PIDFD_GETFD, -1}, + [PPME_SYSCALL_PIDFD_OPEN_E] = (ppm_sc_code[]){PPM_SC_PIDFD_OPEN, -1}, + [PPME_SYSCALL_PIDFD_OPEN_X] = (ppm_sc_code[]){PPM_SC_PIDFD_OPEN, -1}, + [PPME_SYSCALL_INIT_MODULE_E] = (ppm_sc_code[]){PPM_SC_INIT_MODULE, -1}, + [PPME_SYSCALL_INIT_MODULE_X] = (ppm_sc_code[]){PPM_SC_INIT_MODULE, -1}, + [PPME_SYSCALL_FINIT_MODULE_E] = (ppm_sc_code[]){PPM_SC_FINIT_MODULE, -1}, + [PPME_SYSCALL_FINIT_MODULE_X] = (ppm_sc_code[]){PPM_SC_FINIT_MODULE, -1}, + [PPME_SYSCALL_MKNOD_E] = (ppm_sc_code[]){PPM_SC_MKNOD, -1}, + [PPME_SYSCALL_MKNOD_X] = (ppm_sc_code[]){PPM_SC_MKNOD, -1}, + [PPME_SYSCALL_MKNODAT_E] = (ppm_sc_code[]){PPM_SC_MKNODAT, -1}, + [PPME_SYSCALL_MKNODAT_X] = (ppm_sc_code[]){PPM_SC_MKNODAT, -1}, + [PPME_SYSCALL_NEWFSTATAT_E] = (ppm_sc_code[]){PPM_SC_NEWFSTATAT, -1}, + [PPME_SYSCALL_NEWFSTATAT_X] = (ppm_sc_code[]){PPM_SC_NEWFSTATAT, -1}, + [PPME_SYSCALL_PROCESS_VM_READV_E] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_READV, -1}, + [PPME_SYSCALL_PROCESS_VM_READV_X] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_READV, -1}, + [PPME_SYSCALL_PROCESS_VM_WRITEV_E] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_WRITEV, -1}, + [PPME_SYSCALL_PROCESS_VM_WRITEV_X] = (ppm_sc_code[]){PPM_SC_PROCESS_VM_WRITEV, -1}, + [PPME_SYSCALL_DELETE_MODULE_E] = (ppm_sc_code[]){PPM_SC_DELETE_MODULE, -1}, + [PPME_SYSCALL_DELETE_MODULE_X] = (ppm_sc_code[]){PPM_SC_DELETE_MODULE, -1}, + [PPME_SYSCALL_SETREUID_E] = (ppm_sc_code[]){PPM_SC_SETREUID, -1}, + [PPME_SYSCALL_SETREUID_X] = (ppm_sc_code[]){PPM_SC_SETREUID, -1}, + [PPME_SYSCALL_SETREGID_E] = (ppm_sc_code[]){PPM_SC_SETREGID, -1}, + [PPME_SYSCALL_SETREGID_X] = (ppm_sc_code[]){PPM_SC_SETREGID, -1}, }; -#if defined(__GNUC__) || (__STDC_VERSION__ >=201112L) -_Static_assert(sizeof(g_events_to_sc_map) / sizeof(*g_events_to_sc_map) == PPM_EVENT_MAX, "Missing entries in g_events_to_sc_map table."); +#if defined(__GNUC__) || (__STDC_VERSION__ >= 201112L) +_Static_assert(sizeof(g_events_to_sc_map) / sizeof(*g_events_to_sc_map) == PPM_EVENT_MAX, + "Missing entries in g_events_to_sc_map table."); #endif -int scap_get_modifies_state_ppm_sc(uint8_t ppm_sc_array[PPM_SC_MAX]) -{ - if(ppm_sc_array == NULL) - { +int scap_get_modifies_state_ppm_sc(uint8_t ppm_sc_array[PPM_SC_MAX]) { + if(ppm_sc_array == NULL) { return SCAP_FAILURE; } @@ -480,11 +1010,10 @@ int scap_get_modifies_state_ppm_sc(uint8_t ppm_sc_array[PPM_SC_MAX]) uint8_t events_array[PPM_EVENT_MAX] = {0}; // Collect EF_MODIFIES_STATE events - for (int event_nr = 2; event_nr < PPM_EVENT_MAX; event_nr++) - { - if (g_event_info[event_nr].flags & EF_MODIFIES_STATE && - (g_event_info[event_nr].category & EC_SYSCALL || g_event_info[event_nr].category & EC_TRACEPOINT)) - { + for(int event_nr = 2; event_nr < PPM_EVENT_MAX; event_nr++) { + if(g_event_info[event_nr].flags & EF_MODIFIES_STATE && + (g_event_info[event_nr].category & EC_SYSCALL || + g_event_info[event_nr].category & EC_TRACEPOINT)) { events_array[event_nr] = 1; } } @@ -493,10 +1022,8 @@ int scap_get_modifies_state_ppm_sc(uint8_t ppm_sc_array[PPM_SC_MAX]) scap_get_ppm_sc_from_events(events_array, ppm_sc_array); // Append UF_NEVER_DROP syscalls too! - for (int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) - { - if (g_syscall_table[syscall_nr].flags & UF_NEVER_DROP) - { + for(int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) { + if(g_syscall_table[syscall_nr].flags & UF_NEVER_DROP) { uint32_t code = g_syscall_table[syscall_nr].ppm_sc; ppm_sc_array[code] = 1; } @@ -504,10 +1031,9 @@ int scap_get_modifies_state_ppm_sc(uint8_t ppm_sc_array[PPM_SC_MAX]) return SCAP_SUCCESS; } -int scap_get_events_from_ppm_sc(const uint8_t ppm_sc_array[PPM_SC_MAX], uint8_t events_array[PPM_EVENT_MAX]) -{ - if(ppm_sc_array == NULL || events_array == NULL) - { +int scap_get_events_from_ppm_sc(const uint8_t ppm_sc_array[PPM_SC_MAX], + uint8_t events_array[PPM_EVENT_MAX]) { + if(ppm_sc_array == NULL || events_array == NULL) { return SCAP_FAILURE; } @@ -517,15 +1043,12 @@ int scap_get_events_from_ppm_sc(const uint8_t ppm_sc_array[PPM_SC_MAX], uint8_t memset(events_array, 0, sizeof(*events_array) * PPM_EVENT_MAX); // Load associated events from event_table, skip generics - for(int ev = 0; ev < PPM_EVENT_MAX; ev++) - { + for(int ev = 0; ev < PPM_EVENT_MAX; ev++) { const ppm_sc_code *sc_codes = g_events_to_sc_map[ev]; - while (sc_codes && *sc_codes != -1) - { + while(sc_codes && *sc_codes != -1) { const ppm_sc_code sc_code = *sc_codes; sc_codes++; - if(ppm_sc_array[sc_code]) - { + if(ppm_sc_array[sc_code]) { events_array[ev] = 1; break; } @@ -535,10 +1058,9 @@ int scap_get_events_from_ppm_sc(const uint8_t ppm_sc_array[PPM_SC_MAX], uint8_t return SCAP_SUCCESS; } -int scap_get_ppm_sc_from_events(const uint8_t events_array[PPM_EVENT_MAX], uint8_t ppm_sc_array[PPM_SC_MAX]) -{ - if (events_array == NULL || ppm_sc_array == NULL) - { +int scap_get_ppm_sc_from_events(const uint8_t events_array[PPM_EVENT_MAX], + uint8_t ppm_sc_array[PPM_SC_MAX]) { + if(events_array == NULL || ppm_sc_array == NULL) { return SCAP_FAILURE; } @@ -548,16 +1070,13 @@ int scap_get_ppm_sc_from_events(const uint8_t events_array[PPM_EVENT_MAX], uint8 memset(ppm_sc_array, 0, sizeof(*ppm_sc_array) * PPM_SC_MAX); // Load associated ppm_sc from event_table - for (int ev = 0; ev < PPM_EVENT_MAX; ev++) - { - if(!events_array[ev]) - { + for(int ev = 0; ev < PPM_EVENT_MAX; ev++) { + if(!events_array[ev]) { continue; } const ppm_sc_code *sc_codes = g_events_to_sc_map[ev]; - while (sc_codes && *sc_codes != -1) - { + while(sc_codes && *sc_codes != -1) { ppm_sc_array[*sc_codes] = 1; sc_codes++; } @@ -565,48 +1084,39 @@ int scap_get_ppm_sc_from_events(const uint8_t events_array[PPM_EVENT_MAX], uint8 return SCAP_SUCCESS; } -ppm_sc_code scap_ppm_sc_from_name(const char *name) -{ +ppm_sc_code scap_ppm_sc_from_name(const char *name) { int start = 0; int max = PPM_SC_MAX; const char *sc_name = name; - if(name == NULL) - { + if(name == NULL) { return -1; } - for (int i = start; i < max; i++) - { + for(int i = start; i < max; i++) { /* We need the strlen because all empty entries in the syscall_info_table are "", so * if we pass a "" we will have a match! */ - if(strlen(sc_name) !=0 && strcmp(sc_name, scap_get_ppm_sc_name(i)) == 0) - { + if(strlen(sc_name) != 0 && strcmp(sc_name, scap_get_ppm_sc_name(i)) == 0) { return i; } } return -1; } -ppm_sc_code scap_native_id_to_ppm_sc(int native_id) -{ - if (native_id < 0 || native_id >= SYSCALL_TABLE_SIZE) - { +ppm_sc_code scap_native_id_to_ppm_sc(int native_id) { + if(native_id < 0 || native_id >= SYSCALL_TABLE_SIZE) { return PPM_SC_UNKNOWN; } return g_syscall_table[native_id].ppm_sc; } -/* Here we must be sure that there is a 1:1 relation between syscall_id:ppm_sc +/* Here we must be sure that there is a 1:1 relation between syscall_id:ppm_sc * otherwise there is the risk to return only the first occurrence */ -int scap_ppm_sc_to_native_id(ppm_sc_code sc_code) -{ - for(int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) - { - if(g_syscall_table[syscall_nr].ppm_sc == sc_code) - { +int scap_ppm_sc_to_native_id(ppm_sc_code sc_code) { + for(int syscall_nr = 0; syscall_nr < SYSCALL_TABLE_SIZE; syscall_nr++) { + if(g_syscall_table[syscall_nr].ppm_sc == sc_code) { return syscall_nr; } } diff --git a/userspace/libscap/linux/scap_procs.c b/userspace/libscap/linux/scap_procs.c index 9b93d3f760..eec236765d 100644 --- a/userspace/libscap/linux/scap_procs.c +++ b/userspace/libscap/linux/scap_procs.c @@ -40,16 +40,14 @@ limitations under the License. #include #include -int32_t scap_proc_fill_cwd(char* error, char* procdirname, struct scap_threadinfo* tinfo) -{ +int32_t scap_proc_fill_cwd(char* error, char* procdirname, struct scap_threadinfo* tinfo) { int target_res; char filename[SCAP_MAX_PATH_SIZE]; snprintf(filename, sizeof(filename), "%scwd", procdirname); target_res = readlink(filename, tinfo->cwd, sizeof(tinfo->cwd) - 1); - if(target_res <= 0) - { + if(target_res <= 0) { return scap_errprintf(error, errno, "readlink %s failed", filename); } @@ -57,8 +55,9 @@ int32_t scap_proc_fill_cwd(char* error, char* procdirname, struct scap_threadinf return SCAP_SUCCESS; } -int32_t scap_proc_fill_info_from_stats(char* error, char* procdirname, struct scap_threadinfo* tinfo) -{ +int32_t scap_proc_fill_info_from_stats(char* error, + char* procdirname, + struct scap_threadinfo* tinfo) { char filename[SCAP_MAX_PATH_SIZE]; uint32_t pidinfo_nfound = 0; uint32_t caps_nfound = 0; @@ -100,179 +99,118 @@ int32_t scap_proc_fill_info_from_stats(char* error, char* procdirname, struct sc snprintf(filename, sizeof(filename), "%sstatus", procdirname); FILE* f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { ASSERT(false); return scap_errprintf(error, errno, "open status file %s failed", filename); } - while(fgets(line, sizeof(line), f) != NULL) - { - if(strstr(line, "Tgid") == line) - { + while(fgets(line, sizeof(line), f) != NULL) { + if(strstr(line, "Tgid") == line) { pidinfo_nfound++; - if(sscanf(line, "Tgid: %" PRIu64, &tgid) == 1) - { + if(sscanf(line, "Tgid: %" PRIu64, &tgid) == 1) { tinfo->pid = tgid; - } - else - { + } else { ASSERT(false); } } - if(strstr(line, "Uid") == line) - { + if(strstr(line, "Uid") == line) { pidinfo_nfound++; - if(sscanf(line, "Uid: %" PRIu64 " %" PRIu32, &tmp, &uid) == 2) - { + if(sscanf(line, "Uid: %" PRIu64 " %" PRIu32, &tmp, &uid) == 2) { tinfo->uid = uid; - } - else - { + } else { ASSERT(false); } - } - else if(strstr(line, "Gid") == line) - { + } else if(strstr(line, "Gid") == line) { pidinfo_nfound++; - if(sscanf(line, "Gid: %" PRIu64 " %" PRIu32, &tmp, &uid) == 2) - { + if(sscanf(line, "Gid: %" PRIu64 " %" PRIu32, &tmp, &uid) == 2) { tinfo->gid = uid; - } - else - { + } else { ASSERT(false); } } - if(strstr(line, "CapInh") == line) - { + if(strstr(line, "CapInh") == line) { caps_nfound++; - if(sscanf(line, "CapInh: %" PRIx64, &cap_inheritable) == 1) - { + if(sscanf(line, "CapInh: %" PRIx64, &cap_inheritable) == 1) { tinfo->cap_inheritable = cap_inheritable; - } - else - { + } else { ASSERT(false); } } - if(strstr(line, "CapPrm") == line) - { + if(strstr(line, "CapPrm") == line) { caps_nfound++; - if(sscanf(line, "CapPrm: %" PRIx64, &cap_permitted) == 1) - { + if(sscanf(line, "CapPrm: %" PRIx64, &cap_permitted) == 1) { tinfo->cap_permitted = cap_permitted; - } - else - { + } else { ASSERT(false); } } - if(strstr(line, "CapEff") == line) - { + if(strstr(line, "CapEff") == line) { caps_nfound++; - if(sscanf(line, "CapEff: %" PRIx64, &cap_effective) == 1) - { + if(sscanf(line, "CapEff: %" PRIx64, &cap_effective) == 1) { tinfo->cap_effective = cap_effective; - } - else - { + } else { ASSERT(false); } - } - else if(strstr(line, "PPid") == line) - { + } else if(strstr(line, "PPid") == line) { pidinfo_nfound++; - if(sscanf(line, "PPid: %" PRIu64, &ppid) == 1) - { + if(sscanf(line, "PPid: %" PRIu64, &ppid) == 1) { tinfo->ptid = ppid; - } - else - { + } else { ASSERT(false); } - } - else if(strstr(line, "VmSize:") == line) - { + } else if(strstr(line, "VmSize:") == line) { vm_nfound++; - if(sscanf(line, "VmSize: %" PRIu32, &vmsize_kb) == 1) - { + if(sscanf(line, "VmSize: %" PRIu32, &vmsize_kb) == 1) { tinfo->vmsize_kb = vmsize_kb; - } - else - { + } else { ASSERT(false); } - } - else if(strstr(line, "VmRSS:") == line) - { + } else if(strstr(line, "VmRSS:") == line) { vm_nfound++; - if(sscanf(line, "VmRSS: %" PRIu32, &vmrss_kb) == 1) - { + if(sscanf(line, "VmRSS: %" PRIu32, &vmrss_kb) == 1) { tinfo->vmrss_kb = vmrss_kb; - } - else - { + } else { ASSERT(false); } - } - else if(strstr(line, "VmSwap:") == line) - { + } else if(strstr(line, "VmSwap:") == line) { vm_nfound++; - if(sscanf(line, "VmSwap: %" PRIu32, &vmswap_kb) == 1) - { + if(sscanf(line, "VmSwap: %" PRIu32, &vmswap_kb) == 1) { tinfo->vmswap_kb = vmswap_kb; - } - else - { + } else { ASSERT(false); } - } - else if(strstr(line, "NSpid:") == line) - { + } else if(strstr(line, "NSpid:") == line) { pidinfo_nfound++; - if(sscanf(line, "NSpid: %*u %" PRIu64, &vtid) == 1) - { + if(sscanf(line, "NSpid: %*u %" PRIu64, &vtid) == 1) { tinfo->vtid = vtid; - } - else - { + } else { tinfo->vtid = tinfo->tid; } - } - else if(strstr(line, "NSpgid:") == line) - { + } else if(strstr(line, "NSpgid:") == line) { pidinfo_nfound++; - if(sscanf(line, "NSpgid: %*u %" PRIu64, &vpgid) == 1) - { + if(sscanf(line, "NSpgid: %*u %" PRIu64, &vpgid) == 1) { tinfo->vpgid = vpgid; } - } - else if(strstr(line, "NStgid:") == line) - { + } else if(strstr(line, "NStgid:") == line) { pidinfo_nfound++; - if(sscanf(line, "NStgid: %*u %" PRIu64, &vpid) == 1) - { + if(sscanf(line, "NStgid: %*u %" PRIu64, &vpid) == 1) { tinfo->vpid = vpid; - } - else - { + } else { tinfo->vpid = tinfo->pid; } } - if(pidinfo_nfound == 7 && caps_nfound == 3 && vm_nfound == 3) - { + if(pidinfo_nfound == 7 && caps_nfound == 3 && vm_nfound == 3) { break; } } @@ -291,15 +229,13 @@ int32_t scap_proc_fill_info_from_stats(char* error, char* procdirname, struct sc snprintf(filename, sizeof(filename), "%sstat", procdirname); f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { ASSERT(false); return scap_errprintf(error, errno, "read stat file %s failed", filename); } size_t ssres = fread(line, 1, sizeof(line) - 1, f); - if(ssres == 0) - { + if(ssres == 0) { ASSERT(false); fclose(f); return scap_errprintf(error, errno, "Could not read from stat file %s", filename); @@ -307,8 +243,7 @@ int32_t scap_proc_fill_info_from_stats(char* error, char* procdirname, struct sc line[ssres] = 0; s = strrchr(line, ')'); - if(s == NULL) - { + if(s == NULL) { ASSERT(false); fclose(f); return scap_errprintf(error, 0, "Could not find closing bracket in stat file %s", filename); @@ -317,31 +252,34 @@ int32_t scap_proc_fill_info_from_stats(char* error, char* procdirname, struct sc // // Extract the line content // - if(sscanf(s + 2, "%c %" PRId64 " %" PRId64 " %" PRId64 " %" PRIu32 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64, - &tmpc, - &tmp, - &pgid, - &sid, - &tty, - &tmp, - &tmp, - &pfminor, - &tmp, - &pfmajor) != 10) - { + if(sscanf(s + 2, + "%c %" PRId64 " %" PRId64 " %" PRId64 " %" PRIu32 " %" PRId64 " %" PRId64 " %" PRId64 + " %" PRId64 " %" PRId64, + &tmpc, + &tmp, + &pgid, + &sid, + &tty, + &tmp, + &tmp, + &pfminor, + &tmp, + &pfmajor) != 10) { ASSERT(false); fclose(f); - return scap_errprintf(error, 0, "Could not read expected fields from stat file %s", filename); + return scap_errprintf(error, + 0, + "Could not read expected fields from stat file %s", + filename); } tinfo->pfmajor = pfmajor; tinfo->pfminor = pfminor; - tinfo->sid = (uint64_t) sid; + tinfo->sid = (uint64_t)sid; // If we did not find vpgid above, set it to pgid from the // global namespace. - if(tinfo->vpgid == 0) - { + if(tinfo->vpgid == 0) { tinfo->vpgid = pgid; } @@ -361,8 +299,7 @@ static int32_t scap_proc_fill_flimit(uint64_t tid, struct scap_threadinfo* tinfo struct rlimit rl; #ifdef __NR_prlimit64 - if(syscall(SYS_prlimit64, tid, RLIMIT_NOFILE, NULL, &rl) == 0) - { + if(syscall(SYS_prlimit64, tid, RLIMIT_NOFILE, NULL, &rl) == 0) { tinfo->fdlimit = rl.rlim_cur; return SCAP_SUCCESS; } @@ -378,8 +315,9 @@ static int32_t scap_proc_fill_flimit(uint64_t tid, struct scap_threadinfo* tinfo } #endif -int32_t scap_proc_fill_pidns_start_ts(char* error, struct scap_threadinfo* tinfo, const char* procdirname) -{ +int32_t scap_proc_fill_pidns_start_ts(char* error, + struct scap_threadinfo* tinfo, + const char* procdirname) { char proc_cmdline_pidns[SCAP_MAX_PATH_SIZE]; struct stat targetstat = {0}; @@ -387,22 +325,18 @@ int32_t scap_proc_fill_pidns_start_ts(char* error, struct scap_threadinfo* tinfo // processes will not be equal to the boot time but to the time when the // host init started. snprintf(proc_cmdline_pidns, sizeof(proc_cmdline_pidns), "%sroot/proc/1/cmdline", procdirname); - if(stat(proc_cmdline_pidns, &targetstat) == 0) - { - tinfo->pidns_init_start_ts = targetstat.st_ctim.tv_sec * SECOND_TO_NS + targetstat.st_ctim.tv_nsec; + if(stat(proc_cmdline_pidns, &targetstat) == 0) { + tinfo->pidns_init_start_ts = + targetstat.st_ctim.tv_sec * SECOND_TO_NS + targetstat.st_ctim.tv_nsec; return SCAP_SUCCESS; - } - else - { + } else { tinfo->pidns_init_start_ts = 0; return SCAP_FAILURE; } } -static int32_t scap_get_vtid(struct scap_linux_platform *platform, uint64_t tid, int64_t *vtid) -{ - if(platform->m_linux_vtable && platform->m_linux_vtable->get_vtid) - { +static int32_t scap_get_vtid(struct scap_linux_platform* platform, uint64_t tid, int64_t* vtid) { + if(platform->m_linux_vtable && platform->m_linux_vtable->get_vtid) { return platform->m_linux_vtable->get_vtid(platform->m_engine, tid, vtid); } @@ -410,10 +344,8 @@ static int32_t scap_get_vtid(struct scap_linux_platform *platform, uint64_t tid, return SCAP_FAILURE; } -static int32_t scap_get_vpid(struct scap_linux_platform *platform, int64_t pid, int64_t *vpid) -{ - if(platform->m_linux_vtable && platform->m_linux_vtable->get_vpid) - { +static int32_t scap_get_vpid(struct scap_linux_platform* platform, int64_t pid, int64_t* vpid) { + if(platform->m_linux_vtable && platform->m_linux_vtable->get_vpid) { return platform->m_linux_vtable->get_vpid(platform->m_engine, pid, vpid); } @@ -421,39 +353,34 @@ static int32_t scap_get_vpid(struct scap_linux_platform *platform, int64_t pid, return SCAP_FAILURE; } -int32_t scap_proc_fill_root(char* error, struct scap_threadinfo* tinfo, const char* procdirname) -{ +int32_t scap_proc_fill_root(char* error, struct scap_threadinfo* tinfo, const char* procdirname) { char root_path[SCAP_MAX_PATH_SIZE]; snprintf(root_path, sizeof(root_path), "%sroot", procdirname); ssize_t r = readlink(root_path, tinfo->root, sizeof(tinfo->root) - 1); - if (r > 0) - { + if(r > 0) { tinfo->root[r] = '\0'; return SCAP_SUCCESS; - } - else - { + } else { return scap_errprintf(error, errno, "readlink %s failed", root_path); } } -int32_t scap_proc_fill_loginuid(char* error, struct scap_threadinfo* tinfo, const char* procdirname) -{ +int32_t scap_proc_fill_loginuid(char* error, + struct scap_threadinfo* tinfo, + const char* procdirname) { uint32_t loginuid; char loginuid_path[SCAP_MAX_PATH_SIZE]; char line[512]; snprintf(loginuid_path, sizeof(loginuid_path), "%sloginuid", procdirname); FILE* f = fopen(loginuid_path, "r"); - if(f == NULL) - { + if(f == NULL) { // If Linux kernel is built with CONFIG_AUDIT=n, loginuid management // (and associated /proc file) is not implemented. // Record default loginuid value of invalid uid in this case. tinfo->loginuid = (uint32_t)UINT32_MAX; return SCAP_SUCCESS; } - if (fgets(line, sizeof(line), f) == NULL) - { + if(fgets(line, sizeof(line), f) == NULL) { ASSERT(false); fclose(f); return scap_errprintf(error, errno, "Could not read loginuid from %s", loginuid_path); @@ -461,43 +388,46 @@ int32_t scap_proc_fill_loginuid(char* error, struct scap_threadinfo* tinfo, cons fclose(f); - if(sscanf(line, "%" PRIu32, &loginuid) == 1) - { + if(sscanf(line, "%" PRIu32, &loginuid) == 1) { tinfo->loginuid = loginuid; return SCAP_SUCCESS; - } - else - { + } else { ASSERT(false); return scap_errprintf(error, 0, "Could not read loginuid from %s", loginuid_path); } } -int32_t scap_proc_fill_exe_ino_ctime_mtime(char* error, struct scap_threadinfo* tinfo, const char *procdirname, const char *exetarget) -{ +int32_t scap_proc_fill_exe_ino_ctime_mtime(char* error, + struct scap_threadinfo* tinfo, + const char* procdirname, + const char* exetarget) { struct stat targetstat = {0}; // extract ino field from executable path if it exists - if(stat(exetarget, &targetstat) == 0) - { + if(stat(exetarget, &targetstat) == 0) { tinfo->exe_ino = targetstat.st_ino; - tinfo->exe_ino_ctime = targetstat.st_ctim.tv_sec * SECOND_TO_NS + targetstat.st_ctim.tv_nsec; - tinfo->exe_ino_mtime = targetstat.st_mtim.tv_sec * SECOND_TO_NS + targetstat.st_mtim.tv_nsec; + tinfo->exe_ino_ctime = + targetstat.st_ctim.tv_sec * SECOND_TO_NS + targetstat.st_ctim.tv_nsec; + tinfo->exe_ino_mtime = + targetstat.st_mtim.tv_sec * SECOND_TO_NS + targetstat.st_mtim.tv_nsec; } return SCAP_SUCCESS; } -int32_t scap_proc_fill_exe_writable(char* error, struct scap_threadinfo* tinfo, uint32_t uid, uint32_t gid, const char *procdirname, const char *exetarget) -{ +int32_t scap_proc_fill_exe_writable(char* error, + struct scap_threadinfo* tinfo, + uint32_t uid, + uint32_t gid, + const char* procdirname, + const char* exetarget) { char proc_exe_path[SCAP_MAX_PATH_SIZE]; struct stat targetstat; snprintf(proc_exe_path, sizeof(proc_exe_path), "%sroot%s", procdirname, exetarget); // if the file doesn't exist we can't determine if it was writable, assume false - if(stat(proc_exe_path, &targetstat) < 0) - { + if(stat(proc_exe_path, &targetstat) < 0) { return SCAP_SUCCESS; } @@ -531,16 +461,20 @@ int32_t scap_proc_fill_exe_writable(char* error, struct scap_threadinfo* tinfo, } int ret; - if((ret = thread_seteuid(orig_uid)) < 0) - { - return scap_errprintf(error, -ret, "Could not restore original euid from %d to %d", - uid, orig_uid); + if((ret = thread_seteuid(orig_uid)) < 0) { + return scap_errprintf(error, + -ret, + "Could not restore original euid from %d to %d", + uid, + orig_uid); } - if((ret = thread_setegid(orig_gid)) < 0) - { - return scap_errprintf(error, -ret, "Could not restore original egid from %d to %d", - gid, orig_gid); + if((ret = thread_setegid(orig_gid)) < 0) { + return scap_errprintf(error, + -ret, + "Could not restore original egid from %d to %d", + gid, + orig_gid); } return SCAP_SUCCESS; @@ -549,10 +483,13 @@ int32_t scap_proc_fill_exe_writable(char* error, struct scap_threadinfo* tinfo, // // Add a process to the list by parsing its entry under /proc // -static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platform, struct scap_proclist* proclist, - uint32_t tid, char* procdirname, struct scap_ns_socket_list** sockets_by_ns, - uint64_t* num_fds_ret, char* error) -{ +static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platform, + struct scap_proclist* proclist, + uint32_t tid, + char* procdirname, + struct scap_ns_socket_list** sockets_by_ns, + uint64_t* num_fds_ret, + char* error) { char dir_name[256]; char target_name[SCAP_MAX_PATH_SIZE]; int target_res; @@ -573,10 +510,13 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor // // Gather the executable full name // - target_res = readlink(filename, target_name, sizeof(target_name) - 1); // Getting the target of the exe, i.e. to which binary it points to + target_res = readlink( + filename, + target_name, + sizeof(target_name) - + 1); // Getting the target of the exe, i.e. to which binary it points to - if(target_res <= 0) - { + if(target_res <= 0) { // // No exe. This either // - a kernel thread (if there is no cmdline). In that case we skip it. @@ -585,27 +525,21 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor // snprintf(filename, sizeof(filename), "%scmdline", dir_name); f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { return scap_errprintf(error, errno, "can't find valid proc dir in %s", dir_name); } ASSERT(sizeof(line) >= SCAP_MAX_PATH_SIZE); - if(fgets(line, SCAP_MAX_PATH_SIZE, f) == NULL) - { + if(fgets(line, SCAP_MAX_PATH_SIZE, f) == NULL) { fclose(f); return scap_errprintf(error, errno, "can't read cmdline file %s", filename); - } - else - { + } else { fclose(f); } target_name[0] = 0; - } - else - { + } else { // null-terminate target_name (readlink() does not append a null byte) target_name[target_res] = 0; } @@ -625,16 +559,12 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor snprintf(filename, sizeof(filename), "%sstatus", dir_name); f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { return scap_errprintf(error, errno, "can't open %s", filename); - } - else - { + } else { ASSERT(sizeof(line) >= SCAP_MAX_PATH_SIZE); - if(fgets(line, SCAP_MAX_PATH_SIZE, f) == NULL) - { + if(fgets(line, SCAP_MAX_PATH_SIZE, f) == NULL) { fclose(f); return scap_errprintf(error, errno, "can't read from %s", filename); } @@ -650,20 +580,16 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor snprintf(filename, sizeof(filename), "%scmdline", dir_name); f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { return scap_errprintf(error, errno, "can't open cmdline file %s", filename); - } - else - { + } else { ASSERT(sizeof(line) >= SCAP_MAX_ARGS_SIZE); filesize = fread(line, 1, SCAP_MAX_ARGS_SIZE, f); - if(filesize > 0) - { + if(filesize > 0) { // In case `args` is greater than `SCAP_MAX_ARGS_SIZE` it could be // truncated so we put a `/0` at the end manually. - line[filesize-1] = 0; + line[filesize - 1] = 0; // We always count also the terminator so `+1` // Please note that this could be exactly `SCAP_MAX_ARGS_SIZE` @@ -673,19 +599,14 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor // Please note if `exe_len` is `SCAP_MAX_ARGS_SIZE` we will return an empty `args`. tinfo.args_len = filesize - exe_len; - if(tinfo.args_len > 0) - { + if(tinfo.args_len > 0) { memcpy(tinfo.args, line + exe_len, tinfo.args_len); tinfo.args[tinfo.args_len - 1] = 0; - } - else - { + } else { tinfo.args_len = 0; tinfo.args[0] = 0; } - } - else - { + } else { tinfo.args_len = 0; tinfo.args[0] = 0; tinfo.exe[0] = 0; @@ -700,27 +621,21 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor snprintf(filename, sizeof(filename), "%senviron", dir_name); f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { return scap_errprintf(error, errno, "can't open environ file %s", filename); - } - else - { + } else { ASSERT(sizeof(line) >= SCAP_MAX_ENV_SIZE); filesize = fread(line, 1, SCAP_MAX_ENV_SIZE, f); - if(filesize > 0) - { + if(filesize > 0) { line[filesize - 1] = 0; tinfo.env_len = filesize; memcpy(tinfo.env, line, tinfo.env_len); tinfo.env[SCAP_MAX_ENV_SIZE - 1] = 0; - } - else - { + } else { tinfo.env[0] = 0; tinfo.env_len = 0; } @@ -731,92 +646,101 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor // // set the current working directory of the process // - if(SCAP_FAILURE == scap_proc_fill_cwd(linux_platform->m_lasterr, dir_name, &tinfo)) - { - return scap_errprintf(error, 0, "can't fill cwd for %s (%s)", - dir_name, linux_platform->m_lasterr); + if(SCAP_FAILURE == scap_proc_fill_cwd(linux_platform->m_lasterr, dir_name, &tinfo)) { + return scap_errprintf(error, + 0, + "can't fill cwd for %s (%s)", + dir_name, + linux_platform->m_lasterr); } // // extract the user id and ppid from /proc/pid/status // - if(SCAP_FAILURE == scap_proc_fill_info_from_stats(linux_platform->m_lasterr, dir_name, &tinfo)) - { - return scap_errprintf(error, 0, "can't fill uid and pid for %s (%s)", - dir_name, linux_platform->m_lasterr); + if(SCAP_FAILURE == + scap_proc_fill_info_from_stats(linux_platform->m_lasterr, dir_name, &tinfo)) { + return scap_errprintf(error, + 0, + "can't fill uid and pid for %s (%s)", + dir_name, + linux_platform->m_lasterr); } // // Set the file limit // - if(SCAP_FAILURE == scap_proc_fill_flimit(tinfo.tid, &tinfo)) - { - return scap_errprintf(error, 0, "can't fill flimit for %s (%s)", - dir_name, linux_platform->m_lasterr); - } - - if(scap_cgroup_get_thread(&linux_platform->m_cgroups, dir_name, &tinfo.cgroups, linux_platform->m_lasterr) == SCAP_FAILURE) - { - return scap_errprintf(error, 0, "can't fill cgroups for %s (%s)", - dir_name, linux_platform->m_lasterr); - } - - if(scap_proc_fill_pidns_start_ts(linux_platform->m_lasterr, &tinfo, dir_name) == SCAP_FAILURE) - { + if(SCAP_FAILURE == scap_proc_fill_flimit(tinfo.tid, &tinfo)) { + return scap_errprintf(error, + 0, + "can't fill flimit for %s (%s)", + dir_name, + linux_platform->m_lasterr); + } + + if(scap_cgroup_get_thread(&linux_platform->m_cgroups, + dir_name, + &tinfo.cgroups, + linux_platform->m_lasterr) == SCAP_FAILURE) { + return scap_errprintf(error, + 0, + "can't fill cgroups for %s (%s)", + dir_name, + linux_platform->m_lasterr); + } + + if(scap_proc_fill_pidns_start_ts(linux_platform->m_lasterr, &tinfo, dir_name) == SCAP_FAILURE) { // ignore errors // the thread may not have /proc visible so we shouldn't kill the scan if this fails } // These values should be read already from /status file, leave these // fallback functions for older kernels < 4.1 - if(tinfo.vtid == 0 && scap_get_vtid(linux_platform, tinfo.tid, &tinfo.vtid) == SCAP_FAILURE) - { + if(tinfo.vtid == 0 && scap_get_vtid(linux_platform, tinfo.tid, &tinfo.vtid) == SCAP_FAILURE) { tinfo.vtid = tinfo.tid; } - if(tinfo.vpid == 0 && scap_get_vpid(linux_platform, tinfo.tid, &tinfo.vpid) == SCAP_FAILURE) - { + if(tinfo.vpid == 0 && scap_get_vpid(linux_platform, tinfo.tid, &tinfo.vpid) == SCAP_FAILURE) { tinfo.vpid = tinfo.pid; } // // set the current root of the process // - if(SCAP_FAILURE == scap_proc_fill_root(linux_platform->m_lasterr, &tinfo, dir_name)) - { - return scap_errprintf(error, 0, "can't fill root for %s (%s)", - dir_name, linux_platform->m_lasterr); + if(SCAP_FAILURE == scap_proc_fill_root(linux_platform->m_lasterr, &tinfo, dir_name)) { + return scap_errprintf(error, + 0, + "can't fill root for %s (%s)", + dir_name, + linux_platform->m_lasterr); } // // set the loginuid // - if(SCAP_FAILURE == scap_proc_fill_loginuid(linux_platform->m_lasterr, &tinfo, dir_name)) - { - return scap_errprintf(error, 0, "can't fill loginuid for %s (%s)", - dir_name, linux_platform->m_lasterr); + if(SCAP_FAILURE == scap_proc_fill_loginuid(linux_platform->m_lasterr, &tinfo, dir_name)) { + return scap_errprintf(error, + 0, + "can't fill loginuid for %s (%s)", + dir_name, + linux_platform->m_lasterr); } // Container start time for host processes will be equal to when the // host init started char proc_cmdline[SCAP_MAX_PATH_SIZE]; snprintf(proc_cmdline, sizeof(proc_cmdline), "%scmdline", dir_name); - if(stat(proc_cmdline, &dirstat) == 0) - { + if(stat(proc_cmdline, &dirstat) == 0) { tinfo.clone_ts = dirstat.st_ctim.tv_sec * SECOND_TO_NS + dirstat.st_ctim.tv_nsec; } - // If tid is different from pid, assume this is a thread and that the FDs are shared, and set the - // corresponding process flags. + // If tid is different from pid, assume this is a thread and that the FDs are shared, and set + // the corresponding process flags. // XXX we should see if the process creation flags are stored somewhere in /proc and handle this // properly instead of making assumptions. // - if(tinfo.tid == tinfo.pid) - { + if(tinfo.tid == tinfo.pid) { tinfo.flags = 0; - } - else - { + } else { /* Probably we are doing this because `pthread_create` calls `clone()` * with `CLONE_FILES`, but this is just an assumption. * All threads populated by /proc scan will have `fdtable->size()==0`. @@ -824,42 +748,67 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor tinfo.flags = PPM_CL_CLONE_THREAD | PPM_CL_CLONE_FILES; } - if(SCAP_FAILURE == scap_proc_fill_exe_ino_ctime_mtime(linux_platform->m_lasterr, &tinfo, dir_name, target_name)) - { - return scap_errprintf(error, 0, "can't fill exe writable access for %s (%s)", - dir_name, linux_platform->m_lasterr); + if(SCAP_FAILURE == scap_proc_fill_exe_ino_ctime_mtime(linux_platform->m_lasterr, + &tinfo, + dir_name, + target_name)) { + return scap_errprintf(error, + 0, + "can't fill exe writable access for %s (%s)", + dir_name, + linux_platform->m_lasterr); } - if(SCAP_FAILURE == scap_proc_fill_exe_writable(linux_platform->m_lasterr, &tinfo, tinfo.uid, tinfo.gid, dir_name, target_name)) - { - return scap_errprintf(error, 0, "can't fill exe writable access for %s (%s)", - dir_name, linux_platform->m_lasterr); + if(SCAP_FAILURE == scap_proc_fill_exe_writable(linux_platform->m_lasterr, + &tinfo, + tinfo.uid, + tinfo.gid, + dir_name, + target_name)) { + return scap_errprintf(error, + 0, + "can't fill exe writable access for %s (%s)", + dir_name, + linux_platform->m_lasterr); } - scap_threadinfo *new_tinfo = &tinfo; + scap_threadinfo* new_tinfo = &tinfo; // // Done. Add the entry to the process table, or fire the notification callback // - proclist->m_proc_callback(proclist->m_proc_callback_context, error, tinfo.tid, &tinfo, NULL, &new_tinfo); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + tinfo.tid, + &tinfo, + NULL, + &new_tinfo); // // Only add fds for processes, not threads // - if(new_tinfo->pid == new_tinfo->tid) - { - res = scap_fd_scan_fd_dir(linux_platform, proclist, dir_name, new_tinfo, sockets_by_ns, num_fds_ret, error); + if(new_tinfo->pid == new_tinfo->tid) { + res = scap_fd_scan_fd_dir(linux_platform, + proclist, + dir_name, + new_tinfo, + sockets_by_ns, + num_fds_ret, + error); } return res; } -static int32_t single_thread_proc_callback(void* context, char* error, int64_t tid, scap_threadinfo* tinfo, scap_fdinfo* fdinfo, scap_threadinfo** new_tinfo) -{ - scap_threadinfo *out_proc = (scap_threadinfo*)context; +static int32_t single_thread_proc_callback(void* context, + char* error, + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo, + scap_threadinfo** new_tinfo) { + scap_threadinfo* out_proc = (scap_threadinfo*)context; *out_proc = *tinfo; - if(new_tinfo) - { + if(new_tinfo) { *new_tinfo = out_proc; } return SCAP_SUCCESS; @@ -868,9 +817,12 @@ static int32_t single_thread_proc_callback(void* context, char* error, int64_t t // // Read a single thread info from /proc // -int32_t scap_proc_read_thread(struct scap_linux_platform* linux_platform, char* procdirname, uint64_t tid, - struct scap_threadinfo* tinfo, char* error, bool scan_sockets) -{ +int32_t scap_proc_read_thread(struct scap_linux_platform* linux_platform, + char* procdirname, + uint64_t tid, + struct scap_threadinfo* tinfo, + char* error, + bool scan_sockets) { struct scap_proclist single_thread_proclist; init_proclist(&single_thread_proclist, single_thread_proc_callback, tinfo); @@ -879,20 +831,27 @@ int32_t scap_proc_read_thread(struct scap_linux_platform* linux_platform, char* int32_t res; char add_error[SCAP_LASTERR_SIZE]; - if(!scan_sockets) - { + if(!scan_sockets) { sockets_by_ns = (void*)-1; } - res = scap_proc_add_from_proc(linux_platform, &single_thread_proclist, tid, procdirname, &sockets_by_ns, NULL, - add_error); - if(res != SCAP_SUCCESS) - { - scap_errprintf(error, 0, "cannot add proc tid = %"PRIu64", dirname = %s, error=%s", tid, procdirname, add_error); + res = scap_proc_add_from_proc(linux_platform, + &single_thread_proclist, + tid, + procdirname, + &sockets_by_ns, + NULL, + add_error); + if(res != SCAP_SUCCESS) { + scap_errprintf(error, + 0, + "cannot add proc tid = %" PRIu64 ", dirname = %s, error=%s", + tid, + procdirname, + add_error); } - if(sockets_by_ns != NULL && sockets_by_ns != (void*)-1) - { + if(sockets_by_ns != NULL && sockets_by_ns != (void*)-1) { scap_fd_free_ns_sockets_list(&sockets_by_ns); } @@ -902,10 +861,13 @@ int32_t scap_proc_read_thread(struct scap_linux_platform* linux_platform, char* // // Scan a directory containing multiple processes under /proc // -static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_platform, struct scap_proclist* proclist, char* procdirname, int parenttid, char *error) -{ - DIR *dir_p; - struct dirent *dir_entry_p; +static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_platform, + struct scap_proclist* proclist, + char* procdirname, + int parenttid, + char* error) { + DIR* dir_p; + struct dirent* dir_entry_p; scap_threadinfo* tinfo; uint64_t tid; int32_t res = SCAP_SUCCESS; @@ -918,8 +880,7 @@ static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_p dir_p = opendir(procdirname); - if(dir_p == NULL) - { + if(dir_p == NULL) { scap_errprintf(error, errno, "error opening the %s directory", procdirname); return SCAP_NOTFOUND; } @@ -938,24 +899,20 @@ static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_p uint64_t min_proc_time_ms = UINT64_MAX; uint64_t max_proc_time_ms = 0; - if (do_timing) - { + if(do_timing) { start_ts_ms = scap_get_monotonic_ts_ms(&monotonic_ts_context); last_log_ts_ms = start_ts_ms; last_proc_ts_ms = start_ts_ms; } bool timeout_expired = false; - while (!timeout_expired) - { + while(!timeout_expired) { dir_entry_p = readdir(dir_p); - if (dir_entry_p == NULL) - { + if(dir_entry_p == NULL) { break; } - if(strspn(dir_entry_p->d_name, "0123456789") != strlen(dir_entry_p->d_name)) - { + if(strspn(dir_entry_p->d_name, "0123456789") != strlen(dir_entry_p->d_name)) { continue; } @@ -968,8 +925,7 @@ static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_p // If this is a recursive call for tasks of a parent process, // skip the main thread entry // - if(parenttid != -1 && tid == parenttid) - { + if(parenttid != -1 && tid == parenttid) { continue; } @@ -979,10 +935,9 @@ static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_p // list to see if we've encountered this tid already // HASH_FIND_INT64(proclist->m_proclist, &tid, tinfo); - if(tinfo != NULL) - { + if(tinfo != NULL) { ASSERT(false); - res = scap_errprintf(error, 0, "duplicate process %"PRIu64, tid); + res = scap_errprintf(error, 0, "duplicate process %" PRIu64, tid); break; } @@ -992,10 +947,14 @@ static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_p // We have a process that needs to be explored // uint64_t num_fds_this_proc; - res = scap_proc_add_from_proc(linux_platform, proclist, tid, procdirname, &sockets_by_ns, - &num_fds_this_proc, add_error); - if(res != SCAP_SUCCESS) - { + res = scap_proc_add_from_proc(linux_platform, + proclist, + tid, + procdirname, + &sockets_by_ns, + &num_fds_this_proc, + add_error); + if(res != SCAP_SUCCESS) { // // When a /proc lookup fails (while scanning the whole directory, // not just while looking up a single tid), @@ -1016,11 +975,10 @@ static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_p // See if this process includes tasks that need to be added // Note the use of recursion will re-enter this function for the childdir. // - if(parenttid == -1 && !linux_platform->m_minimal_scan) - { + if(parenttid == -1 && !linux_platform->m_minimal_scan) { snprintf(childdir, sizeof(childdir), "%s/%u/task", procdirname, (int)tid); - if(_scap_proc_scan_proc_dir_impl(linux_platform, proclist, childdir, tid, error) == SCAP_FAILURE) - { + if(_scap_proc_scan_proc_dir_impl(linux_platform, proclist, childdir, tid, error) == + SCAP_FAILURE) { res = SCAP_FAILURE; break; } @@ -1033,100 +991,89 @@ static int32_t _scap_proc_scan_proc_dir_impl(struct scap_linux_platform* linux_p // After successful processing of a process at the top level, // perform timing processing if configured. - if (do_timing) - { + if(do_timing) { cur_ts_ms = scap_get_monotonic_ts_ms(&monotonic_ts_context); uint64_t total_elapsed_time_ms = cur_ts_ms - start_ts_ms; uint64_t this_proc_elapsed_time_ms = cur_ts_ms - last_proc_ts_ms; last_proc_ts_ms = cur_ts_ms; - if (this_proc_elapsed_time_ms < min_proc_time_ms) - { + if(this_proc_elapsed_time_ms < min_proc_time_ms) { min_proc_time_ms = this_proc_elapsed_time_ms; } - if (this_proc_elapsed_time_ms > max_proc_time_ms) - { + if(this_proc_elapsed_time_ms > max_proc_time_ms) { max_proc_time_ms = this_proc_elapsed_time_ms; } - if (linux_platform->m_proc_scan_log_interval_ms != SCAP_PROC_SCAN_LOG_NONE) - { + if(linux_platform->m_proc_scan_log_interval_ms != SCAP_PROC_SCAN_LOG_NONE) { uint64_t log_elapsed_time_ms = cur_ts_ms - last_log_ts_ms; - if (log_elapsed_time_ms >= linux_platform->m_proc_scan_log_interval_ms) - { + if(log_elapsed_time_ms >= linux_platform->m_proc_scan_log_interval_ms) { scap_debug_log(linux_platform, - "scap_proc_scan: %ld proc in %ld ms, avg=%ld/min=%ld/max=%ld, last pid %ld, num_fds %ld", - num_procs_processed, - total_elapsed_time_ms, - (total_elapsed_time_ms / (uint64_t)num_procs_processed), - min_proc_time_ms, - max_proc_time_ms, - last_tid_processed, - total_num_fds); + "scap_proc_scan: %ld proc in %ld ms, avg=%ld/min=%ld/max=%ld, " + "last pid %ld, num_fds %ld", + num_procs_processed, + total_elapsed_time_ms, + (total_elapsed_time_ms / (uint64_t)num_procs_processed), + min_proc_time_ms, + max_proc_time_ms, + last_tid_processed, + total_num_fds); last_log_ts_ms = cur_ts_ms; } } - if (linux_platform->m_proc_scan_timeout_ms != SCAP_PROC_SCAN_TIMEOUT_NONE) - { - if (total_elapsed_time_ms >= linux_platform->m_proc_scan_timeout_ms) - { + if(linux_platform->m_proc_scan_timeout_ms != SCAP_PROC_SCAN_TIMEOUT_NONE) { + if(total_elapsed_time_ms >= linux_platform->m_proc_scan_timeout_ms) { timeout_expired = true; } } } } - if (do_timing) - { + if(do_timing) { cur_ts_ms = scap_get_monotonic_ts_ms(&monotonic_ts_context); uint64_t total_elapsed_time_ms = cur_ts_ms - start_ts_ms; - uint64_t avg_proc_time_ms = (num_procs_processed != 0) ? - (total_elapsed_time_ms / num_procs_processed) : 0; + uint64_t avg_proc_time_ms = + (num_procs_processed != 0) ? (total_elapsed_time_ms / num_procs_processed) : 0; - if (timeout_expired) - { + if(timeout_expired) { scap_debug_log(linux_platform, - "scap_proc_scan TIMEOUT (%ld ms): %ld proc in %ld ms, avg=%ld/min=%ld/max=%ld, last pid %ld, num_fds %ld", - linux_platform->m_proc_scan_timeout_ms, - num_procs_processed, - total_elapsed_time_ms, - avg_proc_time_ms, - min_proc_time_ms, - max_proc_time_ms, - last_tid_processed, - total_num_fds); - } - else if ((linux_platform->m_proc_scan_log_interval_ms != SCAP_PROC_SCAN_LOG_NONE) && - (num_procs_processed != 0)) - { + "scap_proc_scan TIMEOUT (%ld ms): %ld proc in %ld ms, " + "avg=%ld/min=%ld/max=%ld, last pid %ld, num_fds %ld", + linux_platform->m_proc_scan_timeout_ms, + num_procs_processed, + total_elapsed_time_ms, + avg_proc_time_ms, + min_proc_time_ms, + max_proc_time_ms, + last_tid_processed, + total_num_fds); + } else if((linux_platform->m_proc_scan_log_interval_ms != SCAP_PROC_SCAN_LOG_NONE) && + (num_procs_processed != 0)) { scap_debug_log(linux_platform, - "scap_proc_scan DONE: %ld proc in %ld ms, avg=%ld/min=%ld/max=%ld, last pid %ld, num_fds %ld", - num_procs_processed, - total_elapsed_time_ms, - avg_proc_time_ms, - min_proc_time_ms, - max_proc_time_ms, - last_tid_processed, - total_num_fds); + "scap_proc_scan DONE: %ld proc in %ld ms, avg=%ld/min=%ld/max=%ld, last " + "pid %ld, num_fds %ld", + num_procs_processed, + total_elapsed_time_ms, + avg_proc_time_ms, + min_proc_time_ms, + max_proc_time_ms, + last_tid_processed, + total_num_fds); } } closedir(dir_p); - if(sockets_by_ns != NULL && sockets_by_ns != (void*)-1) - { + if(sockets_by_ns != NULL && sockets_by_ns != (void*)-1) { scap_fd_free_ns_sockets_list(&sockets_by_ns); } return res; } -int32_t scap_linux_getpid_global(struct scap_platform* platform, int64_t *pid, char* error) -{ +int32_t scap_linux_getpid_global(struct scap_platform* platform, int64_t* pid, char* error) { struct scap_linux_platform* linux_platform = (struct scap_linux_platform*)platform; - if(linux_platform->m_linux_vtable && linux_platform->m_linux_vtable->getpid_global) - { + if(linux_platform->m_linux_vtable && linux_platform->m_linux_vtable->getpid_global) { return linux_platform->m_linux_vtable->getpid_global(linux_platform->m_engine, pid, error); } @@ -1136,16 +1083,13 @@ int32_t scap_linux_getpid_global(struct scap_platform* platform, int64_t *pid, c snprintf(filename, sizeof(filename), "%s/proc/self/status", scap_get_host_root()); FILE* f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { ASSERT(false); return scap_errprintf(error, errno, "can not open status file %s", filename); } - while(fgets(line, sizeof(line), f) != NULL) - { - if(sscanf(line, "Tgid: %" PRId64, pid) == 1) - { + while(fgets(line, sizeof(line), f) != NULL) { + if(sscanf(line, "Tgid: %" PRId64, pid) == 1) { fclose(f); return SCAP_SUCCESS; } @@ -1155,95 +1099,110 @@ int32_t scap_linux_getpid_global(struct scap_platform* platform, int64_t *pid, c return scap_errprintf(error, 0, "could not find tgid in status file %s", filename); } -int32_t scap_linux_proc_get(struct scap_platform* platform, int64_t tid, - struct scap_threadinfo* tinfo, bool scan_sockets) -{ +int32_t scap_linux_proc_get(struct scap_platform* platform, + int64_t tid, + struct scap_threadinfo* tinfo, + bool scan_sockets) { struct scap_linux_platform* linux_platform = (struct scap_linux_platform*)platform; char filename[SCAP_MAX_PATH_SIZE]; snprintf(filename, sizeof(filename), "%s/proc", scap_get_host_root()); - return scap_proc_read_thread(linux_platform, filename, tid, tinfo, linux_platform->m_lasterr, scan_sockets); + return scap_proc_read_thread(linux_platform, + filename, + tid, + tinfo, + linux_platform->m_lasterr, + scan_sockets); } -bool scap_linux_is_thread_alive(struct scap_platform* platform, int64_t pid, int64_t tid, const char* comm) -{ +bool scap_linux_is_thread_alive(struct scap_platform* platform, + int64_t pid, + int64_t tid, + const char* comm) { char charbuf[SCAP_MAX_PATH_SIZE]; FILE* f; - snprintf(charbuf, sizeof(charbuf), "%s/proc/%" PRId64 "/task/%" PRId64 "/comm", scap_get_host_root(), pid, tid); + snprintf(charbuf, + sizeof(charbuf), + "%s/proc/%" PRId64 "/task/%" PRId64 "/comm", + scap_get_host_root(), + pid, + tid); f = fopen(charbuf, "r"); - if(f != NULL) - { - if(fgets(charbuf, sizeof(charbuf), f) != NULL) - { - if(strncmp(charbuf, comm, strlen(comm)) == 0) - { + if(f != NULL) { + if(fgets(charbuf, sizeof(charbuf), f) != NULL) { + if(strncmp(charbuf, comm, strlen(comm)) == 0) { fclose(f); return true; } } fclose(f); - } - else - { + } else { // - // If /proc//task//comm does not exist but /proc//task//exe does exist, we assume we're on an ancient - // OS like RHEL5 and we return true. - // This could generate some false positives on such old distros, and we're going to accept it. + // If /proc//task//comm does not exist but /proc//task//exe does exist, + // we assume we're on an ancient OS like RHEL5 and we return true. This could generate some + // false positives on such old distros, and we're going to accept it. // - snprintf(charbuf, sizeof(charbuf), "%s/proc/%" PRId64 "/task/%" PRId64 "/exe", scap_get_host_root(), pid, tid); + snprintf(charbuf, + sizeof(charbuf), + "%s/proc/%" PRId64 "/task/%" PRId64 "/exe", + scap_get_host_root(), + pid, + tid); f = fopen(charbuf, "r"); - if(f != NULL) - { + if(f != NULL) { fclose(f); return true; } - } return false; } -int32_t scap_linux_refresh_proc_table(struct scap_platform* platform, struct scap_proclist* proclist) -{ +int32_t scap_linux_refresh_proc_table(struct scap_platform* platform, + struct scap_proclist* proclist) { char procdirname[SCAP_MAX_PATH_SIZE]; struct scap_linux_platform* linux_platform = (struct scap_linux_platform*)platform; - if(proclist->m_proclist) - { + if(proclist->m_proclist) { scap_proc_free_table(proclist); proclist->m_proclist = NULL; } snprintf(procdirname, sizeof(procdirname), "%s/proc", scap_get_host_root()); scap_cgroup_enable_cache(&linux_platform->m_cgroups); - int32_t ret = _scap_proc_scan_proc_dir_impl(linux_platform, proclist, procdirname, -1, linux_platform->m_lasterr); + int32_t ret = _scap_proc_scan_proc_dir_impl(linux_platform, + proclist, + procdirname, + -1, + linux_platform->m_lasterr); scap_cgroup_clear_cache(&linux_platform->m_cgroups); return ret; } -int32_t scap_linux_get_threadlist(struct scap_platform* platform, struct ppm_proclist_info **procinfo_p, char *lasterr) -{ +int32_t scap_linux_get_threadlist(struct scap_platform* platform, + struct ppm_proclist_info** procinfo_p, + char* lasterr) { struct scap_linux_platform* linux_platform = (struct scap_linux_platform*)platform; - if(linux_platform->m_linux_vtable && linux_platform->m_linux_vtable->get_threadlist) - { - return linux_platform->m_linux_vtable->get_threadlist(linux_platform->m_engine, procinfo_p, lasterr); + if(linux_platform->m_linux_vtable && linux_platform->m_linux_vtable->get_threadlist) { + return linux_platform->m_linux_vtable->get_threadlist(linux_platform->m_engine, + procinfo_p, + lasterr); } - DIR *dir_p = NULL; - FILE *fp = NULL; - struct dirent *dir_entry_p; + DIR* dir_p = NULL; + FILE* fp = NULL; + struct dirent* dir_entry_p; char procdirname[SCAP_MAX_PATH_SIZE]; - if(*procinfo_p == NULL) - { - if(scap_alloc_proclist_info(procinfo_p, SCAP_DRIVER_PROCINFO_INITIAL_SIZE, lasterr) == false) - { + if(*procinfo_p == NULL) { + if(scap_alloc_proclist_info(procinfo_p, SCAP_DRIVER_PROCINFO_INITIAL_SIZE, lasterr) == + false) { return SCAP_FAILURE; } } @@ -1253,63 +1212,65 @@ int32_t scap_linux_get_threadlist(struct scap_platform* platform, struct ppm_pro snprintf(procdirname, sizeof(procdirname), "%s/proc", scap_get_host_root()); dir_p = opendir(procdirname); - if(dir_p == NULL) - { + if(dir_p == NULL) { scap_errprintf(lasterr, errno, "error opening the %s directory", procdirname); goto error; } - while((dir_entry_p = readdir(dir_p)) != NULL) - { + while((dir_entry_p = readdir(dir_p)) != NULL) { char tasksdirname[SCAP_MAX_PATH_SIZE]; - struct dirent *taskdir_entry_p; - DIR *taskdir_p; + struct dirent* taskdir_entry_p; + DIR* taskdir_p; - if(strspn(dir_entry_p->d_name, "0123456789") != strlen(dir_entry_p->d_name)) - { + if(strspn(dir_entry_p->d_name, "0123456789") != strlen(dir_entry_p->d_name)) { continue; } - snprintf(tasksdirname, sizeof(tasksdirname), "%s/%s/task", procdirname, dir_entry_p->d_name); + snprintf(tasksdirname, + sizeof(tasksdirname), + "%s/%s/task", + procdirname, + dir_entry_p->d_name); taskdir_p = opendir(tasksdirname); - if(taskdir_p == NULL) - { + if(taskdir_p == NULL) { scap_errprintf(lasterr, errno, "error opening the %s directory", tasksdirname); continue; } - while((taskdir_entry_p = readdir(taskdir_p)) != NULL) - { + while((taskdir_entry_p = readdir(taskdir_p)) != NULL) { char filename[SCAP_MAX_PATH_SIZE]; unsigned long utime; unsigned long stime; int tid; - if(strspn(taskdir_entry_p->d_name, "0123456789") != strlen(taskdir_entry_p->d_name)) - { + if(strspn(taskdir_entry_p->d_name, "0123456789") != strlen(taskdir_entry_p->d_name)) { continue; } - snprintf(filename, sizeof(filename), "%s/%s/stat", tasksdirname, taskdir_entry_p->d_name); + snprintf(filename, + sizeof(filename), + "%s/%s/stat", + tasksdirname, + taskdir_entry_p->d_name); fp = fopen(filename, "r"); - if(fp == NULL) - { + if(fp == NULL) { continue; } - if(fscanf(fp, "%d %*[^)] %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu %lu", &tid, &utime, &stime) != 3) - { + if(fscanf(fp, + "%d %*[^)] %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu %lu", + &tid, + &utime, + &stime) != 3) { fclose(fp); fp = NULL; continue; } - if((*procinfo_p)->n_entries == (*procinfo_p)->max_entries) - { - if(!scap_alloc_proclist_info(procinfo_p, (*procinfo_p)->n_entries + 256, lasterr)) - { + if((*procinfo_p)->n_entries == (*procinfo_p)->max_entries) { + if(!scap_alloc_proclist_info(procinfo_p, (*procinfo_p)->n_entries + 256, lasterr)) { goto error; } } @@ -1327,21 +1288,20 @@ int32_t scap_linux_get_threadlist(struct scap_platform* platform, struct ppm_pro taskdir_p = NULL; } - error: - if(dir_p) - { +error: + if(dir_p) { closedir(dir_p); } - if(fp) - { + if(fp) { fclose(fp); } return SCAP_SUCCESS; } -int32_t scap_linux_get_fdlist(struct scap_platform* platform, struct scap_threadinfo *tinfo, char *lasterr) -{ +int32_t scap_linux_get_fdlist(struct scap_platform* platform, + struct scap_threadinfo* tinfo, + char* lasterr) { int res = SCAP_SUCCESS; uint64_t num_fds_ret = 0; char proc_dir[SCAP_MAX_PATH_SIZE]; @@ -1351,9 +1311,14 @@ int32_t scap_linux_get_fdlist(struct scap_platform* platform, struct scap_thread // We collect file descriptors only for the main thread snprintf(proc_dir, sizeof(proc_dir), "%s/proc/%lu/", scap_get_host_root(), tinfo->pid); - res = scap_fd_scan_fd_dir(linux_platform, &platform->m_proclist, proc_dir, tinfo, &sockets_by_ns, &num_fds_ret, lasterr); - if(sockets_by_ns != NULL && sockets_by_ns != (void*)-1) - { + res = scap_fd_scan_fd_dir(linux_platform, + &platform->m_proclist, + proc_dir, + tinfo, + &sockets_by_ns, + &num_fds_ret, + lasterr); + if(sockets_by_ns != NULL && sockets_by_ns != (void*)-1) { scap_fd_free_ns_sockets_list(&sockets_by_ns); } return res; diff --git a/userspace/libscap/linux/scap_userlist.c b/userspace/libscap/linux/scap_userlist.c index 9741445657..6d0edc8de4 100644 --- a/userspace/libscap/linux/scap_userlist.c +++ b/userspace/libscap/linux/scap_userlist.c @@ -34,9 +34,8 @@ limitations under the License. // // Allocate and return the list of users on this system // -int32_t scap_linux_create_userlist(struct scap_platform* platform) -{ - struct scap_linux_platform* handle = (struct scap_linux_platform*)platform; +int32_t scap_linux_create_userlist(struct scap_platform *platform) { + struct scap_linux_platform *handle = (struct scap_linux_platform *)platform; bool file_lookup = false; FILE *f = NULL; char filename[SCAP_MAX_PATH_SIZE]; @@ -50,8 +49,7 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) // If the list of users was already allocated for this handle (for example because this is // not the first user list block), free it // - if(platform->m_userlist != NULL) - { + if(platform->m_userlist != NULL) { scap_free_userlist(platform->m_userlist); platform->m_userlist = NULL; } @@ -59,30 +57,27 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) // // Memory allocations // - platform->m_userlist = (scap_userlist*)malloc(sizeof(scap_userlist)); - if(platform->m_userlist == NULL) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation failed(1)"); + platform->m_userlist = (scap_userlist *)malloc(sizeof(scap_userlist)); + if(platform->m_userlist == NULL) { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation failed(1)"); return SCAP_FAILURE; } userlist = platform->m_userlist; userlist->totsavelen = 0; - usercnt = 32; // initial user count; will be realloc'd if needed - userlist->users = (scap_userinfo*)malloc(usercnt * sizeof(scap_userinfo)); - if(userlist->users == NULL) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation failed(2)"); + usercnt = 32; // initial user count; will be realloc'd if needed + userlist->users = (scap_userinfo *)malloc(usercnt * sizeof(scap_userinfo)); + if(userlist->users == NULL) { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation failed(2)"); free(userlist); platform->m_userlist = NULL; return SCAP_FAILURE; } - grpcnt = 32; // initial group count; will be realloc'd if needed - userlist->groups = (scap_groupinfo*)malloc(grpcnt * sizeof(scap_groupinfo)); - if(userlist->groups == NULL) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "grouplist allocation failed(2)"); + grpcnt = 32; // initial group count; will be realloc'd if needed + userlist->groups = (scap_groupinfo *)malloc(grpcnt * sizeof(scap_groupinfo)); + if(userlist->groups == NULL) { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "grouplist allocation failed(2)"); free(userlist->users); free(userlist); platform->m_userlist = NULL; @@ -91,22 +86,17 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) // check for host root const char *host_root = scap_get_host_root(); - if(host_root[0] == '\0') - { + if(host_root[0] == '\0') { file_lookup = false; - } - else - { + } else { file_lookup = true; } // users - if(file_lookup) - { + if(file_lookup) { snprintf(filename, sizeof(filename), "%s/etc/passwd", host_root); f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { // if we don't have it inside the host root, we'll proceed without a list free(userlist->users); free(userlist->groups); @@ -114,35 +104,25 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) platform->m_userlist = NULL; return SCAP_SUCCESS; } - } - else - { + } else { setpwent(); } - for(useridx = 0; file_lookup ? (p = fgetpwent(f)) : (p = getpwent()); useridx++) - { - if (useridx == usercnt) - { - usercnt<<=1; + for(useridx = 0; file_lookup ? (p = fgetpwent(f)) : (p = getpwent()); useridx++) { + if(useridx == usercnt) { + usercnt <<= 1; void *tmp = realloc(userlist->users, usercnt * sizeof(scap_userinfo)); - if (tmp) - { + if(tmp) { userlist->users = tmp; - } - else - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation failed(2)"); + } else { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation failed(2)"); free(userlist->users); free(userlist->groups); free(userlist); platform->m_userlist = NULL; - if(file_lookup) - { + if(file_lookup) { fclose(f); - } - else - { + } else { endpwent(); } return SCAP_FAILURE; @@ -152,62 +132,49 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) scap_userinfo *user = &userlist->users[useridx]; user->uid = p->pw_uid; user->gid = p->pw_gid; - - if(p->pw_name) - { + + if(p->pw_name) { strlcpy(user->name, p->pw_name, sizeof(user->name)); - } - else - { + } else { *user->name = '\0'; } - if(p->pw_dir) - { + if(p->pw_dir) { strlcpy(user->homedir, p->pw_dir, sizeof(user->homedir)); - } - else - { + } else { *user->homedir = '\0'; } - if(p->pw_shell) - { + if(p->pw_shell) { strlcpy(user->shell, p->pw_shell, sizeof(user->shell)); - } - else - { + } else { *user->shell = '\0'; } - userlist->totsavelen += - sizeof(uint8_t) + // type - sizeof(uint32_t) + // uid - sizeof(uint32_t) + // gid - strlen(user->name) + 2 + - strlen(user->homedir) + 2 + - strlen(user->shell) + 2; + userlist->totsavelen += sizeof(uint8_t) + // type + sizeof(uint32_t) + // uid + sizeof(uint32_t) + // gid + strlen(user->name) + 2 + strlen(user->homedir) + 2 + + strlen(user->shell) + 2; } - if(file_lookup) - { + if(file_lookup) { fclose(f); - } - else - { + } else { endpwent(); } // if userIdx == 0 -> realloc with size 0 means free, and NULL is returned. // so, we will end up with userlist->nusers = 0 and userlist->users NULL. userlist->nusers = useridx; - if (useridx < usercnt) - { + if(useridx < usercnt) { // Reduce array size - scap_userinfo *reduced_userinfos = realloc(userlist->users, useridx * sizeof(scap_userinfo)); - if(reduced_userinfos == NULL && useridx > 0) - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "userlist allocation while reducing array size"); + scap_userinfo *reduced_userinfos = + realloc(userlist->users, useridx * sizeof(scap_userinfo)); + if(reduced_userinfos == NULL && useridx > 0) { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "userlist allocation while reducing array size"); free(userlist->users); free(userlist->groups); free(userlist); @@ -218,12 +185,10 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) } // groups - if(file_lookup) - { + if(file_lookup) { snprintf(filename, sizeof(filename), "%s/etc/group", host_root); f = fopen(filename, "r"); - if(f == NULL) - { + if(f == NULL) { // if we reached this point we had passwd but we don't have group snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "failed to open %s", filename); free(userlist->users); @@ -232,35 +197,25 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) platform->m_userlist = NULL; return SCAP_FAILURE; } - } - else - { + } else { setgrent(); } - for(grpidx = 0; file_lookup ? (g = fgetgrent(f)) : (g = getgrent()); grpidx++) - { - if (grpidx == grpcnt) - { - grpcnt<<=1; + for(grpidx = 0; file_lookup ? (g = fgetgrent(f)) : (g = getgrent()); grpidx++) { + if(grpidx == grpcnt) { + grpcnt <<= 1; void *tmp = realloc(userlist->groups, grpcnt * sizeof(scap_groupinfo)); - if (tmp) - { + if(tmp) { userlist->groups = tmp; - } - else - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "grouplist allocation failed(2)"); + } else { + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "grouplist allocation failed(2)"); free(userlist->users); free(userlist->groups); free(userlist); platform->m_userlist = NULL; - if(file_lookup) - { + if(file_lookup) { fclose(f); - } - else - { + } else { endgrent(); } return SCAP_FAILURE; @@ -269,39 +224,30 @@ int32_t scap_linux_create_userlist(struct scap_platform* platform) scap_groupinfo *group = &userlist->groups[grpidx]; group->gid = g->gr_gid; - if(g->gr_name) - { + if(g->gr_name) { strlcpy(group->name, g->gr_name, sizeof(group->name)); - } - else - { + } else { *group->name = '\0'; } - userlist->totsavelen += - sizeof(uint8_t) + // type - sizeof(uint32_t) + // gid - strlen(group->name) + 2; + userlist->totsavelen += sizeof(uint8_t) + // type + sizeof(uint32_t) + // gid + strlen(group->name) + 2; } - if(file_lookup) - { + if(file_lookup) { fclose(f); - } - else - { + } else { endgrent(); } // if grpidx == 0 -> realloc with size 0 means free, and NULL is returned. // so, we will end up with userlist->ngroups = 0 and userlist->groups NULL. userlist->ngroups = grpidx; - if (grpidx < grpcnt) - { + if(grpidx < grpcnt) { // Reduce array size scap_groupinfo *reduced_groups = realloc(userlist->groups, grpidx * sizeof(scap_groupinfo)); - if(reduced_groups == NULL && grpidx > 0) - { + if(reduced_groups == NULL && grpidx > 0) { snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "grouplist allocation failed(2)"); free(userlist->users); free(userlist->groups); diff --git a/userspace/libscap/linux/sleep.h b/userspace/libscap/linux/sleep.h index 26578cdd87..4e0db527d0 100644 --- a/userspace/libscap/linux/sleep.h +++ b/userspace/libscap/linux/sleep.h @@ -20,7 +20,6 @@ limitations under the License. #include -static inline void sleep_ms(int ms) -{ +static inline void sleep_ms(int ms) { usleep(ms * 1000); } diff --git a/userspace/libscap/linux/unixid.h b/userspace/libscap/linux/unixid.h index 7ea0c19033..d9a164858b 100644 --- a/userspace/libscap/linux/unixid.h +++ b/userspace/libscap/linux/unixid.h @@ -27,11 +27,10 @@ limitations under the License. \return On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error. */ -static inline int thread_seteuid(uid_t uid) -{ +static inline int thread_seteuid(uid_t uid) { int result; - if (uid == (uid_t) ~0) { + if(uid == (uid_t)~0) { errno = EINVAL; return -1; } @@ -51,11 +50,10 @@ static inline int thread_seteuid(uid_t uid) \return On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error. */ -static inline int thread_setegid(gid_t gid) -{ +static inline int thread_setegid(gid_t gid) { int result; - if (gid == (gid_t) ~0) { + if(gid == (gid_t)~0) { errno = EINVAL; return -1; } diff --git a/userspace/libscap/macos/gettimeofday.h b/userspace/libscap/macos/gettimeofday.h index 58af1b8064..21c6fc8841 100644 --- a/userspace/libscap/macos/gettimeofday.h +++ b/userspace/libscap/macos/gettimeofday.h @@ -21,14 +21,12 @@ limitations under the License. #include #include -static inline uint64_t get_timestamp_ns() -{ +static inline uint64_t get_timestamp_ns() { uint64_t ts; struct timeval tv; gettimeofday(&tv, NULL); - ts = tv.tv_sec * (uint64_t) 1000000000 + tv.tv_usec * 1000; + ts = tv.tv_sec * (uint64_t)1000000000 + tv.tv_usec * 1000; return ts; } - diff --git a/userspace/libscap/macos/sleep.h b/userspace/libscap/macos/sleep.h index 26578cdd87..4e0db527d0 100644 --- a/userspace/libscap/macos/sleep.h +++ b/userspace/libscap/macos/sleep.h @@ -20,7 +20,6 @@ limitations under the License. #include -static inline void sleep_ms(int ms) -{ +static inline void sleep_ms(int ms) { usleep(ms * 1000); } diff --git a/userspace/libscap/metrics_v2.h b/userspace/libscap/metrics_v2.h index 896ed16709..623bd25839 100644 --- a/userspace/libscap/metrics_v2.h +++ b/userspace/libscap/metrics_v2.h @@ -24,7 +24,6 @@ limitations under the License. extern "C" { #endif - // // Limits for metrics_v2 metric name // @@ -57,7 +56,8 @@ extern "C" { #define METRICS_V2_RULE_COUNTERS (1 << 4) #define METRICS_V2_MISC (1 << 5) #define METRICS_V2_PLUGINS (1 << 6) -#define METRICS_V2_KERNEL_COUNTERS_PER_CPU (1 << 7) // Requesting this does also silently enable METRICS_V2_KERNEL_COUNTERS +#define METRICS_V2_KERNEL_COUNTERS_PER_CPU \ + (1 << 7) // Requesting this does also silently enable METRICS_V2_KERNEL_COUNTERS typedef union metrics_v2_value { uint32_t u32; @@ -69,7 +69,7 @@ typedef union metrics_v2_value { int i; } metrics_v2_value; -typedef enum metrics_v2_value_type{ +typedef enum metrics_v2_value_type { METRIC_VALUE_TYPE_U32, METRIC_VALUE_TYPE_S32, METRIC_VALUE_TYPE_U64, @@ -80,7 +80,7 @@ typedef enum metrics_v2_value_type{ METRIC_VALUE_TYPE_MAX, } metrics_v2_value_type; -typedef enum metrics_v2_value_unit{ +typedef enum metrics_v2_value_unit { METRIC_VALUE_UNIT_COUNT, METRIC_VALUE_UNIT_RATIO, METRIC_VALUE_UNIT_PERC, @@ -95,7 +95,7 @@ typedef enum metrics_v2_value_unit{ METRIC_VALUE_UNIT_MAX, } metrics_v2_value_unit; -typedef enum metrics_v2_metric_type{ +typedef enum metrics_v2_metric_type { METRIC_VALUE_METRIC_TYPE_MONOTONIC, METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, METRIC_VALUE_METRIC_TYPE_MAX, @@ -104,8 +104,7 @@ typedef enum metrics_v2_metric_type{ /*! \brief Metrics schema, used for libscap and libsinsp metrics about an in progress capture. */ -typedef struct metrics_v2 -{ +typedef struct metrics_v2 { /* Metric metadata */ char name[METRIC_NAME_MAX]; uint32_t flags; diff --git a/userspace/libscap/ppm_sc_names.c b/userspace/libscap/ppm_sc_names.c index 858126f687..f6e0afc438 100644 --- a/userspace/libscap/ppm_sc_names.c +++ b/userspace/libscap/ppm_sc_names.c @@ -38,40 +38,34 @@ limitations under the License. static char g_ppm_sc_names[PPM_SC_MAX][PPM_MAX_NAME_LEN]; -static void load_ppm_sc_table() -{ +static void load_ppm_sc_table() { const char *sc_names[PPM_SC_MAX] = { #define PPM_SC_X(name, value) [value] = #name, - PPM_SC_FIELDS + PPM_SC_FIELDS #undef PPM_SC_X }; /* Use `tolower` to obtain lowe case names. */ - for(int i = 0; i < PPM_SC_MAX; i++) - { - if(!sc_names[i]) - { + for(int i = 0; i < PPM_SC_MAX; i++) { + if(!sc_names[i]) { continue; } strlcpy(g_ppm_sc_names[i], sc_names[i], PPM_MAX_NAME_LEN); char *p = g_ppm_sc_names[i]; - for(; *p; ++p) - { + for(; *p; ++p) { *p = tolower(*p); } } } /* Get the name of the sc_code */ -const char *scap_get_ppm_sc_name(ppm_sc_code sc) -{ +const char *scap_get_ppm_sc_name(ppm_sc_code sc) { /* We avoid the check for perf reasons */ ASSERT(sc >= 0 && sc < PPM_SC_MAX); /* Lazy loading */ - if(g_ppm_sc_names[0][0] == '\0') - { + if(g_ppm_sc_names[0][0] == '\0') { load_ppm_sc_table(); } return g_ppm_sc_names[sc]; diff --git a/userspace/libscap/ringbuffer/devset.c b/userspace/libscap/ringbuffer/devset.c index 7dad0adc9f..c719d0ac4d 100644 --- a/userspace/libscap/ringbuffer/devset.c +++ b/userspace/libscap/ringbuffer/devset.c @@ -25,19 +25,16 @@ limitations under the License. #include #include -int32_t devset_init(struct scap_device_set *devset, size_t num_devs, char *lasterr) -{ +int32_t devset_init(struct scap_device_set *devset, size_t num_devs, char *lasterr) { devset->m_ndevs = num_devs; - devset->m_devs = (scap_device*) calloc(devset->m_ndevs, sizeof(scap_device)); - if(!devset->m_devs) - { + devset->m_devs = (scap_device *)calloc(devset->m_ndevs, sizeof(scap_device)); + if(!devset->m_devs) { strlcpy(lasterr, "error allocating the device handles", SCAP_LASTERR_SIZE); return SCAP_FAILURE; } - for(size_t j = 0; j < num_devs; ++j) - { + for(size_t j = 0; j < num_devs; ++j) { devset->m_devs[j].m_buffer = INVALID_MAPPING; devset->m_devs[j].m_bufinfo = INVALID_MAPPING; devset->m_devs[j].m_bufstatus = INVALID_MAPPING; @@ -52,24 +49,20 @@ int32_t devset_init(struct scap_device_set *devset, size_t num_devs, char *laste return SCAP_SUCCESS; } -void devset_close_device(struct scap_device *dev) -{ +void devset_close_device(struct scap_device *dev) { devset_munmap(dev->m_buffer, dev->m_mmap_size); devset_munmap(dev->m_bufinfo, dev->m_bufinfo_size); devset_close(dev->m_fd); devset_close(dev->m_bufinfo_fd); } -void devset_free(struct scap_device_set *devset) -{ - if(devset == NULL || devset->m_devs == NULL) - { +void devset_free(struct scap_device_set *devset) { + if(devset == NULL || devset->m_devs == NULL) { return; } uint32_t j; - for(j = 0; j < devset->m_ndevs; j++) - { + for(j = 0; j < devset->m_ndevs; j++) { struct scap_device *dev = &devset->m_devs[j]; devset_close_device(dev); } diff --git a/userspace/libscap/ringbuffer/devset.h b/userspace/libscap/ringbuffer/devset.h index 5f1780be7c..a61168dea7 100644 --- a/userspace/libscap/ringbuffer/devset.h +++ b/userspace/libscap/ringbuffer/devset.h @@ -41,54 +41,46 @@ struct udig_ring_buffer_status; // // The device descriptor // -typedef struct scap_device -{ +typedef struct scap_device { int m_fd; - int m_bufinfo_fd; // used by udig + int m_bufinfo_fd; // used by udig char* m_buffer; unsigned long m_buffer_size; - unsigned long m_mmap_size; // generally 2 * m_buffer_size, but bpf does weird things + unsigned long m_mmap_size; // generally 2 * m_buffer_size, but bpf does weird things uint32_t m_lastreadsize; - char* m_sn_next_event; // Pointer to the next event available for scap_next - uint32_t m_sn_len; // Number of bytes available in the buffer pointed by m_sn_next_event - union - { + char* m_sn_next_event; // Pointer to the next event available for scap_next + uint32_t m_sn_len; // Number of bytes available in the buffer pointed by m_sn_next_event + union { // Anonymous struct with ppm stuff - struct - { + struct { struct ppm_ring_buffer_info* m_bufinfo; int m_bufinfo_size; - struct udig_ring_buffer_status* m_bufstatus; // used by udig + struct udig_ring_buffer_status* m_bufstatus; // used by udig }; }; } scap_device; -struct scap_device_set -{ +struct scap_device_set { scap_device* m_devs; uint32_t m_ndevs; uint64_t m_buffer_empty_wait_time_us; char* m_lasterr; }; -int32_t devset_init(struct scap_device_set *devset, size_t num_devs, char *lasterr); -void devset_close_device(struct scap_device *dev); -void devset_free(struct scap_device_set *devset); +int32_t devset_init(struct scap_device_set* devset, size_t num_devs, char* lasterr); +void devset_close_device(struct scap_device* dev); +void devset_free(struct scap_device_set* devset); -static inline void devset_munmap(void* addr, size_t size) -{ - if(addr != INVALID_MAPPING) - { +static inline void devset_munmap(void* addr, size_t size) { + if(addr != INVALID_MAPPING) { int ret = munmap(addr, size); ASSERT(ret == 0); - (void) ret; + (void)ret; } } -static inline void devset_close(int fd) -{ - if(fd != INVALID_FD) - { +static inline void devset_close(int fd) { + if(fd != INVALID_FD) { close(fd); } } diff --git a/userspace/libscap/ringbuffer/ringbuffer.c b/userspace/libscap/ringbuffer/ringbuffer.c index da70c7a626..b3c58cf00e 100644 --- a/userspace/libscap/ringbuffer/ringbuffer.c +++ b/userspace/libscap/ringbuffer/ringbuffer.c @@ -24,8 +24,7 @@ limitations under the License. #include #include -int32_t check_buffer_bytes_dim(char* last_err, unsigned long buf_bytes_dim) -{ +int32_t check_buffer_bytes_dim(char* last_err, unsigned long buf_bytes_dim) { /* If you face some memory allocation issues, please remember that: * * Each data page is mapped twice to allow "virtual" @@ -46,20 +45,24 @@ int32_t check_buffer_bytes_dim(char* last_err, unsigned long buf_bytes_dim) */ unsigned long page_size = sysconf(_SC_PAGESIZE); - if(page_size == SCAP_FAILURE) - { - if(last_err != NULL) - { - snprintf(last_err, SCAP_LASTERR_SIZE, "unable to get the system page size: %s", strerror(errno)); + if(page_size == SCAP_FAILURE) { + if(last_err != NULL) { + snprintf(last_err, + SCAP_LASTERR_SIZE, + "unable to get the system page size: %s", + strerror(errno)); } return SCAP_FAILURE; } - if(!validate_buffer_bytes_dim(buf_bytes_dim, page_size)) - { - if(last_err != NULL) - { - snprintf(last_err, SCAP_LASTERR_SIZE, "the specified per-CPU ring buffer dimension (%lu) is not allowed! Please use a power of 2 and a multiple of the actual page_size (%lu)!", buf_bytes_dim, page_size); + if(!validate_buffer_bytes_dim(buf_bytes_dim, page_size)) { + if(last_err != NULL) { + snprintf(last_err, + SCAP_LASTERR_SIZE, + "the specified per-CPU ring buffer dimension (%lu) is not allowed! Please use " + "a power of 2 and a multiple of the actual page_size (%lu)!", + buf_bytes_dim, + page_size); } return SCAP_FAILURE; } diff --git a/userspace/libscap/ringbuffer/ringbuffer.h b/userspace/libscap/ringbuffer/ringbuffer.h index 987454abe8..36d3cba96e 100644 --- a/userspace/libscap/ringbuffer/ringbuffer.h +++ b/userspace/libscap/ringbuffer/ringbuffer.h @@ -25,27 +25,25 @@ limitations under the License. #include #include -/* Check buffer dimension in bytes. +/* Check buffer dimension in bytes. * Our 2 eBPF probes require that this number is a power of 2! Right now we force this * constraint to all our drivers (also the kernel module and udig) just for conformity. */ int32_t check_buffer_bytes_dim(char* error, unsigned long buf_bytes_dim); - #ifndef GET_BUF_POINTERS #define GET_BUF_POINTERS ringbuffer_get_buf_pointers -static inline void ringbuffer_get_buf_pointers(scap_device* dev, uint64_t* phead, uint64_t* ptail, uint64_t* pread_size) -{ +static inline void ringbuffer_get_buf_pointers(scap_device* dev, + uint64_t* phead, + uint64_t* ptail, + uint64_t* pread_size) { struct ppm_ring_buffer_info* bufinfo = dev->m_bufinfo; *phead = bufinfo->head; *ptail = bufinfo->tail; - if(*ptail > *phead) - { + if(*ptail > *phead) { *pread_size = dev->m_buffer_size - *ptail + *phead; - } - else - { + } else { *pread_size = *phead - *ptail; } } @@ -53,8 +51,7 @@ static inline void ringbuffer_get_buf_pointers(scap_device* dev, uint64_t* phead #ifndef ADVANCE_TAIL #define ADVANCE_TAIL ringbuffer_advance_tail -static inline void ringbuffer_advance_tail(struct scap_device* dev) -{ +static inline void ringbuffer_advance_tail(struct scap_device* dev) { uint32_t ttail; // @@ -72,12 +69,9 @@ static inline void ringbuffer_advance_tail(struct scap_device* dev) // mem_barrier(); - if(ttail < dev->m_buffer_size) - { + if(ttail < dev->m_buffer_size) { dev->m_bufinfo->tail = ttail; - } - else - { + } else { dev->m_bufinfo->tail = ttail - dev->m_buffer_size; } @@ -91,8 +85,7 @@ static inline void ringbuffer_advance_tail(struct scap_device* dev) * \param buf [out] buffer holding the returned data * \param len [out] number of bytes read into buf */ -static inline int32_t ringbuffer_readbuf(struct scap_device *dev, char** buf, uint32_t* len) -{ +static inline int32_t ringbuffer_readbuf(struct scap_device* dev, char** buf, uint32_t* len) { uint64_t thead; uint64_t ttail; uint64_t read_size; @@ -100,10 +93,7 @@ static inline int32_t ringbuffer_readbuf(struct scap_device *dev, char** buf, ui // // Read the pointers. // - ringbuffer_get_buf_pointers(dev, - &thead, - &ttail, - &read_size); + ringbuffer_get_buf_pointers(dev, &thead, &ttail, &read_size); // // Remember read_size so we can update the tail at the next call @@ -120,8 +110,7 @@ static inline int32_t ringbuffer_readbuf(struct scap_device *dev, char** buf, ui } #endif -static inline uint64_t buf_size_used(scap_device* dev) -{ +static inline uint64_t buf_size_used(scap_device* dev) { uint64_t read_size; uint64_t thead; uint64_t ttail; @@ -134,14 +123,11 @@ static inline uint64_t buf_size_used(scap_device* dev) /* if at least one buffer has more than `BUFFER_EMPTY_THRESHOLD_B` return false * otherwise return true and consider all the buffers empty. */ -static inline bool are_buffers_empty(struct scap_device_set *devset) -{ +static inline bool are_buffers_empty(struct scap_device_set* devset) { uint32_t j; - for(j = 0; j < devset->m_ndevs; j++) - { - if(buf_size_used(&devset->m_devs[j]) > BUFFER_EMPTY_THRESHOLD_B) - { + for(j = 0; j < devset->m_ndevs; j++) { + if(buf_size_used(&devset->m_devs[j]) > BUFFER_EMPTY_THRESHOLD_B) { return false; } } @@ -149,33 +135,25 @@ static inline bool are_buffers_empty(struct scap_device_set *devset) return true; } -static inline int32_t refill_read_buffers(struct scap_device_set *devset) -{ +static inline int32_t refill_read_buffers(struct scap_device_set* devset) { uint32_t j; uint32_t ndevs = devset->m_ndevs; - if(are_buffers_empty(devset)) - { + if(are_buffers_empty(devset)) { sleep_ms(devset->m_buffer_empty_wait_time_us / 1000); - devset->m_buffer_empty_wait_time_us = MIN(devset->m_buffer_empty_wait_time_us * 2, - BUFFER_EMPTY_WAIT_TIME_US_MAX); - } - else - { + devset->m_buffer_empty_wait_time_us = + MIN(devset->m_buffer_empty_wait_time_us * 2, BUFFER_EMPTY_WAIT_TIME_US_MAX); + } else { devset->m_buffer_empty_wait_time_us = BUFFER_EMPTY_WAIT_TIME_US_START; } /* In any case (potentially also after a `sleep`) we refill our buffers */ - for(j = 0; j < ndevs; j++) - { - struct scap_device *dev = &(devset->m_devs[j]); + for(j = 0; j < ndevs; j++) { + struct scap_device* dev = &(devset->m_devs[j]); - int32_t res = READBUF(dev, - &dev->m_sn_next_event, - &dev->m_sn_len); + int32_t res = READBUF(dev, &dev->m_sn_next_event, &dev->m_sn_len); - if(res != SCAP_SUCCESS) - { + if(res != SCAP_SUCCESS) { return res; } } @@ -186,16 +164,14 @@ static inline int32_t refill_read_buffers(struct scap_device_set *devset) #ifndef NEXT_EVENT #define NEXT_EVENT ringbuffer_next_event -static inline scap_evt* ringbuffer_next_event(scap_device* dev) -{ +static inline scap_evt* ringbuffer_next_event(scap_device* dev) { return (scap_evt*)dev->m_sn_next_event; } #endif #ifndef ADVANCE_TO_EVT #define ADVANCE_TO_EVT ringbuffer_advance_to_evt -static inline void ringbuffer_advance_to_evt(scap_device* dev, scap_evt *event) -{ +static inline void ringbuffer_advance_to_evt(scap_device* dev, scap_evt* event) { ASSERT(dev->m_sn_len >= event->len); dev->m_sn_len -= event->len; dev->m_sn_next_event += event->len; @@ -206,10 +182,11 @@ static inline void ringbuffer_advance_to_evt(scap_device* dev, scap_evt *event) * \brief Get next event in the ringbuffer * * The flow here is: - * - For every buffer, read how many data are available and save the pointer + its length. (this is what we call a block) - * - Consume from all these blocks the event with the lowest timestamp. (repeat until all the blocks are empty!) - * When we have read all the data from a buffer block, update the consumer position for that buffer, and wait - * for all the other buffer blocks to be read. + * - For every buffer, read how many data are available and save the pointer + its length. (this is + * what we call a block) + * - Consume from all these blocks the event with the lowest timestamp. (repeat until all the blocks + * are empty!) When we have read all the data from a buffer block, update the consumer position for + * that buffer, and wait for all the other buffer blocks to be read. * - When we have consumed all the blocks we are ready to read again a new block for every buffer * * Possible pain points: @@ -224,9 +201,10 @@ static inline void ringbuffer_advance_to_evt(scap_device* dev, scap_evt *event) * gets stored * \param pflags [out] where the flags for the event get stored */ -static inline int32_t ringbuffer_next(struct scap_device_set* devset, scap_evt** pevent, uint16_t* pdevid, - uint32_t* pflags) -{ +static inline int32_t ringbuffer_next(struct scap_device_set* devset, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags) { uint32_t j; uint64_t min_ts = 0xffffffffffffffffLL; scap_evt* pe = NULL; @@ -234,8 +212,7 @@ static inline int32_t ringbuffer_next(struct scap_device_set* devset, scap_evt** *pdevid = 65535; - for(j = 0; j < ndevs; j++) - { + for(j = 0; j < ndevs; j++) { scap_device* dev = &(devset->m_devs[j]); /* `dev->m_sn_len` and `dev->m_lastreadsize` initially contain the dimension @@ -243,30 +220,28 @@ static inline int32_t ringbuffer_next(struct scap_device_set* devset, scap_evt** * The difference is that `dev->m_sn_len` is decreased at every new event * that we read while `dev->m_lastreadsize` preserve the block dimension since * it will be used to move the consumer position in `ADVANCE_TAIL`. - * + * * Note that even if we have consumed the entire block for this buffer we don't refill * it immediately but we wait for all other buffers! - */ - if(dev->m_sn_len == 0) - { + */ + if(dev->m_sn_len == 0) { /* If we don't have data from this ring, but we are * still occupying, free the resources for the * producer rather than sitting on them. - * + * * Please note: this is the unique point in which * we move the consumer position. We move the consumer * position only when we have consumed all the block * previously read in `refill_read_buffers`. - * + * * This could be quite dangerous if we read huge blocks * because we have to read the entire block before increasing * the consumer! - * - * `dev->m_lastreadsize` this contains the full length of the entire + * + * `dev->m_lastreadsize` this contains the full length of the entire * block we have just consumed. */ - if(dev->m_lastreadsize > 0) - { + if(dev->m_lastreadsize > 0) { ADVANCE_TAIL(dev); } @@ -277,11 +252,10 @@ static inline int32_t ringbuffer_next(struct scap_device_set* devset, scap_evt** pe = NEXT_EVENT(dev); /* Search the event with the lower timestamp */ - if(pe->ts < min_ts) - { - /* if the event length is greater than the remaining size in our block there is something wrong! */ - if(pe->len > dev->m_sn_len) - { + if(pe->ts < min_ts) { + /* if the event length is greater than the remaining size in our block there is + * something wrong! */ + if(pe->len > dev->m_sn_len) { snprintf(devset->m_lasterr, SCAP_LASTERR_SIZE, "scap_next buffer corruption"); dump_ringbuffer(dev); @@ -296,20 +270,17 @@ static inline int32_t ringbuffer_next(struct scap_device_set* devset, scap_evt** } } - if(*pdevid != 65535) - { + if(*pdevid != 65535) { /* Check from which buffer we have read and move the position inside - * the block with `ADVANCE_TO_EVT` - */ + * the block with `ADVANCE_TO_EVT` + */ struct scap_device* dev = &devset->m_devs[*pdevid]; ADVANCE_TO_EVT(dev, (*pevent)); // we don't really store the flags in the ringbuffer anywhere *pflags = 0; return SCAP_SUCCESS; - } - else - { + } else { /* If there are enough new data read again one block for every buffer * otherwise sleep! */ @@ -317,13 +288,11 @@ static inline int32_t ringbuffer_next(struct scap_device_set* devset, scap_evt** } } -static inline uint64_t ringbuffer_get_max_buf_used(struct scap_device_set *devset) -{ +static inline uint64_t ringbuffer_get_max_buf_used(struct scap_device_set* devset) { uint64_t i; uint64_t max = 0; - for(i = 0; i < devset->m_ndevs; i++) - { + for(i = 0; i < devset->m_ndevs; i++) { uint64_t size = buf_size_used(&devset->m_devs[i]); max = size > max ? size : max; } diff --git a/userspace/libscap/ringbuffer/ringbuffer_dump.c b/userspace/libscap/ringbuffer/ringbuffer_dump.c index a993b74a49..9135e2c979 100644 --- a/userspace/libscap/ringbuffer/ringbuffer_dump.c +++ b/userspace/libscap/ringbuffer/ringbuffer_dump.c @@ -9,12 +9,9 @@ #include #include -static inline bool all_zeros(const char* addr, size_t len) -{ - for(int i = 0; i < len; i++) - { - if(addr[i] != 0) - { +static inline bool all_zeros(const char* addr, size_t len) { + for(int i = 0; i < len; i++) { + if(addr[i] != 0) { return false; } } @@ -22,14 +19,12 @@ static inline bool all_zeros(const char* addr, size_t len) return true; } -struct tick -{ +struct tick { size_t offset; char marker; }; -struct dump_span -{ +struct dump_span { size_t start; size_t end; const char* label; @@ -39,51 +34,39 @@ struct dump_span size_t num_ticks; }; -static inline bool intervals_overlap(size_t start1, size_t end1, size_t start2, size_t end2) -{ +static inline bool intervals_overlap(size_t start1, size_t end1, size_t start2, size_t end2) { // Handle the complement case for the first interval - if(end1 < start1) - { + if(end1 < start1) { return (start1 < end2 || start2 < end1); } // Handle the complement case for the second interval - if(end2 < start2) - { + if(end2 < start2) { return (start2 < end1 || start1 < end2); } // Normal case return (start1 < end2) && (start2 < end1); } -static inline bool in_span(const struct dump_span* span, size_t offset) -{ - if(span->start <= span->end) - { +static inline bool in_span(const struct dump_span* span, size_t offset) { + if(span->start <= span->end) { // normal case return offset >= span->start && offset < span->end; - } - else - { + } else { // inverted case, the actual span is [0, end) + [start, buffer_size] return offset < span->end || offset >= span->start; } } -static inline bool next_in_span(const struct dump_span* span, size_t offset, size_t len) -{ - if(offset + 1 < len) - { +static inline bool next_in_span(const struct dump_span* span, size_t offset, size_t len) { + if(offset + 1 < len) { return in_span(span, offset + 1); } return span->start > span->end; } -static inline int next_tick(int current_tick, size_t offset, const struct dump_span* span) -{ - for(int i = current_tick + 1; i < span->num_ticks; i++) - { - if(span->ticks[i].offset >= offset) - { +static inline int next_tick(int current_tick, size_t offset, const struct dump_span* span) { + for(int i = current_tick + 1; i < span->num_ticks; i++) { + if(span->ticks[i].offset >= offset) { return i; } } @@ -91,19 +74,20 @@ static inline int next_tick(int current_tick, size_t offset, const struct dump_s return -1; } -static int compare_ticks(const void* a, const void* b) -{ +static int compare_ticks(const void* a, const void* b) { const struct tick* ta = a; const struct tick* tb = b; return ta->offset - tb->offset; } -static inline void draw_span(size_t offset, size_t len, size_t bytes_per_line, const struct dump_span* span, void* tag, - size_t total_len) -{ - if(!intervals_overlap(offset, offset + len, span->start, span->end)) - { +static inline void draw_span(size_t offset, + size_t len, + size_t bytes_per_line, + const struct dump_span* span, + void* tag, + size_t total_len) { + if(!intervals_overlap(offset, offset + len, span->start, span->end)) { return; } @@ -111,43 +95,33 @@ static inline void draw_span(size_t offset, size_t len, size_t bytes_per_line, c int current_tick = -1; - for(int i = 0; i < len; i++) - { + for(int i = 0; i < len; i++) { char c[4] = " "; char s = ' '; - if(in_span(span, offset + i)) - { + if(in_span(span, offset + i)) { c[0] = span->marker; c[1] = span->marker; c[2] = '>'; - if(next_in_span(span, offset + i, total_len)) - { + if(next_in_span(span, offset + i, total_len)) { c[2] = span->marker; s = span->marker; } - } - else if(next_in_span(span, offset + i, total_len)) - { + } else if(next_in_span(span, offset + i, total_len)) { c[2] = '<'; } - if(current_tick != -1) - { - if(span->ticks[current_tick].offset == offset + i) - { + if(current_tick != -1) { + if(span->ticks[current_tick].offset == offset + i) { c[0] = span->ticks[current_tick].marker; current_tick = next_tick(current_tick, offset + i, span); } - } - else - { + } else { current_tick = next_tick(current_tick, offset + i, span); } fprintf(stderr, "%s", c); - if(i == bytes_per_line / 2 - 1) - { + if(i == bytes_per_line / 2 - 1) { fprintf(stderr, "%c", s); } } @@ -155,22 +129,21 @@ static inline void draw_span(size_t offset, size_t len, size_t bytes_per_line, c fprintf(stderr, "\n"); } -static inline void hexdump(const char* buffer, size_t len, void* tag, const struct dump_span* spans, size_t num_spans) -{ +static inline void hexdump(const char* buffer, + size_t len, + void* tag, + const struct dump_span* spans, + size_t num_spans) { size_t i; size_t j; const size_t bytes_per_line = 32; bool blanks = false; - for(i = 0; i < len; i += bytes_per_line) - { - if(all_zeros(buffer + i, MIN(len - i, bytes_per_line))) - { + for(i = 0; i < len; i += bytes_per_line) { + if(all_zeros(buffer + i, MIN(len - i, bytes_per_line))) { blanks = true; continue; - } - else if(blanks) - { + } else if(blanks) { fprintf(stderr, "RINGBUFFER DUMP[%p] ...\n", tag); blanks = false; } @@ -179,82 +152,71 @@ static inline void hexdump(const char* buffer, size_t len, void* tag, const stru fprintf(stderr, "RINGBUFFER DUMP[%p] %08zx ", tag, i); // Print hex values - for(j = 0; j < bytes_per_line; j++) - { - if(i + j < len) - { + for(j = 0; j < bytes_per_line; j++) { + if(i + j < len) { fprintf(stderr, "%02x ", (unsigned char)buffer[i + j]); - } - else - { + } else { fprintf(stderr, " "); } - if(j == bytes_per_line / 2 - 1) - { + if(j == bytes_per_line / 2 - 1) { fprintf(stderr, " "); } } // Print ASCII values fprintf(stderr, " | "); - for(j = 0; j < bytes_per_line; j++) - { - if(i + j < len) - { + for(j = 0; j < bytes_per_line; j++) { + if(i + j < len) { char c = buffer[i + j]; - if(c >= 32 && c <= 126) // printable ASCII range + if(c >= 32 && c <= 126) // printable ASCII range { fprintf(stderr, "%c", c); - } - else - { + } else { fprintf(stderr, "."); } } - if(j == bytes_per_line / 2 - 1) - { + if(j == bytes_per_line / 2 - 1) { fprintf(stderr, " "); } } fprintf(stderr, "\n"); - for(int k = 0; k < num_spans; k++) - { + for(int k = 0; k < num_spans; k++) { draw_span(i, MIN(len - i, bytes_per_line), bytes_per_line, &spans[k], tag, len); } } } -static inline const char* push_event_ticks(const char* event, struct dump_span* span, size_t offset, size_t buffer_size) -{ - if(!in_span(span, offset)) - { +static inline const char* push_event_ticks(const char* event, + struct dump_span* span, + size_t offset, + size_t buffer_size) { + if(!in_span(span, offset)) { fprintf(stderr, "tick %zu outside span (%zu, %zu)\n", offset, span->start, span->end); return NULL; } struct tick* new_ticks = realloc(span->ticks, (span->num_ticks + 5) * sizeof(struct tick)); - if(new_ticks == NULL) - { + if(new_ticks == NULL) { fprintf(stderr, "Failed to allocate memory for ticks\n"); return NULL; } - new_ticks[span->num_ticks].offset = offset; // tid + new_ticks[span->num_ticks].offset = offset; // tid new_ticks[span->num_ticks].marker = 't'; - new_ticks[span->num_ticks + 1].offset = (offset + 8) % buffer_size; // ts + new_ticks[span->num_ticks + 1].offset = (offset + 8) % buffer_size; // ts new_ticks[span->num_ticks + 1].marker = 'T'; - new_ticks[span->num_ticks + 2].offset = (offset + 16) % buffer_size; // len + new_ticks[span->num_ticks + 2].offset = (offset + 16) % buffer_size; // len new_ticks[span->num_ticks + 2].marker = 'l'; - new_ticks[span->num_ticks + 3].offset = (offset + 20) % buffer_size; // type + new_ticks[span->num_ticks + 3].offset = (offset + 20) % buffer_size; // type new_ticks[span->num_ticks + 3].marker = '^'; - new_ticks[span->num_ticks + 4].offset = (offset + 22) % buffer_size; // nparams + new_ticks[span->num_ticks + 4].offset = (offset + 22) % buffer_size; // nparams new_ticks[span->num_ticks + 4].marker = 'n'; span->ticks = new_ticks; @@ -263,18 +225,16 @@ static inline const char* push_event_ticks(const char* event, struct dump_span* uint32_t nparams = ((scap_evt*)event)->nparams; size_t param_offset = offset + 26 + nparams * 2; new_ticks = realloc(span->ticks, (span->num_ticks + nparams) * sizeof(struct tick)); - if(new_ticks == NULL) - { + if(new_ticks == NULL) { fprintf(stderr, "Failed to allocate memory for ticks\n"); return NULL; } - for(int i = 0; i < nparams; i++) - { + for(int i = 0; i < nparams; i++) { // none of the kernel-generated events use large param sizes uint16_t len = ((uint16_t*)(event + sizeof(scap_evt)))[i]; - new_ticks[span->num_ticks].offset = param_offset % buffer_size; // param value + new_ticks[span->num_ticks].offset = param_offset % buffer_size; // param value new_ticks[span->num_ticks].marker = '0' + i; param_offset += len; @@ -286,68 +246,72 @@ static inline const char* push_event_ticks(const char* event, struct dump_span* return event + ((scap_evt*)event)->len; } -void dump_ringbuffer(struct scap_device* dev) -{ +void dump_ringbuffer(struct scap_device* dev) { char* buf_copy = malloc(dev->m_buffer_size); - if(buf_copy == NULL) - { + if(buf_copy == NULL) { fprintf(stderr, "RINGBUFFER_DUMP[%p] Failed to allocate buffer for ringbuffer dump\n", dev); - } - else - { + } else { // do this soon so that the producer doesn't overwrite *too* much memcpy(buf_copy, dev->m_buffer, dev->m_buffer_size); } fprintf(stderr, "RINGBUFFER DUMP[%p] Ringbuffer metadata:\n", dev); fprintf(stderr, "RINGBUFFER DUMP[%p] m_buffer_size: 0x%lx\n", dev, dev->m_buffer_size); fprintf(stderr, "RINGBUFFER DUMP[%p] m_lastreadsize: 0x%x\n", dev, dev->m_lastreadsize); - fprintf(stderr, "RINGBUFFER DUMP[%p] m_sn_next_event: 0x%lx\n", dev, dev->m_sn_next_event - dev->m_buffer); + fprintf(stderr, + "RINGBUFFER DUMP[%p] m_sn_next_event: 0x%lx\n", + dev, + dev->m_sn_next_event - dev->m_buffer); fprintf(stderr, "RINGBUFFER DUMP[%p] m_sn_len: 0x%x\n", dev, dev->m_sn_len); fprintf(stderr, "RINGBUFFER DUMP[%p] head: 0x%x\n", dev, dev->m_bufinfo->head); fprintf(stderr, "RINGBUFFER DUMP[%p] tail: 0x%x\n", dev, dev->m_bufinfo->tail); fprintf(stderr, "RINGBUFFER DUMP[%p] ---\n", dev); - fprintf(stderr, "RINGBUFFER DUMP[%p] last read: 0x%x .. 0x%x\n", dev, dev->m_bufinfo->tail, - dev->m_bufinfo->tail + dev->m_lastreadsize); + fprintf(stderr, + "RINGBUFFER DUMP[%p] last read: 0x%x .. 0x%x\n", + dev, + dev->m_bufinfo->tail, + dev->m_bufinfo->tail + dev->m_lastreadsize); struct dump_span spans[] = { - {.start = dev->m_bufinfo->tail, - .end = (dev->m_bufinfo->tail + dev->m_lastreadsize) % dev->m_buffer_size, - .label = "lastread", - .marker = '~'}, - {.start = dev->m_sn_next_event - dev->m_buffer, - .end = (dev->m_sn_next_event - dev->m_buffer + dev->m_sn_len) % dev->m_buffer_size, - .label = "next evt", - .marker = '*'}, - {.start = dev->m_bufinfo->tail, .end = dev->m_bufinfo->head, .label = "used", .marker = '-'}, + {.start = dev->m_bufinfo->tail, + .end = (dev->m_bufinfo->tail + dev->m_lastreadsize) % dev->m_buffer_size, + .label = "lastread", + .marker = '~'}, + {.start = dev->m_sn_next_event - dev->m_buffer, + .end = (dev->m_sn_next_event - dev->m_buffer + dev->m_sn_len) % dev->m_buffer_size, + .label = "next evt", + .marker = '*'}, + {.start = dev->m_bufinfo->tail, + .end = dev->m_bufinfo->head, + .label = "used", + .marker = '-'}, }; const char* event = dev->m_buffer + dev->m_bufinfo->tail; - while(event && event < dev->m_buffer + dev->m_bufinfo->tail + dev->m_lastreadsize) - { + while(event && event < dev->m_buffer + dev->m_bufinfo->tail + dev->m_lastreadsize) { push_event_ticks(event, &spans[0], event - dev->m_buffer, dev->m_buffer_size); event += ((scap_evt*)event)->len; } qsort(spans[0].ticks, spans[0].num_ticks, sizeof(struct tick), compare_ticks); event = dev->m_sn_next_event; - while(event && event < dev->m_sn_next_event + dev->m_sn_len) - { + while(event && event < dev->m_sn_next_event + dev->m_sn_len) { push_event_ticks(event, &spans[1], event - dev->m_buffer, dev->m_buffer_size); event += ((scap_evt*)event)->len; } qsort(spans[1].ticks, spans[1].num_ticks, sizeof(struct tick), compare_ticks); - if(buf_copy != NULL) - { + if(buf_copy != NULL) { fprintf(stderr, - "RINGBUFFER DUMP[%p] Buffer content: " - "-------------------------------------------------------------------------------------------\n", - dev); + "RINGBUFFER DUMP[%p] Buffer content: " + "----------------------------------------------------------------------------------" + "---------\n", + dev); hexdump(buf_copy, dev->m_buffer_size, dev, spans, sizeof(spans) / sizeof(spans[0])); fprintf(stderr, - "RINGBUFFER DUMP[%p] End of buffer content " - "-------------------------------------------------------------------------------------\n", - dev); + "RINGBUFFER DUMP[%p] End of buffer content " + "----------------------------------------------------------------------------------" + "---\n", + dev); free(buf_copy); } diff --git a/userspace/libscap/scap-int.h b/userspace/libscap/scap-int.h index f2fac0a961..2661fc8d45 100644 --- a/userspace/libscap/scap-int.h +++ b/userspace/libscap/scap-int.h @@ -31,7 +31,7 @@ limitations under the License. #ifdef __linux__ #include -#endif // __linux__ +#endif // __linux__ #ifdef __cplusplus extern "C" { @@ -40,9 +40,8 @@ extern "C" { // // The open instance handle // -struct scap -{ - const struct scap_vtable *m_vtable; +struct scap { + const struct scap_vtable* m_vtable; struct scap_engine_handle m_engine; char m_lasterr[SCAP_LASTERR_SIZE]; @@ -50,7 +49,7 @@ struct scap uint64_t m_evtcnt; // Function which may be called to log an event - falcosecurity_log_fn m_log_fn; + falcosecurity_log_fn m_log_fn; }; // @@ -69,10 +68,14 @@ void scap_free_iflist(scap_addrlist* ifhandle); // Free a previously allocated list of users void scap_free_userlist(scap_userlist* uhandle); -int32_t scap_proc_fill_pidns_start_ts(char* error, struct scap_threadinfo* tinfo, const char* procdirname); +int32_t scap_proc_fill_pidns_start_ts(char* error, + struct scap_threadinfo* tinfo, + const char* procdirname); -bool scap_alloc_proclist_info(struct ppm_proclist_info **proclist_p, uint32_t n_entries, char* error); -void scap_free_proclist_info(struct ppm_proclist_info *proclist); +bool scap_alloc_proclist_info(struct ppm_proclist_info** proclist_p, + uint32_t n_entries, + char* error); +void scap_free_proclist_info(struct ppm_proclist_info* proclist); void scap_free_device_table(scap_mountinfo* dev_list); @@ -82,8 +85,8 @@ void scap_free_device_table(scap_mountinfo* dev_list); // #ifndef __cplusplus #ifndef MIN -#define MIN(X,Y) ((X) < (Y)? (X):(Y)) -#define MAX(X,Y) ((X) > (Y)? (X):(Y)) +#define MIN(X, Y) ((X) < (Y) ? (X) : (Y)) +#define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) #endif #endif diff --git a/userspace/libscap/scap.c b/userspace/libscap/scap.c index fb5e05500d..84108dc379 100644 --- a/userspace/libscap/scap.c +++ b/userspace/libscap/scap.c @@ -35,28 +35,25 @@ limitations under the License. // but only on an actual Linux system. // // Still, to compile properly on non-Linux, provide implementations -// of scap_linux_alloc_platform() and scap_linux_hostinfo_alloc_platform() that always fail at runtime. -struct scap_platform* scap_linux_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context) -{ +// of scap_linux_alloc_platform() and scap_linux_hostinfo_alloc_platform() that always fail at +// runtime. +struct scap_platform* scap_linux_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context) { return NULL; } -struct scap_platform* scap_linux_hostinfo_alloc_platform() -{ +struct scap_platform* scap_linux_hostinfo_alloc_platform() { return NULL; } #endif -const char* scap_getlasterr(scap_t* handle) -{ +const char* scap_getlasterr(scap_t* handle) { return handle ? handle->m_lasterr : "null scap handle"; } -int32_t scap_init_engine(scap_t* handle, scap_open_args* oargs, const struct scap_vtable* vtable) -{ +int32_t scap_init_engine(scap_t* handle, scap_open_args* oargs, const struct scap_vtable* vtable) { int32_t rc; - if(!handle) - { + if(!handle) { return SCAP_FAILURE; } @@ -66,22 +63,19 @@ int32_t scap_init_engine(scap_t* handle, scap_open_args* oargs, const struct sca handle->m_vtable = vtable; handle->m_engine.m_handle = handle->m_vtable->alloc_handle(handle, handle->m_lasterr); - if(!handle->m_engine.m_handle) - { + if(!handle->m_engine.m_handle) { snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "error allocating the engine structure"); return SCAP_FAILURE; } handle->m_log_fn = oargs->log_fn; - if(handle->m_vtable->init && (rc = handle->m_vtable->init(handle, oargs)) != SCAP_SUCCESS) - { + if(handle->m_vtable->init && (rc = handle->m_vtable->init(handle, oargs)) != SCAP_SUCCESS) { return rc; } rc = check_api_compatibility(handle->m_vtable, handle->m_engine, handle->m_lasterr); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } @@ -89,17 +83,14 @@ int32_t scap_init_engine(scap_t* handle, scap_open_args* oargs, const struct sca return SCAP_SUCCESS; } -scap_t* scap_alloc(void) -{ +scap_t* scap_alloc(void) { return calloc(1, sizeof(scap_t)); } -int32_t scap_init(scap_t* handle, scap_open_args* oargs, const struct scap_vtable* vtable) -{ +int32_t scap_init(scap_t* handle, scap_open_args* oargs, const struct scap_vtable* vtable) { int32_t rc; - if(!handle) - { + if(!handle) { return SCAP_FAILURE; } @@ -115,25 +106,24 @@ int32_t scap_init(scap_t* handle, scap_open_args* oargs, const struct scap_vtabl // ioctls on the driver fd, so we need to initialize the engine before the platform. rc = scap_init_engine(handle, oargs, vtable); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } return SCAP_SUCCESS; } -scap_t* scap_open(scap_open_args* oargs, const struct scap_vtable* vtable, char* error, int32_t* rc) -{ +scap_t* scap_open(scap_open_args* oargs, + const struct scap_vtable* vtable, + char* error, + int32_t* rc) { scap_t* handle = scap_alloc(); - if(!handle) - { + if(!handle) { snprintf(error, SCAP_LASTERR_SIZE, "Could not allocate memory for the scap handle"); return NULL; } *rc = scap_init(handle, oargs, vtable); - if(*rc != SCAP_SUCCESS) - { + if(*rc != SCAP_SUCCESS) { strlcpy(error, handle->m_lasterr, SCAP_LASTERR_SIZE); scap_close(handle); return NULL; @@ -142,28 +132,23 @@ scap_t* scap_open(scap_open_args* oargs, const struct scap_vtable* vtable, char* return handle; } -uint32_t scap_restart_capture(scap_t* handle) -{ - if(!handle) - { +uint32_t scap_restart_capture(scap_t* handle) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable->savefile_ops) - { + if(handle->m_vtable->savefile_ops) { return handle->m_vtable->savefile_ops->restart_capture(handle); - } - else - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "capture restart supported only in capture mode"); + } else { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "capture restart supported only in capture mode"); return SCAP_FAILURE; } } -void scap_deinit(scap_t* handle) -{ - if(handle->m_vtable) - { +void scap_deinit(scap_t* handle) { + if(handle->m_vtable) { /* The capture should be stopped before * closing the engine, here we only enforce it. * Please note that there are some corner cases in which @@ -177,18 +162,15 @@ void scap_deinit(scap_t* handle) } } -void scap_free(scap_t* handle) -{ +void scap_free(scap_t* handle) { // // Release the handle // free(handle); } -void scap_close(scap_t* handle) -{ - if(!handle) - { +void scap_close(scap_t* handle) { + if(!handle) { return; } @@ -196,58 +178,46 @@ void scap_close(scap_t* handle) scap_free(handle); } -uint64_t scap_get_engine_flags(scap_t* handle) -{ - if(handle && handle->m_vtable && handle->m_vtable->get_flags) - { +uint64_t scap_get_engine_flags(scap_t* handle) { + if(handle && handle->m_vtable && handle->m_vtable->get_flags) { return handle->m_vtable->get_flags(handle->m_engine); } return 0; } -uint32_t scap_get_ndevs(scap_t* handle) -{ - if(handle && handle->m_vtable) - { +uint32_t scap_get_ndevs(scap_t* handle) { + if(handle && handle->m_vtable) { return handle->m_vtable->get_n_devs(handle->m_engine); } return 1; } -int32_t scap_readbuf(scap_t* handle, uint32_t cpuid, char** buf, uint32_t* len) -{ +int32_t scap_readbuf(scap_t* handle, uint32_t cpuid, char** buf, uint32_t* len) { // engines do not even necessarily have a concept of a buffer // that you read events from return SCAP_NOT_SUPPORTED; } -uint64_t scap_max_buf_used(scap_t* handle) -{ - if(handle && handle->m_vtable) - { +uint64_t scap_max_buf_used(scap_t* handle) { + if(handle && handle->m_vtable) { return handle->m_vtable->get_max_buf_used(handle->m_engine); } return 0; } -int32_t scap_next(scap_t* handle, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags) -{ +int32_t scap_next(scap_t* handle, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags) { // Note: devid is like cpuid but not 1:1, e.g. consider CPU1 offline: // CPU0 CPU1 CPU2 CPU3 // DEV0 DEV1 DEV2 DEV3 <- CPU1 online // DEV0 XXXX DEV1 DEV2 <- CPU1 offline int32_t res = SCAP_FAILURE; - if(handle && handle->m_vtable) - { + if(handle && handle->m_vtable) { res = handle->m_vtable->next(handle->m_engine, pevent, pdevid, pflags); - } - else - { + } else { res = SCAP_FAILURE; } - if(res == SCAP_SUCCESS) - { + if(res == SCAP_SUCCESS) { handle->m_evtcnt++; } @@ -257,10 +227,8 @@ int32_t scap_next(scap_t* handle, scap_evt** pevent, uint16_t* pdevid, uint32_t* // // Return the number of dropped events for the given handle. // -int32_t scap_get_stats(scap_t* handle, scap_stats* stats) -{ - if(!handle || stats == NULL) - { +int32_t scap_get_stats(scap_t* handle, scap_stats* stats) { + if(!handle || stats == NULL) { return SCAP_FAILURE; } @@ -288,8 +256,7 @@ int32_t scap_get_stats(scap_t* handle, scap_stats* stats) stats->n_suppressed = 0; stats->n_tids_suppressed = 0; - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->get_stats(handle->m_engine, stats); } @@ -300,16 +267,16 @@ int32_t scap_get_stats(scap_t* handle, scap_stats* stats) // // Return engine statistics (including counters and `bpftool prog show` like stats) // -const struct metrics_v2* scap_get_stats_v2(scap_t* handle, uint32_t flags, uint32_t* nstats, int32_t* rc) -{ +const struct metrics_v2* scap_get_stats_v2(scap_t* handle, + uint32_t flags, + uint32_t* nstats, + int32_t* rc) { // If we enable per-cpu counters, we also enable kernel global counters by default. - if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) - { + if(flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU) { flags |= METRICS_V2_KERNEL_COUNTERS; } - if(handle && handle->m_vtable) - { + if(handle && handle->m_vtable) { return handle->m_vtable->get_stats_v2(handle->m_engine, flags, nstats, rc); } ASSERT(false); @@ -321,19 +288,16 @@ const struct metrics_v2* scap_get_stats_v2(scap_t* handle, uint32_t flags, uint3 // // Stop capturing the events // -int32_t scap_stop_capture(scap_t* handle) -{ - if(handle == NULL) - { +int32_t scap_stop_capture(scap_t* handle) { + if(handle == NULL) { return SCAP_SUCCESS; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->stop_capture(handle->m_engine); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); ASSERT(false); return SCAP_FAILURE; } @@ -341,184 +305,158 @@ int32_t scap_stop_capture(scap_t* handle) // // Start capturing the events // -int32_t scap_start_capture(scap_t* handle) -{ - if(!handle) - { +int32_t scap_start_capture(scap_t* handle) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->start_capture(handle->m_engine); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); ASSERT(false); return SCAP_FAILURE; } -int32_t scap_stop_dropping_mode(scap_t* handle) -{ - if(!handle) - { +int32_t scap_stop_dropping_mode(scap_t* handle) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->configure(handle->m_engine, SCAP_SAMPLING_RATIO, 1, 0); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); ASSERT(false); return SCAP_FAILURE; } -int32_t scap_start_dropping_mode(scap_t* handle, uint32_t sampling_ratio) -{ - if(!handle) - { +int32_t scap_start_dropping_mode(scap_t* handle, uint32_t sampling_ratio) { + if(!handle) { return SCAP_FAILURE; } - switch(sampling_ratio) - { - case 1: - case 2: - case 4: - case 8: - case 16: - case 32: - case 64: - case 128: - break; - default: - return snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid sampling ratio size"); + switch(sampling_ratio) { + case 1: + case 2: + case 4: + case 8: + case 16: + case 32: + case 64: + case 128: + break; + default: + return snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "invalid sampling ratio size"); } - if(handle->m_vtable) - { - return handle->m_vtable->configure(handle->m_engine, SCAP_SAMPLING_RATIO, sampling_ratio, 1); + if(handle->m_vtable) { + return handle->m_vtable->configure(handle->m_engine, + SCAP_SAMPLING_RATIO, + sampling_ratio, + 1); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); ASSERT(false); return SCAP_FAILURE; } -int32_t scap_set_snaplen(scap_t* handle, uint32_t snaplen) -{ - if(!handle) - { +int32_t scap_set_snaplen(scap_t* handle, uint32_t snaplen) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->configure(handle->m_engine, SCAP_SNAPLEN, snaplen, 0); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } -int64_t scap_get_readfile_offset(scap_t* handle) -{ - if(!handle) - { +int64_t scap_get_readfile_offset(scap_t* handle) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable->savefile_ops) - { + if(handle->m_vtable->savefile_ops) { return handle->m_vtable->savefile_ops->get_readfile_offset(handle->m_engine); - } - else - { - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "scap_get_readfile_offset only works on captures"); + } else { + snprintf(handle->m_lasterr, + SCAP_LASTERR_SIZE, + "scap_get_readfile_offset only works on captures"); return SCAP_FAILURE; } } -int32_t scap_set_ppm_sc(scap_t* handle, ppm_sc_code ppm_sc, bool enabled) -{ - if (handle == NULL) - { +int32_t scap_set_ppm_sc(scap_t* handle, ppm_sc_code ppm_sc, bool enabled) { + if(handle == NULL) { return SCAP_FAILURE; } - if (ppm_sc >= PPM_SC_MAX) - { + if(ppm_sc >= PPM_SC_MAX) { snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "%s(%d) wrong param", __FUNCTION__, ppm_sc); ASSERT(false); return SCAP_FAILURE; } - uint32_t op = enabled ? SCAP_PPM_SC_MASK_SET : SCAP_PPM_SC_MASK_UNSET; + uint32_t op = enabled ? SCAP_PPM_SC_MASK_SET : SCAP_PPM_SC_MASK_UNSET; - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->configure(handle->m_engine, SCAP_PPM_SC_MASK, op, ppm_sc); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } int32_t scap_set_dropfailed(scap_t* handle, bool enabled) { - if(!handle) - { + if(!handle) { return SCAP_FAILURE; } - if(handle && handle->m_vtable) - { + if(handle && handle->m_vtable) { return handle->m_vtable->configure(handle->m_engine, SCAP_DROP_FAILED, enabled, 0); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } -int32_t scap_enable_dynamic_snaplen(scap_t* handle) -{ - if(!handle) - { +int32_t scap_enable_dynamic_snaplen(scap_t* handle) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->configure(handle->m_engine, SCAP_DYNAMIC_SNAPLEN, 1, 0); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } -int32_t scap_disable_dynamic_snaplen(scap_t* handle) -{ - if(!handle) - { +int32_t scap_disable_dynamic_snaplen(scap_t* handle) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->configure(handle->m_engine, SCAP_DYNAMIC_SNAPLEN, 0, 0); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } -const char* scap_get_host_root() -{ +const char* scap_get_host_root() { char* p = getenv(SCAP_HOST_ROOT_ENV_VAR_NAME); static char env_str[SCAP_MAX_PATH_SIZE + 1]; static bool inited = false; - if (! inited) { + if(!inited) { strlcpy(env_str, p ? p : "", sizeof(env_str)); inited = true; } @@ -526,97 +464,79 @@ const char* scap_get_host_root() return env_str; } -uint64_t scap_ftell(scap_t *handle) -{ - if(handle && handle->m_vtable->savefile_ops) - { +uint64_t scap_ftell(scap_t* handle) { + if(handle && handle->m_vtable->savefile_ops) { return handle->m_vtable->savefile_ops->ftell_capture(handle->m_engine); - } - else - { + } else { return 0; } } -void scap_fseek(scap_t *handle, uint64_t off) -{ - if(handle && handle->m_vtable->savefile_ops) - { +void scap_fseek(scap_t* handle, uint64_t off) { + if(handle && handle->m_vtable->savefile_ops) { handle->m_vtable->savefile_ops->fseek_capture(handle->m_engine, off); } } -int32_t scap_get_n_tracepoint_hit(scap_t* handle, long* ret) -{ - if(!handle) - { +int32_t scap_get_n_tracepoint_hit(scap_t* handle, long* ret) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->get_n_tracepoint_hit(handle->m_engine, ret); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } -bool scap_check_current_engine(scap_t *handle, const char* engine_name) -{ - if(engine_name && handle && handle->m_vtable) - { +bool scap_check_current_engine(scap_t* handle, const char* engine_name) { + if(engine_name && handle && handle->m_vtable) { return strcmp(handle->m_vtable->name, engine_name) == 0; } return false; } -int32_t scap_set_fullcapture_port_range(scap_t* handle, uint16_t range_start, uint16_t range_end) -{ - if(!handle) - { +int32_t scap_set_fullcapture_port_range(scap_t* handle, uint16_t range_start, uint16_t range_end) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { - return handle->m_vtable->configure(handle->m_engine, SCAP_FULLCAPTURE_PORT_RANGE, range_start, range_end); + if(handle->m_vtable) { + return handle->m_vtable->configure(handle->m_engine, + SCAP_FULLCAPTURE_PORT_RANGE, + range_start, + range_end); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } -int32_t scap_set_statsd_port(scap_t* const handle, const uint16_t port) -{ - if(!handle) - { +int32_t scap_set_statsd_port(scap_t* const handle, const uint16_t port) { + if(!handle) { return SCAP_FAILURE; } - if(handle->m_vtable) - { + if(handle->m_vtable) { return handle->m_vtable->configure(handle->m_engine, SCAP_STATSD_PORT, port, 0); } - snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); + snprintf(handle->m_lasterr, SCAP_LASTERR_SIZE, "operation not supported"); return SCAP_FAILURE; } -uint64_t scap_get_driver_api_version(scap_t* handle) -{ - if(handle && handle->m_vtable && handle->m_vtable->get_api_version) - { +uint64_t scap_get_driver_api_version(scap_t* handle) { + if(handle && handle->m_vtable && handle->m_vtable->get_api_version) { return handle->m_vtable->get_api_version(handle->m_engine); } return 0; } -uint64_t scap_get_driver_schema_version(scap_t* handle) -{ - if(handle && handle->m_vtable && handle->m_vtable->get_schema_version) - { +uint64_t scap_get_driver_schema_version(scap_t* handle) { + if(handle && handle->m_vtable && handle->m_vtable->get_schema_version) { return handle->m_vtable->get_schema_version(handle->m_engine); } diff --git a/userspace/libscap/scap.h b/userspace/libscap/scap.h index 70b8876ff5..f91478cf05 100644 --- a/userspace/libscap/scap.h +++ b/userspace/libscap/scap.h @@ -27,19 +27,19 @@ extern "C" { #endif /*! - \mainpage libscap documentation + \mainpage libscap documentation - \section Introduction + \section Introduction - libscap is the low-level component that exports the following functionality: - - live capture control (start/stop/pause...) - - trace file management - - event retrieval - - extraction of system state from /proc + libscap is the low-level component that exports the following functionality: + - live capture control (start/stop/pause...) + - trace file management + - event retrieval + - extraction of system state from /proc - This manual includes the following sections: - - \ref scap_defs - - \ref scap_functs + This manual includes the following sections: + - \ref scap_defs + - \ref scap_functs */ /////////////////////////////////////////////////////////////////////////////// @@ -124,11 +124,10 @@ struct scap_vtable; /*! \brief Statistics about an in progress capture */ -typedef struct scap_stats -{ - uint64_t n_evts; ///< Total number of events that were received by the driver. - uint64_t n_drops; ///< Number of dropped events. - uint64_t n_drops_buffer; ///< Number of dropped events caused by full buffer. +typedef struct scap_stats { + uint64_t n_evts; ///< Total number of events that were received by the driver. + uint64_t n_drops; ///< Number of dropped events. + uint64_t n_drops_buffer; ///< Number of dropped events caused by full buffer. uint64_t n_drops_buffer_clone_fork_enter; uint64_t n_drops_buffer_clone_fork_exit; uint64_t n_drops_buffer_execve_enter; @@ -143,19 +142,20 @@ typedef struct scap_stats uint64_t n_drops_buffer_other_interest_exit; uint64_t n_drops_buffer_close_exit; uint64_t n_drops_buffer_proc_exit; - uint64_t n_drops_scratch_map; ///< Number of dropped events caused by full frame scratch map. - uint64_t n_drops_pf; ///< Number of dropped events caused by invalid memory access. - uint64_t n_drops_bug; ///< Number of dropped events caused by an invalid condition in the kernel instrumentation. - uint64_t n_preemptions; ///< Number of preemptions. - uint64_t n_suppressed; ///< Number of events skipped due to the tid being in a set of suppressed tids. - uint64_t n_tids_suppressed; ///< Number of threads currently being suppressed. -}scap_stats; + uint64_t n_drops_scratch_map; ///< Number of dropped events caused by full frame scratch map. + uint64_t n_drops_pf; ///< Number of dropped events caused by invalid memory access. + uint64_t n_drops_bug; ///< Number of dropped events caused by an invalid condition in the + ///< kernel instrumentation. + uint64_t n_preemptions; ///< Number of preemptions. + uint64_t n_suppressed; ///< Number of events skipped due to the tid being in a set of + ///< suppressed tids. + uint64_t n_tids_suppressed; ///< Number of threads currently being suppressed. +} scap_stats; /*! \brief File Descriptor type */ -typedef enum scap_fd_type -{ +typedef enum scap_fd_type { SCAP_FD_UNINITIALIZED = -1, SCAP_FD_UNKNOWN = 0, SCAP_FD_FILE = 1, @@ -179,137 +179,137 @@ typedef enum scap_fd_type SCAP_FD_IOURING = 19, SCAP_FD_MEMFD = 20, SCAP_FD_PIDFD = 21 -}scap_fd_type; +} scap_fd_type; /*! \brief Socket type / transport protocol */ -typedef enum scap_l4_proto -{ - SCAP_L4_UNKNOWN = 0, ///< unknown protocol, likely caused by some parsing problem - SCAP_L4_NA = 1, ///< protocol not available, because the fd is not a socket +typedef enum scap_l4_proto { + SCAP_L4_UNKNOWN = 0, ///< unknown protocol, likely caused by some parsing problem + SCAP_L4_NA = 1, ///< protocol not available, because the fd is not a socket SCAP_L4_TCP = 2, SCAP_L4_UDP = 3, SCAP_L4_ICMP = 4, - SCAP_L4_RAW = 5, ///< Raw socket -}scap_l4_proto; + SCAP_L4_RAW = 5, ///< Raw socket +} scap_l4_proto; /*! \brief Information about a file descriptor */ -typedef struct scap_fdinfo -{ - int64_t fd; ///< The FD number, which uniquely identifies this file descriptor. - uint64_t ino; ///< The inode. - scap_fd_type type; ///< This file descriptor's type. - union - { - struct - { - uint32_t sip; ///< Source IP - uint32_t dip; ///< Destination IP - uint16_t sport; ///< Source port - uint16_t dport; ///< Destination port - uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. - } ipv4info; ///< Information specific to IPv4 sockets - struct - { - uint32_t sip[4]; ///< Source IP - uint32_t dip[4]; ///< Destination IP - uint16_t sport; ///< Source Port - uint16_t dport; ///< Destination Port - uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. - } ipv6info; ///< Information specific to IPv6 sockets - struct - { - uint32_t ip; ///< Local IP - uint16_t port; ///< Local Port - uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. - } ipv4serverinfo; ///< Information specific to IPv4 server sockets, e.g. sockets used for bind(). - struct - { - uint32_t ip[4]; ///< Local IP - uint16_t port; ///< Local Port - uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. - } ipv6serverinfo; ///< Information specific to IPv6 server sockets, e.g. sockets used for bind(). - struct - { - uint64_t source; ///< Source socket endpoint - uint64_t destination; ///< Destination socket endpoint - char fname[SCAP_MAX_PATH_SIZE]; ///< Name associated to this unix socket - } unix_socket_info; ///< Information specific to unix sockets - struct - { - uint32_t open_flags; ///< Flags associated with the file - char fname[SCAP_MAX_PATH_SIZE]; ///< Name associated to this file - uint32_t mount_id; ///< The id of the vfs mount the file is in until we find dev major:minor - uint32_t dev; ///< Major/minor number of the device containing this file - } regularinfo; ///< Information specific to regular files +typedef struct scap_fdinfo { + int64_t fd; ///< The FD number, which uniquely identifies this file descriptor. + uint64_t ino; ///< The inode. + scap_fd_type type; ///< This file descriptor's type. + union { + struct { + uint32_t sip; ///< Source IP + uint32_t dip; ///< Destination IP + uint16_t sport; ///< Source port + uint16_t dport; ///< Destination port + uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. + } ipv4info; ///< Information specific to IPv4 sockets + struct { + uint32_t sip[4]; ///< Source IP + uint32_t dip[4]; ///< Destination IP + uint16_t sport; ///< Source Port + uint16_t dport; ///< Destination Port + uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. + } ipv6info; ///< Information specific to IPv6 sockets + struct { + uint32_t ip; ///< Local IP + uint16_t port; ///< Local Port + uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. + } ipv4serverinfo; ///< Information specific to IPv4 server sockets, e.g. sockets used for + ///< bind(). + struct { + uint32_t ip[4]; ///< Local IP + uint16_t port; ///< Local Port + uint8_t l4proto; ///< Transport protocol. See \ref scap_l4_proto. + } ipv6serverinfo; ///< Information specific to IPv6 server sockets, e.g. sockets used for + ///< bind(). + struct { + uint64_t source; ///< Source socket endpoint + uint64_t destination; ///< Destination socket endpoint + char fname[SCAP_MAX_PATH_SIZE]; ///< Name associated to this unix socket + } unix_socket_info; ///< Information specific to unix sockets + struct { + uint32_t open_flags; ///< Flags associated with the file + char fname[SCAP_MAX_PATH_SIZE]; ///< Name associated to this file + uint32_t mount_id; ///< The id of the vfs mount the file is in until we find dev + ///< major:minor + uint32_t dev; ///< Major/minor number of the device containing this file + } regularinfo; ///< Information specific to regular files char fname[SCAP_MAX_PATH_SIZE]; ///< The name for file system FDs - }info; - UT_hash_handle hh; ///< makes this structure hashable -}scap_fdinfo; + } info; + UT_hash_handle hh; ///< makes this structure hashable +} scap_fdinfo; /*! \brief Process information */ -typedef struct scap_threadinfo -{ - uint64_t tid; ///< The thread/task id. - uint64_t pid; ///< The id of the process containing this thread. In single thread processes, this is equal to tid. - uint64_t ptid; ///< The id of the thread that created this thread. - uint64_t sid; ///< The session id of the process containing this thread. - uint64_t vpgid; ///< The process group of this thread, as seen from its current pid namespace - char comm[SCAP_MAX_PATH_SIZE+1]; ///< Command name (e.g. "top") - char exe[SCAP_MAX_PATH_SIZE+1]; ///< argv[0] (e.g. "sshd: user@pts/4") - char exepath[SCAP_MAX_PATH_SIZE+1]; ///< full executable path - bool exe_writable; ///< true if the original executable is writable by the same user that spawned it. - bool exe_upper_layer; //< True if the original executable belongs to upper layer in overlayfs - bool exe_lower_layer; //< True if the original executable belongs to lower layer in overlayfs - bool exe_from_memfd; //< True if the original executable is stored in pathless memory referenced by a memfd - char args[SCAP_MAX_ARGS_SIZE+1]; ///< Command line arguments (e.g. "-d1") - uint16_t args_len; ///< Command line arguments length - char env[SCAP_MAX_ENV_SIZE+1]; ///< Environment - uint16_t env_len; ///< Environment length - char cwd[SCAP_MAX_PATH_SIZE+1]; ///< The current working directory - int64_t fdlimit; ///< The maximum number of files this thread is allowed to open - uint32_t flags; ///< the process flags. - uint32_t uid; ///< user id - uint32_t gid; ///< group id - uint64_t cap_permitted; ///< permitted capabilities - uint64_t cap_effective; ///< effective capabilities - uint64_t cap_inheritable; ///< inheritable capabilities - uint64_t exe_ino; ///< executable inode ino - uint64_t exe_ino_ctime; ///< executable inode ctime (last status change time) - uint64_t exe_ino_mtime; ///< executable inode mtime (last modification time) - uint64_t exe_ino_ctime_duration_clone_ts; ///< duration in ns between executable inode ctime (last status change time) and clone_ts - uint64_t exe_ino_ctime_duration_pidns_start; ///< duration in ns between pidns start ts and executable inode ctime (last status change time) if pidns start predates ctime - uint32_t vmsize_kb; ///< total virtual memory (as kb) - uint32_t vmrss_kb; ///< resident non-swapped memory (as kb) - uint32_t vmswap_kb; ///< swapped memory (as kb) - uint64_t pfmajor; ///< number of major page faults since start - uint64_t pfminor; ///< number of minor page faults since start - int64_t vtid; ///< The virtual id of this thread. - int64_t vpid; ///< The virtual id of the process containing this thread. In single thread threads, this is equal to vtid. - uint64_t pidns_init_start_ts; /// #include - -bool scap_apply_semver_check(uint32_t current_major, uint32_t current_minor, uint32_t current_patch, - uint32_t required_major, uint32_t required_minor, uint32_t required_patch) -{ - if(current_major != required_major) - { +bool scap_apply_semver_check(uint32_t current_major, + uint32_t current_minor, + uint32_t current_patch, + uint32_t required_major, + uint32_t required_minor, + uint32_t required_patch) { + if(current_major != required_major) { return false; } - if(current_minor < required_minor) - { + if(current_minor < required_minor) { return false; } - if(current_minor == required_minor && current_patch < required_patch) - { + if(current_minor == required_minor && current_patch < required_patch) { return false; } return true; } -bool scap_is_api_compatible(unsigned long driver_api_version, unsigned long required_api_version) -{ +bool scap_is_api_compatible(unsigned long driver_api_version, unsigned long required_api_version) { unsigned long driver_major = PPM_API_VERSION_MAJOR(driver_api_version); unsigned long driver_minor = PPM_API_VERSION_MINOR(driver_api_version); unsigned long driver_patch = PPM_API_VERSION_PATCH(driver_api_version); @@ -52,48 +50,56 @@ bool scap_is_api_compatible(unsigned long driver_api_version, unsigned long requ unsigned long required_minor = PPM_API_VERSION_MINOR(required_api_version); unsigned long required_patch = PPM_API_VERSION_PATCH(required_api_version); - return scap_apply_semver_check(driver_major, driver_minor, driver_patch, required_major, required_minor, required_patch); + return scap_apply_semver_check(driver_major, + driver_minor, + driver_patch, + required_major, + required_minor, + required_patch); } -static int32_t check_api_compatibility_impl(uint64_t current_version, uint64_t minimum_version, const char* label, char *error) -{ - if(!scap_is_api_compatible(current_version, minimum_version)) - { - return scap_errprintf(error, 0, "Driver supports %s version %llu.%llu.%llu, but running version needs %llu.%llu.%llu", - label, - PPM_API_VERSION_MAJOR(current_version), - PPM_API_VERSION_MINOR(current_version), - PPM_API_VERSION_PATCH(current_version), - PPM_API_VERSION_MAJOR(minimum_version), - PPM_API_VERSION_MINOR(minimum_version), - PPM_API_VERSION_PATCH(minimum_version)); +static int32_t check_api_compatibility_impl(uint64_t current_version, + uint64_t minimum_version, + const char* label, + char* error) { + if(!scap_is_api_compatible(current_version, minimum_version)) { + return scap_errprintf(error, + 0, + "Driver supports %s version %llu.%llu.%llu, but running version " + "needs %llu.%llu.%llu", + label, + PPM_API_VERSION_MAJOR(current_version), + PPM_API_VERSION_MINOR(current_version), + PPM_API_VERSION_PATCH(current_version), + PPM_API_VERSION_MAJOR(minimum_version), + PPM_API_VERSION_MINOR(minimum_version), + PPM_API_VERSION_PATCH(minimum_version)); } return SCAP_SUCCESS; } -int32_t check_api_compatibility(const struct scap_vtable* vtable, struct scap_engine_handle engine, char *error) -{ +int32_t check_api_compatibility(const struct scap_vtable* vtable, + struct scap_engine_handle engine, + char* error) { int rc; - if(vtable && vtable->get_api_version) - { + if(vtable && vtable->get_api_version) { uint64_t version = vtable->get_api_version(engine); rc = check_api_compatibility_impl(version, SCAP_MINIMUM_DRIVER_API_VERSION, "API", error); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } } - if(vtable && vtable->get_schema_version) - { + if(vtable && vtable->get_schema_version) { uint64_t version = vtable->get_schema_version(engine); - rc = check_api_compatibility_impl(version, SCAP_MINIMUM_DRIVER_SCHEMA_VERSION, "schema", error); - if(rc != SCAP_SUCCESS) - { + rc = check_api_compatibility_impl(version, + SCAP_MINIMUM_DRIVER_SCHEMA_VERSION, + "schema", + error); + if(rc != SCAP_SUCCESS) { return rc; } } return SCAP_SUCCESS; } - diff --git a/userspace/libscap/scap_api_version.h b/userspace/libscap/scap_api_version.h index dbf6f2f36c..edfd40dce1 100644 --- a/userspace/libscap/scap_api_version.h +++ b/userspace/libscap/scap_api_version.h @@ -33,7 +33,13 @@ bool scap_is_api_compatible(unsigned long driver_api_version, unsigned long requ /** * Apply the `semver` checks on current and required versions. */ -bool scap_apply_semver_check(uint32_t current_major, uint32_t current_minor, uint32_t current_patch, - uint32_t required_major, uint32_t required_minor, uint32_t required_patch); - -int32_t check_api_compatibility(const struct scap_vtable* vtable, struct scap_engine_handle engine, char *error); +bool scap_apply_semver_check(uint32_t current_major, + uint32_t current_minor, + uint32_t current_patch, + uint32_t required_major, + uint32_t required_minor, + uint32_t required_patch); + +int32_t check_api_compatibility(const struct scap_vtable* vtable, + struct scap_engine_handle engine, + char* error); diff --git a/userspace/libscap/scap_assert.h b/userspace/libscap/scap_assert.h index 7517b21368..cac86c8b58 100644 --- a/userspace/libscap/scap_assert.h +++ b/userspace/libscap/scap_assert.h @@ -27,9 +27,9 @@ limitations under the License. #ifdef ASSERT #undef ASSERT -#endif // ASSERT +#endif // ASSERT #ifdef _DEBUG #define ASSERT(X) assert(X) -#else // _DEBUG +#else // _DEBUG #define ASSERT(X) -#endif // _DEBUG +#endif // _DEBUG diff --git a/userspace/libscap/scap_cgroup_set.h b/userspace/libscap/scap_cgroup_set.h index a29a59ebf1..7805437921 100644 --- a/userspace/libscap/scap_cgroup_set.h +++ b/userspace/libscap/scap_cgroup_set.h @@ -21,16 +21,14 @@ limitations under the License. #include #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - // just a sequence of NUL-terminated strings in a single buffer - struct scap_cgroup_set - { - int len; - char path[SCAP_MAX_CGROUPS_SIZE]; - }; +// just a sequence of NUL-terminated strings in a single buffer +struct scap_cgroup_set { + int len; + char path[SCAP_MAX_CGROUPS_SIZE]; +}; #ifdef __cplusplus }; diff --git a/userspace/libscap/scap_const.h b/userspace/libscap/scap_const.h index dcae7cc630..9257032d3c 100644 --- a/userspace/libscap/scap_const.h +++ b/userspace/libscap/scap_const.h @@ -37,4 +37,3 @@ limitations under the License. // Last error string size for `scap_open...` methods. // #define SCAP_LASTERR_SIZE 256 - diff --git a/userspace/libscap/scap_engine_util.c b/userspace/libscap/scap_engine_util.c index 1e2cb01bca..9907857d74 100644 --- a/userspace/libscap/scap_engine_util.c +++ b/userspace/libscap/scap_engine_util.c @@ -26,22 +26,18 @@ limitations under the License. #include -static inline uint64_t timespec_to_nsec(const struct timespec* ts) -{ +static inline uint64_t timespec_to_nsec(const struct timespec* ts) { return ts->tv_sec * 1000000000 + ts->tv_nsec; } -int32_t scap_get_precise_boot_time(char* last_err, uint64_t *boot_time) -{ +int32_t scap_get_precise_boot_time(char* last_err, uint64_t* boot_time) { struct timespec wall_ts, boot_ts; - if(clock_gettime(CLOCK_BOOTTIME, &boot_ts) < 0) - { + if(clock_gettime(CLOCK_BOOTTIME, &boot_ts) < 0) { return scap_errprintf(last_err, errno, "Failed to get CLOCK_BOOTTIME"); } - if(clock_gettime(CLOCK_REALTIME, &wall_ts) < 0) - { + if(clock_gettime(CLOCK_REALTIME, &wall_ts) < 0) { return scap_errprintf(last_err, errno, "Failed to get CLOCK_REALTIME"); } @@ -49,14 +45,11 @@ int32_t scap_get_precise_boot_time(char* last_err, uint64_t *boot_time) return SCAP_SUCCESS; } -bool scap_get_bpf_stats_enabled() -{ +bool scap_get_bpf_stats_enabled() { FILE* f; - if((f = fopen("/proc/sys/kernel/bpf_stats_enabled", "r"))) - { + if((f = fopen("/proc/sys/kernel/bpf_stats_enabled", "r"))) { uint32_t bpf_stats_enabled = 0; - if(fscanf(f, "%u", &bpf_stats_enabled) == 1) - { + if(fscanf(f, "%u", &bpf_stats_enabled) == 1) { fclose(f); return bpf_stats_enabled; } @@ -65,4 +58,3 @@ bool scap_get_bpf_stats_enabled() } return false; } - diff --git a/userspace/libscap/scap_engine_util.h b/userspace/libscap/scap_engine_util.h index e7a019ebb1..efa8b03f8f 100644 --- a/userspace/libscap/scap_engine_util.h +++ b/userspace/libscap/scap_engine_util.h @@ -22,8 +22,7 @@ limitations under the License. #include #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif /** @@ -38,7 +37,7 @@ extern "C" * - doesn't need wide compatibility (only needs to work on systems supporting eBPF) * - needs as much accuracy as we can get (otherwise eBPF event timestamps will be wrong) */ -int32_t scap_get_precise_boot_time(char* last_err, uint64_t *boot_time); +int32_t scap_get_precise_boot_time(char* last_err, uint64_t* boot_time); bool scap_get_bpf_stats_enabled(); diff --git a/userspace/libscap/scap_event.c b/userspace/libscap/scap_event.c index 09bf57d59e..539c76bb3b 100644 --- a/userspace/libscap/scap_event.c +++ b/userspace/libscap/scap_event.c @@ -24,7 +24,7 @@ limitations under the License. #else #include #include -#endif // _WIN32 +#endif // _WIN32 #include #include @@ -34,87 +34,73 @@ limitations under the License. // // Get the event info table // -const struct ppm_event_info* scap_get_event_info_table() -{ +const struct ppm_event_info *scap_get_event_info_table() { return g_event_info; } -enum ppm_event_category scap_get_syscall_category_from_event(ppm_event_code ev) -{ +enum ppm_event_category scap_get_syscall_category_from_event(ppm_event_code ev) { ASSERT(ev < PPM_EVENT_MAX); - return g_event_info[ev].category & (EC_SYSCALL -1); + return g_event_info[ev].category & (EC_SYSCALL - 1); } -enum ppm_event_category scap_get_event_category_from_event(ppm_event_code ev) -{ +enum ppm_event_category scap_get_event_category_from_event(ppm_event_code ev) { ASSERT(ev < PPM_EVENT_MAX); - return g_event_info[ev].category & ~(EC_SYSCALL -1); + return g_event_info[ev].category & ~(EC_SYSCALL - 1); } -uint32_t scap_event_getlen(scap_evt* e) -{ +uint32_t scap_event_getlen(scap_evt *e) { return e->len; } -uint64_t scap_event_get_num(scap_t* handle) -{ +uint64_t scap_event_get_num(scap_t *handle) { return handle->m_evtcnt; } -uint64_t scap_event_get_ts(scap_evt* e) -{ +uint64_t scap_event_get_ts(scap_evt *e) { return e->ts; } #ifdef PPM_ENABLE_SENTINEL -uint32_t scap_event_get_sentinel_begin(scap_evt* e) -{ +uint32_t scap_event_get_sentinel_begin(scap_evt *e) { return e->sentinel_begin; } #endif -const struct ppm_event_info* scap_event_getinfo(const scap_evt* e) -{ +const struct ppm_event_info *scap_event_getinfo(const scap_evt *e) { return &(g_event_info[e->type]); } -uint32_t scap_event_has_large_payload(const scap_evt* e) -{ +uint32_t scap_event_has_large_payload(const scap_evt *e) { return (g_event_info[e->type].flags & EF_LARGE_PAYLOAD) != 0; } -uint32_t scap_event_decode_params(const scap_evt *e, struct scap_sized_buffer *params) -{ - char *len_buf = (char*)e + sizeof(struct ppm_evt_hdr); +uint32_t scap_event_decode_params(const scap_evt *e, struct scap_sized_buffer *params) { + char *len_buf = (char *)e + sizeof(struct ppm_evt_hdr); char *param_buf = len_buf; uint32_t is_large = scap_event_has_large_payload(e); uint32_t param_size_32; uint16_t param_size_16; - const struct ppm_event_info* event_info = &(g_event_info[e->type]); - + const struct ppm_event_info *event_info = &(g_event_info[e->type]); + // If we're reading a capture created with a newer version, it may contain // new parameters. If instead we're reading an older version, the current // event table entry may contain new parameters. // Use the minimum between the two values. uint32_t n = event_info->nparams < e->nparams ? event_info->nparams : e->nparams; - if(is_large) - { + if(is_large) { param_buf += sizeof(uint32_t) * e->nparams; - } else - { + } else { param_buf += sizeof(uint16_t) * e->nparams; } for(size_t i = 0; i < n; i++) { - if(is_large) - { + if(is_large) { memcpy(¶m_size_32, len_buf, sizeof(uint32_t)); params[i].size = param_size_32; len_buf += sizeof(uint32_t); - } else - { + } else { memcpy(¶m_size_16, len_buf, sizeof(uint16_t)); params[i].size = param_size_16; len_buf += sizeof(uint16_t); @@ -127,41 +113,49 @@ uint32_t scap_event_decode_params(const scap_evt *e, struct scap_sized_buffer *p return n; } -void scap_event_set_param_length_regular(scap_evt *event, uint32_t n, uint16_t len) -{ - memcpy((char *)event + sizeof(struct ppm_evt_hdr) + sizeof(uint16_t) * n, &len, sizeof(uint16_t)); +void scap_event_set_param_length_regular(scap_evt *event, uint32_t n, uint16_t len) { + memcpy((char *)event + sizeof(struct ppm_evt_hdr) + sizeof(uint16_t) * n, + &len, + sizeof(uint16_t)); } -void scap_event_set_param_length_large(scap_evt *event, uint32_t n, uint32_t len) -{ - memcpy((char *)event + sizeof(struct ppm_evt_hdr) + sizeof(uint32_t) * n, &len, sizeof(uint32_t)); +void scap_event_set_param_length_large(scap_evt *event, uint32_t n, uint32_t len) { + memcpy((char *)event + sizeof(struct ppm_evt_hdr) + sizeof(uint32_t) * n, + &len, + sizeof(uint32_t)); } -static inline int32_t scap_buffer_can_fit(struct scap_sized_buffer buf, size_t len) -{ +static inline int32_t scap_buffer_can_fit(struct scap_sized_buffer buf, size_t len) { return (buf.size >= len); } -int32_t scap_event_encode_params(struct scap_sized_buffer event_buf, size_t *event_size, char *error, ppm_event_code event_type, uint32_t n, ...) -{ - va_list args; - va_start(args, n); - int32_t ret = scap_event_encode_params_v(event_buf, event_size, error, event_type, n, args); - va_end(args); +int32_t scap_event_encode_params(struct scap_sized_buffer event_buf, + size_t *event_size, + char *error, + ppm_event_code event_type, + uint32_t n, + ...) { + va_list args; + va_start(args, n); + int32_t ret = scap_event_encode_params_v(event_buf, event_size, error, event_type, n, args); + va_end(args); return ret; } -int32_t scap_event_encode_params_v(const struct scap_sized_buffer event_buf, size_t *event_size, char *error, ppm_event_code event_type, uint32_t n, va_list args) -{ +int32_t scap_event_encode_params_v(const struct scap_sized_buffer event_buf, + size_t *event_size, + char *error, + ppm_event_code event_type, + uint32_t n, + va_list args) { scap_evt *event = NULL; const struct ppm_event_info *event_info = &g_event_info[event_type]; // len_size is the size in bytes of an entry of the parameter length array size_t len_size = sizeof(uint16_t); - if((event_info->flags & EF_LARGE_PAYLOAD) != 0) - { + if((event_info->flags & EF_LARGE_PAYLOAD) != 0) { len_size = sizeof(uint32_t); } @@ -169,27 +163,25 @@ int32_t scap_event_encode_params_v(const struct scap_sized_buffer event_buf, siz size_t len = sizeof(struct ppm_evt_hdr) + len_size * n; - // every buffer write access needs to be guarded by a scap_buffer_can_fit call to check if it's large enough - if (scap_buffer_can_fit(event_buf, len)) - { + // every buffer write access needs to be guarded by a scap_buffer_can_fit call to check if it's + // large enough + if(scap_buffer_can_fit(event_buf, len)) { event = event_buf.buf; event->type = event_type; event->nparams = n; event->len = len; } - for(int i = 0; i < n; i++) - { + for(int i = 0; i < n; i++) { const struct ppm_param_info *pi = &event_info->params[i]; struct scap_const_sized_buffer param = {0}; - uint8_t u8_arg; - uint16_t u16_arg; - uint32_t u32_arg; - uint64_t u64_arg; + uint8_t u8_arg; + uint16_t u16_arg; + uint32_t u32_arg; + uint64_t u64_arg; - switch(pi->type) - { + switch(pi->type) { case PT_INT8: case PT_UINT8: case PT_FLAGS8: @@ -197,7 +189,7 @@ int32_t scap_event_encode_params_v(const struct scap_sized_buffer event_buf, siz case PT_L4PROTO: case PT_SOCKFAMILY: case PT_ENUMFLAGS8: - u8_arg = (uint8_t) (va_arg(args, int) & 0xff); + u8_arg = (uint8_t)(va_arg(args, int) & 0xff); param.buf = &u8_arg; param.size = sizeof(uint8_t); break; @@ -208,7 +200,7 @@ int32_t scap_event_encode_params_v(const struct scap_sized_buffer event_buf, siz case PT_PORT: case PT_FLAGS16: case PT_ENUMFLAGS16: - u16_arg = (uint16_t) (va_arg(args, int) & 0xffff); + u16_arg = (uint16_t)(va_arg(args, int) & 0xffff); param.buf = &u16_arg; param.size = sizeof(uint16_t); break; @@ -223,9 +215,9 @@ int32_t scap_event_encode_params_v(const struct scap_sized_buffer event_buf, siz case PT_SIGSET: case PT_MODE: case PT_ENUMFLAGS32: - u32_arg = va_arg(args, uint32_t); - param.buf = &u32_arg; - param.size = sizeof(uint32_t); + u32_arg = va_arg(args, uint32_t); + param.buf = &u32_arg; + param.size = sizeof(uint32_t); break; case PT_INT64: @@ -236,110 +228,125 @@ int32_t scap_event_encode_params_v(const struct scap_sized_buffer event_buf, siz case PT_RELTIME: case PT_ABSTIME: case PT_DOUBLE: - u64_arg = va_arg(args, uint64_t); - param.buf = &u64_arg; - param.size = sizeof(uint64_t); + u64_arg = va_arg(args, uint64_t); + param.buf = &u64_arg; + param.size = sizeof(uint64_t); break; case PT_CHARBUF: case PT_FSPATH: case PT_FSRELPATH: - param.buf = va_arg(args, char*); - if(param.buf == NULL) - { + param.buf = va_arg(args, char *); + if(param.buf == NULL) { param.size = 0; - } - else - { + } else { param.size = strlen(param.buf) + 1; } break; - case PT_BYTEBUF: /* A raw buffer of bytes not suitable for printing */ - case PT_SOCKTUPLE: /* A sockaddr tuple,1byte family + 12byte data + 12byte data */ - case PT_FDLIST: /* A list of fds, 16bit count + count * (64bit fd + 16bit flags) */ - case PT_DYN: /* Type can vary depending on the context. Used for filter fields like evt.rawarg. */ - case PT_CHARBUFARRAY: /* Pointer to an array of strings, exported by the user events decoder. 64bit. For internal use only. */ - case PT_CHARBUF_PAIR_ARRAY: /* Pointer to an array of string pairs, exported by the user events decoder. 64bit. For internal use only. */ - case PT_IPV4NET: /* An IPv4 network. */ - case PT_IPV6ADDR: /* A 16 byte raw IPv6 address. */ - case PT_IPV6NET: /* An IPv6 network. */ - case PT_IPADDR: /* Either an IPv4 or IPv6 address. The length indicates which one it is. */ - case PT_IPNET: /* Either an IPv4 or IPv6 network. The length indicates which one it is. */ + case PT_BYTEBUF: /* A raw buffer of bytes not suitable for printing */ + case PT_SOCKTUPLE: /* A sockaddr tuple,1byte family + 12byte data + 12byte data */ + case PT_FDLIST: /* A list of fds, 16bit count + count * (64bit fd + 16bit flags) */ + case PT_DYN: /* Type can vary depending on the context. Used for filter fields like + evt.rawarg. */ + case PT_CHARBUFARRAY: /* Pointer to an array of strings, exported by the user events + decoder. 64bit. For internal use only. */ + case PT_CHARBUF_PAIR_ARRAY: /* Pointer to an array of string pairs, exported by the user + events decoder. 64bit. For internal use only. */ + case PT_IPV4NET: /* An IPv4 network. */ + case PT_IPV6ADDR: /* A 16 byte raw IPv6 address. */ + case PT_IPV6NET: /* An IPv6 network. */ + case PT_IPADDR: /* Either an IPv4 or IPv6 address. The length indicates which one it is. */ + case PT_IPNET: /* Either an IPv4 or IPv6 network. The length indicates which one it is. */ case PT_SOCKADDR: - param = va_arg(args, struct scap_const_sized_buffer); + param = va_arg(args, struct scap_const_sized_buffer); break; - + case PT_NONE: - case PT_MAX: - break; // Nothing to do - default: // Unsupported event - snprintf(error, SCAP_LASTERR_SIZE, "event param %d (param type %d) is unsupported", i, pi->type); + case PT_MAX: + break; // Nothing to do + default: // Unsupported event + snprintf(error, + SCAP_LASTERR_SIZE, + "event param %d (param type %d) is unsupported", + i, + pi->type); return SCAP_FAILURE; } uint16_t param_size_16; uint32_t param_size_32; - switch(len_size) - { - case sizeof(uint16_t): - param_size_16 = (uint16_t) (param.size & 0xffff); - if (param_size_16 != param.size) - { - snprintf(error, SCAP_LASTERR_SIZE, "could not fit event param %d size %zu for event with type %d in %zu bytes", - i, param.size, event->type, len_size); - return SCAP_FAILURE; - } - if (scap_buffer_can_fit(event_buf, len)) - { - scap_event_set_param_length_regular(event, i, param_size_16); - } - break; - case sizeof(uint32_t): - param_size_32 = (uint32_t) (param.size & 0xffffffff); - if (param_size_32 != param.size) - { - snprintf(error, SCAP_LASTERR_SIZE, "could not fit event param %d size %zu for event with type %d in %zu bytes", - i, param.size, event->type, len_size); - return SCAP_FAILURE; - } - if (scap_buffer_can_fit(event_buf, len)) - { - scap_event_set_param_length_large(event, i, param_size_32); - } - break; - default: - snprintf(error, SCAP_LASTERR_SIZE, "unexpected param %d length %zu for event with type %d", - i, len_size, event->type); + switch(len_size) { + case sizeof(uint16_t): + param_size_16 = (uint16_t)(param.size & 0xffff); + if(param_size_16 != param.size) { + snprintf( + error, + SCAP_LASTERR_SIZE, + "could not fit event param %d size %zu for event with type %d in %zu bytes", + i, + param.size, + event->type, + len_size); return SCAP_FAILURE; + } + if(scap_buffer_can_fit(event_buf, len)) { + scap_event_set_param_length_regular(event, i, param_size_16); + } + break; + case sizeof(uint32_t): + param_size_32 = (uint32_t)(param.size & 0xffffffff); + if(param_size_32 != param.size) { + snprintf( + error, + SCAP_LASTERR_SIZE, + "could not fit event param %d size %zu for event with type %d in %zu bytes", + i, + param.size, + event->type, + len_size); + return SCAP_FAILURE; + } + if(scap_buffer_can_fit(event_buf, len)) { + scap_event_set_param_length_large(event, i, param_size_32); + } + break; + default: + snprintf(error, + SCAP_LASTERR_SIZE, + "unexpected param %d length %zu for event with type %d", + i, + len_size, + event->type); + return SCAP_FAILURE; } - if (scap_buffer_can_fit(event_buf, len + param.size) && param.size != 0) - { - memcpy(((char*)event_buf.buf + len), param.buf, param.size); + if(scap_buffer_can_fit(event_buf, len + param.size) && param.size != 0) { + memcpy(((char *)event_buf.buf + len), param.buf, param.size); } - len = len + param.size; + len = len + param.size; } #ifdef PPM_ENABLE_SENTINEL - if (scap_buffer_can_fit(event_buf, len + sizeof(uint32_t))) - { + if(scap_buffer_can_fit(event_buf, len + sizeof(uint32_t))) { event->sentinel_begin = 0x01020304; - memcpy(((char*)event_buf.buf + len), &event->sentinel_begin, sizeof(uint32_t)); + memcpy(((char *)event_buf.buf + len), &event->sentinel_begin, sizeof(uint32_t)); } len = len + sizeof(uint32_t); #endif - if (event_size != NULL) - { + if(event_size != NULL) { *event_size = len; } // we were not able to write the event to the buffer - if (!scap_buffer_can_fit(event_buf, len)) - { - snprintf(error, SCAP_LASTERR_SIZE, "Could not encode event of size %zu into supplied buffer sized %zu.", len, event_buf.size); + if(!scap_buffer_can_fit(event_buf, len)) { + snprintf(error, + SCAP_LASTERR_SIZE, + "Could not encode event of size %zu into supplied buffer sized %zu.", + len, + event_buf.size); return SCAP_INPUT_TOO_SMALL; } diff --git a/userspace/libscap/scap_fds.c b/userspace/libscap/scap_fds.c index 89ea1564ca..5b9e8cabb9 100644 --- a/userspace/libscap/scap_fds.c +++ b/userspace/libscap/scap_fds.c @@ -22,15 +22,12 @@ limitations under the License. #include #include -void scap_fd_free_table(scap_fdinfo **fds) -{ +void scap_fd_free_table(scap_fdinfo **fds) { struct scap_fdinfo *fdi; struct scap_fdinfo *tfdi; - if(*fds) - { - HASH_ITER(hh, *fds, fdi, tfdi) - { + if(*fds) { + HASH_ITER(hh, *fds, fdi, tfdi) { HASH_DEL(*fds, fdi); free(fdi); } @@ -38,10 +35,8 @@ void scap_fd_free_table(scap_fdinfo **fds) } } -void scap_fd_free_proc_fd_table(scap_threadinfo *tinfo) -{ - if(tinfo->fdlist) - { +void scap_fd_free_proc_fd_table(scap_threadinfo *tinfo) { + if(tinfo->fdlist) { scap_fd_free_table(&tinfo->fdlist); } } @@ -49,12 +44,10 @@ void scap_fd_free_proc_fd_table(scap_threadinfo *tinfo) // // Free the device table // -void scap_free_device_table(scap_mountinfo* dev_list) -{ +void scap_free_device_table(scap_mountinfo *dev_list) { scap_mountinfo *dev, *tdev; - HASH_ITER(hh, dev_list, dev, tdev) - { + HASH_ITER(hh, dev_list, dev, tdev) { HASH_DEL(dev_list, dev); free(dev); } diff --git a/userspace/libscap/scap_iflist.c b/userspace/libscap/scap_iflist.c index 14010b731c..f6e016cbb3 100644 --- a/userspace/libscap/scap_iflist.c +++ b/userspace/libscap/scap_iflist.c @@ -24,17 +24,13 @@ limitations under the License. // // Free a previously allocated list of interfaces // -void scap_free_iflist(scap_addrlist* ifhandle) -{ - if(ifhandle) - { - if(ifhandle->v6list) - { +void scap_free_iflist(scap_addrlist* ifhandle) { + if(ifhandle) { + if(ifhandle->v6list) { free(ifhandle->v6list); } - if(ifhandle->v4list) - { + if(ifhandle->v4list) { free(ifhandle->v4list); } diff --git a/userspace/libscap/scap_log.h b/userspace/libscap/scap_log.h index a450179ccc..9034ea7483 100644 --- a/userspace/libscap/scap_log.h +++ b/userspace/libscap/scap_log.h @@ -1,7 +1,6 @@ #pragma once -enum falcosecurity_log_severity -{ +enum falcosecurity_log_severity { FALCOSECURITY_LOG_SEV_FATAL = 1, FALCOSECURITY_LOG_SEV_CRITICAL = 2, FALCOSECURITY_LOG_SEV_ERROR = 3, @@ -12,4 +11,6 @@ enum falcosecurity_log_severity FALCOSECURITY_LOG_SEV_TRACE = 8, }; -typedef void (*falcosecurity_log_fn)(const char* component, const char* msg, const enum falcosecurity_log_severity sev); +typedef void (*falcosecurity_log_fn)(const char* component, + const char* msg, + const enum falcosecurity_log_severity sev); diff --git a/userspace/libscap/scap_machine_info.h b/userspace/libscap/scap_machine_info.h index 32153f9354..67cdb3eed6 100644 --- a/userspace/libscap/scap_machine_info.h +++ b/userspace/libscap/scap_machine_info.h @@ -37,28 +37,28 @@ extern "C" { /*! \brief Machine information */ -typedef struct _scap_machine_info -{ - uint32_t num_cpus; ///< Number of processors - uint64_t memory_size_bytes; ///< Physical memory size - uint64_t max_pid; ///< Highest PID number on this machine - char hostname[128]; ///< The machine hostname - uint64_t boot_ts_epoch; ///< Host boot ts in nanoseconds (epoch) - uint64_t flags; ///< flags - uint64_t reserved3; ///< reserved for future use - uint64_t reserved4; ///< reserved for future use, note: because of scap file captures needs to remain uint64_t, use flags if possible -}scap_machine_info; +typedef struct _scap_machine_info { + uint32_t num_cpus; ///< Number of processors + uint64_t memory_size_bytes; ///< Physical memory size + uint64_t max_pid; ///< Highest PID number on this machine + char hostname[128]; ///< The machine hostname + uint64_t boot_ts_epoch; ///< Host boot ts in nanoseconds (epoch) + uint64_t flags; ///< flags + uint64_t reserved3; ///< reserved for future use + uint64_t reserved4; ///< reserved for future use, note: because of scap file captures needs to + ///< remain uint64_t, use flags if possible +} scap_machine_info; #pragma pack(pop) /*! \brief Agent information, not intended for scap file use */ -typedef struct _scap_agent_info -{ - uint64_t start_ts_epoch; ///< Agent start timestamp, stat /proc/self/cmdline approach, unit: epoch in nanoseconds - double start_time; ///< /proc/self/stat start_time divided by HZ, unit: seconds since boot - char uname_r[128]; ///< Kernel release `uname -r` +typedef struct _scap_agent_info { + uint64_t start_ts_epoch; ///< Agent start timestamp, stat /proc/self/cmdline approach, unit: + ///< epoch in nanoseconds + double start_time; ///< /proc/self/stat start_time divided by HZ, unit: seconds since boot + char uname_r[128]; ///< Kernel release `uname -r` } scap_agent_info; #ifdef __cplusplus diff --git a/userspace/libscap/scap_open.h b/userspace/libscap/scap_open.h index 8fb6b804d4..502f4fd270 100644 --- a/userspace/libscap/scap_open.h +++ b/userspace/libscap/scap_open.h @@ -27,29 +27,27 @@ limitations under the License. #include #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - /*! - * \brief Argument for scap_open - * Set any PPM_SC syscall idx to true to enable its tracing at driver level, - * otherwise syscalls are not traced (so called "uninteresting syscalls"). - */ - typedef struct - { - bool ppm_sc[PPM_SC_MAX]; - } interesting_ppm_sc_set; - - typedef struct scap_open_args - { - bool import_users; ///< true if the user list should be created when opening the capture. - interesting_ppm_sc_set ppm_sc_of_interest; ///< syscalls of interest. - falcosecurity_log_fn log_fn; //< Function which SCAP may use to log messages - uint64_t proc_scan_timeout_ms; //< Timeout in msec, after which so-far-successful scan of /proc should be cut short with success return - uint64_t proc_scan_log_interval_ms; //< Interval for logging progress messages from /proc scan - void* engine_params; ///< engine-specific params. - } scap_open_args; +/*! + * \brief Argument for scap_open + * Set any PPM_SC syscall idx to true to enable its tracing at driver level, + * otherwise syscalls are not traced (so called "uninteresting syscalls"). + */ +typedef struct { + bool ppm_sc[PPM_SC_MAX]; +} interesting_ppm_sc_set; + +typedef struct scap_open_args { + bool import_users; ///< true if the user list should be created when opening the capture. + interesting_ppm_sc_set ppm_sc_of_interest; ///< syscalls of interest. + falcosecurity_log_fn log_fn; //< Function which SCAP may use to log messages + uint64_t proc_scan_timeout_ms; //< Timeout in msec, after which so-far-successful scan of /proc + // should be cut short with success return + uint64_t proc_scan_log_interval_ms; //< Interval for logging progress messages from /proc scan + void* engine_params; ///< engine-specific params. +} scap_open_args; #ifdef __cplusplus } diff --git a/userspace/libscap/scap_platform.c b/userspace/libscap/scap_platform.c index 410d56a075..27757c2ed6 100644 --- a/userspace/libscap/scap_platform.c +++ b/userspace/libscap/scap_platform.c @@ -22,36 +22,32 @@ limitations under the License. #include #include -int32_t scap_generic_init_platform(struct scap_platform* platform, char* lasterr, struct scap_open_args* oargs) -{ +int32_t scap_generic_init_platform(struct scap_platform* platform, + char* lasterr, + struct scap_open_args* oargs) { memset(&platform->m_machine_info, 0, sizeof(platform->m_machine_info)); memset(&platform->m_agent_info, 0, sizeof(platform->m_agent_info)); return SCAP_SUCCESS; } -static int32_t scap_generic_close_platform(struct scap_platform* platform) -{ - if (platform->m_addrlist) - { +static int32_t scap_generic_close_platform(struct scap_platform* platform) { + if(platform->m_addrlist) { scap_free_iflist(platform->m_addrlist); platform->m_addrlist = NULL; } - if (platform->m_userlist) - { + if(platform->m_userlist) { scap_free_userlist(platform->m_userlist); platform->m_userlist = NULL; } - if(platform->m_proclist.m_proclist != NULL) - { + if(platform->m_proclist.m_proclist != NULL) { scap_proc_free_table(&platform->m_proclist); platform->m_proclist.m_proclist = NULL; } - if(platform->m_driver_procinfo != NULL) - { + if(platform->m_driver_procinfo != NULL) { scap_free_proclist_info(platform->m_driver_procinfo); platform->m_driver_procinfo = NULL; } @@ -59,23 +55,21 @@ static int32_t scap_generic_close_platform(struct scap_platform* platform) return SCAP_SUCCESS; } -static void scap_generic_free_platform(struct scap_platform* platform) -{ +static void scap_generic_free_platform(struct scap_platform* platform) { free(platform); } struct scap_platform_vtable scap_generic_platform_vtable = { - .init_platform = NULL, - .close_platform = NULL, - .free_platform = scap_generic_free_platform, + .init_platform = NULL, + .close_platform = NULL, + .free_platform = scap_generic_free_platform, }; -struct scap_platform* scap_generic_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context) -{ +struct scap_platform* scap_generic_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context) { struct scap_platform* platform = calloc(1, sizeof(*platform)); - if(platform == NULL) - { + if(platform == NULL) { return NULL; } @@ -86,67 +80,54 @@ struct scap_platform* scap_generic_alloc_platform(proc_entry_callback proc_callb return platform; } -int32_t scap_platform_init(struct scap_platform *platform, char *lasterr, struct scap_engine_handle engine, - struct scap_open_args *oargs) -{ +int32_t scap_platform_init(struct scap_platform* platform, + char* lasterr, + struct scap_engine_handle engine, + struct scap_open_args* oargs) { int32_t rc; - if(!platform) - { + if(!platform) { return SCAP_SUCCESS; } rc = scap_generic_init_platform(platform, lasterr, oargs); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { scap_platform_close(platform); return rc; } - if(platform->m_vtable && platform->m_vtable->init_platform) - { + if(platform->m_vtable && platform->m_vtable->init_platform) { rc = platform->m_vtable->init_platform(platform, lasterr, engine, oargs); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { scap_platform_close(platform); } return rc; - } - else - { + } else { return SCAP_SUCCESS; } } -int32_t scap_platform_close(struct scap_platform* platform) -{ +int32_t scap_platform_close(struct scap_platform* platform) { int32_t rc; - if(!platform) - { + if(!platform) { return SCAP_SUCCESS; } rc = scap_generic_close_platform(platform); - if(rc != SCAP_SUCCESS) - { + if(rc != SCAP_SUCCESS) { return rc; } - if(platform->m_vtable && platform->m_vtable->close_platform) - { + if(platform->m_vtable && platform->m_vtable->close_platform) { return platform->m_vtable->close_platform(platform); - } - else - { + } else { return SCAP_SUCCESS; } } -void scap_platform_free(struct scap_platform* platform) -{ - if(!platform) - { +void scap_platform_free(struct scap_platform* platform) { + if(!platform) { return; } diff --git a/userspace/libscap/scap_platform.h b/userspace/libscap/scap_platform.h index b2319a62ea..3920822ee9 100644 --- a/userspace/libscap/scap_platform.h +++ b/userspace/libscap/scap_platform.h @@ -38,15 +38,20 @@ struct scap_platform; // Note: every platform alloc function needs to set up the proc_callback, since // this needs to be called before opening the engine; otherwise the proclist callback // won't be set up in time (for the savefile engine) -struct scap_platform* scap_generic_alloc_platform(proc_entry_callback proc_callback, void* proc_callback_context); +struct scap_platform* scap_generic_alloc_platform(proc_entry_callback proc_callback, + void* proc_callback_context); // initialize the common part of the platform handle -int32_t scap_generic_init_platform(struct scap_platform* platform, char* lasterr, struct scap_open_args* oargs); +int32_t scap_generic_init_platform(struct scap_platform* platform, + char* lasterr, + struct scap_open_args* oargs); // initialize a platform handle // this calls `scap_generic_init_platform` and `init_platform` from the vtable -int32_t scap_platform_init(struct scap_platform *platform, char *lasterr, struct scap_engine_handle engine, - struct scap_open_args *oargs); +int32_t scap_platform_init(struct scap_platform* platform, + char* lasterr, + struct scap_engine_handle engine, + struct scap_open_args* oargs); // close a platform // this calls `close_platform` from the vtable and also diff --git a/userspace/libscap/scap_platform_api.c b/userspace/libscap/scap_platform_api.c index 6202a3a459..3853d6d9a0 100644 --- a/userspace/libscap/scap_platform_api.c +++ b/userspace/libscap/scap_platform_api.c @@ -24,69 +24,62 @@ limitations under the License. #include #include -scap_addrlist* scap_get_ifaddr_list(struct scap_platform* platform) -{ - if (platform) - { +scap_addrlist* scap_get_ifaddr_list(struct scap_platform* platform) { + if(platform) { return platform->m_addrlist; } return NULL; } -void scap_refresh_iflist(struct scap_platform* platform) -{ - if (platform && platform->m_vtable->refresh_addr_list) - { +void scap_refresh_iflist(struct scap_platform* platform) { + if(platform && platform->m_vtable->refresh_addr_list) { platform->m_vtable->refresh_addr_list(platform); } } -scap_userlist* scap_get_user_list(struct scap_platform* platform) -{ - if (platform) - { +scap_userlist* scap_get_user_list(struct scap_platform* platform) { + if(platform) { return platform->m_userlist; } return NULL; } -uint32_t scap_get_device_by_mount_id(struct scap_platform* platform, const char *procdir, unsigned long requested_mount_id) -{ - if (platform && platform->m_vtable->get_device_by_mount_id) - { +uint32_t scap_get_device_by_mount_id(struct scap_platform* platform, + const char* procdir, + unsigned long requested_mount_id) { + if(platform && platform->m_vtable->get_device_by_mount_id) { return platform->m_vtable->get_device_by_mount_id(platform, procdir, requested_mount_id); } return 0; } -int32_t scap_proc_get(struct scap_platform* platform, int64_t tid, struct scap_threadinfo* tinfo, - bool scan_sockets) -{ - if (platform && platform->m_vtable->get_proc) - { +int32_t scap_proc_get(struct scap_platform* platform, + int64_t tid, + struct scap_threadinfo* tinfo, + bool scan_sockets) { + if(platform && platform->m_vtable->get_proc) { return platform->m_vtable->get_proc(platform, tid, tinfo, scan_sockets); } return SCAP_FAILURE; } -int32_t scap_refresh_proc_table(struct scap_platform* platform) -{ - if (platform && platform->m_vtable->refresh_proc_table) - { +int32_t scap_refresh_proc_table(struct scap_platform* platform) { + if(platform && platform->m_vtable->refresh_proc_table) { return platform->m_vtable->refresh_proc_table(platform, &platform->m_proclist); } return SCAP_FAILURE; } -bool scap_is_thread_alive(struct scap_platform* platform, int64_t pid, int64_t tid, const char* comm) -{ - if (platform && platform->m_vtable->is_thread_alive) - { +bool scap_is_thread_alive(struct scap_platform* platform, + int64_t pid, + int64_t tid, + const char* comm) { + if(platform && platform->m_vtable->is_thread_alive) { return platform->m_vtable->is_thread_alive(platform, pid, tid, comm); } @@ -94,16 +87,13 @@ bool scap_is_thread_alive(struct scap_platform* platform, int64_t pid, int64_t t return true; } -int32_t scap_getpid_global(struct scap_platform* platform, int64_t* pid) -{ - if (platform == NULL) - { +int32_t scap_getpid_global(struct scap_platform* platform, int64_t* pid) { + if(platform == NULL) { ASSERT(false); return SCAP_FAILURE; } - if (platform->m_vtable->get_global_pid == NULL) - { + if(platform->m_vtable->get_global_pid == NULL) { return SCAP_NOT_SUPPORTED; } @@ -111,13 +101,10 @@ int32_t scap_getpid_global(struct scap_platform* platform, int64_t* pid) return platform->m_vtable->get_global_pid(platform, pid, lasterr); } -const scap_machine_info* scap_get_machine_info(struct scap_platform* platform) -{ - if(platform) - { +const scap_machine_info* scap_get_machine_info(struct scap_platform* platform) { + if(platform) { scap_machine_info* machine_info = &platform->m_machine_info; - if(machine_info->num_cpus != (uint32_t)-1) - { + if(machine_info->num_cpus != (uint32_t)-1) { return machine_info; } } @@ -131,22 +118,18 @@ const scap_machine_info* scap_get_machine_info(struct scap_platform* platform) // // Get the agent information // -const scap_agent_info* scap_get_agent_info(struct scap_platform* platform) -{ - if(platform) - { +const scap_agent_info* scap_get_agent_info(struct scap_platform* platform) { + if(platform) { return (const scap_agent_info*)&platform->m_agent_info; } return NULL; } -struct ppm_proclist_info* scap_get_threadlist(struct scap_platform* platform, char* error) -{ - if (platform && platform->m_vtable->get_threadlist) - { - if(platform->m_vtable->get_threadlist(platform, &platform->m_driver_procinfo, error) == SCAP_SUCCESS) - { +struct ppm_proclist_info* scap_get_threadlist(struct scap_platform* platform, char* error) { + if(platform && platform->m_vtable->get_threadlist) { + if(platform->m_vtable->get_threadlist(platform, &platform->m_driver_procinfo, error) == + SCAP_SUCCESS) { return platform->m_driver_procinfo; } return NULL; @@ -156,10 +139,10 @@ struct ppm_proclist_info* scap_get_threadlist(struct scap_platform* platform, ch return NULL; } -int32_t scap_get_fdlist(struct scap_platform* platform, struct scap_threadinfo* tinfo, char* error) -{ - if (platform && platform->m_vtable->get_fdlist) - { +int32_t scap_get_fdlist(struct scap_platform* platform, + struct scap_threadinfo* tinfo, + char* error) { + if(platform && platform->m_vtable->get_fdlist) { return platform->m_vtable->get_fdlist(platform, tinfo, error); } diff --git a/userspace/libscap/scap_platform_api.h b/userspace/libscap/scap_platform_api.h index 6cb4a20720..ee88ceb572 100644 --- a/userspace/libscap/scap_platform_api.h +++ b/userspace/libscap/scap_platform_api.h @@ -59,19 +59,27 @@ void scap_refresh_iflist(struct scap_platform* platform); */ struct scap_userlist* scap_get_user_list(struct scap_platform* platform); -// get the device major/minor number for the requested_mount_id, looking in procdir/mountinfo if needed +// get the device major/minor number for the requested_mount_id, looking in procdir/mountinfo if +// needed // XXX: procdir is Linux-specific -uint32_t scap_get_device_by_mount_id(struct scap_platform* platform, const char *procdir, unsigned long requested_mount_id); +uint32_t scap_get_device_by_mount_id(struct scap_platform* platform, + const char* procdir, + unsigned long requested_mount_id); // Get the information about a process. // The returned pointer must be freed via scap_proc_free by the caller. -int32_t scap_proc_get(struct scap_platform* platform, int64_t tid, struct scap_threadinfo* tinfo, - bool scan_sockets); +int32_t scap_proc_get(struct scap_platform* platform, + int64_t tid, + struct scap_threadinfo* tinfo, + bool scan_sockets); int32_t scap_refresh_proc_table(struct scap_platform* platform); // Check if the given thread exists in /proc -bool scap_is_thread_alive(struct scap_platform* platform, int64_t pid, int64_t tid, const char* comm); +bool scap_is_thread_alive(struct scap_platform* platform, + int64_t pid, + int64_t tid, + const char* comm); // like getpid() but returns the global PID even inside a container int32_t scap_getpid_global(struct scap_platform* platform, int64_t* pid); diff --git a/userspace/libscap/scap_platform_impl.h b/userspace/libscap/scap_platform_impl.h index 7afeac2003..e5929e5662 100644 --- a/userspace/libscap/scap_platform_impl.h +++ b/userspace/libscap/scap_platform_impl.h @@ -40,11 +40,13 @@ struct scap_userlist; struct ppm_proclist_info; // a method table for platform-specific operations -struct scap_platform_vtable -{ +struct scap_platform_vtable { // initialize the platform-specific structure // at this point the engine is fully initialized and operational - int32_t (*init_platform)(struct scap_platform* platform, char* lasterr, struct scap_engine_handle engine, struct scap_open_args* oargs); + int32_t (*init_platform)(struct scap_platform* platform, + char* lasterr, + struct scap_engine_handle engine, + struct scap_open_args* oargs); // refresh the interface list and place it inside // platform->m_addrlist @@ -52,15 +54,24 @@ struct scap_platform_vtable // given a mount id, return the device major:minor // XXX this is Linux-specific - uint32_t (*get_device_by_mount_id)(struct scap_platform*, const char *procdir, unsigned long requested_mount_id); + uint32_t (*get_device_by_mount_id)(struct scap_platform*, + const char* procdir, + unsigned long requested_mount_id); - int32_t (*get_proc)(struct scap_platform*, int64_t tid, struct scap_threadinfo* tinfo, bool scan_sockets); + int32_t (*get_proc)(struct scap_platform*, + int64_t tid, + struct scap_threadinfo* tinfo, + bool scan_sockets); int32_t (*refresh_proc_table)(struct scap_platform*, struct scap_proclist* proclist); bool (*is_thread_alive)(struct scap_platform*, int64_t pid, int64_t tid, const char* comm); - int32_t (*get_global_pid)(struct scap_platform*, int64_t *pid, char *error); - int32_t (*get_threadlist)(struct scap_platform* platform, struct ppm_proclist_info **procinfo_p, char *lasterr); - int32_t (*get_fdlist)(struct scap_platform* platform, struct scap_threadinfo *tinfo, char *lasterr); + int32_t (*get_global_pid)(struct scap_platform*, int64_t* pid, char* error); + int32_t (*get_threadlist)(struct scap_platform* platform, + struct ppm_proclist_info** procinfo_p, + char* lasterr); + int32_t (*get_fdlist)(struct scap_platform* platform, + struct scap_threadinfo* tinfo, + char* lasterr); // close the platform structure // clean up all data, make it ready for another call to `init_platform` @@ -75,11 +86,10 @@ struct scap_platform_vtable // the parts of the platform struct shared across all implementations // this *must* be the first member of all implementations // (the pointers are cast back&forth between the two) -struct scap_platform -{ +struct scap_platform { const struct scap_platform_vtable* m_vtable; - struct scap_addrlist *m_addrlist; - struct scap_userlist *m_userlist; + struct scap_addrlist* m_addrlist; + struct scap_userlist* m_userlist; struct scap_proclist m_proclist; scap_agent_info m_agent_info; diff --git a/userspace/libscap/scap_proc_util.c b/userspace/libscap/scap_proc_util.c index 1a822f6e88..d24703ef1e 100644 --- a/userspace/libscap/scap_proc_util.c +++ b/userspace/libscap/scap_proc_util.c @@ -19,28 +19,35 @@ limitations under the License. #include #include -int32_t scap_proc_scan_vtable(char *error, struct scap_proclist *proclist, uint64_t n_tinfos, const scap_threadinfo *tinfos, void* ctx, get_fdinfos_fn get_fdinfos) -{ +int32_t scap_proc_scan_vtable(char *error, + struct scap_proclist *proclist, + uint64_t n_tinfos, + const scap_threadinfo *tinfos, + void *ctx, + get_fdinfos_fn get_fdinfos) { scap_threadinfo *tinfo; scap_threadinfo new_tinfo; uint32_t res = SCAP_SUCCESS; uint64_t i; - for (i = 0; i < n_tinfos; i++) - { + for(i = 0; i < n_tinfos; i++) { // we need a copy because tinfos is const // note: we drop the copy, so we lose the filtering information (tinfo->filtered_out) - // but that is only ever used when reading captures (and that code does not call this function) + // but that is only ever used when reading captures (and that code does not call this + // function) new_tinfo = tinfos[i]; // // Add the entry to the process table, or fire the notification callback // - proclist->m_proc_callback(proclist->m_proc_callback_context, error, new_tinfo.tid, &new_tinfo, NULL, - &tinfo); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + new_tinfo.tid, + &new_tinfo, + NULL, + &tinfo); - if(tinfo->pid != tinfo->tid) - { + if(tinfo->pid != tinfo->tid) { continue; } @@ -48,17 +55,19 @@ int32_t scap_proc_scan_vtable(char *error, struct scap_proclist *proclist, uint6 const scap_fdinfo *fdinfos; res = (*get_fdinfos)(ctx, &tinfos[i], &n_fdinfos, &fdinfos); - if(res != SCAP_SUCCESS) - { + if(res != SCAP_SUCCESS) { continue; } uint64_t j; - for(j = 0; j < n_fdinfos; j++) - { + for(j = 0; j < n_fdinfos; j++) { scap_fdinfo fdi = fdinfos[j]; - proclist->m_proc_callback(proclist->m_proc_callback_context, error, tinfo->tid, - tinfo, &fdi, NULL); + proclist->m_proc_callback(proclist->m_proc_callback_context, + error, + tinfo->tid, + tinfo, + &fdi, + NULL); } } diff --git a/userspace/libscap/scap_proc_util.h b/userspace/libscap/scap_proc_util.h index 81fdca2e4a..a58a65979c 100644 --- a/userspace/libscap/scap_proc_util.h +++ b/userspace/libscap/scap_proc_util.h @@ -38,10 +38,18 @@ typedef struct scap_threadinfo scap_threadinfo; * @return SCAP_SUCCESS or a failure code * */ -typedef int32_t (*get_fdinfos_fn)(void* ctx, const scap_threadinfo *tinfo, uint64_t *n, const scap_fdinfo **fdinfos); +typedef int32_t (*get_fdinfos_fn)(void *ctx, + const scap_threadinfo *tinfo, + uint64_t *n, + const scap_fdinfo **fdinfos); // Scan process information from engine vtable -int32_t scap_proc_scan_vtable(char *error, struct scap_proclist *proclist, uint64_t n_tinfos, const scap_threadinfo *tinfos, void* ctx, get_fdinfos_fn get_fdinfos); +int32_t scap_proc_scan_vtable(char *error, + struct scap_proclist *proclist, + uint64_t n_tinfos, + const scap_threadinfo *tinfos, + void *ctx, + get_fdinfos_fn get_fdinfos); #ifdef __cplusplus }; diff --git a/userspace/libscap/scap_procs.c b/userspace/libscap/scap_procs.c index 0dfa7731f1..9d032c6b1f 100644 --- a/userspace/libscap/scap_procs.c +++ b/userspace/libscap/scap_procs.c @@ -28,8 +28,7 @@ limitations under the License. // // Delete a process entry // -static void scap_proc_delete(struct scap_proclist* proclist, scap_threadinfo* proc) -{ +static void scap_proc_delete(struct scap_proclist* proclist, scap_threadinfo* proc) { // // First, free the fd table for this process descriptor // @@ -49,50 +48,44 @@ static void scap_proc_delete(struct scap_proclist* proclist, scap_threadinfo* pr // // Free the process table // -void scap_proc_free_table(struct scap_proclist* proclist) -{ +void scap_proc_free_table(struct scap_proclist* proclist) { struct scap_threadinfo* tinfo; struct scap_threadinfo* ttinfo; - HASH_ITER(hh, proclist->m_proclist, tinfo, ttinfo) - { + HASH_ITER(hh, proclist->m_proclist, tinfo, ttinfo) { scap_proc_delete(proclist, tinfo); } } -int32_t scap_fd_add(scap_threadinfo* tinfo, scap_fdinfo* fdinfo) -{ +int32_t scap_fd_add(scap_threadinfo* tinfo, scap_fdinfo* fdinfo) { int32_t uth_status = SCAP_SUCCESS; HASH_ADD_INT64(tinfo->fdlist, fd, fdinfo); - if(uth_status == SCAP_SUCCESS) - { + if(uth_status == SCAP_SUCCESS) { return SCAP_SUCCESS; - } - else - { + } else { return SCAP_FAILURE; } } -int32_t default_proc_entry_callback(void* context, char* error, int64_t tid, scap_threadinfo* tinfo, - scap_fdinfo* fdinfo, scap_threadinfo** new_tinfo) -{ +int32_t default_proc_entry_callback(void* context, + char* error, + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo, + scap_threadinfo** new_tinfo) { struct scap_proclist* proclist = (struct scap_proclist*)context; - if(fdinfo != NULL) - { + if(fdinfo != NULL) { // add an fd // First, find the threadinfo (if not passed by the caller) - if(tinfo == NULL) - { + if(tinfo == NULL) { // // Identify the process descriptor // HASH_FIND_INT64(proclist->m_proclist, &tid, tinfo); - if(tinfo == NULL) - { + if(tinfo == NULL) { // // We have the fdinfo but no associated tid, skip it // @@ -101,46 +94,41 @@ int32_t default_proc_entry_callback(void* context, char* error, int64_t tid, sca } int32_t uth_status = SCAP_SUCCESS; - scap_fdinfo *tfdi; + scap_fdinfo* tfdi; // Make sure this fd doesn't already exist HASH_FIND_INT64(tinfo->fdlist, &(fdinfo->fd), tfdi); - if(tfdi != NULL) - { + if(tfdi != NULL) { // // This can happen if: // - a close() has been dropped when capturing - // - an fd has been closed by clone() or execve() (it happens when the fd is opened with the FD_CLOEXEC flag, + // - an fd has been closed by clone() or execve() (it happens when the fd is opened + // with the FD_CLOEXEC flag, // which we don't currently parse. - // In either case, removing the old fd, replacing it with the new one and keeping going is a reasonable - // choice. + // In either case, removing the old fd, replacing it with the new one and keeping going + // is a reasonable choice. // HASH_DEL(tinfo->fdlist, tfdi); free(tfdi); } - scap_fdinfo *new_fdi = malloc(sizeof(*new_fdi)); - if(new_fdi == NULL) - { + scap_fdinfo* new_fdi = malloc(sizeof(*new_fdi)); + if(new_fdi == NULL) { snprintf(error, SCAP_LASTERR_SIZE, "process table allocation error (1)"); return SCAP_FAILURE; } *new_fdi = *fdinfo; HASH_ADD_INT64(tinfo->fdlist, fd, new_fdi); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { snprintf(error, SCAP_LASTERR_SIZE, "process table allocation error (2)"); return SCAP_FAILURE; } - } - else - { + } else { // add a thread // get a copy of tinfo on the heap - scap_threadinfo *heap_tinfo = malloc(sizeof(*heap_tinfo)); - if(heap_tinfo == NULL) - { + scap_threadinfo* heap_tinfo = malloc(sizeof(*heap_tinfo)); + if(heap_tinfo == NULL) { return scap_errprintf(error, errno, "can't allocate procinfo struct"); } @@ -149,60 +137,53 @@ int32_t default_proc_entry_callback(void* context, char* error, int64_t tid, sca int32_t uth_status = SCAP_SUCCESS; HASH_ADD_INT64(proclist->m_proclist, tid, heap_tinfo); - if(uth_status != SCAP_SUCCESS) - { + if(uth_status != SCAP_SUCCESS) { snprintf(error, SCAP_LASTERR_SIZE, "process table allocation error (2)"); free(heap_tinfo); return SCAP_FAILURE; } - if(new_tinfo) - { + if(new_tinfo) { *new_tinfo = heap_tinfo; } } return SCAP_SUCCESS; } -void init_proclist(struct scap_proclist* proclist, proc_entry_callback callback, void* callback_context) -{ - if(callback == NULL) - { +void init_proclist(struct scap_proclist* proclist, + proc_entry_callback callback, + void* callback_context) { + if(callback == NULL) { proclist->m_proc_callback = default_proc_entry_callback; proclist->m_proc_callback_context = proclist; - } - else - { + } else { proclist->m_proc_callback = callback; proclist->m_proc_callback_context = callback_context; } proclist->m_proclist = NULL; } -bool scap_alloc_proclist_info(struct ppm_proclist_info **proclist_p, uint32_t n_entries, char* error) -{ +bool scap_alloc_proclist_info(struct ppm_proclist_info** proclist_p, + uint32_t n_entries, + char* error) { uint32_t memsize; - if(n_entries >= SCAP_DRIVER_PROCINFO_MAX_SIZE) - { + if(n_entries >= SCAP_DRIVER_PROCINFO_MAX_SIZE) { snprintf(error, SCAP_LASTERR_SIZE, "driver process list too big"); return false; } - memsize = sizeof(struct ppm_proclist_info) + - sizeof(struct ppm_proc_info) * n_entries; + memsize = sizeof(struct ppm_proclist_info) + sizeof(struct ppm_proc_info) * n_entries; - struct ppm_proclist_info *procinfo = (struct ppm_proclist_info*) realloc(*proclist_p, memsize); - if(procinfo == NULL) - { + struct ppm_proclist_info* procinfo = (struct ppm_proclist_info*)realloc(*proclist_p, memsize); + if(procinfo == NULL) { free(*proclist_p); *proclist_p = NULL; snprintf(error, SCAP_LASTERR_SIZE, "driver process list allocation error"); return false; } - if(*proclist_p == NULL) - { + if(*proclist_p == NULL) { procinfo->n_entries = 0; } @@ -212,7 +193,6 @@ bool scap_alloc_proclist_info(struct ppm_proclist_info **proclist_p, uint32_t n_ return true; } -void scap_free_proclist_info(struct ppm_proclist_info *proclist) -{ +void scap_free_proclist_info(struct ppm_proclist_info* proclist) { free(proclist); } diff --git a/userspace/libscap/scap_procs.h b/userspace/libscap/scap_procs.h index ce0bbc8a13..d27a3e8160 100644 --- a/userspace/libscap/scap_procs.h +++ b/userspace/libscap/scap_procs.h @@ -34,32 +34,43 @@ typedef struct scap_fdinfo scap_fdinfo; @param tid: the thread id @param tinfo: the thread info @param fdinfo: the fd info, if any (NULL if adding a thread) - @param new_tinfo: a pointer to a thread info pointer. If the callback returns a different thread info, + @param new_tinfo: a pointer to a thread info pointer. If the callback returns a different thread + info, @return SCAP_* status code - *Note*: currently tinfo may be NULL if fdinfo is not NULL. This makes life harder for fd callbacks. + *Note*: currently tinfo may be NULL if fdinfo is not NULL. This makes life harder for fd + callbacks. Memory ownership rule: tinfo and fdinfo are owned by the caller and must not be freed or stored - by the callback. The callback can return a different tinfo, which must not be freed or stored by the caller, - but can be assumed to be valid at least until the next call to the callback. + by the callback. The callback can return a different tinfo, which must not be freed or stored by + the caller, but can be assumed to be valid at least until the next call to the callback. */ -typedef int32_t (*proc_entry_callback)(void* context, char* error, int64_t tid, scap_threadinfo* tinfo, - scap_fdinfo* fdinfo, scap_threadinfo** new_tinfo); - -int32_t default_proc_entry_callback(void* context, char* error, int64_t tid, scap_threadinfo* tinfo, - scap_fdinfo* fdinfo, scap_threadinfo** new_tinfo); - -struct scap_proclist -{ +typedef int32_t (*proc_entry_callback)(void* context, + char* error, + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo, + scap_threadinfo** new_tinfo); + +int32_t default_proc_entry_callback(void* context, + char* error, + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo, + scap_threadinfo** new_tinfo); + +struct scap_proclist { proc_entry_callback m_proc_callback; void* m_proc_callback_context; scap_threadinfo* m_proclist; }; -void init_proclist(struct scap_proclist* proclist, proc_entry_callback callback, void* callback_context); +void init_proclist(struct scap_proclist* proclist, + proc_entry_callback callback, + void* callback_context); #ifdef __cplusplus } diff --git a/userspace/libscap/scap_savefile.c b/userspace/libscap/scap_savefile.c index 5e73a031db..6b0ee55bfd 100644 --- a/userspace/libscap/scap_savefile.c +++ b/userspace/libscap/scap_savefile.c @@ -16,7 +16,6 @@ limitations under the License. */ - #include #include @@ -25,8 +24,8 @@ limitations under the License. #include #else struct iovec { - void *iov_base; /* Starting address */ - size_t iov_len; /* Number of bytes to transfer */ + void *iov_base; /* Starting address */ + size_t iov_len; /* Number of bytes to transfer */ }; #endif @@ -37,8 +36,7 @@ struct iovec { #include #include -const char* scap_dump_getlasterr(scap_dumper_t* d) -{ +const char *scap_dump_getlasterr(scap_dumper_t *d) { return d ? d->m_lasterr : "null dumper"; } @@ -51,29 +49,21 @@ const char* scap_dump_getlasterr(scap_dumper_t* d) // // Write data into a dump file // -static int scap_dump_write(scap_dumper_t *d, void* buf, unsigned len) -{ - if(d->m_type == DT_FILE) - { +static int scap_dump_write(scap_dumper_t *d, void *buf, unsigned len) { + if(d->m_type == DT_FILE) { return gzwrite(d->m_f, buf, len); - } - else - { - if(d->m_targetbufcurpos + len >= d->m_targetbufend) - { - if(d->m_type == DT_MEM) - { + } else { + if(d->m_targetbufcurpos + len >= d->m_targetbufend) { + if(d->m_type == DT_MEM) { return -1; } // DT_MANAGED_BUF, try to increase the size - size_t targetbufsize = PPM_DUMPER_MANAGED_BUF_RESIZE_FACTOR * (d->m_targetbufend - d->m_targetbuf); + size_t targetbufsize = + PPM_DUMPER_MANAGED_BUF_RESIZE_FACTOR * (d->m_targetbufend - d->m_targetbuf); - uint8_t *targetbuf = (uint8_t *)realloc( - d->m_targetbuf, - targetbufsize); - if(targetbuf == NULL) - { + uint8_t *targetbuf = (uint8_t *)realloc(d->m_targetbuf, targetbufsize); + if(targetbuf == NULL) { free(d->m_targetbuf); return -1; } @@ -91,15 +81,12 @@ static int scap_dump_write(scap_dumper_t *d, void* buf, unsigned len) } } -static int scap_dump_writev(scap_dumper_t *d, const struct iovec *iov, int iovcnt) -{ +static int scap_dump_writev(scap_dumper_t *d, const struct iovec *iov, int iovcnt) { unsigned totlen = 0; int i; - for (i = 0; i < iovcnt; i++) - { - if(scap_dump_write(d, iov[i].iov_base, iov[i].iov_len) < 0) - { + for(i = 0; i < iovcnt; i++) { + if(scap_dump_write(d, iov[i].iov_base, iov[i].iov_len) < 0) { return -1; } @@ -109,8 +96,7 @@ static int scap_dump_writev(scap_dumper_t *d, const struct iovec *iov, int iovcn return totlen; } -uint8_t* scap_get_memorydumper_curpos(scap_dumper_t *d) -{ +uint8_t *scap_get_memorydumper_curpos(scap_dumper_t *d) { return d->m_targetbufcurpos; } @@ -123,17 +109,13 @@ static uint32_t scap_normalize_block_len(uint32_t blocklen) return ((blocklen + 3) >> 2) << 2; } -static int32_t scap_write_padding(scap_dumper_t *d, uint32_t blocklen) -{ +static int32_t scap_write_padding(scap_dumper_t *d, uint32_t blocklen) { int32_t val = 0; uint32_t bytestowrite = scap_normalize_block_len(blocklen) - blocklen; - if(scap_dump_write(d, &val, bytestowrite) == bytestowrite) - { + if(scap_dump_write(d, &val, bytestowrite) == bytestowrite) { return SCAP_SUCCESS; - } - else - { + } else { return SCAP_FAILURE; } } @@ -141,50 +123,47 @@ static int32_t scap_write_padding(scap_dumper_t *d, uint32_t blocklen) // // Calculate the length on disk of an fd entry's info // -static uint32_t scap_fd_info_len(scap_fdinfo *fdi) -{ +static uint32_t scap_fd_info_len(scap_fdinfo *fdi) { // // NB: new fields must be appended // uint32_t res = sizeof(uint32_t) + sizeof(fdi->ino) + 1 + sizeof(fdi->fd); - switch(fdi->type) - { + switch(fdi->type) { case SCAP_FD_IPV4_SOCK: - res += 4 + // sip - 4 + // dip - 2 + // sport - 2 + // dport - 1; // l4proto + res += 4 + // sip + 4 + // dip + 2 + // sport + 2 + // dport + 1; // l4proto break; case SCAP_FD_IPV4_SERVSOCK: - res += 4 + // ip - 2 + // port - 1; // l4proto + res += 4 + // ip + 2 + // port + 1; // l4proto break; case SCAP_FD_IPV6_SOCK: - res += sizeof(uint32_t) * 4 + // sip - sizeof(uint32_t) * 4 + // dip - sizeof(uint16_t) + // sport - sizeof(uint16_t) + // dport - sizeof(uint8_t); // l4proto + res += sizeof(uint32_t) * 4 + // sip + sizeof(uint32_t) * 4 + // dip + sizeof(uint16_t) + // sport + sizeof(uint16_t) + // dport + sizeof(uint8_t); // l4proto break; case SCAP_FD_IPV6_SERVSOCK: - res += sizeof(uint32_t) * 4 + // ip - sizeof(uint16_t) + // port - sizeof(uint8_t); // l4proto + res += sizeof(uint32_t) * 4 + // ip + sizeof(uint16_t) + // port + sizeof(uint8_t); // l4proto break; case SCAP_FD_UNIX_SOCK: - res += - sizeof(uint64_t) + // unix source - sizeof(uint64_t) + // unix destination - (uint32_t)strnlen(fdi->info.unix_socket_info.fname, SCAP_MAX_PATH_SIZE) + 2; + res += sizeof(uint64_t) + // unix source + sizeof(uint64_t) + // unix destination + (uint32_t)strnlen(fdi->info.unix_socket_info.fname, SCAP_MAX_PATH_SIZE) + 2; break; case SCAP_FD_FILE_V2: - res += sizeof(uint32_t) + // open_flags - (uint32_t)strnlen(fdi->info.regularinfo.fname, SCAP_MAX_PATH_SIZE) + 2 + - sizeof(uint32_t); // dev + res += sizeof(uint32_t) + // open_flags + (uint32_t)strnlen(fdi->info.regularinfo.fname, SCAP_MAX_PATH_SIZE) + 2 + + sizeof(uint32_t); // dev break; case SCAP_FD_FIFO: case SCAP_FD_FILE: @@ -201,7 +180,8 @@ static uint32_t scap_fd_info_len(scap_fdinfo *fdi) case SCAP_FD_IOURING: case SCAP_FD_MEMFD: case SCAP_FD_PIDFD: - res += (uint32_t)strnlen(fdi->info.fname, SCAP_MAX_PATH_SIZE) + 2; // 2 is the length field before the string + res += (uint32_t)strnlen(fdi->info.fname, SCAP_MAX_PATH_SIZE) + + 2; // 2 is the length field before the string break; default: ASSERT(false); @@ -214,90 +194,88 @@ static uint32_t scap_fd_info_len(scap_fdinfo *fdi) // // Write the given fd info to disk // -static int32_t scap_fd_write_to_disk(scap_dumper_t *d, scap_fdinfo *fdi, uint32_t len) -{ - +static int32_t scap_fd_write_to_disk(scap_dumper_t *d, scap_fdinfo *fdi, uint32_t len) { uint8_t type = (uint8_t)fdi->type; uint16_t stlen; if(scap_dump_write(d, &(len), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(fdi->fd), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(fdi->ino), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(type), sizeof(uint8_t)) != sizeof(uint8_t)) - { + scap_dump_write(d, &(fdi->fd), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(fdi->ino), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(type), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi1)"); return SCAP_FAILURE; } - switch(fdi->type) - { + switch(fdi->type) { case SCAP_FD_IPV4_SOCK: if(scap_dump_write(d, &(fdi->info.ipv4info.sip), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(fdi->info.ipv4info.dip), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(fdi->info.ipv4info.sport), sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, &(fdi->info.ipv4info.dport), sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, &(fdi->info.ipv4info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + scap_dump_write(d, &(fdi->info.ipv4info.dip), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(fdi->info.ipv4info.sport), sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, &(fdi->info.ipv4info.dport), sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, &(fdi->info.ipv4info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi2)"); return SCAP_FAILURE; } break; case SCAP_FD_IPV4_SERVSOCK: - if(scap_dump_write(d, &(fdi->info.ipv4serverinfo.ip), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(fdi->info.ipv4serverinfo.port), sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, &(fdi->info.ipv4serverinfo.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + if(scap_dump_write(d, &(fdi->info.ipv4serverinfo.ip), sizeof(uint32_t)) != + sizeof(uint32_t) || + scap_dump_write(d, &(fdi->info.ipv4serverinfo.port), sizeof(uint16_t)) != + sizeof(uint16_t) || + scap_dump_write(d, &(fdi->info.ipv4serverinfo.l4proto), sizeof(uint8_t)) != + sizeof(uint8_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi3)"); return SCAP_FAILURE; } break; case SCAP_FD_IPV6_SOCK: - if(scap_dump_write(d, (char*)fdi->info.ipv6info.sip, sizeof(uint32_t) * 4) != sizeof(uint32_t) * 4 || - scap_dump_write(d, (char*)fdi->info.ipv6info.dip, sizeof(uint32_t) * 4) != sizeof(uint32_t) * 4 || - scap_dump_write(d, &(fdi->info.ipv6info.sport), sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, &(fdi->info.ipv6info.dport), sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, &(fdi->info.ipv6info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + if(scap_dump_write(d, (char *)fdi->info.ipv6info.sip, sizeof(uint32_t) * 4) != + sizeof(uint32_t) * 4 || + scap_dump_write(d, (char *)fdi->info.ipv6info.dip, sizeof(uint32_t) * 4) != + sizeof(uint32_t) * 4 || + scap_dump_write(d, &(fdi->info.ipv6info.sport), sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, &(fdi->info.ipv6info.dport), sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, &(fdi->info.ipv6info.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi7)"); } break; case SCAP_FD_IPV6_SERVSOCK: - if(scap_dump_write(d, &(fdi->info.ipv6serverinfo.ip), sizeof(uint32_t) * 4) != sizeof(uint32_t) * 4 || - scap_dump_write(d, &(fdi->info.ipv6serverinfo.port), sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, &(fdi->info.ipv6serverinfo.l4proto), sizeof(uint8_t)) != sizeof(uint8_t)) - { + if(scap_dump_write(d, &(fdi->info.ipv6serverinfo.ip), sizeof(uint32_t) * 4) != + sizeof(uint32_t) * 4 || + scap_dump_write(d, &(fdi->info.ipv6serverinfo.port), sizeof(uint16_t)) != + sizeof(uint16_t) || + scap_dump_write(d, &(fdi->info.ipv6serverinfo.l4proto), sizeof(uint8_t)) != + sizeof(uint8_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi8)"); } break; case SCAP_FD_UNIX_SOCK: - if(scap_dump_write(d, &(fdi->info.unix_socket_info.source), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(fdi->info.unix_socket_info.destination), sizeof(uint64_t)) != sizeof(uint64_t)) - { + if(scap_dump_write(d, &(fdi->info.unix_socket_info.source), sizeof(uint64_t)) != + sizeof(uint64_t) || + scap_dump_write(d, &(fdi->info.unix_socket_info.destination), sizeof(uint64_t)) != + sizeof(uint64_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi4)"); return SCAP_FAILURE; } stlen = (uint16_t)strnlen(fdi->info.unix_socket_info.fname, SCAP_MAX_PATH_SIZE); if(scap_dump_write(d, &stlen, sizeof(uint16_t)) != sizeof(uint16_t) || - (stlen > 0 && scap_dump_write(d, fdi->info.unix_socket_info.fname, stlen) != stlen)) - { + (stlen > 0 && scap_dump_write(d, fdi->info.unix_socket_info.fname, stlen) != stlen)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi5)"); return SCAP_FAILURE; } break; case SCAP_FD_FILE_V2: - if(scap_dump_write(d, &(fdi->info.regularinfo.open_flags), sizeof(uint32_t)) != sizeof(uint32_t)) - { + if(scap_dump_write(d, &(fdi->info.regularinfo.open_flags), sizeof(uint32_t)) != + sizeof(uint32_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi1)"); return SCAP_FAILURE; } stlen = (uint16_t)strnlen(fdi->info.regularinfo.fname, SCAP_MAX_PATH_SIZE); if(scap_dump_write(d, &stlen, sizeof(uint16_t)) != sizeof(uint16_t) || - (stlen > 0 && scap_dump_write(d, fdi->info.regularinfo.fname, stlen) != stlen)) - { + (stlen > 0 && scap_dump_write(d, fdi->info.regularinfo.fname, stlen) != stlen)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi1)"); return SCAP_FAILURE; } - if(scap_dump_write(d, &(fdi->info.regularinfo.dev), sizeof(uint32_t)) != sizeof(uint32_t)) - { + if(scap_dump_write(d, &(fdi->info.regularinfo.dev), sizeof(uint32_t)) != sizeof(uint32_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (dev)"); return SCAP_FAILURE; } @@ -318,9 +296,8 @@ static int32_t scap_fd_write_to_disk(scap_dumper_t *d, scap_fdinfo *fdi, uint32_ case SCAP_FD_MEMFD: case SCAP_FD_PIDFD: stlen = (uint16_t)strnlen(fdi->info.fname, SCAP_MAX_PATH_SIZE); - if(scap_dump_write(d, &stlen, sizeof(uint16_t)) != sizeof(uint16_t) || - (stlen > 0 && scap_dump_write(d, fdi->info.fname, stlen) != stlen)) - { + if(scap_dump_write(d, &stlen, sizeof(uint16_t)) != sizeof(uint16_t) || + (stlen > 0 && scap_dump_write(d, fdi->info.fname, stlen) != stlen)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fi6)"); return SCAP_FAILURE; } @@ -338,8 +315,7 @@ static int32_t scap_fd_write_to_disk(scap_dumper_t *d, scap_fdinfo *fdi, uint32_ return SCAP_SUCCESS; } -int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) -{ +int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) { block_header bh; uint32_t bt; uint32_t totlen = sizeof(tinfo->tid); // This includes the tid @@ -347,9 +323,8 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) struct scap_fdinfo *fdi; struct scap_fdinfo *tfdi; - uint32_t* lengths = calloc(HASH_COUNT(tinfo->fdlist), sizeof(uint32_t)); - if(lengths == NULL) - { + uint32_t *lengths = calloc(HASH_COUNT(tinfo->fdlist), sizeof(uint32_t)); + if(lengths == NULL) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "scap_write_proc_fds memory allocation failure"); return SCAP_FAILURE; } @@ -357,11 +332,8 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) // // First pass of the table to calculate the lengths // - HASH_ITER(hh, tinfo->fdlist, fdi, tfdi) - { - if(fdi->type != SCAP_FD_UNINITIALIZED && - fdi->type != SCAP_FD_UNKNOWN) - { + HASH_ITER(hh, tinfo->fdlist, fdi, tfdi) { + if(fdi->type != SCAP_FD_UNINITIALIZED && fdi->type != SCAP_FD_UNKNOWN) { uint32_t fl = scap_fd_info_len(fdi); lengths[idx++] = fl; totlen += fl; @@ -375,8 +347,7 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) bh.block_type = FDL_BLOCK_TYPE_V2; bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + totlen + 4); - if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) - { + if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) { free(lengths); snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd1)"); return SCAP_FAILURE; @@ -385,8 +356,7 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) // // Write the tid // - if(scap_dump_write(d, &tinfo->tid, sizeof(tinfo->tid)) != sizeof(tinfo->tid)) - { + if(scap_dump_write(d, &tinfo->tid, sizeof(tinfo->tid)) != sizeof(tinfo->tid)) { free(lengths); snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd2)"); return SCAP_FAILURE; @@ -395,12 +365,9 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) // // Second pass of the table to dump it // - HASH_ITER(hh, tinfo->fdlist, fdi, tfdi) - { - if(fdi->type != SCAP_FD_UNINITIALIZED && fdi->type != SCAP_FD_UNKNOWN) - { - if(scap_fd_write_to_disk(d, fdi, lengths[idx++]) != SCAP_SUCCESS) - { + HASH_ITER(hh, tinfo->fdlist, fdi, tfdi) { + if(fdi->type != SCAP_FD_UNINITIALIZED && fdi->type != SCAP_FD_UNKNOWN) { + if(scap_fd_write_to_disk(d, fdi, lengths[idx++]) != SCAP_SUCCESS) { free(lengths); return SCAP_FAILURE; } @@ -412,8 +379,7 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) // // Add the padding // - if(scap_write_padding(d, totlen) != SCAP_SUCCESS) - { + if(scap_write_padding(d, totlen) != SCAP_SUCCESS) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd3)"); return SCAP_FAILURE; } @@ -422,8 +388,7 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) // Create the trailer // bt = bh.block_total_length; - if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (fd4)"); return SCAP_FAILURE; } @@ -434,19 +399,15 @@ int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo) // // Write the fd list blocks // -static int32_t scap_write_fdlist(scap_dumper_t *d, struct scap_proclist *proclist) -{ +static int32_t scap_write_fdlist(scap_dumper_t *d, struct scap_proclist *proclist) { struct scap_threadinfo *tinfo; struct scap_threadinfo *ttinfo; int32_t res; - HASH_ITER(hh, proclist->m_proclist, tinfo, ttinfo) - { - if(!tinfo->filtered_out) - { + HASH_ITER(hh, proclist->m_proclist, tinfo, ttinfo) { + if(!tinfo->filtered_out) { res = scap_write_proc_fds(d, tinfo); - if(res != SCAP_SUCCESS) - { + if(res != SCAP_SUCCESS) { return res; } } @@ -460,16 +421,14 @@ static int32_t scap_write_fdlist(scap_dumper_t *d, struct scap_proclist *proclis // time window and write everything at once with a secondary dumper. // By doing so, the likelihood of having a wrong total length is lower. // -scap_dumper_t *scap_write_proclist_begin() -{ +scap_dumper_t *scap_write_proclist_begin() { return scap_managedbuf_dump_create(); } // // Write the process list block // -static int32_t scap_write_proclist_header(scap_dumper_t *d, uint32_t totlen) -{ +static int32_t scap_write_proclist_header(scap_dumper_t *d, uint32_t totlen) { block_header bh; // @@ -478,8 +437,7 @@ static int32_t scap_write_proclist_header(scap_dumper_t *d, uint32_t totlen) bh.block_type = PL_BLOCK_TYPE_V9; bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + totlen + 4); - if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) - { + if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (1)"); return SCAP_FAILURE; } @@ -490,8 +448,7 @@ static int32_t scap_write_proclist_header(scap_dumper_t *d, uint32_t totlen) // // Write the process list block // -static int32_t scap_write_proclist_trailer(scap_dumper_t *d, uint32_t totlen) -{ +static int32_t scap_write_proclist_trailer(scap_dumper_t *d, uint32_t totlen) { block_header bh; uint32_t bt; @@ -501,8 +458,7 @@ static int32_t scap_write_proclist_trailer(scap_dumper_t *d, uint32_t totlen) // // Blocks need to be 4-byte padded // - if(scap_write_padding(d, totlen) != SCAP_SUCCESS) - { + if(scap_write_padding(d, totlen) != SCAP_SUCCESS) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (3)"); return SCAP_FAILURE; } @@ -511,8 +467,7 @@ static int32_t scap_write_proclist_trailer(scap_dumper_t *d, uint32_t totlen) // Create the trailer // bt = bh.block_total_length; - if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (4)"); return SCAP_FAILURE; } @@ -520,29 +475,24 @@ static int32_t scap_write_proclist_trailer(scap_dumper_t *d, uint32_t totlen) return SCAP_SUCCESS; } -int scap_write_proclist_end(scap_dumper_t *d, scap_dumper_t *proclist_dumper, uint32_t totlen) -{ +int scap_write_proclist_end(scap_dumper_t *d, scap_dumper_t *proclist_dumper, uint32_t totlen) { ASSERT(proclist_dumper != NULL); ASSERT(proclist_dumper->m_type == DT_MANAGED_BUF); int res = SCAP_SUCCESS; - do - { + do { scap_dump_flush(proclist_dumper); - if(scap_write_proclist_header(d, totlen) != SCAP_SUCCESS) - { + if(scap_write_proclist_header(d, totlen) != SCAP_SUCCESS) { res = SCAP_FAILURE; break; } - if(scap_dump_write(d, proclist_dumper->m_targetbuf, totlen) <= 0) - { + if(scap_dump_write(d, proclist_dumper->m_targetbuf, totlen) <= 0) { res = SCAP_FAILURE; break; } - if(scap_write_proclist_trailer(d, totlen) != SCAP_SUCCESS) - { + if(scap_write_proclist_trailer(d, totlen) != SCAP_SUCCESS) { res = SCAP_FAILURE; break; } @@ -556,46 +506,54 @@ int scap_write_proclist_end(scap_dumper_t *d, scap_dumper_t *proclist_dumper, ui // // Write the process list block // -static int32_t scap_write_proclist_entry(scap_dumper_t *d, struct scap_threadinfo *tinfo, uint32_t *len) -{ +static int32_t scap_write_proclist_entry(scap_dumper_t *d, + struct scap_threadinfo *tinfo, + uint32_t *len) { struct iovec args = {tinfo->args, tinfo->args_len}; struct iovec env = {tinfo->env, tinfo->env_len}; struct iovec cgroups = {tinfo->cgroups.path, tinfo->cgroups.len}; - return scap_write_proclist_entry_bufs(d, tinfo, len, - tinfo->comm, - tinfo->exe, - tinfo->exepath, - &args, 1, - &env, 1, - tinfo->cwd, - &cgroups, 1, - tinfo->root); + return scap_write_proclist_entry_bufs(d, + tinfo, + len, + tinfo->comm, + tinfo->exe, + tinfo->exepath, + &args, + 1, + &env, + 1, + tinfo->cwd, + &cgroups, + 1, + tinfo->root); } -static uint16_t iov_size(const struct iovec *iov, uint32_t iovcnt) -{ +static uint16_t iov_size(const struct iovec *iov, uint32_t iovcnt) { uint16_t len = 0; uint32_t i; - for (i = 0; i < iovcnt; i++) - { + for(i = 0; i < iovcnt; i++) { len += iov[i].iov_len; } return len; } -int32_t scap_write_proclist_entry_bufs(scap_dumper_t *d, struct scap_threadinfo *tinfo, uint32_t *len, - const char *comm, - const char *exe, - const char *exepath, - const struct iovec *args, int argscnt, - const struct iovec *envs, int envscnt, - const char *cwd, - const struct iovec *cgroups, int cgroupscnt, - const char *root) -{ +int32_t scap_write_proclist_entry_bufs(scap_dumper_t *d, + struct scap_threadinfo *tinfo, + uint32_t *len, + const char *comm, + const char *exe, + const char *exepath, + const struct iovec *args, + int argscnt, + const struct iovec *envs, + int envscnt, + const char *cwd, + const struct iovec *cgroups, + int cgroupscnt, + const char *root) { uint16_t commlen; uint16_t exelen; uint16_t exepathlen; @@ -618,92 +576,84 @@ int32_t scap_write_proclist_entry_bufs(scap_dumper_t *d, struct scap_threadinfo // // NB: new fields must be appended // - *len = (uint32_t)(sizeof(uint32_t) + // len - sizeof(uint64_t) + // tid - sizeof(uint64_t) + // pid - sizeof(uint64_t) + // ptid - sizeof(uint64_t) + // sid - sizeof(uint64_t) + // vpgid - 2 + commlen + - 2 + exelen + - 2 + exepathlen + - 2 + argslen + - 2 + cwdlen + - sizeof(uint64_t) + // fdlimit - sizeof(uint32_t) + // flags - sizeof(uint32_t) + // uid - sizeof(uint32_t) + // gid - sizeof(uint32_t) + // vmsize_kb - sizeof(uint32_t) + // vmrss_kb - sizeof(uint32_t) + // vmswap_kb - sizeof(uint64_t) + // pfmajor - sizeof(uint64_t) + // pfminor - 2 + envlen + - sizeof(int64_t) + // vtid - sizeof(int64_t) + // vpid - 2 + cgroupslen + - 2 + rootlen + - sizeof(uint64_t) + // pidns_init_start_ts - sizeof(uint32_t) + // tty - sizeof(uint32_t) + // loginuid (auid) - sizeof(uint8_t) + // exe_writable - sizeof(uint64_t) + // cap_inheritable - sizeof(uint64_t) + // cap_permitted - sizeof(uint64_t) + // cap_effective - sizeof(uint8_t) + // exe_upper_layer - sizeof(uint64_t) + // exe_ino - sizeof(uint64_t) + // exe_ino_ctime - sizeof(uint64_t) + // exe_ino_mtime - sizeof(uint8_t) + // exe_from_memfd - sizeof(uint8_t)); // exe_lower_layer + *len = (uint32_t)(sizeof(uint32_t) + // len + sizeof(uint64_t) + // tid + sizeof(uint64_t) + // pid + sizeof(uint64_t) + // ptid + sizeof(uint64_t) + // sid + sizeof(uint64_t) + // vpgid + 2 + commlen + 2 + exelen + 2 + exepathlen + 2 + argslen + 2 + cwdlen + + sizeof(uint64_t) + // fdlimit + sizeof(uint32_t) + // flags + sizeof(uint32_t) + // uid + sizeof(uint32_t) + // gid + sizeof(uint32_t) + // vmsize_kb + sizeof(uint32_t) + // vmrss_kb + sizeof(uint32_t) + // vmswap_kb + sizeof(uint64_t) + // pfmajor + sizeof(uint64_t) + // pfminor + 2 + envlen + sizeof(int64_t) + // vtid + sizeof(int64_t) + // vpid + 2 + cgroupslen + 2 + rootlen + sizeof(uint64_t) + // pidns_init_start_ts + sizeof(uint32_t) + // tty + sizeof(uint32_t) + // loginuid (auid) + sizeof(uint8_t) + // exe_writable + sizeof(uint64_t) + // cap_inheritable + sizeof(uint64_t) + // cap_permitted + sizeof(uint64_t) + // cap_effective + sizeof(uint8_t) + // exe_upper_layer + sizeof(uint64_t) + // exe_ino + sizeof(uint64_t) + // exe_ino_ctime + sizeof(uint64_t) + // exe_ino_mtime + sizeof(uint8_t) + // exe_from_memfd + sizeof(uint8_t)); // exe_lower_layer if(scap_dump_write(d, len, sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->tid), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->pid), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->ptid), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->sid), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->vpgid), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &commlen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, (char *) comm, commlen) != commlen || - scap_dump_write(d, &exelen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, (char *) exe, exelen) != exelen || - scap_dump_write(d, &exepathlen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, (char *) exepath, exepathlen) != exepathlen || - scap_dump_write(d, &argslen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_writev(d, args, argscnt) != argslen || - scap_dump_write(d, &cwdlen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, (char *) cwd, cwdlen) != cwdlen || - scap_dump_write(d, &(tinfo->fdlimit), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->flags), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->uid), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->gid), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->vmsize_kb), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->vmrss_kb), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->vmswap_kb), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->pfmajor), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->pfminor), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &envlen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_writev(d, envs, envscnt) != envlen || - scap_dump_write(d, &(tinfo->vtid), sizeof(int64_t)) != sizeof(int64_t) || - scap_dump_write(d, &(tinfo->vpid), sizeof(int64_t)) != sizeof(int64_t) || - scap_dump_write(d, &(cgroupslen), sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_writev(d, cgroups, cgroupscnt) != cgroupslen || - scap_dump_write(d, &rootlen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, (char *) root, rootlen) != rootlen || - scap_dump_write(d, &(tinfo->pidns_init_start_ts), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->tty), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->loginuid), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(tinfo->exe_writable), sizeof(uint8_t)) != sizeof(uint8_t) || - scap_dump_write(d, &(tinfo->cap_inheritable), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->cap_permitted), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->cap_effective), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->exe_upper_layer), sizeof(uint8_t)) != sizeof(uint8_t) || - scap_dump_write(d, &(tinfo->exe_ino), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->exe_ino_ctime), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->exe_ino_mtime), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(tinfo->exe_from_memfd), sizeof(uint8_t)) != sizeof(uint8_t) || - scap_dump_write(d, &(tinfo->exe_lower_layer), sizeof(uint8_t)) != sizeof(uint8_t)) - { + scap_dump_write(d, &(tinfo->tid), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->pid), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->ptid), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->sid), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->vpgid), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &commlen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, (char *)comm, commlen) != commlen || + scap_dump_write(d, &exelen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, (char *)exe, exelen) != exelen || + scap_dump_write(d, &exepathlen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, (char *)exepath, exepathlen) != exepathlen || + scap_dump_write(d, &argslen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_writev(d, args, argscnt) != argslen || + scap_dump_write(d, &cwdlen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, (char *)cwd, cwdlen) != cwdlen || + scap_dump_write(d, &(tinfo->fdlimit), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->flags), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->uid), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->gid), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->vmsize_kb), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->vmrss_kb), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->vmswap_kb), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->pfmajor), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->pfminor), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &envlen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_writev(d, envs, envscnt) != envlen || + scap_dump_write(d, &(tinfo->vtid), sizeof(int64_t)) != sizeof(int64_t) || + scap_dump_write(d, &(tinfo->vpid), sizeof(int64_t)) != sizeof(int64_t) || + scap_dump_write(d, &(cgroupslen), sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_writev(d, cgroups, cgroupscnt) != cgroupslen || + scap_dump_write(d, &rootlen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, (char *)root, rootlen) != rootlen || + scap_dump_write(d, &(tinfo->pidns_init_start_ts), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->tty), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->loginuid), sizeof(uint32_t)) != sizeof(uint32_t) || + scap_dump_write(d, &(tinfo->exe_writable), sizeof(uint8_t)) != sizeof(uint8_t) || + scap_dump_write(d, &(tinfo->cap_inheritable), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->cap_permitted), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->cap_effective), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->exe_upper_layer), sizeof(uint8_t)) != sizeof(uint8_t) || + scap_dump_write(d, &(tinfo->exe_ino), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->exe_ino_ctime), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->exe_ino_mtime), sizeof(uint64_t)) != sizeof(uint64_t) || + scap_dump_write(d, &(tinfo->exe_from_memfd), sizeof(uint8_t)) != sizeof(uint8_t) || + scap_dump_write(d, &(tinfo->exe_lower_layer), sizeof(uint8_t)) != sizeof(uint8_t)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (2)"); return SCAP_FAILURE; } @@ -714,36 +664,29 @@ int32_t scap_write_proclist_entry_bufs(scap_dumper_t *d, struct scap_threadinfo // // Write the process list block // -static int32_t scap_write_proclist(scap_dumper_t *d, struct scap_proclist *proclist) -{ +static int32_t scap_write_proclist(scap_dumper_t *d, struct scap_proclist *proclist) { // // Exit immediately if the process list is empty // - if(HASH_COUNT(proclist->m_proclist) == 0) - { + if(HASH_COUNT(proclist->m_proclist) == 0) { return SCAP_SUCCESS; } scap_dumper_t *proclist_dumper = scap_write_proclist_begin(); - if(proclist_dumper == NULL) - { + if(proclist_dumper == NULL) { return SCAP_FAILURE; } - uint32_t totlen = 0; struct scap_threadinfo *tinfo; struct scap_threadinfo *ttinfo; - HASH_ITER(hh, proclist->m_proclist, tinfo, ttinfo) - { - if(tinfo->filtered_out) - { + HASH_ITER(hh, proclist->m_proclist, tinfo, ttinfo) { + if(tinfo->filtered_out) { continue; } uint32_t len = 0; - if(scap_write_proclist_entry(proclist_dumper, tinfo, &len) != SCAP_SUCCESS) - { + if(scap_write_proclist_entry(proclist_dumper, tinfo, &len) != SCAP_SUCCESS) { scap_dump_close(proclist_dumper); return SCAP_FAILURE; } @@ -757,8 +700,7 @@ static int32_t scap_write_proclist(scap_dumper_t *d, struct scap_proclist *procl // // Write the machine info block // -static int32_t scap_write_machine_info(scap_dumper_t *d, scap_machine_info *machine_info) -{ +static int32_t scap_write_machine_info(scap_dumper_t *d, scap_machine_info *machine_info) { block_header bh; uint32_t bt; @@ -766,14 +708,14 @@ static int32_t scap_write_machine_info(scap_dumper_t *d, scap_machine_info *mach // Write the section header // bh.block_type = MI_BLOCK_TYPE; - bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + sizeof(scap_machine_info) + 4); + bh.block_total_length = + scap_normalize_block_len(sizeof(block_header) + sizeof(scap_machine_info) + 4); bt = bh.block_total_length; if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) || - scap_dump_write(d, machine_info, sizeof(*machine_info)) != sizeof(*machine_info) || - scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + scap_dump_write(d, machine_info, sizeof(*machine_info)) != sizeof(*machine_info) || + scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (MI1)"); return SCAP_FAILURE; } @@ -784,8 +726,7 @@ static int32_t scap_write_machine_info(scap_dumper_t *d, scap_machine_info *mach // // Write the interface list block // -static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) -{ +static int32_t scap_write_iflist(scap_dumper_t *d, scap_addrlist *addrlist) { block_header bh; uint32_t bt; uint32_t entrylen; @@ -795,10 +736,10 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) // // Get the interface list // - if(addrlist == NULL) - { + if(addrlist == NULL) { // - // This can happen when the event source is a capture that was generated by a plugin, no big deal + // This can happen when the event source is a capture that was generated by a plugin, no big + // deal // return SCAP_SUCCESS; } @@ -807,11 +748,12 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) // Create the block // bh.block_type = IL_BLOCK_TYPE_V2; - bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + (addrlist->n_v4_addrs + addrlist->n_v6_addrs)*sizeof(uint32_t) + - addrlist->totlen + 4); + bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + + (addrlist->n_v4_addrs + addrlist->n_v6_addrs) * + sizeof(uint32_t) + + addrlist->totlen + 4); - if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) - { + if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF1)"); return SCAP_FAILURE; } @@ -819,8 +761,7 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) // // Dump the ipv4 list // - for(j = 0; j < addrlist->n_v4_addrs; j++) - { + for(j = 0; j < addrlist->n_v4_addrs; j++) { scap_ifinfo_ipv4 *entry = &(addrlist->v4list[j]); entrylen = sizeof(scap_ifinfo_ipv4) + entry->ifnamelen - SCAP_MAX_PATH_SIZE; @@ -832,8 +773,7 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) scap_dump_write(d, &(entry->netmask), sizeof(uint32_t)) != sizeof(uint32_t) || scap_dump_write(d, &(entry->bcast), sizeof(uint32_t)) != sizeof(uint32_t) || scap_dump_write(d, &(entry->linkspeed), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(entry->ifname), entry->ifnamelen) != entry->ifnamelen) - { + scap_dump_write(d, &(entry->ifname), entry->ifnamelen) != entry->ifnamelen) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF2)"); return SCAP_FAILURE; } @@ -844,8 +784,7 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) // // Dump the ipv6 list // - for(j = 0; j < addrlist->n_v6_addrs; j++) - { + for(j = 0; j < addrlist->n_v6_addrs; j++) { scap_ifinfo_ipv6 *entry = &(addrlist->v6list[j]); entrylen = sizeof(scap_ifinfo_ipv6) + entry->ifnamelen - SCAP_MAX_PATH_SIZE; @@ -857,8 +796,7 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) scap_dump_write(d, &(entry->netmask), SCAP_IPV6_ADDR_LEN) != SCAP_IPV6_ADDR_LEN || scap_dump_write(d, &(entry->bcast), SCAP_IPV6_ADDR_LEN) != SCAP_IPV6_ADDR_LEN || scap_dump_write(d, &(entry->linkspeed), sizeof(uint64_t)) != sizeof(uint64_t) || - scap_dump_write(d, &(entry->ifname), entry->ifnamelen) != entry->ifnamelen) - { + scap_dump_write(d, &(entry->ifname), entry->ifnamelen) != entry->ifnamelen) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF2)"); return SCAP_FAILURE; } @@ -869,8 +807,7 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) // // Blocks need to be 4-byte padded // - if(scap_write_padding(d, totlen) != SCAP_SUCCESS) - { + if(scap_write_padding(d, totlen) != SCAP_SUCCESS) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF3)"); return SCAP_FAILURE; } @@ -879,8 +816,7 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) // Create the trailer // bt = bh.block_total_length; - if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF4)"); return SCAP_FAILURE; } @@ -891,8 +827,7 @@ static int32_t scap_write_iflist(scap_dumper_t* d, scap_addrlist* addrlist) // // Write the user list block // -static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userlist) -{ +static int32_t scap_write_userlist(scap_dumper_t *d, struct scap_userlist *userlist) { block_header bh; uint32_t bt; uint32_t j; @@ -905,47 +840,48 @@ static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userl // // Make sure we have a user list interface list // - if(userlist == NULL) - { + if(userlist == NULL) { // - // This can happen when the event source is a capture that was generated by a plugin, no big deal + // This can happen when the event source is a capture that was generated by a plugin, no big + // deal // return SCAP_SUCCESS; } - uint32_t* lengths = calloc(userlist->nusers + userlist->ngroups, sizeof(uint32_t)); - if(lengths == NULL) - { - snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "scap_write_userlist memory allocation failure (1)"); + uint32_t *lengths = calloc(userlist->nusers + userlist->ngroups, sizeof(uint32_t)); + if(lengths == NULL) { + snprintf(d->m_lasterr, + SCAP_LASTERR_SIZE, + "scap_write_userlist memory allocation failure (1)"); return SCAP_FAILURE; } // // Calculate the lengths // - for(j = 0; j < userlist->nusers; j++) - { - scap_userinfo* info = &userlist->users[j]; + for(j = 0; j < userlist->nusers; j++) { + scap_userinfo *info = &userlist->users[j]; namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN); homedirlen = (uint16_t)strnlen(info->homedir, SCAP_MAX_PATH_SIZE); shelllen = (uint16_t)strnlen(info->shell, SCAP_MAX_PATH_SIZE); // NB: new fields must be appended - size_t ul = sizeof(uint32_t) + sizeof(type) + sizeof(info->uid) + sizeof(info->gid) + sizeof(uint16_t) + - namelen + sizeof(uint16_t) + homedirlen + sizeof(uint16_t) + shelllen; + size_t ul = sizeof(uint32_t) + sizeof(type) + sizeof(info->uid) + sizeof(info->gid) + + sizeof(uint16_t) + namelen + sizeof(uint16_t) + homedirlen + sizeof(uint16_t) + + shelllen; totlen += ul; lengths[j] = ul; } - for(j = 0; j < userlist->ngroups; j++) - { - scap_groupinfo* info = &userlist->groups[j]; + for(j = 0; j < userlist->ngroups; j++) { + scap_groupinfo *info = &userlist->groups[j]; namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN); // NB: new fields must be appended - uint32_t gl = sizeof(uint32_t) + sizeof(type) + sizeof(info->gid) + sizeof(uint16_t) + namelen; + uint32_t gl = + sizeof(uint32_t) + sizeof(type) + sizeof(info->gid) + sizeof(uint16_t) + namelen; totlen += gl; lengths[userlist->nusers + j] = gl; } @@ -956,8 +892,7 @@ static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userl bh.block_type = UL_BLOCK_TYPE_V2; bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + totlen + 4); - if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) - { + if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh)) { free(lengths); snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF1)"); return SCAP_FAILURE; @@ -967,25 +902,23 @@ static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userl // Dump the users // type = USERBLOCK_TYPE_USER; - for(j = 0; j < userlist->nusers; j++) - { - scap_userinfo* info = &userlist->users[j]; + for(j = 0; j < userlist->nusers; j++) { + scap_userinfo *info = &userlist->users[j]; namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN); homedirlen = (uint16_t)strnlen(info->homedir, SCAP_MAX_PATH_SIZE); shelllen = (uint16_t)strnlen(info->shell, SCAP_MAX_PATH_SIZE); if(scap_dump_write(d, &(lengths[j]), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(type), sizeof(type)) != sizeof(type) || - scap_dump_write(d, &(info->uid), sizeof(info->uid)) != sizeof(info->uid) || - scap_dump_write(d, &(info->gid), sizeof(info->gid)) != sizeof(info->gid) || - scap_dump_write(d, &namelen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, info->name, namelen) != namelen || - scap_dump_write(d, &homedirlen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, info->homedir, homedirlen) != homedirlen || - scap_dump_write(d, &shelllen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, info->shell, shelllen) != shelllen) - { + scap_dump_write(d, &(type), sizeof(type)) != sizeof(type) || + scap_dump_write(d, &(info->uid), sizeof(info->uid)) != sizeof(info->uid) || + scap_dump_write(d, &(info->gid), sizeof(info->gid)) != sizeof(info->gid) || + scap_dump_write(d, &namelen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, info->name, namelen) != namelen || + scap_dump_write(d, &homedirlen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, info->homedir, homedirlen) != homedirlen || + scap_dump_write(d, &shelllen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, info->shell, shelllen) != shelllen) { free(lengths); snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (U1)"); return SCAP_FAILURE; @@ -996,18 +929,17 @@ static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userl // Dump the groups // type = USERBLOCK_TYPE_GROUP; - for(j = 0; j < userlist->ngroups; j++) - { - scap_groupinfo* info = &userlist->groups[j]; + for(j = 0; j < userlist->ngroups; j++) { + scap_groupinfo *info = &userlist->groups[j]; namelen = (uint16_t)strnlen(info->name, MAX_CREDENTIALS_STR_LEN); - if(scap_dump_write(d, &(lengths[userlist->nusers + j]), sizeof(uint32_t)) != sizeof(uint32_t) || - scap_dump_write(d, &(type), sizeof(type)) != sizeof(type) || - scap_dump_write(d, &(info->gid), sizeof(info->gid)) != sizeof(info->gid) || - scap_dump_write(d, &namelen, sizeof(uint16_t)) != sizeof(uint16_t) || - scap_dump_write(d, info->name, namelen) != namelen) - { + if(scap_dump_write(d, &(lengths[userlist->nusers + j]), sizeof(uint32_t)) != + sizeof(uint32_t) || + scap_dump_write(d, &(type), sizeof(type)) != sizeof(type) || + scap_dump_write(d, &(info->gid), sizeof(info->gid)) != sizeof(info->gid) || + scap_dump_write(d, &namelen, sizeof(uint16_t)) != sizeof(uint16_t) || + scap_dump_write(d, info->name, namelen) != namelen) { free(lengths); snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (U2)"); return SCAP_FAILURE; @@ -1019,8 +951,7 @@ static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userl // // Blocks need to be 4-byte padded // - if(scap_write_padding(d, totlen) != SCAP_SUCCESS) - { + if(scap_write_padding(d, totlen) != SCAP_SUCCESS) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF3)"); return SCAP_FAILURE; } @@ -1029,8 +960,7 @@ static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userl // Create the trailer // bt = bh.block_total_length; - if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + if(scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (IF4)"); return SCAP_FAILURE; } @@ -1041,8 +971,9 @@ static int32_t scap_write_userlist(scap_dumper_t* d, struct scap_userlist *userl // // Create the dump file headers and add the tables // -static int32_t scap_setup_dump(scap_dumper_t* d, struct scap_platform *platform, const char *fname) -{ +static int32_t scap_setup_dump(scap_dumper_t *d, + struct scap_platform *platform, + const char *fname) { block_header bh; section_header_block sh; uint32_t bt; @@ -1061,52 +992,45 @@ static int32_t scap_setup_dump(scap_dumper_t* d, struct scap_platform *platform, bt = bh.block_total_length; if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) || - scap_dump_write(d, &sh, sizeof(sh)) != sizeof(sh) || - scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + scap_dump_write(d, &sh, sizeof(sh)) != sizeof(sh) || + scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file %s (5)", fname); return SCAP_FAILURE; } - if(platform) - { + if(platform) { // // Write the machine info // - if(scap_write_machine_info(d, &platform->m_machine_info) != SCAP_SUCCESS) - { + if(scap_write_machine_info(d, &platform->m_machine_info) != SCAP_SUCCESS) { return SCAP_FAILURE; } // // Write the interface list // - if(scap_write_iflist(d, platform->m_addrlist) != SCAP_SUCCESS) - { + if(scap_write_iflist(d, platform->m_addrlist) != SCAP_SUCCESS) { return SCAP_FAILURE; } // // Write the user list // - if(scap_write_userlist(d, platform->m_userlist) != SCAP_SUCCESS) - { + if(scap_write_userlist(d, platform->m_userlist) != SCAP_SUCCESS) { return SCAP_FAILURE; } // // Write the process list // - if(scap_write_proclist(d, &platform->m_proclist) != SCAP_SUCCESS) - { + if(scap_write_proclist(d, &platform->m_proclist) != SCAP_SUCCESS) { return SCAP_FAILURE; } // // Write the fd lists // - if(scap_write_fdlist(d, &platform->m_proclist) != SCAP_SUCCESS) - { + if(scap_write_fdlist(d, &platform->m_proclist) != SCAP_SUCCESS) { return SCAP_FAILURE; } } @@ -1118,17 +1042,18 @@ static int32_t scap_setup_dump(scap_dumper_t* d, struct scap_platform *platform, } // fname is only used for log messages in scap_setup_dump -static scap_dumper_t *scap_dump_open_gzfile(struct scap_platform* platform, gzFile gzfile, const char *fname, char* lasterr) -{ - scap_dumper_t* res = (scap_dumper_t*)malloc(sizeof(scap_dumper_t)); +static scap_dumper_t *scap_dump_open_gzfile(struct scap_platform *platform, + gzFile gzfile, + const char *fname, + char *lasterr) { + scap_dumper_t *res = (scap_dumper_t *)malloc(sizeof(scap_dumper_t)); res->m_f = gzfile; res->m_type = DT_FILE; res->m_targetbuf = NULL; res->m_targetbufcurpos = NULL; res->m_targetbufend = NULL; - if(scap_setup_dump(res, platform, fname) != SCAP_SUCCESS) - { + if(scap_setup_dump(res, platform, fname) != SCAP_SUCCESS) { strlcpy(lasterr, res->m_lasterr, SCAP_LASTERR_SIZE); free(res); res = NULL; @@ -1140,15 +1065,15 @@ static scap_dumper_t *scap_dump_open_gzfile(struct scap_platform* platform, gzFi // // Open a "savefile" for writing. // -scap_dumper_t *scap_dump_open(struct scap_platform *platform, const char *fname, compression_mode compress, - char *lasterr) -{ +scap_dumper_t *scap_dump_open(struct scap_platform *platform, + const char *fname, + compression_mode compress, + char *lasterr) { gzFile f = NULL; int fd = -1; - const char* mode; + const char *mode; - switch(compress) - { + switch(compress) { case SCAP_COMPRESSION_GZIP: mode = "wb"; break; @@ -1161,29 +1086,23 @@ scap_dumper_t *scap_dump_open(struct scap_platform *platform, const char *fname, return NULL; } - if(fname[0] == '-' && fname[1] == '\0') - { -#ifndef _WIN32 + if(fname[0] == '-' && fname[1] == '\0') { +#ifndef _WIN32 fd = dup(STDOUT_FILENO); #else fd = 1; #endif - if(fd != -1) - { + if(fd != -1) { f = gzdopen(fd, mode); fname = "standard output"; } - } - else - { + } else { f = gzopen(fname, mode); } - if(f == NULL) - { -#ifndef _WIN32 - if(fd != -1) - { + if(f == NULL) { +#ifndef _WIN32 + if(fd != -1) { close(fd); } #endif @@ -1197,12 +1116,14 @@ scap_dumper_t *scap_dump_open(struct scap_platform *platform, const char *fname, // // Open a savefile for writing, using the provided fd -scap_dumper_t* scap_dump_open_fd(struct scap_platform* platform, int fd, compression_mode compress, bool skip_proc_scan, char* lasterr) -{ +scap_dumper_t *scap_dump_open_fd(struct scap_platform *platform, + int fd, + compression_mode compress, + bool skip_proc_scan, + char *lasterr) { gzFile f = NULL; - switch(compress) - { + switch(compress) { case SCAP_COMPRESSION_GZIP: f = gzdopen(fd, "wb"); break; @@ -1214,9 +1135,8 @@ scap_dumper_t* scap_dump_open_fd(struct scap_platform* platform, int fd, compres snprintf(lasterr, SCAP_LASTERR_SIZE, "invalid compression mode"); return NULL; } - - if(f == NULL) - { + + if(f == NULL) { snprintf(lasterr, SCAP_LASTERR_SIZE, "can't open fd %d", fd); return NULL; } @@ -1227,11 +1147,12 @@ scap_dumper_t* scap_dump_open_fd(struct scap_platform* platform, int fd, compres // // Open a memory "savefile" // -scap_dumper_t *scap_memory_dump_open(struct scap_platform* platform, uint8_t* targetbuf, uint64_t targetbufsize, char* lasterr) -{ - scap_dumper_t* res = (scap_dumper_t*)malloc(sizeof(scap_dumper_t)); - if(res == NULL) - { +scap_dumper_t *scap_memory_dump_open(struct scap_platform *platform, + uint8_t *targetbuf, + uint64_t targetbufsize, + char *lasterr) { + scap_dumper_t *res = (scap_dumper_t *)malloc(sizeof(scap_dumper_t)); + if(res == NULL) { snprintf(lasterr, SCAP_LASTERR_SIZE, "scap_dump_memory_open memory allocation failure (1)"); return NULL; } @@ -1242,8 +1163,7 @@ scap_dumper_t *scap_memory_dump_open(struct scap_platform* platform, uint8_t* ta res->m_targetbufcurpos = targetbuf; res->m_targetbufend = targetbuf + targetbufsize; - if(scap_setup_dump(res, platform, "") != SCAP_SUCCESS) - { + if(scap_setup_dump(res, platform, "") != SCAP_SUCCESS) { strlcpy(lasterr, res->m_lasterr, SCAP_LASTERR_SIZE); free(res); res = NULL; @@ -1255,11 +1175,9 @@ scap_dumper_t *scap_memory_dump_open(struct scap_platform* platform, uint8_t* ta // // Create a dumper with an internally managed buffer // -scap_dumper_t *scap_managedbuf_dump_create() -{ +scap_dumper_t *scap_managedbuf_dump_create() { scap_dumper_t *res = (scap_dumper_t *)malloc(sizeof(scap_dumper_t)); - if(res == NULL) - { + if(res == NULL) { return NULL; } @@ -1275,14 +1193,10 @@ scap_dumper_t *scap_managedbuf_dump_create() // // Close a "savefile" opened with scap_dump_open // -void scap_dump_close(scap_dumper_t *d) -{ - if(d->m_type == DT_FILE) - { +void scap_dump_close(scap_dumper_t *d) { + if(d->m_type == DT_FILE) { gzclose(d->m_f); - } - else if (d->m_type == DT_MANAGED_BUF) - { + } else if(d->m_type == DT_MANAGED_BUF) { free(d->m_targetbuf); } @@ -1292,34 +1206,24 @@ void scap_dump_close(scap_dumper_t *d) // // Return the current size of a tracefile // -int64_t scap_dump_get_offset(scap_dumper_t *d) -{ - if(d->m_type == DT_FILE) - { +int64_t scap_dump_get_offset(scap_dumper_t *d) { + if(d->m_type == DT_FILE) { return gzoffset(d->m_f); - } - else - { + } else { return (int64_t)d->m_targetbufcurpos - (int64_t)d->m_targetbuf; } } -int64_t scap_dump_ftell(scap_dumper_t *d) -{ - if(d->m_type == DT_FILE) - { +int64_t scap_dump_ftell(scap_dumper_t *d) { + if(d->m_type == DT_FILE) { return gztell(d->m_f); - } - else - { + } else { return (int64_t)d->m_targetbufcurpos - (int64_t)d->m_targetbuf; } } -void scap_dump_flush(scap_dumper_t *d) -{ - if(d->m_type == DT_FILE) - { +void scap_dump_flush(scap_dumper_t *d) { + if(d->m_type == DT_FILE) { gzflush(d->m_f, Z_FULL_FLUSH); } } @@ -1327,48 +1231,44 @@ void scap_dump_flush(scap_dumper_t *d) // // Write an event to a dump file // -int32_t scap_dump(scap_dumper_t *d, scap_evt *e, uint16_t cpuid, uint32_t flags) -{ +int32_t scap_dump(scap_dumper_t *d, scap_evt *e, uint16_t cpuid, uint32_t flags) { block_header bh; uint32_t bt; bool large_payload = flags & SCAP_DF_LARGE; flags &= ~SCAP_DF_LARGE; - if(flags == 0) - { + if(flags == 0) { // // Write the section header // bh.block_type = large_payload ? EV_BLOCK_TYPE_V2_LARGE : EV_BLOCK_TYPE_V2; - bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + sizeof(cpuid) + e->len + 4); + bh.block_total_length = + scap_normalize_block_len(sizeof(block_header) + sizeof(cpuid) + e->len + 4); bt = bh.block_total_length; if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) || - scap_dump_write(d, &cpuid, sizeof(cpuid)) != sizeof(cpuid) || - scap_dump_write(d, e, e->len) != e->len || - scap_write_padding(d, sizeof(cpuid) + e->len) != SCAP_SUCCESS || - scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + scap_dump_write(d, &cpuid, sizeof(cpuid)) != sizeof(cpuid) || + scap_dump_write(d, e, e->len) != e->len || + scap_write_padding(d, sizeof(cpuid) + e->len) != SCAP_SUCCESS || + scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (6)"); return SCAP_FAILURE; } - } - else - { + } else { // // Write the section header // bh.block_type = large_payload ? EVF_BLOCK_TYPE_V2_LARGE : EVF_BLOCK_TYPE_V2; - bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + sizeof(cpuid) + sizeof(flags) + e->len + 4); + bh.block_total_length = scap_normalize_block_len(sizeof(block_header) + sizeof(cpuid) + + sizeof(flags) + e->len + 4); bt = bh.block_total_length; if(scap_dump_write(d, &bh, sizeof(bh)) != sizeof(bh) || - scap_dump_write(d, &cpuid, sizeof(cpuid)) != sizeof(cpuid) || - scap_dump_write(d, &flags, sizeof(flags)) != sizeof(flags) || - scap_dump_write(d, e, e->len) != e->len || - scap_write_padding(d, sizeof(cpuid) + e->len) != SCAP_SUCCESS || - scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) - { + scap_dump_write(d, &cpuid, sizeof(cpuid)) != sizeof(cpuid) || + scap_dump_write(d, &flags, sizeof(flags)) != sizeof(flags) || + scap_dump_write(d, e, e->len) != e->len || + scap_write_padding(d, sizeof(cpuid) + e->len) != SCAP_SUCCESS || + scap_dump_write(d, &bt, sizeof(bt)) != sizeof(bt)) { snprintf(d->m_lasterr, SCAP_LASTERR_SIZE, "error writing to file (7)"); return SCAP_FAILURE; } diff --git a/userspace/libscap/scap_savefile.h b/userspace/libscap/scap_savefile.h index 266bf4f9fa..5c8ea16cd3 100644 --- a/userspace/libscap/scap_savefile.h +++ b/userspace/libscap/scap_savefile.h @@ -29,37 +29,36 @@ limitations under the License. /////////////////////////////////////////////////////////////////////////////// // GENERIC BLOCK /////////////////////////////////////////////////////////////////////////////// -typedef struct _block_header -{ +typedef struct _block_header { uint32_t block_type; - uint32_t block_total_length; // Block length, including this header and the trailing 32bits block length. -}block_header; + uint32_t block_total_length; // Block length, including this header and the trailing 32bits + // block length. +} block_header; /////////////////////////////////////////////////////////////////////////////// // SECTION HEADER BLOCK /////////////////////////////////////////////////////////////////////////////// // Block type of the section header block -#define SHB_BLOCK_TYPE 0x0A0D0D0A /*\r\n\n\r*/ +#define SHB_BLOCK_TYPE 0x0A0D0D0A /*\r\n\n\r*/ // Magic of the section header block // Used to recognize if a section is in host byte order or not. -#define SHB_MAGIC 0x1A2B3C4D +#define SHB_MAGIC 0x1A2B3C4D // Major version of the file format supported by this library. // Must be increased only when if the new version of the software // is not able anymore to read older captures -#define CURRENT_MAJOR_VERSION 1 +#define CURRENT_MAJOR_VERSION 1 // Minor version of the file format supported by this library. // We used to bump it every time the event table was updated, but // after adding {retro,forward} captures compatibility support // this is not required anymore. -#define CURRENT_MINOR_VERSION 2 +#define CURRENT_MINOR_VERSION 2 -typedef struct _section_header_block -{ +typedef struct _section_header_block { uint32_t byte_order_magic; uint16_t major_version; uint16_t minor_version; uint64_t section_length; -}section_header_block; +} section_header_block; // NB: // Starting from scap version 1.2, block versions will no longer be changed. @@ -71,86 +70,94 @@ typedef struct _section_header_block /////////////////////////////////////////////////////////////////////////////// // MACHINE INFO BLOCK /////////////////////////////////////////////////////////////////////////////// -#define MI_BLOCK_TYPE 0x201 -#define MI_BLOCK_TYPE_INT 0x8002ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility +#define MI_BLOCK_TYPE 0x201 +#define MI_BLOCK_TYPE_INT \ + 0x8002ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility /////////////////////////////////////////////////////////////////////////////// // PROCESS LIST BLOCK /////////////////////////////////////////////////////////////////////////////// -#define PL_BLOCK_TYPE_V1 0x202 -#define PL_BLOCK_TYPE_V1_INT 0x8000ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility +#define PL_BLOCK_TYPE_V1 0x202 +#define PL_BLOCK_TYPE_V1_INT \ + 0x8000ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility -#define PL_BLOCK_TYPE_V2 0x207 -#define PL_BLOCK_TYPE_V2_INT 0x8013ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility +#define PL_BLOCK_TYPE_V2 0x207 +#define PL_BLOCK_TYPE_V2_INT \ + 0x8013ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility -#define PL_BLOCK_TYPE_V3 0x209 -#define PL_BLOCK_TYPE_V3_INT 0x8014ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility +#define PL_BLOCK_TYPE_V3 0x209 +#define PL_BLOCK_TYPE_V3_INT \ + 0x8014ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility -#define PL_BLOCK_TYPE_V4 0x210 +#define PL_BLOCK_TYPE_V4 0x210 -#define PL_BLOCK_TYPE_V5 0x211 +#define PL_BLOCK_TYPE_V5 0x211 -#define PL_BLOCK_TYPE_V6 0x212 +#define PL_BLOCK_TYPE_V6 0x212 -#define PL_BLOCK_TYPE_V7 0x213 +#define PL_BLOCK_TYPE_V7 0x213 -#define PL_BLOCK_TYPE_V8 0x214 +#define PL_BLOCK_TYPE_V8 0x214 -#define PL_BLOCK_TYPE_V9 0x215 +#define PL_BLOCK_TYPE_V9 0x215 /////////////////////////////////////////////////////////////////////////////// // FD LIST BLOCK /////////////////////////////////////////////////////////////////////////////// -#define FDL_BLOCK_TYPE 0x203 -#define FDL_BLOCK_TYPE_INT 0x8001ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility -#define FDL_BLOCK_TYPE_V2 0x218 +#define FDL_BLOCK_TYPE 0x203 +#define FDL_BLOCK_TYPE_INT \ + 0x8001ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility +#define FDL_BLOCK_TYPE_V2 0x218 /////////////////////////////////////////////////////////////////////////////// // EVENT BLOCK /////////////////////////////////////////////////////////////////////////////// -#define EV_BLOCK_TYPE 0x204 -#define EV_BLOCK_TYPE_INT 0x8010ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility -#define EV_BLOCK_TYPE_V2 0x216 +#define EV_BLOCK_TYPE 0x204 +#define EV_BLOCK_TYPE_INT \ + 0x8010ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility +#define EV_BLOCK_TYPE_V2 0x216 -#define EV_BLOCK_TYPE_V2_LARGE 0x221 +#define EV_BLOCK_TYPE_V2_LARGE 0x221 /////////////////////////////////////////////////////////////////////////////// // INTERFACE LIST BLOCK /////////////////////////////////////////////////////////////////////////////// -#define IL_BLOCK_TYPE 0x205 -#define IL_BLOCK_TYPE_INT 0x8011ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility -#define IL_BLOCK_TYPE_V2 0x219 +#define IL_BLOCK_TYPE 0x205 +#define IL_BLOCK_TYPE_INT \ + 0x8011ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility +#define IL_BLOCK_TYPE_V2 0x219 /////////////////////////////////////////////////////////////////////////////// // USER LIST BLOCK /////////////////////////////////////////////////////////////////////////////// -#define UL_BLOCK_TYPE 0x206 -#define UL_BLOCK_TYPE_INT 0x8012ABCD // This is the unofficial number used before the - // library release. We'll keep it for a while for - // backward compatibility -#define UL_BLOCK_TYPE_V2 0x220 +#define UL_BLOCK_TYPE 0x206 +#define UL_BLOCK_TYPE_INT \ + 0x8012ABCD // This is the unofficial number used before the + // library release. We'll keep it for a while for + // backward compatibility +#define UL_BLOCK_TYPE_V2 0x220 /////////////////////////////////////////////////////////////////////////////// // EVENT BLOCK WITH FLAGS /////////////////////////////////////////////////////////////////////////////// -#define EVF_BLOCK_TYPE 0x208 +#define EVF_BLOCK_TYPE 0x208 -#define EVF_BLOCK_TYPE_V2 0x217 +#define EVF_BLOCK_TYPE_V2 0x217 -#define EVF_BLOCK_TYPE_V2_LARGE 0x222 +#define EVF_BLOCK_TYPE_V2_LARGE 0x222 #pragma pack(pop) diff --git a/userspace/libscap/scap_savefile_api.h b/userspace/libscap/scap_savefile_api.h index 6eb06f3437..520d5da1be 100644 --- a/userspace/libscap/scap_savefile_api.h +++ b/userspace/libscap/scap_savefile_api.h @@ -30,8 +30,7 @@ extern "C" { struct scap_platform; -typedef enum ppm_dumper_type -{ +typedef enum ppm_dumper_type { DT_FILE = 0, DT_MEM = 1, DT_MANAGED_BUF = 2, @@ -40,13 +39,12 @@ typedef enum ppm_dumper_type #define PPM_DUMPER_MANAGED_BUF_SIZE (3 * 1024 * 1024) #define PPM_DUMPER_MANAGED_BUF_RESIZE_FACTOR (1.25) -typedef struct scap_dumper -{ +typedef struct scap_dumper { gzFile m_f; ppm_dumper_type m_type; - uint8_t* m_targetbuf; - uint8_t* m_targetbufcurpos; - uint8_t* m_targetbufend; + uint8_t *m_targetbuf; + uint8_t *m_targetbufcurpos; + uint8_t *m_targetbufend; char m_lasterr[SCAP_LASTERR_SIZE]; } scap_dumper_t; @@ -57,31 +55,38 @@ struct iovec; /*! \brief Indicates the compression type used when writing a tracefile */ -typedef enum compression_mode -{ +typedef enum compression_mode { SCAP_COMPRESSION_NONE = 0, SCAP_COMPRESSION_GZIP = 1 } compression_mode; -uint8_t* scap_get_memorydumper_curpos(scap_dumper_t *d); +uint8_t *scap_get_memorydumper_curpos(scap_dumper_t *d); int32_t scap_write_proc_fds(scap_dumper_t *d, struct scap_threadinfo *tinfo); -scap_dumper_t* scap_write_proclist_begin(); +scap_dumper_t *scap_write_proclist_begin(); int scap_write_proclist_end(scap_dumper_t *d, scap_dumper_t *proclist_dumper, uint32_t totlen); -scap_dumper_t *scap_memory_dump_open(struct scap_platform* platform, uint8_t* targetbuf, uint64_t targetbufsize, char* lasterr); +scap_dumper_t *scap_memory_dump_open(struct scap_platform *platform, + uint8_t *targetbuf, + uint64_t targetbufsize, + char *lasterr); scap_dumper_t *scap_managedbuf_dump_create(); // Variant of scap_write_proclist_entry where array-backed information // about the thread is provided separate from the scap_threadinfo // struct. -int32_t scap_write_proclist_entry_bufs(scap_dumper_t *d, struct scap_threadinfo *tinfo, uint32_t *len, - const char *comm, - const char *exe, - const char *exepath, - const struct iovec *args, int argscnt, - const struct iovec *envs, int envscnt, - const char *cwd, - const struct iovec *cgroups, int cgroupscnt, - const char *root); +int32_t scap_write_proclist_entry_bufs(scap_dumper_t *d, + struct scap_threadinfo *tinfo, + uint32_t *len, + const char *comm, + const char *exe, + const char *exepath, + const struct iovec *args, + int argscnt, + const struct iovec *envs, + int envscnt, + const char *cwd, + const struct iovec *cgroups, + int cgroupscnt, + const char *root); /*! \brief Open a trace file for writing @@ -91,8 +96,10 @@ int32_t scap_write_proclist_entry_bufs(scap_dumper_t *d, struct scap_threadinfo \return Dump handle that can be used to identify this specific dump instance. */ -scap_dumper_t *scap_dump_open(struct scap_platform *platform, const char *fname, compression_mode compress, - char *lasterr); +scap_dumper_t *scap_dump_open(struct scap_platform *platform, + const char *fname, + compression_mode compress, + char *lasterr); /*! \brief Open a trace file for writing, using the provided fd. @@ -102,7 +109,11 @@ scap_dumper_t *scap_dump_open(struct scap_platform *platform, const char *fname, \return Dump handle that can be used to identify this specific dump instance. */ -scap_dumper_t* scap_dump_open_fd(struct scap_platform* platform, int fd, compression_mode compress, bool skip_proc_scan, char* lasterr); +scap_dumper_t *scap_dump_open_fd(struct scap_platform *platform, + int fd, + compression_mode compress, + bool skip_proc_scan, + char *lasterr); /*! \brief Close a trace file. @@ -147,12 +158,12 @@ void scap_dump_flush(scap_dumper_t *d); On Failure, SCAP_FAILURE is returned and scap_dump_getlasterr() can be used to obtain the cause of the error. */ -int32_t scap_dump(scap_dumper_t *d, scap_evt* e, uint16_t cpuid, uint32_t flags); +int32_t scap_dump(scap_dumper_t *d, scap_evt *e, uint16_t cpuid, uint32_t flags); /*! \brief Return a string with the last error that happened on the given dumper. */ -const char* scap_dump_getlasterr(scap_dumper_t* handle); +const char *scap_dump_getlasterr(scap_dumper_t *handle); #ifdef __cplusplus } diff --git a/userspace/libscap/scap_userlist.c b/userspace/libscap/scap_userlist.c index 0687e2e6f1..25def33579 100644 --- a/userspace/libscap/scap_userlist.c +++ b/userspace/libscap/scap_userlist.c @@ -23,10 +23,8 @@ limitations under the License. // // Free a previously allocated list of users // -void scap_free_userlist(scap_userlist* uhandle) -{ - if(uhandle) - { +void scap_free_userlist(scap_userlist* uhandle) { + if(uhandle) { free(uhandle->users); free(uhandle->groups); free(uhandle); diff --git a/userspace/libscap/scap_vtable.h b/userspace/libscap/scap_vtable.h index cbe1d0d0ab..206fa133ea 100644 --- a/userspace/libscap/scap_vtable.h +++ b/userspace/libscap/scap_vtable.h @@ -35,8 +35,8 @@ struct scap_proclist; enum scap_ppm_sc_mask_op { // SCAP_PPM_SC_MASK_ZERO = 0, //< disable all syscalls - SUPPORT DROPPED - SCAP_PPM_SC_MASK_SET = 1, //< enable a syscall - SCAP_PPM_SC_MASK_UNSET = 2, //< disable a syscall + SCAP_PPM_SC_MASK_SET = 1, //< enable a syscall + SCAP_PPM_SC_MASK_UNSET = 2, //< disable a syscall }; /** @@ -113,7 +113,7 @@ struct scap_savefile_vtable { int64_t (*get_readfile_offset)(struct scap_engine_handle engine); }; -#define ENGINE_FLAG_BPF_STATS_ENABLED (1<<0) +#define ENGINE_FLAG_BPF_STATS_ENABLED (1 << 0) struct scap_vtable { /** @@ -121,7 +121,7 @@ struct scap_vtable { */ const char* name; - const struct scap_savefile_vtable *savefile_ops; + const struct scap_savefile_vtable* savefile_ops; /** * @brief allocate an engine-specific handle @@ -178,7 +178,10 @@ struct scap_vtable { * The memory pointed to by *pevent must be owned by the engine * and must remain valid at least until the next call to next() */ - int32_t (*next)(struct scap_engine_handle engine, scap_evt** pevent, uint16_t* pdevid, uint32_t* pflags); + int32_t (*next)(struct scap_engine_handle engine, + scap_evt** pevent, + uint16_t* pdevid, + uint32_t* pflags); /** * @brief start a capture @@ -203,7 +206,10 @@ struct scap_vtable { * @param arg2 setting-specific value * @return SCAP_SUCCESS or a failure code */ - int32_t (*configure)(struct scap_engine_handle engine, enum scap_setting setting, unsigned long arg1, unsigned long arg2); + int32_t (*configure)(struct scap_engine_handle engine, + enum scap_setting setting, + unsigned long arg1, + unsigned long arg2); /** * @brief get engine statistics @@ -211,7 +217,7 @@ struct scap_vtable { * @param stats [out] the stats struct to be filled * @return SCAP_SUCCESS or a failure code */ - int32_t (*get_stats)(struct scap_engine_handle engine, struct scap_stats *stats); + int32_t (*get_stats)(struct scap_engine_handle engine, struct scap_stats* stats); /** * @brief get engine statistics (including counters and `bpftool prog show` like stats) @@ -220,7 +226,10 @@ struct scap_vtable { * @param rc [out] Pointer to return code * @return Pointer to a \ref metrics_v2 structure filled with the statistics */ - const struct metrics_v2* (*get_stats_v2)(struct scap_engine_handle engine, uint32_t flags, uint32_t* nstats, int32_t* rc); + const struct metrics_v2* (*get_stats_v2)(struct scap_engine_handle engine, + uint32_t flags, + uint32_t* nstats, + int32_t* rc); /** * @brief get the number of tracepoint hits @@ -228,7 +237,7 @@ struct scap_vtable { * @param ret [out] the number of hits * @return SCAP_SUCCESS or a failure code */ - int32_t (*get_n_tracepoint_hit)(struct scap_engine_handle engine, long *ret); + int32_t (*get_n_tracepoint_hit)(struct scap_engine_handle engine, long* ret); /** * @brief get the number of used devices diff --git a/userspace/libscap/scap_zlib.h b/userspace/libscap/scap_zlib.h index 74400e9f21..94751b3504 100644 --- a/userspace/libscap/scap_zlib.h +++ b/userspace/libscap/scap_zlib.h @@ -27,15 +27,18 @@ limitations under the License. #include #else #include -#define gzFile FILE* +#define gzFile FILE* #define gzflush(X, Y) fflush(X) #define gzopen fopen -#define gzdopen(fd, mode) fdopen(fd, mode) +#define gzdopen(fd, mode) fdopen(fd, mode) #define gzclose fclose #define gzoffset ftell #define gzwrite(F, B, S) fwrite(B, 1, S, F) #define gzread(F, B, S) fread(B, 1, S, F) #define gztell(F) ftell(F) -inline static const char *gzerror(FILE *F, int *E) {*E = ferror(F); return "error reading file descriptor";} +inline static const char *gzerror(FILE *F, int *E) { + *E = ferror(F); + return "error reading file descriptor"; +} #define gzseek fseek #endif diff --git a/userspace/libscap/strerror.c b/userspace/libscap/strerror.c index 4d46da86cc..728e81b264 100644 --- a/userspace/libscap/strerror.c +++ b/userspace/libscap/strerror.c @@ -37,8 +37,7 @@ limitations under the License. #define strerror_r(errnum, buf, size) strerror_s(buf, size, errnum) #endif -int32_t scap_errprintf_unchecked(char *buf, int errnum, const char* fmt, ...) -{ +int32_t scap_errprintf_unchecked(char* buf, int errnum, const char* fmt, ...) { int len; va_list va; @@ -47,11 +46,9 @@ int32_t scap_errprintf_unchecked(char *buf, int errnum, const char* fmt, ...) len = vsnprintf(buf, SCAP_LASTERR_SIZE, fmt, va); va_end(va); - if (errnum > 0 && len < SCAP_LASTERR_SIZE - 1) - { + if(errnum > 0 && len < SCAP_LASTERR_SIZE - 1) { char err_buf[SCAP_LASTERR_SIZE]; - if(strerror_r(errnum, err_buf, sizeof(err_buf)) < 0) - { + if(strerror_r(errnum, err_buf, sizeof(err_buf)) < 0) { snprintf(err_buf, sizeof(err_buf), "Unknown error %d", errnum); } snprintf(buf + len, SCAP_LASTERR_SIZE - len, ": %s", err_buf); diff --git a/userspace/libscap/strerror.h b/userspace/libscap/strerror.h index 009de16d58..015665bd2d 100644 --- a/userspace/libscap/strerror.h +++ b/userspace/libscap/strerror.h @@ -16,7 +16,6 @@ limitations under the License. */ - #pragma once #include @@ -26,14 +25,16 @@ extern "C" { #endif #ifdef __GNUC__ -int32_t scap_errprintf_unchecked(char *buf, int errnum, const char* fmt, ...) __attribute__ ((format (printf, 3, 4))); +int32_t scap_errprintf_unchecked(char* buf, int errnum, const char* fmt, ...) + __attribute__((format(printf, 3, 4))); #define scap_errprintf scap_errprintf_unchecked #else #include -#define scap_errprintf(BUF, ERRNUM, ...) ((void)sizeof(printf(__VA_ARGS__)), scap_errprintf_unchecked(BUF, ERRNUM, __VA_ARGS__)) -int32_t scap_errprintf_unchecked(char *buf, int errnum, const char* fmt, ...); +#define scap_errprintf(BUF, ERRNUM, ...) \ + ((void)sizeof(printf(__VA_ARGS__)), scap_errprintf_unchecked(BUF, ERRNUM, __VA_ARGS__)) +int32_t scap_errprintf_unchecked(char* buf, int errnum, const char* fmt, ...); #endif #ifdef __cplusplus diff --git a/userspace/libscap/strl.h b/userspace/libscap/strl.h index 4334dc9fa8..45641b8050 100644 --- a/userspace/libscap/strl.h +++ b/userspace/libscap/strl.h @@ -22,59 +22,61 @@ limitations under the License. #pragma once /*! - \brief Copy up to size - 1 characters from the NUL-terminated string src to dst, NUL-terminating the result. + \brief Copy up to size - 1 characters from the NUL-terminated string src to dst, NUL-terminating + the result. \return The length of the source string. */ #ifndef HAVE_STRLCPY static inline size_t strlcpy(char *dst, const char *src, size_t size) { - size_t srcsize = strlen(src); - if (size == 0) { - return srcsize; - } + size_t srcsize = strlen(src); + if(size == 0) { + return srcsize; + } - size_t copysize = srcsize; + size_t copysize = srcsize; - if (copysize > size - 1) { - copysize = size - 1; - } + if(copysize > size - 1) { + copysize = size - 1; + } - memcpy(dst, src, copysize); - dst[copysize] = '\0'; + memcpy(dst, src, copysize); + dst[copysize] = '\0'; - return srcsize; + return srcsize; } #endif /*! - \brief Append the NUL-terminated string src to the end of dst. It will append at most size − strlen(dst) − 1 bytes, NUL-terminating the result. + \brief Append the NUL-terminated string src to the end of dst. It will append at most size − + strlen(dst) − 1 bytes, NUL-terminating the result. \return The initial length of dst plus the length of src */ #ifndef HAVE_STRLCAT static inline size_t strlcat(char *dst, const char *src, size_t size) { - size_t srcsize = strlen(src); - size_t dstsize = strlen(dst); + size_t srcsize = strlen(src); + size_t dstsize = strlen(dst); - if (dstsize >= size) { - return size; - } + if(dstsize >= size) { + return size; + } - if (srcsize == 0) { - return dstsize; - } + if(srcsize == 0) { + return dstsize; + } - size_t totalsize = srcsize + dstsize; - if (totalsize > size - 1) { - totalsize = size - 1; - } + size_t totalsize = srcsize + dstsize; + if(totalsize > size - 1) { + totalsize = size - 1; + } - size_t copysize = totalsize - dstsize; - memcpy(dst + dstsize, src, copysize); - dst[totalsize] = '\0'; + size_t copysize = totalsize - dstsize; + memcpy(dst + dstsize, src, copysize); + dst[totalsize] = '\0'; - return dstsize + srcsize; + return dstsize + srcsize; } #endif diff --git a/userspace/libscap/userspace_flag_helpers.h b/userspace/libscap/userspace_flag_helpers.h index a8b90a0f04..0e97d5b76e 100644 --- a/userspace/libscap/userspace_flag_helpers.h +++ b/userspace/libscap/userspace_flag_helpers.h @@ -25,8 +25,8 @@ limitations under the License. #include #if !defined(__APPLE__) #include -#endif //__APPLE__ -#endif //__EMSCRIPTEN__ _WIN32 +#endif //__APPLE__ +#endif //__EMSCRIPTEN__ _WIN32 #if !defined(_WIN32) #include #include @@ -34,7 +34,7 @@ limitations under the License. #include #include #include -#endif //_WIN32 +#endif //_WIN32 #define ASSERT assert #ifndef F_CANCELLK @@ -42,10 +42,10 @@ limitations under the License. #endif #ifndef QFMT_VFS_OLD -#define QFMT_VFS_OLD 1 -#define QFMT_VFS_V0 2 +#define QFMT_VFS_OLD 1 +#define QFMT_VFS_V0 2 #define QFMT_OCFS2 3 -#define QFMT_VFS_V1 4 +#define QFMT_VFS_V1 4 #endif #define u8 uint8_t diff --git a/userspace/libscap/uthash_ext.h b/userspace/libscap/uthash_ext.h index 28a115b3c3..2445768952 100644 --- a/userspace/libscap/uthash_ext.h +++ b/userspace/libscap/uthash_ext.h @@ -18,17 +18,13 @@ limitations under the License. #pragma once -#define uthash_fatal(msg) uth_status = SCAP_FAILURE +#define uthash_fatal(msg) uth_status = SCAP_FAILURE /* `uthash.h` is generated at build time, see `uthash.cmake` */ #include "uthash.h" /* Further definitions on top of 'uthash.h' */ -#define HASH_FIND_INT32(head,findint,out) \ - HASH_FIND(hh,head,findint,sizeof(uint32_t),out) -#define HASH_ADD_INT32(head,intfield,add) \ - HASH_ADD(hh,head,intfield,sizeof(uint32_t),add) -#define HASH_FIND_INT64(head,findint,out) \ - HASH_FIND(hh,head,findint,sizeof(uint64_t),out) -#define HASH_ADD_INT64(head,intfield,add) \ - HASH_ADD(hh,head,intfield,sizeof(uint64_t),add) +#define HASH_FIND_INT32(head, findint, out) HASH_FIND(hh, head, findint, sizeof(uint32_t), out) +#define HASH_ADD_INT32(head, intfield, add) HASH_ADD(hh, head, intfield, sizeof(uint32_t), add) +#define HASH_FIND_INT64(head, findint, out) HASH_FIND(hh, head, findint, sizeof(uint64_t), out) +#define HASH_ADD_INT64(head, intfield, add) HASH_ADD(hh, head, intfield, sizeof(uint64_t), add) diff --git a/userspace/libscap/win32/gettimeofday.h b/userspace/libscap/win32/gettimeofday.h index d7b2fdd5e3..5093e6ae4a 100644 --- a/userspace/libscap/win32/gettimeofday.h +++ b/userspace/libscap/win32/gettimeofday.h @@ -21,9 +21,8 @@ limitations under the License. #include #include -static inline uint64_t ft_to_epoch_nsec(FILETIME* ft) -{ - static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL); +static inline uint64_t ft_to_epoch_nsec(FILETIME* ft) { + static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); uint64_t ftl = (((uint64_t)ft->dwHighDateTime) << 32) + ft->dwLowDateTime; ftl -= EPOCH; @@ -31,11 +30,9 @@ static inline uint64_t ft_to_epoch_nsec(FILETIME* ft) return ts; } -static inline uint64_t get_timestamp_ns() -{ +static inline uint64_t get_timestamp_ns() { FILETIME ft; GetSystemTimePreciseAsFileTime(&ft); return ft_to_epoch_nsec(&ft); } - diff --git a/userspace/libscap/win32/sleep.h b/userspace/libscap/win32/sleep.h index 9bbe076eff..7e215fc4ce 100644 --- a/userspace/libscap/win32/sleep.h +++ b/userspace/libscap/win32/sleep.h @@ -20,7 +20,6 @@ limitations under the License. #include -static inline void sleep_ms(int ms) -{ +static inline void sleep_ms(int ms) { Sleep((DWORD)ms); } diff --git a/userspace/libsinsp/CMakeLists.txt b/userspace/libsinsp/CMakeLists.txt index 1ffa22bbbc..f3abd43db1 100644 --- a/userspace/libsinsp/CMakeLists.txt +++ b/userspace/libsinsp/CMakeLists.txt @@ -2,17 +2,15 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # option(USE_BUNDLED_DEPS "Enable bundled dependencies instead of using the system ones" ON) @@ -35,13 +33,13 @@ include(jsoncpp) include(zlib) if(NOT MINIMAL_BUILD) - if (NOT WIN32 AND NOT EMSCRIPTEN) + if(NOT WIN32 AND NOT EMSCRIPTEN) include(curl) include(cares) endif() # NOT WIN32 endif() -if(NOT WIN32 AND NOT APPLE ) +if(NOT WIN32 AND NOT APPLE) if(NOT MINIMAL_BUILD AND NOT EMSCRIPTEN) include(grpc) include(protobuf) @@ -49,11 +47,12 @@ if(NOT WIN32 AND NOT APPLE ) endif() # NOT MINIMAL_BUILD endif() -if (NOT EMSCRIPTEN) +if(NOT EMSCRIPTEN) include(tbb) endif() -add_library(sinsp +add_library( + sinsp filter/ast.cpp filter/escaping.cpp filter/parser.cpp @@ -113,11 +112,8 @@ add_library(sinsp events/sinsp_events_ppm_sc.cpp ) -if (ENABLE_THREAD_POOL AND NOT EMSCRIPTEN) - target_sources(sinsp - PRIVATE - thread_pool_bs.cpp - ) +if(ENABLE_THREAD_POOL AND NOT EMSCRIPTEN) + target_sources(sinsp PRIVATE thread_pool_bs.cpp) endif() if(NOT WIN32 AND NOT APPLE) @@ -125,72 +121,57 @@ if(NOT WIN32 AND NOT APPLE) endif() if(NOT MINIMAL_BUILD AND NOT EMSCRIPTEN) - target_sources(sinsp - PRIVATE - container_engine/docker/async_source.cpp - container_engine/docker/base.cpp + target_sources( + sinsp PRIVATE container_engine/docker/async_source.cpp container_engine/docker/base.cpp ) if(NOT WIN32) - target_sources(sinsp - PRIVATE - container_engine/docker/docker_linux.cpp - container_engine/docker/connection_linux.cpp - container_engine/docker/podman.cpp - container_engine/libvirt_lxc.cpp - container_engine/lxc.cpp - container_engine/mesos.cpp - container_engine/rkt.cpp - container_engine/bpm.cpp - cri_settings.cpp - runc.cpp + target_sources( + sinsp + PRIVATE container_engine/docker/docker_linux.cpp + container_engine/docker/connection_linux.cpp + container_engine/docker/podman.cpp + container_engine/libvirt_lxc.cpp + container_engine/lxc.cpp + container_engine/mesos.cpp + container_engine/rkt.cpp + container_engine/bpm.cpp + cri_settings.cpp + runc.cpp ) endif() if(NOT WIN32 AND NOT APPLE) - target_sources(sinsp - PRIVATE - cgroup_limits.cpp - container_engine/cri.cpp - grpc_channel_registry.cpp + target_sources( + sinsp PRIVATE cgroup_limits.cpp container_engine/cri.cpp grpc_channel_registry.cpp ) endif() endif() -target_include_directories(sinsp -PUBLIC - $ - $ - $ +target_include_directories( + sinsp + PUBLIC $ $ + $ ) -if (EMSCRIPTEN) +if(EMSCRIPTEN) target_compile_options(sinsp PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0") endif() set_sinsp_target_properties(sinsp) -target_link_libraries(sinsp - PUBLIC scap - PRIVATE - "${CURL_LIBRARIES}" - "${JSONCPP_LIB}" - "${RE2_LIB}" +target_link_libraries( + sinsp + PUBLIC scap + PRIVATE "${CURL_LIBRARIES}" "${JSONCPP_LIB}" "${RE2_LIB}" ) -set(SINSP_PKGCONFIG_LIBRARIES - scap - "${ZLIB_LIB}" - "${CURL_LIBRARIES}" - "${JSONCPP_LIB}" - "${RE2_LIB}" -) +set(SINSP_PKGCONFIG_LIBRARIES scap "${ZLIB_LIB}" "${CURL_LIBRARIES}" "${JSONCPP_LIB}" "${RE2_LIB}") if(NOT EMSCRIPTEN) - target_link_libraries(sinsp - INTERFACE - "${CARES_LIB}" - PRIVATE - "${TBB_LIB}" + target_link_libraries( + sinsp + INTERFACE "${CARES_LIB}" + PRIVATE "${TBB_LIB}" ) list(APPEND SINSP_PKGCONFIG_LIBRARIES "${CARES_LIB}") endif() @@ -212,25 +193,36 @@ if(ENABLE_THREAD_POOL AND USE_BUNDLED_BS_THREADPOOL) endif() function(prepare_cri_grpc api_version) - configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cri-${api_version}.proto ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.proto COPYONLY) - add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.grpc.pb.cc - ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.grpc.pb.h - ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.pb.cc - ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.pb.h - COMMENT "Generate CRI grpc code for API version ${api_version}" - DEPENDS - COMMAND ${PROTOC} -I ${CMAKE_CURRENT_BINARY_DIR} --cpp_out=. ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.proto - COMMAND ${PROTOC} -I ${CMAKE_CURRENT_BINARY_DIR} --grpc_out=. --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.proto - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) - add_library(cri_${api_version} STATIC ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.pb.cc ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.grpc.pb.cc) - target_include_directories(cri_${api_version} - PUBLIC - $ + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/cri-${api_version}.proto + ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.proto COPYONLY + ) + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.grpc.pb.cc + ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.grpc.pb.h + ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.pb.cc + ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.pb.h + COMMENT "Generate CRI grpc code for API version ${api_version}" + DEPENDS + COMMAND ${PROTOC} -I ${CMAKE_CURRENT_BINARY_DIR} --cpp_out=. + ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.proto + COMMAND + ${PROTOC} -I ${CMAKE_CURRENT_BINARY_DIR} --grpc_out=. + --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} + ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.proto + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + add_library( + cri_${api_version} STATIC ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.pb.cc + ${CMAKE_CURRENT_BINARY_DIR}/cri-${api_version}.grpc.pb.cc + ) + target_include_directories( + cri_${api_version} PUBLIC $ ) add_dependencies(cri_${api_version} grpc) endfunction() -if (NOT EMSCRIPTEN) +if(NOT EMSCRIPTEN) add_dependencies(sinsp tbb) endif() @@ -248,25 +240,21 @@ if(NOT WIN32) prepare_cri_grpc(v1alpha2) prepare_cri_grpc(v1) - target_link_libraries(sinsp - PRIVATE - cri_v1alpha2 - cri_v1 - INTERFACE - "${GRPC_LIBRARIES}" - "${GRPCPP_LIB}" - "${GRPC_LIB}" - "${GPR_LIB}" - "${PROTOBUF_LIB}" - "${CARES_LIB}" + target_link_libraries( + sinsp + PRIVATE cri_v1alpha2 cri_v1 + INTERFACE "${GRPC_LIBRARIES}" "${GRPCPP_LIB}" "${GRPC_LIB}" "${GPR_LIB}" + "${PROTOBUF_LIB}" "${CARES_LIB}" ) - list(APPEND SINSP_PKGCONFIG_LIBRARIES - "${GRPC_LIBRARIES}" - "${GRPCPP_LIB}" - "${GRPC_LIB}" - "${GPR_LIB}" - "${PROTOBUF_LIB}" - "${CARES_LIB}" + list( + APPEND + SINSP_PKGCONFIG_LIBRARIES + "${GRPC_LIBRARIES}" + "${GRPCPP_LIB}" + "${GRPC_LIB}" + "${GPR_LIB}" + "${PROTOBUF_LIB}" + "${CARES_LIB}" ) if(NOT MUSL_OPTIMIZED_BUILD) @@ -292,7 +280,7 @@ if(NOT WIN32) target_link_libraries(sinsp INTERFACE dl pthread) list(APPEND SINSP_PKGCONFIG_LIBRARIES dl pthread) - if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9.0) target_link_libraries(sinsp INTERFACE stdc++fs) list(APPEND SINSP_PKGCONFIG_LIBRARIES stdc++fs) @@ -309,12 +297,12 @@ endif() option(CREATE_TEST_TARGETS "Enable make-targets for unit testing" ON) if(CREATE_TEST_TARGETS) - # Add unit test directories - add_subdirectory(test) + # Add unit test directories + add_subdirectory(test) endif() option(BUILD_LIBSINSP_EXAMPLES "Build libsinsp examples" ON) -if (BUILD_LIBSINSP_EXAMPLES) +if(BUILD_LIBSINSP_EXAMPLES) add_subdirectory(examples) add_subdirectory(sinsp_debug) endif() @@ -324,10 +312,9 @@ if(NOT DEFINED SINSP_AGENT_CGROUP_MEM_PATH_ENV_VAR) endif() add_definitions(-DSINSP_AGENT_CGROUP_MEM_PATH_ENV_VAR="${SINSP_AGENT_CGROUP_MEM_PATH_ENV_VAR}") -# Build our pkg-config "Libs:" flags. For now, loop over SINSP_PKGCONFIG_LIBRARIES. If -# we ever start using pkg_search_module or pkg_check_modules in cmake/modules -# we could add each module to our "Requires:" line instead. We might need to -# expand this to use some of the techniques in +# Build our pkg-config "Libs:" flags. For now, loop over SINSP_PKGCONFIG_LIBRARIES. If we ever start +# using pkg_search_module or pkg_check_modules in cmake/modules we could add each module to our +# "Requires:" line instead. We might need to expand this to use some of the techniques in # https://github.com/curl/curl/blob/curl-7_84_0/CMakeLists.txt#L1539 set(SINSP_PKG_CONFIG_LIBS) set(SINSP_PKG_CONFIG_LIBDIRS "") @@ -361,4 +348,6 @@ list(REMOVE_DUPLICATES SINSP_PKG_CONFIG_LIBDIRS) string(REPLACE ";" " " SINSP_PKG_CONFIG_LIBDIRS "${SINSP_PKG_CONFIG_LIBDIRS}") list(REMOVE_DUPLICATES SINSP_PKG_CONFIG_INCLUDES) string(REPLACE ";" " " SINSP_PKG_CONFIG_INCLUDES "${SINSP_PKG_CONFIG_INCLUDES}") -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/libsinsp.pc.in ${CMAKE_CURRENT_BINARY_DIR}/libsinsp.pc @ONLY) +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/libsinsp.pc.in ${CMAKE_CURRENT_BINARY_DIR}/libsinsp.pc @ONLY +) diff --git a/userspace/libsinsp/async/async_key_value_source.h b/userspace/libsinsp/async/async_key_value_source.h index c14ecd10a2..f82e29b9c5 100644 --- a/userspace/libsinsp/async/async_key_value_source.h +++ b/userspace/libsinsp/async/async_key_value_source.h @@ -28,8 +28,7 @@ limitations under the License. #include #include -namespace libsinsp -{ +namespace libsinsp { /** * Base class for classes that need to collect values asynchronously from some @@ -71,8 +70,7 @@ namespace libsinsp * operator=(). */ template -class async_key_value_source -{ +class async_key_value_source { public: /** * If provided to the constructor as max_wait_ms, then lookup will @@ -84,9 +82,7 @@ class async_key_value_source * A callback handler will take a key and a output reference to the * value. */ - typedef std::function - callback_handler; + typedef std::function callback_handler; /** * A ttl expired handler will take the expired key as argument. @@ -172,8 +168,7 @@ class async_key_value_source * @returns true if this method was able to lookup and return the * value synchronously; false otherwise. */ - bool lookup(const key_type& key, value_type& value, - const callback_handler& handler); + bool lookup(const key_type& key, value_type& value, const callback_handler& handler); /** * Lookup value(s) based on the given key. This method will block @@ -212,9 +207,10 @@ class async_key_value_source * @returns true if this method was able to lookup and return the * value synchronously; false otherwise. */ - bool lookup(const key_type& key, value_type& value, - const callback_handler& handler, - const ttl_expired_handler& ttl_expired); + bool lookup(const key_type& key, + value_type& value, + const callback_handler& handler, + const ttl_expired_handler& ttl_expired); /** * Lookup a value based on the specified key, after an initial delay. @@ -224,10 +220,10 @@ class async_key_value_source * @see lookup() for details */ bool lookup_delayed(const key_type& key, - value_type& value, - std::chrono::milliseconds delay, - const callback_handler& handler = callback_handler(), - const ttl_expired_handler& ttl_expired = ttl_expired_handler()); + value_type& value, + std::chrono::milliseconds delay, + const callback_handler& handler = callback_handler(), + const ttl_expired_handler& ttl_expired = ttl_expired_handler()); /** * Determines if the async thread associated with this @@ -319,9 +315,7 @@ class async_key_value_source * If value_ptr is non-NULL, the contents will be saved and provided * to the next call of dequeue_next_key(). */ - void defer_lookup(const key_type& key, - value_type* value_ptr, - std::chrono::milliseconds delay); + void defer_lookup(const key_type& key, value_type* value_ptr, std::chrono::milliseconds delay); /** * Concrete subclasses must override this method to perform the @@ -350,23 +344,20 @@ class async_key_value_source /** * Holds information associated with a single lookup() request. */ - struct lookup_request - { + struct lookup_request { lookup_request(): - m_available(false), - m_value(), - m_available_condition(), - m_callback(), - m_start_time(std::chrono::steady_clock::now()) - { } - - lookup_request(const lookup_request& rhs) : - m_available(rhs.m_available), - m_value(rhs.m_value), - m_available_condition(/*not rhs*/), - m_callback(rhs.m_callback), - m_start_time(rhs.m_start_time) - { } + m_available(false), + m_value(), + m_available_condition(), + m_callback(), + m_start_time(std::chrono::steady_clock::now()) {} + + lookup_request(const lookup_request& rhs): + m_available(rhs.m_available), + m_value(rhs.m_value), + m_available_condition(/*not rhs*/), + m_callback(rhs.m_callback), + m_start_time(rhs.m_start_time) {} /** Is the value here available? */ bool m_available; @@ -389,7 +380,6 @@ class async_key_value_source */ ttl_expired_handler m_ttl_callback; - /** The time at which this request was made. */ std::chrono::time_point m_start_time; }; @@ -427,12 +417,12 @@ class async_key_value_source std::condition_variable m_queue_not_empty_condition; using queue_item_t = std::pair, key_type>; - std::priority_queue, std::greater> m_request_queue; + std::priority_queue, std::greater> + m_request_queue; std::set m_request_set; value_map m_value_map; }; - -} // end namespace libsinsp +} // end namespace libsinsp #include diff --git a/userspace/libsinsp/base64.h b/userspace/libsinsp/base64.h index 2627c3c45c..4c87570866 100644 --- a/userspace/libsinsp/base64.h +++ b/userspace/libsinsp/base64.h @@ -22,29 +22,40 @@ #include #include -class Base64 -{ +class Base64 { public: - template static inline void encode(const char* input, uint64_t length, bool add_padding, Out& ret); + template + static inline void encode(const char* input, uint64_t length, bool add_padding, Out& ret); - template static inline bool decodeWithoutPadding(std::string_view input, Out& ret); + template + static inline bool decodeWithoutPadding(std::string_view input, Out& ret); private: template - static inline bool decodeBase(const uint8_t cur_char, uint64_t pos, Out& ret, - const unsigned char* const reverse_lookup_table); + static inline bool decodeBase(const uint8_t cur_char, + uint64_t pos, + Out& ret, + const unsigned char* const reverse_lookup_table); template - static inline bool decodeLast(const uint8_t cur_char, uint64_t pos, Out& ret, - const unsigned char* const reverse_lookup_table); + static inline bool decodeLast(const uint8_t cur_char, + uint64_t pos, + Out& ret, + const unsigned char* const reverse_lookup_table); template - static inline void encodeBase(const uint8_t cur_char, uint64_t pos, uint8_t& next_c, Out& ret, - const char* const char_table); + static inline void encodeBase(const uint8_t cur_char, + uint64_t pos, + uint8_t& next_c, + Out& ret, + const char* const char_table); template - static inline void encodeLast(uint64_t pos, uint8_t last_char, Out& ret, const char* const char_table, - bool add_padding); + static inline void encodeLast(uint64_t pos, + uint8_t last_char, + Out& ret, + const char* const char_table, + bool add_padding); // clang-format off static inline constexpr char CHAR_TABLE[] = @@ -66,17 +77,17 @@ class Base64 }; template -bool Base64::decodeBase(const uint8_t cur_char, uint64_t pos, Out& ret, const unsigned char* const reverse_lookup_table) -{ +bool Base64::decodeBase(const uint8_t cur_char, + uint64_t pos, + Out& ret, + const unsigned char* const reverse_lookup_table) { const unsigned char c = reverse_lookup_table[static_cast(cur_char)]; - if(c == 64) - { + if(c == 64) { // Invalid character return false; } - switch(pos % 4) - { + switch(pos % 4) { case 0: ret.push_back(c << 2); break; @@ -96,17 +107,17 @@ bool Base64::decodeBase(const uint8_t cur_char, uint64_t pos, Out& ret, const un } template -bool Base64::decodeLast(const uint8_t cur_char, uint64_t pos, Out& ret, const unsigned char* const reverse_lookup_table) -{ +bool Base64::decodeLast(const uint8_t cur_char, + uint64_t pos, + Out& ret, + const unsigned char* const reverse_lookup_table) { const unsigned char c = reverse_lookup_table[static_cast(cur_char)]; - if(c == 64) - { + if(c == 64) { // Invalid character return false; } - switch(pos % 4) - { + switch(pos % 4) { case 0: return false; case 1: @@ -123,10 +134,12 @@ bool Base64::decodeLast(const uint8_t cur_char, uint64_t pos, Out& ret, const un } template -void Base64::encodeBase(const uint8_t cur_char, uint64_t pos, uint8_t& next_c, Out& ret, const char* const char_table) -{ - switch(pos % 3) - { +void Base64::encodeBase(const uint8_t cur_char, + uint64_t pos, + uint8_t& next_c, + Out& ret, + const char* const char_table) { + switch(pos % 3) { case 0: ret.push_back(char_table[cur_char >> 2]); next_c = (cur_char & 0x03) << 4; @@ -144,22 +157,22 @@ void Base64::encodeBase(const uint8_t cur_char, uint64_t pos, uint8_t& next_c, O } template -void Base64::encodeLast(uint64_t pos, uint8_t last_char, Out& ret, const char* const char_table, bool add_padding) -{ - switch(pos % 3) - { +void Base64::encodeLast(uint64_t pos, + uint8_t last_char, + Out& ret, + const char* const char_table, + bool add_padding) { + switch(pos % 3) { case 1: ret.push_back(char_table[last_char]); - if(add_padding) - { + if(add_padding) { ret.push_back('='); ret.push_back('='); } break; case 2: ret.push_back(char_table[last_char]); - if(add_padding) - { + if(add_padding) { ret.push_back('='); } break; @@ -168,8 +181,8 @@ void Base64::encodeLast(uint64_t pos, uint8_t last_char, Out& ret, const char* c } } -template void Base64::encode(const char* input, uint64_t length, bool add_padding, Out& ret) -{ +template +void Base64::encode(const char* input, uint64_t length, bool add_padding, Out& ret) { uint64_t output_length = (length + 2) / 3 * 4; ret.clear(); ret.reserve(output_length); @@ -177,29 +190,25 @@ template void Base64::encode(const char* input, uint64_t length, bool uint64_t pos = 0; uint8_t next_c = 0; - for(uint64_t i = 0; i < length; ++i) - { + for(uint64_t i = 0; i < length; ++i) { encodeBase(input[i], pos++, next_c, ret, CHAR_TABLE); } encodeLast(pos, next_c, ret, CHAR_TABLE, add_padding); } -template bool Base64::decodeWithoutPadding(std::string_view input, Out& ret) -{ +template +bool Base64::decodeWithoutPadding(std::string_view input, Out& ret) { ret.clear(); - if(input.empty()) - { + if(input.empty()) { return true; } // At most last two chars can be '='. size_t n = input.length(); - if(input[n - 1] == '=') - { + if(input[n - 1] == '=') { n--; - if(n > 0 && input[n - 1] == '=') - { + if(n > 0 && input[n - 1] == '=') { n--; } } @@ -207,26 +216,21 @@ template bool Base64::decodeWithoutPadding(std::string_view input, Ou uint64_t last = n - 1; // Determine output length. size_t max_length = (n + 3) / 4 * 3; - if(n % 4 == 3) - { + if(n % 4 == 3) { max_length -= 1; } - if(n % 4 == 2) - { + if(n % 4 == 2) { max_length -= 2; } ret.reserve(max_length); - for(uint64_t i = 0; i < last; ++i) - { - if(!decodeBase(input[i], i, ret, REVERSE_LOOKUP_TABLE)) - { + for(uint64_t i = 0; i < last; ++i) { + if(!decodeBase(input[i], i, ret, REVERSE_LOOKUP_TABLE)) { return false; } } - if(!decodeLast(input[last], last, ret, REVERSE_LOOKUP_TABLE)) - { + if(!decodeLast(input[last], last, ret, REVERSE_LOOKUP_TABLE)) { return false; } diff --git a/userspace/libsinsp/capture_stats_source.h b/userspace/libsinsp/capture_stats_source.h index 38000a995b..cdd0d75866 100644 --- a/userspace/libsinsp/capture_stats_source.h +++ b/userspace/libsinsp/capture_stats_source.h @@ -32,8 +32,7 @@ struct scap_stats; * not add additional APIs here. If some client of sinsp needs a different * set of APIs, introduce a new interface. */ -class SINSP_PUBLIC capture_stats_source -{ +class SINSP_PUBLIC capture_stats_source { public: virtual ~capture_stats_source() = default; @@ -62,5 +61,7 @@ class SINSP_PUBLIC capture_stats_source * * @return Pointer to a \ref metrics_v2 structure filled with the libscap stats. */ - virtual const struct metrics_v2* get_capture_stats_v2(uint32_t flags, uint32_t* nstats, int32_t* rc) const = 0; + virtual const struct metrics_v2* get_capture_stats_v2(uint32_t flags, + uint32_t* nstats, + int32_t* rc) const = 0; }; diff --git a/userspace/libsinsp/cgroup_limits.cpp b/userspace/libsinsp/cgroup_limits.cpp index 4e79ecc633..b0246c852c 100644 --- a/userspace/libsinsp/cgroup_limits.cpp +++ b/userspace/libsinsp/cgroup_limits.cpp @@ -8,53 +8,51 @@ namespace { // to prevent 32-bit number of kilobytes from overflowing, ignore values larger than 4 TiB. // This reports extremely large values (e.g. almost-but-not-quite 9EiB as set by k8s) as unlimited. -// Note: we use the same maximum value for cpu shares/quotas as well; the typical values are much lower -// and so should never exceed CGROUP_VAL_MAX either +// Note: we use the same maximum value for cpu shares/quotas as well; the typical values are much +// lower and so should never exceed CGROUP_VAL_MAX either constexpr const int64_t CGROUP_VAL_MAX = (1ULL << 42u) - 1; -bool read_one_cgroup_val(const std::string &path, std::istream &stream, int64_t &out) -{ +bool read_one_cgroup_val(const std::string &path, std::istream &stream, int64_t &out) { std::string str_val; int64_t val = -1; stream >> str_val; - if(str_val == "max") - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "(cgroup-limits) value of %s is set to max, ignoring", - path.c_str(), val); + if(str_val == "max") { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "(cgroup-limits) value of %s is set to max, ignoring", + path.c_str(), + val); return false; } - try - { + try { val = std::stoll(str_val); - } - catch(const std::exception &e) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "(cgroup-limits) Cannot convert value of %s (%s) to an integer, ignoring", - path.c_str(), str_val.c_str()); + } catch(const std::exception &e) { + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "(cgroup-limits) Cannot convert value of %s (%s) to an integer, ignoring", + path.c_str(), + str_val.c_str()); return false; } - if(val <= 0 || val > CGROUP_VAL_MAX) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "(cgroup-limits) value of %s (%lld) out of range, ignoring", - path.c_str(), val); + if(val <= 0 || val > CGROUP_VAL_MAX) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "(cgroup-limits) value of %s (%lld) out of range, ignoring", + path.c_str(), + val); return false; } out = val; return true; } -bool read_cgroup_vals(const std::string &path, std::istream &stream) -{ +bool read_cgroup_vals(const std::string &path, std::istream &stream) { return true; } template -bool read_cgroup_vals(const std::string &path, std::istream &stream, int64_t &out, Args... args) -{ +bool read_cgroup_vals(const std::string &path, std::istream &stream, int64_t &out, Args... args) { return read_one_cgroup_val(path, stream, out) && read_cgroup_vals(path, stream, args...); } @@ -69,11 +67,10 @@ bool read_cgroup_vals(const std::string &path, std::istream &stream, int64_t &ou */ template bool read_cgroup_val(const std::shared_ptr &subsys, - const std::string &cgroup, - const std::string &filename, - int64_t &out, - Args... args) -{ + const std::string &cgroup, + const std::string &filename, + int64_t &out, + Args... args) { std::string path = *subsys + "/" + cgroup + "/" + filename; std::ifstream fs(path); @@ -83,121 +80,152 @@ bool read_cgroup_val(const std::shared_ptr &subsys, /** * Read from a cpuset file to get the number of cpus in the cpuset */ -bool read_cgroup_list_count(const std::string& subsys, - const std::string& cgroup, - const std::string& filename, - int32_t& out) -{ +bool read_cgroup_list_count(const std::string &subsys, + const std::string &cgroup, + const std::string &filename, + int32_t &out) { std::string path = subsys + "/" + cgroup + "/" + filename; std::ifstream cg_val(path); - if(!cg_val) - { + if(!cg_val) { return false; } - std::string cpuset_cpus((std::istreambuf_iterator(cg_val)), - std::istreambuf_iterator()); + std::string cpuset_cpus((std::istreambuf_iterator(cg_val)), + std::istreambuf_iterator()); - if(cpuset_cpus.empty()) - { + if(cpuset_cpus.empty()) { return false; } // Is the file just whitespace? - if (cpuset_cpus.find_last_not_of(" \r\t\n") == std::string::npos) - { + if(cpuset_cpus.find_last_not_of(" \r\t\n") == std::string::npos) { return false; } - libsinsp::cgroup_list_counter counter; + libsinsp::cgroup_list_counter counter; out = counter(cpuset_cpus.c_str()); libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "(cgroup-limits) Pulling cpu set from %s: %s = %d", - path.c_str(), - cpuset_cpus.c_str(), - out); + "(cgroup-limits) Pulling cpu set from %s: %s = %d", + path.c_str(), + cpuset_cpus.c_str(), + out); - return (out > 0); + return (out > 0); } -} +} // namespace namespace libsinsp { namespace cgroup_limits { -bool get_cgroup_resource_limits(const cgroup_limits_key& key, cgroup_limits_value& value, bool name_check) -{ - sinsp_cgroup& cgroups = sinsp_cgroup::instance(); +bool get_cgroup_resource_limits(const cgroup_limits_key &key, + cgroup_limits_value &value, + bool name_check) { + sinsp_cgroup &cgroups = sinsp_cgroup::instance(); bool found_all = true; int memcg_version; std::shared_ptr memcg_root = cgroups.lookup_cgroup_dir("memory", memcg_version); - if(name_check && key.m_mem_cgroup.find(key.m_container_id) == std::string::npos) - { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "(cgroup-limits) mem cgroup for container [%s]: %s/%s -- no per-container memory cgroup, ignoring", - key.m_container_id.c_str(), memcg_root->c_str(), key.m_mem_cgroup.c_str()); - } - else - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "(cgroup-limits) mem cgroup for container [%s]: %s/%s", - key.m_container_id.c_str(), memcg_root->c_str(), key.m_mem_cgroup.c_str()); + if(name_check && key.m_mem_cgroup.find(key.m_container_id) == std::string::npos) { + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "(cgroup-limits) mem cgroup for container [%s]: %s/%s -- no " + "per-container memory cgroup, ignoring", + key.m_container_id.c_str(), + memcg_root->c_str(), + key.m_mem_cgroup.c_str()); + } else { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "(cgroup-limits) mem cgroup for container [%s]: %s/%s", + key.m_container_id.c_str(), + memcg_root->c_str(), + key.m_mem_cgroup.c_str()); const char *filename = memcg_version == 2 ? "memory.max" : "memory.limit_in_bytes"; - found_all = read_cgroup_val(memcg_root, key.m_mem_cgroup, filename, value.m_memory_limit) && found_all; + found_all = read_cgroup_val(memcg_root, key.m_mem_cgroup, filename, value.m_memory_limit) && + found_all; } int cpu_version; std::shared_ptr cpucg_root = cgroups.lookup_cgroup_dir("cpu", cpu_version); - if(name_check && key.m_cpu_cgroup.find(key.m_container_id) == std::string::npos) - { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "(cgroup-limits) cpu cgroup for container [%s]: %s/%s -- no per-container CPU cgroup, ignoring", - key.m_container_id.c_str(), cpucg_root->c_str(), key.m_cpu_cgroup.c_str()); - } - else - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "(cgroup-limits) cpu cgroup for container [%s]: %s/%s", - key.m_container_id.c_str(), cpucg_root->c_str(), key.m_cpu_cgroup.c_str()); - if(cpu_version == 2) - { - found_all = read_cgroup_val(cpucg_root, key.m_cpu_cgroup, "cpu.weight", value.m_cpu_shares) && - found_all; - found_all = read_cgroup_val(cpucg_root, key.m_cpu_cgroup, "cpu.max", value.m_cpu_quota, - value.m_cpu_period) && - found_all; - } - else - { - found_all = read_cgroup_val(cpucg_root, key.m_cpu_cgroup, "cpu.shares", value.m_cpu_shares) && found_all; - found_all = read_cgroup_val(cpucg_root, key.m_cpu_cgroup, "cpu.cfs_quota_us", value.m_cpu_quota) && found_all; - found_all = read_cgroup_val(cpucg_root, key.m_cpu_cgroup, "cpu.cfs_period_us", value.m_cpu_period) && found_all; + if(name_check && key.m_cpu_cgroup.find(key.m_container_id) == std::string::npos) { + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "(cgroup-limits) cpu cgroup for container [%s]: %s/%s -- no " + "per-container CPU cgroup, ignoring", + key.m_container_id.c_str(), + cpucg_root->c_str(), + key.m_cpu_cgroup.c_str()); + } else { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "(cgroup-limits) cpu cgroup for container [%s]: %s/%s", + key.m_container_id.c_str(), + cpucg_root->c_str(), + key.m_cpu_cgroup.c_str()); + if(cpu_version == 2) { + found_all = read_cgroup_val(cpucg_root, + key.m_cpu_cgroup, + "cpu.weight", + value.m_cpu_shares) && + found_all; + found_all = read_cgroup_val(cpucg_root, + key.m_cpu_cgroup, + "cpu.max", + value.m_cpu_quota, + value.m_cpu_period) && + found_all; + } else { + found_all = read_cgroup_val(cpucg_root, + key.m_cpu_cgroup, + "cpu.shares", + value.m_cpu_shares) && + found_all; + found_all = read_cgroup_val(cpucg_root, + key.m_cpu_cgroup, + "cpu.cfs_quota_us", + value.m_cpu_quota) && + found_all; + found_all = read_cgroup_val(cpucg_root, + key.m_cpu_cgroup, + "cpu.cfs_period_us", + value.m_cpu_period) && + found_all; } } int cpuset_version; std::shared_ptr cpuset_root = cgroups.lookup_cgroup_dir("cpuset", cpuset_version); - if(name_check && key.m_cpuset_cgroup.find(key.m_container_id) == std::string::npos) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "(cgroup-limits) cpuset cgroup for container [%s]: %s/%s -- no per-container cpuset cgroup, ignoring", - key.m_container_id.c_str(), cpuset_root->c_str(), key.m_cpuset_cgroup.c_str()); - } - else - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "(cgroup-limits) cpuset cgroup for container [%s]: %s/%s", - key.m_container_id.c_str(), cpuset_root->c_str(), key.m_cpuset_cgroup.c_str()); + if(name_check && key.m_cpuset_cgroup.find(key.m_container_id) == std::string::npos) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "(cgroup-limits) cpuset cgroup for container [%s]: %s/%s -- no " + "per-container cpuset cgroup, ignoring", + key.m_container_id.c_str(), + cpuset_root->c_str(), + key.m_cpuset_cgroup.c_str()); + } else { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "(cgroup-limits) cpuset cgroup for container [%s]: %s/%s", + key.m_container_id.c_str(), + cpuset_root->c_str(), + key.m_cpuset_cgroup.c_str()); found_all = read_cgroup_list_count(*cpuset_root, - key.m_cpuset_cgroup, - "cpuset.cpus", - value.m_cpuset_cpu_count) && found_all; + key.m_cpuset_cgroup, + "cpuset.cpus", + value.m_cpuset_cpu_count) && + found_all; } - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "(cgroup-limits) Got cgroup limits for container [%s]: " - "mem_limit=%ld, cpu_shares=%ld cpu_quota=%ld cpu_period=%ld cpuset_cpu_count=%d", - key.m_container_id.c_str(), - value.m_memory_limit, value.m_cpu_shares, value.m_cpu_quota, value.m_cpu_period, value.m_cpuset_cpu_count); + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "(cgroup-limits) Got cgroup limits for container [%s]: " + "mem_limit=%ld, cpu_shares=%ld cpu_quota=%ld cpu_period=%ld cpuset_cpu_count=%d", + key.m_container_id.c_str(), + value.m_memory_limit, + value.m_cpu_shares, + value.m_cpu_quota, + value.m_cpu_period, + value.m_cpuset_cpu_count); return found_all; } -} -} +} // namespace cgroup_limits +} // namespace libsinsp diff --git a/userspace/libsinsp/cgroup_limits.h b/userspace/libsinsp/cgroup_limits.h index c3f37658d4..50eb930d8b 100644 --- a/userspace/libsinsp/cgroup_limits.h +++ b/userspace/libsinsp/cgroup_limits.h @@ -5,23 +5,17 @@ #include namespace { -bool less_than(const std::string& lhs, const std::string& rhs, bool if_equal=false) -{ +bool less_than(const std::string& lhs, const std::string& rhs, bool if_equal = false) { int cmp = lhs.compare(rhs); - if(cmp < 0) - { + if(cmp < 0) { return true; - } - else if(cmp > 0) - { + } else if(cmp > 0) { return false; - } - else - { + } else { return if_equal; } } -} +} // namespace namespace libsinsp { namespace cgroup_limits { @@ -36,34 +30,30 @@ struct cgroup_limits_key { cgroup_limits_key() {} cgroup_limits_key(std::string container_id, - std::string cpu_cgroup_dir, - std::string mem_cgroup_dir, - std::string cpuset_cgroup_dir) : - m_container_id(std::move(container_id)), - m_cpu_cgroup(std::move(cpu_cgroup_dir)), - m_mem_cgroup(std::move(mem_cgroup_dir)), - m_cpuset_cgroup(std::move(cpuset_cgroup_dir)) { } + std::string cpu_cgroup_dir, + std::string mem_cgroup_dir, + std::string cpuset_cgroup_dir): + m_container_id(std::move(container_id)), + m_cpu_cgroup(std::move(cpu_cgroup_dir)), + m_mem_cgroup(std::move(mem_cgroup_dir)), + m_cpuset_cgroup(std::move(cpuset_cgroup_dir)) {} - bool operator<(const cgroup_limits_key& rhs) const - { - return less_than(m_container_id, rhs.m_container_id, - less_than(m_cpu_cgroup, rhs.m_cpu_cgroup, - less_than(m_mem_cgroup, rhs.m_mem_cgroup, - less_than(m_cpuset_cgroup, rhs.m_cpuset_cgroup)))); + bool operator<(const cgroup_limits_key& rhs) const { + return less_than(m_container_id, + rhs.m_container_id, + less_than(m_cpu_cgroup, + rhs.m_cpu_cgroup, + less_than(m_mem_cgroup, + rhs.m_mem_cgroup, + less_than(m_cpuset_cgroup, rhs.m_cpuset_cgroup)))); } - bool operator==(const cgroup_limits_key& rhs) const - { - return m_container_id == rhs.m_container_id && - m_cpu_cgroup == rhs.m_cpu_cgroup && - m_mem_cgroup == rhs.m_mem_cgroup && - m_cpuset_cgroup == rhs.m_cpuset_cgroup; + bool operator==(const cgroup_limits_key& rhs) const { + return m_container_id == rhs.m_container_id && m_cpu_cgroup == rhs.m_cpu_cgroup && + m_mem_cgroup == rhs.m_mem_cgroup && m_cpuset_cgroup == rhs.m_cpuset_cgroup; } - explicit operator const std::string&() const - { - return m_container_id; - } + explicit operator const std::string&() const { return m_container_id; } std::string m_container_id; std::string m_cpu_cgroup; @@ -77,12 +67,12 @@ struct cgroup_limits_key { * This contains all the cgroup values we read during the asynchronous lookup */ struct cgroup_limits_value { - cgroup_limits_value() : - m_cpu_shares(0), - m_cpu_quota(0), - m_cpu_period(0), - m_memory_limit(0), - m_cpuset_cpu_count(0) {} + cgroup_limits_value(): + m_cpu_shares(0), + m_cpu_quota(0), + m_cpu_period(0), + m_memory_limit(0), + m_cpuset_cpu_count(0) {} int64_t m_cpu_shares; int64_t m_cpu_quota; @@ -108,10 +98,12 @@ struct cgroup_limits_value { * in the future", while `true` means we really don't expect them to change * any more. */ -bool get_cgroup_resource_limits(const cgroup_limits_key& key, cgroup_limits_value& value, bool name_check = true); +bool get_cgroup_resource_limits(const cgroup_limits_key& key, + cgroup_limits_value& value, + bool name_check = true); -} -} +} // namespace cgroup_limits +} // namespace libsinsp namespace std { /** @@ -119,7 +111,8 @@ namespace std { * * It allows `cgroup_limits_key` instances to be used as `unordered_map` keys */ -template<> struct hash { +template<> +struct hash { std::size_t operator()(const libsinsp::cgroup_limits::cgroup_limits_key& h) const { size_t h1 = ::std::hash{}(h.m_container_id); size_t h2 = ::std::hash{}(h.m_cpu_cgroup); @@ -128,4 +121,4 @@ template<> struct hash { return h1 ^ (h2 << 1u) ^ (h3 << 2u) ^ (h4 << 3u); } }; -} \ No newline at end of file +} // namespace std diff --git a/userspace/libsinsp/cgroup_list_counter.h b/userspace/libsinsp/cgroup_list_counter.h index 93ec3e2a5a..fae6465efd 100644 --- a/userspace/libsinsp/cgroup_list_counter.h +++ b/userspace/libsinsp/cgroup_list_counter.h @@ -3,8 +3,7 @@ #include #include -namespace libsinsp -{ +namespace libsinsp { /** * Simple helper to read a comma-separated list that includes ranges and @@ -16,8 +15,7 @@ namespace libsinsp * * Returns -1 if string is invalid. */ -class cgroup_list_counter -{ +class cgroup_list_counter { public: const int INVALID_CPU_COUNT = -1; @@ -25,53 +23,40 @@ class cgroup_list_counter * Return the number of elements given by the buffer. If needed, log at the * given log-level. */ - int operator ()(const char *buffer) - { + int operator()(const char *buffer) { reset(); int cpu_count = 0; - try - { + try { const char *position = buffer; - for(; '\0' != *position; ++position) - { - if ('-' == *position) - { - if (nullptr == m_section_start) - { + for(; '\0' != *position; ++position) { + if('-' == *position) { + if(nullptr == m_section_start) { throw std::runtime_error("duplicate range indicator before start"); } - if (nullptr != m_range_indicator) - { + if(nullptr != m_range_indicator) { throw std::runtime_error("duplicate range indicators"); } m_range_indicator = position; - } - else if (',' == *position) - { + } else if(',' == *position) { cpu_count += process_section(m_section_start, position, m_range_indicator); reset(); - } - else if (nullptr == m_section_start) - { + } else if(nullptr == m_section_start) { m_section_start = position; } - } // There is never a trailing comma so always process the // final section cpu_count += process_section(m_section_start, position, m_range_indicator); - } - catch (const std::exception& ex) - { + } catch(const std::exception &ex) { libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "Invalid List Format: %s. Detail: %s", - buffer, - ex.what()); + "Invalid List Format: %s. Detail: %s", + buffer, + ex.what()); return INVALID_CPU_COUNT; } @@ -79,39 +64,32 @@ class cgroup_list_counter } private: - - static int process_number(const char *section_start, const char *section_end) - { + static int process_number(const char *section_start, const char *section_end) { std::string section(section_start, section_end - section_start); return std::stoi(section.c_str()); - } - static int process_section(const char *section_start, const char *section_end, const char *range_indicator) - { - if (nullptr == section_start) - { + static int process_section(const char *section_start, + const char *section_end, + const char *range_indicator) { + if(nullptr == section_start) { throw std::runtime_error("invalid end of section before start of section"); } - if (nullptr == section_end) - { + if(nullptr == section_end) { throw std::runtime_error("invalid end of section"); } - if (section_end <= section_start) - { + if(section_end <= section_start) { throw std::runtime_error("invalid section"); } - if (range_indicator) - { + if(range_indicator) { // Split into two sections int first = process_number(section_start, range_indicator); int second = process_number(range_indicator + 1, section_end); - if (second <= first) - { + if(second <= first) { throw std::runtime_error("invalid range"); } @@ -123,8 +101,7 @@ class cgroup_list_counter return 1; } - void reset() - { + void reset() { m_section_start = nullptr; m_range_indicator = nullptr; } @@ -133,4 +110,4 @@ class cgroup_list_counter const char *m_range_indicator = nullptr; }; -} +} // namespace libsinsp diff --git a/userspace/libsinsp/container.cpp b/userspace/libsinsp/container.cpp index 62b0239eac..31d2655569 100644 --- a/userspace/libsinsp/container.cpp +++ b/userspace/libsinsp/container.cpp @@ -30,7 +30,7 @@ limitations under the License. #include #include #include -#endif // MINIMAL_BUILD +#endif // MINIMAL_BUILD #include #include @@ -41,34 +41,29 @@ limitations under the License. using namespace libsinsp; -sinsp_container_manager::sinsp_container_manager(sinsp* inspector) : - m_last_flush_time_ns(0), - m_inspector(inspector), - m_static_container(false), - m_container_engine_mask(~0ULL) -{ - if (m_inspector != nullptr) - { +sinsp_container_manager::sinsp_container_manager(sinsp* inspector): + m_last_flush_time_ns(0), + m_inspector(inspector), + m_static_container(false), + m_container_engine_mask(~0ULL) { + if(m_inspector != nullptr) { m_sinsp_stats_v2 = m_inspector->get_sinsp_stats_v2(); - } - else - { + } else { m_sinsp_stats_v2 = nullptr; } } -bool sinsp_container_manager::remove_inactive_containers() -{ +bool sinsp_container_manager::remove_inactive_containers() { bool res = false; - if(m_last_flush_time_ns == 0) - { - m_last_flush_time_ns = m_inspector->get_lastevent_ts() - m_inspector->m_containers_purging_scan_time_ns + 30 * ONE_SECOND_IN_NS; + if(m_last_flush_time_ns == 0) { + m_last_flush_time_ns = m_inspector->get_lastevent_ts() - + m_inspector->m_containers_purging_scan_time_ns + + 30 * ONE_SECOND_IN_NS; } if(m_inspector->get_lastevent_ts() > - m_last_flush_time_ns + m_inspector->m_containers_purging_scan_time_ns) - { + m_last_flush_time_ns + m_inspector->m_containers_purging_scan_time_ns) { res = true; m_last_flush_time_ns = m_inspector->get_lastevent_ts(); @@ -79,43 +74,35 @@ bool sinsp_container_manager::remove_inactive_containers() threadinfo_map_t* threadtable = m_inspector->m_thread_manager->get_threads(); - threadtable->loop([&] (const sinsp_threadinfo& tinfo) { - if(!tinfo.m_container_id.empty()) - { + threadtable->loop([&](const sinsp_threadinfo& tinfo) { + if(!tinfo.m_container_id.empty()) { containers_in_use.insert(tinfo.m_container_id); } return true; }); auto containers = m_containers.lock(); - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_missing_container_images = 0; // Will include pod sanboxes, but that's ok m_sinsp_stats_v2->m_n_containers = containers->size(); } - for(auto it = containers->begin(); it != containers->end();) - { + for(auto it = containers->begin(); it != containers->end();) { sinsp_container_info::ptr_t container = it->second; - if (m_sinsp_stats_v2) - { + if(m_sinsp_stats_v2) { auto container_info = container.get(); - if (!container_info || (container_info && !container_info->m_is_pod_sandbox && container_info->m_image.empty())) - { + if(!container_info || (container_info && !container_info->m_is_pod_sandbox && + container_info->m_image.empty())) { // Only count missing container images and exclude sandboxes m_sinsp_stats_v2->m_n_missing_container_images++; } } - if(containers_in_use.find(it->first) == containers_in_use.end()) - { - for(const auto &remove_cb : m_remove_callbacks) - { + if(containers_in_use.find(it->first) == containers_in_use.end()) { + for(const auto& remove_cb : m_remove_callbacks) { remove_cb(*container); } containers->erase(it++); - } - else - { + } else { ++it; } } @@ -124,41 +111,38 @@ bool sinsp_container_manager::remove_inactive_containers() return res; } -sinsp_container_info::ptr_t sinsp_container_manager::get_container(const std::string& container_id) const -{ +sinsp_container_info::ptr_t sinsp_container_manager::get_container( + const std::string& container_id) const { auto containers = m_containers.lock(); auto it = containers->find(container_id); - if(it != containers->end()) - { + if(it != containers->end()) { return it->second; } return nullptr; } -bool sinsp_container_manager::resolve_container(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) -{ +bool sinsp_container_manager::resolve_container(sinsp_threadinfo* tinfo, + bool query_os_for_missing_info) { ASSERT(tinfo); bool matches = false; tinfo->m_container_id = ""; - if(m_inspector->get_observer()) - { - matches = m_inspector->get_observer()->on_resolve_container(this, tinfo, query_os_for_missing_info); + if(m_inspector->get_observer()) { + matches = m_inspector->get_observer()->on_resolve_container(this, + tinfo, + query_os_for_missing_info); } // Delayed so there's a chance to set alternate socket paths, // timeouts, after creation but before inspector open. - if(m_container_engines.empty()) - { + if(m_container_engines.empty()) { create_engines(); } - for(auto &eng : m_container_engines) - { + for(auto& eng : m_container_engines) { matches = matches || eng->resolve(tinfo, query_os_for_missing_info); - if(matches) - { + if(matches) { break; } } @@ -169,8 +153,7 @@ bool sinsp_container_manager::resolve_container(sinsp_threadinfo* tinfo, bool qu return matches; } -std::string sinsp_container_manager::container_to_json(const sinsp_container_info& container_info) -{ +std::string sinsp_container_manager::container_to_json(const sinsp_container_info& container_info) { Json::Value obj; Json::Value& container = obj["container"]; container["id"] = container_info.m_id; @@ -189,8 +172,7 @@ std::string sinsp_container_manager::container_to_json(const sinsp_container_inf Json::Value mounts = Json::arrayValue; - for (auto &mntinfo : container_info.m_mounts) - { + for(auto& mntinfo : container_info.m_mounts) { Json::Value mount; mount["Source"] = mntinfo.m_source; @@ -206,7 +188,8 @@ std::string sinsp_container_manager::container_to_json(const sinsp_container_inf container["User"] = container_info.m_container_user; - sinsp_container_info::container_health_probe::add_health_probes(container_info.m_health_probes, container); + sinsp_container_info::container_health_probe::add_health_probes(container_info.m_health_probes, + container); char addrbuff[100]; uint32_t iph = htonl(container_info.m_container_ip); @@ -218,8 +201,7 @@ std::string sinsp_container_manager::container_to_json(const sinsp_container_inf Json::Value port_mappings = Json::arrayValue; - for(auto &mapping : container_info.m_port_mappings) - { + for(auto& mapping : container_info.m_port_mappings) { Json::Value jmap; jmap["HostIp"] = mapping.m_host_ip; jmap["HostPort"] = mapping.m_host_port; @@ -231,58 +213,54 @@ std::string sinsp_container_manager::container_to_json(const sinsp_container_inf container["port_mappings"] = port_mappings; Json::Value labels; - for (auto &pair : container_info.m_labels) - { + for(auto& pair : container_info.m_labels) { labels[pair.first] = pair.second; } container["labels"] = labels; Json::Value pod_sandbox_labels; - for (auto &pair : container_info.m_pod_sandbox_labels) - { + for(auto& pair : container_info.m_pod_sandbox_labels) { pod_sandbox_labels[pair.first] = pair.second; } container["pod_sandbox_labels"] = pod_sandbox_labels; Json::Value env_vars = Json::arrayValue; - for (auto &var : container_info.m_env) - { + for(auto& var : container_info.m_env) { // Only append a limited set of mesos/marathon-related // environment variables. - if(var.find("MESOS") != std::string::npos || - var.find("MARATHON") != std::string::npos || - var.find("mesos") != std::string::npos) - { + if(var.find("MESOS") != std::string::npos || var.find("MARATHON") != std::string::npos || + var.find("mesos") != std::string::npos) { env_vars.append(var); } } container["env"] = env_vars; - container["memory_limit"] = (Json::Value::Int64) container_info.m_memory_limit; - container["swap_limit"] = (Json::Value::Int64) container_info.m_swap_limit; - container["cpu_shares"] = (Json::Value::Int64) container_info.m_cpu_shares; - container["cpu_quota"] = (Json::Value::Int64) container_info.m_cpu_quota; - container["cpu_period"] = (Json::Value::Int64) container_info.m_cpu_period; - container["cpuset_cpu_count"] = (Json::Value::Int) container_info.m_cpuset_cpu_count; + container["memory_limit"] = (Json::Value::Int64)container_info.m_memory_limit; + container["swap_limit"] = (Json::Value::Int64)container_info.m_swap_limit; + container["cpu_shares"] = (Json::Value::Int64)container_info.m_cpu_shares; + container["cpu_quota"] = (Json::Value::Int64)container_info.m_cpu_quota; + container["cpu_period"] = (Json::Value::Int64)container_info.m_cpu_period; + container["cpuset_cpu_count"] = (Json::Value::Int)container_info.m_cpuset_cpu_count; - if(!container_info.m_mesos_task_id.empty()) - { + if(!container_info.m_mesos_task_id.empty()) { container["mesos_task_id"] = container_info.m_mesos_task_id; } - container["metadata_deadline"] = (Json::Value::UInt64) container_info.m_metadata_deadline; + container["metadata_deadline"] = (Json::Value::UInt64)container_info.m_metadata_deadline; return Json::FastWriter().write(obj); } -bool sinsp_container_manager::container_to_sinsp_event(const std::string& json, sinsp_evt* evt, std::unique_ptr tinfo, char *scap_err) -{ +bool sinsp_container_manager::container_to_sinsp_event(const std::string& json, + sinsp_evt* evt, + std::unique_ptr tinfo, + char* scap_err) { uint32_t json_len = json.length() + 1; size_t totlen = sizeof(scap_evt) + sizeof(uint32_t) + json_len; ASSERT(evt->get_scap_evt_storage() == nullptr); evt->set_scap_evt_storage(new char[totlen]); - evt->set_scap_evt((scap_evt *) evt->get_scap_evt_storage()); + evt->set_scap_evt((scap_evt*)evt->get_scap_evt_storage()); evt->set_cpuid(0); evt->set_num(0); @@ -291,8 +269,12 @@ bool sinsp_container_manager::container_to_sinsp_event(const std::string& json, scap_evt* scapevt = evt->get_scap_evt(); scapevt->ts = UINT64_MAX; scapevt->tid = -1; - if (scap_event_encode_params(scap_sized_buffer{scapevt, totlen}, nullptr, scap_err, PPME_CONTAINER_JSON_2_E, 1, json.c_str()) != SCAP_SUCCESS) - { + if(scap_event_encode_params(scap_sized_buffer{scapevt, totlen}, + nullptr, + scap_err, + PPME_CONTAINER_JSON_2_E, + 1, + json.c_str()) != SCAP_SUCCESS) { return false; } @@ -304,37 +286,35 @@ bool sinsp_container_manager::container_to_sinsp_event(const std::string& json, return true; } -sinsp_container_manager::map_ptr_t sinsp_container_manager::get_containers() const -{ +sinsp_container_manager::map_ptr_t sinsp_container_manager::get_containers() const { return m_containers.lock(); } -void sinsp_container_manager::add_container(const sinsp_container_info::ptr_t& container_info, sinsp_threadinfo *thread) -{ - set_lookup_status(container_info->m_id, container_info->m_type, container_info->get_lookup_status()); +void sinsp_container_manager::add_container(const sinsp_container_info::ptr_t& container_info, + sinsp_threadinfo* thread) { + set_lookup_status(container_info->m_id, + container_info->m_type, + container_info->get_lookup_status()); { auto containers = m_containers.lock(); (*containers)[container_info->m_id] = container_info; } - for(const auto& new_cb : m_new_callbacks) - { + for(const auto& new_cb : m_new_callbacks) { new_cb(*container_info, thread); } } -void sinsp_container_manager::replace_container(const sinsp_container_info::ptr_t& container_info) -{ +void sinsp_container_manager::replace_container(const sinsp_container_info::ptr_t& container_info) { auto containers = m_containers.lock(); ASSERT(containers->find(container_info->m_id) != containers->end()); (*containers)[container_info->m_id] = container_info; } -void sinsp_container_manager::notify_new_container(const sinsp_container_info& container_info, sinsp_threadinfo *tinfo) -{ - if (!m_inspector->m_inited || m_inspector->is_offline()) - { +void sinsp_container_manager::notify_new_container(const sinsp_container_info& container_info, + sinsp_threadinfo* tinfo) { + if(!m_inspector->m_inited || m_inspector->is_offline()) { // This is either: // * being called from a threadinfo->resolve_container // before sinsp is actually started (ie: while parsing proc), @@ -343,27 +323,26 @@ void sinsp_container_manager::notify_new_container(const sinsp_container_info& c // * being called in capture mode (no need to send any event as we will read it) // // Fallback at just storing the new container. - // NOTE: this must be kept in sync with what happens on container event parsing, in parsers.cpp. + // NOTE: this must be kept in sync with what happens on container event parsing, in + // parsers.cpp. const auto container = m_inspector->m_container_manager.get_container(container_info.m_id); - if(container != nullptr && container->is_successful()) - { - SINSP_DEBUG("Ignoring new container notification for already successful lookup of %s", container_info.m_id.c_str()); - } - else - { + if(container != nullptr && container->is_successful()) { + SINSP_DEBUG("Ignoring new container notification for already successful lookup of %s", + container_info.m_id.c_str()); + } else { // We don't log any warning when the inspector // is doing its initial scan from /proc + any // container lookups. Those don't have // retries. - if(!container_info.is_successful() && m_inspector->m_inited) - { + if(!container_info.is_successful() && m_inspector->m_inited) { // This means that the container // engine made multiple attempts to // look up the info and all attempts // failed. Log that as a warning. libsinsp_logger()->format(sinsp_logger::SEV_WARNING, - "notify_new_container (%s): Saving empty container info after repeated failed lookups", - container_info.m_id.c_str()); + "notify_new_container (%s): Saving empty container info " + "after repeated failed lookups", + container_info.m_id.c_str()); } add_container(std::make_shared(container_info), tinfo); } @@ -377,70 +356,64 @@ void sinsp_container_manager::notify_new_container(const sinsp_container_info& c char scap_err[SCAP_LASTERR_SIZE]; - if(container_to_sinsp_event(container_to_json(container_info), evt.get(), container_info.get_tinfo(m_inspector), scap_err)) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "notify_new_container (%s): created CONTAINER_JSON event, queuing to inspector", - container_info.m_id.c_str()); + if(container_to_sinsp_event(container_to_json(container_info), + evt.get(), + container_info.get_tinfo(m_inspector), + scap_err)) { + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "notify_new_container (%s): created CONTAINER_JSON event, queuing to inspector", + container_info.m_id.c_str()); // Enqueue it onto the queue of pending container events for the inspector m_inspector->handle_async_event(std::move(evt)); - } - else - { - libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "notify_new_container (%s): could not create CONTAINER_JSON event: %s, dropping", - container_info.m_id.c_str(), - scap_err); + } else { + libsinsp_logger()->format( + sinsp_logger::SEV_ERROR, + "notify_new_container (%s): could not create CONTAINER_JSON event: %s, dropping", + container_info.m_id.c_str(), + scap_err); } } -bool sinsp_container_manager::async_allowed() const -{ +bool sinsp_container_manager::async_allowed() const { // Until sinsp is not started, force-run synchronously return m_inspector->m_inited; } -void sinsp_container_manager::dump_containers(sinsp_dumper& dumper) -{ +void sinsp_container_manager::dump_containers(sinsp_dumper& dumper) { char scap_err[SCAP_LASTERR_SIZE]; - for(const auto& it : (*m_containers.lock())) - { + for(const auto& it : (*m_containers.lock())) { sinsp_evt evt; - if(container_to_sinsp_event(container_to_json(*it.second), &evt, it.second->get_tinfo(m_inspector), scap_err)) - { + if(container_to_sinsp_event(container_to_json(*it.second), + &evt, + it.second->get_tinfo(m_inspector), + scap_err)) { evt.get_scap_evt()->ts = m_inspector->get_new_ts(); dumper.dump(&evt); - } - else - { - libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "dump_containers (%s): could not create CONTAINER_JSON event: %s, dropping", - scap_err, - it.second->m_id.c_str()); + } else { + libsinsp_logger()->format( + sinsp_logger::SEV_ERROR, + "dump_containers (%s): could not create CONTAINER_JSON event: %s, dropping", + scap_err, + it.second->m_id.c_str()); } } } -std::string sinsp_container_manager::get_container_name(sinsp_threadinfo* tinfo) const -{ +std::string sinsp_container_manager::get_container_name(sinsp_threadinfo* tinfo) const { std::string res; - if(tinfo->m_container_id.empty()) - { + if(tinfo->m_container_id.empty()) { res = "host"; - } - else - { + } else { const sinsp_container_info::ptr_t container_info = get_container(tinfo->m_container_id); - if(!container_info) - { + if(!container_info) { return ""; } - if(container_info->m_name.empty()) - { + if(container_info->m_name.empty()) { return ""; } @@ -450,20 +423,18 @@ std::string sinsp_container_manager::get_container_name(sinsp_threadinfo* tinfo) return res; } -void sinsp_container_manager::identify_category(sinsp_threadinfo *tinfo) -{ - if(tinfo->m_container_id.empty()) - { +void sinsp_container_manager::identify_category(sinsp_threadinfo* tinfo) { + if(tinfo->m_container_id.empty()) { return; } - if(tinfo->m_vpid == 1) - { - if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) - { + if(tinfo->m_vpid == 1) { + if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "identify_category (%ld) (%s): initial process for container, assigning CAT_CONTAINER", - tinfo->m_tid, tinfo->m_comm.c_str()); + "identify_category (%ld) (%s): initial process for " + "container, assigning CAT_CONTAINER", + tinfo->m_tid, + tinfo->m_comm.c_str()); } tinfo->m_category = sinsp_threadinfo::CAT_CONTAINER; @@ -474,13 +445,13 @@ void sinsp_container_manager::identify_category(sinsp_threadinfo *tinfo) // Categories are passed from parent to child threads const sinsp_threadinfo* ptinfo = tinfo->get_parent_thread(); - if(ptinfo && ptinfo->m_category != sinsp_threadinfo::CAT_NONE) - { - if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) - { + if(ptinfo && ptinfo->m_category != sinsp_threadinfo::CAT_NONE) { + if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "identify_category (%ld) (%s): taking parent category %d", - tinfo->m_tid, tinfo->m_comm.c_str(), ptinfo->m_category); + "identify_category (%ld) (%s): taking parent category %d", + tinfo->m_tid, + tinfo->m_comm.c_str(), + ptinfo->m_category); } tinfo->m_category = ptinfo->m_category; @@ -488,18 +459,16 @@ void sinsp_container_manager::identify_category(sinsp_threadinfo *tinfo) } sinsp_container_info::ptr_t cinfo = get_container(tinfo->m_container_id); - if(!cinfo) - { + if(!cinfo) { return; } - if(!cinfo->is_successful()) - { - if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) - { + if(!cinfo->is_successful()) { + if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "identify_category (%ld) (%s): container metadata incomplete", - tinfo->m_tid, tinfo->m_comm.c_str()); + "identify_category (%ld) (%s): container metadata incomplete", + tinfo->m_tid, + tinfo->m_comm.c_str()); } return; @@ -514,23 +483,20 @@ void sinsp_container_manager::identify_category(sinsp_threadinfo *tinfo) // This indicates the initial process of the health probe. sinsp_container_info::container_health_probe::probe_type ptype = - cinfo->match_health_probe(tinfo); + cinfo->match_health_probe(tinfo); - if(ptype == sinsp_container_info::container_health_probe::PT_NONE) - { + if(ptype == sinsp_container_info::container_health_probe::PT_NONE) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "identify_category (%ld) (%s): container health probe PT_NONE", - tinfo->m_tid, tinfo->m_comm.c_str()); + "identify_category (%ld) (%s): container health probe PT_NONE", + tinfo->m_tid, + tinfo->m_comm.c_str()); return; } bool found_container_init = false; - sinsp_threadinfo::visitor_func_t visitor = - [&found_container_init] (sinsp_threadinfo *ptinfo) - { - if(ptinfo->m_vpid == 1 && !ptinfo->m_container_id.empty()) - { + sinsp_threadinfo::visitor_func_t visitor = [&found_container_init](sinsp_threadinfo* ptinfo) { + if(ptinfo->m_vpid == 1 && !ptinfo->m_container_id.empty()) { found_container_init = true; return false; @@ -541,16 +507,16 @@ void sinsp_container_manager::identify_category(sinsp_threadinfo *tinfo) tinfo->traverse_parent_state(visitor); - if(!found_container_init) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "identify_category (%ld) (%s): not under container init, assigning category %s", - tinfo->m_tid, tinfo->m_comm.c_str(), - sinsp_container_info::container_health_probe::probe_type_names[ptype].c_str()); + if(!found_container_init) { + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "identify_category (%ld) (%s): not under container init, assigning category %s", + tinfo->m_tid, + tinfo->m_comm.c_str(), + sinsp_container_info::container_health_probe::probe_type_names[ptype].c_str()); // Each health probe type maps to a command category - switch(ptype) - { + switch(ptype) { case sinsp_container_info::container_health_probe::PT_NONE: case sinsp_container_info::container_health_probe::PT_END: break; @@ -567,165 +533,136 @@ void sinsp_container_manager::identify_category(sinsp_threadinfo *tinfo) } } -void sinsp_container_manager::subscribe_on_new_container(new_container_cb callback) -{ +void sinsp_container_manager::subscribe_on_new_container(new_container_cb callback) { m_new_callbacks.emplace_back(callback); } -void sinsp_container_manager::subscribe_on_remove_container(remove_container_cb callback) -{ +void sinsp_container_manager::subscribe_on_remove_container(remove_container_cb callback) { m_remove_callbacks.emplace_back(callback); } -void sinsp_container_manager::create_engines() -{ - if (m_static_container) - { +void sinsp_container_manager::create_engines() { + if(m_static_container) { auto engine = std::make_shared(*this, - m_static_id, - m_static_name, - m_static_image); + m_static_id, + m_static_name, + m_static_image); m_container_engines.push_back(engine); m_container_engine_by_type[CT_STATIC] = engine; return; } #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) #ifndef _WIN32 - if (m_container_engine_mask & (1 << CT_PODMAN)) - { + if(m_container_engine_mask & (1 << CT_PODMAN)) { auto podman_engine = std::make_shared(*this); m_container_engines.push_back(podman_engine); m_container_engine_by_type[CT_PODMAN] = podman_engine; } - if (m_container_engine_mask & (1 << CT_DOCKER)) - { + if(m_container_engine_mask & (1 << CT_DOCKER)) { auto docker_engine = std::make_shared(*this); m_container_engines.push_back(docker_engine); m_container_engine_by_type[CT_DOCKER] = docker_engine; } - if (m_container_engine_mask & - ((1 << CT_CRI) | - (1 << CT_CRIO) | - (1 << CT_CONTAINERD))) - { + if(m_container_engine_mask & ((1 << CT_CRI) | (1 << CT_CRIO) | (1 << CT_CONTAINERD))) { auto cri_engine = std::make_shared(*this); m_container_engines.push_back(cri_engine); m_container_engine_by_type[CT_CRI] = cri_engine; m_container_engine_by_type[CT_CRIO] = cri_engine; m_container_engine_by_type[CT_CONTAINERD] = cri_engine; } - if (m_container_engine_mask & (1 << CT_LXC)) - { + if(m_container_engine_mask & (1 << CT_LXC)) { auto lxc_engine = std::make_shared(*this); m_container_engines.push_back(lxc_engine); m_container_engine_by_type[CT_LXC] = lxc_engine; } - if (m_container_engine_mask & (1 << CT_LIBVIRT_LXC)) - { + if(m_container_engine_mask & (1 << CT_LIBVIRT_LXC)) { auto libvirt_lxc_engine = std::make_shared(*this); m_container_engines.push_back(libvirt_lxc_engine); m_container_engine_by_type[CT_LIBVIRT_LXC] = libvirt_lxc_engine; } - if (m_container_engine_mask & (1 << CT_MESOS)) - { + if(m_container_engine_mask & (1 << CT_MESOS)) { auto mesos_engine = std::make_shared(*this); m_container_engines.push_back(mesos_engine); m_container_engine_by_type[CT_MESOS] = mesos_engine; } - if (m_container_engine_mask & (1 << CT_RKT)) - { + if(m_container_engine_mask & (1 << CT_RKT)) { auto rkt_engine = std::make_shared(*this); m_container_engines.push_back(rkt_engine); m_container_engine_by_type[CT_RKT] = rkt_engine; } - if (m_container_engine_mask & (1 << CT_BPM)) - { + if(m_container_engine_mask & (1 << CT_BPM)) { auto bpm_engine = std::make_shared(*this); m_container_engines.push_back(bpm_engine); m_container_engine_by_type[CT_BPM] = bpm_engine; } -#endif // _WIN32 -#endif // MINIMAL_BUILD +#endif // _WIN32 +#endif // MINIMAL_BUILD } void sinsp_container_manager::update_container_with_size(sinsp_container_type type, - const std::string& container_id) -{ + const std::string& container_id) { auto found = m_container_engine_by_type.find(type); - if(found == m_container_engine_by_type.end()) - { + if(found == m_container_engine_by_type.end()) { libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "Container type %d not found when requesting size for %s", - type, - container_id.c_str()); + "Container type %d not found when requesting size for %s", + type, + container_id.c_str()); return; } - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "Request size for %s", - container_id.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "Request size for %s", container_id.c_str()); found->second->update_with_size(container_id); } -void sinsp_container_manager::cleanup() -{ - for(auto &eng : m_container_engines) - { +void sinsp_container_manager::cleanup() { + for(auto& eng : m_container_engines) { eng->cleanup(); } } -void sinsp_container_manager::set_docker_socket_path(std::string socket_path) -{ +void sinsp_container_manager::set_docker_socket_path(std::string socket_path) { #if !defined(MINIMAL_BUILD) && !defined(_WIN32) && !defined(__EMSCRIPTEN__) libsinsp::container_engine::docker_linux::set_docker_sock(std::move(socket_path)); #endif } -void sinsp_container_manager::set_query_docker_image_info(bool query_image_info) -{ +void sinsp_container_manager::set_query_docker_image_info(bool query_image_info) { #if !defined(MINIMAL_BUILD) && !defined(_WIN32) && !defined(__EMSCRIPTEN__) libsinsp::container_engine::docker_async_source::set_query_image_info(query_image_info); #endif } -void sinsp_container_manager::set_cri_extra_queries(bool extra_queries) -{ +void sinsp_container_manager::set_cri_extra_queries(bool extra_queries) { #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) libsinsp::container_engine::cri::set_extra_queries(extra_queries); #endif } -void sinsp_container_manager::set_cri_socket_path(const std::string &path) -{ +void sinsp_container_manager::set_cri_socket_path(const std::string& path) { #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) libsinsp::container_engine::cri::set_cri_socket_path(path); #endif } -void sinsp_container_manager::add_cri_socket_path(const std::string &path) -{ +void sinsp_container_manager::add_cri_socket_path(const std::string& path) { #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) libsinsp::container_engine::cri::add_cri_socket_path(path); #endif } -void sinsp_container_manager::set_cri_timeout(int64_t timeout_ms) -{ +void sinsp_container_manager::set_cri_timeout(int64_t timeout_ms) { #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) libsinsp::container_engine::cri::set_cri_timeout(timeout_ms); #endif } -void sinsp_container_manager::set_cri_async(bool async) -{ +void sinsp_container_manager::set_cri_async(bool async) { #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) libsinsp::container_engine::cri::set_async(async); #endif } -void sinsp_container_manager::set_container_labels_max_len(uint32_t max_label_len) -{ +void sinsp_container_manager::set_container_labels_max_len(uint32_t max_label_len) { sinsp_container_info::m_container_label_max_length = max_label_len; } diff --git a/userspace/libsinsp/container.h b/userspace/libsinsp/container.h index 8b4cc1a7f1..17305c96d3 100644 --- a/userspace/libsinsp/container.h +++ b/userspace/libsinsp/container.h @@ -40,12 +40,12 @@ limitations under the License. class sinsp_dumper; -class sinsp_container_manager : - public libsinsp::container_engine::container_cache_interface -{ +class sinsp_container_manager : public libsinsp::container_engine::container_cache_interface { public: - using map_ptr_t = libsinsp::ConstMutexGuard>; - using map_mut_ptr_t = libsinsp::MutexGuard>; + using map_ptr_t = + libsinsp::ConstMutexGuard>; + using map_mut_ptr_t = + libsinsp::MutexGuard>; /** * Due to how the container manager is architected, it makes it difficult @@ -64,10 +64,7 @@ class sinsp_container_manager : */ map_ptr_t get_containers() const; - inline map_mut_ptr_t get_containers() - { - return m_containers.lock(); - } + inline map_mut_ptr_t get_containers() { return m_containers.lock(); } bool remove_inactive_containers(); @@ -77,7 +74,8 @@ class sinsp_container_manager : * @param container_info shared_ptr owning the container_info to add/update * @param thread a thread in the container, only passed to callbacks */ - void add_container(const sinsp_container_info::ptr_t& container_info, sinsp_threadinfo *thread) override; + void add_container(const sinsp_container_info::ptr_t& container_info, + sinsp_threadinfo* thread) override; /** * @brief Update a container by replacing its entry with a new one @@ -97,7 +95,7 @@ class sinsp_container_manager : * the container, get a new shared_ptr and pass it * to replace_container() */ - sinsp_container_info::ptr_t get_container(const std::string &id) const override; + sinsp_container_info::ptr_t get_container(const std::string& id) const override; /** * @brief Generate container JSON event from a new container @@ -106,7 +104,8 @@ class sinsp_container_manager : * Note: this is unrelated to on_new_container callbacks even though * both happen during container creation */ - void notify_new_container(const sinsp_container_info& container_info, sinsp_threadinfo *tinfo = nullptr) override; + void notify_new_container(const sinsp_container_info& container_info, + sinsp_threadinfo* tinfo = nullptr) override; bool async_allowed() const override; @@ -131,15 +130,15 @@ class sinsp_container_manager : // will *not* change any category to NONE, so a threadinfo // that initially has a category will retain its category // across execs e.g. "sh -c /bin/true" execing /bin/true. - void identify_category(sinsp_threadinfo *tinfo); + void identify_category(sinsp_threadinfo* tinfo); - bool container_exists(const std::string& container_id) const override{ + bool container_exists(const std::string& container_id) const override { auto containers = m_containers.lock(); return containers->find(container_id) != containers->end() || - m_lookups.find(container_id) != m_lookups.end(); + m_lookups.find(container_id) != m_lookups.end(); } - typedef std::function new_container_cb; + typedef std::function new_container_cb; typedef std::function remove_container_cb; void subscribe_on_new_container(new_container_cb callback); void subscribe_on_remove_container(remove_container_cb callback); @@ -155,10 +154,7 @@ class sinsp_container_manager : * This method *must* be called before the first container detection, * i.e. before inspector->open() */ - inline void set_container_engine_mask(uint64_t mask) - { - m_container_engine_mask = mask; - } + inline void set_container_engine_mask(uint64_t mask) { m_container_engine_mask = mask; } /** * @brief Set static container information @@ -172,8 +168,9 @@ class sinsp_container_manager : * This method *must* be called before the first container detection, * i.e. before inspector->open() */ - inline void set_static_container(const std::string& id, const std::string& name, const std::string& image) - { + inline void set_static_container(const std::string& id, + const std::string& name, + const std::string& image) { m_static_id = id; m_static_name = name; m_static_image = image; @@ -187,15 +184,14 @@ class sinsp_container_manager : * to include the size of the container layer. This is not filled in the * initial request because it can easily take seconds. */ - void update_container_with_size(sinsp_container_type type, - const std::string& container_id); + void update_container_with_size(sinsp_container_type type, const std::string& container_id); void cleanup(); void set_docker_socket_path(std::string socket_path); void set_query_docker_image_info(bool query_image_info); void set_cri_extra_queries(bool extra_queries); void set_cri_socket_path(const std::string& path); - void add_cri_socket_path(const std::string &path); + void add_cri_socket_path(const std::string& path); void set_cri_timeout(int64_t timeout_ms); void set_cri_async(bool async); void set_container_labels_max_len(uint32_t max_label_len); @@ -212,8 +208,9 @@ class sinsp_container_manager : * state of the lookup via this method and call should_lookup() before * starting a new lookup. */ - void set_lookup_status(const std::string& container_id, sinsp_container_type ctype, sinsp_container_lookup::state state) override - { + void set_lookup_status(const std::string& container_id, + sinsp_container_type ctype, + sinsp_container_lookup::state state) override { m_lookups[container_id][ctype] = state; } @@ -227,11 +224,9 @@ class sinsp_container_manager : * This method effectively checks if m_lookups[container_id][ctype] * exists, without creating unnecessary map entries along the way. */ - bool should_lookup(const std::string& container_id, sinsp_container_type ctype) override - { + bool should_lookup(const std::string& container_id, sinsp_container_type ctype) override { auto container_lookups = m_lookups.find(container_id); - if(container_lookups == m_lookups.end()) - { + if(container_lookups == m_lookups.end()) { return true; } auto engine_lookup = container_lookups->second.find(ctype); @@ -239,28 +234,37 @@ class sinsp_container_manager : } /** - * \brief get the list of container engines in the inspector - * - * @return a pointer to the list of container engines - */ - std::list>* get_container_engines() { + * \brief get the list of container engines in the inspector + * + * @return a pointer to the list of container engines + */ + std::list>* + get_container_engines() { return &m_container_engines; } uint64_t m_last_flush_time_ns; std::string container_to_json(const sinsp_container_info& container_info); - private: - bool container_to_sinsp_event(const std::string& json, sinsp_evt* evt, std::unique_ptr tinfo, char* scap_err); - std::string get_docker_env(const Json::Value &env_vars, const std::string &mti); - - std::list> m_container_engines; - std::map> m_container_engine_by_type; + bool container_to_sinsp_event(const std::string& json, + sinsp_evt* evt, + std::unique_ptr tinfo, + char* scap_err); + std::string get_docker_env(const Json::Value& env_vars, const std::string& mti); + + std::list> + m_container_engines; + std::map> + m_container_engine_by_type; sinsp* m_inspector; std::shared_ptr m_sinsp_stats_v2; - libsinsp::Mutex>> m_containers; - std::unordered_map> m_lookups; + libsinsp::Mutex>> + m_containers; + std::unordered_map> + m_lookups; std::list m_new_callbacks; std::list m_remove_callbacks; @@ -273,4 +277,3 @@ class sinsp_container_manager : std::string m_static_image; uint64_t m_container_engine_mask; }; - diff --git a/userspace/libsinsp/container_engine/bpm.cpp b/userspace/libsinsp/container_engine/bpm.cpp index 9e482d1cb7..e51acb45a1 100644 --- a/userspace/libsinsp/container_engine/bpm.cpp +++ b/userspace/libsinsp/container_engine/bpm.cpp @@ -20,13 +20,11 @@ limitations under the License. using namespace libsinsp::container_engine; -bool bpm::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) -{ +bool bpm::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) { sinsp_container_info container_info; bool matches = false; - for(const auto& it : tinfo->cgroups()) - { + for(const auto& it : tinfo->cgroups()) { std::string cgroup = it.second; size_t pos; @@ -34,16 +32,18 @@ bool bpm::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) // Non-systemd and systemd BPM // pos = cgroup.find("bpm-"); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { auto id_start = pos + sizeof("bpm-") - 1; auto id_end = cgroup.find(".scope", id_start); auto id = cgroup.substr(id_start, id_end - id_start); // As of BPM v1.0.3, the container ID is only allowed to contain the following chars - // see https://github.com/cloudfoundry-incubator/bpm-release/blob/v1.0.3/src/bpm/jobid/encoding.go - if (!id.empty() && strspn(id.c_str(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-") == id.size()) - { + // see + // https://github.com/cloudfoundry-incubator/bpm-release/blob/v1.0.3/src/bpm/jobid/encoding.go + if(!id.empty() && + strspn(id.c_str(), + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-") == + id.size()) { container_info.m_type = CT_BPM; container_info.m_id = id; matches = true; @@ -52,17 +52,16 @@ bool bpm::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) } } - if (!matches) - { + if(!matches) { return false; } tinfo->m_container_id = container_info.m_id; - if(container_cache().should_lookup(container_info.m_id, CT_BPM)) - { + if(container_cache().should_lookup(container_info.m_id, CT_BPM)) { container_info.m_name = container_info.m_id; container_info.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); - container_cache().add_container(std::make_shared(container_info), tinfo); + container_cache().add_container(std::make_shared(container_info), + tinfo); container_cache().notify_new_container(container_info, tinfo); } return true; diff --git a/userspace/libsinsp/container_engine/bpm.h b/userspace/libsinsp/container_engine/bpm.h index 5f04ac6faa..b51756ebe8 100644 --- a/userspace/libsinsp/container_engine/bpm.h +++ b/userspace/libsinsp/container_engine/bpm.h @@ -27,13 +27,11 @@ class sinsp_threadinfo; namespace libsinsp { namespace container_engine { -class bpm : public container_engine_base -{ +class bpm : public container_engine_base { public: - bpm(container_cache_interface& cache) : container_engine_base(cache) - {} + bpm(container_cache_interface& cache): container_engine_base(cache) {} - bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; + bool resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) override; }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/container_async_source.h b/userspace/libsinsp/container_engine/container_async_source.h index b266ee0dca..45af35dc67 100644 --- a/userspace/libsinsp/container_engine/container_async_source.h +++ b/userspace/libsinsp/container_engine/container_async_source.h @@ -22,10 +22,8 @@ limitations under the License. #include #include -namespace libsinsp -{ -namespace container_engine -{ +namespace libsinsp { +namespace container_engine { class container_cache_interface; @@ -35,8 +33,8 @@ class container_cache_interface; * @tparam key_type lookup key */ template -class container_async_source : public libsinsp::async_key_value_source -{ +class container_async_source + : public libsinsp::async_key_value_source { using parent_type = libsinsp::async_key_value_source; using callback_handler = typename parent_type::callback_handler; @@ -47,9 +45,7 @@ class container_async_source : public libsinsp::async_key_value_source diff --git a/userspace/libsinsp/container_engine/container_cache_interface.h b/userspace/libsinsp/container_engine/container_cache_interface.h index a8f61d8b52..23b12b3ff6 100644 --- a/userspace/libsinsp/container_engine/container_cache_interface.h +++ b/userspace/libsinsp/container_engine/container_cache_interface.h @@ -20,24 +20,24 @@ limitations under the License. #include -namespace libsinsp -{ -namespace container_engine -{ +namespace libsinsp { +namespace container_engine { /** * Interface for a container cache for container engines. */ -class container_cache_interface -{ +class container_cache_interface { public: virtual ~container_cache_interface() = default; - virtual void notify_new_container(const sinsp_container_info& container_info, sinsp_threadinfo *tinfo = nullptr) = 0; + virtual void notify_new_container(const sinsp_container_info& container_info, + sinsp_threadinfo* tinfo = nullptr) = 0; virtual bool should_lookup(const std::string& container_id, sinsp_container_type ctype) = 0; - virtual void set_lookup_status(const std::string& container_id, sinsp_container_type ctype, sinsp_container_lookup::state state) = 0; + virtual void set_lookup_status(const std::string& container_id, + sinsp_container_type ctype, + sinsp_container_lookup::state state) = 0; /** * Get a container from the cache. @@ -47,7 +47,8 @@ class container_cache_interface /** * Add a new container to the cache. */ - virtual void add_container(const sinsp_container_info::ptr_t& container_info, sinsp_threadinfo *thread) = 0; + virtual void add_container(const sinsp_container_info::ptr_t& container_info, + sinsp_threadinfo* thread) = 0; /** * Update a container by replacing its entry with a new one @@ -59,9 +60,8 @@ class container_cache_interface */ virtual bool container_exists(const std::string& container_id) const = 0; - virtual bool async_allowed() const = 0; }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/container_engine_base.cpp b/userspace/libsinsp/container_engine/container_engine_base.cpp index 6183f51565..d174b94066 100644 --- a/userspace/libsinsp/container_engine/container_engine_base.cpp +++ b/userspace/libsinsp/container_engine/container_engine_base.cpp @@ -19,25 +19,17 @@ limitations under the License. #include #include -namespace libsinsp -{ +namespace libsinsp { -namespace container_engine -{ +namespace container_engine { -container_engine_base::container_engine_base(container_cache_interface &cache) : - m_cache(cache) -{ -} +container_engine_base::container_engine_base(container_cache_interface &cache): m_cache(cache) {} -void container_engine_base::update_with_size(const std::string &container_id) -{ +void container_engine_base::update_with_size(const std::string &container_id) { SINSP_DEBUG("Updating container size not supported for this container type."); } -void container_engine_base::cleanup() -{ -} +void container_engine_base::cleanup() {} -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/container_engine_base.h b/userspace/libsinsp/container_engine/container_engine_base.h index 0aa669d2f2..5c5fea1919 100644 --- a/userspace/libsinsp/container_engine/container_engine_base.h +++ b/userspace/libsinsp/container_engine/container_engine_base.h @@ -33,7 +33,7 @@ namespace container_engine { */ class container_engine_base { public: - container_engine_base(container_cache_interface &cache); + container_engine_base(container_cache_interface& cache); virtual ~container_engine_base() = default; @@ -41,8 +41,7 @@ class container_engine_base { * Find a container associated with the given tinfo and add it to the * cache. */ - virtual bool resolve(sinsp_threadinfo* tinfo, - bool query_os_for_missing_info) = 0; + virtual bool resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) = 0; /** * Update an existing container with the size of the container layer. @@ -57,14 +56,10 @@ class container_engine_base { /** * Derived class accessor to the cache */ - container_cache_interface& container_cache() - { - return m_cache; - } + container_cache_interface& container_cache() { return m_cache; } private: container_cache_interface& m_cache; }; -} -} - +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/cri.cpp b/userspace/libsinsp/container_engine/cri.cpp index c97c0c76b1..6a85d2d398 100644 --- a/userspace/libsinsp/container_engine/cri.cpp +++ b/userspace/libsinsp/container_engine/cri.cpp @@ -20,9 +20,9 @@ limitations under the License. #include #ifdef GRPC_INCLUDE_IS_GRPCPP -# include +#include #else -# include +#include #endif #include @@ -39,28 +39,23 @@ using namespace libsinsp::cri; using namespace libsinsp::container_engine; using namespace libsinsp::runc; -namespace -{ +namespace { // do the CRI communication asynchronously bool s_async = true; constexpr const cgroup_layout CRI_CGROUP_LAYOUT[] = { - {"/", ""}, // non-systemd containerd - {"/crio-", ""}, // non-systemd cri-o - {"/cri-containerd-", ".scope"}, // systemd containerd - {"/crio-", ".scope"}, // systemd cri-o - {":cri-containerd:", ""}, // containerd without "SystemdCgroup = true" - {"/docker-", ".scope"}, // systemd docker in cri-dockerd scenario - {nullptr, nullptr} -}; -} // namespace - - -cri::cri(container_cache_interface &cache) : container_engine_base(cache) -{ - libsinsp::cri::cri_settings& cri_settings = libsinsp::cri::cri_settings::get(); - if (cri_settings.get_cri_unix_socket_paths().empty()) - { + {"/", ""}, // non-systemd containerd + {"/crio-", ""}, // non-systemd cri-o + {"/cri-containerd-", ".scope"}, // systemd containerd + {"/crio-", ".scope"}, // systemd cri-o + {":cri-containerd:", ""}, // containerd without "SystemdCgroup = true" + {"/docker-", ".scope"}, // systemd docker in cri-dockerd scenario + {nullptr, nullptr}}; +} // namespace + +cri::cri(container_cache_interface &cache): container_engine_base(cache) { + libsinsp::cri::cri_settings &cri_settings = libsinsp::cri::cri_settings::get(); + if(cri_settings.get_cri_unix_socket_paths().empty()) { // containerd as primary default value when empty cri_settings.add_cri_unix_socket_path("/run/containerd/containerd.sock"); // crio-o as secondary default value when empty @@ -69,45 +64,35 @@ cri::cri(container_cache_interface &cache) : container_engine_base(cache) cri_settings.add_cri_unix_socket_path("/run/k3s/containerd/containerd.sock"); } - // Try all specified unix socket paths // NOTE: having multiple container runtimes on the same host is a sporadic case, // so we wouldn't make things complex to support that. // On the other hand, specifying multiple unix socket paths (and using only the first match) // will solve the "same config, multiple hosts" use case. - for (auto &p : cri_settings.get_cri_unix_socket_paths()) - { - if(p.empty()) - { + for(auto &p : cri_settings.get_cri_unix_socket_paths()) { + if(p.empty()) { continue; } auto cri_path = scap_get_host_root() + p; struct stat s = {}; - if(stat(cri_path.c_str(), &s) != 0 || (s.st_mode & S_IFMT) != S_IFSOCK) - { + if(stat(cri_path.c_str(), &s) != 0 || (s.st_mode & S_IFMT) != S_IFSOCK) { continue; } m_cri_v1 = std::make_unique(cri_path); - if(!m_cri_v1->is_ok()) - { + if(!m_cri_v1->is_ok()) { m_cri_v1.reset(nullptr); - } - else - { + } else { // Store used unix_socket_path cri_settings.set_cri_unix_socket_path(p); break; } m_cri_v1alpha2 = std::make_unique(cri_path); - if(!m_cri_v1alpha2->is_ok()) - { + if(!m_cri_v1alpha2->is_ok()) { m_cri_v1alpha2.reset(nullptr); - } - else - { + } else { // Store used unix_socket_path cri_settings.set_cri_unix_socket_path(p); break; @@ -115,28 +100,23 @@ cri::cri(container_cache_interface &cache) : container_engine_base(cache) } } -void cri::cleanup() -{ - if(m_async_source) - { +void cri::cleanup() { + if(m_async_source) { m_async_source->quiesce(); } libsinsp::cri::cri_settings::set_cri_extra_queries(true); } -void cri::set_cri_socket_path(const std::string& path) -{ +void cri::set_cri_socket_path(const std::string &path) { libsinsp::cri::cri_settings::clear_cri_unix_socket_paths(); add_cri_socket_path(path); } -void cri::add_cri_socket_path(const std::string& path) -{ +void cri::add_cri_socket_path(const std::string &path) { libsinsp::cri::cri_settings::add_cri_unix_socket_path(path); } -void cri::set_cri_timeout(int64_t timeout_ms) -{ +void cri::set_cri_timeout(int64_t timeout_ms) { libsinsp::cri::cri_settings::set_cri_timeout(timeout_ms); } @@ -144,64 +124,56 @@ void cri::set_extra_queries(bool extra_queries) { libsinsp::cri::cri_settings::set_cri_extra_queries(extra_queries); } -void cri::set_async(bool async) -{ +void cri::set_async(bool async) { s_async = async; } -bool cri::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) -{ +bool cri::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) { container_cache_interface *cache = &container_cache(); std::string container_id, cgroup; - if(!matches_runc_cgroups(tinfo, CRI_CGROUP_LAYOUT, container_id, cgroup)) - { + if(!matches_runc_cgroups(tinfo, CRI_CGROUP_LAYOUT, container_id, cgroup)) { return false; } tinfo->m_container_id = container_id; - if(!m_cri_v1alpha2 && !m_cri_v1) - { + if(!m_cri_v1alpha2 && !m_cri_v1) { // This isn't an error in the case where the // configured unix domain socket doesn't exist. In // that case, s_cri isn't initialized at all. Hence, // the DEBUG. libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cri (%s): Could not parse cri (no s_cri object)", - container_id.c_str()); + "cri (%s): Could not parse cri (no s_cri object)", + container_id.c_str()); return false; } - if(!cache->should_lookup(container_id, get_cri_runtime_type())) - { + if(!cache->should_lookup(container_id, get_cri_runtime_type())) { return true; } auto container = sinsp_container_info(); container.m_id = container_id; container.m_type = get_cri_runtime_type(); - if (mesos::set_mesos_task_id(container, tinfo)) - { + if(mesos::set_mesos_task_id(container, tinfo)) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cri (%s) Mesos CRI container, Mesos task ID: [%s]", - container_id.c_str(), container.m_mesos_task_id.c_str()); + "cri (%s) Mesos CRI container, Mesos task ID: [%s]", + container_id.c_str(), + container.m_mesos_task_id.c_str()); } // note: query_os_for_missing_info is set to 'true' by default - if (query_os_for_missing_info) - { + if(query_os_for_missing_info) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cri (%s): Performing lookup", - container_id.c_str()); + "cri (%s): Performing lookup", + container_id.c_str()); - libsinsp::cgroup_limits::cgroup_limits_key key( - container.m_id, - tinfo->get_cgroup("cpu"), - tinfo->get_cgroup("memory"), - tinfo->get_cgroup("cpuset")); + libsinsp::cgroup_limits::cgroup_limits_key key(container.m_id, + tinfo->get_cgroup("cpu"), + tinfo->get_cgroup("memory"), + tinfo->get_cgroup("cpuset")); - if(!m_async_source) - { + if(!m_async_source) { // Each lookup attempt involves two CRI API calls (see // `cri_async_source::parse`), each one having a default timeout // of 1000ms (`cri::set_cri_timeout`). @@ -220,11 +192,13 @@ bool cri::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) // taking into account elapsed time. uint64_t max_wait_ms = 20000; auto async_source = - new cri_async_source(cache, m_cri_v1alpha2.get(), m_cri_v1.get(), max_wait_ms); + new cri_async_source(cache, m_cri_v1alpha2.get(), m_cri_v1.get(), max_wait_ms); m_async_source = std::unique_ptr(async_source); } - cache->set_lookup_status(container_id, get_cri_runtime_type(), sinsp_container_lookup::state::STARTED); + cache->set_lookup_status(container_id, + get_cri_runtime_type(), + sinsp_container_lookup::state::STARTED); // sinsp_container_lookup is set-up to perform 5 retries at most, with // an exponential backoff with 2000 ms of maximum wait time. @@ -232,92 +206,85 @@ bool cri::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) bool done; const bool async = s_async && cache->async_allowed(); - if(async) - { + if(async) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cri_async (%s): Starting asynchronous lookup", - container_id.c_str()); + "cri_async (%s): Starting asynchronous lookup", + container_id.c_str()); done = m_async_source->lookup(key, result); - } - else - { + } else { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cri_async (%s): Starting synchronous lookup", - container_id.c_str()); + "cri_async (%s): Starting synchronous lookup", + container_id.c_str()); // `lookup_sync` function directly invokes the container engine specific parser `parse` done = m_async_source->lookup_sync(key, result); - // note: The container image is the most crucial field from a security incident response perspective. - // We aim to raise the bar for successful container lookups. Conversely, pod sandboxes do not include - // a container image in the API response. - if(!result.m_image.empty() || result.is_pod_sandbox()) - { + // note: The container image is the most crucial field from a security incident response + // perspective. We aim to raise the bar for successful container lookups. Conversely, + // pod sandboxes do not include a container image in the API response. + if(!result.m_image.empty() || result.is_pod_sandbox()) { /* - * Only for synchronous lookup option (e.g. Falco's default is async not sync) - * - * Explicitly check for the most crucial retrieved value (`m_image`) to be present before enabling the - * fast-track container add option. At this point, the container with only the cgroup (container id) was - * already added to the cache. Therefore, we can proceed to call `replace_container`. - * - * Bypassing the round-trip process: - * `source_callback` -> `notify_new_container` -> - * `container_to_sinsp_event(container_to_json(container_info), ...)` -> - * `parse_container_json_evt` -> `m_inspector->m_container_manager.add_container()` - * - * In `parse_container_json_evt`, we still re-add the container to support native 'container' events - * and new container callbacks that may expect the container as JSON in the artificial sinsp evt. - * However, we can avoid delays by storing the container struct in the container cache now. - * This is beneficial because syscall events do not explicitly require container events, instead, - * they directly retrieve container details from the container cache. This new feature can mitigate - * issues noted by adopters, such as the absence of container images in syscall events even when - * disabling async lookups. - */ + * Only for synchronous lookup option (e.g. Falco's default is async not sync) + * + * Explicitly check for the most crucial retrieved value (`m_image`) to be present + * before enabling the fast-track container add option. At this point, the container + * with only the cgroup (container id) was already added to the cache. Therefore, we + * can proceed to call `replace_container`. + * + * Bypassing the round-trip process: + * `source_callback` -> `notify_new_container` -> + * `container_to_sinsp_event(container_to_json(container_info), ...)` -> + * `parse_container_json_evt` -> `m_inspector->m_container_manager.add_container()` + * + * In `parse_container_json_evt`, we still re-add the container to support native + * 'container' events and new container callbacks that may expect the container as + * JSON in the artificial sinsp evt. However, we can avoid delays by storing the + * container struct in the container cache now. This is beneficial because syscall + * events do not explicitly require container events, instead, they directly + * retrieve container details from the container cache. This new feature can + * mitigate issues noted by adopters, such as the absence of container images in + * syscall events even when disabling async lookups. + */ result.set_lookup_status(sinsp_container_lookup::state::STARTED); - // note: The cache should not have SUCCESSFUL as lookup status at this point, else `parse_container_json_evt` would wrongly exit early. + // note: The cache should not have SUCCESSFUL as lookup status at this point, else + // `parse_container_json_evt` would wrongly exit early. cache->replace_container(std::make_shared(result)); - // note: On the other hand `parse_container_json_evt` expects SUCCESSFUL as lookup state for the incoming container event / - // the not yet cached container, exactly how it was done within `lookup_sync`. + // note: On the other hand `parse_container_json_evt` expects SUCCESSFUL as lookup + // state for the incoming container event / the not yet cached container, exactly + // how it was done within `lookup_sync`. result.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); } } - if (done) - { + if(done) { // if a previous lookup call already found the metadata, process it now m_async_source->source_callback(key, result); - if(async) - { + if(async) { // This should *never* happen, in async mode as ttl is 0 (never wait) - libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "cri_async (%s): Unexpected immediate return from cri_async lookup", - container_id.c_str()); - + libsinsp_logger()->format( + sinsp_logger::SEV_ERROR, + "cri_async (%s): Unexpected immediate return from cri_async lookup", + container_id.c_str()); } } - } - else - { + } else { cache->notify_new_container(container, tinfo); } return true; } -void cri::update_with_size(const std::string& container_id) -{ +void cri::update_with_size(const std::string &container_id) { sinsp_container_info::ptr_t existing = container_cache().get_container(container_id); - if(!existing) - { + if(!existing) { libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "cri (%s): Failed to locate existing container data", - container_id.c_str()); + "cri (%s): Failed to locate existing container data", + container_id.c_str()); ASSERT(false); return; } std::optional writable_layer_size = get_writable_layer_size(existing->m_full_id); - if(!writable_layer_size.has_value()) - { + if(!writable_layer_size.has_value()) { return; } @@ -325,8 +292,7 @@ void cri::update_with_size(const std::string& container_id) shared_ptr updated(std::make_shared(*existing)); updated->m_size_rw_bytes = *writable_layer_size; - if(existing->m_size_rw_bytes == updated->m_size_rw_bytes) - { + if(existing->m_size_rw_bytes == updated->m_size_rw_bytes) { // no data has changed return; } @@ -334,47 +300,32 @@ void cri::update_with_size(const std::string& container_id) container_cache().replace_container(updated); } -sinsp_container_type cri::get_cri_runtime_type() const -{ - if(m_cri_v1) - { +sinsp_container_type cri::get_cri_runtime_type() const { + if(m_cri_v1) { return m_cri_v1->get_cri_runtime_type(); - } - else if(m_cri_v1alpha2) - { + } else if(m_cri_v1alpha2) { return m_cri_v1alpha2->get_cri_runtime_type(); - } - else - { + } else { return sinsp_container_type::CT_CRI; } } -std::optional cri::get_writable_layer_size(const string &container_id) -{ - if(m_cri_v1) - { +std::optional cri::get_writable_layer_size(const string &container_id) { + if(m_cri_v1) { return m_cri_v1->get_writable_layer_size(container_id); - } - else if(m_cri_v1alpha2) - { + } else if(m_cri_v1alpha2) { return m_cri_v1alpha2->get_writable_layer_size(container_id); - } - else - { + } else { return std::nullopt; } } -bool cri_async_source::parse(const cri_async_source::key_type &key, sinsp_container_info &container) -{ - if(m_cri_v1) - { +bool cri_async_source::parse(const cri_async_source::key_type &key, + sinsp_container_info &container) { + if(m_cri_v1) { return m_cri_v1->parse(key, container); - } - else if(m_cri_v1alpha2) - { + } else if(m_cri_v1alpha2) { return m_cri_v1alpha2->parse(key, container); } return false; diff --git a/userspace/libsinsp/container_engine/cri.h b/userspace/libsinsp/container_engine/cri.h index f37f5c5980..e00af883ad 100644 --- a/userspace/libsinsp/container_engine/cri.h +++ b/userspace/libsinsp/container_engine/cri.h @@ -42,56 +42,44 @@ namespace container_engine { * 2. Apparently CRI can fail to find a freshly created container * for a short while, so we should delay the query a bit. */ -class cri_async_source : public container_async_source -{ +class cri_async_source : public container_async_source { using key_type = libsinsp::cgroup_limits::cgroup_limits_key; + public: explicit cri_async_source(container_cache_interface* cache, - ::libsinsp::cri::cri_interface_v1alpha2* cri_v1alpha2, - ::libsinsp::cri::cri_interface_v1* cri_v1, uint64_t ttl_ms): - container_async_source(NO_WAIT_LOOKUP, ttl_ms, cache), - m_cri_v1alpha2(cri_v1alpha2), - m_cri_v1(cri_v1) - { - } + ::libsinsp::cri::cri_interface_v1alpha2* cri_v1alpha2, + ::libsinsp::cri::cri_interface_v1* cri_v1, + uint64_t ttl_ms): + container_async_source(NO_WAIT_LOOKUP, ttl_ms, cache), + m_cri_v1alpha2(cri_v1alpha2), + m_cri_v1(cri_v1) {} - void quiesce() { - async_key_value_source::stop(); - } + void quiesce() { async_key_value_source::stop(); } bool parse(const key_type& key, sinsp_container_info& container) override; + private: const char* name() const override { return "cri"; }; - sinsp_container_type container_type(const key_type& key) const override - { - if(m_cri_v1) - { + sinsp_container_type container_type(const key_type& key) const override { + if(m_cri_v1) { return m_cri_v1->get_cri_runtime_type(); - } - else if(m_cri_v1alpha2) - { + } else if(m_cri_v1alpha2) { return m_cri_v1alpha2->get_cri_runtime_type(); - } - else - { + } else { return sinsp_container_type::CT_CRI; } } - std::string container_id(const key_type& key) const override - { - return key.m_container_id; - } + std::string container_id(const key_type& key) const override { return key.m_container_id; } ::libsinsp::cri::cri_interface_v1alpha2* m_cri_v1alpha2; ::libsinsp::cri::cri_interface_v1* m_cri_v1; }; -class cri : public container_engine_base -{ +class cri : public container_engine_base { public: - cri(container_cache_interface &cache); - bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; + cri(container_cache_interface& cache); + bool resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) override; void update_with_size(const std::string& container_id) override; void cleanup() override; static void set_cri_socket_path(const std::string& path); @@ -103,11 +91,11 @@ class cri : public container_engine_base private: [[nodiscard]] sinsp_container_type get_cri_runtime_type() const; - std::optional get_writable_layer_size(const std::string &container_id); + std::optional get_writable_layer_size(const std::string& container_id); std::unique_ptr m_async_source; std::unique_ptr<::libsinsp::cri::cri_interface_v1alpha2> m_cri_v1alpha2; std::unique_ptr<::libsinsp::cri::cri_interface_v1> m_cri_v1; }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/docker/async_source.cpp b/userspace/libsinsp/container_engine/docker/async_source.cpp index bf06edda9b..7941f8a918 100644 --- a/userspace/libsinsp/container_engine/docker/async_source.cpp +++ b/userspace/libsinsp/container_engine/docker/async_source.cpp @@ -28,52 +28,42 @@ using namespace libsinsp::container_engine; bool docker_async_source::m_query_image_info = true; docker_async_source::docker_async_source(uint64_t max_wait_ms, - uint64_t ttl_ms, - container_cache_interface *cache) - : container_async_source(max_wait_ms, ttl_ms, cache) -{ -} + uint64_t ttl_ms, + container_cache_interface* cache): + container_async_source(max_wait_ms, ttl_ms, cache) {} -docker_async_source::~docker_async_source() -{ +docker_async_source::~docker_async_source() { this->stop(); - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async: Source destructor"); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "docker_async: Source destructor"); } -bool docker_async_source::get_k8s_pod_spec(const Json::Value &config_obj, - Json::Value &spec) -{ +bool docker_async_source::get_k8s_pod_spec(const Json::Value& config_obj, Json::Value& spec) { std::string cfg_str; Json::Reader reader; std::string k8s_label = "annotation.kubectl.kubernetes.io/last-applied-configuration"; - if(config_obj.isNull() || - !config_obj.isMember("Labels") || - !config_obj["Labels"].isMember(k8s_label)) - { + if(config_obj.isNull() || !config_obj.isMember("Labels") || + !config_obj["Labels"].isMember(k8s_label)) { return false; } // The pod spec is stored as a stringified json label on the container cfg_str = config_obj["Labels"][k8s_label].asString(); - if(cfg_str == "") - { + if(cfg_str == "") { return false; } Json::Value cfg; - if(!reader.parse(cfg_str.c_str(), cfg)) - { - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Could not parse pod config '%s'", cfg_str.c_str()); + if(!reader.parse(cfg_str.c_str(), cfg)) { + libsinsp_logger()->format(sinsp_logger::SEV_WARNING, + "Could not parse pod config '%s'", + cfg_str.c_str()); return false; } - if(!cfg.isMember("spec") || - !cfg["spec"].isMember("containers") || - !cfg["spec"]["containers"].isArray()) - { + if(!cfg.isMember("spec") || !cfg["spec"].isMember("containers") || + !cfg["spec"]["containers"].isArray()) { return false; } @@ -83,20 +73,16 @@ bool docker_async_source::get_k8s_pod_spec(const Json::Value &config_obj, return true; } -std::string docker_async_source::normalize_arg(const std::string &arg) -{ +std::string docker_async_source::normalize_arg(const std::string& arg) { std::string ret = arg; - if(ret.empty()) - { + if(ret.empty()) { return ret; } // Remove pairs of leading/trailing " or ' chars, if present - while(ret.front() == '"' || ret.front() == '\'') - { - if(ret.back() == ret.front()) - { + while(ret.front() == '"' || ret.front() == '\'') { + if(ret.back() == ret.front()) { ret.pop_back(); ret.erase(0, 1); } @@ -105,68 +91,69 @@ std::string docker_async_source::normalize_arg(const std::string &arg) return ret; } -void docker_async_source::parse_healthcheck(const Json::Value &healthcheck_obj, - sinsp_container_info &container) -{ +void docker_async_source::parse_healthcheck(const Json::Value& healthcheck_obj, + sinsp_container_info& container) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker (%s): Trying to parse healthcheck from %s", - container.m_id.c_str(), Json::FastWriter().write(healthcheck_obj).c_str()); + "docker (%s): Trying to parse healthcheck from %s", + container.m_id.c_str(), + Json::FastWriter().write(healthcheck_obj).c_str()); - if(healthcheck_obj.isNull()) - { - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Could not parse health check from %s (No Healthcheck property)", - Json::FastWriter().write(healthcheck_obj).c_str()); + if(healthcheck_obj.isNull()) { + libsinsp_logger()->format(sinsp_logger::SEV_WARNING, + "Could not parse health check from %s (No Healthcheck property)", + Json::FastWriter().write(healthcheck_obj).c_str()); return; } - if(!healthcheck_obj.isMember("Test")) - { - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Could not parse health check from %s (Healthcheck does not have Test property)", - Json::FastWriter().write(healthcheck_obj).c_str()); + if(!healthcheck_obj.isMember("Test")) { + libsinsp_logger()->format( + sinsp_logger::SEV_WARNING, + "Could not parse health check from %s (Healthcheck does not have Test property)", + Json::FastWriter().write(healthcheck_obj).c_str()); return; } - const Json::Value &test_obj = healthcheck_obj["Test"]; + const Json::Value& test_obj = healthcheck_obj["Test"]; - if(!test_obj.isArray()) - { - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Could not parse health check from %s (Healthcheck Test property is not array)", - Json::FastWriter().write(healthcheck_obj).c_str()); + if(!test_obj.isArray()) { + libsinsp_logger()->format( + sinsp_logger::SEV_WARNING, + "Could not parse health check from %s (Healthcheck Test property is not array)", + Json::FastWriter().write(healthcheck_obj).c_str()); return; } - if(test_obj.size() == 1) - { - if(test_obj[0].asString() != "NONE") - { - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Could not parse health check from %s (Expected NONE for single-element Test array)", - Json::FastWriter().write(healthcheck_obj).c_str()); + if(test_obj.size() == 1) { + if(test_obj[0].asString() != "NONE") { + libsinsp_logger()->format(sinsp_logger::SEV_WARNING, + "Could not parse health check from %s (Expected NONE for " + "single-element Test array)", + Json::FastWriter().write(healthcheck_obj).c_str()); } return; } - if(test_obj[0].asString() == "CMD") - { + if(test_obj[0].asString() == "CMD") { std::string exe = normalize_arg(test_obj[1].asString()); std::vector args; - for(uint32_t i = 2; i < test_obj.size(); i++) - { + for(uint32_t i = 2; i < test_obj.size(); i++) { args.push_back(normalize_arg(test_obj[i].asString())); } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker (%s): Setting PT_HEALTHCHECK exe=%s nargs=%d", - container.m_id.c_str(), exe.c_str(), args.size()); - - container.m_health_probes.emplace_back(sinsp_container_info::container_health_probe::PT_HEALTHCHECK, - std::move(exe), - std::move(args)); - } - else if(test_obj[0].asString() == "CMD-SHELL") - { + "docker (%s): Setting PT_HEALTHCHECK exe=%s nargs=%d", + container.m_id.c_str(), + exe.c_str(), + args.size()); + + container.m_health_probes.emplace_back( + sinsp_container_info::container_health_probe::PT_HEALTHCHECK, + std::move(exe), + std::move(args)); + } else if(test_obj[0].asString() == "CMD-SHELL") { std::string exe = "/bin/sh"; std::vector args; @@ -174,52 +161,54 @@ void docker_async_source::parse_healthcheck(const Json::Value &healthcheck_obj, args.push_back(test_obj[1].asString()); libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker (%s): Setting PT_HEALTHCHECK exe=%s nargs=%d", - container.m_id.c_str(), exe.c_str(), args.size()); - - container.m_health_probes.emplace_back(sinsp_container_info::container_health_probe::PT_HEALTHCHECK, - std::move(exe), - std::move(args)); - } - else - { - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Could not parse health check from %s (Expected CMD/CMD-SHELL for multi-element Test array)", - Json::FastWriter().write(healthcheck_obj).c_str()); + "docker (%s): Setting PT_HEALTHCHECK exe=%s nargs=%d", + container.m_id.c_str(), + exe.c_str(), + args.size()); + + container.m_health_probes.emplace_back( + sinsp_container_info::container_health_probe::PT_HEALTHCHECK, + std::move(exe), + std::move(args)); + } else { + libsinsp_logger()->format(sinsp_logger::SEV_WARNING, + "Could not parse health check from %s (Expected CMD/CMD-SHELL " + "for multi-element Test array)", + Json::FastWriter().write(healthcheck_obj).c_str()); return; } } -bool docker_async_source::parse_liveness_readiness_probe(const Json::Value &probe_obj, - sinsp_container_info::container_health_probe::probe_type ptype, - sinsp_container_info &container) -{ - if(probe_obj.isNull() || - !probe_obj.isMember("exec") || - !probe_obj["exec"].isMember("command")) - { - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Could not parse liveness/readiness probe from %s", - Json::FastWriter().write(probe_obj).c_str()); +bool docker_async_source::parse_liveness_readiness_probe( + const Json::Value& probe_obj, + sinsp_container_info::container_health_probe::probe_type ptype, + sinsp_container_info& container) { + if(probe_obj.isNull() || !probe_obj.isMember("exec") || + !probe_obj["exec"].isMember("command")) { + libsinsp_logger()->format(sinsp_logger::SEV_WARNING, + "Could not parse liveness/readiness probe from %s", + Json::FastWriter().write(probe_obj).c_str()); return false; } const Json::Value command_obj = probe_obj["exec"]["command"]; - if(!command_obj.isNull() && command_obj.isArray()) - { + if(!command_obj.isNull() && command_obj.isArray()) { std::string exe; std::vector args; exe = normalize_arg(command_obj[0].asString()); - for(uint32_t i = 1; i < command_obj.size(); i++) - { + for(uint32_t i = 1; i < command_obj.size(); i++) { args.push_back(normalize_arg(command_obj[i].asString())); } - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker (%s): Setting %s exe=%s nargs=%d", - container.m_id.c_str(), - sinsp_container_info::container_health_probe::probe_type_names[ptype].c_str(), - exe.c_str(), args.size()); + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "docker (%s): Setting %s exe=%s nargs=%d", + container.m_id.c_str(), + sinsp_container_info::container_health_probe::probe_type_names[ptype].c_str(), + exe.c_str(), + args.size()); container.m_health_probes.emplace_back(ptype, std::move(exe), std::move(args)); } @@ -227,244 +216,220 @@ bool docker_async_source::parse_liveness_readiness_probe(const Json::Value &prob return true; } -bool docker_async_source::get_sandbox_liveness_readiness_probes(const Json::Value &config_obj, - sinsp_container_info &container) -{ +bool docker_async_source::get_sandbox_liveness_readiness_probes(const Json::Value& config_obj, + sinsp_container_info& container) { std::string sandbox_container_id; std::string sandbox_label = "io.kubernetes.sandbox.id"; - if(config_obj.isNull() || - !config_obj.isMember("Labels") || - !config_obj["Labels"].isMember(sandbox_label)) - { + if(config_obj.isNull() || !config_obj.isMember("Labels") || + !config_obj["Labels"].isMember(sandbox_label)) { SINSP_DEBUG("docker (%s): No sandbox label found, not copying liveness/readiness probes", - container.m_id.c_str()); + container.m_id.c_str()); return false; } sandbox_container_id = config_obj["Labels"][sandbox_label].asString(); - if(sandbox_container_id.size() > 12) - { + if(sandbox_container_id.size() > 12) { sandbox_container_id.resize(12); } sinsp_container_info::ptr_t sandbox_container = m_cache->get_container(sandbox_container_id); - if(!sandbox_container) - { - SINSP_DEBUG("docker (%s): Sandbox container %s doesn't exist, not copying liveness/readiness probes", - container.m_id.c_str(), sandbox_container_id.c_str()); + if(!sandbox_container) { + SINSP_DEBUG( + "docker (%s): Sandbox container %s doesn't exist, not copying liveness/readiness " + "probes", + container.m_id.c_str(), + sandbox_container_id.c_str()); return false; } - if(sandbox_container->m_health_probes.size() == 0) - { - SINSP_DEBUG("docker (%s): Sandbox container %s has no liveness/readiness probes, not copying", - container.m_id.c_str(), sandbox_container_id.c_str()); + if(sandbox_container->m_health_probes.size() == 0) { + SINSP_DEBUG( + "docker (%s): Sandbox container %s has no liveness/readiness probes, not copying", + container.m_id.c_str(), + sandbox_container_id.c_str()); return false; } SINSP_DEBUG("docker (%s): Copying liveness/readiness probes from sandbox container %s", - container.m_id.c_str(), sandbox_container_id.c_str()); + container.m_id.c_str(), + sandbox_container_id.c_str()); container.m_health_probes = sandbox_container->m_health_probes; return true; } -void docker_async_source::parse_health_probes(const Json::Value &config_obj, - sinsp_container_info &container) -{ +void docker_async_source::parse_health_probes(const Json::Value& config_obj, + sinsp_container_info& container) { Json::Value spec; bool liveness_readiness_added = false; - // When parsing the full container json for live containers, a label contains stringified json that - // contains the probes. - if (get_k8s_pod_spec(config_obj, spec)) - { + // When parsing the full container json for live containers, a label contains stringified json + // that contains the probes. + if(get_k8s_pod_spec(config_obj, spec)) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker (%s): Parsing liveness/readiness probes from pod spec", - container.m_id.c_str()); - - if(spec.isMember("livenessProbe")) - { - if(parse_liveness_readiness_probe(spec["livenessProbe"], - sinsp_container_info::container_health_probe::PT_LIVENESS_PROBE, - container)) - { + "docker (%s): Parsing liveness/readiness probes from pod spec", + container.m_id.c_str()); + + if(spec.isMember("livenessProbe")) { + if(parse_liveness_readiness_probe( + spec["livenessProbe"], + sinsp_container_info::container_health_probe::PT_LIVENESS_PROBE, + container)) { liveness_readiness_added = true; } - } - else if(spec.isMember("readinessProbe")) - { - if(parse_liveness_readiness_probe(spec["readinessProbe"], - sinsp_container_info::container_health_probe::PT_READINESS_PROBE, - container)) - { + } else if(spec.isMember("readinessProbe")) { + if(parse_liveness_readiness_probe( + spec["readinessProbe"], + sinsp_container_info::container_health_probe::PT_READINESS_PROBE, + container)) { liveness_readiness_added = true; } } } - // Otherwise, try to copy the liveness/readiness probe from the sandbox container, if it exists. - else if (get_sandbox_liveness_readiness_probes(config_obj, container)) - { + // Otherwise, try to copy the liveness/readiness probe from the sandbox container, if it exists. + else if(get_sandbox_liveness_readiness_probes(config_obj, container)) { liveness_readiness_added = true; - } - else - { + } else { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker (%s): No liveness/readiness probes found", - container.m_id.c_str()); + "docker (%s): No liveness/readiness probes found", + container.m_id.c_str()); } // To avoid any confusion about containers that both refer to // a healthcheck and liveness/readiness probe, we only // consider a healthcheck if no liveness/readiness was added. - if(!liveness_readiness_added && config_obj.isMember("Healthcheck")) - { + if(!liveness_readiness_added && config_obj.isMember("Healthcheck")) { parse_healthcheck(config_obj["Healthcheck"], container); } } -void docker_async_source::set_query_image_info(bool query_image_info) -{ +void docker_async_source::set_query_image_info(bool query_image_info) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async: Setting query_image_info=%s", - (query_image_info ? "true" : "false")); + "docker_async: Setting query_image_info=%s", + (query_image_info ? "true" : "false")); m_query_image_info = query_image_info; } -void docker_async_source::fetch_image_info(const docker_lookup_request& request, sinsp_container_info& container) -{ +void docker_async_source::fetch_image_info(const docker_lookup_request& request, + sinsp_container_info& container) { Json::Reader reader; libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s) image (%s): Fetching image info", - request.container_id.c_str(), - container.m_imageid.c_str()); + "docker_async (%s) image (%s): Fetching image info", + request.container_id.c_str(), + container.m_imageid.c_str()); std::string img_json; std::string url = "/images/" + container.m_imageid + "/json?digests=1"; - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async url: %s", - url.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "docker_async url: %s", url.c_str()); - if(m_connection.get_docker(request, url, img_json) != docker_connection::RESP_OK) - { + if(m_connection.get_docker(request, url, img_json) != docker_connection::RESP_OK) { libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s) image (%s): Could not fetch image info", - request.container_id.c_str(), - container.m_imageid.c_str()); + "docker_async (%s) image (%s): Could not fetch image info", + request.container_id.c_str(), + container.m_imageid.c_str()); return; } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s) image (%s): Image info fetch returned \"%s\"", - request.container_id.c_str(), - container.m_imageid.c_str(), - img_json.c_str()); + "docker_async (%s) image (%s): Image info fetch returned \"%s\"", + request.container_id.c_str(), + container.m_imageid.c_str(), + img_json.c_str()); Json::Value img_root; - if(!reader.parse(img_json, img_root)) - { - libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s) image (%s): Could not parse json image info \"%s\"", - request.container_id.c_str(), - container.m_imageid.c_str(), - img_json.c_str()); + if(!reader.parse(img_json, img_root)) { + libsinsp_logger()->format( + sinsp_logger::SEV_ERROR, + "docker_async (%s) image (%s): Could not parse json image info \"%s\"", + request.container_id.c_str(), + container.m_imageid.c_str(), + img_json.c_str()); return; } parse_image_info(container, img_root); } -void docker_async_source::fetch_image_info_from_list(const docker_lookup_request& request, sinsp_container_info& container) -{ +void docker_async_source::fetch_image_info_from_list(const docker_lookup_request& request, + sinsp_container_info& container) { Json::Reader reader; libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Fetching image list", - request.container_id.c_str()); + "docker_async (%s): Fetching image list", + request.container_id.c_str()); std::string img_json; std::string url = "/images/json?digests=1"; - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async url: %s", - url.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "docker_async url: %s", url.c_str()); /* - * Apparently at least the RHEL9 version of podman doesn't properly respond - * to /images/json?digests=1, while it does return all the info we need - * without the query parameter. - * - * Since ?digests=1 is defined in the Docker API, prefer this as the default, - * but also try the podman variant. - * - * Note: the API does not return an HTTP error but instead an empty 200 response, - * so checking the HTTP status is not enough. - */ - if(m_connection.get_docker(request, url, img_json) != docker_connection::RESP_OK - || img_json.empty()) - { - libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s): Could not fetch image list; trying without ?digests=1", - request.container_id.c_str()); + * Apparently at least the RHEL9 version of podman doesn't properly respond + * to /images/json?digests=1, while it does return all the info we need + * without the query parameter. + * + * Since ?digests=1 is defined in the Docker API, prefer this as the default, + * but also try the podman variant. + * + * Note: the API does not return an HTTP error but instead an empty 200 response, + * so checking the HTTP status is not enough. + */ + if(m_connection.get_docker(request, url, img_json) != docker_connection::RESP_OK || + img_json.empty()) { + libsinsp_logger()->format( + sinsp_logger::SEV_ERROR, + "docker_async (%s): Could not fetch image list; trying without ?digests=1", + request.container_id.c_str()); std::string url = "/images/json"; - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async url: %s", - url.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "docker_async url: %s", url.c_str()); - if(m_connection.get_docker(request, url, img_json) != docker_connection::RESP_OK - || img_json.empty()) - { + if(m_connection.get_docker(request, url, img_json) != docker_connection::RESP_OK || + img_json.empty()) { libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s): Could not fetch image list", - request.container_id.c_str()); + "docker_async (%s): Could not fetch image list", + request.container_id.c_str()); return; } } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Image list fetch returned \"%s\"", - request.container_id.c_str(), - img_json.c_str()); + "docker_async (%s): Image list fetch returned \"%s\"", + request.container_id.c_str(), + img_json.c_str()); Json::Value img_root; - if(!reader.parse(img_json, img_root)) - { + if(!reader.parse(img_json, img_root)) { libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s): Could not parse json image list \"%s\"", - request.container_id.c_str(), - img_json.c_str()); + "docker_async (%s): Could not parse json image list \"%s\"", + request.container_id.c_str(), + img_json.c_str()); return; } const std::string match_name = container.m_imagerepo + ':' + container.m_imagetag; - for(const auto& img : img_root) - { + for(const auto& img : img_root) { // the "Names" field is podman specific. we could parse repotags // twice but this is less effort and we only call this function // for podman anyway const auto& names = img["Names"]; - if(!names.isArray()) - { + if(!names.isArray()) { return; } - for(const auto& name : names) - { - if(name == match_name) - { + for(const auto& name : names) { + if(name == match_name) { std::string imgstr = img["Id"].asString(); size_t cpos = imgstr.find(':'); - if(cpos != std::string::npos) - { + if(cpos != std::string::npos) { imgstr = imgstr.substr(cpos + 1); } container.m_imageid = std::move(imgstr); @@ -476,18 +441,15 @@ void docker_async_source::fetch_image_info_from_list(const docker_lookup_request } } -void docker_async_source::parse_image_info(sinsp_container_info& container, const Json::Value& img) -{ +void docker_async_source::parse_image_info(sinsp_container_info& container, + const Json::Value& img) { const auto& podman_digest = img["Digest"]; - if(podman_digest.isString()) - { + if(podman_digest.isString()) { // img["Digest"] if present is the digest in the form we need it // e.g. "sha256:b6a9fc3535388a6fc04f3bdb83fb4d9d0b4ffd85e7609a6ff2f0f731427823e3" // so just use it directly container.m_imagedigest = podman_digest.asString(); - } - else - { + } else { // img_root["RepoDigests"] contains only digests for images pulled from registries. // If an image gets retagged and is never pushed to any registry, we will not find // that entry in container.m_imagerepo. Also, for locally built images we have the @@ -498,19 +460,15 @@ void docker_async_source::parse_image_info(sinsp_container_info& container, cons // so we need to split it at the `@` (the part before is the repo, // the part after is the digest) std::unordered_set imageDigestSet; - for(const auto& rdig : img["RepoDigests"]) - { - if(rdig.isString()) - { + for(const auto& rdig : img["RepoDigests"]) { + if(rdig.isString()) { std::string repodigest = rdig.asString(); - std::string digest = repodigest.substr(repodigest.find('@')+1); + std::string digest = repodigest.substr(repodigest.find('@') + 1); imageDigestSet.insert(digest); - if(container.m_imagerepo.empty()) - { + if(container.m_imagerepo.empty()) { container.m_imagerepo = repodigest.substr(0, repodigest.find('@')); } - if(repodigest.find(container.m_imagerepo) != std::string::npos) - { + if(repodigest.find(container.m_imagerepo) != std::string::npos) { container.m_imagedigest = digest; break; } @@ -523,45 +481,41 @@ void docker_async_source::parse_image_info(sinsp_container_info& container, cons container.m_imagedigest = *imageDigestSet.begin(); } } - for(const auto& rtag : img["RepoTags"]) - { - if(rtag.isString()) - { + for(const auto& rtag : img["RepoTags"]) { + if(rtag.isString()) { std::string repotag = rtag.asString(); - if(container.m_imagerepo.empty()) - { + if(container.m_imagerepo.empty()) { container.m_imagerepo = repotag.substr(0, repotag.rfind(':')); } - if(repotag.find(container.m_imagerepo) != std::string::npos) - { - container.m_imagetag = repotag.substr(repotag.rfind(':')+1); + if(repotag.find(container.m_imagerepo) != std::string::npos) { + container.m_imagetag = repotag.substr(repotag.rfind(':') + 1); break; } } } } -void docker_async_source::get_image_info(const docker_lookup_request& request, sinsp_container_info& container, const Json::Value& root) -{ +void docker_async_source::get_image_info(const docker_lookup_request& request, + sinsp_container_info& container, + const Json::Value& root) { container.m_image = root["Config"]["Image"].asString(); // podman has the image *name*, not the *id* in the Image field // detect that with the presence of '/' in the field std::string imgstr = root["Image"].asString(); - if(imgstr.find('/') == std::string::npos) - { + if(imgstr.find('/') == std::string::npos) { // no '/' in the Image field, assume it's a Docker image id size_t cpos = imgstr.find(':'); - if(cpos != std::string::npos) - { + if(cpos != std::string::npos) { container.m_imageid = imgstr.substr(cpos + 1); } // containers can be spawned using just the imageID as image name, // with or without the hash prefix (e.g. sha256:) // - // e.g. an image with the id `sha256:ddcca4b8a6f0367b5de2764dfe76b0a4bfa6d75237932185923705da47004347` - // can be used to run a container as: + // e.g. an image with the id + // `sha256:ddcca4b8a6f0367b5de2764dfe76b0a4bfa6d75237932185923705da47004347` can be used to + // run a container as: // - docker run sha256:ddcca4b8a6f0367b5de2764dfe76b0a4bfa6d75237932185923705da47004347 // - docker run ddcca4b8a6f0367b5de2764dfe76b0a4bfa6d75237932185923705da47004347 // - docker run sha256:ddcca4 @@ -574,85 +528,77 @@ void docker_async_source::get_image_info(const docker_lookup_request& request, s // (available in container.m_image) is the repo name like `redis` // and use that to determine the name and tag bool no_name = sinsp_utils::startswith(container.m_imageid, container.m_image) || - sinsp_utils::startswith(imgstr, container.m_image); + sinsp_utils::startswith(imgstr, container.m_image); - if(!no_name || !m_query_image_info) - { + if(!no_name || !m_query_image_info) { std::string hostname, port; sinsp_utils::split_container_image(container.m_image, - hostname, - port, - container.m_imagerepo, - container.m_imagetag, - container.m_imagedigest, - false); + hostname, + port, + container.m_imagerepo, + container.m_imagetag, + container.m_imagedigest, + false); } if(m_query_image_info && !container.m_imageid.empty() && - (no_name || container.m_imagedigest.empty() || container.m_imagetag.empty())) - { + (no_name || container.m_imagedigest.empty() || container.m_imagetag.empty())) { fetch_image_info(request, container); } - if(container.m_imagetag.empty()) - { + if(container.m_imagetag.empty()) { container.m_imagetag = "latest"; } - } - else - { + } else { // a '/' is present in the Image field. Parse it into parts std::string hostname, port; sinsp_utils::split_container_image(imgstr, - hostname, - port, - container.m_imagerepo, - container.m_imagetag, - container.m_imagedigest, - false); + hostname, + port, + container.m_imagerepo, + container.m_imagetag, + container.m_imagedigest, + false); // we need the tag set in the call to `fetch_image_from_list` // so set it here instead of after the if/else - if(container.m_imagetag.empty()) - { + if(container.m_imagetag.empty()) { container.m_imagetag = "latest"; } // we don't have the image id so we need to list all images // and find the matching one by comparing the repo names - if(m_query_image_info) - { + if(m_query_image_info) { fetch_image_info_from_list(request, container); } } - } -void docker_async_source::parse_json_mounts(const Json::Value &mnt_obj, std::vector &mounts) -{ - if(!mnt_obj.isNull() && mnt_obj.isArray()) - { - for(uint32_t i=0; i& mounts) { + if(!mnt_obj.isNull() && mnt_obj.isArray()) { + for(uint32_t i = 0; i < mnt_obj.size(); i++) { + const Json::Value& mount = mnt_obj[i]; + mounts.emplace_back(mount["Source"], + mount["Destination"], + mount["Mode"], + mount["RW"], + mount["Propagation"]); } } } - -bool docker_async_source::parse(const docker_lookup_request& request, sinsp_container_info& container) -{ +bool docker_async_source::parse(const docker_lookup_request& request, + sinsp_container_info& container) { std::string json; libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Looking up info for container via socket %s", - request.container_id.c_str(), request.docker_socket.c_str()); + "docker_async (%s): Looking up info for container via socket %s", + request.container_id.c_str(), + request.docker_socket.c_str()); std::string api_request = "/containers/" + request.container_id + "/json"; - if(request.request_rw_size) - { + if(request.request_rw_size) { api_request += "?size=true"; } @@ -660,23 +606,25 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont switch(resp) { case docker_connection::docker_response::RESP_BAD_REQUEST: - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Initial url fetch failed, trying w/o api version", - request.container_id.c_str()); + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "docker_async (%s): Initial url fetch failed, trying w/o api version", + request.container_id.c_str()); m_connection.set_api_version(""); json = ""; - resp = m_connection.get_docker(request, "/containers/" + request.container_id + "/json", json); - if (resp == docker_connection::docker_response::RESP_OK) - { + resp = m_connection.get_docker(request, + "/containers/" + request.container_id + "/json", + json); + if(resp == docker_connection::docker_response::RESP_OK) { break; } /* FALLTHRU */ case docker_connection::docker_response::RESP_ERROR: case docker_connection::docker_response::RESP_TIMEOUT: libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Url fetch failed, returning false", - request.container_id.c_str()); + "docker_async (%s): Url fetch failed, returning false", + request.container_id.c_str()); return false; case docker_connection::docker_response::RESP_OK: @@ -684,30 +632,28 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Parsing containers response \"%s\"", - request.container_id.c_str(), - json.c_str()); + "docker_async (%s): Parsing containers response \"%s\"", + request.container_id.c_str(), + json.c_str()); Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(json, root); - if(!parsingSuccessful) - { + if(!parsingSuccessful) { libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s): Could not parse json \"%s\", returning false", - request.container_id.c_str(), - json.c_str()); + "docker_async (%s): Could not parse json \"%s\", returning false", + request.container_id.c_str(), + json.c_str()); ASSERT(false); return false; } - + get_image_info(request, container, root); const Json::Value& config_obj = root["Config"]; const Json::Value& user = config_obj["User"]; - if(!user.isNull()) - { + if(!user.isNull()) { container.m_container_user = user.asString(); } @@ -716,30 +662,27 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont container.m_full_id = root["Id"].asString(); container.m_name = root["Name"].asString(); // k8s Docker container names could have '/' as the first character. - if(!container.m_name.empty() && container.m_name[0] == '/') - { + if(!container.m_name.empty() && container.m_name[0] == '/') { container.m_name = container.m_name.substr(1); } - if(container.m_name.find("k8s_POD") == 0) - { + if(container.m_name.find("k8s_POD") == 0) { container.m_is_pod_sandbox = true; } // Get the created time - this will be string format i.e. "%Y-%m-%dT%H:%M:%SZ" // Convert it to seconds. This can be done with get_epoc_utc_seconds() - container.m_created_time = static_cast(get_epoch_utc_seconds(root["Created"].asString())); + container.m_created_time = + static_cast(get_epoch_utc_seconds(root["Created"].asString())); const Json::Value& net_obj = root["NetworkSettings"]; std::string ip = net_obj["IPAddress"].asString(); - if(ip.empty()) - { + if(ip.empty()) { const Json::Value& hconfig_obj = root["HostConfig"]; std::string net_mode = hconfig_obj["NetworkMode"].asString(); - if(strncmp(net_mode.c_str(), "container:", strlen("container:")) == 0) - { + if(strncmp(net_mode.c_str(), "container:", strlen("container:")) == 0) { std::string secondary_container_id = net_mode.substr(net_mode.find(":") + 1); sinsp_container_info pcnt; @@ -749,64 +692,56 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont // secondary container, but we're in a // separate thread so this is ok. libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s), secondary (%s): Doing blocking fetch of secondary container", - request.container_id.c_str(), - secondary_container_id.c_str()); + "docker_async (%s), secondary (%s): Doing blocking fetch of " + "secondary container", + request.container_id.c_str(), + secondary_container_id.c_str()); if(parse(docker_lookup_request(secondary_container_id, - request.docker_socket, - request.container_type, - request.uid, - false /*don't request size since we just need the IP*/), - pcnt)) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s), secondary (%s): Secondary fetch successful", - request.container_id.c_str(), - secondary_container_id.c_str()); + request.docker_socket, + request.container_type, + request.uid, + false /*don't request size since we just need the IP*/), + pcnt)) { + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "docker_async (%s), secondary (%s): Secondary fetch successful", + request.container_id.c_str(), + secondary_container_id.c_str()); container.m_container_ip = pcnt.m_container_ip; - } - else - { - libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s), secondary (%s): Secondary fetch failed", - request.container_id.c_str(), - secondary_container_id.c_str()); + } else { + libsinsp_logger()->format( + sinsp_logger::SEV_ERROR, + "docker_async (%s), secondary (%s): Secondary fetch failed", + request.container_id.c_str(), + secondary_container_id.c_str()); } } - } - else - { - if(inet_pton(AF_INET, ip.c_str(), &container.m_container_ip) == -1) - { + } else { + if(inet_pton(AF_INET, ip.c_str(), &container.m_container_ip) == -1) { ASSERT(false); } container.m_container_ip = ntohl(container.m_container_ip); } std::vector ports = net_obj["Ports"].getMemberNames(); - for(std::vector::const_iterator it = ports.begin(); it != ports.end(); ++it) - { + for(std::vector::const_iterator it = ports.begin(); it != ports.end(); ++it) { size_t tcp_pos = it->find("/tcp"); - if(tcp_pos == std::string::npos) - { + if(tcp_pos == std::string::npos) { continue; } uint16_t container_port = atoi(it->c_str()); const Json::Value& v = net_obj["Ports"][*it]; - if(v.isArray()) - { - for(uint32_t j = 0; j < v.size(); ++j) - { + if(v.isArray()) { + for(uint32_t j = 0; j < v.size(); ++j) { sinsp_container_info::container_port_mapping port_mapping; ip = v[j]["HostIp"].asString(); std::string port = v[j]["HostPort"].asString(); - if(inet_pton(AF_INET, ip.c_str(), &port_mapping.m_host_ip) == -1) - { + if(inet_pton(AF_INET, ip.c_str(), &port_mapping.m_host_ip) == -1) { ASSERT(false); continue; } @@ -820,32 +755,25 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont } std::vector labels = config_obj["Labels"].getMemberNames(); - for(std::vector::const_iterator it = labels.begin(); it != labels.end(); ++it) - { + for(std::vector::const_iterator it = labels.begin(); it != labels.end(); ++it) { std::string val = config_obj["Labels"][*it].asString(); - if(val.length() <= sinsp_container_info::m_container_label_max_length ) { + if(val.length() <= sinsp_container_info::m_container_label_max_length) { container.m_labels[*it] = val; } } - if(request.container_type == sinsp_container_type::CT_PODMAN) - { - if(request.uid == 0) - { + if(request.container_type == sinsp_container_type::CT_PODMAN) { + if(request.uid == 0) { container.m_labels.erase("podman_owner_uid"); - } - else - { + } else { container.m_labels["podman_owner_uid"] = std::to_string(request.uid); } } const Json::Value& env_vars = config_obj["Env"]; - for(const auto& env_var : env_vars) - { - if(env_var.isString()) - { + for(const auto& env_var : env_vars) { + if(env_var.isString()) { container.m_env.emplace_back(env_var.asString()); } } @@ -854,8 +782,7 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont container.m_memory_limit = host_config_obj["Memory"].asInt64(); container.m_swap_limit = host_config_obj["MemorySwap"].asInt64(); const auto cpu_shares = host_config_obj["CpuShares"].asInt64(); - if(cpu_shares > 0) - { + if(cpu_shares > 0) { container.m_cpu_shares = cpu_shares; } @@ -863,38 +790,37 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont * 2 separate docker APIs use CFS CPU scheduler to constrain container CPU usage * Reference: https://docs.docker.com/engine/reference/run/ * 1) docker run --cpus= - * is converted into a cfs_cpu_quota value for the default cfs_cpu_period=100000 - * cfs_cpu_period cannot be changed with this API - * For example, if =0.5, cfs_cpu_quota=50000 and cfs_cpu_period=100000 - * 2) docker run --cpu-quota= --cpu-period= - * CFS quota and/or period can be set directly. The default period is 100000 and default quota - * is 0 (which translates to unconstrained) - * For example, if =12345 and =67890, then cfs_cpu_quota=12345 and cfs_cpu_period=67890 - * These 2 APIs are mutually exclusive: docker throws an error if an attempt is made to use --cpus in combination - * with either --cpu-quota or --cpu-period + * is converted into a cfs_cpu_quota value for the default + * cfs_cpu_period=100000 cfs_cpu_period cannot be changed with this API For example, if =0.5, cfs_cpu_quota=50000 and cfs_cpu_period=100000 2) docker run --cpu-quota= + * --cpu-period= CFS quota and/or period can be set directly. The default period is + * 100000 and default quota is 0 (which translates to unconstrained) For example, if + * =12345 and =67890, then cfs_cpu_quota=12345 and cfs_cpu_period=67890 These 2 + * APIs are mutually exclusive: docker throws an error if an attempt is made to use --cpus in + * combination with either --cpu-quota or --cpu-period * * docker_response json output: * 1) When --cpus is used, the value is returned as NanoCpus; both CpuQuota and CpuPeriod are 0 - * Since cfs_cpu_period=100000=10^5 and 10^9 NanoCpus is 1 CPU, which translates to cfs_cpu_quota=100000=10^5, - * we need to divide NanoCpus by 10^4=10000 to convert NanoCpus into cfs_cpu_quota + * Since cfs_cpu_period=100000=10^5 and 10^9 NanoCpus is 1 CPU, which translates to + * cfs_cpu_quota=100000=10^5, we need to divide NanoCpus by 10^4=10000 to convert NanoCpus into + * cfs_cpu_quota * - * 2) When --cpu-quota and/or --cpu-period are used, the corresponding values are returned; NanoCpus is 0 + * 2) When --cpu-quota and/or --cpu-period are used, the corresponding values are returned; + * NanoCpus is 0 */ - container.m_cpu_quota = std::max(host_config_obj["CpuQuota"].asInt64(), host_config_obj["NanoCpus"].asInt64()/10000); + container.m_cpu_quota = std::max(host_config_obj["CpuQuota"].asInt64(), + host_config_obj["NanoCpus"].asInt64() / 10000); const auto cpu_period = host_config_obj["CpuPeriod"].asInt64(); - if(cpu_period > 0) - { + if(cpu_period > 0) { container.m_cpu_period = cpu_period; } const auto cpuset_cpus = host_config_obj["CpusetCpus"].asString(); - if (!cpuset_cpus.empty()) - { + if(!cpuset_cpus.empty()) { libsinsp::cgroup_list_counter counter; container.m_cpuset_cpu_count = counter(cpuset_cpus.c_str()); } const Json::Value& privileged = host_config_obj["Privileged"]; - if(!privileged.isNull() && privileged.isBool()) - { + if(!privileged.isNull() && privileged.isBool()) { container.m_privileged = privileged.asBool(); } @@ -903,8 +829,7 @@ bool docker_async_source::parse(const docker_lookup_request& request, sinsp_cont container.m_size_rw_bytes = root["SizeRw"].asInt64(); libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): parse returning true", - request.container_id.c_str()); + "docker_async (%s): parse returning true", + request.container_id.c_str()); return true; } - diff --git a/userspace/libsinsp/container_engine/docker/async_source.h b/userspace/libsinsp/container_engine/docker/async_source.h index 8cb3aa96e2..4d7283924d 100644 --- a/userspace/libsinsp/container_engine/docker/async_source.h +++ b/userspace/libsinsp/container_engine/docker/async_source.h @@ -11,15 +11,15 @@ namespace container_engine { class container_cache_interface; -class docker_async_source : public container_async_source -{ +class docker_async_source : public container_async_source { using key_type = docker_lookup_request; public: - docker_async_source(uint64_t max_wait_ms, uint64_t ttl_ms, container_cache_interface *cache); + docker_async_source(uint64_t max_wait_ms, uint64_t ttl_ms, container_cache_interface* cache); virtual ~docker_async_source(); - static void parse_json_mounts(const Json::Value &mnt_obj, std::vector &mounts); + static void parse_json_mounts(const Json::Value& mnt_obj, + std::vector& mounts); static void set_query_image_info(bool query_image_info); private: @@ -27,34 +27,29 @@ class docker_async_source : public container_async_source const char* name() const override { return "docker"; }; - sinsp_container_type container_type(const key_type& key) const override - { + sinsp_container_type container_type(const key_type& key) const override { return key.container_type; } - std::string container_id(const key_type& key) const override - { - return key.container_id; - } + std::string container_id(const key_type& key) const override { return key.container_id; } // Look for a pod specification in this container's labels and // if found set spec to the pod spec. - bool get_k8s_pod_spec(const Json::Value &config_obj, - Json::Value &spec); + bool get_k8s_pod_spec(const Json::Value& config_obj, Json::Value& spec); - std::string normalize_arg(const std::string &arg); + std::string normalize_arg(const std::string& arg); // Parse a healthcheck out of the provided healthcheck object, // updating the container info with any healthcheck found. - void parse_healthcheck(const Json::Value &healthcheck_obj, - sinsp_container_info &container); + void parse_healthcheck(const Json::Value& healthcheck_obj, sinsp_container_info& container); // Parse either a readiness or liveness probe out of the // provided object, updating the container info with any probe // found. Returns true if the healthcheck/livenesss/readiness // probe info was found and could be parsed. - bool parse_liveness_readiness_probe(const Json::Value &probe_obj, - sinsp_container_info::container_health_probe::probe_type ptype, - sinsp_container_info &container); + bool parse_liveness_readiness_probe( + const Json::Value& probe_obj, + sinsp_container_info::container_health_probe::probe_type ptype, + sinsp_container_info& container); // See if this config has a io.kubernetes.sandbox.id label // referring to a different container. (NOTE: this is not the @@ -64,17 +59,18 @@ class docker_async_source : public container_async_source // sandbox container id was found, the corresponding container // was found, and if the health checks could be copied from // that container. - bool get_sandbox_liveness_readiness_probes(const Json::Value &config_obj, - sinsp_container_info &container); + bool get_sandbox_liveness_readiness_probes(const Json::Value& config_obj, + sinsp_container_info& container); // Parse all healthchecks/liveness probes/readiness probes out // of the provided object, updating the container info as required. - void parse_health_probes(const Json::Value &config_obj, - sinsp_container_info &container); + void parse_health_probes(const Json::Value& config_obj, sinsp_container_info& container); // Analyze the container JSON response and get the details about // the image, possibly executing extra API calls - void get_image_info(const docker_lookup_request& request, sinsp_container_info& container, const Json::Value& root); + void get_image_info(const docker_lookup_request& request, + sinsp_container_info& container, + const Json::Value& root); // Given the image info (either the result of /images//json, // or one of the items from the result of /images/json), find @@ -87,12 +83,12 @@ class docker_async_source : public container_async_source // Podman reports image repository/tag instead of the image id, // so to fetch the image digest we need to list all the images, // find one with matching repository/tag and get the digest from there - void fetch_image_info_from_list(const docker_lookup_request& request, sinsp_container_info& container); + void fetch_image_info_from_list(const docker_lookup_request& request, + sinsp_container_info& container); docker_connection m_connection; static bool m_query_image_info; }; - -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/docker/base.cpp b/userspace/libsinsp/container_engine/docker/base.cpp index b5b29a2da7..1f3f8351a0 100644 --- a/userspace/libsinsp/container_engine/docker/base.cpp +++ b/userspace/libsinsp/container_engine/docker/base.cpp @@ -4,19 +4,17 @@ using namespace libsinsp::container_engine; -void docker_base::cleanup() -{ +void docker_base::cleanup() { m_docker_info_source.reset(NULL); } -bool -docker_base::resolve_impl(sinsp_threadinfo *tinfo, const docker_lookup_request& request, bool query_os_for_missing_info) -{ +bool docker_base::resolve_impl(sinsp_threadinfo *tinfo, + const docker_lookup_request &request, + bool query_os_for_missing_info) { container_cache_interface *cache = &container_cache(); - if(!m_docker_info_source) - { + if(!m_docker_info_source) { libsinsp_logger()->log("docker_async: Creating docker async source", - sinsp_logger::SEV_DEBUG); + sinsp_logger::SEV_DEBUG); uint64_t max_wait_ms = 10000; auto src = new docker_async_source(docker_async_source::NO_WAIT_LOOKUP, max_wait_ms, cache); m_docker_info_source.reset(src); @@ -26,10 +24,8 @@ docker_base::resolve_impl(sinsp_threadinfo *tinfo, const docker_lookup_request& sinsp_container_info::ptr_t container_info = cache->get_container(request.container_id); - if(!container_info) - { - if(!query_os_for_missing_info) - { + if(!container_info) { + if(!query_os_for_missing_info) { auto container = sinsp_container_info(); container.m_type = request.container_type; container.m_id = request.container_id; @@ -38,14 +34,15 @@ docker_base::resolve_impl(sinsp_threadinfo *tinfo, const docker_lookup_request& return true; } - if(cache->should_lookup(request.container_id, request.container_type)) - { + if(cache->should_lookup(request.container_id, request.container_type)) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): No existing container info", - request.container_id.c_str()); + "docker_async (%s): No existing container info", + request.container_id.c_str()); // give docker a chance to return metadata for this container - cache->set_lookup_status(request.container_id, request.container_type, sinsp_container_lookup::state::STARTED); + cache->set_lookup_status(request.container_id, + request.container_type, + sinsp_container_lookup::state::STARTED); parse_docker(request, cache); } return false; @@ -57,38 +54,32 @@ docker_base::resolve_impl(sinsp_threadinfo *tinfo, const docker_lookup_request& return container_info->is_successful(); } -void docker_base::parse_docker(const docker_lookup_request& request, container_cache_interface *cache) -{ +void docker_base::parse_docker(const docker_lookup_request &request, + container_cache_interface *cache) { sinsp_container_info result; bool done; - if (cache->async_allowed()) - { + if(cache->async_allowed()) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Starting asynchronous lookup", - request.container_id.c_str()); + "docker_async (%s): Starting asynchronous lookup", + request.container_id.c_str()); done = m_docker_info_source->lookup(request, result); - } - else - { + } else { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Starting synchronous lookup", - request.container_id.c_str()); + "docker_async (%s): Starting synchronous lookup", + request.container_id.c_str()); done = m_docker_info_source->lookup_sync(request, result); } - if (done) - { + if(done) { // if a previous lookup call already found the metadata, process it now m_docker_info_source->source_callback(request, result); - if(cache->async_allowed()) - { + if(cache->async_allowed()) { // This should *never* happen, in async mode as ttl is 0 (never wait) libsinsp_logger()->format(sinsp_logger::SEV_ERROR, - "docker_async (%s): Unexpected immediate return from docker_info_source.lookup()", - request.container_id.c_str()); - + "docker_async (%s): Unexpected immediate return from " + "docker_info_source.lookup()", + request.container_id.c_str()); } } } - diff --git a/userspace/libsinsp/container_engine/docker/base.h b/userspace/libsinsp/container_engine/docker/base.h index 0da7b44622..d6093a5cb8 100644 --- a/userspace/libsinsp/container_engine/docker/base.h +++ b/userspace/libsinsp/container_engine/docker/base.h @@ -10,22 +10,21 @@ namespace container_engine { struct docker_lookup_request; -class docker_base : public container_engine_base -{ +class docker_base : public container_engine_base { public: - docker_base(container_cache_interface &cache) : container_engine_base(cache) - {} + docker_base(container_cache_interface &cache): container_engine_base(cache) {} void cleanup() override; protected: - void parse_docker(const docker_lookup_request& request, container_cache_interface *cache); + void parse_docker(const docker_lookup_request &request, container_cache_interface *cache); - bool resolve_impl(sinsp_threadinfo *tinfo, const docker_lookup_request& request, - bool query_os_for_missing_info); + bool resolve_impl(sinsp_threadinfo *tinfo, + const docker_lookup_request &request, + bool query_os_for_missing_info); std::unique_ptr m_docker_info_source; }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/docker/connection.h b/userspace/libsinsp/container_engine/docker/connection.h index 60a732e62a..8556d55790 100644 --- a/userspace/libsinsp/container_engine/docker/connection.h +++ b/userspace/libsinsp/container_engine/docker/connection.h @@ -15,31 +15,24 @@ namespace container_engine { class docker_connection { public: - enum docker_response { - RESP_OK = 0, - RESP_BAD_REQUEST = 1, - RESP_ERROR = 2, - RESP_TIMEOUT = 3 - }; + enum docker_response { RESP_OK = 0, RESP_BAD_REQUEST = 1, RESP_ERROR = 2, RESP_TIMEOUT = 3 }; docker_connection(); ~docker_connection(); - docker_response - get_docker(const docker_lookup_request& request, const std::string& req_url, std::string& json); + docker_response get_docker(const docker_lookup_request& request, + const std::string& req_url, + std::string& json); - void set_api_version(const std::string& api_version) - { - m_api_version = api_version; - } + void set_api_version(const std::string& api_version) { m_api_version = api_version; } private: std::string m_api_version; #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(MINIMAL_BUILD) - CURLM *m_curlm; + CURLM* m_curlm; #endif }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/docker/connection_linux.cpp b/userspace/libsinsp/container_engine/docker/connection_linux.cpp index c5f2ad3f47..22c7b23135 100644 --- a/userspace/libsinsp/container_engine/docker/connection_linux.cpp +++ b/userspace/libsinsp/container_engine/docker/connection_linux.cpp @@ -23,46 +23,40 @@ limitations under the License. namespace { const uint32_t max_allowed_timeouts = 5; -size_t docker_curl_write_callback(const char *ptr, size_t size, size_t nmemb, std::string *json) -{ +size_t docker_curl_write_callback(const char* ptr, size_t size, size_t nmemb, std::string* json) { const std::size_t total = size * nmemb; json->append(ptr, total); return total; } -} +} // namespace using namespace libsinsp::container_engine; -docker_connection::docker_connection(): - m_api_version("/v1.24"), - m_curlm(nullptr) -{ +docker_connection::docker_connection(): m_api_version("/v1.24"), m_curlm(nullptr) { m_curlm = curl_multi_init(); - if(m_curlm) - { - curl_multi_setopt(m_curlm, CURLMOPT_PIPELINING, CURLPIPE_HTTP1|CURLPIPE_MULTIPLEX); + if(m_curlm) { + curl_multi_setopt(m_curlm, CURLMOPT_PIPELINING, CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX); } } -docker_connection::~docker_connection() -{ - if(m_curlm) - { +docker_connection::~docker_connection() { + if(m_curlm) { curl_multi_cleanup(m_curlm); m_curlm = NULL; } } -docker_connection::docker_response docker_connection::get_docker(const docker_lookup_request& request, const std::string& req_url, std::string &json) -{ +docker_connection::docker_response docker_connection::get_docker( + const docker_lookup_request& request, + const std::string& req_url, + std::string& json) { CURL* curl = curl_easy_init(); - if(!curl) - { + if(!curl) { libsinsp_logger()->format(sinsp_logger::SEV_WARNING, - "docker_async (%s): Failed to initialize curl handle", - req_url.c_str()); + "docker_async (%s): Failed to initialize curl handle", + req_url.c_str()); return docker_response::RESP_ERROR; } @@ -76,49 +70,44 @@ docker_connection::docker_response docker_connection::get_docker(const docker_lo std::string url = "http://localhost" + m_api_version + req_url; libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Fetching url", - url.c_str()); + "docker_async (%s): Fetching url", + url.c_str()); - if(curl_easy_setopt(curl, CURLOPT_URL, url.c_str()) != CURLE_OK) - { + if(curl_easy_setopt(curl, CURLOPT_URL, url.c_str()) != CURLE_OK) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): curl_easy_setopt(CURLOPT_URL) failed", - url.c_str()); + "docker_async (%s): curl_easy_setopt(CURLOPT_URL) failed", + url.c_str()); curl_easy_cleanup(curl); ASSERT(false); return docker_response::RESP_ERROR; } - if(curl_easy_setopt(curl, CURLOPT_WRITEDATA, &json) != CURLE_OK) - { + if(curl_easy_setopt(curl, CURLOPT_WRITEDATA, &json) != CURLE_OK) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): curl_easy_setopt(CURLOPT_WRITEDATA) failed", - url.c_str()); + "docker_async (%s): curl_easy_setopt(CURLOPT_WRITEDATA) failed", + url.c_str()); curl_easy_cleanup(curl); ASSERT(false); return docker_response::RESP_ERROR; } - if(curl_multi_add_handle(m_curlm, curl) != CURLM_OK) - { + if(curl_multi_add_handle(m_curlm, curl) != CURLM_OK) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): curl_multi_add_handle() failed", - url.c_str()); + "docker_async (%s): curl_multi_add_handle() failed", + url.c_str()); curl_easy_cleanup(curl); ASSERT(false); return docker_response::RESP_ERROR; } uint32_t num_timeouts = 0; - while(true) - { + while(true) { int still_running; CURLMcode res = curl_multi_perform(m_curlm, &still_running); - if(res != CURLM_OK) - { + if(res != CURLM_OK) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): curl_multi_perform() failed", - url.c_str()); + "docker_async (%s): curl_multi_perform() failed", + url.c_str()); curl_multi_remove_handle(m_curlm, curl); curl_easy_cleanup(curl); @@ -126,46 +115,41 @@ docker_connection::docker_response docker_connection::get_docker(const docker_lo return docker_response::RESP_ERROR; } - if(still_running == 0) - { + if(still_running == 0) { break; } int numfds; res = curl_multi_wait(m_curlm, NULL, 0, 1000, &numfds); - if(res != CURLM_OK) - { + if(res != CURLM_OK) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): curl_multi_wait() failed", - url.c_str()); + "docker_async (%s): curl_multi_wait() failed", + url.c_str()); curl_multi_remove_handle(m_curlm, curl); curl_easy_cleanup(curl); ASSERT(false); return docker_response::RESP_ERROR; } - if(numfds == 0) - { + if(numfds == 0) { // Operation timed out - if(++num_timeouts >= max_allowed_timeouts) - { + if(++num_timeouts >= max_allowed_timeouts) { libsinsp_logger()->format(sinsp_logger::SEV_WARNING, - "docker_async (%s): Max timeouts exceeded", - url.c_str()); + "docker_async (%s): Max timeouts exceeded", + url.c_str()); return docker_response::RESP_TIMEOUT; } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): Operation timed out %d times", - url.c_str(), - num_timeouts); + "docker_async (%s): Operation timed out %d times", + url.c_str(), + num_timeouts); } } - if(curl_multi_remove_handle(m_curlm, curl) != CURLM_OK) - { + if(curl_multi_remove_handle(m_curlm, curl) != CURLM_OK) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): curl_multi_remove_handle() failed", - url.c_str()); + "docker_async (%s): curl_multi_remove_handle() failed", + url.c_str()); curl_easy_cleanup(curl); ASSERT(false); @@ -173,11 +157,11 @@ docker_connection::docker_response docker_connection::get_docker(const docker_lo } long http_code = 0; - if(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code) != CURLE_OK) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): curl_easy_getinfo(CURLINFO_RESPONSE_CODE) failed", - url.c_str()); + if(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code) != CURLE_OK) { + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "docker_async (%s): curl_easy_getinfo(CURLINFO_RESPONSE_CODE) failed", + url.c_str()); curl_easy_cleanup(curl); ASSERT(false); @@ -186,32 +170,31 @@ docker_connection::docker_response docker_connection::get_docker(const docker_lo curl_easy_cleanup(curl); libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): http_code=%ld", - url.c_str(), http_code); + "docker_async (%s): http_code=%ld", + url.c_str(), + http_code); - switch(http_code) - { + switch(http_code) { case 0: /* connection failed, apparently */ libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): returning RESP_ERROR", - url.c_str()); + "docker_async (%s): returning RESP_ERROR", + url.c_str()); return docker_response::RESP_ERROR; case 200: libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): returning RESP_OK", - url.c_str()); + "docker_async (%s): returning RESP_OK", + url.c_str()); return docker_response::RESP_OK; default: libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): returning RESP_BAD_REQUEST", - url.c_str()); + "docker_async (%s): returning RESP_BAD_REQUEST", + url.c_str()); return docker_response::RESP_BAD_REQUEST; } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): fallthrough, returning RESP_OK", - url.c_str()); + "docker_async (%s): fallthrough, returning RESP_OK", + url.c_str()); return docker_response::RESP_OK; } - diff --git a/userspace/libsinsp/container_engine/docker/docker_linux.cpp b/userspace/libsinsp/container_engine/docker/docker_linux.cpp index 3b9af38747..a6d75cb1c3 100644 --- a/userspace/libsinsp/container_engine/docker/docker_linux.cpp +++ b/userspace/libsinsp/container_engine/docker/docker_linux.cpp @@ -25,49 +25,45 @@ using namespace libsinsp::runc; namespace { -constexpr const cgroup_layout DOCKER_CGROUP_LAYOUT[] = { - {"/", ""}, // non-systemd docker - {"/docker-", ".scope"}, // systemd docker - {nullptr, nullptr} -}; +constexpr const cgroup_layout DOCKER_CGROUP_LAYOUT[] = {{"/", ""}, // non-systemd docker + {"/docker-", ".scope"}, // systemd docker + {nullptr, nullptr}}; } std::string docker_linux::m_docker_sock = "/var/run/docker.sock"; -bool docker_linux::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) -{ +bool docker_linux::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) { std::string container_id, cgroup; - if(!matches_runc_cgroups(tinfo, DOCKER_CGROUP_LAYOUT, container_id, cgroup)) - { + if(!matches_runc_cgroups(tinfo, DOCKER_CGROUP_LAYOUT, container_id, cgroup)) { return false; } - return resolve_impl(tinfo, docker_lookup_request( - container_id, - m_docker_sock, - CT_DOCKER, - 0, - false), query_os_for_missing_info); + return resolve_impl(tinfo, + docker_lookup_request(container_id, m_docker_sock, CT_DOCKER, 0, false), + query_os_for_missing_info); } -void docker_linux::update_with_size(const std::string &container_id) -{ +void docker_linux::update_with_size(const std::string& container_id) { auto cb = [this](const docker_lookup_request& instruction, const sinsp_container_info& res) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async (%s): with size callback result=%d", - instruction.container_id.c_str(), - res.get_lookup_status()); + "docker_async (%s): with size callback result=%d", + instruction.container_id.c_str(), + res.get_lookup_status()); sinsp_container_info::ptr_t updated = std::make_shared(res); container_cache().replace_container(updated); }; libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "docker_async size request (%s)", - container_id.c_str()); + "docker_async size request (%s)", + container_id.c_str()); sinsp_container_info result; - docker_lookup_request instruction(container_id, m_docker_sock, CT_DOCKER, 0, true /*request rw size*/); + docker_lookup_request instruction(container_id, + m_docker_sock, + CT_DOCKER, + 0, + true /*request rw size*/); (void)m_docker_info_source->lookup(instruction, result, cb); } diff --git a/userspace/libsinsp/container_engine/docker/docker_linux.h b/userspace/libsinsp/container_engine/docker/docker_linux.h index d6947e6976..a7c15d610e 100644 --- a/userspace/libsinsp/container_engine/docker/docker_linux.h +++ b/userspace/libsinsp/container_engine/docker/docker_linux.h @@ -8,15 +8,12 @@ namespace container_engine { class docker_linux : public docker_base { public: - docker_linux(container_cache_interface& cache) : docker_base(cache) {} + docker_linux(container_cache_interface& cache): docker_base(cache) {} - static void set_docker_sock(std::string docker_sock) - { - m_docker_sock = std::move(docker_sock); - } + static void set_docker_sock(std::string docker_sock) { m_docker_sock = std::move(docker_sock); } // implement container_engine_base - bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; + bool resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) override; void update_with_size(const std::string& container_id) override; @@ -24,5 +21,5 @@ class docker_linux : public docker_base { static std::string m_docker_sock; }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/docker/lookup_request.h b/userspace/libsinsp/container_engine/docker/lookup_request.h index a9cd0d4bcf..0b283d2324 100644 --- a/userspace/libsinsp/container_engine/docker/lookup_request.h +++ b/userspace/libsinsp/container_engine/docker/lookup_request.h @@ -5,57 +5,43 @@ namespace libsinsp { namespace container_engine { -struct docker_lookup_request -{ - docker_lookup_request() : - container_type(CT_DOCKER), - uid(0), - request_rw_size(false) - {} +struct docker_lookup_request { + docker_lookup_request(): container_type(CT_DOCKER), uid(0), request_rw_size(false) {} docker_lookup_request(const std::string& container_id_value, - const std::string& docker_socket_value, - sinsp_container_type container_type_value, - unsigned long uid_value, - bool rw_size_value) : - container_id(container_id_value), - docker_socket(docker_socket_value), - container_type(container_type_value), - uid(uid_value), - request_rw_size(rw_size_value) - {} - - bool operator<(const docker_lookup_request& rhs) const - { - if(container_id != rhs.container_id) - { + const std::string& docker_socket_value, + sinsp_container_type container_type_value, + unsigned long uid_value, + bool rw_size_value): + container_id(container_id_value), + docker_socket(docker_socket_value), + container_type(container_type_value), + uid(uid_value), + request_rw_size(rw_size_value) {} + + bool operator<(const docker_lookup_request& rhs) const { + if(container_id != rhs.container_id) { return container_id < rhs.container_id; } - if(docker_socket != rhs.docker_socket) - { + if(docker_socket != rhs.docker_socket) { return docker_socket < rhs.docker_socket; } - if(container_type != rhs.container_type) - { + if(container_type != rhs.container_type) { return container_type < rhs.container_type; } - if(uid != rhs.uid) - { + if(uid != rhs.uid) { return uid < rhs.uid; } return request_rw_size < rhs.request_rw_size; } - bool operator==(const docker_lookup_request& rhs) const - { - return container_id == rhs.container_id && - docker_socket == rhs.docker_socket && - container_type == rhs.container_type && - uid == rhs.uid && + bool operator==(const docker_lookup_request& rhs) const { + return container_id == rhs.container_id && docker_socket == rhs.docker_socket && + container_type == rhs.container_type && uid == rhs.uid && request_rw_size == rhs.request_rw_size; } @@ -66,6 +52,5 @@ struct docker_lookup_request bool request_rw_size; }; - -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/docker/podman.cpp b/userspace/libsinsp/container_engine/docker/podman.cpp index 3ed3daed55..f9ea1d07ab 100644 --- a/userspace/libsinsp/container_engine/docker/podman.cpp +++ b/userspace/libsinsp/container_engine/docker/podman.cpp @@ -36,14 +36,12 @@ std::string podman::m_user_api_sock_pattern = "/run/user/*/podman/podman.sock"; namespace { constexpr const cgroup_layout ROOT_PODMAN_CGROUP_LAYOUT[] = { - {"/libpod-", ".scope"}, // podman - {"/libpod-", ".scope/container"}, // podman - {"/libpod-", ""}, // non-systemd podman, e.g. on alpine - {nullptr, nullptr} -}; - -int get_userns_root_uid(int64_t tid) -{ + {"/libpod-", ".scope"}, // podman + {"/libpod-", ".scope/container"}, // podman + {"/libpod-", ""}, // non-systemd podman, e.g. on alpine + {nullptr, nullptr}}; + +int get_userns_root_uid(int64_t tid) { std::stringstream uid_map_file; uid_map_file << scap_get_host_root() << "/proc/" << tid << "/uid_map"; @@ -57,41 +55,34 @@ int get_userns_root_uid(int64_t tid) // 0 for root containers, // >0 for rootless containers, // NO_MATCH if the process is not in a podman container -int get_podman_cgroup_uid(const std::string &cgroup, std::string &container_id, int64_t tid) -{ - if(cgroup.empty()) - { +int get_podman_cgroup_uid(const std::string &cgroup, std::string &container_id, int64_t tid) { + if(cgroup.empty()) { // can't get the cgroup name return libsinsp::procfs_utils::NO_MATCH; } size_t pos = cgroup.find("podman-"); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { // .../podman-.scope/ - int podman_pid; // unused except to set the sscanf return value - char c; // ^ same - if(sscanf(cgroup.c_str() + pos, "podman-%d.scope/%c", &podman_pid, &c) != 2) - { + int podman_pid; // unused except to set the sscanf return value + char c; // ^ same + if(sscanf(cgroup.c_str() + pos, "podman-%d.scope/%c", &podman_pid, &c) != 2) { // cgroup doesn't match the expected pattern return libsinsp::procfs_utils::NO_MATCH; } - if(!match_one_container_id(cgroup, ".scope/", "", container_id)) - { + if(!match_one_container_id(cgroup, ".scope/", "", container_id)) { return libsinsp::procfs_utils::NO_MATCH; } int uid = get_userns_root_uid(tid); - if(uid == 0) - { + if(uid == 0) { // root doesn't spawn rootless containers return libsinsp::procfs_utils::NO_MATCH; } return uid; - } else - { + } else { // when rootless podman containers are run as a service, // there's nothing identifying podman in the cgroup as it looks like: // /user.slice/user-.slice/user@.service// @@ -102,19 +93,16 @@ int get_podman_cgroup_uid(const std::string &cgroup, std::string &container_id, // we can probably narrow the prefix down to ".service/" in the typical // case but as we're already basically guessing, let's keep it generic - if(!match_one_container_id(cgroup, "/", "", container_id)) - { + if(!match_one_container_id(cgroup, "/", "", container_id)) { return libsinsp::procfs_utils::NO_MATCH; } int uid; - if(sscanf(cgroup.c_str(), "/user.slice/user-%d.slice/", &uid) == 1) - { + if(sscanf(cgroup.c_str(), "/user.slice/user-%d.slice/", &uid) == 1) { return uid; } return libsinsp::procfs_utils::NO_MATCH; } - } // Check whether `tinfo` belongs to a podman container @@ -123,26 +111,22 @@ int get_podman_cgroup_uid(const std::string &cgroup, std::string &container_id, // 0 for root containers, // >0 for rootless containers, // NO_MATCH if the process is not in a podman container -int detect_podman(const sinsp_threadinfo *tinfo, std::string &container_id) -{ +int detect_podman(const sinsp_threadinfo *tinfo, std::string &container_id) { std::string cgroup; - if(matches_runc_cgroups(tinfo, ROOT_PODMAN_CGROUP_LAYOUT, container_id, cgroup)) - { + if(matches_runc_cgroups(tinfo, ROOT_PODMAN_CGROUP_LAYOUT, container_id, cgroup)) { // User: /user.slice/user-1000.slice/user@1000.service/user.slice/libpod-$ID.scope/container // Root: /machine.slice/libpod-$ID.scope/container int uid; - if (sscanf(cgroup.c_str(), "/user.slice/user-%d.slice/", &uid) == 1) - { + if(sscanf(cgroup.c_str(), "/user.slice/user-%d.slice/", &uid) == 1) { return uid; } - return 0; // root + return 0; // root } // the kernel driver does not return cgroups without subsystems (e.g. name=systemd) // in the cgroups field, so we have to do a check here, and load /proc/pid/cgroups // ourselves if needed - if(tinfo->get_cgroup("name=systemd", cgroup)) - { + if(tinfo->get_cgroup("name=systemd", cgroup)) { return get_podman_cgroup_uid(cgroup, container_id, tinfo->m_tid); } @@ -150,21 +134,18 @@ int detect_podman(const sinsp_threadinfo *tinfo, std::string &container_id) proc_cgroups_tinfo.m_tid = tinfo->m_tid; sinsp_cgroup::instance().lookup_cgroups(proc_cgroups_tinfo); - for(const auto& proc_cgroup: proc_cgroups_tinfo.cgroups()) - { + for(const auto &proc_cgroup : proc_cgroups_tinfo.cgroups()) { int ret = get_podman_cgroup_uid(proc_cgroup.second, container_id, tinfo->m_tid); - if(ret != libsinsp::procfs_utils::NO_MATCH) - { + if(ret != libsinsp::procfs_utils::NO_MATCH) { return ret; } } return libsinsp::procfs_utils::NO_MATCH; } -} +} // namespace -bool podman::can_api_sock_exist() -{ +bool podman::can_api_sock_exist() { glob_t gl; int rc; int glob_flags = 0; @@ -175,8 +156,7 @@ bool podman::can_api_sock_exist() std::string api_sock = scap_get_host_root() + m_api_sock; std::string user_api_sock_pattern = scap_get_host_root() + m_user_api_sock_pattern; - if (access(api_sock.c_str(), R_OK|W_OK) == 0) - { + if(access(api_sock.c_str(), R_OK | W_OK) == 0) { return true; } @@ -187,38 +167,31 @@ bool podman::can_api_sock_exist() return (rc == 0); } -bool podman::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) -{ +bool podman::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) { std::string container_id, api_sock; - if(!m_api_sock_can_exist.has_value()) - { - if (query_os_for_missing_info) - { + if(!m_api_sock_can_exist.has_value()) { + if(query_os_for_missing_info) { m_api_sock_can_exist = can_api_sock_exist(); - } - else - { + } else { // Short-circuit: always enable podman when running from a capture file. m_api_sock_can_exist = true; } } - if(!m_api_sock_can_exist.value()) - { + if(!m_api_sock_can_exist.value()) { return false; } int uid = detect_podman(tinfo, container_id); - switch(uid) - { - case 0: // root, use the default socket + switch(uid) { + case 0: // root, use the default socket api_sock = m_api_sock; break; case libsinsp::procfs_utils::NO_MATCH: return false; - default: // rootless container, use the user's socket + default: // rootless container, use the user's socket api_sock = "/run/user/" + std::to_string(uid) + "/podman/podman.sock"; break; } diff --git a/userspace/libsinsp/container_engine/docker/podman.h b/userspace/libsinsp/container_engine/docker/podman.h index 28d43734f5..c7ca282070 100644 --- a/userspace/libsinsp/container_engine/docker/podman.h +++ b/userspace/libsinsp/container_engine/docker/podman.h @@ -7,8 +7,7 @@ namespace libsinsp { namespace container_engine { -class podman : public docker_base -{ +class podman : public docker_base { public: podman(container_cache_interface& cache): docker_base(cache) {} @@ -25,8 +24,8 @@ class podman : public docker_base // Return whether or not any possible api socket exists. (The actual socket is // implement container_engine_base - bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; + bool resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) override; }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/libvirt_lxc.cpp b/userspace/libsinsp/container_engine/libvirt_lxc.cpp index c62db286a7..161c87f377 100644 --- a/userspace/libsinsp/container_engine/libvirt_lxc.cpp +++ b/userspace/libsinsp/container_engine/libvirt_lxc.cpp @@ -21,21 +21,16 @@ limitations under the License. using namespace libsinsp::container_engine; -bool libvirt_lxc::match(sinsp_threadinfo* tinfo, sinsp_container_info &container_info) -{ - for(const auto& it : tinfo->cgroups()) - { +bool libvirt_lxc::match(sinsp_threadinfo* tinfo, sinsp_container_info& container_info) { + for(const auto& it : tinfo->cgroups()) { // // Non-systemd libvirt-lxc // const auto& cgroup = it.second; size_t pos = cgroup.find(".libvirt-lxc"); - if(pos != std::string::npos && - pos == cgroup.length() - sizeof(".libvirt-lxc") + 1) - { + if(pos != std::string::npos && pos == cgroup.length() - sizeof(".libvirt-lxc") + 1) { size_t pos2 = cgroup.find_last_of("/"); - if(pos2 != std::string::npos) - { + if(pos2 != std::string::npos) { container_info.m_type = CT_LIBVIRT_LXC; container_info.m_id = cgroup.substr(pos2 + 1, pos - pos2 - 1); return true; @@ -46,14 +41,12 @@ bool libvirt_lxc::match(sinsp_threadinfo* tinfo, sinsp_container_info &container // systemd libvirt-lxc // pos = cgroup.find("-lxc\\x2"); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { size_t pos2 = cgroup.find(".scope"); - if(pos2 != std::string::npos && - pos2 == cgroup.length() - sizeof(".scope") + 1) - { + if(pos2 != std::string::npos && pos2 == cgroup.length() - sizeof(".scope") + 1) { container_info.m_type = CT_LIBVIRT_LXC; - container_info.m_id = cgroup.substr(pos + sizeof("-lxc\\x2"), pos2 - pos - sizeof("-lxc\\x2")); + container_info.m_id = + cgroup.substr(pos + sizeof("-lxc\\x2"), pos2 - pos - sizeof("-lxc\\x2")); return true; } } @@ -62,8 +55,7 @@ bool libvirt_lxc::match(sinsp_threadinfo* tinfo, sinsp_container_info &container // Legacy libvirt-lxc // pos = cgroup.find("/libvirt/lxc/"); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { container_info.m_type = CT_LIBVIRT_LXC; container_info.m_id = cgroup.substr(pos + sizeof("/libvirt/lxc/") - 1); return true; @@ -72,18 +64,15 @@ bool libvirt_lxc::match(sinsp_threadinfo* tinfo, sinsp_container_info &container return false; } -bool libvirt_lxc::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) -{ +bool libvirt_lxc::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) { auto container = sinsp_container_info(); - if (!match(tinfo, container)) - { + if(!match(tinfo, container)) { return false; } tinfo->m_container_id = container.m_id; - if(container_cache().should_lookup(container.m_id, CT_LIBVIRT_LXC)) - { + if(container_cache().should_lookup(container.m_id, CT_LIBVIRT_LXC)) { container.m_name = container.m_id; container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); container_cache().add_container(std::make_shared(container), tinfo); diff --git a/userspace/libsinsp/container_engine/libvirt_lxc.h b/userspace/libsinsp/container_engine/libvirt_lxc.h index 7c0663f200..a40e71b258 100644 --- a/userspace/libsinsp/container_engine/libvirt_lxc.h +++ b/userspace/libsinsp/container_engine/libvirt_lxc.h @@ -26,15 +26,14 @@ class sinsp_threadinfo; namespace libsinsp { namespace container_engine { -class libvirt_lxc : public container_engine_base -{ +class libvirt_lxc : public container_engine_base { public: - libvirt_lxc(container_cache_interface &cache) : container_engine_base(cache) - {} + libvirt_lxc(container_cache_interface &cache): container_engine_base(cache) {} bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; + protected: - bool match(sinsp_threadinfo* tinfo, sinsp_container_info &container_info); + bool match(sinsp_threadinfo *tinfo, sinsp_container_info &container_info); }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/lxc.cpp b/userspace/libsinsp/container_engine/lxc.cpp index ce161ad962..1b4fa2d079 100644 --- a/userspace/libsinsp/container_engine/lxc.cpp +++ b/userspace/libsinsp/container_engine/lxc.cpp @@ -22,24 +22,21 @@ limitations under the License. using namespace libsinsp::container_engine; constexpr const std::string_view LXC_CGROUP_LAYOUT[] = { - "/lxc/", // non-systemd - "/lxc.payload/", // systemd - "/lxc.payload.", // lxc4.0 layout: https://linuxcontainers.org/lxc/news/2020_03_25_13_03.html + "/lxc/", // non-systemd + "/lxc.payload/", // systemd + "/lxc.payload.", // lxc4.0 layout: + // https://linuxcontainers.org/lxc/news/2020_03_25_13_03.html }; -bool lxc::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) -{ +bool lxc::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) { auto container = sinsp_container_info(); bool matches = false; - for(const auto& it : tinfo->cgroups()) - { + for(const auto &it : tinfo->cgroups()) { const auto &cgroup = it.second; - for(const auto &cgroup_layout : LXC_CGROUP_LAYOUT) - { + for(const auto &cgroup_layout : LXC_CGROUP_LAYOUT) { size_t pos = cgroup.find(cgroup_layout); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { auto id_start = pos + cgroup_layout.length(); auto id_end = cgroup.find('/', id_start); container.m_type = CT_LXC; @@ -48,20 +45,17 @@ bool lxc::resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) break; } } - if (matches) - { + if(matches) { break; } } - if (!matches) - { + if(!matches) { return false; } tinfo->m_container_id = container.m_id; - if (container_cache().should_lookup(container.m_id, CT_LXC)) - { + if(container_cache().should_lookup(container.m_id, CT_LXC)) { container.m_name = container.m_id; container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); container_cache().add_container(std::make_shared(container), tinfo); diff --git a/userspace/libsinsp/container_engine/lxc.h b/userspace/libsinsp/container_engine/lxc.h index e4f4fb47b2..ca336f5d32 100644 --- a/userspace/libsinsp/container_engine/lxc.h +++ b/userspace/libsinsp/container_engine/lxc.h @@ -26,13 +26,11 @@ class sinsp_threadinfo; namespace libsinsp { namespace container_engine { -class lxc : public container_engine_base -{ +class lxc : public container_engine_base { public: - lxc(container_cache_interface &cache) : container_engine_base(cache) - {} + lxc(container_cache_interface &cache): container_engine_base(cache) {} bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/mesos.cpp b/userspace/libsinsp/container_engine/mesos.cpp index 22d123fcee..c4943d5cd3 100644 --- a/userspace/libsinsp/container_engine/mesos.cpp +++ b/userspace/libsinsp/container_engine/mesos.cpp @@ -23,20 +23,18 @@ limitations under the License. #include #include -bool libsinsp::container_engine::mesos::match(sinsp_threadinfo* tinfo, sinsp_container_info &container_info) -{ - for(const auto& it : tinfo->cgroups()) - { +bool libsinsp::container_engine::mesos::match(sinsp_threadinfo* tinfo, + sinsp_container_info& container_info) { + for(const auto& it : tinfo->cgroups()) { std::string cgroup = it.second; size_t pos; pos = cgroup.find("/mesos/"); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { // It should match `/mesos/a9f41620-b165-4d24-abe0-af0af92e7b20` auto id = cgroup.substr(pos + sizeof("/mesos/") - 1); - if(id.size() == 36 && id.find_first_not_of("0123456789abcdefABCDEF-") == std::string::npos) - { + if(id.size() == 36 && + id.find_first_not_of("0123456789abcdefABCDEF-") == std::string::npos) { container_info.m_type = CT_MESOS; container_info.m_id = std::move(id); // Consider a mesos container valid only if we find the mesos_task_id @@ -51,16 +49,15 @@ bool libsinsp::container_engine::mesos::match(sinsp_threadinfo* tinfo, sinsp_con return false; } -bool libsinsp::container_engine::mesos::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) -{ +bool libsinsp::container_engine::mesos::resolve(sinsp_threadinfo* tinfo, + bool query_os_for_missing_info) { auto container = sinsp_container_info(); - if (!match(tinfo, container)) + if(!match(tinfo, container)) return false; tinfo->m_container_id = container.m_id; - if(container_cache().should_lookup(container.m_id, CT_MESOS)) - { + if(container_cache().should_lookup(container.m_id, CT_MESOS)) { container.m_name = container.m_id; container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); container_cache().add_container(std::make_shared(container), tinfo); @@ -69,20 +66,24 @@ bool libsinsp::container_engine::mesos::resolve(sinsp_threadinfo* tinfo, bool qu return true; } -std::string libsinsp::container_engine::mesos::get_env_mesos_task_id(sinsp_threadinfo* tinfo) -{ +std::string libsinsp::container_engine::mesos::get_env_mesos_task_id(sinsp_threadinfo* tinfo) { std::string mtid; - sinsp_threadinfo::visitor_func_t visitor = [&mtid] (sinsp_threadinfo *ptinfo) - { + sinsp_threadinfo::visitor_func_t visitor = [&mtid](sinsp_threadinfo* ptinfo) { // Mesos task ID detection is not a straightforward task; // this list may have to be extended. - mtid = ptinfo->get_env("MESOS_TASK_ID"); // Marathon - if(!mtid.empty()) { return false; } - mtid = ptinfo->get_env("mesos_task_id"); // Chronos - if(!mtid.empty()) { return false; } - mtid = ptinfo->get_env("MESOS_EXECUTOR_ID"); // others - if(!mtid.empty()) { return false; } + mtid = ptinfo->get_env("MESOS_TASK_ID"); // Marathon + if(!mtid.empty()) { + return false; + } + mtid = ptinfo->get_env("mesos_task_id"); // Chronos + if(!mtid.empty()) { + return false; + } + mtid = ptinfo->get_env("MESOS_EXECUTOR_ID"); // others + if(!mtid.empty()) { + return false; + } return true; }; @@ -90,16 +91,15 @@ std::string libsinsp::container_engine::mesos::get_env_mesos_task_id(sinsp_threa // Try the current thread first. visitor returns true if mtid // was not filled in. In this case we should traverse the // parents. - if(tinfo && visitor(tinfo)) - { + if(tinfo && visitor(tinfo)) { tinfo->traverse_parent_state(visitor); } return mtid; } -bool libsinsp::container_engine::mesos::set_mesos_task_id(sinsp_container_info &container, sinsp_threadinfo* tinfo) -{ +bool libsinsp::container_engine::mesos::set_mesos_task_id(sinsp_container_info& container, + sinsp_threadinfo* tinfo) { ASSERT(tinfo); // there are applications that do not share their environment in /proc/[PID]/environ @@ -111,30 +111,30 @@ bool libsinsp::container_engine::mesos::set_mesos_task_id(sinsp_container_info & // get_env_mesos_task_id(sinsp_threadinfo*) implementation) environment variable, so we // peek into the parent process environment to discover it - if(tinfo) - { + if(tinfo) { std::string& mtid = container.m_mesos_task_id; - if(mtid.empty()) - { + if(mtid.empty()) { mtid = get_env_mesos_task_id(tinfo); // Ensure that the mesos task id vaguely looks // like a real id. We assume it must be at // least 3 characters and contain a dot or underscore - if(!mtid.empty() && mtid.length()>=3 && - (mtid.find_first_of("._") != std::string::npos)) - { - libsinsp_logger()->log("Mesos native container: [" + container.m_id + "], Mesos task ID: " + mtid, sinsp_logger::SEV_DEBUG); + if(!mtid.empty() && mtid.length() >= 3 && + (mtid.find_first_of("._") != std::string::npos)) { + libsinsp_logger()->log( + "Mesos native container: [" + container.m_id + "], Mesos task ID: " + mtid, + sinsp_logger::SEV_DEBUG); return true; - } - else - { - libsinsp_logger()->log("Mesos container [" + container.m_id + "]," - "thread [" + std::to_string(tinfo->m_tid) + - "], has likely malformed mesos task id [" + mtid + "], ignoring", sinsp_logger::SEV_DEBUG); + } else { + libsinsp_logger()->log("Mesos container [" + container.m_id + + "]," + "thread [" + + std::to_string(tinfo->m_tid) + + "], has likely malformed mesos task id [" + mtid + + "], ignoring", + sinsp_logger::SEV_DEBUG); } } } return false; } - diff --git a/userspace/libsinsp/container_engine/mesos.h b/userspace/libsinsp/container_engine/mesos.h index bc7ed44618..7753b71fa3 100644 --- a/userspace/libsinsp/container_engine/mesos.h +++ b/userspace/libsinsp/container_engine/mesos.h @@ -28,20 +28,18 @@ class sinsp_threadinfo; namespace libsinsp { namespace container_engine { -class mesos : public container_engine_base -{ +class mesos : public container_engine_base { public: - mesos(container_cache_interface& cache) : container_engine_base(cache) - {} + mesos(container_cache_interface &cache): container_engine_base(cache) {} bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; - static bool set_mesos_task_id(sinsp_container_info& container, sinsp_threadinfo *tinfo); + static bool set_mesos_task_id(sinsp_container_info &container, sinsp_threadinfo *tinfo); protected: - bool match(sinsp_threadinfo *tinfo, sinsp_container_info& container_info); + bool match(sinsp_threadinfo *tinfo, sinsp_container_info &container_info); static std::string get_env_mesos_task_id(sinsp_threadinfo *tinfo); }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/rkt.cpp b/userspace/libsinsp/container_engine/rkt.cpp index 29556020fa..796e379286 100644 --- a/userspace/libsinsp/container_engine/rkt.cpp +++ b/userspace/libsinsp/container_engine/rkt.cpp @@ -25,33 +25,30 @@ limitations under the License. using namespace libsinsp::container_engine; -bool rkt::match(container_cache_interface *cache, sinsp_threadinfo *tinfo, sinsp_container_info& container_info, std::string& rkt_podid, std::string& rkt_appname, bool query_os_for_missing_info) -{ - for(const auto& it : tinfo->cgroups()) - { +bool rkt::match(container_cache_interface* cache, + sinsp_threadinfo* tinfo, + sinsp_container_info& container_info, + std::string& rkt_podid, + std::string& rkt_appname, + bool query_os_for_missing_info) { + for(const auto& it : tinfo->cgroups()) { std::string cgroup = it.second; static const std::string COREOS_PODID_VAR = "container_uuid="; static const std::string SYSTEMD_UUID_ARG = "--uuid="; static const std::string SERVICE_SUFFIX = ".service"; - if(cgroup.rfind(SERVICE_SUFFIX) == cgroup.size() - SERVICE_SUFFIX.size()) - { + if(cgroup.rfind(SERVICE_SUFFIX) == cgroup.size() - SERVICE_SUFFIX.size()) { // check if there is a parent with pod uuid var - sinsp_threadinfo::visitor_func_t visitor = [&](sinsp_threadinfo* ptinfo) - { - for(const auto& env_var : ptinfo->get_env()) - { + sinsp_threadinfo::visitor_func_t visitor = [&](sinsp_threadinfo* ptinfo) { + for(const auto& env_var : ptinfo->get_env()) { auto container_uuid_pos = env_var.find(COREOS_PODID_VAR); - if(container_uuid_pos == 0) - { + if(container_uuid_pos == 0) { rkt_podid = env_var.substr(COREOS_PODID_VAR.size()); return false; } } - for(const auto& arg : ptinfo->m_args) - { - if(arg.find(SYSTEMD_UUID_ARG) != std::string::npos) - { + for(const auto& arg : ptinfo->m_args) { + if(arg.find(SYSTEMD_UUID_ARG) != std::string::npos) { rkt_podid = arg.substr(SYSTEMD_UUID_ARG.size()); return false; } @@ -60,24 +57,28 @@ bool rkt::match(container_cache_interface *cache, sinsp_threadinfo *tinfo, sinsp }; tinfo->traverse_parent_state(visitor); - if(!rkt_podid.empty()) - { + if(!rkt_podid.empty()) { auto last_slash = cgroup.find_last_of("/"); - rkt_appname = cgroup.substr(last_slash + 1, cgroup.size() - last_slash - SERVICE_SUFFIX.size() - 1); + rkt_appname = cgroup.substr(last_slash + 1, + cgroup.size() - last_slash - SERVICE_SUFFIX.size() - 1); char image_manifest_path[SCAP_MAX_PATH_SIZE]; - snprintf(image_manifest_path, sizeof(image_manifest_path), "%s/var/lib/rkt/pods/run/%s/appsinfo/%s/manifest", scap_get_host_root(), rkt_podid.c_str(), rkt_appname.c_str()); + snprintf(image_manifest_path, + sizeof(image_manifest_path), + "%s/var/lib/rkt/pods/run/%s/appsinfo/%s/manifest", + scap_get_host_root(), + rkt_podid.c_str(), + rkt_appname.c_str()); - // First lookup if the container exists in our table, otherwise only if we are live check if it has - // an entry in /var/lib/rkt. In capture mode only the former will be used. - // In live mode former will be used only if we already hit that container - bool is_rkt_pod_id_valid = cache->container_exists(rkt_podid + ":" + rkt_appname); // if it's already on our table - if(!is_rkt_pod_id_valid && query_os_for_missing_info) - { + // First lookup if the container exists in our table, otherwise only if we are live + // check if it has an entry in /var/lib/rkt. In capture mode only the former will be + // used. In live mode former will be used only if we already hit that container + bool is_rkt_pod_id_valid = cache->container_exists( + rkt_podid + ":" + rkt_appname); // if it's already on our table + if(!is_rkt_pod_id_valid && query_os_for_missing_info) { is_rkt_pod_id_valid = (access(image_manifest_path, F_OK) == 0); } - if(is_rkt_pod_id_valid) - { + if(is_rkt_pod_id_valid) { container_info.m_type = CT_RKT; container_info.m_id = rkt_podid + ":" + rkt_appname; container_info.m_name = rkt_appname; @@ -96,22 +97,18 @@ bool rkt::match(container_cache_interface *cache, sinsp_threadinfo *tinfo, sinsp static const std::string COREOS_PODID_VAR = "container_uuid="; auto prefix = tinfo->m_root.find(COREOS_PREFIX); - if(prefix == 0) - { + if(prefix == 0) { auto suffix = tinfo->m_root.find(COREOS_APP_SUFFIX, prefix); - if(suffix != std::string::npos) - { + if(suffix != std::string::npos) { bool valid_id = false; - rkt_appname = tinfo->m_root.substr(prefix + COREOS_PREFIX.size(), suffix - prefix - COREOS_PREFIX.size()); + rkt_appname = tinfo->m_root.substr(prefix + COREOS_PREFIX.size(), + suffix - prefix - COREOS_PREFIX.size()); // It is a rkt pod with stage1-coreos - sinsp_threadinfo::visitor_func_t visitor = [&] (sinsp_threadinfo *ptinfo) - { - for(const auto& env_var : ptinfo->get_env()) - { + sinsp_threadinfo::visitor_func_t visitor = [&](sinsp_threadinfo* ptinfo) { + for(const auto& env_var : ptinfo->get_env()) { auto container_uuid_pos = env_var.find(COREOS_PODID_VAR); - if(container_uuid_pos == 0) - { + if(container_uuid_pos == 0) { rkt_podid = env_var.substr(COREOS_PODID_VAR.size()); container_info.m_type = CT_RKT; container_info.m_id = rkt_podid + ":" + rkt_appname; @@ -125,32 +122,29 @@ bool rkt::match(container_cache_interface *cache, sinsp_threadinfo *tinfo, sinsp // Try the current thread first. visitor returns true if no coreos pid // info was found. In this case we traverse the parents. - if (visitor(tinfo)) - { + if(visitor(tinfo)) { tinfo->traverse_parent_state(visitor); } return valid_id; } - } - else - { + } else { // String used to detect stage1-fly pods static const std::string FLY_PREFIX = "/var/lib/rkt/pods/run/"; static const std::string FLY_PODID_SUFFIX = "/stage1/rootfs/opt/stage2/"; static const std::string FLY_APP_SUFFIX = "/rootfs"; auto prefix = tinfo->m_root.find(FLY_PREFIX); - if(prefix == 0) - { - auto podid_suffix = tinfo->m_root.find(FLY_PODID_SUFFIX, prefix+FLY_PREFIX.size()); - if(podid_suffix != std::string::npos) - { - rkt_podid = tinfo->m_root.substr(prefix + FLY_PREFIX.size(), podid_suffix - prefix - FLY_PREFIX.size()); - auto appname_suffix = tinfo->m_root.find(FLY_APP_SUFFIX, podid_suffix+FLY_PODID_SUFFIX.size()); - if(appname_suffix != std::string::npos) - { - rkt_appname = tinfo->m_root.substr(podid_suffix + FLY_PODID_SUFFIX.size(), - appname_suffix-podid_suffix-FLY_PODID_SUFFIX.size()); + if(prefix == 0) { + auto podid_suffix = tinfo->m_root.find(FLY_PODID_SUFFIX, prefix + FLY_PREFIX.size()); + if(podid_suffix != std::string::npos) { + rkt_podid = tinfo->m_root.substr(prefix + FLY_PREFIX.size(), + podid_suffix - prefix - FLY_PREFIX.size()); + auto appname_suffix = + tinfo->m_root.find(FLY_APP_SUFFIX, podid_suffix + FLY_PODID_SUFFIX.size()); + if(appname_suffix != std::string::npos) { + rkt_appname = tinfo->m_root.substr( + podid_suffix + FLY_PODID_SUFFIX.size(), + appname_suffix - podid_suffix - FLY_PODID_SUFFIX.size()); container_info.m_type = CT_RKT; container_info.m_id = rkt_podid + ":" + rkt_appname; container_info.m_name = rkt_appname; @@ -162,21 +156,18 @@ bool rkt::match(container_cache_interface *cache, sinsp_threadinfo *tinfo, sinsp return false; } -bool rkt::rkt::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) -{ - container_cache_interface *cache = &container_cache(); +bool rkt::rkt::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) { + container_cache_interface* cache = &container_cache(); auto container = sinsp_container_info(); std::string rkt_podid, rkt_appname; - if (!match(cache, tinfo, container, rkt_podid, rkt_appname, query_os_for_missing_info)) - { + if(!match(cache, tinfo, container, rkt_podid, rkt_appname, query_os_for_missing_info)) { return false; } tinfo->m_container_id = container.m_id; - if (!query_os_for_missing_info || !cache->should_lookup(container.m_id, CT_RKT)) - { + if(!query_os_for_missing_info || !cache->should_lookup(container.m_id, CT_RKT)) { return true; } @@ -186,82 +177,82 @@ bool rkt::rkt::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) bool have_rkt = true; #endif - if (have_rkt) - { + if(have_rkt) { container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); cache->add_container(std::make_shared(container), tinfo); cache->notify_new_container(container, tinfo); return true; - } - else - { + } else { return false; } } -bool rkt::rkt::parse_rkt(sinsp_container_info &container, const std::string &podid, const std::string &appname) -{ +bool rkt::rkt::parse_rkt(sinsp_container_info& container, + const std::string& podid, + const std::string& appname) { bool ret = false; Json::Reader reader; Json::Value jroot; char image_manifest_path[SCAP_MAX_PATH_SIZE]; - snprintf(image_manifest_path, sizeof(image_manifest_path), "%s/var/lib/rkt/pods/run/%s/appsinfo/%s/manifest", scap_get_host_root(), podid.c_str(), appname.c_str()); + snprintf(image_manifest_path, + sizeof(image_manifest_path), + "%s/var/lib/rkt/pods/run/%s/appsinfo/%s/manifest", + scap_get_host_root(), + podid.c_str(), + appname.c_str()); std::ifstream image_manifest(image_manifest_path); - if(reader.parse(image_manifest, jroot)) - { + if(reader.parse(image_manifest, jroot)) { container.m_image = jroot["name"].asString(); - for(const auto& label_entry : jroot["labels"]) - { + for(const auto& label_entry : jroot["labels"]) { std::string val = label_entry["value"].asString(); - if(val.length() <= sinsp_container_info::m_container_label_max_length ) { + if(val.length() <= sinsp_container_info::m_container_label_max_length) { container.m_labels.emplace(label_entry["name"].asString(), val); } } auto version_label_it = container.m_labels.find("version"); - if(version_label_it != container.m_labels.end()) - { + if(version_label_it != container.m_labels.end()) { container.m_image += ":" + version_label_it->second; } ret = true; } char net_info_path[SCAP_MAX_PATH_SIZE]; - snprintf(net_info_path, sizeof(net_info_path), "%s/var/lib/rkt/pods/run/%s/net-info.json", scap_get_host_root(), podid.c_str()); + snprintf(net_info_path, + sizeof(net_info_path), + "%s/var/lib/rkt/pods/run/%s/net-info.json", + scap_get_host_root(), + podid.c_str()); std::ifstream net_info(net_info_path); - if(reader.parse(net_info, jroot) && jroot.size() > 0) - { + if(reader.parse(net_info, jroot) && jroot.size() > 0) { const auto& first_net = jroot[0]; - if(inet_pton(AF_INET, first_net["ip"].asCString(), &container.m_container_ip) == -1) - { + if(inet_pton(AF_INET, first_net["ip"].asCString(), &container.m_container_ip) == -1) { ASSERT(false); } container.m_container_ip = ntohl(container.m_container_ip); } char pod_manifest_path[SCAP_MAX_PATH_SIZE]; - snprintf(pod_manifest_path, sizeof(pod_manifest_path), "%s/var/lib/rkt/pods/run/%s/pod", scap_get_host_root(), podid.c_str()); + snprintf(pod_manifest_path, + sizeof(pod_manifest_path), + "%s/var/lib/rkt/pods/run/%s/pod", + scap_get_host_root(), + podid.c_str()); std::ifstream pod_manifest(pod_manifest_path); std::unordered_map image_ports; - if(reader.parse(pod_manifest, jroot) && jroot.size() > 0) - { - for(const auto& japp : jroot["apps"]) - { - if (japp["name"].asString() == appname) - { - for(const auto& image_port : japp["app"]["ports"]) - { + if(reader.parse(pod_manifest, jroot) && jroot.size() > 0) { + for(const auto& japp : jroot["apps"]) { + if(japp["name"].asString() == appname) { + for(const auto& image_port : japp["app"]["ports"]) { image_ports[image_port["name"].asString()] = image_port["port"].asUInt(); } break; } } - for(const auto& jport : jroot["ports"]) - { + for(const auto& jport : jroot["ports"]) { auto host_port = jport["hostPort"].asUInt(); auto container_port_it = image_ports.find(jport["name"].asString()); - if(host_port > 0 && container_port_it != image_ports.end()) - { + if(host_port > 0 && container_port_it != image_ports.end()) { sinsp_container_info::container_port_mapping port_mapping; port_mapping.m_host_port = host_port; port_mapping.m_container_port = container_port_it->second; diff --git a/userspace/libsinsp/container_engine/rkt.h b/userspace/libsinsp/container_engine/rkt.h index 8ac562194e..5ae6a0c2d9 100644 --- a/userspace/libsinsp/container_engine/rkt.h +++ b/userspace/libsinsp/container_engine/rkt.h @@ -28,19 +28,23 @@ class sinsp_threadinfo; namespace libsinsp { namespace container_engine { -class rkt : public container_engine_base -{ +class rkt : public container_engine_base { public: - rkt(container_cache_interface& cache) : container_engine_base(cache) - {} + rkt(container_cache_interface& cache): container_engine_base(cache) {} - bool resolve(sinsp_threadinfo *tinfo, bool query_os_for_missing_info) override; + bool resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) override; protected: - bool match(container_cache_interface *cache, sinsp_threadinfo *tinfo, sinsp_container_info& container_info, - std::string& rkt_podid, std::string& rkt_appname, bool query_os_for_missing_info); - - bool parse_rkt(sinsp_container_info& container, const std::string& podid, const std::string& appname); + bool match(container_cache_interface* cache, + sinsp_threadinfo* tinfo, + sinsp_container_info& container_info, + std::string& rkt_podid, + std::string& rkt_appname, + bool query_os_for_missing_info); + + bool parse_rkt(sinsp_container_info& container, + const std::string& podid, + const std::string& appname); }; -} -} +} // namespace container_engine +} // namespace libsinsp diff --git a/userspace/libsinsp/container_engine/sinsp_container_type.h b/userspace/libsinsp/container_engine/sinsp_container_type.h index f285c2a08c..1e21969129 100644 --- a/userspace/libsinsp/container_engine/sinsp_container_type.h +++ b/userspace/libsinsp/container_engine/sinsp_container_type.h @@ -18,8 +18,7 @@ limitations under the License. #pragma once -enum sinsp_container_type -{ +enum sinsp_container_type { CT_DOCKER = 0, CT_LXC = 1, CT_LIBVIRT_LXC = 2, diff --git a/userspace/libsinsp/container_engine/static_container.cpp b/userspace/libsinsp/container_engine/static_container.cpp index ec30f34b86..95f6cbe6a6 100644 --- a/userspace/libsinsp/container_engine/static_container.cpp +++ b/userspace/libsinsp/container_engine/static_container.cpp @@ -26,9 +26,8 @@ using namespace libsinsp::container_engine; static_container::static_container(container_cache_interface& cache, const std::string& id, const std::string& name, - const std::string& image) - : container_engine_base(cache) -{ + const std::string& image): + container_engine_base(cache) { m_static_container_info = std::make_shared(); m_static_container_info->m_id = id; m_static_container_info->m_type = CT_STATIC; @@ -40,19 +39,17 @@ static_container::static_container(container_cache_interface& cache, std::string hostname; std::string port; sinsp_utils::split_container_image(m_static_container_info->m_image, - hostname, - port, - m_static_container_info->m_imagerepo, - m_static_container_info->m_imagetag, - m_static_container_info->m_imagedigest, - false); - + hostname, + port, + m_static_container_info->m_imagerepo, + m_static_container_info->m_imagetag, + m_static_container_info->m_imagedigest, + false); cache.add_container(m_static_container_info, nullptr); } -bool static_container::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) -{ +bool static_container::resolve(sinsp_threadinfo* tinfo, bool query_os_for_missing_info) { tinfo->m_container_id = m_static_container_info->m_id; return true; } diff --git a/userspace/libsinsp/container_engine/static_container.h b/userspace/libsinsp/container_engine/static_container.h index 3ad0548cd9..6fc0bd8f46 100644 --- a/userspace/libsinsp/container_engine/static_container.h +++ b/userspace/libsinsp/container_engine/static_container.h @@ -24,18 +24,15 @@ class sinsp_threadinfo; #include #include -namespace libsinsp -{ -namespace container_engine -{ +namespace libsinsp { +namespace container_engine { /** * static container can be used in cases where we a-priori know that every thread comes from a * single container, for which there is not necessarily an accessible runtime interface, and for * which we already know all appropriate metadata statically. It can be used, say, for userspace * monitoring inside a single container */ -class static_container : public container_engine_base -{ +class static_container : public container_engine_base { public: static_container(container_cache_interface& cache, const std::string& id, diff --git a/userspace/libsinsp/container_info.cpp b/userspace/libsinsp/container_info.cpp index 4b4c5ed102..0da66283e5 100644 --- a/userspace/libsinsp/container_info.cpp +++ b/userspace/libsinsp/container_info.cpp @@ -22,87 +22,71 @@ limitations under the License. #include #include -std::vector sinsp_container_info::container_health_probe::probe_type_names = { - "None", - "Healthcheck", - "LivenessProbe", - "ReadinessProbe", - "End" -}; +std::vector sinsp_container_info::container_health_probe::probe_type_names = + {"None", "Healthcheck", "LivenessProbe", "ReadinessProbe", "End"}; // Initialize container max label length to default 100 value uint32_t sinsp_container_info::m_container_label_max_length = 100; -sinsp_container_info::container_health_probe::container_health_probe() -{ -} +sinsp_container_info::container_health_probe::container_health_probe() {} -sinsp_container_info::container_health_probe::container_health_probe(const probe_type ptype, - const std::string &&exe, - const std::vector &&args) - : m_probe_type(ptype), - m_health_probe_exe(exe), - m_health_probe_args(args) -{ -} +sinsp_container_info::container_health_probe::container_health_probe( + const probe_type ptype, + const std::string &&exe, + const std::vector &&args): + m_probe_type(ptype), + m_health_probe_exe(exe), + m_health_probe_args(args) {} -sinsp_container_info::container_health_probe::~container_health_probe() -{ -} +sinsp_container_info::container_health_probe::~container_health_probe() {} -void sinsp_container_info::container_health_probe::parse_health_probes(const Json::Value &config_obj, - std::list &probes) -{ +void sinsp_container_info::container_health_probe::parse_health_probes( + const Json::Value &config_obj, + std::list &probes) { // Add any health checks described in the container config/labels. - for(int i=PT_NONE; i != PT_END; i++) - { + for(int i = PT_NONE; i != PT_END; i++) { std::string key = probe_type_names[i]; - const Json::Value& probe_obj = config_obj[key]; + const Json::Value &probe_obj = config_obj[key]; - if(!probe_obj.isNull() && probe_obj.isObject()) - { - const Json::Value& probe_exe_obj = probe_obj["exe"]; + if(!probe_obj.isNull() && probe_obj.isObject()) { + const Json::Value &probe_exe_obj = probe_obj["exe"]; - if(!probe_exe_obj.isNull() && probe_exe_obj.isConvertibleTo(Json::stringValue)) - { - const Json::Value& probe_args_obj = probe_obj["args"]; + if(!probe_exe_obj.isNull() && probe_exe_obj.isConvertibleTo(Json::stringValue)) { + const Json::Value &probe_args_obj = probe_obj["args"]; std::string probe_exe = probe_exe_obj.asString(); std::vector probe_args; - if(!probe_args_obj.isNull() && probe_args_obj.isArray()) - { - for(const auto &item : probe_args_obj) - { - if(item.isConvertibleTo(Json::stringValue)) - { + if(!probe_args_obj.isNull() && probe_args_obj.isArray()) { + for(const auto &item : probe_args_obj) { + if(item.isConvertibleTo(Json::stringValue)) { probe_args.push_back(item.asString()); } } } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "add_health_probes: adding %s %s %d", - probe_type_names[i].c_str(), - probe_exe.c_str(), - probe_args.size()); - - probes.emplace_back(static_cast(i), std::move(probe_exe), std::move(probe_args)); + "add_health_probes: adding %s %s %d", + probe_type_names[i].c_str(), + probe_exe.c_str(), + probe_args.size()); + + probes.emplace_back(static_cast(i), + std::move(probe_exe), + std::move(probe_args)); } } } } -void sinsp_container_info::container_health_probe::add_health_probes(const std::list &probes, - Json::Value &config_obj) -{ - for(auto &probe : probes) - { +void sinsp_container_info::container_health_probe::add_health_probes( + const std::list &probes, + Json::Value &config_obj) { + for(auto &probe : probes) { std::string key = probe_type_names[probe.m_probe_type]; Json::Value args; config_obj[key]["exe"] = probe.m_health_probe_exe; - for(auto &arg : probe.m_health_probe_args) - { + for(auto &arg : probe.m_health_probe_args) { args.append(arg); } @@ -110,23 +94,20 @@ void sinsp_container_info::container_health_probe::add_health_probes(const std:: } } -const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by_idx(uint32_t idx) const -{ - if (idx >= m_mounts.size()) - { +const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by_idx( + uint32_t idx) const { + if(idx >= m_mounts.size()) { return NULL; } return &(m_mounts[idx]); } -const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by_source(const std::string& source) const -{ +const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by_source( + const std::string &source) const { // note: linear search - for (auto &mntinfo :m_mounts) - { - if(sinsp_utils::glob_match(source.c_str(), mntinfo.m_source.c_str())) - { + for(auto &mntinfo : m_mounts) { + if(sinsp_utils::glob_match(source.c_str(), mntinfo.m_source.c_str())) { return &mntinfo; } } @@ -134,13 +115,11 @@ const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by return NULL; } -const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by_dest(const std::string& dest) const -{ +const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by_dest( + const std::string &dest) const { // note: linear search - for (auto &mntinfo :m_mounts) - { - if(sinsp_utils::glob_match(dest.c_str(), mntinfo.m_dest.c_str())) - { + for(auto &mntinfo : m_mounts) { + if(sinsp_utils::glob_match(dest.c_str(), mntinfo.m_dest.c_str())) { return &mntinfo; } } @@ -148,8 +127,7 @@ const sinsp_container_info::container_mount_info *sinsp_container_info::mount_by return NULL; } -std::unique_ptr sinsp_container_info::get_tinfo(sinsp* inspector) const -{ +std::unique_ptr sinsp_container_info::get_tinfo(sinsp *inspector) const { auto tinfo = inspector->build_threadinfo(); tinfo->m_tid = -1; tinfo->m_pid = -1; @@ -161,29 +139,28 @@ std::unique_ptr sinsp_container_info::get_tinfo(sinsp* inspect return tinfo; } -sinsp_container_info::container_health_probe::probe_type sinsp_container_info::match_health_probe(sinsp_threadinfo *tinfo) const -{ +sinsp_container_info::container_health_probe::probe_type sinsp_container_info::match_health_probe( + sinsp_threadinfo *tinfo) const { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "match_health_probe (%s): %u health probes to consider", - m_id.c_str(), m_health_probes.size()); - - auto pred = [&] (const container_health_probe &p) { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "match_health_probe (%s): Matching tinfo %s %d against %s %d", - m_id.c_str(), - tinfo->m_exe.c_str(), tinfo->m_args.size(), - p.m_health_probe_exe.c_str(), p.m_health_probe_args.size()); - - return (p.m_health_probe_exe == tinfo->m_exe && - p.m_health_probe_args == tinfo->m_args); - }; - - auto match = std::find_if(m_health_probes.begin(), - m_health_probes.end(), - pred); - - if(match == m_health_probes.end()) - { + "match_health_probe (%s): %u health probes to consider", + m_id.c_str(), + m_health_probes.size()); + + auto pred = [&](const container_health_probe &p) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "match_health_probe (%s): Matching tinfo %s %d against %s %d", + m_id.c_str(), + tinfo->m_exe.c_str(), + tinfo->m_args.size(), + p.m_health_probe_exe.c_str(), + p.m_health_probe_args.size()); + + return (p.m_health_probe_exe == tinfo->m_exe && p.m_health_probe_args == tinfo->m_args); + }; + + auto match = std::find_if(m_health_probes.begin(), m_health_probes.end(), pred); + + if(match == m_health_probes.end()) { return container_health_probe::PT_NONE; } diff --git a/userspace/libsinsp/container_info.h b/userspace/libsinsp/container_info.h index 6968fa147b..90a9d14d5c 100644 --- a/userspace/libsinsp/container_info.h +++ b/userspace/libsinsp/container_info.h @@ -32,32 +32,26 @@ class sinsp; class sinsp_threadinfo; namespace std { -template<> struct hash { - std::size_t operator()(const sinsp_container_type& h) const { +template<> +struct hash { + std::size_t operator()(const sinsp_container_type &h) const { return std::hash{}(static_cast(h)); } }; -} +} // namespace std // Docker and CRI-compatible runtimes are very similar -static inline bool is_docker_compatible(sinsp_container_type t) -{ - return t == CT_DOCKER || - t == CT_CRI || - t == CT_CONTAINERD || - t == CT_CRIO || - t == CT_PODMAN; +static inline bool is_docker_compatible(sinsp_container_type t) { + return t == CT_DOCKER || t == CT_CRI || t == CT_CONTAINERD || t == CT_CRIO || t == CT_PODMAN; } -class sinsp_container_lookup -{ +class sinsp_container_lookup { public: sinsp_container_lookup(short max_retry = 3, short max_delay_ms = 500): - m_max_retry(max_retry), - m_max_delay_ms(max_delay_ms), - m_state(state::FAILED), - m_retry(0) - { + m_max_retry(max_retry), + m_max_delay_ms(max_delay_ms), + m_state(state::FAILED), + m_retry(0) { assert(max_retry >= 0); assert(max_delay_ms > 0); } @@ -74,28 +68,18 @@ class sinsp_container_lookup * If all engines fail to find metadata for a container, we need to remember that * for each engine individually and there's only one sinsp_container_info->m_type */ - enum class state - { - STARTED = 0, - SUCCESSFUL = 1, - FAILED = 2 - }; + enum class state { STARTED = 0, SUCCESSFUL = 1, FAILED = 2 }; state get_status() const { return m_state; } void set_status(state s) { m_state = s; } - bool is_successful() const - { - return m_state == state::SUCCESSFUL; - } + bool is_successful() const { return m_state == state::SUCCESSFUL; } /** * True when not successful and we didn't do too many attempts */ - bool should_retry() const - { - if(is_successful()) - { + bool should_retry() const { + if(is_successful()) { return false; } @@ -105,27 +89,17 @@ class sinsp_container_lookup /** * i.e. whether we didn't do any retry yet */ - bool first_attempt() const - { - return m_retry == 0; - } + bool first_attempt() const { return m_retry == 0; } - short retry_no() const - { - return m_retry; - } + short retry_no() const { return m_retry; } - void attempt_increment() - { - ++m_retry; - } + void attempt_increment() { ++m_retry; } /** * Compute the delay and increment retry count */ - short delay() - { - int curr_delay = 125 << (m_retry-1); + short delay() { + int curr_delay = 125 << (m_retry - 1); return curr_delay > m_max_delay_ms ? m_max_delay_ms : curr_delay; } @@ -136,72 +110,60 @@ class sinsp_container_lookup short m_retry; }; -class sinsp_container_info -{ +class sinsp_container_info { public: using ptr_t = std::shared_ptr; - class container_port_mapping - { + class container_port_mapping { public: - container_port_mapping(): - m_host_ip(0), - m_host_port(0), - m_container_port(0) - { - } + container_port_mapping(): m_host_ip(0), m_host_port(0), m_container_port(0) {} uint32_t m_host_ip; uint16_t m_host_port; uint16_t m_container_port; }; - class container_mount_info - { + class container_mount_info { public: container_mount_info(): - m_source(""), - m_dest(""), - m_mode(""), - m_rdwr(false), - m_propagation("") - { - } - - container_mount_info(const std::string&& source, const std::string&& dest, - const std::string&& mode, const bool rw, - const std::string&& propagation) : - m_source(source), m_dest(dest), m_mode(mode), m_rdwr(rw), m_propagation(propagation) - { - } - - container_mount_info(const Json::Value &source, const Json::Value &dest, - const Json::Value &mode, const Json::Value &rw, - const Json::Value &propagation) - { + m_source(""), + m_dest(""), + m_mode(""), + m_rdwr(false), + m_propagation("") {} + + container_mount_info(const std::string &&source, + const std::string &&dest, + const std::string &&mode, + const bool rw, + const std::string &&propagation): + m_source(source), + m_dest(dest), + m_mode(mode), + m_rdwr(rw), + m_propagation(propagation) {} + + container_mount_info(const Json::Value &source, + const Json::Value &dest, + const Json::Value &mode, + const Json::Value &rw, + const Json::Value &propagation) { get_string_value(source, m_source); get_string_value(dest, m_dest); get_string_value(mode, m_mode); get_string_value(propagation, m_propagation); - if(!rw.isNull() && rw.isBool()) - { + if(!rw.isNull() && rw.isBool()) { m_rdwr = rw.asBool(); } } - std::string to_string() const - { - return m_source + ":" + - m_dest + ":" + - m_mode + ":" + - (m_rdwr ? "true" : "false") + ":" + - m_propagation; + std::string to_string() const { + return m_source + ":" + m_dest + ":" + m_mode + ":" + (m_rdwr ? "true" : "false") + + ":" + m_propagation; } - inline void get_string_value(const Json::Value &val, std::string &result) - { - if(!val.isNull() && val.isString()) - { + inline void get_string_value(const Json::Value &val, std::string &result) { + if(!val.isNull() && val.isString()) { result = val.asString(); } } @@ -213,10 +175,8 @@ class sinsp_container_info std::string m_propagation; }; - class container_health_probe - { + class container_health_probe { public: - // The type of health probe enum probe_type { PT_NONE = 0, @@ -234,16 +194,16 @@ class sinsp_container_info // Parse any health probes out of the provided // container json, updating the list of probes. static void parse_health_probes(const Json::Value &config_obj, - std::list &probes); + std::list &probes); // Serialize the list of health probes, adding to the provided json object static void add_health_probes(const std::list &probes, - Json::Value &config_obj); + Json::Value &config_obj); container_health_probe(); container_health_probe(const probe_type probe_type, - const std::string &&exe, - const std::vector &&args); + const std::string &&exe, + const std::vector &&args); virtual ~container_health_probe(); // The probe_type that should be used for commands @@ -256,51 +216,40 @@ class sinsp_container_info }; sinsp_container_info(sinsp_container_lookup &&lookup = sinsp_container_lookup()): - m_type(CT_UNKNOWN), - m_container_ip(0), - m_privileged(false), - m_memory_limit(0), - m_swap_limit(0), - m_cpu_shares(1024), - m_cpu_quota(0), - m_cpu_period(100000), - m_cpuset_cpu_count(0), - m_is_pod_sandbox(false), - m_lookup(std::move(lookup)), - m_container_user(""), - m_metadata_deadline(0), - m_size_rw_bytes(-1) - { - } - - void clear() - { + m_type(CT_UNKNOWN), + m_container_ip(0), + m_privileged(false), + m_memory_limit(0), + m_swap_limit(0), + m_cpu_shares(1024), + m_cpu_quota(0), + m_cpu_period(100000), + m_cpuset_cpu_count(0), + m_is_pod_sandbox(false), + m_lookup(std::move(lookup)), + m_container_user(""), + m_metadata_deadline(0), + m_size_rw_bytes(-1) {} + + void clear() { this->~sinsp_container_info(); new(this) sinsp_container_info(); } - const std::vector& get_env() const { return m_env; } + const std::vector &get_env() const { return m_env; } const container_mount_info *mount_by_idx(uint32_t idx) const; - const container_mount_info *mount_by_source(const std::string&) const; - const container_mount_info *mount_by_dest(const std::string&) const; + const container_mount_info *mount_by_source(const std::string &) const; + const container_mount_info *mount_by_dest(const std::string &) const; - bool is_pod_sandbox() const { - return m_is_pod_sandbox; - } + bool is_pod_sandbox() const { return m_is_pod_sandbox; } bool is_successful() const { return m_lookup.is_successful(); } - void set_lookup_status(sinsp_container_lookup::state s) - { - m_lookup.set_status(s); - } - sinsp_container_lookup::state get_lookup_status() const - { - return m_lookup.get_status(); - } + void set_lookup_status(sinsp_container_lookup::state s) { m_lookup.set_status(s); } + sinsp_container_lookup::state get_lookup_status() const { return m_lookup.get_status(); } - std::unique_ptr get_tinfo(sinsp* inspector) const; + std::unique_ptr get_tinfo(sinsp *inspector) const; // Match a process against the set of health probes container_health_probe::probe_type match_health_probe(sinsp_threadinfo *tinfo) const; diff --git a/userspace/libsinsp/cri.h b/userspace/libsinsp/cri.h index 83c6c5ec26..d9ab8a4f14 100644 --- a/userspace/libsinsp/cri.h +++ b/userspace/libsinsp/cri.h @@ -27,102 +27,67 @@ limitations under the License. #include #include #include -#endif // MINIMAL_BUILD +#endif // MINIMAL_BUILD #include #include #ifdef GRPC_INCLUDE_IS_GRPCPP -# include +#include #else -# include +#include #endif namespace libsinsp { namespace cri { -class cri_settings -{ +class cri_settings { public: cri_settings(); ~cri_settings(); - static cri_settings& get(); + static cri_settings &get(); - static const std::vector& get_cri_unix_socket_paths() - { + static const std::vector &get_cri_unix_socket_paths() { return get().m_cri_unix_socket_paths; } - static void set_cri_unix_socket_paths(const std::vector& v) - { + static void set_cri_unix_socket_paths(const std::vector &v) { get().m_cri_unix_socket_paths = v; } - static const int64_t& get_cri_timeout() - { - return get().m_cri_timeout; - } + static const int64_t &get_cri_timeout() { return get().m_cri_timeout; } - static void set_cri_timeout(const int64_t& v) - { - get().m_cri_timeout = v; - } + static void set_cri_timeout(const int64_t &v) { get().m_cri_timeout = v; } - static const int64_t& get_cri_size_timeout() - { - return get().m_cri_size_timeout; - } + static const int64_t &get_cri_size_timeout() { return get().m_cri_size_timeout; } - static void set_cri_size_timeout(const int64_t& v) - { - get().m_cri_size_timeout = v; - } + static void set_cri_size_timeout(const int64_t &v) { get().m_cri_size_timeout = v; } - static const sinsp_container_type& get_cri_runtime_type() - { - return get().m_cri_runtime_type; - } + static const sinsp_container_type &get_cri_runtime_type() { return get().m_cri_runtime_type; } - static void set_cri_runtime_type(const sinsp_container_type& v) - { + static void set_cri_runtime_type(const sinsp_container_type &v) { get().m_cri_runtime_type = v; } - static const std::string& get_cri_unix_socket_path() - { - return get().m_cri_unix_socket_path; - } + static const std::string &get_cri_unix_socket_path() { return get().m_cri_unix_socket_path; } - static void set_cri_unix_socket_path(const std::string& v) - { - get().m_cri_unix_socket_path = v; - } + static void set_cri_unix_socket_path(const std::string &v) { get().m_cri_unix_socket_path = v; } - static const bool& get_cri_extra_queries() - { - return get().m_cri_extra_queries; - } + static const bool &get_cri_extra_queries() { return get().m_cri_extra_queries; } - static void set_cri_extra_queries(const bool& v) - { - get().m_cri_extra_queries = v; - } + static void set_cri_extra_queries(const bool &v) { get().m_cri_extra_queries = v; } - static void add_cri_unix_socket_path(const std::string& v) - { + static void add_cri_unix_socket_path(const std::string &v) { get().m_cri_unix_socket_paths.emplace_back(v); } - static void clear_cri_unix_socket_paths() - { - get().m_cri_unix_socket_paths.clear(); - } + static void clear_cri_unix_socket_paths() { get().m_cri_unix_socket_paths.clear(); } private: static std::unique_ptr s_instance; - cri_settings(const cri_settings&) = delete; - cri_settings& operator=(const cri_settings&) = delete; + cri_settings(const cri_settings &) = delete; + cri_settings &operator=(const cri_settings &) = delete; std::vector m_cri_unix_socket_paths; int64_t m_cri_timeout; @@ -132,8 +97,7 @@ class cri_settings bool m_cri_extra_queries; }; -class cri_api_v1alpha2 -{ +class cri_api_v1alpha2 { public: static constexpr const char *version = "v1alpha2"; using RuntimeService = runtime::v1alpha2::RuntimeService; @@ -163,8 +127,7 @@ class cri_api_v1alpha2 using MountPropagation = runtime::v1alpha2::MountPropagation; }; -class cri_api_v1 -{ +class cri_api_v1 { public: static constexpr const char *version = "v1"; using RuntimeService = runtime::v1::RuntimeService; @@ -194,20 +157,16 @@ class cri_api_v1 using MountPropagation = runtime::v1::MountPropagation; }; -template class cri_interface -{ +template +class cri_interface { public: - - cri_interface(const std::string& cri_path); + cri_interface(const std::string &cri_path); /** * @brief did we manage to connect to CRI and get the runtime name/version? * @return true if successfully connected to CRI */ - bool is_ok() const - { - return m_cri != nullptr; - } + bool is_ok() const { return m_cri != nullptr; } /** * @brief get the detected CRI runtime type @@ -223,26 +182,32 @@ template class cri_interface /** * @brief thin wrapper around CRI gRPC ContainerStatus call * @param container_id container ID - * @param resp reference to the response of type api::ContainerStatusResponse (if the RPC is successful, it will be filled out) + * @param resp reference to the response of type api::ContainerStatusResponse (if the RPC is + * successful, it will be filled out) * @return grpc::Status, status of the gRPC call */ - grpc::Status get_container_status_resp(const std::string &container_id, typename api::ContainerStatusResponse &resp); + grpc::Status get_container_status_resp(const std::string &container_id, + typename api::ContainerStatusResponse &resp); /** * @brief thin wrapper around CRI gRPC ContainerStats call * @param container_id container ID - * @param resp reference to the response of type api::ContainerStatusResponse (if the RPC is successful, it will be filled out) + * @param resp reference to the response of type api::ContainerStatusResponse (if the RPC is + * successful, it will be filled out) * @return grpc::Status, status of the gRPC call */ - grpc::Status get_container_stats_resp(const std::string &container_id, typename api::ContainerStatsResponse &resp); + grpc::Status get_container_stats_resp(const std::string &container_id, + typename api::ContainerStatsResponse &resp); /** * @brief thin wrapper around CRI gRPC PodSandboxStatus call make request * @param pod_sandbox_id pod sandbox ID - * @param resp reference to the response of type api::PodSandboxStatusResponse (if the RPC is successful, it will be filled out) + * @param resp reference to the response of type api::PodSandboxStatusResponse (if the RPC is + * successful, it will be filled out) * @return grpc::Status, status of the gRPC call */ - grpc::Status get_pod_sandbox_status_resp(const std::string &pod_sandbox_id, typename api::PodSandboxStatusResponse &resp); + grpc::Status get_pod_sandbox_status_resp(const std::string &pod_sandbox_id, + typename api::PodSandboxStatusResponse &resp); /** * @brief get image id info from CRI via extra API calls @@ -269,7 +234,8 @@ template class cri_interface * @param container the container info to fill out * @return true if successful */ - bool parse_cri_base(const typename api::ContainerStatus &status, sinsp_container_info &container); + bool parse_cri_base(const typename api::ContainerStatus &status, + sinsp_container_info &container); /** * @brief fill out container image information based on CRI response @@ -279,17 +245,18 @@ template class cri_interface * @return true if successful */ bool parse_cri_image(const typename api::ContainerStatus &status, - const Json::Value &root, - sinsp_container_info &container); + const Json::Value &root, + sinsp_container_info &container); /** - * @brief fill out pod sandbox id, only valid when used w/ ContainerStatusResponse, not PodSandboxStatusResponse + * @brief fill out pod sandbox id, only valid when used w/ ContainerStatusResponse, not + * PodSandboxStatusResponse * @param root Json::Value of status.info() at "info" of the ContainerStatusResponse * @param container the container info to fill out * @return true if successful */ bool parse_cri_pod_sandbox_id_for_container(const Json::Value &root, - sinsp_container_info &container); + sinsp_container_info &container); /** * @brief fill out container mount information based on CRI response @@ -297,10 +264,12 @@ template class cri_interface * @param container the container info to fill out * @return true if successful */ - bool parse_cri_mounts(const typename api::ContainerStatus &status, sinsp_container_info &container); + bool parse_cri_mounts(const typename api::ContainerStatus &status, + sinsp_container_info &container); /** - * @brief fill out container environment variables based on CRI response, valid for containerd only + * @brief fill out container environment variables based on CRI response, valid for containerd + * only * @param root Json::Value of status.info() at "info" of the ContainerStatusResponse * @param container the container info to fill out * @return true if successful @@ -343,7 +312,8 @@ template class cri_interface * @param container the container info to fill out * @return true if successful */ - bool parse_cri_labels(const typename api::ContainerStatus &status, sinsp_container_info &container); + bool parse_cri_labels(const typename api::ContainerStatus &status, + sinsp_container_info &container); /////////////////////////////////////////////////////////// // CRI response (PodSandboxStatus) parsers helpers @@ -355,10 +325,12 @@ template class cri_interface * @param container the container info to fill out * @return true if successful */ - bool parse_cri_base(const typename api::PodSandboxStatus &status, sinsp_container_info &container); + bool parse_cri_base(const typename api::PodSandboxStatus &status, + sinsp_container_info &container); /** - * @brief fill out pod sandbox id, only valid when used w/ PodSandboxStatus, not ContainerStatusResponse + * @brief fill out pod sandbox id, only valid when used w/ PodSandboxStatus, not + * ContainerStatusResponse * @param container the container info to fill out * @note effectively assigning the existing container.m_full_id as pod sandbox ID * @return true if successful @@ -371,7 +343,8 @@ template class cri_interface * @param container the container info to fill out * @return true if successful */ - bool parse_cri_labels(const typename api::PodSandboxStatus &status, sinsp_container_info &container); + bool parse_cri_labels(const typename api::PodSandboxStatus &status, + sinsp_container_info &container); /** * @brief fill out pod sandbox labels @@ -379,7 +352,8 @@ template class cri_interface * @param container the container info to fill out * @return true if successful */ - bool parse_cri_pod_sandbox_labels(const typename api::PodSandboxStatus &status, sinsp_container_info &container); + bool parse_cri_pod_sandbox_labels(const typename api::PodSandboxStatus &status, + sinsp_container_info &container); /** * @brief fill out pod sandbox network info @@ -389,9 +363,8 @@ template class cri_interface * @return true if successful */ bool parse_cri_pod_sandbox_network(const typename api::PodSandboxStatus &status, - const Json::Value &root, - sinsp_container_info &container); - + const Json::Value &root, + sinsp_container_info &container); ///////////////////////////// // Generic parsers helpers @@ -404,19 +377,20 @@ template class cri_interface */ Json::Value get_info_jvalue(const google::protobuf::Map &info); - /////////////////////////////////////////////////////////////////// // Main CRI parse entrypoint (make API calls and parse responses) /////////////////////////////////////////////////////////////////// /** - * @brief fill in container metadata using the CRI API (`containerd` and `cri-o` container runtimes). - * This is the main CRI parser calling each parse_* helper after making the respective CRI API call(s). + * @brief fill in container metadata using the CRI API (`containerd` and `cri-o` container + * runtimes). This is the main CRI parser calling each parse_* helper after making the + * respective CRI API call(s). * @param key includes container_id, but container.m_id is used to make the CRI API calls * @param container the container info to fill * @return true on success, false on failure */ - bool parse(const libsinsp::cgroup_limits::cgroup_limits_key &key, sinsp_container_info &container); + bool parse(const libsinsp::cgroup_limits::cgroup_limits_key &key, + sinsp_container_info &container); private: std::unique_ptr m_cri; @@ -426,5 +400,5 @@ template class cri_interface using cri_interface_v1alpha2 = cri_interface; using cri_interface_v1 = cri_interface; -} -} +} // namespace cri +} // namespace libsinsp diff --git a/userspace/libsinsp/cri.hpp b/userspace/libsinsp/cri.hpp index 953d9128e7..c591ad997c 100644 --- a/userspace/libsinsp/cri.hpp +++ b/userspace/libsinsp/cri.hpp @@ -28,15 +28,13 @@ limitations under the License. #define MAX_CNIRESULT_LENGTH 4096 -namespace libsinsp -{ -namespace cri -{ +namespace libsinsp { +namespace cri { -template -inline cri_interface::cri_interface(const std::string &cri_path) -{ - std::shared_ptr channel = libsinsp::grpc_channel_registry::get_channel("unix://" + cri_path); +template +inline cri_interface::cri_interface(const std::string &cri_path) { + std::shared_ptr channel = + libsinsp::grpc_channel_registry::get_channel("unix://" + cri_path); m_cri = api::RuntimeService::NewStub(channel); @@ -45,43 +43,41 @@ inline cri_interface::cri_interface(const std::string &cri_path) vreq.set_version(api::version); grpc::ClientContext context; - auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(cri_settings::get_cri_timeout()); + auto deadline = std::chrono::system_clock::now() + + std::chrono::milliseconds(cri_settings::get_cri_timeout()); context.set_deadline(deadline); grpc::Status status = m_cri->Version(&context, vreq, &vresp); - if(!status.ok()) - { - libsinsp_logger()->format(sinsp_logger::SEV_NOTICE, - "cri: CRI runtime returned an error after version check at %s: %s", cri_path.c_str(), - status.error_message().c_str()); + if(!status.ok()) { + libsinsp_logger()->format( + sinsp_logger::SEV_NOTICE, + "cri: CRI runtime returned an error after version check at %s: %s", + cri_path.c_str(), + status.error_message().c_str()); m_cri.reset(nullptr); return; } - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "cri: CRI runtime: %s %s", vresp.runtime_name().c_str(), - vresp.runtime_version().c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "cri: CRI runtime: %s %s", + vresp.runtime_name().c_str(), + vresp.runtime_version().c_str()); m_cri_image = api::ImageService::NewStub(channel); const std::string &runtime_name = vresp.runtime_name(); - if(runtime_name == "containerd") - { + if(runtime_name == "containerd") { m_cri_runtime_type = CT_CONTAINERD; - } - else if(runtime_name == "cri-o") - { + } else if(runtime_name == "cri-o") { m_cri_runtime_type = CT_CRIO; - } - else - { + } else { m_cri_runtime_type = CT_CRI; } cri_settings::set_cri_runtime_type(m_cri_runtime_type); } -template -inline sinsp_container_type cri_interface::get_cri_runtime_type() const -{ +template +inline sinsp_container_type cri_interface::get_cri_runtime_type() const { return m_cri_runtime_type; } @@ -90,70 +86,74 @@ inline sinsp_container_type cri_interface::get_cri_runtime_type() const ////////////////////////// template -inline grpc::Status cri_interface::get_container_status_resp(const std::string &container_id, - typename api::ContainerStatusResponse &resp) -{ +inline grpc::Status cri_interface::get_container_status_resp( + const std::string &container_id, + typename api::ContainerStatusResponse &resp) { typename api::ContainerStatusRequest req; req.set_container_id(container_id); req.set_verbose(true); grpc::ClientContext context; - auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(cri_settings::get_cri_timeout()); + auto deadline = std::chrono::system_clock::now() + + std::chrono::milliseconds(cri_settings::get_cri_timeout()); context.set_deadline(deadline); return m_cri->ContainerStatus(&context, req, &resp); } template -inline grpc::Status cri_interface::get_container_stats_resp(const std::string &container_id, - typename api::ContainerStatsResponse &resp) -{ +inline grpc::Status cri_interface::get_container_stats_resp( + const std::string &container_id, + typename api::ContainerStatsResponse &resp) { typename api::ContainerStatsRequest req; req.set_container_id(container_id); grpc::ClientContext context; - auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(cri_settings::get_cri_size_timeout()); + auto deadline = std::chrono::system_clock::now() + + std::chrono::milliseconds(cri_settings::get_cri_size_timeout()); context.set_deadline(deadline); return m_cri->ContainerStats(&context, req, &resp); } template -grpc::Status cri_interface::get_pod_sandbox_status_resp(const std::string &pod_sandbox_id, - typename api::PodSandboxStatusResponse &resp) -{ +grpc::Status cri_interface::get_pod_sandbox_status_resp( + const std::string &pod_sandbox_id, + typename api::PodSandboxStatusResponse &resp) { typename api::PodSandboxStatusRequest req; req.set_pod_sandbox_id(pod_sandbox_id); req.set_verbose(true); grpc::ClientContext context; - auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(cri_settings::get_cri_timeout()); + auto deadline = std::chrono::system_clock::now() + + std::chrono::milliseconds(cri_settings::get_cri_timeout()); context.set_deadline(deadline); return m_cri->PodSandboxStatus(&context, req, &resp); } -template -inline std::string cri_interface::get_container_image_id(const std::string &image_ref) -{ +template +inline std::string cri_interface::get_container_image_id(const std::string &image_ref) { typename api::ListImagesRequest req; typename api::ListImagesResponse resp; auto filter = req.mutable_filter(); auto spec = filter->mutable_image(); spec->set_image(image_ref); grpc::ClientContext context; - auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(cri_settings::get_cri_timeout()); + auto deadline = std::chrono::system_clock::now() + + std::chrono::milliseconds(cri_settings::get_cri_timeout()); context.set_deadline(deadline); grpc::Status status = m_cri_image->ListImages(&context, req, &resp); - switch(resp.images_size()) - { + switch(resp.images_size()) { case 0: - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Image ref %s not in list from CRI", image_ref.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_WARNING, + "Image ref %s not in list from CRI", + image_ref.c_str()); ASSERT(false); break; - case 1: - { + case 1: { const auto &image = resp.images(0); return image.id(); } default: - libsinsp_logger()->format(sinsp_logger::SEV_WARNING, "Image ref %s matches more than once in list from CRI", - image_ref.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_WARNING, + "Image ref %s matches more than once in list from CRI", + image_ref.c_str()); ASSERT(false); break; } @@ -162,43 +162,45 @@ inline std::string cri_interface::get_container_image_id(const std::string } template -inline std::optional cri_interface::get_writable_layer_size(const std::string &container_id) -{ +inline std::optional cri_interface::get_writable_layer_size( + const std::string &container_id) { // Synchronously get the stats response and update the container table. // Note that this needs to use the full id. typename api::ContainerStatsResponse resp; grpc::Status status = get_container_stats_resp(container_id, resp); - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): Status from ContainerStats: (%s)", container_id.c_str(), - status.error_message().empty() ? "SUCCESS" : status.error_message().c_str()); + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "cri (%s): Status from ContainerStats: (%s)", + container_id.c_str(), + status.error_message().empty() ? "SUCCESS" : status.error_message().c_str()); - if(!status.ok()) - { + if(!status.ok()) { return std::nullopt; } - if(!resp.has_stats()) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): Failed to update size: stats() not found", - container_id.c_str()); + if(!resp.has_stats()) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): Failed to update size: stats() not found", + container_id.c_str()); ASSERT(false); return std::nullopt; } const auto &resp_stats = resp.stats(); - if(!resp_stats.has_writable_layer()) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): Failed to update size: writable_layer() not found", - container_id.c_str()); + if(!resp_stats.has_writable_layer()) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): Failed to update size: writable_layer() not found", + container_id.c_str()); ASSERT(false); return std::nullopt; } - if(!resp_stats.writable_layer().has_used_bytes()) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): Failed to update size: used_bytes() not found", - container_id.c_str()); + if(!resp_stats.writable_layer().has_used_bytes()) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): Failed to update size: used_bytes() not found", + container_id.c_str()); ASSERT(false); return std::nullopt; } @@ -210,10 +212,10 @@ inline std::optional cri_interface::get_writable_layer_size(const // Generic parsers helpers ///////////////////////////// -inline bool walk_down_json(const Json::Value &root, const Json::Value **out, const std::string &key) -{ - if(root.isMember(key)) - { +inline bool walk_down_json(const Json::Value &root, + const Json::Value **out, + const std::string &key) { + if(root.isMember(key)) { *out = &root[key]; return true; } @@ -221,39 +223,34 @@ inline bool walk_down_json(const Json::Value &root, const Json::Value **out, con } template -inline bool walk_down_json(const Json::Value &root, const Json::Value **out, const std::string &key, Args... args) -{ - if(root.isMember(key)) - { +inline bool walk_down_json(const Json::Value &root, + const Json::Value **out, + const std::string &key, + Args... args) { + if(root.isMember(key)) { return walk_down_json(root[key], out, args...); } return false; } -inline bool set_numeric_32(const Json::Value &dict, const std::string &key, int32_t &val) -{ - if(!dict.isMember(key)) - { +inline bool set_numeric_32(const Json::Value &dict, const std::string &key, int32_t &val) { + if(!dict.isMember(key)) { return false; } const auto &json_val = dict[key]; - if(!json_val.isNumeric()) - { + if(!json_val.isNumeric()) { return false; } val = json_val.asInt(); return true; } -inline bool set_numeric_64(const Json::Value &dict, const std::string &key, int64_t &val) -{ - if(!dict.isMember(key)) - { +inline bool set_numeric_64(const Json::Value &dict, const std::string &key, int64_t &val) { + if(!dict.isMember(key)) { return false; } const auto &json_val = dict[key]; - if(!json_val.isNumeric()) - { + if(!json_val.isNumeric()) { return false; } val = json_val.asInt64(); @@ -261,14 +258,12 @@ inline bool set_numeric_64(const Json::Value &dict, const std::string &key, int6 } template -inline Json::Value cri_interface::get_info_jvalue(const google::protobuf::Map &info) -{ - +inline Json::Value cri_interface::get_info_jvalue( + const google::protobuf::Map &info) { Json::Value root; Json::Reader reader; const auto &info_it = info.find("info"); - if(info_it == info.end()) - { + if(info_it == info.end()) { return root; } reader.parse(info_it->second, root); @@ -279,10 +274,9 @@ inline Json::Value cri_interface::get_info_jvalue(const google::protobuf::M // CRI response (ContainerStatusResponse) parsers helpers /////////////////////////////////////////////////////////// - template -inline bool cri_interface::parse_cri_base(const typename api::ContainerStatus &status, sinsp_container_info &container) -{ +inline bool cri_interface::parse_cri_base(const typename api::ContainerStatus &status, + sinsp_container_info &container) { container.m_full_id = status.id(); container.m_name = status.metadata().name(); // This is in Nanoseconds(in CRI API). Need to convert it to seconds. @@ -292,16 +286,14 @@ inline bool cri_interface::parse_cri_base(const typename api::ContainerStat } template -inline bool cri_interface::parse_cri_pod_sandbox_id_for_container(const Json::Value &root, - sinsp_container_info &container) -{ - if(root.isNull()) - { +inline bool cri_interface::parse_cri_pod_sandbox_id_for_container( + const Json::Value &root, + sinsp_container_info &container) { + if(root.isNull()) { return false; } - if(root.isMember("sandboxID") && root["sandboxID"].isString()) - { + if(root.isMember("sandboxID") && root["sandboxID"].isString()) { std::string pod_sandbox_id = root["sandboxID"].asString(); container.m_pod_sandbox_id = pod_sandbox_id; // Add the pod sandbox id as label to the container for backward compatibility @@ -312,12 +304,10 @@ inline bool cri_interface::parse_cri_pod_sandbox_id_for_container(const Jso } template -inline bool cri_interface::parse_cri_labels(const typename api::ContainerStatus &status, sinsp_container_info &container) -{ - for(const auto &pair : status.labels()) - { - if(pair.second.length() <= sinsp_container_info::m_container_label_max_length) - { +inline bool cri_interface::parse_cri_labels(const typename api::ContainerStatus &status, + sinsp_container_info &container) { + for(const auto &pair : status.labels()) { + if(pair.second.length() <= sinsp_container_info::m_container_label_max_length) { container.m_labels[pair.first] = pair.second; } } @@ -326,9 +316,8 @@ inline bool cri_interface::parse_cri_labels(const typename api::ContainerSt template inline bool cri_interface::parse_cri_image(const typename api::ContainerStatus &status, - const Json::Value &root, - sinsp_container_info &container) -{ + const Json::Value &root, + sinsp_container_info &container) { // image_ref may be one of two forms: // host/image@sha256:digest // sha256:digest @@ -339,69 +328,78 @@ inline bool cri_interface::parse_cri_image(const typename api::ContainerSta bool get_tag_from_image = false; auto digest_start = image_ref.find("sha256:"); - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): parse_cri_image: image_ref=%s, digest_start=%d", - container.m_id.c_str(), image_ref.c_str(), digest_start); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): parse_cri_image: image_ref=%s, digest_start=%d", + container.m_id.c_str(), + image_ref.c_str(), + digest_start); - switch(digest_start) - { - case 0: // sha256:digest + switch(digest_start) { + case 0: // sha256:digest have_digest = true; break; case std::string::npos: break; - default: // host/image@sha256:digest + default: // host/image@sha256:digest have_digest = image_ref[digest_start - 1] == '@'; - if(have_digest) - { + if(have_digest) { image_name = image_ref.substr(0, digest_start - 1); get_tag_from_image = true; } } - if(image_name.empty() || strncmp(image_name.c_str(), "sha256", 6) == 0) - { - /* Retrieve image_name from annotations as backup when image name may (still) start with sha256 - * or otherwise was not successfully retrieved. Brute force try each schema we know of for containerd - * and cri-o container runtimes. - */ + if(image_name.empty() || strncmp(image_name.c_str(), "sha256", 6) == 0) { + /* Retrieve image_name from annotations as backup when image name may (still) start with + * sha256 or otherwise was not successfully retrieved. Brute force try each schema we know + * of for containerd and cri-o container runtimes. + */ - if(!root.isNull()) - { + if(!root.isNull()) { Json::Value jvalue; jvalue = root["runtimeSpec"]["annotations"]["io.kubernetes.cri.image-name"]; - if(jvalue.isNull()) - { - jvalue = - root["runtimeSpec"]["annotations"]["io.kubernetes.cri-o.Image"]; + if(jvalue.isNull()) { + jvalue = root["runtimeSpec"]["annotations"]["io.kubernetes.cri-o.Image"]; } - if(jvalue.isNull()) - { - jvalue = root["runtimeSpec"]["annotations"] - ["io.kubernetes.cri-o.ImageName"]; + if(jvalue.isNull()) { + jvalue = root["runtimeSpec"]["annotations"]["io.kubernetes.cri-o.ImageName"]; } - if(!jvalue.isNull()) - { + if(!jvalue.isNull()) { image_name = jvalue.asString(); get_tag_from_image = false; } } } - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): parse_cri_image: have_digest=%d image_name=%s", - container.m_id.c_str(), have_digest, image_name.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): parse_cri_image: have_digest=%d image_name=%s", + container.m_id.c_str(), + have_digest, + image_name.c_str()); std::string hostname, port, digest; - sinsp_utils::split_container_image(image_name, hostname, port, container.m_imagerepo, container.m_imagetag, - digest, false); - - if(get_tag_from_image) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): parse_cri_image: tag=%s, pulling tag from %s", - container.m_id.c_str(), container.m_imagetag.c_str(), status.image().image().c_str()); + sinsp_utils::split_container_image(image_name, + hostname, + port, + container.m_imagerepo, + container.m_imagetag, + digest, + false); + + if(get_tag_from_image) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): parse_cri_image: tag=%s, pulling tag from %s", + container.m_id.c_str(), + container.m_imagetag.c_str(), + status.image().image().c_str()); std::string digest2, repo; - sinsp_utils::split_container_image(status.image().image(), hostname, port, repo, container.m_imagetag, - digest2, false); + sinsp_utils::split_container_image(status.image().image(), + hostname, + port, + repo, + container.m_imagetag, + digest2, + false); image_name.push_back(':'); image_name.append(container.m_imagetag); @@ -409,44 +407,40 @@ inline bool cri_interface::parse_cri_image(const typename api::ContainerSta container.m_image = image_name; - if(have_digest) - { + if(have_digest) { container.m_imagedigest = image_ref.substr(digest_start); - } - else - { + } else { container.m_imagedigest = digest; } - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): parse_cri_image: repo=%s tag=%s image=%s digest=%s", - container.m_id.c_str(), container.m_imagerepo.c_str(), container.m_imagetag.c_str(), - container.m_image.c_str(), container.m_imagedigest.c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): parse_cri_image: repo=%s tag=%s image=%s digest=%s", + container.m_id.c_str(), + container.m_imagerepo.c_str(), + container.m_imagetag.c_str(), + container.m_image.c_str(), + container.m_imagedigest.c_str()); return true; } template -inline bool cri_interface::parse_cri_json_imageid(const Json::Value &root, sinsp_container_info &container) -{ - if(root.isNull()) - { +inline bool cri_interface::parse_cri_json_imageid(const Json::Value &root, + sinsp_container_info &container) { + if(root.isNull()) { return false; } const Json::Value *image = nullptr; - if(!walk_down_json(root, &image, "config", "image", "image") || !image->isString()) - { + if(!walk_down_json(root, &image, "config", "image", "image") || !image->isString()) { return false; } auto image_str = image->asString(); auto pos = image_str.find(':'); - if(pos == std::string::npos) - { + if(pos == std::string::npos) { container.m_imageid = std::move(image_str); - } - else - { + } else { container.m_imageid = image_str.substr(pos + 1); } @@ -454,13 +448,11 @@ inline bool cri_interface::parse_cri_json_imageid(const Json::Value &root, } template -inline bool cri_interface::parse_cri_mounts(const typename api::ContainerStatus &status, sinsp_container_info &container) -{ - for(const auto &mount : status.mounts()) - { +inline bool cri_interface::parse_cri_mounts(const typename api::ContainerStatus &status, + sinsp_container_info &container) { + for(const auto &mount : status.mounts()) { const char *propagation; - switch(mount.propagation()) - { + switch(mount.propagation()) { case api::MountPropagation::PROPAGATION_PRIVATE: propagation = "private"; break; @@ -474,33 +466,32 @@ inline bool cri_interface::parse_cri_mounts(const typename api::ContainerSt propagation = "unknown"; break; } - container.m_mounts.emplace_back(mount.host_path(), mount.container_path(), "", !mount.readonly(), - propagation); + container.m_mounts.emplace_back(mount.host_path(), + mount.container_path(), + "", + !mount.readonly(), + propagation); } return true; } -template -inline bool cri_interface::parse_cri_env(const Json::Value &root, sinsp_container_info &container) -{ - if(root.isNull()) - { +template +inline bool cri_interface::parse_cri_env(const Json::Value &root, + sinsp_container_info &container) { + if(root.isNull()) { return false; } const Json::Value *envs = nullptr; - if(!walk_down_json(root, &envs, "config", "envs") || !envs->isArray()) - { + if(!walk_down_json(root, &envs, "config", "envs") || !envs->isArray()) { return false; } - for(const auto &env_var : *envs) - { + for(const auto &env_var : *envs) { const auto &key = env_var["key"]; const auto &value = env_var["value"]; - if(key.isString() && value.isString()) - { + if(key.isString() && value.isString()) { auto var = key.asString(); var += '='; var += value.asString(); @@ -511,29 +502,25 @@ inline bool cri_interface::parse_cri_env(const Json::Value &root, sinsp_con } template -inline bool cri_interface::parse_cri_ext_container_info(const Json::Value &root, sinsp_container_info &container) -{ - if(root.isNull()) - { +inline bool cri_interface::parse_cri_ext_container_info(const Json::Value &root, + sinsp_container_info &container) { + if(root.isNull()) { return false; } const Json::Value *linux = nullptr; - if(!walk_down_json(root, &linux, "runtimeSpec", "linux") || !linux->isObject()) - { + if(!walk_down_json(root, &linux, "runtimeSpec", "linux") || !linux->isObject()) { return false; } const Json::Value *memory = nullptr; - if(walk_down_json(*linux, &memory, "resources", "memory")) - { + if(walk_down_json(*linux, &memory, "resources", "memory")) { set_numeric_64(*memory, "limit", container.m_memory_limit); container.m_swap_limit = container.m_memory_limit; } const Json::Value *cpu = nullptr; - if(walk_down_json(*linux, &cpu, "resources", "cpu") && cpu->isObject()) - { + if(walk_down_json(*linux, &cpu, "resources", "cpu") && cpu->isObject()) { set_numeric_64(*cpu, "shares", container.m_cpu_shares); set_numeric_64(*cpu, "quota", container.m_cpu_quota); set_numeric_64(*cpu, "period", container.m_cpu_period); @@ -543,23 +530,22 @@ inline bool cri_interface::parse_cri_ext_container_info(const Json::Value & bool priv_found = false; const Json::Value *privileged = nullptr; // old containerd? - if(walk_down_json(*linux, &privileged, "security_context", "privileged") && privileged->isBool()) - { + if(walk_down_json(*linux, &privileged, "security_context", "privileged") && + privileged->isBool()) { container.m_privileged = privileged->asBool(); priv_found = true; } // containerd - if(!priv_found && walk_down_json(root, &privileged, "config", "linux", "security_context", "privileged") && - privileged->isBool()) - { + if(!priv_found && + walk_down_json(root, &privileged, "config", "linux", "security_context", "privileged") && + privileged->isBool()) { container.m_privileged = privileged->asBool(); priv_found = true; } // cri-o - if(!priv_found && walk_down_json(root, &privileged, "privileged") && privileged->isBool()) - { + if(!priv_found && walk_down_json(root, &privileged, "privileged") && privileged->isBool()) { container.m_privileged = privileged->asBool(); priv_found = true; } @@ -568,16 +554,14 @@ inline bool cri_interface::parse_cri_ext_container_info(const Json::Value & } template -inline bool cri_interface::parse_cri_user_info(const Json::Value &root, sinsp_container_info &container) -{ - if(root.isNull()) - { +inline bool cri_interface::parse_cri_user_info(const Json::Value &root, + sinsp_container_info &container) { + if(root.isNull()) { return false; } const Json::Value *uid = nullptr; - if(!walk_down_json(root, &uid, "runtimeSpec", "process", "user", "uid") || !uid->isInt()) - { + if(!walk_down_json(root, &uid, "runtimeSpec", "process", "user", "uid") || !uid->isInt()) { return false; } @@ -591,8 +575,8 @@ inline bool cri_interface::parse_cri_user_info(const Json::Value &root, sin // overloaded w/ PodSandboxStatus template -inline bool cri_interface::parse_cri_base(const typename api::PodSandboxStatus &status, sinsp_container_info &container) -{ +inline bool cri_interface::parse_cri_base(const typename api::PodSandboxStatus &status, + sinsp_container_info &container) { container.m_full_id = status.id(); container.m_name = status.metadata().name(); // This is in Nanoseconds(in CRI API). Need to convert it to seconds. @@ -602,8 +586,8 @@ inline bool cri_interface::parse_cri_base(const typename api::PodSandboxSta } template -inline bool cri_interface::parse_cri_pod_sandbox_id_for_podsandbox(sinsp_container_info &container) -{ +inline bool cri_interface::parse_cri_pod_sandbox_id_for_podsandbox( + sinsp_container_info &container) { container.m_pod_sandbox_id = container.m_full_id; // Add the pod sandbox id as label to the container for backward compatibility container.m_labels["io.kubernetes.sandbox.id"] = container.m_full_id; @@ -613,12 +597,10 @@ inline bool cri_interface::parse_cri_pod_sandbox_id_for_podsandbox(sinsp_co // overloaded w/ PodSandboxStatus template -inline bool cri_interface::parse_cri_labels(const typename api::PodSandboxStatus &status, sinsp_container_info &container) -{ - for(const auto &pair : status.labels()) - { - if(pair.second.length() <= sinsp_container_info::m_container_label_max_length) - { +inline bool cri_interface::parse_cri_labels(const typename api::PodSandboxStatus &status, + sinsp_container_info &container) { + for(const auto &pair : status.labels()) { + if(pair.second.length() <= sinsp_container_info::m_container_label_max_length) { container.m_labels[pair.first] = pair.second; } } @@ -630,12 +612,11 @@ inline bool cri_interface::parse_cri_labels(const typename api::PodSandboxS } template -inline bool cri_interface::parse_cri_pod_sandbox_labels(const typename api::PodSandboxStatus &status, sinsp_container_info &container) -{ - for(const auto &pair : status.labels()) - { - if(pair.second.length() <= sinsp_container_info::m_container_label_max_length) - { +inline bool cri_interface::parse_cri_pod_sandbox_labels( + const typename api::PodSandboxStatus &status, + sinsp_container_info &container) { + for(const auto &pair : status.labels()) { + if(pair.second.length() <= sinsp_container_info::m_container_label_max_length) { container.m_pod_sandbox_labels[pair.first] = pair.second; } } @@ -643,24 +624,22 @@ inline bool cri_interface::parse_cri_pod_sandbox_labels(const typename api: } template -inline bool cri_interface::parse_cri_pod_sandbox_network(const typename api::PodSandboxStatus &status, - const Json::Value &root, - sinsp_container_info &container) -{ +inline bool cri_interface::parse_cri_pod_sandbox_network( + const typename api::PodSandboxStatus &status, + const Json::Value &root, + sinsp_container_info &container) { // // Pod IP // const auto pod_ip = status.network().ip(); uint32_t ip; - if(pod_ip.empty() || - // using host netns - (status.linux().namespaces().options().network() == api::NamespaceMode::NODE) || - (inet_pton(AF_INET, pod_ip.c_str(), &ip) == -1)) - { + if(pod_ip.empty() || + // using host netns + (status.linux().namespaces().options().network() == api::NamespaceMode::NODE) || + (inet_pton(AF_INET, pod_ip.c_str(), &ip) == -1)) { container.m_container_ip = 0; - } else - { + } else { container.m_container_ip = ntohl(ip); } @@ -668,29 +647,24 @@ inline bool cri_interface::parse_cri_pod_sandbox_network(const typename api // Pod Sandbox CNI Result // - if(root.isNull()) - { + if(root.isNull()) { return false; } std::string cniresult; Json::Value jvalue; - /* Lookup approach is brute force "try all schemas" we know of, do not condition by container runtime for - * possible future "would just work" luck in case other runtimes standardize on one of the current schemas. */ + /* Lookup approach is brute force "try all schemas" we know of, do not condition by container + * runtime for possible future "would just work" luck in case other runtimes standardize on one + * of the current schemas. */ jvalue = root["cniResult"]["Interfaces"]; /* pod info schema of CT_CONTAINERD runtime. */ - if(!jvalue.isNull()) - { + if(!jvalue.isNull()) { /* If applicable remove members / fields not needed for incident response. */ jvalue.removeMember("lo"); - for(auto &key : jvalue.getMemberNames()) - { - if(0 == strncmp(key.c_str(), "veth", 4)) - { + for(auto &key : jvalue.getMemberNames()) { + if(0 == strncmp(key.c_str(), "veth", 4)) { jvalue.removeMember(key); - } - else - { + } else { jvalue[key].removeMember("Mac"); jvalue[key].removeMember("Sandbox"); } @@ -700,18 +674,17 @@ inline bool cri_interface::parse_cri_pod_sandbox_network(const typename api cniresult = fastWriter.write(jvalue); } - if(jvalue.isNull()) - { + if(jvalue.isNull()) { jvalue = root["runtimeSpec"]["annotations"] - ["io.kubernetes.cri-o.CNIResult"]; /* pod info schema of CT_CRIO runtime. Note interfaces - names are unknown here. */ - if(!jvalue.isNull()) - { + ["io.kubernetes.cri-o.CNIResult"]; /* pod info schema of CT_CRIO runtime. Note + interfaces names are unknown here. */ + if(!jvalue.isNull()) { cniresult = jvalue.asString(); } } - if(cniresult[cniresult.size() - 1] == '\n') /* Make subsequent ETLs nicer w/ minor cleanups if applicable. */ + if(cniresult[cniresult.size() - 1] == + '\n') /* Make subsequent ETLs nicer w/ minor cleanups if applicable. */ { cniresult.pop_back(); } @@ -731,57 +704,56 @@ inline bool cri_interface::parse_cri_pod_sandbox_network(const typename api /////////////////////////////////////////////////////////////////// template -inline bool cri_interface::parse(const libsinsp::cgroup_limits::cgroup_limits_key &key, sinsp_container_info &container) -{ +inline bool cri_interface::parse(const libsinsp::cgroup_limits::cgroup_limits_key &key, + sinsp_container_info &container) { typename api::ContainerStatusResponse container_status_resp; // status contains info around if API call suceeded and is not the container status property grpc::Status status = get_container_status_resp(container.m_id, container_status_resp); - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): ContainerStatusResponse status error message: (%s)", container.m_id.c_str(), - status.error_message().c_str()); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): ContainerStatusResponse status error message: (%s)", + container.m_id.c_str(), + status.error_message().c_str()); // If container status failed try to get the pod sandbox status. - if(!status.ok()) - { + if(!status.ok()) { typename api::PodSandboxStatusResponse pod_sandbox_status_resp; status = get_pod_sandbox_status_resp(container.m_id, pod_sandbox_status_resp); - if(status.ok()) - { + if(status.ok()) { /* - * We also want to ensure that the pod sandbox container stored in the container cache is - * fully filled out with available information as applicable. - * Most notably, the container's m_full_id and m_pod_sandbox_id will be the same, and the - * absence of container images can be attributed to the fact that they are not available for - * pod sandbox container processes. - * Another notable fact is that for pod sandbox containers container.m_lables and - * container.m_pod_sandbox_labels are also the same. - */ + * We also want to ensure that the pod sandbox container stored in the container cache + * is fully filled out with available information as applicable. Most notably, the + * container's m_full_id and m_pod_sandbox_id will be the same, and the absence of + * container images can be attributed to the fact that they are not available for pod + * sandbox container processes. Another notable fact is that for pod sandbox containers + * container.m_lables and container.m_pod_sandbox_labels are also the same. + */ container.m_is_pod_sandbox = true; const auto &resp_pod_sandbox_container = pod_sandbox_status_resp.status(); const auto &resp_pod_sandbox_container_info = pod_sandbox_status_resp.info(); const auto root_pod_sandbox = get_info_jvalue(resp_pod_sandbox_container_info); parse_cri_base(resp_pod_sandbox_container, container); parse_cri_pod_sandbox_id_for_podsandbox(container); - // `parse_cri_labels`: The pod sandbox container does not contain the namespace etc as labels. - // To be consistent in the k8s filterchecks we retrieve the namespace from elsewhere in the response and - // add them as labels + // `parse_cri_labels`: The pod sandbox container does not contain the namespace etc as + // labels. To be consistent in the k8s filterchecks we retrieve the namespace from + // elsewhere in the response and add them as labels parse_cri_labels(resp_pod_sandbox_container, container); parse_cri_pod_sandbox_network(resp_pod_sandbox_container, root_pod_sandbox, container); parse_cri_pod_sandbox_labels(resp_pod_sandbox_container, container); return true; - } - else - { + } else { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cri (%s): id is neither a container nor a pod sandbox: %s", - container.m_id.c_str(), status.error_message().c_str()); + "cri (%s): id is neither a container nor a pod sandbox: %s", + container.m_id.c_str(), + status.error_message().c_str()); return false; } } - if(!container_status_resp.has_status()) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): ContainerStatusResponse call no status, returning", container.m_id.c_str()); + if(!container_status_resp.has_status()) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cri (%s): ContainerStatusResponse call no status, returning", + container.m_id.c_str()); ASSERT(false); return false; } @@ -796,11 +768,12 @@ inline bool cri_interface::parse(const libsinsp::cgroup_limits::cgroup_limi parse_cri_json_imageid(root_container, container); parse_cri_mounts(resp_container, container); parse_cri_env(root_container, container); - // In some cases (e.g. openshift), the cri-o response may not have an info property, which is used to set the container user. In those cases, the container name stays at its default "" value. + // In some cases (e.g. openshift), the cri-o response may not have an info property, which is + // used to set the container user. In those cases, the container name stays at its default + // "" value. parse_cri_user_info(root_container, container); bool ret = parse_cri_ext_container_info(root_container, container); - if(!ret) - { + if(!ret) { libsinsp::cgroup_limits::cgroup_limits_value limits; libsinsp::cgroup_limits::get_cgroup_resource_limits(key, limits); @@ -811,37 +784,43 @@ inline bool cri_interface::parse(const libsinsp::cgroup_limits::cgroup_limi container.m_cpuset_cpu_count = limits.m_cpuset_cpu_count; } - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cri (%s): after container parsing: repo=%s tag=%s image=%s digest=%s", - container.m_id.c_str(), container.m_imagerepo.c_str(), container.m_imagetag.c_str(), - container.m_image.c_str(), container.m_imagedigest.c_str()); + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "cri (%s): after container parsing: repo=%s tag=%s image=%s digest=%s", + container.m_id.c_str(), + container.m_imagerepo.c_str(), + container.m_imagetag.c_str(), + container.m_image.c_str(), + container.m_imagedigest.c_str()); // Enabled by default for Falco consumer - if(cri_settings::get_cri_extra_queries()) - { - if(container.m_imageid.empty()) - { + if(cri_settings::get_cri_extra_queries()) { + if(container.m_imageid.empty()) { // `get_container_image_id`: Makes new / extra API calls container.m_imageid = get_container_image_id(resp_container.image_ref()); - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cri (%s): after get_container_image_id: repo=%s tag=%s image=%s digest=%s", - container.m_id.c_str(), container.m_imagerepo.c_str(), - container.m_imagetag.c_str(), container.m_image.c_str(), - container.m_imagedigest.c_str()); + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "cri (%s): after get_container_image_id: repo=%s tag=%s image=%s digest=%s", + container.m_id.c_str(), + container.m_imagerepo.c_str(), + container.m_imagetag.c_str(), + container.m_image.c_str(), + container.m_imagedigest.c_str()); } /* - * The recent refactor makes full use of PodSandboxStatusResponse, removing the need to access pod sandbox containers - * in k8s filterchecks. Now, we also store the pod sandbox labels in the container. - * While this might seem redundant in cases where multiple containers exist in a pod, considering that the concurrent - * number of containers on a node is typically capped at 100-300 and many pods contain only 1-3 containers, - * it doesn't add significant overhead. Moreover, these extra lookups have always been performed for container ips in the past - * and therefore are no new additions. - */ + * The recent refactor makes full use of PodSandboxStatusResponse, removing the need to + * access pod sandbox containers in k8s filterchecks. Now, we also store the pod sandbox + * labels in the container. While this might seem redundant in cases where multiple + * containers exist in a pod, considering that the concurrent number of containers on a node + * is typically capped at 100-300 and many pods contain only 1-3 containers, it doesn't add + * significant overhead. Moreover, these extra lookups have always been performed for + * container ips in the past and therefore are no new additions. + */ typename api::PodSandboxStatusResponse pod_sandbox_status_resp; status = get_pod_sandbox_status_resp(container.m_pod_sandbox_id, pod_sandbox_status_resp); - if (!status.ok()) - { - // do not mark overall lookup as false only because the PodSandboxStatusResponse failed, + if(!status.ok()) { + // do not mark overall lookup as false only because the PodSandboxStatusResponse failed, // but previous ContainerStatusResponse succeeded return true; } @@ -855,5 +834,5 @@ inline bool cri_interface::parse(const libsinsp::cgroup_limits::cgroup_limi return true; } -} // namespace cri -} // namespace libsinsp +} // namespace cri +} // namespace libsinsp diff --git a/userspace/libsinsp/cri_settings.cpp b/userspace/libsinsp/cri_settings.cpp index 5e38087460..32abaa8e4a 100644 --- a/userspace/libsinsp/cri_settings.cpp +++ b/userspace/libsinsp/cri_settings.cpp @@ -18,33 +18,27 @@ limitations under the License. #include -namespace libsinsp -{ -namespace cri -{ +namespace libsinsp { +namespace cri { cri_settings::cri_settings(): - m_cri_unix_socket_paths(), - m_cri_timeout(1000), - m_cri_size_timeout(10000), - m_cri_runtime_type(CT_CRI), - m_cri_unix_socket_path(), - m_cri_extra_queries(true) -{ } + m_cri_unix_socket_paths(), + m_cri_timeout(1000), + m_cri_size_timeout(10000), + m_cri_runtime_type(CT_CRI), + m_cri_unix_socket_path(), + m_cri_extra_queries(true) {} -cri_settings::~cri_settings() -{ } +cri_settings::~cri_settings() {} std::unique_ptr cri_settings::s_instance = nullptr; -cri_settings& cri_settings::get() -{ - if(s_instance == nullptr) - { +cri_settings& cri_settings::get() { + if(s_instance == nullptr) { s_instance = std::make_unique(); } return *s_instance; } -} // namespace cri -} // namespace libsinsp +} // namespace cri +} // namespace libsinsp diff --git a/userspace/libsinsp/dns_manager.cpp b/userspace/libsinsp/dns_manager.cpp index 2f20b0067c..95771042ad 100644 --- a/userspace/libsinsp/dns_manager.cpp +++ b/userspace/libsinsp/dns_manager.cpp @@ -18,31 +18,26 @@ limitations under the License. #include -void sinsp_dns_resolver::refresh(uint64_t erase_timeout, uint64_t base_refresh_timeout, uint64_t max_refresh_timeout, std::future f_exit) -{ +void sinsp_dns_resolver::refresh(uint64_t erase_timeout, + uint64_t base_refresh_timeout, + uint64_t max_refresh_timeout, + std::future f_exit) { #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) sinsp_dns_manager &manager = sinsp_dns_manager::get(); - while(true) - { - if(!manager.m_cache.empty()) - { + while(true) { + if(!manager.m_cache.empty()) { std::list to_delete; uint64_t ts = sinsp_utils::get_current_time_ns(); - for(auto &it: manager.m_cache) - { + for(auto &it : manager.m_cache) { const std::string &name = it.first; sinsp_dns_manager::dns_info &info = it.second; - if((ts > info.m_last_used_ts) && - (ts - info.m_last_used_ts) > erase_timeout) - { + if((ts > info.m_last_used_ts) && (ts - info.m_last_used_ts) > erase_timeout) { // remove the entry if it's hasn't been used for a whole hour to_delete.push_back(name); - } - else if(ts > (info.m_last_resolve_ts + info.m_timeout)) - { + } else if(ts > (info.m_last_resolve_ts + info.m_timeout)) { sinsp_dns_manager::dns_info refreshed_info = manager.resolve(name, ts); refreshed_info.m_timeout = base_refresh_timeout; refreshed_info.m_last_resolve_ts = info.m_last_resolve_ts = ts; @@ -50,30 +45,25 @@ void sinsp_dns_resolver::refresh(uint64_t erase_timeout, uint64_t base_refresh_t // dns_info::operator!= will check if some // v4 or v6 addresses are changed from the // last resolution - if(refreshed_info != info) - { + if(refreshed_info != info) { info = refreshed_info; - } - else if(info.m_timeout < max_refresh_timeout) - { + } else if(info.m_timeout < max_refresh_timeout) { // double the timeout until 320 secs info.m_timeout <<= 1; } } } - if(!to_delete.empty()) - { + if(!to_delete.empty()) { manager.m_erase_mutex.lock(); - for(const auto &name : to_delete) - { + for(const auto &name : to_delete) { manager.m_cache.unsafe_erase(name); } manager.m_erase_mutex.unlock(); } } - if(f_exit.wait_for(std::chrono::nanoseconds(base_refresh_timeout)) == std::future_status::ready) - { + if(f_exit.wait_for(std::chrono::nanoseconds(base_refresh_timeout)) == + std::future_status::ready) { break; } } @@ -81,8 +71,8 @@ void sinsp_dns_resolver::refresh(uint64_t erase_timeout, uint64_t base_refresh_t } #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) -inline sinsp_dns_manager::dns_info sinsp_dns_manager::resolve(const std::string &name, uint64_t ts) -{ +inline sinsp_dns_manager::dns_info sinsp_dns_manager::resolve(const std::string &name, + uint64_t ts) { dns_info dinfo; addrinfo hints, *result, *rp; @@ -92,18 +82,14 @@ inline sinsp_dns_manager::dns_info sinsp_dns_manager::resolve(const std::string hints.ai_family = AF_UNSPEC; int s = getaddrinfo(name.c_str(), NULL, &hints, &result); - if (!s && result) - { - for (rp = result; rp != NULL; rp = rp->ai_next) - { - if(rp->ai_family == AF_INET) - { - dinfo.m_v4_addrs.insert(((sockaddr_in*)rp->ai_addr)->sin_addr.s_addr); - } - else // AF_INET6 + if(!s && result) { + for(rp = result; rp != NULL; rp = rp->ai_next) { + if(rp->ai_family == AF_INET) { + dinfo.m_v4_addrs.insert(((sockaddr_in *)rp->ai_addr)->sin_addr.s_addr); + } else // AF_INET6 { ipv6addr v6; - memcpy(v6.m_b, ((sockaddr_in6*)rp->ai_addr)->sin6_addr.s6_addr, sizeof(ipv6addr)); + memcpy(v6.m_b, ((sockaddr_in6 *)rp->ai_addr)->sin6_addr.s6_addr, sizeof(ipv6addr)); dinfo.m_v6_addrs.insert(v6); } } @@ -113,20 +99,21 @@ inline sinsp_dns_manager::dns_info sinsp_dns_manager::resolve(const std::string } #endif -bool sinsp_dns_manager::match(const char *name, int af, void *addr, uint64_t ts) -{ +bool sinsp_dns_manager::match(const char *name, int af, void *addr, uint64_t ts) { #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) - if(!m_resolver) - { - m_resolver = std::make_unique(sinsp_dns_resolver::refresh, m_erase_timeout, m_base_refresh_timeout, m_max_refresh_timeout, m_exit_signal.get_future()); + if(!m_resolver) { + m_resolver = std::make_unique(sinsp_dns_resolver::refresh, + m_erase_timeout, + m_base_refresh_timeout, + m_max_refresh_timeout, + m_exit_signal.get_future()); } std::string sname = std::string(name); m_erase_mutex.lock(); - if(m_cache.find(sname) == m_cache.end()) - { + if(m_cache.find(sname) == m_cache.end()) { dns_info dinfo = resolve(sname, ts); dinfo.m_timeout = m_base_refresh_timeout; dinfo.m_last_resolve_ts = ts; @@ -138,46 +125,37 @@ bool sinsp_dns_manager::match(const char *name, int af, void *addr, uint64_t ts) m_erase_mutex.unlock(); - if(af == AF_INET6) - { + if(af == AF_INET6) { ipv6addr v6; memcpy(v6.m_b, addr, sizeof(ipv6addr)); return dinfo.m_v6_addrs.find(v6) != dinfo.m_v6_addrs.end(); - } - else if(af == AF_INET) - { + } else if(af == AF_INET) { return dinfo.m_v4_addrs.find(*(uint32_t *)addr) != dinfo.m_v4_addrs.end(); } #endif return false; } -std::string sinsp_dns_manager::name_of(int af, void *addr, uint64_t ts) -{ +std::string sinsp_dns_manager::name_of(int af, void *addr, uint64_t ts) { std::string ret; #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) - if(!m_cache.empty()) - { + if(!m_cache.empty()) { m_erase_mutex.lock(); - for(auto &it: m_cache) - { + for(auto &it : m_cache) { const std::string &name = it.first; sinsp_dns_manager::dns_info &info = it.second; - if(af == AF_INET6) - { + if(af == AF_INET6) { ipv6addr v6; memcpy(v6.m_b, addr, sizeof(ipv6addr)); - if (info.m_v6_addrs.find(v6) != info.m_v6_addrs.end()) - { + if(info.m_v6_addrs.find(v6) != info.m_v6_addrs.end()) { info.m_last_used_ts = ts; ret = name; break; } - } - else if(af == AF_INET && info.m_v4_addrs.find(*(uint32_t *)addr) != info.m_v4_addrs.end()) - { + } else if(af == AF_INET && + info.m_v4_addrs.find(*(uint32_t *)addr) != info.m_v4_addrs.end()) { info.m_last_used_ts = ts; ret = name; break; @@ -189,10 +167,8 @@ std::string sinsp_dns_manager::name_of(int af, void *addr, uint64_t ts) return ret; } -void sinsp_dns_manager::cleanup() -{ - if(m_resolver) - { +void sinsp_dns_manager::cleanup() { + if(m_resolver) { m_exit_signal.set_value(); m_resolver->join(); m_resolver.reset(); diff --git a/userspace/libsinsp/dns_manager.h b/userspace/libsinsp/dns_manager.h index b03d8afab1..c8d3b91069 100644 --- a/userspace/libsinsp/dns_manager.h +++ b/userspace/libsinsp/dns_manager.h @@ -34,42 +34,30 @@ limitations under the License. #endif #include - -struct sinsp_dns_resolver -{ - static void refresh(uint64_t erase_timeout, uint64_t base_refresh_timeout, uint64_t max_refresh_timeout, std::future f_exit); +struct sinsp_dns_resolver { + static void refresh(uint64_t erase_timeout, + uint64_t base_refresh_timeout, + uint64_t max_refresh_timeout, + std::future f_exit); }; -class sinsp_dns_manager -{ +class sinsp_dns_manager { public: - bool match(const char *name, int af, void *addr, uint64_t ts); std::string name_of(int af, void *addr, uint64_t ts); void cleanup(); - static sinsp_dns_manager& get() - { + static sinsp_dns_manager &get() { static sinsp_dns_manager instance; return instance; }; - void set_erase_timeout(uint64_t ns) - { - m_erase_timeout = ns; - }; - void set_base_refresh_timeout(uint64_t ns) - { - m_base_refresh_timeout = ns; - }; - void set_max_refresh_timeout(uint64_t ns) - { - m_max_refresh_timeout = ns; - }; + void set_erase_timeout(uint64_t ns) { m_erase_timeout = ns; }; + void set_base_refresh_timeout(uint64_t ns) { m_base_refresh_timeout = ns; }; + void set_max_refresh_timeout(uint64_t ns) { m_max_refresh_timeout = ns; }; - size_t size() const - { + size_t size() const { #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) return m_cache.size(); #else @@ -78,31 +66,22 @@ class sinsp_dns_manager }; private: + sinsp_dns_manager(): + m_erase_timeout(3600 * ONE_SECOND_IN_NS), + m_base_refresh_timeout(10 * ONE_SECOND_IN_NS), + m_max_refresh_timeout(320 * ONE_SECOND_IN_NS) {}; - sinsp_dns_manager() : - m_erase_timeout(3600 * ONE_SECOND_IN_NS), - m_base_refresh_timeout(10 * ONE_SECOND_IN_NS), - m_max_refresh_timeout(320 * ONE_SECOND_IN_NS) - {}; - - ~sinsp_dns_manager() { - cleanup(); - } + ~sinsp_dns_manager() { cleanup(); } - sinsp_dns_manager(sinsp_dns_manager const&) = delete; - void operator=(sinsp_dns_manager const&) = delete; + sinsp_dns_manager(sinsp_dns_manager const &) = delete; + void operator=(sinsp_dns_manager const &) = delete; #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) - struct dns_info - { - bool operator==(const dns_info &other) const - { + struct dns_info { + bool operator==(const dns_info &other) const { return m_v4_addrs == other.m_v4_addrs && m_v6_addrs == other.m_v6_addrs; }; - bool operator!=(const dns_info &other) const - { - return !operator==(other); - }; + bool operator!=(const dns_info &other) const { return !operator==(other); }; uint64_t m_timeout; uint64_t m_last_resolve_ts; diff --git a/userspace/libsinsp/dumper.cpp b/userspace/libsinsp/dumper.cpp index 0bf0ce7c81..4bf467b4a9 100644 --- a/userspace/libsinsp/dumper.cpp +++ b/userspace/libsinsp/dumper.cpp @@ -21,49 +21,45 @@ limitations under the License. #include #include -sinsp_dumper::sinsp_dumper() -{ +sinsp_dumper::sinsp_dumper() { m_dumper = NULL; m_target_memory_buffer = NULL; m_target_memory_buffer_size = 0; m_nevts = 0; } -sinsp_dumper::sinsp_dumper(uint8_t* target_memory_buffer, uint64_t target_memory_buffer_size) -{ +sinsp_dumper::sinsp_dumper(uint8_t* target_memory_buffer, uint64_t target_memory_buffer_size) { m_dumper = NULL; m_target_memory_buffer = target_memory_buffer; m_target_memory_buffer_size = target_memory_buffer_size; } -sinsp_dumper::~sinsp_dumper() -{ - if(m_dumper != NULL) - { +sinsp_dumper::~sinsp_dumper() { + if(m_dumper != NULL) { scap_dump_close(m_dumper); } } -void sinsp_dumper::open(sinsp* inspector, const std::string& filename, bool compress) -{ +void sinsp_dumper::open(sinsp* inspector, const std::string& filename, bool compress) { char error[SCAP_LASTERR_SIZE]; - if(inspector->get_scap_handle() == NULL) - { + if(inspector->get_scap_handle() == NULL) { throw sinsp_exception("can't start event dump, inspector not opened yet"); } - if(m_target_memory_buffer) - { - m_dumper = scap_memory_dump_open(inspector->get_scap_platform(), m_target_memory_buffer, m_target_memory_buffer_size, error); - } - else - { + if(m_target_memory_buffer) { + m_dumper = scap_memory_dump_open(inspector->get_scap_platform(), + m_target_memory_buffer, + m_target_memory_buffer_size, + error); + } else { auto compress_mode = compress ? SCAP_COMPRESSION_GZIP : SCAP_COMPRESSION_NONE; - m_dumper = scap_dump_open(inspector->get_scap_platform(), filename.c_str(), compress_mode, error); + m_dumper = scap_dump_open(inspector->get_scap_platform(), + filename.c_str(), + compress_mode, + error); } - if(m_dumper == nullptr) - { + if(m_dumper == nullptr) { throw sinsp_exception(error); } @@ -74,19 +70,16 @@ void sinsp_dumper::open(sinsp* inspector, const std::string& filename, bool comp m_nevts = 0; } -void sinsp_dumper::fdopen(sinsp* inspector, int fd, bool compress) -{ +void sinsp_dumper::fdopen(sinsp* inspector, int fd, bool compress) { char error[SCAP_LASTERR_SIZE]; - if(inspector->get_scap_handle() == NULL) - { + if(inspector->get_scap_handle() == NULL) { throw sinsp_exception("can't start event dump, inspector not opened yet"); } auto compress_mode = compress ? SCAP_COMPRESSION_GZIP : SCAP_COMPRESSION_NONE; m_dumper = scap_dump_open_fd(inspector->get_scap_platform(), fd, compress_mode, true, error); - if(m_dumper == nullptr) - { + if(m_dumper == nullptr) { throw sinsp_exception(error); } @@ -97,29 +90,23 @@ void sinsp_dumper::fdopen(sinsp* inspector, int fd, bool compress) m_nevts = 0; } -void sinsp_dumper::close() -{ - if(m_dumper != NULL) - { +void sinsp_dumper::close() { + if(m_dumper != NULL) { scap_dump_close(m_dumper); m_dumper = NULL; } } -bool sinsp_dumper::is_open() const -{ +bool sinsp_dumper::is_open() const { return (m_dumper != NULL); } -bool sinsp_dumper::written_events() const -{ +bool sinsp_dumper::written_events() const { return m_nevts; } -void sinsp_dumper::dump(sinsp_evt* evt) -{ - if(m_dumper == NULL) - { +void sinsp_dumper::dump(sinsp_evt* evt) { + if(m_dumper == NULL) { throw sinsp_exception("dumper not opened yet"); } @@ -128,57 +115,47 @@ void sinsp_dumper::dump(sinsp_evt* evt) scap_dump_flags dflags; dflags = evt->get_dump_flags(&do_drop); - if(do_drop) - { + if(do_drop) { return; } int32_t res = scap_dump(m_dumper, pdevt, evt->get_cpuid(), dflags); - if(res != SCAP_SUCCESS) - { + if(res != SCAP_SUCCESS) { throw sinsp_exception(scap_dump_getlasterr(m_dumper)); } m_nevts++; } -uint64_t sinsp_dumper::written_bytes() const -{ - if(m_dumper == NULL) - { +uint64_t sinsp_dumper::written_bytes() const { + if(m_dumper == NULL) { return 0; } int64_t written_bytes = scap_dump_get_offset(m_dumper); - if(written_bytes == -1) - { + if(written_bytes == -1) { throw sinsp_exception("error getting offset"); } return written_bytes; } -uint64_t sinsp_dumper::next_write_position() const -{ - if(m_dumper == NULL) - { +uint64_t sinsp_dumper::next_write_position() const { + if(m_dumper == NULL) { return 0; } int64_t position = scap_dump_ftell(m_dumper); - if(position == -1) - { + if(position == -1) { throw sinsp_exception("error getting offset"); } return position; } -void sinsp_dumper::flush() -{ - if(m_dumper == NULL) - { +void sinsp_dumper::flush() { + if(m_dumper == NULL) { throw sinsp_exception("dumper not opened yet"); } diff --git a/userspace/libsinsp/dumper.h b/userspace/libsinsp/dumper.h index a7927f94b9..e302cd709c 100644 --- a/userspace/libsinsp/dumper.h +++ b/userspace/libsinsp/dumper.h @@ -35,8 +35,7 @@ typedef struct scap_dumper scap_dumper_t; /*! \brief A support class to dump events to file in scap format. */ -class SINSP_PUBLIC sinsp_dumper -{ +class SINSP_PUBLIC sinsp_dumper { public: /*! \brief Constructs the dumper. @@ -48,8 +47,7 @@ class SINSP_PUBLIC sinsp_dumper Takes the address and the size of a preallocated memory buffer where the data will go. */ - sinsp_dumper(uint8_t* target_memory_buffer, - uint64_t target_memory_buffer_size); + sinsp_dumper(uint8_t* target_memory_buffer, uint64_t target_memory_buffer_size); ~sinsp_dumper(); @@ -99,8 +97,8 @@ class SINSP_PUBLIC sinsp_dumper /*! \brief Return the starting position for the next write into - the file. (Under the covers, this uses gztell while - written_bytes uses gzoffset, which represent different values). + the file. (Under the covers, this uses gztell while + written_bytes uses gzoffset, which represent different values). \return The starting position for the next write. */ @@ -118,15 +116,9 @@ class SINSP_PUBLIC sinsp_dumper */ void dump(sinsp_evt* evt); - inline uint8_t* get_memory_dump_cur_buf() - { - return scap_get_memorydumper_curpos(m_dumper); - } + inline uint8_t* get_memory_dump_cur_buf() { return scap_get_memorydumper_curpos(m_dumper); } - inline void set_inspector(sinsp *inspector) - { - m_inspector = inspector; - } + inline void set_inspector(sinsp* inspector) { m_inspector = inspector; } private: sinsp* m_inspector; diff --git a/userspace/libsinsp/event.cpp b/userspace/libsinsp/event.cpp index 303227ec94..d65565ff74 100644 --- a/userspace/libsinsp/event.cpp +++ b/userspace/libsinsp/event.cpp @@ -43,118 +43,94 @@ limitations under the License. extern sinsp_evttables g_infotables; -#define SET_NUMERIC_FORMAT(resfmt, fmt, ostr, ustr, xstr) do { \ - if(fmt == ppm_print_format::PF_OCT) \ - { \ - resfmt = (char*)"%#" ostr; \ - } \ - else if(fmt == ppm_print_format::PF_DEC) \ - { \ - resfmt = (char*)"%" ustr; \ - } \ - else if(fmt == ppm_print_format::PF_10_PADDED_DEC) \ - { \ - resfmt = (char*)"%09" ustr; \ - } \ - else if(fmt == ppm_print_format::PF_HEX) \ - { \ - resfmt = (char*)"%" xstr; \ - } \ - else \ - { \ - resfmt = (char*)"%" ustr; \ - } \ -} while(0) +#define SET_NUMERIC_FORMAT(resfmt, fmt, ostr, ustr, xstr) \ + do { \ + if(fmt == ppm_print_format::PF_OCT) { \ + resfmt = (char *)"%#" ostr; \ + } else if(fmt == ppm_print_format::PF_DEC) { \ + resfmt = (char *)"%" ustr; \ + } else if(fmt == ppm_print_format::PF_10_PADDED_DEC) { \ + resfmt = (char *)"%09" ustr; \ + } else if(fmt == ppm_print_format::PF_HEX) { \ + resfmt = (char *)"%" xstr; \ + } else { \ + resfmt = (char *)"%" ustr; \ + } \ + } while(0) /////////////////////////////////////////////////////////////////////////////// // sinsp_evt implementation /////////////////////////////////////////////////////////////////////////////// -sinsp_evt::sinsp_evt() : - m_inspector(NULL), - m_pevt(NULL), - m_pevt_storage(NULL), - m_cpuid(0), - m_evtnum(0), - m_flags(EF_NONE), - m_params_loaded(false), - m_info(NULL), - m_paramstr_storage(1024), - m_resolved_paramstr_storage(1024), - m_tinfo(NULL), - m_fdinfo(NULL), - m_fdinfo_name_changed(false), - m_iosize(0), - m_errorcode(0), - m_rawbuf_str_len(0), - m_filtered_out(false), - m_event_info_table(g_infotables.m_event_info) -{ - -} - -sinsp_evt::sinsp_evt(sinsp *inspector) : - m_inspector(inspector), - m_pevt(NULL), - m_pevt_storage(NULL), - m_cpuid(0), - m_evtnum(0), - m_flags(EF_NONE), - m_params_loaded(false), - m_info(NULL), - m_paramstr_storage(1024), - m_resolved_paramstr_storage(1024), - m_tinfo(NULL), - m_fdinfo(NULL), - m_fdinfo_name_changed(false), - m_iosize(0), - m_errorcode(0), - m_rawbuf_str_len(0), - m_filtered_out(false), - m_event_info_table(g_infotables.m_event_info) -{ -} - -sinsp_evt::~sinsp_evt() -{ - if(m_pevt_storage) - { +sinsp_evt::sinsp_evt(): + m_inspector(NULL), + m_pevt(NULL), + m_pevt_storage(NULL), + m_cpuid(0), + m_evtnum(0), + m_flags(EF_NONE), + m_params_loaded(false), + m_info(NULL), + m_paramstr_storage(1024), + m_resolved_paramstr_storage(1024), + m_tinfo(NULL), + m_fdinfo(NULL), + m_fdinfo_name_changed(false), + m_iosize(0), + m_errorcode(0), + m_rawbuf_str_len(0), + m_filtered_out(false), + m_event_info_table(g_infotables.m_event_info) {} + +sinsp_evt::sinsp_evt(sinsp *inspector): + m_inspector(inspector), + m_pevt(NULL), + m_pevt_storage(NULL), + m_cpuid(0), + m_evtnum(0), + m_flags(EF_NONE), + m_params_loaded(false), + m_info(NULL), + m_paramstr_storage(1024), + m_resolved_paramstr_storage(1024), + m_tinfo(NULL), + m_fdinfo(NULL), + m_fdinfo_name_changed(false), + m_iosize(0), + m_errorcode(0), + m_rawbuf_str_len(0), + m_filtered_out(false), + m_event_info_table(g_infotables.m_event_info) {} + +sinsp_evt::~sinsp_evt() { + if(m_pevt_storage) { delete[] m_pevt_storage; } } -const char *sinsp_evt::get_name() const -{ +const char *sinsp_evt::get_name() const { return m_info->name; } -event_direction sinsp_evt::get_direction() const -{ +event_direction sinsp_evt::get_direction() const { return (event_direction)(m_pevt->type & PPME_DIRECTION_FLAG); } -int64_t sinsp_evt::get_tid() const -{ +int64_t sinsp_evt::get_tid() const { return m_pevt->tid; } -void sinsp_evt::set_iosize(uint32_t size) -{ +void sinsp_evt::set_iosize(uint32_t size) { m_iosize = size; } -uint32_t sinsp_evt::get_iosize() const -{ +uint32_t sinsp_evt::get_iosize() const { return m_iosize; } -sinsp_threadinfo* sinsp_evt::get_thread_info(bool query_os_if_not_found) -{ - if(NULL != m_tinfo) - { +sinsp_threadinfo *sinsp_evt::get_thread_info(bool query_os_if_not_found) { + if(NULL != m_tinfo) { return m_tinfo; - } - else if(m_tinfo_ref) - { + } else if(m_tinfo_ref) { m_tinfo = m_tinfo_ref.get(); return m_tinfo; @@ -163,23 +139,16 @@ sinsp_threadinfo* sinsp_evt::get_thread_info(bool query_os_if_not_found) return m_inspector->get_thread_ref(m_pevt->tid, query_os_if_not_found, false).get(); } -int64_t sinsp_evt::get_fd_num() const -{ - if(m_fdinfo) - { +int64_t sinsp_evt::get_fd_num() const { + if(m_fdinfo) { return m_tinfo->m_lastevent_fd; - } - else - { + } else { return sinsp_evt::INVALID_FD_NUM; } } - -uint32_t sinsp_evt::get_num_params() -{ - if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) - { +uint32_t sinsp_evt::get_num_params() { + if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) { load_params(); m_flags |= (uint32_t)sinsp_evt::SINSP_EF_PARAMS_LOADED; } @@ -187,10 +156,8 @@ uint32_t sinsp_evt::get_num_params() return (uint32_t)m_params.size(); } -const sinsp_evt_param *sinsp_evt::get_param(uint32_t id) -{ - if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) - { +const sinsp_evt_param *sinsp_evt::get_param(uint32_t id) { + if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) { load_params(); m_flags |= (uint32_t)sinsp_evt::SINSP_EF_PARAMS_LOADED; } @@ -198,13 +165,11 @@ const sinsp_evt_param *sinsp_evt::get_param(uint32_t id) return &(m_params.at(id)); } -const sinsp_evt_param* sinsp_evt::get_param_by_name(const char* name) -{ +const sinsp_evt_param *sinsp_evt::get_param_by_name(const char *name) { // // Make sure the params are actually loaded // - if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) - { + if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) { load_params(); m_flags |= (uint32_t)sinsp_evt::SINSP_EF_PARAMS_LOADED; } @@ -214,10 +179,8 @@ const sinsp_evt_param* sinsp_evt::get_param_by_name(const char* name) // uint32_t np = get_num_params(); - for(uint32_t j = 0; j < np; j++) - { - if(strcmp(name, get_param_name(j)) == 0) - { + for(uint32_t j = 0; j < np; j++) { + if(strcmp(name, get_param_name(j)) == 0) { return &(m_params[j]); } } @@ -225,10 +188,8 @@ const sinsp_evt_param* sinsp_evt::get_param_by_name(const char* name) return NULL; } -const char *sinsp_evt::get_param_name(uint32_t id) -{ - if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) - { +const char *sinsp_evt::get_param_name(uint32_t id) { + if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) { load_params(); m_flags |= (uint32_t)sinsp_evt::SINSP_EF_PARAMS_LOADED; } @@ -238,10 +199,8 @@ const char *sinsp_evt::get_param_name(uint32_t id) return m_info->params[id].name; } -const ppm_param_info* sinsp_evt::get_param_info(uint32_t id) -{ - if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) - { +const ppm_param_info *sinsp_evt::get_param_info(uint32_t id) { + if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) { load_params(); m_flags |= (uint32_t)sinsp_evt::SINSP_EF_PARAMS_LOADED; } @@ -251,8 +210,11 @@ const ppm_param_info* sinsp_evt::get_param_info(uint32_t id) return &(m_info->params[id]); } -static uint32_t binary_buffer_to_hex_string(char *dst, const char *src, uint32_t dstlen, uint32_t srclen, sinsp_evt::param_fmt fmt) -{ +static uint32_t binary_buffer_to_hex_string(char *dst, + const char *src, + uint32_t dstlen, + uint32_t srclen, + sinsp_evt::param_fmt fmt) { uint32_t j; uint32_t k; uint32_t l = 0; @@ -262,28 +224,22 @@ static uint32_t binary_buffer_to_hex_string(char *dst, const char *src, uint32_t const char *ptr; bool truncated = false; - for(j = 0; j < srclen; j += 8 * sizeof(uint16_t)) - { + for(j = 0; j < srclen; j += 8 * sizeof(uint16_t)) { k = 0; k += snprintf(row + k, sizeof(row) - k, "\n\t0x%.4x:", j); ptr = &src[j]; num_chunks = 0; - while(num_chunks < 8 && ptr < src + srclen) - { - uint16_t chunk = htons(*(uint16_t*)ptr); + while(num_chunks < 8 && ptr < src + srclen) { + uint16_t chunk = htons(*(uint16_t *)ptr); int ret; - if(ptr == src + srclen - 1) - { - ret = snprintf(row + k, sizeof(row) - k, " %.2x", *(((uint8_t*)&chunk) + 1)); - } - else - { + if(ptr == src + srclen - 1) { + ret = snprintf(row + k, sizeof(row) - k, " %.2x", *(((uint8_t *)&chunk) + 1)); + } else { ret = snprintf(row + k, sizeof(row) - k, " %.4x", chunk); } - if (ret < 0 || (unsigned int)ret >= sizeof(row) - k) - { + if(ret < 0 || (unsigned int)ret >= sizeof(row) - k) { dst[0] = 0; return 0; } @@ -293,11 +249,9 @@ static uint32_t binary_buffer_to_hex_string(char *dst, const char *src, uint32_t ptr += sizeof(uint16_t); } - if((fmt & sinsp_evt::PF_HEXASCII) || (fmt & sinsp_evt::PF_JSONHEXASCII)) - { + if((fmt & sinsp_evt::PF_HEXASCII) || (fmt & sinsp_evt::PF_JSONHEXASCII)) { // Fill the row with spaces to align it to other rows - while(num_chunks < 8) - { + while(num_chunks < 8) { memset(row + k, ' ', 5); k += 5; @@ -307,16 +261,11 @@ static uint32_t binary_buffer_to_hex_string(char *dst, const char *src, uint32_t row[k++] = ' '; row[k++] = ' '; - for(ptr = &src[j]; - ptr < src + j + 8 * sizeof(uint16_t) && ptr < src + srclen; - ptr++, k++) - { - if(isprint((int)(uint8_t)*ptr)) - { + for(ptr = &src[j]; ptr < src + j + 8 * sizeof(uint16_t) && ptr < src + srclen; + ptr++, k++) { + if(isprint((int)(uint8_t)*ptr)) { row[k] = *ptr; - } - else - { + } else { row[k] = '.'; } } @@ -324,8 +273,7 @@ static uint32_t binary_buffer_to_hex_string(char *dst, const char *src, uint32_t row[k] = 0; row_len = (uint32_t)strlen(row); - if(l + row_len >= dstlen - 1) - { + if(l + row_len >= dstlen - 1) { truncated = true; break; } @@ -335,41 +283,37 @@ static uint32_t binary_buffer_to_hex_string(char *dst, const char *src, uint32_t dst[l++] = '\n'; - if(truncated) - { + if(truncated) { return dstlen; - } - else - { + } else { return l; } } -static uint32_t binary_buffer_to_asciionly_string(char *dst, const char *src, uint32_t dstlen, uint32_t srclen, sinsp_evt::param_fmt fmt) -{ +static uint32_t binary_buffer_to_asciionly_string(char *dst, + const char *src, + uint32_t dstlen, + uint32_t srclen, + sinsp_evt::param_fmt fmt) { uint32_t j; uint32_t k = 0; - if(fmt != sinsp_evt::PF_EOLS_COMPACT) - { + if(fmt != sinsp_evt::PF_EOLS_COMPACT) { dst[k++] = '\n'; } - for(j = 0; j < srclen; j++) - { + for(j = 0; j < srclen; j++) { // // Make sure there's enough space in the target buffer. // Note that we reserve two bytes, because some characters are expanded // when copied. // - if(k >= dstlen - 1) - { + if(k >= dstlen - 1) { dst[k - 1] = 0; return dstlen; } - if(isprint((int)(uint8_t)src[j])) - { + if(isprint((int)(uint8_t)src[j])) { // switch(src[j]) // { // case '"': @@ -382,46 +326,40 @@ static uint32_t binary_buffer_to_asciionly_string(char *dst, const char *src, ui dst[k] = src[j]; k++; - } - else if(src[j] == '\r') - { + } else if(src[j] == '\r') { dst[k] = '\n'; k++; - } - else if(src[j] == '\n') - { - if(j > 0 && src[j - 1] != '\r') - { + } else if(src[j] == '\n') { + if(j > 0 && src[j - 1] != '\r') { dst[k] = src[j]; k++; } } - } return k; } -static uint32_t binary_buffer_to_string_dots(char *dst, const char *src, uint32_t dstlen, uint32_t srclen, sinsp_evt::param_fmt fmt) -{ +static uint32_t binary_buffer_to_string_dots(char *dst, + const char *src, + uint32_t dstlen, + uint32_t srclen, + sinsp_evt::param_fmt fmt) { uint32_t j; uint32_t k = 0; - for(j = 0; j < srclen; j++) - { + for(j = 0; j < srclen; j++) { // // Make sure there's enough space in the target buffer. // Note that we reserve two bytes, because some characters are expanded // when copied. // - if(k >= dstlen - 1) - { + if(k >= dstlen - 1) { dst[k - 1] = 0; return dstlen; } - if(isprint((int)(uint8_t)src[j])) - { + if(isprint((int)(uint8_t)src[j])) { // switch(src[j]) // { // case '"': @@ -433,9 +371,7 @@ static uint32_t binary_buffer_to_string_dots(char *dst, const char *src, uint32_ // } dst[k] = src[j]; - } - else - { + } else { dst[k] = '.'; } @@ -445,35 +381,33 @@ static uint32_t binary_buffer_to_string_dots(char *dst, const char *src, uint32_ return k; } -static uint32_t binary_buffer_to_base64_string(char *dst, const char *src, uint32_t dstlen, uint32_t srclen, sinsp_evt::param_fmt fmt) -{ +static uint32_t binary_buffer_to_base64_string(char *dst, + const char *src, + uint32_t dstlen, + uint32_t srclen, + sinsp_evt::param_fmt fmt) { // // base64 encoder, malloc-free version of: // http://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c // - static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', - 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', - 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', - '4', '5', '6', '7', '8', '9', '+', '/'}; + static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static uint32_t mod_table[] = {0, 2, 1}; - uint32_t j,k, enc_dstlen; + uint32_t j, k, enc_dstlen; enc_dstlen = 4 * ((srclen + 2) / 3); // // Make sure there's enough space in the target buffer. // - if(enc_dstlen >= dstlen - 1) - { + if(enc_dstlen >= dstlen - 1) { return dstlen; } - for (j = 0, k = 0; j < srclen;) { - + for(j = 0, k = 0; j < srclen;) { uint32_t octet_a = j < srclen ? (unsigned char)src[j++] : 0; uint32_t octet_b = j < srclen ? (unsigned char)src[j++] : 0; uint32_t octet_c = j < srclen ? (unsigned char)src[j++] : 0; @@ -486,69 +420,63 @@ static uint32_t binary_buffer_to_base64_string(char *dst, const char *src, uint3 dst[k++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } - for (j = 0; j < mod_table[srclen % 3]; j++) + for(j = 0; j < mod_table[srclen % 3]; j++) dst[enc_dstlen - 1 - j] = '='; return enc_dstlen; } -static uint32_t binary_buffer_to_json_string(char *dst, const char *src, uint32_t dstlen, uint32_t srclen, sinsp_evt::param_fmt fmt) -{ +static uint32_t binary_buffer_to_json_string(char *dst, + const char *src, + uint32_t dstlen, + uint32_t srclen, + sinsp_evt::param_fmt fmt) { uint32_t k = 0; - switch(fmt) - { - case sinsp_evt::PF_JSONHEX: - case sinsp_evt::PF_JSONHEXASCII: - k = binary_buffer_to_hex_string(dst, src, dstlen, srclen, fmt); - break; - case sinsp_evt::PF_JSONEOLS: - k = binary_buffer_to_asciionly_string(dst, src, dstlen, srclen, fmt); - break; - case sinsp_evt::PF_JSONBASE64: - k = binary_buffer_to_base64_string(dst, src, dstlen, srclen, fmt); - break; - default: - k = binary_buffer_to_string_dots(dst, src, dstlen, srclen, fmt); + switch(fmt) { + case sinsp_evt::PF_JSONHEX: + case sinsp_evt::PF_JSONHEXASCII: + k = binary_buffer_to_hex_string(dst, src, dstlen, srclen, fmt); + break; + case sinsp_evt::PF_JSONEOLS: + k = binary_buffer_to_asciionly_string(dst, src, dstlen, srclen, fmt); + break; + case sinsp_evt::PF_JSONBASE64: + k = binary_buffer_to_base64_string(dst, src, dstlen, srclen, fmt); + break; + default: + k = binary_buffer_to_string_dots(dst, src, dstlen, srclen, fmt); } return k; } -uint32_t binary_buffer_to_string(char *dst, const char *src, uint32_t dstlen, uint32_t srclen, sinsp_evt::param_fmt fmt) -{ +uint32_t binary_buffer_to_string(char *dst, + const char *src, + uint32_t dstlen, + uint32_t srclen, + sinsp_evt::param_fmt fmt) { uint32_t k = 0; - if(dstlen == 0) - { + if(dstlen == 0) { ASSERT(false); return 0; } - if(srclen == 0) - { + if(srclen == 0) { *dst = 0; return 0; } - if(fmt & sinsp_evt::PF_HEX || fmt & sinsp_evt::PF_HEXASCII) - { + if(fmt & sinsp_evt::PF_HEX || fmt & sinsp_evt::PF_HEXASCII) { k = binary_buffer_to_hex_string(dst, src, dstlen, srclen, fmt); - } - else if(fmt & sinsp_evt::PF_BASE64) - { + } else if(fmt & sinsp_evt::PF_BASE64) { k = binary_buffer_to_base64_string(dst, src, dstlen, srclen, fmt); - } - else if(fmt & sinsp_evt::PF_JSON || fmt & sinsp_evt::PF_JSONHEX - || fmt & sinsp_evt::PF_JSONEOLS || fmt & sinsp_evt::PF_JSONHEXASCII - || fmt & sinsp_evt::PF_JSONBASE64) - { + } else if(fmt & sinsp_evt::PF_JSON || fmt & sinsp_evt::PF_JSONHEX || + fmt & sinsp_evt::PF_JSONEOLS || fmt & sinsp_evt::PF_JSONHEXASCII || + fmt & sinsp_evt::PF_JSONBASE64) { k = binary_buffer_to_json_string(dst, src, dstlen, srclen, fmt); - } - else if(fmt & (sinsp_evt::PF_EOLS | sinsp_evt::PF_EOLS_COMPACT)) - { + } else if(fmt & (sinsp_evt::PF_EOLS | sinsp_evt::PF_EOLS_COMPACT)) { k = binary_buffer_to_asciionly_string(dst, src, dstlen, srclen, fmt); - } - else - { + } else { k = binary_buffer_to_string_dots(dst, src, dstlen, srclen, fmt); } @@ -556,23 +484,19 @@ uint32_t binary_buffer_to_string(char *dst, const char *src, uint32_t dstlen, ui return k; } -static uint32_t strcpy_sanitized(char *dest, const char *src, uint32_t dstsize) -{ - volatile char* tmp = (volatile char *)dest; +static uint32_t strcpy_sanitized(char *dest, const char *src, uint32_t dstsize) { + volatile char *tmp = (volatile char *)dest; uint32_t j = 0; g_invalidchar ic; - while(j < dstsize) - { - if(!ic(*src)) - { + while(j < dstsize) { + if(!ic(*src)) { *tmp = *src; tmp++; j++; } - if(*src == 0) - { + if(*src == 0) { *tmp = 0; return j + 1; } @@ -583,39 +507,33 @@ static uint32_t strcpy_sanitized(char *dest, const char *src, uint32_t dstsize) // // In case there wasn't enough space, null-terminate the destination // - if(dstsize) - { + if(dstsize) { dest[dstsize - 1] = 0; } return dstsize; } -int sinsp_evt::render_fd_json(Json::Value *ret, int64_t fd, const char** resolved_str, sinsp_evt::param_fmt fmt) -{ - sinsp_threadinfo* tinfo = get_thread_info(); - if(tinfo == NULL) - { +int sinsp_evt::render_fd_json(Json::Value *ret, + int64_t fd, + const char **resolved_str, + sinsp_evt::param_fmt fmt) { + sinsp_threadinfo *tinfo = get_thread_info(); + if(tinfo == NULL) { return 0; } - if(fd >= 0) - { + if(fd >= 0) { sinsp_fdinfo *fdinfo = tinfo->get_fd(fd); - if(fdinfo) - { + if(fdinfo) { char tch = fdinfo->get_typechar(); char ipprotoch = 0; - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK || - fdinfo->m_type == SCAP_FD_IPV6_SOCK || - fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || - fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) - { + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK || fdinfo->m_type == SCAP_FD_IPV6_SOCK || + fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) { scap_l4_proto l4p = fdinfo->get_l4proto(); - switch(l4p) - { + switch(l4p) { case SCAP_L4_TCP: ipprotoch = 't'; break; @@ -633,12 +551,7 @@ int sinsp_evt::render_fd_json(Json::Value *ret, int64_t fd, const char** resolve } } - char typestr[3] = - { - (fmt & PF_SIMPLE)?(char)0:tch, - ipprotoch, - 0 - }; + char typestr[3] = {(fmt & PF_SIMPLE) ? (char)0 : tch, ipprotoch, 0}; // // Make sure we remove invalid characters from the resolved name @@ -650,22 +563,17 @@ int sinsp_evt::render_fd_json(Json::Value *ret, int64_t fd, const char** resolve (*ret)["typechar"] = typestr; (*ret)["name"] = sanitized_str; } - } - else if(fd == PPM_AT_FDCWD) - { + } else if(fd == PPM_AT_FDCWD) { // // `fd` can be AT_FDCWD on all *at syscalls // (*ret)["name"] = "AT_FDCWD"; - } - else - { + } else { // // Resolve this as an errno // std::string errstr(sinsp_utils::errno_to_str((int32_t)fd)); - if(errstr != "") - { + if(errstr != "") { (*ret)["error"] = errstr; return 0; } @@ -674,41 +582,31 @@ int sinsp_evt::render_fd_json(Json::Value *ret, int64_t fd, const char** resolve return 1; } -char* sinsp_evt::render_fd(int64_t fd, const char** resolved_str, sinsp_evt::param_fmt fmt) -{ +char *sinsp_evt::render_fd(int64_t fd, const char **resolved_str, sinsp_evt::param_fmt fmt) { // // Add the fd number // - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRId64, fd); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%" PRId64, fd); - sinsp_threadinfo* tinfo = get_thread_info(); - if(tinfo == NULL) - { + sinsp_threadinfo *tinfo = get_thread_info(); + if(tinfo == NULL) { // // no thread. Definitely can't resolve the fd, just return the number // return &m_paramstr_storage[0]; } - if(fd >= 0) - { + if(fd >= 0) { sinsp_fdinfo *fdinfo = tinfo->get_fd(fd); - if(fdinfo) - { + if(fdinfo) { char tch = fdinfo->get_typechar(); char ipprotoch = 0; - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK || - fdinfo->m_type == SCAP_FD_IPV6_SOCK || - fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || - fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) - { + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK || fdinfo->m_type == SCAP_FD_IPV6_SOCK || + fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) { scap_l4_proto l4p = fdinfo->get_l4proto(); - switch(l4p) - { + switch(l4p) { case SCAP_L4_TCP: ipprotoch = 't'; break; @@ -726,12 +624,7 @@ char* sinsp_evt::render_fd(int64_t fd, const char** resolved_str, sinsp_evt::par } } - char typestr[3] = - { - (fmt & PF_SIMPLE)?(char)0:tch, - ipprotoch, - 0 - }; + char typestr[3] = {(fmt & PF_SIMPLE) ? (char)0 : tch, ipprotoch, 0}; // // Make sure we remove invalid characters from the resolved name @@ -743,82 +636,71 @@ char* sinsp_evt::render_fd(int64_t fd, const char** resolved_str, sinsp_evt::par // // Make sure the string will fit // - if(sanitized_str.size() >= m_resolved_paramstr_storage.size()) - { + if(sanitized_str.size() >= m_resolved_paramstr_storage.size()) { m_resolved_paramstr_storage.resize(sanitized_str.size() + 1); } snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - "<%s>%s", typestr, sanitized_str.c_str()); + m_resolved_paramstr_storage.size(), + "<%s>%s", + typestr, + sanitized_str.c_str()); } - } - else if(fd == PPM_AT_FDCWD) - { + } else if(fd == PPM_AT_FDCWD) { // // `fd` can be AT_FDCWD on all *at syscalls // - snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - "AT_FDCWD"); - } - else - { + snprintf(&m_resolved_paramstr_storage[0], m_resolved_paramstr_storage.size(), "AT_FDCWD"); + } else { // // Resolve this as an errno // std::string errstr(sinsp_utils::errno_to_str((int32_t)fd)); - if(errstr != "") - { + if(errstr != "") { snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - "%s", errstr.c_str()); + m_resolved_paramstr_storage.size(), + "%s", + errstr.c_str()); } } return &m_paramstr_storage[0]; } -std::string sinsp_evt::get_base_dir(uint32_t id, sinsp_threadinfo *tinfo) -{ +std::string sinsp_evt::get_base_dir(uint32_t id, sinsp_threadinfo *tinfo) { std::string cwd = tinfo->get_cwd(); - const ppm_param_info* param_info = &m_info->params[id]; + const ppm_param_info *param_info = &m_info->params[id]; // If it's a regular FSPATH, just return the thread's CWD - if (param_info->type != PT_FSRELPATH) - { + if(param_info->type != PT_FSRELPATH) { ASSERT(param_info->type == PT_FSPATH); return cwd; } uint64_t dirfd_id = (uint64_t)param_info->info; - if (dirfd_id >= m_info->nparams) - { + if(dirfd_id >= m_info->nparams) { ASSERT(dirfd_id < m_info->nparams); return cwd; } - const ppm_param_info* dir_param_info = &(m_info->params[dirfd_id]); + const ppm_param_info *dir_param_info = &(m_info->params[dirfd_id]); // Ensure the index points to an actual FD - if (dir_param_info->type != PT_FD) - { + if(dir_param_info->type != PT_FD) { return cwd; } const int64_t dirfd = get_param(dirfd_id)->as(); // If the FD is special value PPM_AT_FDCWD, just use CWD - if (dirfd == PPM_AT_FDCWD) - { + if(dirfd == PPM_AT_FDCWD) { return cwd; } // If the previous param is a fd with a value other than AT_FDCWD, // get the path to that fd and use it in place of CWD std::string rel_path_base = tinfo->get_path_for_dir_fd(dirfd); - if (rel_path_base.empty()) - { + if(rel_path_base.empty()) { return rel_path_base; } sanitize_string(rel_path_base); @@ -826,10 +708,11 @@ std::string sinsp_evt::get_base_dir(uint32_t id, sinsp_threadinfo *tinfo) return rel_path_base; } -const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, sinsp_evt::param_fmt fmt) -{ - char* prfmt = NULL; - const ppm_param_info* param_info = NULL; +const char *sinsp_evt::get_param_as_str(uint32_t id, + const char **resolved_str, + sinsp_evt::param_fmt fmt) { + char *prfmt = NULL; + const ppm_param_info *param_info = NULL; std::optional dyn_param; std::string_view s; uint8_t sockfamily; @@ -838,8 +721,7 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, // // Make sure the params are actually loaded // - if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) - { + if((m_flags & sinsp_evt::SINSP_EF_PARAMS_LOADED) == 0) { load_params(); m_flags |= (uint32_t)sinsp_evt::SINSP_EF_PARAMS_LOADED; } @@ -857,8 +739,7 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, const sinsp_evt_param *param = get_param(id); param_info = param->get_info(); - if(param->m_len == 0) - { + if(param->m_len == 0) { snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "NULL"); *resolved_str = &m_resolved_paramstr_storage[0]; return &m_paramstr_storage[0]; @@ -867,16 +748,17 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, // // Get the parameter information // - if(param_info->type == PT_DYN && param_info->info != NULL) - { + if(param_info->type == PT_DYN && param_info->info != NULL) { uint8_t dyn_idx = 0; memcpy(&dyn_idx, param->m_val, sizeof(uint8_t)); if(dyn_idx < param_info->ninfo) { - auto dyn_params = (const ppm_param_info*)param_info->info; + auto dyn_params = (const ppm_param_info *)param_info->info; - dyn_param = sinsp_evt_param(param->m_evt, param->m_idx, - param->m_val + sizeof(uint8_t), param->m_len - sizeof(uint8_t)); + dyn_param = sinsp_evt_param(param->m_evt, + param->m_idx, + param->m_val + sizeof(uint8_t), + param->m_len - sizeof(uint8_t)); param = std::addressof(*dyn_param); param_info = &dyn_params[dyn_idx]; @@ -885,121 +767,96 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, ppm_print_format param_fmt = m_info->params[id].fmt; - switch(param_info->type) - { + switch(param_info->type) { case PT_INT8: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo8, PRId8, PRIX8); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; case PT_INT16: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo16, PRId16, PRIX16); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; case PT_INT32: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo32, PRId32, PRIX32); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; case PT_INT64: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo64, PRId64, PRIX64); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; - case PT_FD: - { - int64_t fd = param->as(); - render_fd(fd, resolved_str, fmt); - break; - } - case PT_PID: - { - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRId64, param->as()); - - sinsp_threadinfo* atinfo = m_inspector->get_thread_ref(param->as(), false, true).get(); - if(atinfo != NULL) - { - std::string& tcomm = atinfo->m_comm; + case PT_FD: { + int64_t fd = param->as(); + render_fd(fd, resolved_str, fmt); + break; + } + case PT_PID: { + snprintf(&m_paramstr_storage[0], + m_paramstr_storage.size(), + "%" PRId64, + param->as()); - // - // Make sure the string will fit - // - if(tcomm.size() >= m_resolved_paramstr_storage.size()) - { - m_resolved_paramstr_storage.resize(tcomm.size() + 1); - } + sinsp_threadinfo *atinfo = + m_inspector->get_thread_ref(param->as(), false, true).get(); + if(atinfo != NULL) { + std::string &tcomm = atinfo->m_comm; - snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - "%s", - tcomm.c_str()); + // + // Make sure the string will fit + // + if(tcomm.size() >= m_resolved_paramstr_storage.size()) { + m_resolved_paramstr_storage.resize(tcomm.size() + 1); } + + snprintf(&m_resolved_paramstr_storage[0], + m_resolved_paramstr_storage.size(), + "%s", + tcomm.c_str()); } - break; + } break; case PT_UINT8: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo8, PRId8, PRIX8); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; case PT_UINT16: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo16, PRId16, PRIX16); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; case PT_UINT32: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo32, PRId32, PRIX32); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; - case PT_ERRNO: - { + case PT_ERRNO: { int64_t val = param->as(); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRId64, val); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%" PRId64, val); // // Resolve this as an errno // std::string errstr; - if(val < 0) - { + if(val < 0) { errstr = sinsp_utils::errno_to_str((int32_t)val); - if(errstr != "") - { + if(errstr != "") { snprintf(&m_resolved_paramstr_storage[0], m_resolved_paramstr_storage.size(), - "%s", errstr.c_str()); + "%s", + errstr.c_str()); } } - } - break; + } break; case PT_UINT64: SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo64, PRId64, PRIX64); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, param->as()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, param->as()); break; case PT_CHARBUF: @@ -1007,70 +864,54 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, // Make sure the string will fit // s = param->as(); - if(s.length() + 1 > m_paramstr_storage.size()) - { + if(s.length() + 1 > m_paramstr_storage.size()) { m_paramstr_storage.resize(s.length() + 1); } - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%s", s.data()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%s", s.data()); break; case PT_FSPATH: - case PT_FSRELPATH: - { + case PT_FSRELPATH: { std::string_view path = param->as(); - if(path.length() + 1 > m_paramstr_storage.size()) - { + if(path.length() + 1 > m_paramstr_storage.size()) { m_paramstr_storage.resize(path.length() + 1); } - strcpy_sanitized(&m_paramstr_storage[0], - path.data(), - path.length() + 1); + strcpy_sanitized(&m_paramstr_storage[0], path.data(), path.length() + 1); - sinsp_threadinfo* tinfo = get_thread_info(); + sinsp_threadinfo *tinfo = get_thread_info(); - if(tinfo) - { - if(path != "") - { + if(tinfo) { + if(path != "") { std::string cwd = get_base_dir(id, tinfo); - if(path.length() + cwd.length() + 1 >= m_resolved_paramstr_storage.size()) - { + if(path.length() + cwd.length() + 1 >= m_resolved_paramstr_storage.size()) { m_resolved_paramstr_storage.resize(path.length() + cwd.length() + 2, 0); } - if(path.empty() || std::filesystem::path(path).is_absolute()) - { + if(path.empty() || std::filesystem::path(path).is_absolute()) { m_resolved_paramstr_storage[0] = 0; - } - else - { + } else { std::string concatenated_path = sinsp_utils::concatenate_paths(cwd, path); - strcpy_sanitized(&m_resolved_paramstr_storage[0], concatenated_path.data(), std::min(concatenated_path.size() + 1, m_resolved_paramstr_storage.size())); + strcpy_sanitized(&m_resolved_paramstr_storage[0], + concatenated_path.data(), + std::min(concatenated_path.size() + 1, + m_resolved_paramstr_storage.size())); } } - } - else - { + } else { *resolved_str = &m_paramstr_storage[0]; } - } - break; - case PT_BYTEBUF: - { - while(true) - { + } break; + case PT_BYTEBUF: { + while(true) { uint32_t blen = binary_buffer_to_string(&m_paramstr_storage[0], - param->m_val, - (uint32_t)m_paramstr_storage.size() - 1, - param->m_len, - fmt); + param->m_val, + (uint32_t)m_paramstr_storage.size() - 1, + param->m_len, + fmt); - if(blen >= m_paramstr_storage.size() - 1) - { + if(blen >= m_paramstr_storage.size() - 1) { // // The buffer didn't fit, expand it and try again // @@ -1080,177 +921,149 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, ASSERT(m_inspector != NULL); if(m_inspector->get_max_evt_output_len() != 0 && - blen > m_inspector->get_max_evt_output_len() && - fmt == PF_NORMAL) - { + blen > m_inspector->get_max_evt_output_len() && fmt == PF_NORMAL) { uint32_t real_len = std::min(blen, m_inspector->get_max_evt_output_len()); m_rawbuf_str_len = real_len; - if(real_len > 3) - { + if(real_len > 3) { m_paramstr_storage[real_len - 3] = '.'; m_paramstr_storage[real_len - 2] = '.'; m_paramstr_storage[real_len - 1] = '.'; } m_paramstr_storage[real_len] = 0; - } - else - { + } else { m_rawbuf_str_len = blen; } break; } - } - break; + } break; case PT_SOCKADDR: sockfamily = param->m_val[0]; - if(sockfamily == PPM_AF_UNIX) - { + if(sockfamily == PPM_AF_UNIX) { ASSERT(param->m_len > 1); // // Sanitize the file string. // - std::string sanitized_str = param->m_val + 1; + std::string sanitized_str = param->m_val + 1; sanitize_string(sanitized_str); snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%s", - sanitized_str.c_str()); - } - else if(sockfamily == PPM_AF_INET) - { - if(param->m_len == 1 + 4 + 2) - { + m_paramstr_storage.size(), + "%s", + sanitized_str.c_str()); + } else if(sockfamily == PPM_AF_INET) { + if(param->m_len == 1 + 4 + 2) { ipv4serverinfo addr; memcpy(&addr.m_ip, param->m_val + 1, sizeof(addr.m_ip)); memcpy(&addr.m_port, param->m_val + 5, sizeof(addr.m_port)); addr.m_l4proto = (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN; - std::string straddr = ipv4serveraddr_to_string(&addr, m_inspector->is_hostname_and_port_resolution_enabled()); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%s", - straddr.c_str()); - } - else - { + std::string straddr = ipv4serveraddr_to_string( + &addr, + m_inspector->is_hostname_and_port_resolution_enabled()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%s", straddr.c_str()); + } else { ASSERT(false); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "INVALID IPv4"); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "INVALID IPv4"); } - } - else if(sockfamily == PPM_AF_INET6) - { - if(param->m_len == 1 + 16 + 2) - { + } else if(sockfamily == PPM_AF_INET6) { + if(param->m_len == 1 + 16 + 2) { ipv6serverinfo addr; - memcpy((uint8_t *) addr.m_ip.m_b, (uint8_t *) param->m_val + 1, sizeof(addr.m_ip.m_b)); + memcpy((uint8_t *)addr.m_ip.m_b, + (uint8_t *)param->m_val + 1, + sizeof(addr.m_ip.m_b)); memcpy(&addr.m_port, param->m_val + 17, sizeof(addr.m_port)); addr.m_l4proto = (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN; - std::string straddr = ipv6serveraddr_to_string(&addr, m_inspector->is_hostname_and_port_resolution_enabled()); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%s", - straddr.c_str()); - } - else - { + std::string straddr = ipv6serveraddr_to_string( + &addr, + m_inspector->is_hostname_and_port_resolution_enabled()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%s", straddr.c_str()); + } else { ASSERT(false); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "INVALID IPv6"); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "INVALID IPv6"); } - } - else - { - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "family %d", sockfamily); + } else { + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "family %d", sockfamily); } break; case PT_SOCKTUPLE: sockfamily = param->m_val[0]; - if(sockfamily == PPM_AF_INET) - { - if(param->m_len == 1 + 4 + 2 + 4 + 2) - { + if(sockfamily == PPM_AF_INET) { + if(param->m_len == 1 + 4 + 2 + 4 + 2) { ipv4tuple addr; memcpy(&addr.m_fields.m_sip, param->m_val + 1, sizeof(uint32_t)); memcpy(&addr.m_fields.m_sport, param->m_val + 5, sizeof(uint16_t)); memcpy(&addr.m_fields.m_dip, param->m_val + 7, sizeof(uint32_t)); memcpy(&addr.m_fields.m_dport, param->m_val + 11, sizeof(uint16_t)); - addr.m_fields.m_l4proto = (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN; - std::string straddr = ipv4tuple_to_string(&addr, m_inspector->is_hostname_and_port_resolution_enabled()); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%s", - straddr.c_str()); - } - else - { + addr.m_fields.m_l4proto = + (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN; + std::string straddr = + ipv4tuple_to_string(&addr, + m_inspector->is_hostname_and_port_resolution_enabled()); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%s", straddr.c_str()); + } else { ASSERT(false); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "INVALID IPv4"); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "INVALID IPv4"); } - } - else if(sockfamily == PPM_AF_INET6) - { - if(param->m_len == 1 + 16 + 2 + 16 + 2) - { - uint8_t* sip6 = (uint8_t*)param->m_val + 1; - uint8_t* dip6 = (uint8_t*)param->m_val + 19; - uint8_t* sip = (uint8_t*)param->m_val + 13; - uint8_t* dip = (uint8_t*)param->m_val + 31; - - if(sinsp_utils::is_ipv4_mapped_ipv6(sip6) && sinsp_utils::is_ipv4_mapped_ipv6(dip6)) - { + } else if(sockfamily == PPM_AF_INET6) { + if(param->m_len == 1 + 16 + 2 + 16 + 2) { + uint8_t *sip6 = (uint8_t *)param->m_val + 1; + uint8_t *dip6 = (uint8_t *)param->m_val + 19; + uint8_t *sip = (uint8_t *)param->m_val + 13; + uint8_t *dip = (uint8_t *)param->m_val + 31; + + if(sinsp_utils::is_ipv4_mapped_ipv6(sip6) && + sinsp_utils::is_ipv4_mapped_ipv6(dip6)) { ipv4tuple addr; memcpy(&addr.m_fields.m_sip, sip, sizeof(uint32_t)); memcpy(&addr.m_fields.m_sport, param->m_val + 17, sizeof(uint16_t)); memcpy(&addr.m_fields.m_dip, dip, sizeof(uint32_t)); memcpy(&addr.m_fields.m_dport, param->m_val + 35, sizeof(uint16_t)); - addr.m_fields.m_l4proto = (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN; - std::string straddr = ipv4tuple_to_string(&addr, m_inspector->is_hostname_and_port_resolution_enabled()); + addr.m_fields.m_l4proto = + (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN; + std::string straddr = ipv4tuple_to_string( + &addr, + m_inspector->is_hostname_and_port_resolution_enabled()); snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%s", - straddr.c_str()); + m_paramstr_storage.size(), + "%s", + straddr.c_str()); break; - } - else - { + } else { char srcstr[INET6_ADDRSTRLEN]; char dststr[INET6_ADDRSTRLEN]; if(inet_ntop(AF_INET6, sip6, srcstr, sizeof(srcstr)) && - inet_ntop(AF_INET6, dip6, dststr, sizeof(dststr))) - { + inet_ntop(AF_INET6, dip6, dststr, sizeof(dststr))) { uint16_t srcport, dstport; memcpy(&srcport, param->m_val + 17, sizeof(srcport)); memcpy(&dstport, param->m_val + 35, sizeof(dstport)); snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%s:%s->%s:%s", - srcstr, - port_to_string(srcport, (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN, m_inspector->is_hostname_and_port_resolution_enabled()).c_str(), - dststr, - port_to_string(dstport, (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() : SCAP_L4_UNKNOWN, m_inspector->is_hostname_and_port_resolution_enabled()).c_str()); + m_paramstr_storage.size(), + "%s:%s->%s:%s", + srcstr, + port_to_string( + srcport, + (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() + : SCAP_L4_UNKNOWN, + m_inspector->is_hostname_and_port_resolution_enabled()) + .c_str(), + dststr, + port_to_string( + dstport, + (m_fdinfo != NULL) ? m_fdinfo->get_l4proto() + : SCAP_L4_UNKNOWN, + m_inspector->is_hostname_and_port_resolution_enabled()) + .c_str()); break; } } } ASSERT(false); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "INVALID IPv6"); - } - else if(sockfamily == PPM_AF_UNIX) - { + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "INVALID IPv6"); + } else if(sockfamily == PPM_AF_UNIX) { ASSERT(param->m_len > 17); // @@ -1263,416 +1076,332 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, memcpy(&src, param->m_val + 1, sizeof(uint64_t)); memcpy(&dst, param->m_val + 9, sizeof(uint64_t)); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRIx64 "->%" PRIx64 " %s", - src, - dst, - sanitized_str.c_str()); - } - else - { snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), - "family %d", sockfamily); + "%" PRIx64 "->%" PRIx64 " %s", + src, + dst, + sanitized_str.c_str()); + } else { + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "family %d", sockfamily); } break; - case PT_FDLIST: - { - sinsp_threadinfo* tinfo = get_thread_info(); - if(!tinfo) - { - break; - } + case PT_FDLIST: { + sinsp_threadinfo *tinfo = get_thread_info(); + if(!tinfo) { + break; + } - uint16_t nfds = 0; - memcpy(&nfds, param->m_val, sizeof(nfds)); - uint32_t pos = 2; - uint32_t spos = 0; + uint16_t nfds = 0; + memcpy(&nfds, param->m_val, sizeof(nfds)); + uint32_t pos = 2; + uint32_t spos = 0; - m_paramstr_storage[0] = 0; + m_paramstr_storage[0] = 0; - for(j = 0; j < nfds; j++) - { - char tch; - int64_t fd = 0; - memcpy(&fd, param->m_val + pos, sizeof(uint64_t)); + for(j = 0; j < nfds; j++) { + char tch; + int64_t fd = 0; + memcpy(&fd, param->m_val + pos, sizeof(uint64_t)); - sinsp_fdinfo *fdinfo = tinfo->get_fd(fd); - if(fdinfo) - { - tch = fdinfo->get_typechar(); - } - else - { - tch = '?'; - } - - int16_t p8; - memcpy(&p8, param->m_val + pos + 8, sizeof(int16_t)); + sinsp_fdinfo *fdinfo = tinfo->get_fd(fd); + if(fdinfo) { + tch = fdinfo->get_typechar(); + } else { + tch = '?'; + } - int r = snprintf(&m_paramstr_storage[0] + spos, - m_paramstr_storage.size() - spos, - "%" PRIu64 ":%c%x%c", - fd, - tch, - (uint32_t) p8, - (j < (uint32_t)(nfds - 1)) ? ' ' : '\0'); + int16_t p8; + memcpy(&p8, param->m_val + pos + 8, sizeof(int16_t)); - if(r < 0 || spos + r >= m_paramstr_storage.size() - 1) - { - m_paramstr_storage[m_paramstr_storage.size() - 1] = 0; - break; - } + int r = snprintf(&m_paramstr_storage[0] + spos, + m_paramstr_storage.size() - spos, + "%" PRIu64 ":%c%x%c", + fd, + tch, + (uint32_t)p8, + (j < (uint32_t)(nfds - 1)) ? ' ' : '\0'); - spos += r; - pos += 10; - } - } - break; - case PT_SYSCALLID: - { - uint16_t ppm_sc = param->as(); - if(ppm_sc >= PPM_SC_MAX) - { - ASSERT(false); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - ""); + if(r < 0 || spos + r >= m_paramstr_storage.size() - 1) { + m_paramstr_storage[m_paramstr_storage.size() - 1] = 0; break; } - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRIu16, - ppm_sc); - - snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - "%s", - scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)); + spos += r; + pos += 10; + } + } break; + case PT_SYSCALLID: { + uint16_t ppm_sc = param->as(); + if(ppm_sc >= PPM_SC_MAX) { + ASSERT(false); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), ""); + break; } - break; - case PT_SIGTYPE: - { - const char* sigstr; - uint8_t val = param->as(); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%" PRIu16, ppm_sc); - sigstr = sinsp_utils::signal_to_str(val); + snprintf(&m_resolved_paramstr_storage[0], + m_resolved_paramstr_storage.size(), + "%s", + scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)); + } break; + case PT_SIGTYPE: { + const char *sigstr; - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRIu8, val); + uint8_t val = param->as(); - if(sigstr) - { - snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - "%s", sigstr); - } + sigstr = sinsp_utils::signal_to_str(val); + + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%" PRIu8, val); + + if(sigstr) { + snprintf(&m_resolved_paramstr_storage[0], + m_resolved_paramstr_storage.size(), + "%s", + sigstr); } - break; - case PT_RELTIME: - { - std::string sigstr; - - uint64_t val = param->as(); - - if(val == (uint64_t)(-1)) - { - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "none"); - m_resolved_paramstr_storage[0] = '\0'; - } - else - { - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRIu64, val); + } break; + case PT_RELTIME: { + std::string sigstr; - snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - "%lgs", - ((double)val) / 1000000000); - } + uint64_t val = param->as(); + + if(val == (uint64_t)(-1)) { + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "none"); + m_resolved_paramstr_storage[0] = '\0'; + } else { + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%" PRIu64, val); + + snprintf(&m_resolved_paramstr_storage[0], + m_resolved_paramstr_storage.size(), + "%lgs", + ((double)val) / 1000000000); } - break; + } break; case PT_FLAGS8: case PT_FLAGS16: case PT_FLAGS32: case PT_ENUMFLAGS8: case PT_ENUMFLAGS16: - case PT_ENUMFLAGS32: - { - uint32_t val = 0; - switch(param_info->type) - { - case PT_FLAGS8: - case PT_ENUMFLAGS8: - val = param->as(); - break; - case PT_FLAGS16: - case PT_ENUMFLAGS16: - val = param->as(); - break; - case PT_FLAGS32: - case PT_ENUMFLAGS32: - val = param->as(); - break; - default: - ASSERT(false); - } - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%" PRIu32, val); - - auto flags = (const ppm_name_value*)m_info->params[id].info; - const bool exact_match = param_info->type == PT_ENUMFLAGS8 || param_info->type == PT_ENUMFLAGS16 || param_info->type == PT_ENUMFLAGS32; - const char *separator = ""; - uint32_t initial_val = val; - uint32_t j = 0; - - while(flags != NULL && flags->name != NULL) - { - bool match = false; - if (exact_match) - { - match = flags->value == initial_val; + case PT_ENUMFLAGS32: { + uint32_t val = 0; + switch(param_info->type) { + case PT_FLAGS8: + case PT_ENUMFLAGS8: + val = param->as(); + break; + case PT_FLAGS16: + case PT_ENUMFLAGS16: + val = param->as(); + break; + case PT_FLAGS32: + case PT_ENUMFLAGS32: + val = param->as(); + break; + default: + ASSERT(false); + } + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%" PRIu32, val); + + auto flags = (const ppm_name_value *)m_info->params[id].info; + const bool exact_match = param_info->type == PT_ENUMFLAGS8 || + param_info->type == PT_ENUMFLAGS16 || + param_info->type == PT_ENUMFLAGS32; + const char *separator = ""; + uint32_t initial_val = val; + uint32_t j = 0; + + while(flags != NULL && flags->name != NULL) { + bool match = false; + if(exact_match) { + match = flags->value == initial_val; + } else { + // If flag is 0, then initial_val needs to be 0 for the flag to be resolved + if((flags->value == 0 && initial_val == 0) || + (flags->value != 0 && (val & flags->value) == flags->value && val != 0)) { + match = true; + // We remove current flags value to avoid duplicate flags e.g. PPM_O_RDWR, + // PPM_O_RDONLY, PPM_O_WRONLY + val &= ~flags->value; } - else - { - // If flag is 0, then initial_val needs to be 0 for the flag to be resolved - if ((flags->value == 0 && initial_val == 0) || - (flags->value != 0 && (val & flags->value) == flags->value && val != 0)) - { - match = true; - // We remove current flags value to avoid duplicate flags e.g. PPM_O_RDWR, PPM_O_RDONLY, PPM_O_WRONLY - val &= ~flags->value; - } + } + if(match) { + if(m_resolved_paramstr_storage.size() < + j + strlen(separator) + strlen(flags->name)) { + m_resolved_paramstr_storage.resize(m_resolved_paramstr_storage.size() * 2); } - if (match) - { - if(m_resolved_paramstr_storage.size() < j + strlen(separator) + strlen(flags->name)) - { - m_resolved_paramstr_storage.resize(m_resolved_paramstr_storage.size() * 2); - } - j += snprintf(&m_resolved_paramstr_storage[j], - m_resolved_paramstr_storage.size(), - "%s%s", - separator, - flags->name); - separator = "|"; - if (!exact_match) - { - if (flags->value == initial_val) - { - // if we reached initial val, we have finished. - // NOTE: for enum flags, we might have multiple flags matching same enum value - // see socket_families (eg: AF_LOCAL, AF_UNIX). Don't break. - break; - } + j += snprintf(&m_resolved_paramstr_storage[j], + m_resolved_paramstr_storage.size(), + "%s%s", + separator, + flags->name); + separator = "|"; + if(!exact_match) { + if(flags->value == initial_val) { + // if we reached initial val, we have finished. + // NOTE: for enum flags, we might have multiple flags matching same enum + // value see socket_families (eg: AF_LOCAL, AF_UNIX). Don't break. + break; } } - - flags++; } - break; + flags++; } - case PT_MODE: - { - uint32_t val = param->as(); - SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo32, PRId32, PRIX32); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - prfmt, val); - - auto mode = (const ppm_name_value*)m_info->params[id].info; - const char *separator = ""; - uint32_t initial_val = val; - uint32_t j = 0; - - while(mode != NULL && mode->name != NULL && mode->value != initial_val) - { - // If mode is 0, then initial_val needs to be 0 for the mode to be resolved - if((mode->value == 0 && initial_val == 0) || - (mode->value != 0 && (val & mode->value) == mode->value && val != 0)) - { - size_t params_len = j + strlen(separator) + strlen(mode->name); - if(m_resolved_paramstr_storage.size() < params_len) - { - m_resolved_paramstr_storage.resize(params_len + 1); - } - - j += snprintf(&m_resolved_paramstr_storage[j], - m_resolved_paramstr_storage.size(), - "%s%s", - separator, - mode->name); - separator = "|"; - // We remove current mode value to avoid duplicates - val &= ~mode->value; + break; + } + case PT_MODE: { + uint32_t val = param->as(); + SET_NUMERIC_FORMAT(prfmt, param_fmt, PRIo32, PRId32, PRIX32); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), prfmt, val); + + auto mode = (const ppm_name_value *)m_info->params[id].info; + const char *separator = ""; + uint32_t initial_val = val; + uint32_t j = 0; + + while(mode != NULL && mode->name != NULL && mode->value != initial_val) { + // If mode is 0, then initial_val needs to be 0 for the mode to be resolved + if((mode->value == 0 && initial_val == 0) || + (mode->value != 0 && (val & mode->value) == mode->value && val != 0)) { + size_t params_len = j + strlen(separator) + strlen(mode->name); + if(m_resolved_paramstr_storage.size() < params_len) { + m_resolved_paramstr_storage.resize(params_len + 1); } - mode++; - } - - if(mode != NULL && mode->name != NULL) - { j += snprintf(&m_resolved_paramstr_storage[j], - m_resolved_paramstr_storage.size(), - "%s%s", - separator, - mode->name); + m_resolved_paramstr_storage.size(), + "%s%s", + separator, + mode->name); + + separator = "|"; + // We remove current mode value to avoid duplicates + val &= ~mode->value; } - break; + mode++; } - case PT_ABSTIME: - { - uint64_t val = param->as(); - time_t sec = val / 1000000000ULL; - unsigned long nsec = val % 1000000000ULL; - struct tm tm; - localtime_r(&sec, &tm); - strftime(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%Y-%m-%d %H:%M:%S.XXXXXXXXX %z", &tm); - snprintf(&m_paramstr_storage[20], 10, "%09ld", nsec); - break; + + if(mode != NULL && mode->name != NULL) { + j += snprintf(&m_resolved_paramstr_storage[j], + m_resolved_paramstr_storage.size(), + "%s%s", + separator, + mode->name); } + + break; + } + case PT_ABSTIME: { + uint64_t val = param->as(); + time_t sec = val / 1000000000ULL; + unsigned long nsec = val % 1000000000ULL; + struct tm tm; + localtime_r(&sec, &tm); + strftime(&m_paramstr_storage[0], + m_paramstr_storage.size(), + "%Y-%m-%d %H:%M:%S.XXXXXXXXX %z", + &tm); + snprintf(&m_paramstr_storage[20], 10, "%09ld", nsec); + break; + } case PT_DYN: ASSERT(false); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "INVALID DYNAMIC PARAMETER"); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "INVALID DYNAMIC PARAMETER"); break; - case PT_UID: - { + case PT_UID: { uint32_t val = param->as(); - if (val < std::numeric_limits::max()) - { + if(val < std::numeric_limits::max()) { // Note: we want to resolve user given the uid // from the event. // Eg: for setuid() the requested uid is not // the threadinfo one yet; // therefore we cannot directly use tinfo->m_user here. - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%d", val); - sinsp_threadinfo* tinfo = get_thread_info(); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%d", val); + sinsp_threadinfo *tinfo = get_thread_info(); scap_userinfo *user_info = NULL; - if (tinfo) - { + if(tinfo) { user_info = m_inspector->m_usergroup_manager.get_user(tinfo->m_container_id, val); } - if (user_info != NULL) - { - strcpy_sanitized(&m_resolved_paramstr_storage[0], user_info->name, - (uint32_t)m_resolved_paramstr_storage.size()); - } - else - { + if(user_info != NULL) { + strcpy_sanitized(&m_resolved_paramstr_storage[0], + user_info->name, + (uint32_t)m_resolved_paramstr_storage.size()); + } else { snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - ""); + m_resolved_paramstr_storage.size(), + ""); } - } - else - { - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "-1"); - snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - ""); + } else { + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "-1"); + snprintf(&m_resolved_paramstr_storage[0], m_resolved_paramstr_storage.size(), ""); } break; } - case PT_GID: - { + case PT_GID: { uint32_t val = param->as(); - if (val < std::numeric_limits::max()) - { + if(val < std::numeric_limits::max()) { // Note: we want to resolve group given the gid // from the event. // Eg: for setgid() the requested gid is not // the threadinfo one yet; // therefore we cannot directly use tinfo->m_group here. - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "%d", val); - sinsp_threadinfo* tinfo = get_thread_info(); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "%d", val); + sinsp_threadinfo *tinfo = get_thread_info(); scap_groupinfo *group_info = NULL; - if (tinfo) - { + if(tinfo) { group_info = m_inspector->m_usergroup_manager.get_group(tinfo->m_container_id, val); } - if (group_info != NULL) - { - strcpy_sanitized(&m_resolved_paramstr_storage[0], group_info->name, - (uint32_t)m_resolved_paramstr_storage.size()); - } - else - { + if(group_info != NULL) { + strcpy_sanitized(&m_resolved_paramstr_storage[0], + group_info->name, + (uint32_t)m_resolved_paramstr_storage.size()); + } else { snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - ""); + m_resolved_paramstr_storage.size(), + ""); } - } - else - { - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "-1"); - snprintf(&m_resolved_paramstr_storage[0], - m_resolved_paramstr_storage.size(), - ""); + } else { + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "-1"); + snprintf(&m_resolved_paramstr_storage[0], m_resolved_paramstr_storage.size(), ""); } break; } - case PT_CHARBUFARRAY: - { + case PT_CHARBUFARRAY: { ASSERT(param->m_len == sizeof(uint64_t)); - std::vector* strvect = (std::vector*)*(uint64_t *)param->m_val; + std::vector *strvect = (std::vector *)*(uint64_t *)param->m_val; m_paramstr_storage[0] = 0; - while(true) - { - std::vector::iterator it; - std::vector::iterator itbeg; + while(true) { + std::vector::iterator it; + std::vector::iterator itbeg; bool need_to_resize = false; // // Copy the arguments // - char* dst = &m_paramstr_storage[0]; - char* dstend = &m_paramstr_storage[0] + m_paramstr_storage.size() - 2; + char *dst = &m_paramstr_storage[0]; + char *dstend = &m_paramstr_storage[0] + m_paramstr_storage.size() - 2; - for(it = itbeg = strvect->begin(); it != strvect->end(); ++it) - { - char* src = *it; + for(it = itbeg = strvect->begin(); it != strvect->end(); ++it) { + char *src = *it; - if(it != itbeg) - { - if(dst < dstend - 1) - { + if(it != itbeg) { + if(dst < dstend - 1) { *dst++ = '.'; } } - while(*src != 0 && dst < dstend) - { + while(*src != 0 && dst < dstend) { *dst++ = *src++; } - if(dst == dstend) - { + if(dst == dstend) { // // Reached the end of m_paramstr_storage, we need to resize it // @@ -1681,8 +1410,7 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, } } - if(need_to_resize) - { + if(need_to_resize) { m_paramstr_storage.resize(m_paramstr_storage.size() * 2); continue; } @@ -1691,46 +1419,40 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, break; } - } - break; - case PT_CHARBUF_PAIR_ARRAY: - { + } break; + case PT_CHARBUF_PAIR_ARRAY: { ASSERT(param->m_len == sizeof(uint64_t)); - std::pair*, std::vector*>* pairs = - (std::pair*, std::vector*>*)*(uint64_t *)param->m_val; + std::pair *, std::vector *> *pairs = + (std::pair *, std::vector *> *)*( + uint64_t *)param->m_val; m_paramstr_storage[0] = 0; - if(pairs->first->size() != pairs->second->size()) - { + if(pairs->first->size() != pairs->second->size()) { ASSERT(false); break; } - while(true) - { - std::vector::iterator it1; - std::vector::iterator itbeg1; - std::vector::iterator it2; - std::vector::iterator itbeg2; + while(true) { + std::vector::iterator it1; + std::vector::iterator itbeg1; + std::vector::iterator it2; + std::vector::iterator itbeg2; bool need_to_resize = false; // // Copy the arguments // - char* dst = &m_paramstr_storage[0]; - char* dstend = &m_paramstr_storage[0] + m_paramstr_storage.size() - 2; + char *dst = &m_paramstr_storage[0]; + char *dstend = &m_paramstr_storage[0] + m_paramstr_storage.size() - 2; for(it1 = itbeg1 = pairs->first->begin(), it2 = itbeg2 = pairs->second->begin(); - it1 != pairs->first->end(); - ++it1, ++it2) - { - char* src = *it1; - - if(it1 != itbeg1) - { - if(dst < dstend - 1) - { + it1 != pairs->first->end(); + ++it1, ++it2) { + char *src = *it1; + + if(it1 != itbeg1) { + if(dst < dstend - 1) { *dst++ = ','; } } @@ -1738,13 +1460,11 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, // // Copy the first string // - while(*src != 0 && dst < dstend) - { + while(*src != 0 && dst < dstend) { *dst++ = *src++; } - if(dst < dstend - 1) - { + if(dst < dstend - 1) { *dst++ = ':'; } @@ -1752,13 +1472,11 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, // Copy the second string // src = *it2; - while(*src != 0 && dst < dstend) - { + while(*src != 0 && dst < dstend) { *dst++ = *src++; } - if(dst == dstend) - { + if(dst == dstend) { // // Reached the end of m_paramstr_storage, we need to resize it // @@ -1767,8 +1485,7 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, } } - if(need_to_resize) - { + if(need_to_resize) { m_paramstr_storage.resize(m_paramstr_storage.size() * 2); continue; } @@ -1780,36 +1497,28 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, break; } - case PT_SIGSET: - { + case PT_SIGSET: { uint32_t val = param->as(); m_resolved_paramstr_storage[0] = '\0'; - m_paramstr_storage[0] = '\0'; + m_paramstr_storage[0] = '\0'; - char* storage = &m_paramstr_storage[0]; + char *storage = &m_paramstr_storage[0]; int remaining = (int)m_paramstr_storage.size(); bool first = true; - for(int sig = 0; sig < 32; sig++) - { - if(val & (1U << sig) ) - { - const char* sigstr = sinsp_utils::signal_to_str(sig+1); - if(sigstr) - { - int printed = snprintf(storage, remaining, - "%s%s", - !first ? " " : "", - sigstr); - if(printed >= remaining) - { - storage[remaining-1] = '\0'; + for(int sig = 0; sig < 32; sig++) { + if(val & (1U << sig)) { + const char *sigstr = sinsp_utils::signal_to_str(sig + 1); + if(sigstr) { + int printed = snprintf(storage, remaining, "%s%s", !first ? " " : "", sigstr); + if(printed >= remaining) { + storage[remaining - 1] = '\0'; break; } - first = false; - storage += printed; + first = false; + storage += printed; remaining -= printed; } } @@ -1818,9 +1527,7 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, } default: ASSERT(false); - snprintf(&m_paramstr_storage[0], - m_paramstr_storage.size(), - "(n.a.)"); + snprintf(&m_paramstr_storage[0], m_paramstr_storage.size(), "(n.a.)"); break; } @@ -1829,12 +1536,9 @@ const char* sinsp_evt::get_param_as_str(uint32_t id, const char** resolved_str, return &m_paramstr_storage[0]; } -std::string sinsp_evt::get_param_value_str(std::string_view name, bool resolved) -{ - for(uint32_t i = 0; i < get_num_params(); i++) - { - if(name == get_param_name(i)) - { +std::string sinsp_evt::get_param_value_str(std::string_view name, bool resolved) { + for(uint32_t i = 0; i < get_num_params(); i++) { + if(name == get_param_name(i)) { return get_param_value_str(i, resolved); } } @@ -1842,28 +1546,23 @@ std::string sinsp_evt::get_param_value_str(std::string_view name, bool resolved) return std::string(); } -std::string sinsp_evt::get_param_value_str(uint32_t i, bool resolved) -{ +std::string sinsp_evt::get_param_value_str(uint32_t i, bool resolved) { const char *param_value_str; const char *val_str; val_str = get_param_as_str(i, ¶m_value_str); - if(resolved) - { - return std::string((*param_value_str == '\0')? val_str : param_value_str); - } - else - { + if(resolved) { + return std::string((*param_value_str == '\0') ? val_str : param_value_str); + } else { return std::string(val_str); } } -const char* sinsp_evt::get_param_value_str(std::string_view name, const char** resolved_str, param_fmt fmt) -{ - for(uint32_t i = 0; i < get_num_params(); i++) - { - if(name == get_param_name(i)) - { +const char *sinsp_evt::get_param_value_str(std::string_view name, + const char **resolved_str, + param_fmt fmt) { + for(uint32_t i = 0; i < get_num_params(); i++) { + if(name == get_param_name(i)) { return get_param_as_str(i, resolved_str, fmt); } } @@ -1872,8 +1571,7 @@ const char* sinsp_evt::get_param_value_str(std::string_view name, const char** r return NULL; } -void sinsp_evt::get_category(sinsp_evt::category* cat) const -{ +void sinsp_evt::get_category(sinsp_evt::category *cat) const { /* We always search the category inside the event table */ cat->m_category = get_category(); @@ -1881,205 +1579,159 @@ void sinsp_evt::get_category(sinsp_evt::category* cat) const // For EC_IO and EC_WAIT events, we dig into the fd state to get the category // and fdtype // - if(cat->m_category & EC_IO_BASE) - { - if(!m_fdinfo) - { + if(cat->m_category & EC_IO_BASE) { + if(!m_fdinfo) { // // The fd info is not present, likely because we missed its creation. // cat->m_subcategory = SC_UNKNOWN; return; - } - else - { - switch(m_fdinfo->m_type) - { - case SCAP_FD_FILE: - case SCAP_FD_FILE_V2: - case SCAP_FD_DIRECTORY: - cat->m_subcategory = SC_FILE; - break; - case SCAP_FD_IPV4_SOCK: - case SCAP_FD_IPV6_SOCK: - cat->m_subcategory = SC_NET; - break; - case SCAP_FD_IPV4_SERVSOCK: - case SCAP_FD_IPV6_SERVSOCK: - cat->m_subcategory = SC_NET; - break; - case SCAP_FD_FIFO: - case SCAP_FD_UNIX_SOCK: - case SCAP_FD_EVENT: - case SCAP_FD_SIGNALFD: - case SCAP_FD_INOTIFY: - case SCAP_FD_USERFAULTFD: - cat->m_subcategory = SC_IPC; - break; - case SCAP_FD_UNSUPPORTED: - case SCAP_FD_EVENTPOLL: - case SCAP_FD_TIMERFD: - case SCAP_FD_BPF: - case SCAP_FD_IOURING: - case SCAP_FD_NETLINK: - case SCAP_FD_MEMFD: - case SCAP_FD_PIDFD: - cat->m_subcategory = SC_OTHER; - break; - case SCAP_FD_UNKNOWN: - cat->m_subcategory = SC_OTHER; - break; - default: - cat->m_subcategory = SC_UNKNOWN; - break; + } else { + switch(m_fdinfo->m_type) { + case SCAP_FD_FILE: + case SCAP_FD_FILE_V2: + case SCAP_FD_DIRECTORY: + cat->m_subcategory = SC_FILE; + break; + case SCAP_FD_IPV4_SOCK: + case SCAP_FD_IPV6_SOCK: + cat->m_subcategory = SC_NET; + break; + case SCAP_FD_IPV4_SERVSOCK: + case SCAP_FD_IPV6_SERVSOCK: + cat->m_subcategory = SC_NET; + break; + case SCAP_FD_FIFO: + case SCAP_FD_UNIX_SOCK: + case SCAP_FD_EVENT: + case SCAP_FD_SIGNALFD: + case SCAP_FD_INOTIFY: + case SCAP_FD_USERFAULTFD: + cat->m_subcategory = SC_IPC; + break; + case SCAP_FD_UNSUPPORTED: + case SCAP_FD_EVENTPOLL: + case SCAP_FD_TIMERFD: + case SCAP_FD_BPF: + case SCAP_FD_IOURING: + case SCAP_FD_NETLINK: + case SCAP_FD_MEMFD: + case SCAP_FD_PIDFD: + cat->m_subcategory = SC_OTHER; + break; + case SCAP_FD_UNKNOWN: + cat->m_subcategory = SC_OTHER; + break; + default: + cat->m_subcategory = SC_UNKNOWN; + break; } } - } - else - { + } else { cat->m_subcategory = sinsp_evt::SC_NONE; } } -bool sinsp_evt::is_filtered_out() const -{ +bool sinsp_evt::is_filtered_out() const { return m_filtered_out; } -scap_dump_flags sinsp_evt::get_dump_flags(bool* should_drop) const -{ +scap_dump_flags sinsp_evt::get_dump_flags(bool *should_drop) const { uint32_t dflags = SCAP_DF_NONE; *should_drop = false; - if(m_filtered_out) - { - if(m_inspector->is_fatfile_enabled()) - { + if(m_filtered_out) { + if(m_inspector->is_fatfile_enabled()) { ppm_event_flags eflags = get_info_flags(); - if(eflags & EF_MODIFIES_STATE) - { + if(eflags & EF_MODIFIES_STATE) { dflags = SCAP_DF_STATE_ONLY; - } - else - { + } else { *should_drop = true; } - } - else - { + } else { *should_drop = true; } - if(*should_drop) - { + if(*should_drop) { ppm_event_category ecat = get_category(); - if(ecat & EC_INTERNAL) - { + if(ecat & EC_INTERNAL) { *should_drop = false; } } } - if(get_info_flags() & EF_LARGE_PAYLOAD) - { + if(get_info_flags() & EF_LARGE_PAYLOAD) { dflags |= SCAP_DF_LARGE; } return (scap_dump_flags)dflags; } -bool sinsp_evt::is_syscall_error() const -{ - return (m_errorcode != 0) && - (m_errorcode != SE_EINPROGRESS) && - (m_errorcode != SE_EAGAIN) && +bool sinsp_evt::is_syscall_error() const { + return (m_errorcode != 0) && (m_errorcode != SE_EINPROGRESS) && (m_errorcode != SE_EAGAIN) && (m_errorcode != SE_ETIMEDOUT); } -bool sinsp_evt::is_file_open_error() const -{ +bool sinsp_evt::is_file_open_error() const { return (m_fdinfo == nullptr) && - ((m_pevt->type == PPME_SYSCALL_OPEN_X) || - (m_pevt->type == PPME_SYSCALL_CREAT_X) || - (m_pevt->type == PPME_SYSCALL_OPENAT_X) || - (m_pevt->type == PPME_SYSCALL_OPENAT_2_X) || - (m_pevt->type == PPME_SYSCALL_OPENAT2_X) || - (m_pevt->type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X)); + ((m_pevt->type == PPME_SYSCALL_OPEN_X) || (m_pevt->type == PPME_SYSCALL_CREAT_X) || + (m_pevt->type == PPME_SYSCALL_OPENAT_X) || (m_pevt->type == PPME_SYSCALL_OPENAT_2_X) || + (m_pevt->type == PPME_SYSCALL_OPENAT2_X) || + (m_pevt->type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X)); } -bool sinsp_evt::is_file_error() const -{ +bool sinsp_evt::is_file_error() const { return is_file_open_error() || ((m_fdinfo != nullptr) && - ((m_fdinfo->m_type == SCAP_FD_FILE) || - (m_fdinfo->m_type == SCAP_FD_FILE_V2))); + ((m_fdinfo->m_type == SCAP_FD_FILE) || (m_fdinfo->m_type == SCAP_FD_FILE_V2))); } -bool sinsp_evt::is_network_error() const -{ - if(m_fdinfo != nullptr) - { - return (m_fdinfo->m_type == SCAP_FD_IPV4_SOCK) || - (m_fdinfo->m_type == SCAP_FD_IPV6_SOCK); - } - else - { - return (m_pevt->type == PPME_SOCKET_ACCEPT_X) || - (m_pevt->type == PPME_SOCKET_ACCEPT4_X) || +bool sinsp_evt::is_network_error() const { + if(m_fdinfo != nullptr) { + return (m_fdinfo->m_type == SCAP_FD_IPV4_SOCK) || (m_fdinfo->m_type == SCAP_FD_IPV6_SOCK); + } else { + return (m_pevt->type == PPME_SOCKET_ACCEPT_X) || (m_pevt->type == PPME_SOCKET_ACCEPT4_X) || (m_pevt->type == PPME_SOCKET_ACCEPT_5_X) || (m_pevt->type == PPME_SOCKET_ACCEPT4_5_X) || (m_pevt->type == PPME_SOCKET_ACCEPT4_6_X) || - (m_pevt->type == PPME_SOCKET_CONNECT_X) || - (m_pevt->type == PPME_SOCKET_BIND_X); + (m_pevt->type == PPME_SOCKET_CONNECT_X) || (m_pevt->type == PPME_SOCKET_BIND_X); } } -uint64_t sinsp_evt::get_lastevent_ts() const -{ +uint64_t sinsp_evt::get_lastevent_ts() const { return m_tinfo->m_lastevent_ts; } -bool sinsp_evt::clone_event(sinsp_evt &dest, const sinsp_evt &src) -{ +bool sinsp_evt::clone_event(sinsp_evt &dest, const sinsp_evt &src) { dest.m_inspector = src.m_inspector; // tinfo - if (src.m_tinfo_ref && src.m_tinfo && src.m_tinfo_ref.get() != src.m_tinfo) - { + if(src.m_tinfo_ref && src.m_tinfo && src.m_tinfo_ref.get() != src.m_tinfo) { // bad data return false; } - if (src.m_tinfo_ref) - { + if(src.m_tinfo_ref) { dest.m_tinfo_ref = src.m_tinfo_ref; dest.m_tinfo = dest.m_tinfo_ref.get(); - } - else if (src.m_tinfo) - { + } else if(src.m_tinfo) { dest.m_tinfo_ref = dest.m_inspector->get_thread_ref(src.m_tinfo->m_tid, false, false); - if (dest.m_tinfo_ref == nullptr) - { + if(dest.m_tinfo_ref == nullptr) { // no tinfo return false; } dest.m_tinfo = dest.m_tinfo_ref.get(); - } - else - { + } else { dest.m_tinfo_ref = nullptr; dest.m_tinfo = nullptr; } - if (src.m_pevt != nullptr) - { + if(src.m_pevt != nullptr) { dest.m_pevt_storage = new char[src.get_scap_evt()->len]; memcpy(dest.m_pevt_storage, src.m_pevt, src.get_scap_evt()->len); - dest.m_pevt = (scap_evt *) dest.m_pevt_storage; - } - else - { + dest.m_pevt = (scap_evt *)dest.m_pevt_storage; + } else { dest.m_pevt_storage = nullptr; dest.m_pevt = nullptr; } @@ -2107,10 +1759,9 @@ bool sinsp_evt::clone_event(sinsp_evt &dest, const sinsp_evt &src) // fd info dest.m_fdinfo = nullptr; dest.m_fdinfo_ref.reset(); - if (src.m_fdinfo != nullptr) - { - //m_fdinfo_ref is only used to keep a handle to this - // copy of the fdinfo which was copied from the global fdinfo table + if(src.m_fdinfo != nullptr) { + // m_fdinfo_ref is only used to keep a handle to this + // copy of the fdinfo which was copied from the global fdinfo table dest.m_fdinfo_ref = src.m_fdinfo->clone(); dest.m_fdinfo = dest.m_fdinfo_ref.get(); } @@ -2119,15 +1770,13 @@ bool sinsp_evt::clone_event(sinsp_evt &dest, const sinsp_evt &src) return true; } -void sinsp_evt::save_enter_event_params(sinsp_evt* enter_evt) -{ +void sinsp_evt::save_enter_event_params(sinsp_evt *enter_evt) { static std::vector path_param = {"path"}; static std::vector oldpath_newpath_param = {"oldpath", "newpath"}; static std::vector name_param = {"name"}; std::vector *pnames = NULL; - switch(get_type()) - { + switch(get_type()) { case PPME_SYSCALL_MKDIR_X: case PPME_SYSCALL_RMDIR_X: case PPME_SYSCALL_UNLINK_X: @@ -2144,53 +1793,49 @@ void sinsp_evt::save_enter_event_params(sinsp_evt* enter_evt) break; }; - if(!pnames) - { + if(!pnames) { return; } - for(const char *pname : (*pnames)) - { + for(const char *pname : (*pnames)) { const sinsp_evt_param *param; param = enter_evt->get_param_by_name(pname); - if(param) - { + if(param) { std::string val = param->as(); m_enter_path_param[pname] = val; } } } -std::optional> sinsp_evt::get_enter_evt_param(const std::string& param) const -{ +std::optional> sinsp_evt::get_enter_evt_param( + const std::string ¶m) const { auto it = m_enter_path_param.find(param); - if(it != m_enter_path_param.end()) - { + if(it != m_enter_path_param.end()) { return it->second; } return std::nullopt; } -void sinsp_evt_param::throw_invalid_len_error(size_t requested_length) const -{ - const ppm_param_info* parinfo = get_info(); +void sinsp_evt_param::throw_invalid_len_error(size_t requested_length) const { + const ppm_param_info *parinfo = get_info(); std::stringstream ss; ss << "could not parse param " << m_idx << " (" << parinfo->name << ") for event " - << m_evt->get_num() << " of type " << m_evt->get_type() << " (" << m_evt->get_name() << "), for tid " << m_evt->get_tid() - << ": expected length " << requested_length << ", found " << m_len; + << m_evt->get_num() << " of type " << m_evt->get_type() << " (" << m_evt->get_name() + << "), for tid " << m_evt->get_tid() << ": expected length " << requested_length + << ", found " << m_len; std::string error_string = ss.str(); libsinsp_logger()->log(error_string, sinsp_logger::SEV_ERROR); - libsinsp_logger()->log("parameter raw data: \n" + buffer_to_multiline_hex(m_val, m_len), sinsp_logger::SEV_ERROR); + libsinsp_logger()->log("parameter raw data: \n" + buffer_to_multiline_hex(m_val, m_len), + sinsp_logger::SEV_ERROR); throw sinsp_exception(error_string); } -const ppm_param_info* sinsp_evt_param::get_info() const -{ +const ppm_param_info *sinsp_evt_param::get_info() const { return &(m_evt->get_info()->params[m_idx]); } diff --git a/userspace/libsinsp/event.h b/userspace/libsinsp/event.h index 93174cf13e..1ec0be47a5 100644 --- a/userspace/libsinsp/event.h +++ b/userspace/libsinsp/event.h @@ -50,49 +50,55 @@ class sinsp_evt; /*! \brief Wrapper that exports the libscap event tables. */ -class SINSP_PUBLIC sinsp_evttables -{ +class SINSP_PUBLIC sinsp_evttables { public: - const struct ppm_event_info* m_event_info; ///< List of events supported by the capture and analysis subsystems. Each entry fully documents an event and its parameters. + const struct ppm_event_info* + m_event_info; ///< List of events supported by the capture and analysis subsystems. + ///< Each entry fully documents an event and its parameters. }; -template inline T get_event_param_as(const class sinsp_evt_param& param); +template +inline T get_event_param_as(const class sinsp_evt_param& param); /*! \brief Event parameter wrapper. This class describes an event parameter coming from the driver. */ -class SINSP_PUBLIC sinsp_evt_param -{ +class SINSP_PUBLIC sinsp_evt_param { public: - const sinsp_evt *m_evt; ///< Pointer to the event that contains this param - uint32_t m_idx; ///< Index of the parameter within the event + const sinsp_evt* m_evt; ///< Pointer to the event that contains this param + uint32_t m_idx; ///< Index of the parameter within the event - const char* m_val; ///< Pointer to the event parameter data. - uint32_t m_len; ///< Length of the parameter pointed by m_val. + const char* m_val; ///< Pointer to the event parameter data. + uint32_t m_len; ///< Length of the parameter pointed by m_val. - sinsp_evt_param(const sinsp_evt *evt, uint32_t idx, const char *val, uint32_t len): - m_evt(evt), m_idx(idx), m_val(val), m_len(len) {} + sinsp_evt_param(const sinsp_evt* evt, uint32_t idx, const char* val, uint32_t len): + m_evt(evt), + m_idx(idx), + m_val(val), + m_len(len) {} /*! \brief Interpret the parameter as a specific type, like: - - Fixed size values (uint32_t, int8_t ..., e.g. param->as()) - - String-like types (NUL-terminated strings) with either: - - std::string_view (e.g. param->as()) to access the original string bytes or a NULL string - - std::string (e.g. param->as()) to obtain a copy of the string or an empty string if the parameter was NULL - - NUL-separated arrays of strings (e.g. "first\0second\0third\0") with std::vector + - Fixed size values (uint32_t, int8_t ..., e.g. param->as()) + - String-like types (NUL-terminated strings) with either: + - std::string_view (e.g. param->as()) to access the original string + bytes or a NULL string + - std::string (e.g. param->as()) to obtain a copy of the string or an empty + string if the parameter was NULL + - NUL-separated arrays of strings (e.g. "first\0second\0third\0") with + std::vector */ template - inline T as() const - { + inline T as() const { return get_event_param_as(*this); } const struct ppm_param_info* get_info() const; // Throws a sinsp_exception detailing why the requested_len is incorrect. - // This is only meant to be called by get_event_param_as. This way, this function will not be inlined - // while get_event_param_as will be inlined. + // This is only meant to be called by get_event_param_as. This way, this function will not be + // inlined while get_event_param_as will be inlined. [[gnu::cold]] void throw_invalid_len_error(size_t requested_len) const; }; @@ -102,15 +108,14 @@ class SINSP_PUBLIC sinsp_evt_param \param param The parameter. */ template -inline T get_event_param_as(const sinsp_evt_param& param) -{ +inline T get_event_param_as(const sinsp_evt_param& param) { static_assert(std::is_fundamental_v, - "event parameter cast (e.g. evt->get_param(N)->as()) unsupported for this type. Implement it or see the available definitions in " __FILE__); + "event parameter cast (e.g. evt->get_param(N)->as()) unsupported for this " + "type. Implement it or see the available definitions in " __FILE__); T ret; - if (param.m_len != sizeof(T)) - { + if(param.m_len != sizeof(T)) { // By moving this error string building operation to a separate function // the compiler is more likely to inline this entire function. param.throw_invalid_len_error(sizeof(T)); @@ -122,17 +127,14 @@ inline T get_event_param_as(const sinsp_evt_param& param) } template<> -inline std::string_view get_event_param_as(const sinsp_evt_param& param) -{ - if (param.m_len == 0) - { +inline std::string_view get_event_param_as(const sinsp_evt_param& param) { + if(param.m_len == 0) { return {}; } size_t string_len = strnlen(param.m_val, param.m_len); // We expect the parameter to be exactly one null-terminated string - if (param.m_len != string_len + 1) - { + if(param.m_len != string_len + 1) { // By moving this error string building operation to a separate function // the compiler is more likely to inline this entire function. param.throw_invalid_len_error(string_len + 1); @@ -142,17 +144,14 @@ inline std::string_view get_event_param_as(const sinsp_evt_par } template<> -inline std::string get_event_param_as(const sinsp_evt_param& param) -{ - if (param.m_len == 0) - { +inline std::string get_event_param_as(const sinsp_evt_param& param) { + if(param.m_len == 0) { return ""; } size_t string_len = strnlen(param.m_val, param.m_len); // We expect the parameter to be exactly one null-terminated string - if (param.m_len != string_len + 1) - { + if(param.m_len != string_len + 1) { // By moving this error string building operation to a separate function // the compiler is more likely to inline this entire function. param.throw_invalid_len_error(string_len + 1); @@ -162,12 +161,12 @@ inline std::string get_event_param_as(const sinsp_evt_param& param) } template<> -inline std::vector get_event_param_as>(const sinsp_evt_param& param) -{ - // vector string parameters coming from the driver may be NUL-terminated or not. Either way, remove the NUL terminator +inline std::vector get_event_param_as>( + const sinsp_evt_param& param) { + // vector string parameters coming from the driver may be NUL-terminated or not. Either way, + // remove the NUL terminator uint32_t len = param.m_len; - if (len > 0 && param.m_val[param.m_len - 1] == '\0') - { + if(len > 0 && param.m_val[param.m_len - 1] == '\0') { len--; } @@ -181,33 +180,31 @@ inline std::vector get_event_param_as>(con events and their parameters, including parsing, formatting and extracting state like the event process or FD. */ -class SINSP_PUBLIC sinsp_evt -{ +class SINSP_PUBLIC sinsp_evt { public: /*! \brief How to render an event parameter to string. */ - enum param_fmt - { - PF_NORMAL = (1 << 0), ///< Normal screen output - PF_JSON = (1 << 1), ///< Json formatting with data in normal screen format - PF_SIMPLE = (1 << 2), ///< Reduced output, e.g. not type character for FDs - PF_HEX = (1 << 3), ///< Hexadecimal output - PF_HEXASCII = (1 << 4), ///< Hexadecimal + ASCII output - PF_EOLS = (1 << 5), ///< Normal + end of lines - PF_EOLS_COMPACT = (1 << 6), ///< Normal + end of lines but with no force EOL at the beginning - PF_BASE64 = (1 << 7), ///< Base64 output - PF_JSONEOLS = (1 << 8), ///< Json formatting with data in hexadecimal format - PF_JSONHEX = (1 << 9), ///< Json formatting with data in hexadecimal format - PF_JSONHEXASCII = (1 << 10), ///< Json formatting with data in hexadecimal + ASCII format - PF_JSONBASE64 = (1 << 11), ///< Json formatting with data in base64 format + enum param_fmt { + PF_NORMAL = (1 << 0), ///< Normal screen output + PF_JSON = (1 << 1), ///< Json formatting with data in normal screen format + PF_SIMPLE = (1 << 2), ///< Reduced output, e.g. not type character for FDs + PF_HEX = (1 << 3), ///< Hexadecimal output + PF_HEXASCII = (1 << 4), ///< Hexadecimal + ASCII output + PF_EOLS = (1 << 5), ///< Normal + end of lines + PF_EOLS_COMPACT = + (1 << 6), ///< Normal + end of lines but with no force EOL at the beginning + PF_BASE64 = (1 << 7), ///< Base64 output + PF_JSONEOLS = (1 << 8), ///< Json formatting with data in hexadecimal format + PF_JSONHEX = (1 << 9), ///< Json formatting with data in hexadecimal format + PF_JSONHEXASCII = (1 << 10), ///< Json formatting with data in hexadecimal + ASCII format + PF_JSONBASE64 = (1 << 11), ///< Json formatting with data in base64 format }; /*! \brief Event subcategory specialization based on the fd type. */ - enum subcategory - { + enum subcategory { SC_UNKNOWN = 0, SC_NONE = 1, SC_OTHER = 2, @@ -216,22 +213,17 @@ class SINSP_PUBLIC sinsp_evt SC_IPC = 5, }; - enum fd_number_type - { - INVALID_FD_NUM = -100000 - }; + enum fd_number_type { INVALID_FD_NUM = -100000 }; /*! \brief Information regarding an event category, enriched with fd state. */ - struct category - { - ppm_event_category m_category; ///< Event category from the driver - subcategory m_subcategory; ///< Domain for IO and wait events + struct category { + ppm_event_category m_category; ///< Event category from the driver + subcategory m_subcategory; ///< Domain for IO and wait events }; - enum flags - { + enum flags { SINSP_EF_NONE = 0, SINSP_EF_PARAMS_LOADED = 1, // SINSP_EF_IS_TRACER = (1 << 1), // note: deprecated @@ -244,110 +236,65 @@ class SINSP_PUBLIC sinsp_evt /*! \brief Set the inspector. */ - inline void set_inspector(sinsp *value) - { - m_inspector = value; - } + inline void set_inspector(sinsp* value) { m_inspector = value; } - inline sinsp* get_inspector() - { - return m_inspector; - } + inline sinsp* get_inspector() { return m_inspector; } - inline const sinsp* get_inspector() const - { - return m_inspector; - } + inline const sinsp* get_inspector() const { return m_inspector; } /*! \brief Get the incremental number of this event. */ - inline uint64_t get_num() const - { - return m_evtnum; - } + inline uint64_t get_num() const { return m_evtnum; } /*! \brief Set the number of this event. */ - inline void set_num(uint64_t evtnum) - { - m_evtnum = evtnum; - } + inline void set_num(uint64_t evtnum) { m_evtnum = evtnum; } /*! \brief Get the number of the CPU where this event was captured. */ - inline uint16_t get_cpuid() const - { - return m_cpuid; - } + inline uint16_t get_cpuid() const { return m_cpuid; } - inline void set_cpuid(uint16_t v) - { - m_cpuid = v; - } + inline void set_cpuid(uint16_t v) { m_cpuid = v; } /*! \brief Get the event type. \note For a list of event types, refer to \ref etypes. */ - virtual inline uint16_t get_type() const - { - return m_pevt->type; - } + virtual inline uint16_t get_type() const { return m_pevt->type; } /*! \brief Get the event source index, as in the positional order of used by the event's inspector event sources. Returns sinsp_no_event_source_idx if the event source is unknown. */ - inline size_t get_source_idx() const - { - return m_source_idx; - } + inline size_t get_source_idx() const { return m_source_idx; } - inline void set_source_idx(size_t v) - { - m_source_idx = v; - } + inline void set_source_idx(size_t v) { m_source_idx = v; } /*! \brief Get the event source name, as in the event's inspector event sources. Returns sinsp_no_event_source_name if the event source is unknown. */ - inline const char* get_source_name() const - { - return m_source_name; - } + inline const char* get_source_name() const { return m_source_name; } - inline void set_source_name(const char* v) - { - m_source_name = v; - } + inline void set_source_name(const char* v) { m_source_name = v; } /*! \brief Get the event info */ - inline const ppm_event_info* get_info() const - { - return m_info; - } + inline const ppm_event_info* get_info() const { return m_info; } - inline void set_info(const ppm_event_info* v) - { - m_info = v; - } + inline void set_info(const ppm_event_info* v) { m_info = v; } /*! \brief Get the event's flags. */ - inline ppm_event_flags get_info_flags() const - { - return m_info->flags; - } + inline ppm_event_flags get_info_flags() const { return m_info->flags; } /*! \brief Return the event direction: in or out. @@ -359,10 +306,7 @@ class SINSP_PUBLIC sinsp_evt \return The event timestamp, in nanoseconds from epoch */ - virtual inline uint64_t get_ts() const - { - return m_pevt->ts; - } + virtual inline uint64_t get_ts() const { return m_pevt->ts; } /*! \brief Return the event name string, e.g. 'open' or 'socket'. @@ -373,8 +317,7 @@ class SINSP_PUBLIC sinsp_evt \brief Return the event category. */ /// TODO: in the next future we need to rename this into `get_syscall_category_from_event` - inline ppm_event_category get_category() const - { + inline ppm_event_category get_category() const { /* Every event category is composed of 2 parts: * 1. The highest bits represent the event category: * - `EC_SYSCALL` @@ -410,30 +353,15 @@ class SINSP_PUBLIC sinsp_evt \note For events that are not I/O related, get_fd_info() returns NULL. */ - inline const sinsp_fdinfo* get_fd_info() const - { - return m_fdinfo; - } + inline const sinsp_fdinfo* get_fd_info() const { return m_fdinfo; } - inline sinsp_fdinfo* get_fd_info() - { - return m_fdinfo; - } + inline sinsp_fdinfo* get_fd_info() { return m_fdinfo; } - inline void set_fd_info(sinsp_fdinfo* v) - { - m_fdinfo = v; - } + inline void set_fd_info(sinsp_fdinfo* v) { m_fdinfo = v; } - inline bool fdinfo_name_changed() const - { - return m_fdinfo_name_changed; - } + inline bool fdinfo_name_changed() const { return m_fdinfo_name_changed; } - inline void set_fdinfo_name_changed(bool changed) - { - m_fdinfo_name_changed = changed; - } + inline void set_fdinfo_name_changed(bool changed) { m_fdinfo_name_changed = changed; } /*! \brief Return the number of the FD associated with this event. @@ -516,7 +444,7 @@ class SINSP_PUBLIC sinsp_evt \brief Returns true if this event represents a file open system call error, false otherwise. - Precondition: is_syscall_error() must return true. + Precondition: is_syscall_error() must return true. */ bool is_file_open_error() const; @@ -551,10 +479,11 @@ class SINSP_PUBLIC sinsp_evt /*! \param resolved_str [out] the string representation of the parameter */ - const char* get_param_value_str(std::string_view name, const char** resolved_str, param_fmt fmt = PF_NORMAL); + const char* get_param_value_str(std::string_view name, + const char** resolved_str, + param_fmt fmt = PF_NORMAL); - inline void init_keep_threadinfo() - { + inline void init_keep_threadinfo() { m_flags = EF_NONE; m_info = &(m_event_info_table[m_pevt->type]); m_fdinfo = NULL; @@ -564,8 +493,7 @@ class SINSP_PUBLIC sinsp_evt m_source_idx = sinsp_no_event_source_idx; m_source_name = sinsp_no_event_source_name; } - inline void init() - { + inline void init() { init_keep_threadinfo(); m_tinfo_ref.reset(); m_tinfo = NULL; @@ -573,10 +501,9 @@ class SINSP_PUBLIC sinsp_evt m_fdinfo_ref.reset(); m_fdinfo_name_changed = false; } - inline void init(uint8_t* evdata, uint16_t cpuid) - { + inline void init(uint8_t* evdata, uint16_t cpuid) { m_flags = EF_NONE; - m_pevt = (scap_evt *)evdata; + m_pevt = (scap_evt*)evdata; m_info = &(m_event_info_table[m_pevt->type]); m_tinfo_ref.reset(); m_tinfo = NULL; @@ -588,31 +515,26 @@ class SINSP_PUBLIC sinsp_evt m_source_idx = sinsp_no_event_source_idx; m_source_name = sinsp_no_event_source_name; } - inline void init(scap_evt *scap_event, - ppm_event_info * ppm_event, - sinsp_threadinfo *threadinfo, - sinsp_fdinfo *fdinfo) - { + inline void init(scap_evt* scap_event, + ppm_event_info* ppm_event, + sinsp_threadinfo* threadinfo, + sinsp_fdinfo* fdinfo) { m_pevt = scap_event; m_info = ppm_event; - m_tinfo_ref.reset(); // we don't own the threadinfo so don't try to manage its lifetime + m_tinfo_ref.reset(); // we don't own the threadinfo so don't try to manage its lifetime m_tinfo = threadinfo; m_tinfo_ref.reset(); m_fdinfo = fdinfo; m_source_idx = sinsp_no_event_source_idx; m_source_name = sinsp_no_event_source_name; } - inline void init(scap_evt* scap_event, - ppm_event_info* ppm_event, - int32_t errorcode) - { + inline void init(scap_evt* scap_event, ppm_event_info* ppm_event, int32_t errorcode) { m_pevt = scap_event; m_info = ppm_event; m_errorcode = errorcode; } - static std::unique_ptr from_scap_evt(std::unique_ptr scap_event) - { + static std::unique_ptr from_scap_evt(std::unique_ptr scap_event) { auto ret = std::make_unique(); auto evdata = scap_event.release(); ret->init(evdata, 0); @@ -620,8 +542,7 @@ class SINSP_PUBLIC sinsp_evt return ret; } - inline void load_params() - { + inline void load_params() { uint32_t j; struct scap_sized_buffer params[PPM_MAX_EVENT_PARAMS]; @@ -633,62 +554,58 @@ class SINSP_PUBLIC sinsp_evt const struct ppm_event_info* event_info = &m_event_info_table[m_pevt->type]; int param_type = 0; - for(j = 0; j < nparams; j++) - { + for(j = 0; j < nparams; j++) { /* Here we need to manage a particular case: - * - * - PT_CHARBUF - * - PT_FSRELPATH - * - PT_BYTEBUF - * - PT_BYTEBUF - * - * In the past these params could be `` or `(NULL)` or empty. - * Now they can be only empty! The ideal solution would be: - * params[i].buf = NULL; - * params[i].size = 0; - * - * The problem is that userspace is not - * able to manage `NULL` pointers... but it manages `` so we - * convert all these cases to `` when they are empty! - * - * If we read scap-files we could face `(NULL)` params, so also in - * this case we convert them to ``. - * - * To be honest there could be another corner case, but right now - * we don't have to manage it: - * - * - PT_SOCKADDR - * - PT_SOCKTUPLE - * - PT_FDLIST - * - * Could be empty, so we will have: - * params[i].buf = "pointer to the next param"; - * params[i].size = 0; - * - * However, as we said in the previous case, the ideal outcome would be: - * params[i].buf = NULL; - * params[i].size = 0; - * - * The difference with the previous case is that the userspace can manage - * these params when they have `params[i].size == 0`, so we don't have - * to use the `` workaround! We could also introduce the `NULL` and so - * put in place the ideal solution for this parameter, but before doing this - * we need to be sure that the userspace never tries to deference the pointer - * otherwise it will trigger a segmentation fault at run-time. So as a first - * step we would keep them as they are. - */ + * + * - PT_CHARBUF + * - PT_FSRELPATH + * - PT_BYTEBUF + * - PT_BYTEBUF + * + * In the past these params could be `` or `(NULL)` or empty. + * Now they can be only empty! The ideal solution would be: + * params[i].buf = NULL; + * params[i].size = 0; + * + * The problem is that userspace is not + * able to manage `NULL` pointers... but it manages `` so we + * convert all these cases to `` when they are empty! + * + * If we read scap-files we could face `(NULL)` params, so also in + * this case we convert them to ``. + * + * To be honest there could be another corner case, but right now + * we don't have to manage it: + * + * - PT_SOCKADDR + * - PT_SOCKTUPLE + * - PT_FDLIST + * + * Could be empty, so we will have: + * params[i].buf = "pointer to the next param"; + * params[i].size = 0; + * + * However, as we said in the previous case, the ideal outcome would be: + * params[i].buf = NULL; + * params[i].size = 0; + * + * The difference with the previous case is that the userspace can manage + * these params when they have `params[i].size == 0`, so we don't have + * to use the `` workaround! We could also introduce the `NULL` and so + * put in place the ideal solution for this parameter, but before doing this + * we need to be sure that the userspace never tries to deference the pointer + * otherwise it will trigger a segmentation fault at run-time. So as a first + * step we would keep them as they are. + */ param_type = event_info->params[j].type; - if((param_type == PT_CHARBUF || - param_type == PT_FSRELPATH || - param_type == PT_FSPATH) - && - (params[j].size == 0 || - (params[j].size == 7 && strncmp((char*)params[j].buf, "(NULL)", 7) == 0))) - { + if((param_type == PT_CHARBUF || param_type == PT_FSRELPATH || + param_type == PT_FSPATH) && + (params[j].size == 0 || + (params[j].size == 7 && strncmp((char*)params[j].buf, "(NULL)", 7) == 0))) { /* Overwrite the value and the size of the param. - * 5 = strlen("") + `\0`. - */ + * 5 = strlen("") + `\0`. + */ params[j].buf = (void*)""; params[j].size = 5; } @@ -699,7 +616,10 @@ class SINSP_PUBLIC sinsp_evt std::string get_param_value_str(uint32_t id, bool resolved); char* render_fd(int64_t fd, const char** resolved_str, sinsp_evt::param_fmt fmt); - int render_fd_json(Json::Value *ret, int64_t fd, const char** resolved_str, sinsp_evt::param_fmt fmt); + int render_fd_json(Json::Value* ret, + int64_t fd, + const char** resolved_str, + sinsp_evt::param_fmt fmt); inline uint32_t get_dump_flags() const { return m_dump_flags; } inline void set_dump_flags(uint32_t v) { m_dump_flags = v; } static bool clone_event(sinsp_evt& dest, const sinsp_evt& src); @@ -709,133 +629,62 @@ class SINSP_PUBLIC sinsp_evt // Save important values from the provided enter event. They // are accessible from get_enter_evt_param(). void save_enter_event_params(sinsp_evt* enter_evt); - std::optional> get_enter_evt_param(const std::string& param) const; + std::optional> get_enter_evt_param( + const std::string& param) const; - inline const scap_evt* get_scap_evt() const - { - return m_pevt; - } + inline const scap_evt* get_scap_evt() const { return m_pevt; } - inline scap_evt* get_scap_evt() - { - return m_pevt; - } + inline scap_evt* get_scap_evt() { return m_pevt; } - inline void set_scap_evt(scap_evt* v) - { - m_pevt = v; - } + inline void set_scap_evt(scap_evt* v) { m_pevt = v; } - inline const char* get_scap_evt_storage() const - { - return m_pevt_storage; - } + inline const char* get_scap_evt_storage() const { return m_pevt_storage; } - inline char* get_scap_evt_storage() - { - return m_pevt_storage; - } + inline char* get_scap_evt_storage() { return m_pevt_storage; } - inline void set_scap_evt_storage(char* v) - { - m_pevt_storage = v; - } + inline void set_scap_evt_storage(char* v) { m_pevt_storage = v; } - inline uint32_t get_flags() const - { - return m_flags; - } + inline uint32_t get_flags() const { return m_flags; } - inline void set_flags(uint32_t v) - { - m_flags = v; - } + inline void set_flags(uint32_t v) { m_flags = v; } - inline int32_t get_rawbuf_str_len() const - { - return m_rawbuf_str_len; - } + inline int32_t get_rawbuf_str_len() const { return m_rawbuf_str_len; } - inline void set_rawbuf_str_len(int32_t v) - { - m_rawbuf_str_len = v; - } + inline void set_rawbuf_str_len(int32_t v) { m_rawbuf_str_len = v; } - inline void set_filtered_out(bool v) - { - m_filtered_out = v; - } + inline void set_filtered_out(bool v) { m_filtered_out = v; } - inline std::shared_ptr get_tinfo_ref() const - { - return m_tinfo_ref; - } + inline std::shared_ptr get_tinfo_ref() const { return m_tinfo_ref; } - inline const std::shared_ptr& get_tinfo_ref() - { - return m_tinfo_ref; - } + inline const std::shared_ptr& get_tinfo_ref() { return m_tinfo_ref; } - inline void set_tinfo_ref(const std::shared_ptr& v) - { - m_tinfo_ref = v; - } + inline void set_tinfo_ref(const std::shared_ptr& v) { m_tinfo_ref = v; } - inline const sinsp_threadinfo* get_tinfo() const - { - return m_tinfo; - } + inline const sinsp_threadinfo* get_tinfo() const { return m_tinfo; } - inline sinsp_threadinfo* get_tinfo() - { - return m_tinfo; - } + inline sinsp_threadinfo* get_tinfo() { return m_tinfo; } - inline void set_tinfo(sinsp_threadinfo* v) - { - m_tinfo = v; - } + inline void set_tinfo(sinsp_threadinfo* v) { m_tinfo = v; } - inline std::shared_ptr get_fdinfo_ref() const - { - return m_fdinfo_ref; - } + inline std::shared_ptr get_fdinfo_ref() const { return m_fdinfo_ref; } - inline const std::shared_ptr& get_fdinfo_ref() - { - return m_fdinfo_ref; - } + inline const std::shared_ptr& get_fdinfo_ref() { return m_fdinfo_ref; } - inline void set_fdinfo_ref(const std::shared_ptr& v) - { - m_fdinfo_ref = v; - } + inline void set_fdinfo_ref(const std::shared_ptr& v) { m_fdinfo_ref = v; } - inline const std::vector& get_paramstr_storage() const - { - return m_paramstr_storage; - } + inline const std::vector& get_paramstr_storage() const { return m_paramstr_storage; } - inline std::vector& get_paramstr_storage() - { - return m_paramstr_storage; - } + inline std::vector& get_paramstr_storage() { return m_paramstr_storage; } - inline const std::vector& get_params() const - { - return m_params; - } + inline const std::vector& get_params() const { return m_params; } - inline std::vector& get_params() - { - return m_params; - } + inline std::vector& get_params() { return m_params; } private: - sinsp* m_inspector; scap_evt* m_pevt; - char *m_pevt_storage; // In some cases an alternate buffer is used to hold m_pevt. This points to that storage. + char* m_pevt_storage; // In some cases an alternate buffer is used to hold m_pevt. This points + // to that storage. uint16_t m_cpuid; uint64_t m_evtnum; uint32_t m_flags; @@ -847,8 +696,8 @@ class SINSP_PUBLIC sinsp_evt std::vector m_paramstr_storage; std::vector m_resolved_paramstr_storage; - // reference to keep threadinfo alive. currently only used for synthetic container event thread info - // it should either be null, or point to the same place as m_tinfo + // reference to keep threadinfo alive. currently only used for synthetic container event thread + // info it should either be null, or point to the same place as m_tinfo std::shared_ptr m_tinfo_ref; sinsp_threadinfo* m_tinfo; sinsp_fdinfo* m_fdinfo; @@ -872,6 +721,10 @@ class SINSP_PUBLIC sinsp_evt const char* m_source_name; }; -uint32_t binary_buffer_to_string(char *dst, const char *src, uint32_t dstlen, uint32_t srclen, sinsp_evt::param_fmt fmt); +uint32_t binary_buffer_to_string(char* dst, + const char* src, + uint32_t dstlen, + uint32_t srclen, + sinsp_evt::param_fmt fmt); /*@}*/ diff --git a/userspace/libsinsp/eventformatter.cpp b/userspace/libsinsp/eventformatter.cpp index d1a2132ff6..e7eb2d4e35 100644 --- a/userspace/libsinsp/eventformatter.cpp +++ b/userspace/libsinsp/eventformatter.cpp @@ -23,37 +23,30 @@ limitations under the License. static constexpr const char* s_not_available_str = ""; -sinsp_evt_formatter::sinsp_evt_formatter(sinsp* inspector, - filter_check_list &available_checks) - : m_inspector(inspector), - m_available_checks(available_checks) -{ -} +sinsp_evt_formatter::sinsp_evt_formatter(sinsp* inspector, filter_check_list& available_checks): + m_inspector(inspector), + m_available_checks(available_checks) {} sinsp_evt_formatter::sinsp_evt_formatter(sinsp* inspector, - const std::string& fmt, - filter_check_list &available_checks) - : m_inspector(inspector), - m_available_checks(available_checks) -{ + const std::string& fmt, + filter_check_list& available_checks): + m_inspector(inspector), + m_available_checks(available_checks) { output_format of = sinsp_evt_formatter::OF_NORMAL; - if(m_inspector->get_buffer_format() == sinsp_evt::PF_JSON - || m_inspector->get_buffer_format() == sinsp_evt::PF_JSONEOLS - || m_inspector->get_buffer_format() == sinsp_evt::PF_JSONHEX - || m_inspector->get_buffer_format() == sinsp_evt::PF_JSONHEXASCII - || m_inspector->get_buffer_format() == sinsp_evt::PF_JSONBASE64) - { + if(m_inspector->get_buffer_format() == sinsp_evt::PF_JSON || + m_inspector->get_buffer_format() == sinsp_evt::PF_JSONEOLS || + m_inspector->get_buffer_format() == sinsp_evt::PF_JSONHEX || + m_inspector->get_buffer_format() == sinsp_evt::PF_JSONHEXASCII || + m_inspector->get_buffer_format() == sinsp_evt::PF_JSONBASE64) { of = sinsp_evt_formatter::OF_JSON; } set_format(of, fmt); } -void sinsp_evt_formatter::set_format(output_format of, const std::string& fmt) -{ - if(fmt.empty()) - { +void sinsp_evt_formatter::set_format(output_format of, const std::string& fmt) { + if(fmt.empty()) { throw sinsp_exception("empty formatting token"); } @@ -65,13 +58,10 @@ void sinsp_evt_formatter::set_format(output_format of, const std::string& fmt) // the string even when not all the values it specifies are set. // std::string lfmt(fmt); - if(lfmt[0] == '*') - { + if(lfmt[0] == '*') { m_require_all_values = false; lfmt.erase(0, 1); - } - else - { + } else { m_require_all_values = true; } @@ -83,50 +73,42 @@ void sinsp_evt_formatter::set_format(output_format of, const std::string& fmt) uint32_t lfmtlen = (uint32_t)lfmt.length(); uint32_t last_nontoken_str_start = 0; uint32_t j = 0; - for(j = 0; j < lfmtlen; j++) - { - if(cfmt[j] == '%') - { + for(j = 0; j < lfmtlen; j++) { + if(cfmt[j] == '%') { int toklen = 0; - if(last_nontoken_str_start != j) - { - auto newtkn = std::make_shared(lfmt.substr(last_nontoken_str_start, j - last_nontoken_str_start)); + if(last_nontoken_str_start != j) { + auto newtkn = std::make_shared( + lfmt.substr(last_nontoken_str_start, j - last_nontoken_str_start)); m_output_tokens.emplace_back(newtkn); m_output_tokenlens.push_back(0); } - if(j == lfmtlen - 1) - { + if(j == lfmtlen - 1) { throw sinsp_exception("invalid formatting syntax: formatting cannot end with a %"); } // - // If the field specifier starts with a number, it means that we have a length transformer + // If the field specifier starts with a number, it means that we have a length + // transformer // - if(isdigit(cfmt[j + 1])) - { + if(isdigit(cfmt[j + 1])) { // // Parse the token length // - sscanf(cfmt+ j + 1, "%d", &toklen); + sscanf(cfmt + j + 1, "%d", &toklen); // // Advance until the beginning of the field name // - while(true) - { - if(j == lfmtlen - 1) - { - throw sinsp_exception("invalid formatting syntax: formatting cannot end with a number"); - } - else if(isdigit(cfmt[j + 1])) - { + while(true) { + if(j == lfmtlen - 1) { + throw sinsp_exception( + "invalid formatting syntax: formatting cannot end with a number"); + } else if(isdigit(cfmt[j + 1])) { j++; continue; - } - else - { + } else { break; } } @@ -137,33 +119,28 @@ void sinsp_evt_formatter::set_format(output_format of, const std::string& fmt) int msize = 0; const char* tstart = cfmt + j + 1; std::vector transformers; - while(true) - { + while(true) { auto prev_size = msize; - for (const auto& tr : libsinsp::filter::parser::supported_field_transformers()) - { - if ((j + 1 + tr.size() + 1) < lfmtlen - && tstart[msize + tr.size()] == '(' - && !strncmp(tstart + msize, tr.c_str(), tr.size())) - { + for(const auto& tr : libsinsp::filter::parser::supported_field_transformers()) { + if((j + 1 + tr.size() + 1) < lfmtlen && tstart[msize + tr.size()] == '(' && + !strncmp(tstart + msize, tr.c_str(), tr.size())) { transformers.emplace_back(filter_transformer_from_str(tr)); - msize += tr.size() + 1; // count '(' + msize += tr.size() + 1; // count '(' j += tr.size() + 1; } } // note: no whitespace is allowed between transformers - if (prev_size == msize) - { + if(prev_size == msize) { break; } } // read field token and make sure it's a valid one const char* fstart = cfmt + j + 1; - chk = m_available_checks.new_filter_check_from_fldname( - std::string_view(fstart), m_inspector, false); - if(chk == nullptr) - { + chk = m_available_checks.new_filter_check_from_fldname(std::string_view(fstart), + m_inspector, + false); + if(chk == nullptr) { throw sinsp_exception("invalid formatting token " + std::string(fstart)); } uint32_t fsize = chk->parse_field_name(fstart, true, false); @@ -175,29 +152,25 @@ void sinsp_evt_formatter::set_format(output_format of, const std::string& fmt) // if we have transformers, create a copy of the field and use it // both for output substitution and for key->value resolution - if (!transformers.empty()) - { - chk = m_available_checks.new_filter_check_from_fldname( - fstart, m_inspector, false); - if(chk == nullptr) - { + if(!transformers.empty()) { + chk = m_available_checks.new_filter_check_from_fldname(fstart, m_inspector, false); + if(chk == nullptr) { throw sinsp_exception("invalid formatting token " + std::string(fstart)); } chk->parse_field_name(fstart, true, false); // apply all transformers and pop back their ')' enclosing token // note: we apply transformers in reserve order to preserve their semantics - for (auto rit = transformers.rbegin(); rit != transformers.rend(); ++rit) - { + for(auto rit = transformers.rbegin(); rit != transformers.rend(); ++rit) { chk->add_transformer(*rit); // note: no whitespace is allowed between transformer enclosing - if (j + 1 >= lfmtlen || cfmt[j + 1] != ')') - { - throw sinsp_exception("missing closing transformer parenthesis: " + std::string(cfmt + j)); + if(j + 1 >= lfmtlen || cfmt[j + 1] != ')') { + throw sinsp_exception("missing closing transformer parenthesis: " + + std::string(cfmt + j)); } j++; - msize++; // count ')' + msize++; // count ')' } // when requested to do so, we'll resolve the field with transformers @@ -213,28 +186,24 @@ void sinsp_evt_formatter::set_format(output_format of, const std::string& fmt) } } - if(last_nontoken_str_start != j) - { - auto chk = std::make_shared(lfmt.substr(last_nontoken_str_start, j - last_nontoken_str_start)); + if(last_nontoken_str_start != j) { + auto chk = std::make_shared( + lfmt.substr(last_nontoken_str_start, j - last_nontoken_str_start)); m_output_tokens.emplace_back(chk); m_output_tokenlens.push_back(0); } } -bool sinsp_evt_formatter::resolve_tokens(sinsp_evt *evt, std::map& values) -{ - for(const auto& t : m_resolution_tokens) - { - if (t.has_transformers && !m_resolve_transformed_fields) - { +bool sinsp_evt_formatter::resolve_tokens(sinsp_evt* evt, + std::map& values) { + for(const auto& t : m_resolution_tokens) { + if(t.has_transformers && !m_resolve_transformed_fields) { continue; } const char* str = t.token->tostring(evt); - if(str == NULL) - { - if(m_require_all_values) - { + if(str == NULL) { + if(m_require_all_values) { return false; } @@ -245,42 +214,36 @@ bool sinsp_evt_formatter::resolve_tokens(sinsp_evt *evt, std::map &fields) -{ +bool sinsp_evt_formatter::get_field_values(sinsp_evt* evt, + std::map& fields) { return resolve_tokens(evt, fields); } -void sinsp_evt_formatter::get_field_names(std::vector &fields) -{ - for(const auto& t : m_resolution_tokens) - { +void sinsp_evt_formatter::get_field_names(std::vector& fields) { + for(const auto& t : m_resolution_tokens) { fields.emplace_back(t.name); } } -sinsp_evt_formatter::output_format sinsp_evt_formatter::get_output_format() -{ +sinsp_evt_formatter::output_format sinsp_evt_formatter::get_output_format() { return m_output_format; } -bool sinsp_evt_formatter::tostring_withformat(sinsp_evt* evt, std::string &output, output_format of) -{ +bool sinsp_evt_formatter::tostring_withformat(sinsp_evt* evt, + std::string& output, + output_format of) { output.clear(); - if(of == OF_JSON) - { + if(of == OF_JSON) { bool retval = true; - for (const auto& t : m_resolution_tokens) - { - if (t.has_transformers && !m_resolve_transformed_fields) - { + for(const auto& t : m_resolution_tokens) { + if(t.has_transformers && !m_resolve_transformed_fields) { // always skip keys with transformers here // todo!: is this the desired behavior? continue; } Json::Value json_value = t.token->tojson(evt); - if(json_value == Json::nullValue && m_require_all_values) - { + if(json_value == Json::nullValue && m_require_all_values) { retval = false; break; } @@ -292,30 +255,22 @@ bool sinsp_evt_formatter::tostring_withformat(sinsp_evt* evt, std::string &outpu } ASSERT(m_output_tokenlens.size() == m_output_tokens.size()); - for(size_t j = 0; j < m_output_tokens.size(); j++) - { + for(size_t j = 0; j < m_output_tokens.size(); j++) { const char* str = m_output_tokens[j]->tostring(evt); - if(str == NULL) - { - if(m_require_all_values) - { + if(str == NULL) { + if(m_require_all_values) { return false; - } - else - { + } else { str = s_not_available_str; } } uint32_t tks = m_output_tokenlens[j]; - if(tks != 0) - { + if(tks != 0) { std::string sstr(str); sstr.resize(tks, ' '); output += sstr; - } - else - { + } else { output += str; } } @@ -323,31 +278,27 @@ bool sinsp_evt_formatter::tostring_withformat(sinsp_evt* evt, std::string &outpu return true; } -bool sinsp_evt_formatter::tostring(sinsp_evt* evt, std::string& res) -{ +bool sinsp_evt_formatter::tostring(sinsp_evt* evt, std::string& res) { return tostring_withformat(evt, res, m_output_format); } -sinsp_evt_formatter_factory::sinsp_evt_formatter_factory(sinsp *inspector, filter_check_list &available_checks) - : m_inspector(inspector), - m_available_checks(available_checks), - m_output_format(sinsp_evt_formatter::OF_NORMAL) -{ -} +sinsp_evt_formatter_factory::sinsp_evt_formatter_factory(sinsp* inspector, + filter_check_list& available_checks): + m_inspector(inspector), + m_available_checks(available_checks), + m_output_format(sinsp_evt_formatter::OF_NORMAL) {} -void sinsp_evt_formatter_factory::set_output_format(sinsp_evt_formatter::output_format of) -{ +void sinsp_evt_formatter_factory::set_output_format(sinsp_evt_formatter::output_format of) { m_formatters.clear(); m_output_format = of; } -std::shared_ptr sinsp_evt_formatter_factory::create_formatter(const std::string &format) -{ +std::shared_ptr sinsp_evt_formatter_factory::create_formatter( + const std::string& format) { auto it = m_formatters.find(format); - if (it != m_formatters.end()) - { + if(it != m_formatters.end()) { return it->second; } diff --git a/userspace/libsinsp/eventformatter.h b/userspace/libsinsp/eventformatter.h index 21ed0c0bf2..3c29167bba 100644 --- a/userspace/libsinsp/eventformatter.h +++ b/userspace/libsinsp/eventformatter.h @@ -35,13 +35,9 @@ limitations under the License. This class can be used to format an event into a string, based on an arbitrary format. */ -class SINSP_PUBLIC sinsp_evt_formatter -{ +class SINSP_PUBLIC sinsp_evt_formatter { public: - enum output_format { - OF_NORMAL = 0, - OF_JSON = 1 - }; + enum output_format { OF_NORMAL = 0, OF_JSON = 1 }; /*! \brief Constructs a formatter. @@ -52,9 +48,11 @@ class SINSP_PUBLIC sinsp_evt_formatter as the one of the output in Falco rules, so refer to the Falco documentation for details. */ - sinsp_evt_formatter(sinsp* inspector, filter_check_list &available_checks); + sinsp_evt_formatter(sinsp *inspector, filter_check_list &available_checks); - sinsp_evt_formatter(sinsp* inspector, const std::string& fmt, filter_check_list &available_checks); + sinsp_evt_formatter(sinsp *inspector, + const std::string &fmt, + filter_check_list &available_checks); virtual ~sinsp_evt_formatter() = default; @@ -67,9 +65,9 @@ class SINSP_PUBLIC sinsp_evt_formatter \return true if all the tokens can be retrieved successfully, false otherwise. */ - bool resolve_tokens(sinsp_evt *evt, std::map& values); + bool resolve_tokens(sinsp_evt *evt, std::map &values); - virtual void set_format(output_format of, const std::string& fmt); + virtual void set_format(output_format of, const std::string &fmt); // For compatibility with sinsp_filter_factory // interface. It just calls resolve_tokens(). @@ -88,17 +86,15 @@ class SINSP_PUBLIC sinsp_evt_formatter \return true if the string should be shown (based on the initial *), false otherwise. */ - inline bool tostring(sinsp_evt* evt, std::string* res) - { - if (!res) - { + inline bool tostring(sinsp_evt *evt, std::string *res) { + if(!res) { return false; } return tostring(evt, *res); } - virtual bool tostring(sinsp_evt* evt, std::string &output); + virtual bool tostring(sinsp_evt *evt, std::string &output); - virtual bool tostring_withformat(sinsp_evt* evt, std::string &output, output_format of); + virtual bool tostring_withformat(sinsp_evt *evt, std::string &output, output_format of); /** * \brief If true, when resolving tokens in key -> value mappings (e.g. @@ -106,28 +102,23 @@ class SINSP_PUBLIC sinsp_evt_formatter * will include fields with their applied transformers. The version of fields * with no transformers will be included in results in any case regardless * of this property. - */ - inline bool get_resolve_transformed_fields() const - { - return m_resolve_transformed_fields; - } + */ + inline bool get_resolve_transformed_fields() const { return m_resolve_transformed_fields; } - inline void set_resolve_transformed_fields(bool v) - { - m_resolve_transformed_fields = v; - } + inline void set_resolve_transformed_fields(bool v) { m_resolve_transformed_fields = v; } private: using token_t = std::shared_ptr; - struct resolution_token - { + struct resolution_token { std::string name; token_t token; bool has_transformers = false; - resolution_token(const std::string& n, token_t t, bool h) - : name(n), token(std::move(t)), has_transformers(h) { } + resolution_token(const std::string &n, token_t t, bool h): + name(n), + token(std::move(t)), + has_transformers(h) {} }; output_format m_output_format; @@ -137,7 +128,7 @@ class SINSP_PUBLIC sinsp_evt_formatter std::vector m_output_tokens; std::vector m_output_tokenlens; std::vector m_resolution_tokens; - sinsp* m_inspector = nullptr; + sinsp *m_inspector = nullptr; filter_check_list &m_available_checks; bool m_require_all_values = false; bool m_resolve_transformed_fields = false; @@ -146,8 +137,7 @@ class SINSP_PUBLIC sinsp_evt_formatter Json::FastWriter m_writer; }; -class sinsp_evt_formatter_factory -{ +class sinsp_evt_formatter_factory { public: sinsp_evt_formatter_factory(sinsp *inspector, filter_check_list &available_checks); virtual ~sinsp_evt_formatter_factory() = default; @@ -157,7 +147,6 @@ class sinsp_evt_formatter_factory virtual std::shared_ptr create_formatter(const std::string &format); protected: - // Maps from output string to formatter std::map> m_formatters; diff --git a/userspace/libsinsp/events/sinsp_events.cpp b/userspace/libsinsp/events/sinsp_events.cpp index 54a4321fa1..bed279f220 100644 --- a/userspace/libsinsp/events/sinsp_events.cpp +++ b/userspace/libsinsp/events/sinsp_events.cpp @@ -1,63 +1,54 @@ #include #include -const ppm_event_info* libsinsp::events::info(ppm_event_code event_type) -{ +const ppm_event_info* libsinsp::events::info(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); - return scap_get_event_info_table() + ((size_t) event_type); + return scap_get_event_info_table() + ((size_t)event_type); } -bool libsinsp::events::is_generic(ppm_event_code event_type) -{ +bool libsinsp::events::is_generic(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); - return event_type == ppm_event_code::PPME_GENERIC_E - || event_type == ppm_event_code::PPME_GENERIC_X; + return event_type == ppm_event_code::PPME_GENERIC_E || + event_type == ppm_event_code::PPME_GENERIC_X; } -bool libsinsp::events::is_unused_event(ppm_event_code event_type) -{ +bool libsinsp::events::is_unused_event(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_flags flags = scap_get_event_info_table()[event_type].flags; return (flags & EF_UNUSED); } -bool libsinsp::events::is_skip_parse_reset_event(ppm_event_code event_type) -{ +bool libsinsp::events::is_skip_parse_reset_event(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_flags flags = scap_get_event_info_table()[event_type].flags; return (flags & EF_SKIPPARSERESET); } -bool libsinsp::events::is_old_version_event(ppm_event_code event_type) -{ +bool libsinsp::events::is_old_version_event(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_flags flags = scap_get_event_info_table()[event_type].flags; return (flags & EF_OLD_VERSION); } -bool libsinsp::events::is_syscall_event(ppm_event_code event_type) -{ +bool libsinsp::events::is_syscall_event(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_category category = scap_get_event_info_table()[event_type].category; return (category & EC_SYSCALL); } -bool libsinsp::events::is_tracepoint_event(ppm_event_code event_type) -{ +bool libsinsp::events::is_tracepoint_event(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_category category = scap_get_event_info_table()[event_type].category; return (category & EC_TRACEPOINT); } -bool libsinsp::events::is_metaevent(ppm_event_code event_type) -{ +bool libsinsp::events::is_metaevent(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_category category = scap_get_event_info_table()[event_type].category; return (category & EC_METAEVENT); } -bool libsinsp::events::is_unknown_event(ppm_event_code event_type) -{ +bool libsinsp::events::is_unknown_event(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_category category = scap_get_event_info_table()[event_type].category; /* Please note this is not an `&` but an `==` if one event has @@ -66,32 +57,30 @@ bool libsinsp::events::is_unknown_event(ppm_event_code event_type) return (category == EC_UNKNOWN); } -bool libsinsp::events::is_plugin_event(ppm_event_code event_type) -{ +bool libsinsp::events::is_plugin_event(ppm_event_code event_type) { ASSERT(event_type < PPM_EVENT_MAX); ppm_event_category category = scap_get_event_info_table()[event_type].category; return (category & EC_PLUGIN); } -std::unordered_set libsinsp::events::event_set_to_names(const libsinsp::events::set& events_set, bool resolve_generic) -{ +std::unordered_set libsinsp::events::event_set_to_names( + const libsinsp::events::set& events_set, + bool resolve_generic) { bool resolved_generic = false; std::unordered_set events_names_set; - for (const auto& ev : events_set) - { - if (libsinsp::events::is_generic(ev)) - { - if (resolve_generic && !resolved_generic) - { - /* note: using existing ppm sc APIs and generic set operations to minimize new logic that requires maintenance beyond what we already have. */ - auto sc_set = libsinsp::events::event_set_to_sc_set(libsinsp::events::set{PPME_GENERIC_E, PPME_GENERIC_X}); - events_names_set = unordered_set_union(libsinsp::events::sc_set_to_sc_names(sc_set), events_names_set); - events_names_set.erase("unknown"); // not needed + for(const auto& ev : events_set) { + if(libsinsp::events::is_generic(ev)) { + if(resolve_generic && !resolved_generic) { + /* note: using existing ppm sc APIs and generic set operations to minimize new logic + * that requires maintenance beyond what we already have. */ + auto sc_set = libsinsp::events::event_set_to_sc_set( + libsinsp::events::set{PPME_GENERIC_E, PPME_GENERIC_X}); + events_names_set = unordered_set_union(libsinsp::events::sc_set_to_sc_names(sc_set), + events_names_set); + events_names_set.erase("unknown"); // not needed resolved_generic = true; } - } - else - { + } else { events_names_set.insert(scap_get_event_info_table()[ev].name); } } @@ -99,17 +88,15 @@ std::unordered_set libsinsp::events::event_set_to_names(const libsi } // todo(jasondellaluce): think about how we can handle well PPME_ASYNCEVENT_E -libsinsp::events::set libsinsp::events::names_to_event_set(const std::unordered_set& events) -{ +libsinsp::events::set libsinsp::events::names_to_event_set( + const std::unordered_set& events) { std::unordered_set remaining_events = events; libsinsp::events::set ppm_event_set; // Main loop, on events (ie: non generic events) - for (int ppm_ev = 2; ppm_ev < PPM_EVENT_MAX; ++ppm_ev) - { + for(int ppm_ev = 2; ppm_ev < PPM_EVENT_MAX; ++ppm_ev) { const char* ppm_ev_name = scap_get_event_info_table()[ppm_ev].name; - if (events.find(ppm_ev_name) != events.end()) - { + if(events.find(ppm_ev_name) != events.end()) { ppm_event_set.insert((ppm_event_code)ppm_ev); remaining_events.erase(ppm_ev_name); } @@ -118,14 +105,11 @@ libsinsp::events::set libsinsp::events::names_to_event_set(const // Only if there are some leftover events: // try to find a ppm_sc name that matches the event, // to eventually enable generic events too! - if (!remaining_events.empty()) - { + if(!remaining_events.empty()) { // Secondary loop, on syscalls and remaining events - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ++ppm_sc) - { + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ++ppm_sc) { const char* ppm_sc_name = scap_get_ppm_sc_name((ppm_sc_code)ppm_sc); - if(remaining_events.find(ppm_sc_name) != remaining_events.end()) - { + if(remaining_events.find(ppm_sc_name) != remaining_events.end()) { ppm_event_set.insert(PPME_GENERIC_E); ppm_event_set.insert(PPME_GENERIC_X); break; @@ -135,31 +119,25 @@ libsinsp::events::set libsinsp::events::names_to_event_set(const return ppm_event_set; } -libsinsp::events::set libsinsp::events::all_event_set() -{ +libsinsp::events::set libsinsp::events::all_event_set() { static libsinsp::events::set ppm_event_set; - if (ppm_event_set.empty()) - { - for(uint32_t ppm_ev = 0; ppm_ev < PPM_EVENT_MAX; ppm_ev++) - { + if(ppm_event_set.empty()) { + for(uint32_t ppm_ev = 0; ppm_ev < PPM_EVENT_MAX; ppm_ev++) { ppm_event_set.insert((ppm_event_code)ppm_ev); } } return ppm_event_set; } -libsinsp::events::set libsinsp::events::event_set_to_sc_set(const set& events_of_interest) -{ +libsinsp::events::set libsinsp::events::event_set_to_sc_set( + const set& events_of_interest) { libsinsp::events::set ppm_sc_set; std::vector sc_vec(PPM_SC_MAX); - if(scap_get_ppm_sc_from_events(events_of_interest.data(), sc_vec.data()) != SCAP_SUCCESS) - { + if(scap_get_ppm_sc_from_events(events_of_interest.data(), sc_vec.data()) != SCAP_SUCCESS) { throw sinsp_exception("`ppm_sc_set` or `events_array` is an unexpected NULL vector!"); } - for (int i = 0; i < PPM_SC_MAX; i++) - { - if (sc_vec[i]) - { + for(int i = 0; i < PPM_SC_MAX; i++) { + if(sc_vec[i]) { ppm_sc_set.insert((ppm_sc_code)i); } } @@ -167,11 +145,9 @@ libsinsp::events::set libsinsp::events::event_set_to_sc_set(const s } /// todo(@Andreagit97): we need to decide if we want to keep this API -libsinsp::events::set libsinsp::events::sinsp_state_event_set() -{ +libsinsp::events::set libsinsp::events::sinsp_state_event_set() { static libsinsp::events::set ppm_event_info_of_interest; - if (ppm_event_info_of_interest.empty()) - { + if(ppm_event_info_of_interest.empty()) { ppm_event_info_of_interest = sc_set_to_event_set(sinsp_state_sc_set()); /* * Fill-up the set of event infos of interest. @@ -179,16 +155,13 @@ libsinsp::events::set libsinsp::events::sinsp_state_event_set() * e.g. container * Skip generic events. */ - for(uint32_t ev = 2; ev < PPM_EVENT_MAX; ev++) - { - if(!libsinsp::events::is_unused_event((ppm_event_code)ev) - && !libsinsp::events::is_unknown_event((ppm_event_code)ev)) - { + for(uint32_t ev = 2; ev < PPM_EVENT_MAX; ev++) { + if(!libsinsp::events::is_unused_event((ppm_event_code)ev) && + !libsinsp::events::is_unknown_event((ppm_event_code)ev)) { /* So far we only covered syscalls, so we need to add * other kinds of metaevents. */ - if(libsinsp::events::is_metaevent((ppm_event_code)ev)) - { + if(libsinsp::events::is_metaevent((ppm_event_code)ev)) { ppm_event_info_of_interest.insert((ppm_event_code)ev); } } diff --git a/userspace/libsinsp/events/sinsp_events.h b/userspace/libsinsp/events/sinsp_events.h index 919fb7cce0..b99a7b55fd 100644 --- a/userspace/libsinsp/events/sinsp_events.h +++ b/userspace/libsinsp/events/sinsp_events.h @@ -29,101 +29,102 @@ namespace events { /*=============================== Events related ===============================*/ /** - * @brief Returns the static information of the event. - * - * @param event_type type of event we want to retrieve info for (must be less than `PPM_EVENT_MAX`) - * @return const ppm_event_info* the info entry of the event. + * @brief Returns the static information of the event. + * + * @param event_type type of event we want to retrieve info for (must be less than `PPM_EVENT_MAX`) + * @return const ppm_event_info* the info entry of the event. */ const ppm_event_info* info(ppm_event_code event_type); /** - * @brief Return true if the event is generic. - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type is generic. + * @brief Return true if the event is generic. + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type is generic. */ bool is_generic(ppm_event_code event_type); /** - * @brief If the event type has one of the following flags return true: - * - `EF_UNUSED` - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has at least one of these flags. + * @brief If the event type has one of the following flags return true: + * - `EF_UNUSED` + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has at least one of these flags. */ bool is_unused_event(ppm_event_code event_type); /** - * @brief If the event type has one of the following flags return true: - * - `EF_SKIPPARSERESET` - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has at least one of these flags. + * @brief If the event type has one of the following flags return true: + * - `EF_SKIPPARSERESET` + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has at least one of these flags. */ bool is_skip_parse_reset_event(ppm_event_code event_type); /** - * @brief Return true if the event has the `EF_OLD_VERSION` flag - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has the `EF_OLD_VERSION` flag. + * @brief Return true if the event has the `EF_OLD_VERSION` flag + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has the `EF_OLD_VERSION` flag. */ bool is_old_version_event(ppm_event_code event_type); /** - * @brief Return true if the event belongs to the `EC_SYSCALL` category - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has the `EC_SYSCALL` category. + * @brief Return true if the event belongs to the `EC_SYSCALL` category + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has the `EC_SYSCALL` category. */ bool is_syscall_event(ppm_event_code event_type); /** - * @brief Return true if the event belongs to the `EC_TRACEPOINT` category - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has the `EC_TRACEPOINT` category. + * @brief Return true if the event belongs to the `EC_TRACEPOINT` category + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has the `EC_TRACEPOINT` category. */ bool is_tracepoint_event(ppm_event_code event_type); /** - * @brief Return true if the event belongs to the `EC_METAEVENT` category - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has the `EC_METAEVENT` category. + * @brief Return true if the event belongs to the `EC_METAEVENT` category + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has the `EC_METAEVENT` category. */ bool is_metaevent(ppm_event_code event_type); /** - * @brief Return true if the event belongs to the `EC_UNKNOWN` category - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has the `EC_UNKNOWN` category. + * @brief Return true if the event belongs to the `EC_UNKNOWN` category + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has the `EC_UNKNOWN` category. */ bool is_unknown_event(ppm_event_code event_type); /** - * @brief Return true if the event belongs to the `EC_PLUGIN` category - * - * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) - * @return true if the event type has the `EC_PLUGIN` category. + * @brief Return true if the event belongs to the `EC_PLUGIN` category + * + * @param event_type type of event we want to check (must be less than `PPM_EVENT_MAX`) + * @return true if the event type has the `EC_PLUGIN` category. */ bool is_plugin_event(ppm_event_code event_type); /*=============================== Events related ===============================*/ -/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) ===============================*/ +/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) + * ===============================*/ /*! - \brief Provide the minimum set of syscalls required by `libsinsp` state collection. - Each returned `ppm_sc` code is tagged with `EF_MODIFIES_STATE` in the event table. + \brief Provide the minimum set of syscalls required by `libsinsp` state collection. + Each returned `ppm_sc` code is tagged with `EF_MODIFIES_STATE` in the event table. - \note Ongoing research to document the influence of each `ppm_sc` on `libsinsp` state. - The returned set contains some `ppm_sc` codes belonging to `io_sc_set()`, it is up to the - client to analyze trade-offs and possibly remove some enforced `ppm_sc` codes. + \note Ongoing research to document the influence of each `ppm_sc` on `libsinsp` state. + The returned set contains some `ppm_sc` codes belonging to `io_sc_set()`, it is up to the + client to analyze trade-offs and possibly remove some enforced `ppm_sc` codes. - WARNING: Without merging your ppm_sc set with the one provided by this method, - we cannot guarantee that `libsinsp` state will always be up to date, or even work at all. + WARNING: Without merging your ppm_sc set with the one provided by this method, + we cannot guarantee that `libsinsp` state will always be up to date, or even work at all. */ set sinsp_state_sc_set(); @@ -196,45 +197,46 @@ set event_names_to_sc_set(const std::unordered_set& ev set sc_names_to_sc_set(const std::unordered_set& syscalls); /** - * @brief When you want to retrieve the events associated with a particular `ppm_sc` you have to - * pass a single-element set, with just the specific `ppm_sc`. On the other side, you want all the events - * associated with a set of `ppm_sc` you have to pass the entire set of `ppm_sc`. - * - * @param ppm_sc_set set of `ppm_sc` from which you want to obtain information - * @return set of events associated with the provided `ppm_sc` set. + * @brief When you want to retrieve the events associated with a particular `ppm_sc` you have to + * pass a single-element set, with just the specific `ppm_sc`. On the other side, you want all the + * events associated with a set of `ppm_sc` you have to pass the entire set of `ppm_sc`. + * + * @param ppm_sc_set set of `ppm_sc` from which you want to obtain information + * @return set of events associated with the provided `ppm_sc` set. */ -set sc_set_to_event_set(const set &ppm_sc_of_interest); +set sc_set_to_event_set(const set& ppm_sc_of_interest); /*! - * \brief [Experimental] - * Enforce minimum sinsp state `ppm_sc` set conditioned by filter `ppm_sc` set. - * - * Use Cases: - * - * (1) Resourceful minimal sinsp state enforcement. The driver only activates a set of `ppm_sc` - * that is needed based on the current `ppm_sc` configuration from filter(s). - * - * (2) "repair" a custom set of user defined `ppm_sc` to ensure the agent runs correctly. - * This setting is useful for cases where the end user takes advantage of complete default - * sinsp state enforcement override, but still would like to rely on some safety minimal sinsp - * state enforcement mechanisms. - * - * `sinsp_repair_state_sc_set` is a more resourceful alternative to the default `sinsp_state_sc_set` - * option as it takes the filter `ppm_sc` set into consideration when selecting the effective set of - * `ppm_sc` that needs to be activated in addition to the filter `ppm_sc` set. - * - * todo: possibly extend e2e tests. - * - * @param ppm_sc_set set of `ppm_sc` from filter(s) - * @return sinsp state compliant set of `ppm_sc` conditioned by set of `ppm_sc` from filter(s) - * -> the returned set includes the set of `ppm_sc` from filter(s) -*/ + * \brief [Experimental] + * Enforce minimum sinsp state `ppm_sc` set conditioned by filter `ppm_sc` set. + * + * Use Cases: + * + * (1) Resourceful minimal sinsp state enforcement. The driver only activates a set of `ppm_sc` + * that is needed based on the current `ppm_sc` configuration from filter(s). + * + * (2) "repair" a custom set of user defined `ppm_sc` to ensure the agent runs correctly. + * This setting is useful for cases where the end user takes advantage of complete default + * sinsp state enforcement override, but still would like to rely on some safety minimal sinsp + * state enforcement mechanisms. + * + * `sinsp_repair_state_sc_set` is a more resourceful alternative to the default `sinsp_state_sc_set` + * option as it takes the filter `ppm_sc` set into consideration when selecting the effective set of + * `ppm_sc` that needs to be activated in addition to the filter `ppm_sc` set. + * + * todo: possibly extend e2e tests. + * + * @param ppm_sc_set set of `ppm_sc` from filter(s) + * @return sinsp state compliant set of `ppm_sc` conditioned by set of `ppm_sc` from filter(s) + * -> the returned set includes the set of `ppm_sc` from filter(s) + */ set sinsp_repair_state_sc_set(const set& ppm_sc_set); +/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) + * ===============================*/ -/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) ===============================*/ - -/*=============================== PPME set related (sinsp_events.cpp) ===============================*/ +/*=============================== PPME set related (sinsp_events.cpp) + * ===============================*/ /*! \brief Get all the available ppm_event. @@ -263,7 +265,8 @@ set sinsp_state_event_set(); e.g. snowflake cases: umount or umount2 -> always both umount, umount2 e.g. generic events -> will map to ALL generic syscalls (can be over 180 generic syscalls) */ -std::unordered_set event_set_to_names(const set& events_set, bool resolve_generic = true); +std::unordered_set event_set_to_names(const set& events_set, + bool resolve_generic = true); /*! \brief Get the ppm_event of all the event names provided in the set. @@ -280,11 +283,13 @@ set names_to_event_set(const std::unordered_set& ev Note: When passing a ppm_event set containing PPME_GENERIC_E, PPME_GENERIC_X, ALL generic syscalls - (can be over 180 generic syscalls) will be returned given the information loss when going from event_set to sc_set. + (can be over 180 generic syscalls) will be returned given the information loss when going from + event_set to sc_set. */ -set event_set_to_sc_set(const set &events_of_interest); +set event_set_to_sc_set(const set& events_of_interest); -/*=============================== PPME set related (sinsp_events.cpp) ===============================*/ +/*=============================== PPME set related (sinsp_events.cpp) + * ===============================*/ -} // events -} // libsinsp +} // namespace events +} // namespace libsinsp diff --git a/userspace/libsinsp/events/sinsp_events_ppm_sc.cpp b/userspace/libsinsp/events/sinsp_events_ppm_sc.cpp index 3f80fbf90d..91619e674d 100644 --- a/userspace/libsinsp/events/sinsp_events_ppm_sc.cpp +++ b/userspace/libsinsp/events/sinsp_events_ppm_sc.cpp @@ -26,22 +26,16 @@ limitations under the License. #define PPM_REPAIR_STATE_SC_NETWORK_BIND (1 << 1) #define PPM_REPAIR_STATE_SC_FD_CLOSE (1 << 2) - -libsinsp::events::set libsinsp::events::sinsp_state_sc_set() -{ +libsinsp::events::set libsinsp::events::sinsp_state_sc_set() { static libsinsp::events::set ppm_sc_set; - if (ppm_sc_set.empty()) - { + if(ppm_sc_set.empty()) { std::vector sc_vec(PPM_SC_MAX); /* Should never happen but just to be sure. */ - if(scap_get_modifies_state_ppm_sc(sc_vec.data()) != SCAP_SUCCESS) - { + if(scap_get_modifies_state_ppm_sc(sc_vec.data()) != SCAP_SUCCESS) { throw sinsp_exception("'ppm_sc_set' is an unexpected NULL vector!"); } - for (int i = 0; i < PPM_SC_MAX; i++) - { - if (sc_vec[i]) - { + for(int i = 0; i < PPM_SC_MAX; i++) { + if(sc_vec[i]) { ppm_sc_set.insert((ppm_sc_code)i); } } @@ -49,97 +43,97 @@ libsinsp::events::set libsinsp::events::sinsp_state_sc_set() return ppm_sc_set; } -libsinsp::events::set libsinsp::events::enforce_simple_sc_set(libsinsp::events::set ppm_sc_set) -{ +libsinsp::events::set libsinsp::events::enforce_simple_sc_set( + libsinsp::events::set ppm_sc_set) { static libsinsp::events::set simple_set = { - PPM_SC_ACCEPT, - PPM_SC_ACCEPT4, - PPM_SC_BIND, - PPM_SC_BPF, - PPM_SC_CAPSET, - PPM_SC_CHDIR, - PPM_SC_CHMOD, - PPM_SC_CHROOT, - PPM_SC_CLONE, - PPM_SC_CLONE3, - PPM_SC_CLOSE, - PPM_SC_CONNECT, - PPM_SC_CREAT, - PPM_SC_DUP, - PPM_SC_DUP2, - PPM_SC_DUP3, - PPM_SC_EVENTFD, - PPM_SC_EVENTFD2, - PPM_SC_EXECVE, - PPM_SC_EXECVEAT, - PPM_SC_FCHDIR, - PPM_SC_FCHMOD, - PPM_SC_FCHMODAT, - PPM_SC_FCNTL, - PPM_SC_FCNTL64, - PPM_SC_FLOCK, - PPM_SC_FORK, - PPM_SC_GETSOCKOPT, - PPM_SC_INOTIFY_INIT, - PPM_SC_INOTIFY_INIT1, - PPM_SC_IOCTL, - PPM_SC_IO_URING_SETUP, - PPM_SC_KILL, - PPM_SC_LINK, - PPM_SC_LINKAT, - PPM_SC_LISTEN, - PPM_SC_MKDIR, - PPM_SC_MKDIRAT, - PPM_SC_MOUNT, - PPM_SC_OPEN, - PPM_SC_OPEN_BY_HANDLE_AT, - PPM_SC_OPENAT, - PPM_SC_OPENAT2, - PPM_SC_PIPE, - PPM_SC_PIPE2, - PPM_SC_PRLIMIT64, - PPM_SC_PTRACE, - PPM_SC_QUOTACTL, - PPM_SC_RECVFROM, - PPM_SC_RECVMSG, - PPM_SC_RENAME, - PPM_SC_RENAMEAT, - PPM_SC_RENAMEAT2, - PPM_SC_RMDIR, - PPM_SC_SECCOMP, - PPM_SC_SENDMSG, - PPM_SC_SENDTO, - PPM_SC_SETGID, - PPM_SC_SETGID32, - PPM_SC_SETNS, - PPM_SC_SETPGID, - PPM_SC_SETRESGID, - PPM_SC_SETRESGID32, - PPM_SC_SETRESUID, - PPM_SC_SETRESUID32, - PPM_SC_SETRLIMIT, - PPM_SC_SETSID, - PPM_SC_SETUID, - PPM_SC_SETUID32, - PPM_SC_SHUTDOWN, - PPM_SC_SIGNALFD, - PPM_SC_SIGNALFD4, - PPM_SC_SOCKET, - PPM_SC_SOCKETPAIR, - PPM_SC_SYMLINK, - PPM_SC_SYMLINKAT, - PPM_SC_TGKILL, - PPM_SC_TIMERFD_CREATE, - PPM_SC_TKILL, - PPM_SC_UMOUNT, - PPM_SC_UMOUNT2, - PPM_SC_UNLINK, - PPM_SC_UNLINKAT, - PPM_SC_UNSHARE, - PPM_SC_USERFAULTFD, - PPM_SC_VFORK, - PPM_SC_SETREUID, - PPM_SC_SETREGID, + PPM_SC_ACCEPT, + PPM_SC_ACCEPT4, + PPM_SC_BIND, + PPM_SC_BPF, + PPM_SC_CAPSET, + PPM_SC_CHDIR, + PPM_SC_CHMOD, + PPM_SC_CHROOT, + PPM_SC_CLONE, + PPM_SC_CLONE3, + PPM_SC_CLOSE, + PPM_SC_CONNECT, + PPM_SC_CREAT, + PPM_SC_DUP, + PPM_SC_DUP2, + PPM_SC_DUP3, + PPM_SC_EVENTFD, + PPM_SC_EVENTFD2, + PPM_SC_EXECVE, + PPM_SC_EXECVEAT, + PPM_SC_FCHDIR, + PPM_SC_FCHMOD, + PPM_SC_FCHMODAT, + PPM_SC_FCNTL, + PPM_SC_FCNTL64, + PPM_SC_FLOCK, + PPM_SC_FORK, + PPM_SC_GETSOCKOPT, + PPM_SC_INOTIFY_INIT, + PPM_SC_INOTIFY_INIT1, + PPM_SC_IOCTL, + PPM_SC_IO_URING_SETUP, + PPM_SC_KILL, + PPM_SC_LINK, + PPM_SC_LINKAT, + PPM_SC_LISTEN, + PPM_SC_MKDIR, + PPM_SC_MKDIRAT, + PPM_SC_MOUNT, + PPM_SC_OPEN, + PPM_SC_OPEN_BY_HANDLE_AT, + PPM_SC_OPENAT, + PPM_SC_OPENAT2, + PPM_SC_PIPE, + PPM_SC_PIPE2, + PPM_SC_PRLIMIT64, + PPM_SC_PTRACE, + PPM_SC_QUOTACTL, + PPM_SC_RECVFROM, + PPM_SC_RECVMSG, + PPM_SC_RENAME, + PPM_SC_RENAMEAT, + PPM_SC_RENAMEAT2, + PPM_SC_RMDIR, + PPM_SC_SECCOMP, + PPM_SC_SENDMSG, + PPM_SC_SENDTO, + PPM_SC_SETGID, + PPM_SC_SETGID32, + PPM_SC_SETNS, + PPM_SC_SETPGID, + PPM_SC_SETRESGID, + PPM_SC_SETRESGID32, + PPM_SC_SETRESUID, + PPM_SC_SETRESUID32, + PPM_SC_SETRLIMIT, + PPM_SC_SETSID, + PPM_SC_SETUID, + PPM_SC_SETUID32, + PPM_SC_SHUTDOWN, + PPM_SC_SIGNALFD, + PPM_SC_SIGNALFD4, + PPM_SC_SOCKET, + PPM_SC_SOCKETPAIR, + PPM_SC_SYMLINK, + PPM_SC_SYMLINKAT, + PPM_SC_TGKILL, + PPM_SC_TIMERFD_CREATE, + PPM_SC_TKILL, + PPM_SC_UMOUNT, + PPM_SC_UMOUNT2, + PPM_SC_UNLINK, + PPM_SC_UNLINKAT, + PPM_SC_UNSHARE, + PPM_SC_USERFAULTFD, + PPM_SC_VFORK, + PPM_SC_SETREUID, + PPM_SC_SETREGID, }; static auto sinsp_state_ppm_sc = sinsp_state_sc_set(); static auto final_set = simple_set.merge(sinsp_state_ppm_sc); @@ -147,117 +141,89 @@ libsinsp::events::set libsinsp::events::enforce_simple_sc_set(libsi } /* The filter should contain only conditions on the syscall category (lower bits)*/ -static inline libsinsp::events::set get_sc_set_from_cat(const std::function& filter) -{ +static inline libsinsp::events::set get_sc_set_from_cat( + const std::function& filter) { std::vector ev_vec(PPM_EVENT_MAX, 0); std::vector sc_vec(PPM_SC_MAX, 0); /* Find all the events involved in that category */ - for(int ev = 0; ev < PPM_EVENT_MAX; ev++) - { + for(int ev = 0; ev < PPM_EVENT_MAX; ev++) { auto cat = scap_get_syscall_category_from_event((ppm_event_code)ev); - if(filter((ppm_event_category)cat)) - { + if(filter((ppm_event_category)cat)) { ev_vec[ev] = 1; } } /* Obtain all sc associated with those events */ - if(scap_get_ppm_sc_from_events(ev_vec.data(), sc_vec.data()) != SCAP_SUCCESS) - { + if(scap_get_ppm_sc_from_events(ev_vec.data(), sc_vec.data()) != SCAP_SUCCESS) { throw sinsp_exception("'sc_vec' or 'ev_vec' is unexpected NULL vector!"); } libsinsp::events::set sc_set; - for(int sc = 0; sc < PPM_SC_MAX; sc++) - { - if(sc_vec[sc]) - { + for(int sc = 0; sc < PPM_SC_MAX; sc++) { + if(sc_vec[sc]) { sc_set.insert((ppm_sc_code)sc); } } return sc_set; } -libsinsp::events::set libsinsp::events::io_sc_set() -{ - static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) - { - return cat == EC_IO_READ || cat == EC_IO_WRITE; - }); +libsinsp::events::set libsinsp::events::io_sc_set() { + static auto sc_set = get_sc_set_from_cat( + [](ppm_event_category cat) { return cat == EC_IO_READ || cat == EC_IO_WRITE; }); return sc_set; } -libsinsp::events::set libsinsp::events::io_other_sc_set() -{ - static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) - { - return cat == EC_IO_OTHER; - }); +libsinsp::events::set libsinsp::events::io_other_sc_set() { + static auto sc_set = + get_sc_set_from_cat([](ppm_event_category cat) { return cat == EC_IO_OTHER; }); return sc_set; } -libsinsp::events::set libsinsp::events::file_sc_set() -{ - static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) - { - return cat == EC_FILE; - }); +libsinsp::events::set libsinsp::events::file_sc_set() { + static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) { return cat == EC_FILE; }); return sc_set; } -libsinsp::events::set libsinsp::events::net_sc_set() -{ - static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) - { - return cat == EC_NET; - }); +libsinsp::events::set libsinsp::events::net_sc_set() { + static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) { return cat == EC_NET; }); return sc_set; } -libsinsp::events::set libsinsp::events::proc_sc_set() -{ - static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) - { - return cat == EC_PROCESS; - }); +libsinsp::events::set libsinsp::events::proc_sc_set() { + static auto sc_set = + get_sc_set_from_cat([](ppm_event_category cat) { return cat == EC_PROCESS; }); return sc_set; } -libsinsp::events::set libsinsp::events::sys_sc_set() -{ - static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) - { - return cat == EC_SYSTEM || cat == EC_MEMORY || cat == EC_SIGNAL; - }); +libsinsp::events::set libsinsp::events::sys_sc_set() { + static auto sc_set = get_sc_set_from_cat([](ppm_event_category cat) { + return cat == EC_SYSTEM || cat == EC_MEMORY || cat == EC_SIGNAL; + }); return sc_set; } -libsinsp::events::set libsinsp::events::event_names_to_sc_set(const std::unordered_set& events) -{ +libsinsp::events::set libsinsp::events::event_names_to_sc_set( + const std::unordered_set& events) { /* Convert event names into an event set, and then convert that into a * syscall set. We exclude generics due to the potential information loss * (e.g. one generic event will include all generic syscalls in the * conversion). Generics are handled below using their actuall syscall name. * Note: this is the same logic with which the "evt.type" filter field * is extracted. */ - auto gen_event_set = libsinsp::events::set( - { PPME_GENERIC_E, PPME_GENERIC_X }); + auto gen_event_set = libsinsp::events::set({PPME_GENERIC_E, PPME_GENERIC_X}); auto event_set = libsinsp::events::names_to_event_set(events); bool has_gen_event = !event_set.intersect(gen_event_set).empty(); event_set = event_set.diff(gen_event_set); auto ppm_sc_set = libsinsp::events::event_set_to_sc_set(event_set); - if (has_gen_event) - { + if(has_gen_event) { std::string name; auto gen_sc_set = libsinsp::events::event_set_to_sc_set(gen_event_set); - for (const auto &sc : gen_sc_set) - { + for(const auto& sc : gen_sc_set) { name.assign(scap_get_ppm_sc_name(sc)); - if (events.find(name) != events.end()) - { + if(events.find(name) != events.end()) { ppm_sc_set.insert(sc); } } @@ -266,48 +232,39 @@ libsinsp::events::set libsinsp::events::event_names_to_sc_set(const return ppm_sc_set; } -libsinsp::events::set libsinsp::events::sc_names_to_sc_set(const std::unordered_set& syscalls) -{ +libsinsp::events::set libsinsp::events::sc_names_to_sc_set( + const std::unordered_set& syscalls) { libsinsp::events::set ppm_sc_set; - for (const auto &name : syscalls) - { + for(const auto& name : syscalls) { auto ppm_sc = scap_ppm_sc_from_name(name.c_str()); - if(static_cast(ppm_sc) != -1) - { + if(static_cast(ppm_sc) != -1) { ppm_sc_set.insert(ppm_sc); } } return ppm_sc_set; } -libsinsp::events::set libsinsp::events::sc_set_to_event_set(const libsinsp::events::set &ppm_sc_set) -{ +libsinsp::events::set libsinsp::events::sc_set_to_event_set( + const libsinsp::events::set& ppm_sc_set) { libsinsp::events::set events_set; std::vector event_vec(PPM_EVENT_MAX); - if(scap_get_events_from_ppm_sc(ppm_sc_set.data(), event_vec.data()) != SCAP_SUCCESS) - { + if(scap_get_events_from_ppm_sc(ppm_sc_set.data(), event_vec.data()) != SCAP_SUCCESS) { throw sinsp_exception("`ppm_sc_array` or `events_set` is an unexpected NULL vector!"); } - for (int i = 0; i < PPM_EVENT_MAX; i++) - { - if (event_vec[i]) - { + for(int i = 0; i < PPM_EVENT_MAX; i++) { + if(event_vec[i]) { events_set.insert((ppm_event_code)i); } } return events_set; } -libsinsp::events::set libsinsp::events::all_sc_set() -{ +libsinsp::events::set libsinsp::events::all_sc_set() { static libsinsp::events::set ppm_sc_set; - if (ppm_sc_set.empty()) - { + if(ppm_sc_set.empty()) { // Skip UNKNOWN - for(uint32_t ppm_sc = 1; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if (scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)[0] != '\0') - { + for(uint32_t ppm_sc = 1; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)[0] != '\0') { // Skip non-existent ppm_sc_set.insert((ppm_sc_code)ppm_sc); } @@ -316,14 +273,12 @@ libsinsp::events::set libsinsp::events::all_sc_set() return ppm_sc_set; } -std::unordered_set libsinsp::events::sc_set_to_sc_names(const libsinsp::events::set& ppm_sc_set) -{ +std::unordered_set libsinsp::events::sc_set_to_sc_names( + const libsinsp::events::set& ppm_sc_set) { std::unordered_set ppm_sc_names_set; - for (const auto& val : ppm_sc_set) - { + for(const auto& val : ppm_sc_set) { std::string ppm_sc_name = scap_get_ppm_sc_name(val); - if (ppm_sc_name != "") - { + if(ppm_sc_name != "") { // Skip non-existent ppm_sc_names_set.insert(ppm_sc_name); } @@ -331,8 +286,8 @@ std::unordered_set libsinsp::events::sc_set_to_sc_names(const libsi return ppm_sc_names_set; } -std::unordered_set libsinsp::events::sc_set_to_event_names(const libsinsp::events::set& ppm_sc_set) -{ +std::unordered_set libsinsp::events::sc_set_to_event_names( + const libsinsp::events::set& ppm_sc_set) { // convert all sc code to their event codes mappings, generic event excluded auto event_set = sc_set_to_event_set(ppm_sc_set); event_set.remove(ppm_event_code::PPME_GENERIC_E); @@ -349,25 +304,24 @@ std::unordered_set libsinsp::events::sc_set_to_event_names(const li return unordered_set_union(event_names_set, remaining_sc_names_set); } -libsinsp::events::set libsinsp::events::sinsp_repair_state_sc_set(const libsinsp::events::set& ppm_sc_set) -{ +libsinsp::events::set libsinsp::events::sinsp_repair_state_sc_set( + const libsinsp::events::set& ppm_sc_set) { uint32_t flags = 0; - if (!libsinsp::events::net_sc_set().intersect(ppm_sc_set).empty()) - { + if(!libsinsp::events::net_sc_set().intersect(ppm_sc_set).empty()) { flags |= PPM_REPAIR_STATE_SC_NETWORK_BASE; flags |= PPM_REPAIR_STATE_SC_FD_CLOSE; } - static libsinsp::events::set accept_listen_sc_set = {PPM_SC_ACCEPT, PPM_SC_ACCEPT4, PPM_SC_LISTEN}; - if (!accept_listen_sc_set.intersect(ppm_sc_set).empty()) - { + static libsinsp::events::set accept_listen_sc_set = {PPM_SC_ACCEPT, + PPM_SC_ACCEPT4, + PPM_SC_LISTEN}; + if(!accept_listen_sc_set.intersect(ppm_sc_set).empty()) { flags |= PPM_REPAIR_STATE_SC_NETWORK_BIND; } - if (!libsinsp::events::file_sc_set().intersect(ppm_sc_set).empty() || - !libsinsp::events::io_sc_set().intersect(ppm_sc_set).empty() || - !libsinsp::events::io_other_sc_set().intersect(ppm_sc_set).empty()) - { + if(!libsinsp::events::file_sc_set().intersect(ppm_sc_set).empty() || + !libsinsp::events::io_sc_set().intersect(ppm_sc_set).empty() || + !libsinsp::events::io_other_sc_set().intersect(ppm_sc_set).empty()) { flags |= PPM_REPAIR_STATE_SC_FD_CLOSE; } @@ -375,40 +329,22 @@ libsinsp::events::set libsinsp::events::sinsp_repair_state_sc_set(c * Consistent enforcement regardless of the input ppm_sc_set. */ libsinsp::events::set repaired_sinsp_state_sc_set = { - PPM_SC_CLONE, - PPM_SC_CLONE3, - PPM_SC_FORK, - PPM_SC_VFORK, - PPM_SC_EXECVE, - PPM_SC_EXECVEAT, - PPM_SC_FCHDIR, - PPM_SC_CHDIR, - PPM_SC_CHROOT, - PPM_SC_CAPSET, - PPM_SC_SETGID, - PPM_SC_SETGID32, - PPM_SC_SETPGID, - PPM_SC_SETRESGID, - PPM_SC_SETRESGID32, - PPM_SC_SETRESUID, - PPM_SC_SETRESUID32, - PPM_SC_SETSID, - PPM_SC_SETUID, - PPM_SC_SETUID32, - PPM_SC_PRCTL, + PPM_SC_CLONE, PPM_SC_CLONE3, PPM_SC_FORK, PPM_SC_VFORK, + PPM_SC_EXECVE, PPM_SC_EXECVEAT, PPM_SC_FCHDIR, PPM_SC_CHDIR, + PPM_SC_CHROOT, PPM_SC_CAPSET, PPM_SC_SETGID, PPM_SC_SETGID32, + PPM_SC_SETPGID, PPM_SC_SETRESGID, PPM_SC_SETRESGID32, PPM_SC_SETRESUID, + PPM_SC_SETRESUID32, PPM_SC_SETSID, PPM_SC_SETUID, PPM_SC_SETUID32, + PPM_SC_PRCTL, }; - if ((flags & PPM_REPAIR_STATE_SC_NETWORK_BASE)) - { + if((flags & PPM_REPAIR_STATE_SC_NETWORK_BASE)) { repaired_sinsp_state_sc_set.insert(PPM_SC_SOCKET); repaired_sinsp_state_sc_set.insert(PPM_SC_GETSOCKOPT); } - if ((flags & PPM_REPAIR_STATE_SC_NETWORK_BIND)) - { + if((flags & PPM_REPAIR_STATE_SC_NETWORK_BIND)) { repaired_sinsp_state_sc_set.insert(PPM_SC_BIND); } - if ((flags & PPM_REPAIR_STATE_SC_FD_CLOSE)) - { + if((flags & PPM_REPAIR_STATE_SC_FD_CLOSE)) { repaired_sinsp_state_sc_set.insert(PPM_SC_CLOSE); } diff --git a/userspace/libsinsp/events/sinsp_events_set.h b/userspace/libsinsp/events/sinsp_events_set.h index 95cfe95589..8a83c5a04b 100644 --- a/userspace/libsinsp/events/sinsp_events_set.h +++ b/userspace/libsinsp/events/sinsp_events_set.h @@ -30,74 +30,74 @@ limitations under the License. // The following are needed on MacOS to be able to // initialize a std::(unordered)map/set{} -namespace std -{ +namespace std { template<> struct hash { - size_t operator()(const ppm_sc_code &pt) const { - return std::hash()((uint32_t)pt); - } + size_t operator()(const ppm_sc_code& pt) const { return std::hash()((uint32_t)pt); } }; template<> struct hash { - size_t operator()(const ppm_event_code &pt) const { + size_t operator()(const ppm_event_code& pt) const { return std::hash()((uint32_t)pt); } }; -} +} // namespace std namespace libsinsp { namespace events { template -class set -{ +class set { private: using vec_t = std::vector; vec_t m_types{}; T m_max; size_t m_size; - inline void check_range(T e) const - { - if(e > m_max) - { + inline void check_range(T e) const { + if(e > m_max) { throw sinsp_exception("invalid event type"); } } public: - struct iterator - { + struct iterator { using iterator_category = std::forward_iterator_tag; - using difference_type = std::ptrdiff_t; - using value_type = T; - using pointer = T*; - using reference = T&; - - iterator(const uint8_t* data, size_t index, size_t max) - : m_data(data), m_index(index), m_max(max) - { + using difference_type = std::ptrdiff_t; + using value_type = T; + using pointer = T*; + using reference = T&; + + iterator(const uint8_t* data, size_t index, size_t max): + m_data(data), + m_index(index), + m_max(max) { set_val(); } reference operator*() { return m_val; } pointer operator->() { return &m_val; } - iterator& operator++() { m_index++; set_val(); return *this; } - iterator operator++(int) { iterator i = *this; ++(*this); return i; } - friend bool operator== (const iterator& a, const iterator& b) - { + iterator& operator++() { + m_index++; + set_val(); + return *this; + } + iterator operator++(int) { + iterator i = *this; + ++(*this); + return i; + } + friend bool operator==(const iterator& a, const iterator& b) { return a.m_data == b.m_data && a.m_index == b.m_index; }; - friend bool operator!= (const iterator& a, const iterator& b) { return !(a == b); }; + friend bool operator!=(const iterator& a, const iterator& b) { return !(a == b); }; + private: - inline void set_val() - { - while (m_index < m_max && m_data[m_index] == 0) - { + inline void set_val() { + while(m_index < m_max && m_data[m_index] == 0) { m_index++; } - m_val = (value_type) m_index; + m_val = (value_type)m_index; } const uint8_t* m_data; @@ -113,175 +113,128 @@ class set set() = delete; template - static set from(InputIterator first, InputIterator last) - { + static set from(InputIterator first, InputIterator last) { set ret; - for (auto i = first; i != last; i++) - { + for(auto i = first; i != last; i++) { ret.insert(*i); } return ret; } template - static set from(const Iterable& v) - { + static set from(const Iterable& v) { return from(v.begin(), v.end()); } template - set(const Iterable& v): set(from(v)) { } + set(const Iterable& v): set(from(v)) {} template - set(InputIterator first, InputIterator last): set(from(first, last)) { } + set(InputIterator first, InputIterator last): set(from(first, last)) {} - set(std::initializer_list v): set(v.begin(), v.end()) { } + set(std::initializer_list v): set(v.begin(), v.end()) {} - inline explicit set(T maxLen): - m_types(maxLen + 1, 0), - m_max(maxLen), - m_size(0) - { - } + inline explicit set(T maxLen): m_types(maxLen + 1, 0), m_max(maxLen), m_size(0) {} - const uint8_t* data() const noexcept - { - return m_types.data(); - } + const uint8_t* data() const noexcept { return m_types.data(); } iterator begin() const { return iterator(m_types.data(), 0, m_max); } iterator end() const { return iterator(m_types.data(), m_max, m_max); } - inline void insert(T e) - { + inline void insert(T e) { check_range(e); - if (m_types[e] == 0) - { + if(m_types[e] == 0) { m_size++; } m_types[e] = 1; } template - inline void insert(InputIterator first, InputIterator last) - { - for (auto i = first; i != last; i++) - { + inline void insert(InputIterator first, InputIterator last) { + for(auto i = first; i != last; i++) { insert(*i); } } - inline void remove(T e) - { + inline void remove(T e) { check_range(e); - if (m_types[e] == 1) - { + if(m_types[e] == 1) { m_size--; } m_types[e] = 0; } - inline bool contains(T e) const - { + inline bool contains(T e) const { check_range(e); return m_types[e] != 0; } - void clear() - { - for(auto& v : m_types) - { + void clear() { + for(auto& v : m_types) { v = 0; } m_size = 0; } - inline bool empty() const - { - return m_size == 0; - } + inline bool empty() const { return m_size == 0; } - inline size_t size() const - { - return m_size; - } + inline size_t size() const { return m_size; } - bool equals(const set& other) const - { - return m_types == other.m_types; - } + bool equals(const set& other) const { return m_types == other.m_types; } - set merge(const set& other) const - { - if (other.m_max != m_max) - { + set merge(const set& other) const { + if(other.m_max != m_max) { throw sinsp_exception("cannot merge sets with different max size."); } set ret(m_max); - for(size_t i = 0; i <= m_max; ++i) - { - if (m_types[i] | other.m_types[i]) - { + for(size_t i = 0; i <= m_max; ++i) { + if(m_types[i] | other.m_types[i]) { ret.insert((T)i); } } return ret; } - set diff(const set& other) const - { - if (other.m_max != m_max) - { + set diff(const set& other) const { + if(other.m_max != m_max) { throw sinsp_exception("cannot diff sets with different max size."); } set ret(m_max); - for(size_t i = 0; i <= m_max; ++i) - { - if (m_types[i] == 1 && other.m_types[i] == 0) - { + for(size_t i = 0; i <= m_max; ++i) { + if(m_types[i] == 1 && other.m_types[i] == 0) { ret.insert((T)i); } } return ret; } - set intersect(const set& other) const - { - if (other.m_max != m_max) - { + set intersect(const set& other) const { + if(other.m_max != m_max) { throw sinsp_exception("cannot intersect sets with different max size."); } set ret(m_max); - for(size_t i = 0; i <= m_max; ++i) - { - if (m_types[i] & other.m_types[i]) - { + for(size_t i = 0; i <= m_max; ++i) { + if(m_types[i] & other.m_types[i]) { ret.insert((T)i); } } return ret; } - void for_each(const std::function& consumer) const - { - for(size_t i = 0; i < m_max; ++i) - { - if(m_types[i] != 0) - { - if(!consumer((T) i)) - { + void for_each(const std::function& consumer) const { + for(size_t i = 0; i < m_max; ++i) { + if(m_types[i] != 0) { + if(!consumer((T)i)) { return; } } } } - set filter(const std::function& predicate) const - { + set filter(const std::function& predicate) const { set ret; - for_each([&ret, &predicate](T v){ - if(predicate(v)) - { + for_each([&ret, &predicate](T v) { + if(predicate(v)) { ret.insert(v); } return true; @@ -292,38 +245,30 @@ class set // Some template specialization for useful constructors -template <> -inline set::set(): set(PPM_SC_MAX) -{ -} +template<> +inline set::set(): set(PPM_SC_MAX) {} template<> -inline set::set(): set(PPM_EVENT_MAX) -{ -} +inline set::set(): set(PPM_EVENT_MAX) {} -} // events -} // libsinsp +} // namespace events +} // namespace libsinsp template -inline bool operator==(const libsinsp::events::set& lhs, const libsinsp::events::set& rhs) -{ +inline bool operator==(const libsinsp::events::set& lhs, const libsinsp::events::set& rhs) { return lhs.equals(rhs); } template -inline bool operator!=(const libsinsp::events::set& lhs, const libsinsp::events::set& rhs) -{ +inline bool operator!=(const libsinsp::events::set& lhs, const libsinsp::events::set& rhs) { return !(lhs == rhs); } template -std::ostream& operator<<(std::ostream& os, const libsinsp::events::set& s) -{ +std::ostream& operator<<(std::ostream& os, const libsinsp::events::set& s) { os << "("; auto first = true; - for (const auto& v : s) - { + for(const auto& v : s) { os << (first ? "" : ", ") << v; first = false; } diff --git a/userspace/libsinsp/examples/CMakeLists.txt b/userspace/libsinsp/examples/CMakeLists.txt index 25a671d0ad..e93a5369c3 100644 --- a/userspace/libsinsp/examples/CMakeLists.txt +++ b/userspace/libsinsp/examples/CMakeLists.txt @@ -2,42 +2,37 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # include(jsoncpp) -add_executable(sinsp-example - util.cpp - test.cpp -) +add_executable(sinsp-example util.cpp test.cpp) -target_link_libraries(sinsp-example - sinsp - "${JSONCPP_LIB}" -) +target_link_libraries(sinsp-example sinsp "${JSONCPP_LIB}") -if (EMSCRIPTEN) +if(EMSCRIPTEN) target_compile_options(sinsp-example PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0") target_link_options(sinsp-example PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0") target_link_options(sinsp-example PRIVATE "-sALLOW_MEMORY_GROWTH=1") target_link_options(sinsp-example PRIVATE "-sEXPORTED_FUNCTIONS=['_main','_htons','_ntohs']") - # note(jasondellaluce): since we run tests with node, we need to add this - # for reading from local capture files. + # note(jasondellaluce): since we run tests with node, we need to add this for reading from local + # capture files. target_link_options(sinsp-example PRIVATE "-sNODERAWFS=1") endif() -if (APPLE AND NOT MINIMAL_BUILD AND NOT EMSCRIPTEN) +if(APPLE + AND NOT MINIMAL_BUILD + AND NOT EMSCRIPTEN +) # Needed when linking libcurl set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -framework Foundation -framework SystemConfiguration") endif() diff --git a/userspace/libsinsp/examples/test.cpp b/userspace/libsinsp/examples/test.cpp index 24ec84ea82..d0334b4bd8 100644 --- a/userspace/libsinsp/examples/test.cpp +++ b/userspace/libsinsp/examples/test.cpp @@ -20,7 +20,7 @@ limitations under the License. #include #ifndef _WIN32 #include -#endif // _WIN32 +#endif // _WIN32 #include #include #include @@ -38,11 +38,10 @@ extern "C" { #include #include } -#endif // _WIN32 +#endif // _WIN32 using namespace std; - // Functions used for dumping to stdout void raw_dump(sinsp&, sinsp_evt* ev); void formatted_dump(sinsp&, sinsp_evt* ev); @@ -66,13 +65,18 @@ static sinsp_filter_check_list s_filterlist; sinsp_evt* get_event(sinsp& inspector, std::function handle_error); -#define EVENT_HEADER "%evt.num %evt.time cat=%evt.category container=%container.id proc=%proc.name(%proc.pid.%thread.tid) " +#define EVENT_HEADER \ + "%evt.num %evt.time cat=%evt.category container=%container.id " \ + "proc=%proc.name(%proc.pid.%thread.tid) " #define EVENT_TRAILER "%evt.dir %evt.type %evt.args" #define EVENT_DEFAULTS EVENT_HEADER EVENT_TRAILER -#define PROCESS_DEFAULTS EVENT_HEADER "ppid=%proc.ppid exe=%proc.exe args=[%proc.cmdline] " EVENT_TRAILER +#define PROCESS_DEFAULTS \ + EVENT_HEADER "ppid=%proc.ppid exe=%proc.exe args=[%proc.cmdline] " EVENT_TRAILER -#define JSON_PROCESS_DEFAULTS "*%evt.num %evt.time %evt.category %container.id %proc.ppid %proc.pid %evt.type %proc.exe %proc.cmdline %evt.args" +#define JSON_PROCESS_DEFAULTS \ + "*%evt.num %evt.time %evt.category %container.id %proc.ppid %proc.pid %evt.type %proc.exe " \ + "%proc.cmdline %evt.args" std::string default_output = EVENT_DEFAULTS; std::string process_output = PROCESS_DEFAULTS; @@ -82,13 +86,11 @@ static std::unique_ptr default_formatter = nullptr; static std::unique_ptr process_formatter = nullptr; static std::unique_ptr net_formatter = nullptr; -static void sigint_handler(int signum) -{ +static void sigint_handler(int signum) { g_interrupted = true; } -static void usage() -{ +static void usage() { string usage = R"(Usage: sinsp-example [options] Overview: Goal of sinsp-example binary is to test and debug sinsp functionality and print events to STDOUT. All drivers are supported. @@ -117,37 +119,32 @@ Overview: Goal of sinsp-example binary is to test and debug sinsp functionality #ifndef _WIN32 // Parse CLI options. -void parse_CLI_options(sinsp& inspector, int argc, char** argv) -{ - static struct option long_options[] = { - {"help", no_argument, 0, 'h'}, - {"filter", required_argument, 0, 'f'}, - {"json", no_argument, 0, 'j'}, - {"all-threads", no_argument, 0, 'a'}, - {"bpf", required_argument, 0, 'b'}, - {"modern_bpf", no_argument, 0, 'm'}, - {"kmod", no_argument, 0, 'k'}, - {"scap_file", required_argument, 0, 's'}, - {"buffer_dim", required_argument, 0, 'd'}, - {"output-fields", required_argument, 0, 'o'}, - {"exclude-users", no_argument, 0, 'E'}, - {"num-events", required_argument, 0, 'n'}, - {"ppm-sc-modifies-state", no_argument, 0, 'z'}, - {"ppm-sc-repair-state", no_argument, 0, 'x'}, - {"remove-io-sc-state", no_argument, 0, 'q'}, - {"enable-glogger", no_argument, 0, 'g'}, - {"raw", no_argument, 0, 'r'}, - {0, 0, 0, 0}}; +void parse_CLI_options(sinsp& inspector, int argc, char** argv) { + static struct option long_options[] = {{"help", no_argument, 0, 'h'}, + {"filter", required_argument, 0, 'f'}, + {"json", no_argument, 0, 'j'}, + {"all-threads", no_argument, 0, 'a'}, + {"bpf", required_argument, 0, 'b'}, + {"modern_bpf", no_argument, 0, 'm'}, + {"kmod", no_argument, 0, 'k'}, + {"scap_file", required_argument, 0, 's'}, + {"buffer_dim", required_argument, 0, 'd'}, + {"output-fields", required_argument, 0, 'o'}, + {"exclude-users", no_argument, 0, 'E'}, + {"num-events", required_argument, 0, 'n'}, + {"ppm-sc-modifies-state", no_argument, 0, 'z'}, + {"ppm-sc-repair-state", no_argument, 0, 'x'}, + {"remove-io-sc-state", no_argument, 0, 'q'}, + {"enable-glogger", no_argument, 0, 'g'}, + {"raw", no_argument, 0, 'r'}, + {0, 0, 0, 0}}; bool format_set = false; int op; int long_index = 0; - while((op = getopt_long(argc, argv, - "hf:jab:mks:d:o:En:zxqgr", - long_options, &long_index)) != -1) - { - switch(op) - { + while((op = getopt_long(argc, argv, "hf:jab:mks:d:o:En:zxqgr", long_options, &long_index)) != + -1) { + switch(op) { case 'h': usage(); exit(EXIT_SUCCESS); @@ -156,8 +153,7 @@ void parse_CLI_options(sinsp& inspector, int argc, char** argv) break; case 'j': dump = formatted_dump; - if(!format_set) - { + if(!format_set) { default_output = DEFAULT_OUTPUT_STR; process_output = JSON_PROCESS_DEFAULTS; net_output = JSON_PROCESS_DEFAULTS " %fd.name"; @@ -215,101 +211,90 @@ void parse_CLI_options(sinsp& inspector, int argc, char** argv) } } } -#endif // _WIN32 +#endif // _WIN32 -libsinsp::events::set extract_filter_sc_codes(sinsp& inspector) -{ +libsinsp::events::set extract_filter_sc_codes(sinsp& inspector) { auto ast = inspector.get_filter_ast(); - if(ast != nullptr) - { + if(ast != nullptr) { return libsinsp::filter::ast::ppm_sc_codes(ast.get()); } return {}; } -void open_engine(sinsp& inspector, libsinsp::events::set events_sc_codes) -{ +void open_engine(sinsp& inspector, libsinsp::events::set events_sc_codes) { std::cout << "-- Try to open: '" + engine_string + "' engine." << std::endl; - libsinsp::events::set ppm_sc; // empty set activaes each available ppm sc in the kernel + libsinsp::events::set + ppm_sc; // empty set activaes each available ppm sc in the kernel /* Select sc codes for active tracing in the kernel. * Include all ppm sc codes from filter AST. * Provide more e2e testing options. * Demonstrate ppm sc API usage. */ - if (ppm_sc_repair_state && !events_sc_codes.empty()) - { + if(ppm_sc_repair_state && !events_sc_codes.empty()) { ppm_sc = libsinsp::events::sinsp_repair_state_sc_set(events_sc_codes); - if (!ppm_sc.empty()) - { + if(!ppm_sc.empty()) { auto events_sc_names = libsinsp::events::sc_set_to_sc_names(ppm_sc); - printf("-- Activated (%ld) ppm sc names in kernel using `sinsp_repair_state_sc_set` enforcement: %s\n", events_sc_names.size(), concat_set_in_order(events_sc_names).c_str()); + printf("-- Activated (%ld) ppm sc names in kernel using `sinsp_repair_state_sc_set` " + "enforcement: %s\n", + events_sc_names.size(), + concat_set_in_order(events_sc_names).c_str()); } } - if (ppm_sc_modifies_state && !events_sc_codes.empty()) - { + if(ppm_sc_modifies_state && !events_sc_codes.empty()) { ppm_sc = libsinsp::events::sinsp_state_sc_set(); - if (ppm_sc_state_remove_io_sc) - { + if(ppm_sc_state_remove_io_sc) { /* Currently used for testing sinsp_state_sc_set() without I/O sc codes. * Approach may change in the future. */ ppm_sc = ppm_sc.diff(libsinsp::events::io_sc_set()); - } ppm_sc = ppm_sc.merge(events_sc_codes); - if (!ppm_sc.empty()) - { + if(!ppm_sc.empty()) { auto events_sc_names = libsinsp::events::sc_set_to_sc_names(ppm_sc); - printf("-- Activated (%ld) ppm sc names in kernel using `sinsp_state_sc_set` enforcement: %s\n", events_sc_names.size(), concat_set_in_order(events_sc_names).c_str()); + printf("-- Activated (%ld) ppm sc names in kernel using `sinsp_state_sc_set` " + "enforcement: %s\n", + events_sc_names.size(), + concat_set_in_order(events_sc_names).c_str()); } } - if(false) - { - + if(false) { } #ifdef HAS_ENGINE_KMOD - else if(!engine_string.compare(KMOD_ENGINE)) - { + else if(!engine_string.compare(KMOD_ENGINE)) { inspector.open_kmod(buffer_bytes_dim, ppm_sc); } #endif #ifdef HAS_ENGINE_BPF - else if(!engine_string.compare(BPF_ENGINE)) - { - if(bpf_path.empty()) - { - std::cerr << "You must specify the path to the bpf probe if you use the 'bpf' engine" << std::endl; + else if(!engine_string.compare(BPF_ENGINE)) { + if(bpf_path.empty()) { + std::cerr << "You must specify the path to the bpf probe if you use the 'bpf' engine" + << std::endl; exit(EXIT_FAILURE); - } - else - { + } else { std::cerr << bpf_path << std::endl; } inspector.open_bpf(bpf_path.c_str(), buffer_bytes_dim, ppm_sc); } #endif #ifdef HAS_ENGINE_SAVEFILE - else if(!engine_string.compare(SAVEFILE_ENGINE)) - { - if(file_path.empty()) - { - std::cerr << "You must specify the path to the file if you use the 'savefile' engine" << std::endl; + else if(!engine_string.compare(SAVEFILE_ENGINE)) { + if(file_path.empty()) { + std::cerr << "You must specify the path to the file if you use the 'savefile' engine" + << std::endl; exit(EXIT_FAILURE); } inspector.open_savefile(file_path.c_str(), 0); } #endif #ifdef HAS_ENGINE_MODERN_BPF - else if(!engine_string.compare(MODERN_BPF_ENGINE)) - { + else if(!engine_string.compare(MODERN_BPF_ENGINE)) { inspector.open_modern_bpf(buffer_bytes_dim, DEFAULT_CPU_FOR_EACH_BUFFER, true, ppm_sc); } #endif - else - { + else { std::cerr << "Unknown engine" << std::endl; exit(EXIT_FAILURE); } @@ -321,34 +306,30 @@ void open_engine(sinsp& inspector, libsinsp::events::set events_sc_ #define insmod(fd, opts, flags) syscall(__NR_finit_module, fd, opts, flags) #define rmmod(name, flags) syscall(__NR_delete_module, name, flags) -static void remove_module() -{ - if (rmmod("scap", 0) != 0) - { +static void remove_module() { + if(rmmod("scap", 0) != 0) { cerr << "[ERROR] Failed to remove kernel module" << strerror(errno) << endl; } } -static bool insert_module() -{ +static bool insert_module() { // Check if we are configured to run with the kernel module if(engine_string.compare(KMOD_ENGINE)) return true; - char *driver_path = getenv("KERNEL_MODULE"); - if (driver_path == NULL || *driver_path == '\0') - { + char* driver_path = getenv("KERNEL_MODULE"); + if(driver_path == NULL || *driver_path == '\0') { // We don't have a path set, assuming the kernel module is already there return true; } int res; int fd = open(driver_path, O_RDONLY); - if (fd < 0) + if(fd < 0) goto error; res = insmod(fd, "", 0); - if (res != 0) + if(res != 0) goto error; atexit(remove_module); @@ -359,22 +340,21 @@ static bool insert_module() error: cerr << "[ERROR] Failed to insert kernel module: " << strerror(errno) << endl; - if (fd > 0) - { + if(fd > 0) { close(fd); } return false; } -#endif // __linux__ +#endif // __linux__ // // Sample filters: // "evt.category=process or evt.category=net" -// "evt.dir=< and (evt.category=net or (evt.type=execveat or evt.type=execve or evt.type=clone or evt.type=fork or evt.type=vfork))" +// "evt.dir=< and (evt.category=net or (evt.type=execveat or evt.type=execve or evt.type=clone or +// evt.type=fork or evt.type=vfork))" // -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { sinsp inspector; #ifndef _WIN32 @@ -383,42 +363,37 @@ int main(int argc, char** argv) #ifdef __linux__ // Try inserting the kernel module bool res = insert_module(); - if (!res) - { + if(!res) { return -1; } -#endif // __linux__ +#endif // __linux__ signal(SIGPIPE, sigint_handler); -#endif // _WIN32 +#endif // _WIN32 signal(SIGINT, sigint_handler); signal(SIGTERM, sigint_handler); - if (enable_glogger) - { + if(enable_glogger) { std::cout << "-- Enabled g_logger.'" << std::endl; libsinsp_logger()->set_severity(sinsp_logger::SEV_DEBUG); libsinsp_logger()->add_stdout_log(); } - if(!filter_string.empty()) - { - try - { + if(!filter_string.empty()) { + try { inspector.set_filter(filter_string); - } - catch(const sinsp_exception& e) - { + } catch(const sinsp_exception& e) { cerr << "[ERROR] Unable to set filter: " << e.what() << endl; } } auto events_sc_codes = extract_filter_sc_codes(inspector); - if(!events_sc_codes.empty()) - { + if(!events_sc_codes.empty()) { auto events_sc_names = libsinsp::events::sc_set_to_sc_names(events_sc_codes); - printf("-- Filter AST (%ld) ppm sc names: %s\n", events_sc_codes.size(), concat_set_in_order(events_sc_names).c_str()); + printf("-- Filter AST (%ld) ppm sc names: %s\n", + events_sc_codes.size(), + concat_set_in_order(events_sc_names).c_str()); } open_engine(inspector, events_sc_codes); @@ -427,61 +402,57 @@ int main(int argc, char** argv) inspector.start_capture(); - default_formatter = std::make_unique(&inspector, default_output, s_filterlist); - process_formatter = std::make_unique(&inspector, process_output, s_filterlist); + default_formatter = + std::make_unique(&inspector, default_output, s_filterlist); + process_formatter = + std::make_unique(&inspector, process_output, s_filterlist); net_formatter = std::make_unique(&inspector, net_output, s_filterlist); std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); uint64_t num_events = 0; - while(!g_interrupted && num_events < max_events) - { - sinsp_evt* ev = get_event(inspector, [](const std::string& error_msg) - { cout << "[ERROR] " << error_msg << endl; }); - if(ev != nullptr) - { + while(!g_interrupted && num_events < max_events) { + sinsp_evt* ev = get_event(inspector, [](const std::string& error_msg) { + cout << "[ERROR] " << error_msg << endl; + }); + if(ev != nullptr) { sinsp_threadinfo* thread = ev->get_thread_info(); - if(!thread || g_all_threads || thread->is_main_thread()) - { + if(!thread || g_all_threads || thread->is_main_thread()) { dump(inspector, ev); num_events++; } } } std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); - const auto duration = std::chrono::duration_cast(end - begin).count(); + const auto duration = + std::chrono::duration_cast(end - begin).count(); inspector.stop_capture(); std::cout << "-- Stop capture" << std::endl; std::cout << "Retrieved events: " << std::to_string(num_events) << std::endl; std::cout << "Time spent: " << duration << "ms" << std::endl; - if (duration > 0) - { + if(duration > 0) { std::cout << "Events/ms: " << num_events / (long double)duration << std::endl; } return 0; } -sinsp_evt* get_event(sinsp& inspector, std::function handle_error) -{ +sinsp_evt* get_event(sinsp& inspector, std::function handle_error) { sinsp_evt* ev = nullptr; int32_t res = inspector.next(&ev); - if (res == SCAP_SUCCESS) - { + if(res == SCAP_SUCCESS) { return ev; } - if (res == SCAP_EOF) - { + if(res == SCAP_EOF) { std::cout << "-- EOF" << std::endl; g_interrupted = true; return nullptr; } - if(res != SCAP_TIMEOUT && res != SCAP_FILTERED_EVENT) - { + if(res != SCAP_TIMEOUT && res != SCAP_FILTERED_EVENT) { handle_error(inspector.getlasterr()); std::this_thread::sleep_for(std::chrono::seconds(g_backoff_timeout_secs)); } @@ -489,82 +460,64 @@ sinsp_evt* get_event(sinsp& inspector, std::function h return nullptr; } -void formatted_dump(sinsp&, sinsp_evt* ev) -{ +void formatted_dump(sinsp&, sinsp_evt* ev) { std::string output; - if(ev->get_category() == EC_PROCESS) - { + if(ev->get_category() == EC_PROCESS) { process_formatter->tostring(ev, output); - } - else if(ev->get_category() == EC_NET || ev->get_category() == EC_IO_READ || ev->get_category() == EC_IO_WRITE) - { + } else if(ev->get_category() == EC_NET || ev->get_category() == EC_IO_READ || + ev->get_category() == EC_IO_WRITE) { net_formatter->tostring(ev, output); - } - else - { + } else { default_formatter->tostring(ev, output); } cout << output << std::endl; } -static void hexdump(const unsigned char* buf, size_t len) -{ +static void hexdump(const unsigned char* buf, size_t len) { bool in_ascii = false; putc('[', stdout); - for(size_t i = 0; i < len; ++i) - { - if(isprint(buf[i])) - { - if(!in_ascii) - { + for(size_t i = 0; i < len; ++i) { + if(isprint(buf[i])) { + if(!in_ascii) { in_ascii = true; - if(i > 0) - { + if(i > 0) { putc(' ', stdout); } putc('"', stdout); } putc(buf[i], stdout); - } - else - { - if(in_ascii) - { + } else { + if(in_ascii) { in_ascii = false; fputs("\" ", stdout); - } - else if(i > 0) - { + } else if(i > 0) { putc(' ', stdout); } printf("%02x", buf[i]); } } - if(in_ascii) - { + if(in_ascii) { putc('"', stdout); } putc(']', stdout); } -void raw_dump(sinsp& inspector, sinsp_evt* ev) -{ +void raw_dump(sinsp& inspector, sinsp_evt* ev) { string date_time; sinsp_utils::ts_to_iso_8601(ev->get_ts(), &date_time); cout << "ts=" << date_time; cout << " tid=" << ev->get_tid(); - cout << " type=" << (ev->get_direction() == SCAP_ED_IN ? '>' : '<') << get_event_type_name(ev); + cout << " type=" << (ev->get_direction() == SCAP_ED_IN ? '>' : '<') << get_event_type_name(ev); cout << " category=" << get_event_category_name(ev->get_category()); cout << " nparams=" << ev->get_num_params(); - for(size_t i = 0; i < ev->get_num_params(); ++i) - { - const sinsp_evt_param *p = ev->get_param(i); - const struct ppm_param_info *pi = ev->get_param_info(i); + for(size_t i = 0; i < ev->get_num_params(); ++i) { + const sinsp_evt_param* p = ev->get_param(i); + const struct ppm_param_info* pi = ev->get_param_info(i); cout << ' ' << i << ':' << pi->name << '='; hexdump((const unsigned char*)p->m_val, p->m_len); } diff --git a/userspace/libsinsp/examples/util.cpp b/userspace/libsinsp/examples/util.cpp index 85a7231b22..5d9d0650d7 100644 --- a/userspace/libsinsp/examples/util.cpp +++ b/userspace/libsinsp/examples/util.cpp @@ -21,45 +21,60 @@ limitations under the License. // // Get the string representation of a ppm_event_category // -std::string get_event_category_name(ppm_event_category category) -{ - switch(category) - { - case EC_UNKNOWN: return "UNKNOWN"; - case EC_OTHER: return "OTHER"; - case EC_FILE: return "FILE"; - case EC_NET: return "NET"; - case EC_IPC: return "IPC"; - case EC_MEMORY: return "MEMORY"; - case EC_PROCESS: return "PROCESS"; - case EC_SLEEP: return "SLEEP"; - case EC_SYSTEM: return "SYSTEM"; - case EC_SIGNAL: return "SIGNAL"; - case EC_USER: return "USER"; - case EC_TIME: return "TIME"; - case EC_PROCESSING: return "PROCESSING"; - case EC_IO_READ: return "IO_READ"; - case EC_IO_WRITE: return "IO_WRITE"; - case EC_IO_OTHER: return "IO_OTHER"; - case EC_WAIT: return "WAIT"; - case EC_SCHEDULER: return "SCHEDULER"; - case EC_INTERNAL: return "INTERNAL"; - default: return "ERROR CONDITION"; - }; +std::string get_event_category_name(ppm_event_category category) { + switch(category) { + case EC_UNKNOWN: + return "UNKNOWN"; + case EC_OTHER: + return "OTHER"; + case EC_FILE: + return "FILE"; + case EC_NET: + return "NET"; + case EC_IPC: + return "IPC"; + case EC_MEMORY: + return "MEMORY"; + case EC_PROCESS: + return "PROCESS"; + case EC_SLEEP: + return "SLEEP"; + case EC_SYSTEM: + return "SYSTEM"; + case EC_SIGNAL: + return "SIGNAL"; + case EC_USER: + return "USER"; + case EC_TIME: + return "TIME"; + case EC_PROCESSING: + return "PROCESSING"; + case EC_IO_READ: + return "IO_READ"; + case EC_IO_WRITE: + return "IO_WRITE"; + case EC_IO_OTHER: + return "IO_OTHER"; + case EC_WAIT: + return "WAIT"; + case EC_SCHEDULER: + return "SCHEDULER"; + case EC_INTERNAL: + return "INTERNAL"; + default: + return "ERROR CONDITION"; + }; } // // Get the string representation of a ppm_event_type // -std::string get_event_type_name(sinsp_evt *ev) -{ +std::string get_event_type_name(sinsp_evt *ev) { uint16_t type = ev->get_type(); - if (type >= PPM_EVENT_MAX) - { + if(type >= PPM_EVENT_MAX) { return "UNKNOWN " + std::to_string(type); } - if (type != PPME_GENERIC_E && type != PPME_GENERIC_X) - { + if(type != PPME_GENERIC_E && type != PPME_GENERIC_X) { return scap_get_event_info_table()[type].name; } diff --git a/userspace/libsinsp/fdinfo.cpp b/userspace/libsinsp/fdinfo.cpp index a39e1d402d..f04d530405 100644 --- a/userspace/libsinsp/fdinfo.cpp +++ b/userspace/libsinsp/fdinfo.cpp @@ -24,10 +24,8 @@ limitations under the License. #include #include -char sinsp_fdinfo::get_typechar() const -{ - switch(m_type) - { +char sinsp_fdinfo::get_typechar() const { + switch(m_type) { case SCAP_FD_FILE_V2: case SCAP_FD_FILE: return CHAR_FD_FILE; @@ -72,15 +70,13 @@ char sinsp_fdinfo::get_typechar() const case SCAP_FD_PIDFD: return CHAR_FD_PIDFD; default: -// ASSERT(false); + // ASSERT(false); return '?'; } } -const char* sinsp_fdinfo::get_typestring() const -{ - switch(m_type) - { +const char* sinsp_fdinfo::get_typestring() const { + switch(m_type) { case SCAP_FD_FILE_V2: case SCAP_FD_FILE: return "file"; @@ -123,13 +119,11 @@ const char* sinsp_fdinfo::get_typestring() const } } -sinsp_fdinfo::sinsp_fdinfo(const std::shared_ptr& dyn_fields) - : table_entry(dyn_fields) -{ -} +sinsp_fdinfo::sinsp_fdinfo( + const std::shared_ptr& dyn_fields): + table_entry(dyn_fields) {} -libsinsp::state::static_struct::field_infos sinsp_fdinfo::static_fields() const -{ +libsinsp::state::static_struct::field_infos sinsp_fdinfo::static_fields() const { libsinsp::state::static_struct::field_infos ret; // the m_type is weird because it's a C-defined non-scoped enum, meaning that it @@ -138,7 +132,7 @@ libsinsp::state::static_struct::field_infos sinsp_fdinfo::static_fields() const // we need to do some smart casting. Our enemy is the platform/compiler dependent // integer size with which the enum could be represented, plus the endianess // of the targeted architecture - auto is_big_endian = htonl(12) == 12; // the chosen number does not matter + auto is_big_endian = htonl(12) == 12; // the chosen number does not matter size_t type_byte_offset = is_big_endian ? (sizeof(scap_fd_type) - 1) : 0; define_static_field(ret, this, ((uint8_t*)(&m_type))[type_byte_offset], "type"); @@ -160,81 +154,99 @@ libsinsp::state::static_struct::field_infos sinsp_fdinfo::static_fields() const define_static_field(ret, this, m_sockinfo.m_ipv4info.m_fields.m_dip, "socket_ipv4_dest_dip"); define_static_field(ret, this, m_sockinfo.m_ipv4info.m_fields.m_sport, "socket_ipv4_src_port"); define_static_field(ret, this, m_sockinfo.m_ipv4info.m_fields.m_dport, "socket_ipv4_dst_port"); - define_static_field(ret, this, m_sockinfo.m_ipv4info.m_fields.m_l4proto, "socket_ipv4_l4_proto"); - define_static_field(ret, this, ((uint64_t*) &m_sockinfo.m_ipv6info.m_fields.m_sip)[0], "socket_ipv6_src_ip_low"); - define_static_field(ret, this, ((uint64_t*) &m_sockinfo.m_ipv6info.m_fields.m_sip)[1], "socket_ipv6_src_ip_high"); - define_static_field(ret, this, ((uint64_t*) &m_sockinfo.m_ipv6info.m_fields.m_dip)[0], "socket_ipv6_dest_ip_low"); - define_static_field(ret, this, ((uint64_t*) &m_sockinfo.m_ipv6info.m_fields.m_dip)[1], "socket_ipv6_dest_ip_high"); + define_static_field(ret, + this, + m_sockinfo.m_ipv4info.m_fields.m_l4proto, + "socket_ipv4_l4_proto"); + define_static_field(ret, + this, + ((uint64_t*)&m_sockinfo.m_ipv6info.m_fields.m_sip)[0], + "socket_ipv6_src_ip_low"); + define_static_field(ret, + this, + ((uint64_t*)&m_sockinfo.m_ipv6info.m_fields.m_sip)[1], + "socket_ipv6_src_ip_high"); + define_static_field(ret, + this, + ((uint64_t*)&m_sockinfo.m_ipv6info.m_fields.m_dip)[0], + "socket_ipv6_dest_ip_low"); + define_static_field(ret, + this, + ((uint64_t*)&m_sockinfo.m_ipv6info.m_fields.m_dip)[1], + "socket_ipv6_dest_ip_high"); define_static_field(ret, this, m_sockinfo.m_ipv6info.m_fields.m_sport, "socket_ipv6_src_port"); define_static_field(ret, this, m_sockinfo.m_ipv6info.m_fields.m_dport, "socket_ipv6_dst_port"); - define_static_field(ret, this, m_sockinfo.m_ipv6info.m_fields.m_l4proto, "socket_ipv6_l4_proto"); + define_static_field(ret, + this, + m_sockinfo.m_ipv6info.m_fields.m_l4proto, + "socket_ipv6_l4_proto"); define_static_field(ret, this, m_sockinfo.m_ipv4serverinfo.m_ip, "socket_ipv4_server_ip"); define_static_field(ret, this, m_sockinfo.m_ipv4serverinfo.m_port, "socket_ipv4_server_port"); - define_static_field(ret, this, m_sockinfo.m_ipv4serverinfo.m_l4proto, "socket_ipv4_server_l4_proto"); - define_static_field(ret, this, ((uint64_t*) &m_sockinfo.m_ipv6serverinfo.m_ip)[0], "socket_ipv6_server_ip_low"); - define_static_field(ret, this, ((uint64_t*) &m_sockinfo.m_ipv6serverinfo.m_ip)[1], "socket_ipv6_server_ip_high"); + define_static_field(ret, + this, + m_sockinfo.m_ipv4serverinfo.m_l4proto, + "socket_ipv4_server_l4_proto"); + define_static_field(ret, + this, + ((uint64_t*)&m_sockinfo.m_ipv6serverinfo.m_ip)[0], + "socket_ipv6_server_ip_low"); + define_static_field(ret, + this, + ((uint64_t*)&m_sockinfo.m_ipv6serverinfo.m_ip)[1], + "socket_ipv6_server_ip_high"); define_static_field(ret, this, m_sockinfo.m_ipv6serverinfo.m_port, "socket_ipv6_server_port"); - define_static_field(ret, this, m_sockinfo.m_ipv6serverinfo.m_l4proto, "socket_ipv6_server_l4_proto"); + define_static_field(ret, + this, + m_sockinfo.m_ipv6serverinfo.m_l4proto, + "socket_ipv6_server_l4_proto"); define_static_field(ret, this, m_sockinfo.m_unixinfo.m_fields.m_source, "socket_unix_src"); define_static_field(ret, this, m_sockinfo.m_unixinfo.m_fields.m_dest, "socket_unix_dest"); return ret; } -std::string sinsp_fdinfo::tostring_clean() const -{ +std::string sinsp_fdinfo::tostring_clean() const { std::string tstr = m_name; sanitize_string(tstr); return tstr; } -void sinsp_fdinfo::add_filename_raw(std::string_view rawpath) -{ +void sinsp_fdinfo::add_filename_raw(std::string_view rawpath) { m_name_raw = std::string(rawpath); } -void sinsp_fdinfo::add_filename(std::string_view fullpath) -{ +void sinsp_fdinfo::add_filename(std::string_view fullpath) { m_name = std::string(fullpath); } bool sinsp_fdinfo::set_net_role_by_guessing(sinsp* inspector, - sinsp_threadinfo* ptinfo, - sinsp_fdinfo* pfdinfo, - bool incoming) -{ + sinsp_threadinfo* ptinfo, + sinsp_fdinfo* pfdinfo, + bool incoming) { // // If this process owns the port, mark it as server, otherwise mark it as client // - if(ptinfo->is_bound_to_port(pfdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport)) - { - if(ptinfo->uses_client_port(pfdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport)) - { + if(ptinfo->is_bound_to_port(pfdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport)) { + if(ptinfo->uses_client_port(pfdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport)) { goto wildass_guess; } pfdinfo->set_role_server(); return true; - } - else - { + } else { pfdinfo->set_role_client(); return true; } wildass_guess: - if(!(pfdinfo->m_flags & (sinsp_fdinfo::FLAGS_ROLE_CLIENT | sinsp_fdinfo::FLAGS_ROLE_SERVER))) - { + if(!(pfdinfo->m_flags & (sinsp_fdinfo::FLAGS_ROLE_CLIENT | sinsp_fdinfo::FLAGS_ROLE_SERVER))) { // // We just assume that a server usually starts with a read and a client with a write // - if(incoming) - { + if(incoming) { pfdinfo->set_role_server(); - } - else - { + } else { pfdinfo->set_role_client(); } } @@ -242,48 +254,34 @@ bool sinsp_fdinfo::set_net_role_by_guessing(sinsp* inspector, return true; } -scap_l4_proto sinsp_fdinfo::get_l4proto() const -{ +scap_l4_proto sinsp_fdinfo::get_l4proto() const { scap_fd_type evt_type = m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - if((scap_l4_proto)m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_RAW) - { + if(evt_type == SCAP_FD_IPV4_SOCK) { + if((scap_l4_proto)m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_RAW) { return SCAP_L4_RAW; } - if(is_role_none()) - { + if(is_role_none()) { return SCAP_L4_NA; } return (scap_l4_proto)(m_sockinfo.m_ipv4info.m_fields.m_l4proto); - } - else if(evt_type == SCAP_FD_IPV4_SERVSOCK) - { + } else if(evt_type == SCAP_FD_IPV4_SERVSOCK) { return (scap_l4_proto)(m_sockinfo.m_ipv4serverinfo.m_l4proto); - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - if((scap_l4_proto)m_sockinfo.m_ipv6info.m_fields.m_l4proto == SCAP_L4_RAW) - { + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + if((scap_l4_proto)m_sockinfo.m_ipv6info.m_fields.m_l4proto == SCAP_L4_RAW) { return SCAP_L4_RAW; } - if(is_role_none()) - { + if(is_role_none()) { return SCAP_L4_NA; } return (scap_l4_proto)(m_sockinfo.m_ipv6info.m_fields.m_l4proto); - } - else if(evt_type == SCAP_FD_IPV6_SERVSOCK) - { + } else if(evt_type == SCAP_FD_IPV6_SERVSOCK) { return (scap_l4_proto)(m_sockinfo.m_ipv6serverinfo.m_l4proto); - } - else - { + } else { return SCAP_L4_NA; } } @@ -293,31 +291,24 @@ static const auto s_fdtable_static_fields = sinsp_fdinfo().static_fields(); /////////////////////////////////////////////////////////////////////////////// // sinsp_fdtable implementation /////////////////////////////////////////////////////////////////////////////// -sinsp_fdtable::sinsp_fdtable(sinsp* inspector) - : table("file_descriptors", &s_fdtable_static_fields) -{ +sinsp_fdtable::sinsp_fdtable(sinsp* inspector): + table("file_descriptors", &s_fdtable_static_fields) { m_tid = 0; m_inspector = inspector; - if (m_inspector != nullptr) - { + if(m_inspector != nullptr) { m_sinsp_stats_v2 = m_inspector->get_sinsp_stats_v2(); - } - else - { + } else { m_sinsp_stats_v2 = nullptr; } reset_cache(); } -inline const std::shared_ptr& sinsp_fdtable::find_ref(int64_t fd) -{ +inline const std::shared_ptr& sinsp_fdtable::find_ref(int64_t fd) { // // Try looking up in our simple cache // - if(m_last_accessed_fd != -1 && fd == m_last_accessed_fd) - { - if (m_sinsp_stats_v2) - { + if(m_last_accessed_fd != -1 && fd == m_last_accessed_fd) { + if(m_sinsp_stats_v2) { m_sinsp_stats_v2->m_n_cached_fd_lookups++; } return m_last_accessed_fdinfo; @@ -328,18 +319,13 @@ inline const std::shared_ptr& sinsp_fdtable::find_ref(int64_t fd) // auto fdit = m_table.find(fd); - if(fdit == m_table.end()) - { - if (m_sinsp_stats_v2) - { + if(fdit == m_table.end()) { + if(m_sinsp_stats_v2) { m_sinsp_stats_v2->m_n_failed_fd_lookups++; } return m_nullptr_ret; - } - else - { - if (m_sinsp_stats_v2 != nullptr) - { + } else { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_noncached_fd_lookups++; } @@ -350,10 +336,10 @@ inline const std::shared_ptr& sinsp_fdtable::find_ref(int64_t fd) } } -inline const std::shared_ptr& sinsp_fdtable::add_ref(int64_t fd, std::unique_ptr fdinfo) -{ - if (fdinfo->dynamic_fields() != dynamic_fields()) - { +inline const std::shared_ptr& sinsp_fdtable::add_ref( + int64_t fd, + std::unique_ptr fdinfo) { + if(fdinfo->dynamic_fields() != dynamic_fields()) { throw sinsp_exception("adding entry with incompatible dynamic defs to fd table"); } @@ -369,33 +355,25 @@ inline const std::shared_ptr& sinsp_fdtable::add_ref(int64_t fd, s // a. the table size is under the limit so create a new entry // b. table size is over the limit, discard the fd // 2. fd is already in the table, replace it - if(it == m_table.end()) - { - if(m_table.size() < m_inspector->m_max_fdtable_size) - { + if(it == m_table.end()) { + if(m_table.size() < m_inspector->m_max_fdtable_size) { // // No entry in the table, this is the normal case // m_last_accessed_fd = -1; - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_added_fds++; } return m_table.emplace(fd, std::move(fdinfo)).first->second; - } - else - { + } else { return m_nullptr_ret; } - } - else - { + } else { // // the fd is already in the table. // - if(it->second->m_flags & sinsp_fdinfo::FLAGS_CLOSE_IN_PROGRESS) - { + if(it->second->m_flags & sinsp_fdinfo::FLAGS_CLOSE_IN_PROGRESS) { // // Sometimes an FD-creating syscall can be called on an FD that is being closed (i.e // the close enter has arrived but the close exit has not arrived yet). @@ -406,20 +384,19 @@ inline const std::shared_ptr& sinsp_fdtable::add_ref(int64_t fd, s fdinfo->m_flags |= sinsp_fdinfo::FLAGS_CLOSE_CANCELED; m_table[CANCELED_FD_NUMBER] = it->second->clone(); - } - else - { + } else { // // This can happen if: // - the event is a dup2 or dup3 that overwrites an existing FD (perfectly legal) // - a close() has been dropped when capturing - // - an fd has been closed by clone() or execve() (it happens when the fd is opened with the FD_CLOEXEC flag, + // - an fd has been closed by clone() or execve() (it happens when the fd is opened + // with the FD_CLOEXEC flag, // which we don't currently parse. - // In either case, removing the old fd, replacing it with the new one and keeping going is a reasonable - // choice. We include an assertion to catch the situation. + // In either case, removing the old fd, replacing it with the new one and keeping going + // is a reasonable choice. We include an assertion to catch the situation. // // XXX Can't have this enabled until the FD_CLOEXEC flag is supported - //ASSERT(false); + // ASSERT(false); } // @@ -431,34 +408,27 @@ inline const std::shared_ptr& sinsp_fdtable::add_ref(int64_t fd, s } } -bool sinsp_fdtable::erase(int64_t fd) -{ +bool sinsp_fdtable::erase(int64_t fd) { auto fdit = m_table.find(fd); - if(fd == m_last_accessed_fd) - { + if(fd == m_last_accessed_fd) { m_last_accessed_fd = -1; } - if(fdit == m_table.end()) - { + if(fdit == m_table.end()) { // // Looks like there's no fd to remove. // Either the fd creation event was dropped or (more likely) our logic doesn't support the // call that created this fd. The assertion will detect it, while in release mode we just // keep going. // - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_failed_fd_lookups++; } return false; - } - else - { + } else { m_table.erase(fdit); - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_noncached_fd_lookups++; m_sinsp_stats_v2->m_n_removed_fds++; } @@ -466,56 +436,49 @@ bool sinsp_fdtable::erase(int64_t fd) } } -void sinsp_fdtable::clear() -{ +void sinsp_fdtable::clear() { m_table.clear(); } -size_t sinsp_fdtable::size() const -{ +size_t sinsp_fdtable::size() const { return m_table.size(); } -void sinsp_fdtable::reset_cache() -{ +void sinsp_fdtable::reset_cache() { m_last_accessed_fd = -1; } -void sinsp_fdtable::lookup_device(sinsp_fdinfo* fdi, uint64_t fd) -{ +void sinsp_fdtable::lookup_device(sinsp_fdinfo* fdi, uint64_t fd) { #ifndef _WIN32 if(m_inspector == nullptr || m_inspector->is_offline() || - (m_inspector->is_plugin() && !m_inspector->is_syscall_plugin())) - { + (m_inspector->is_plugin() && !m_inspector->is_syscall_plugin())) { return; } - if(m_tid != 0 && m_tid != (uint64_t)-1 && fdi->is_file() && fdi->m_dev == 0 && fdi->m_mount_id != 0) - { + if(m_tid != 0 && m_tid != (uint64_t)-1 && fdi->is_file() && fdi->m_dev == 0 && + fdi->m_mount_id != 0) { char procdir[SCAP_MAX_PATH_SIZE]; snprintf(procdir, sizeof(procdir), "%s/proc/%ld/", scap_get_host_root(), m_tid); - fdi->m_dev = scap_get_device_by_mount_id(m_inspector->get_scap_platform(), procdir, fdi->m_mount_id); - fdi->m_mount_id = 0; // don't try again + fdi->m_dev = scap_get_device_by_mount_id(m_inspector->get_scap_platform(), + procdir, + fdi->m_mount_id); + fdi->m_mount_id = 0; // don't try again } -#endif // _WIN32 +#endif // _WIN32 } -sinsp_fdinfo* sinsp_fdtable::find(int64_t fd) -{ +sinsp_fdinfo* sinsp_fdtable::find(int64_t fd) { return find_ref(fd).get(); } -sinsp_fdinfo* sinsp_fdtable::add(int64_t fd, std::unique_ptr fdinfo) -{ +sinsp_fdinfo* sinsp_fdtable::add(int64_t fd, std::unique_ptr fdinfo) { return add_ref(fd, std::move(fdinfo)).get(); } -std::unique_ptr sinsp_fdtable::new_entry() const -{ +std::unique_ptr sinsp_fdtable::new_entry() const { return m_inspector->build_fdinfo(); }; -std::shared_ptr sinsp_fdtable::get_entry(const int64_t& key) -{ +std::shared_ptr sinsp_fdtable::get_entry(const int64_t& key) { return find_ref(key); } diff --git a/userspace/libsinsp/fdinfo.h b/userspace/libsinsp/fdinfo.h index 9549fc6851..47d1ac4b78 100644 --- a/userspace/libsinsp/fdinfo.h +++ b/userspace/libsinsp/fdinfo.h @@ -35,27 +35,27 @@ limitations under the License. #endif // fd type characters -#define CHAR_FD_FILE 'f' -#define CHAR_FD_IPV4_SOCK '4' -#define CHAR_FD_IPV6_SOCK '6' -#define CHAR_FD_DIRECTORY 'd' -#define CHAR_FD_IPV4_SERVSOCK '4' -#define CHAR_FD_IPV6_SERVSOCK '6' -#define CHAR_FD_FIFO 'p' -#define CHAR_FD_UNIX_SOCK 'u' -#define CHAR_FD_EVENT 'e' -#define CHAR_FD_UNKNOWN 'o' -#define CHAR_FD_UNSUPPORTED 'X' -#define CHAR_FD_SIGNAL 's' -#define CHAR_FD_EVENTPOLL 'l' -#define CHAR_FD_INOTIFY 'i' -#define CHAR_FD_TIMERFD 't' -#define CHAR_FD_NETLINK 'n' -#define CHAR_FD_BPF 'b' -#define CHAR_FD_USERFAULTFD 'u' -#define CHAR_FD_IO_URING 'r' -#define CHAR_FD_MEMFD 'm' -#define CHAR_FD_PIDFD 'P' +#define CHAR_FD_FILE 'f' +#define CHAR_FD_IPV4_SOCK '4' +#define CHAR_FD_IPV6_SOCK '6' +#define CHAR_FD_DIRECTORY 'd' +#define CHAR_FD_IPV4_SERVSOCK '4' +#define CHAR_FD_IPV6_SERVSOCK '6' +#define CHAR_FD_FIFO 'p' +#define CHAR_FD_UNIX_SOCK 'u' +#define CHAR_FD_EVENT 'e' +#define CHAR_FD_UNKNOWN 'o' +#define CHAR_FD_UNSUPPORTED 'X' +#define CHAR_FD_SIGNAL 's' +#define CHAR_FD_EVENTPOLL 'l' +#define CHAR_FD_INOTIFY 'i' +#define CHAR_FD_TIMERFD 't' +#define CHAR_FD_NETLINK 'n' +#define CHAR_FD_BPF 'b' +#define CHAR_FD_USERFAULTFD 'u' +#define CHAR_FD_IO_URING 'r' +#define CHAR_FD_MEMFD 'm' +#define CHAR_FD_PIDFD 'P' class sinsp; class sinsp_threadinfo; @@ -65,13 +65,12 @@ class sinsp_threadinfo; * @{ */ -union sinsp_sockinfo -{ - ipv4tuple m_ipv4info; ///< The tuple if this an IPv4 socket. - ipv6tuple m_ipv6info; ///< The tuple if this an IPv6 socket. +union sinsp_sockinfo { + ipv4tuple m_ipv4info; ///< The tuple if this an IPv4 socket. + ipv6tuple m_ipv6info; ///< The tuple if this an IPv6 socket. ipv4serverinfo m_ipv4serverinfo; ///< Information about an IPv4 server socket. - ipv6serverinfo m_ipv6serverinfo; ///< Information about an IPv6 server socket. - unix_tuple m_unixinfo; ///< The tuple if this a unix socket. + ipv6serverinfo m_ipv6serverinfo; ///< Information about an IPv6 server socket. + unix_tuple m_unixinfo; ///< The tuple if this a unix socket. }; /*! @@ -83,17 +82,15 @@ union sinsp_sockinfo you get them by calling \ref sinsp_evt::get_fd_info or \ref sinsp_threadinfo::get_fd. */ -class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry -{ +class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry { public: /*! \brief FD flags. */ - enum flags - { + enum flags { FLAGS_NONE = 0, FLAGS_FROM_PROC = (1 << 0), - //FLAGS_TRANSACTION = (1 << 1), // note: deprecated + // FLAGS_TRANSACTION = (1 << 1), // note: deprecated FLAGS_ROLE_CLIENT = (1 << 2), FLAGS_ROLE_SERVER = (1 << 3), FLAGS_CLOSE_IN_PROGRESS = (1 << 4), @@ -113,7 +110,8 @@ class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry FLAGS_OVERLAY_LOWER = (1 << 18), }; - sinsp_fdinfo(const std::shared_ptr& dyn_fields = nullptr); + sinsp_fdinfo(const std::shared_ptr& dyn_fields = + nullptr); sinsp_fdinfo(sinsp_fdinfo&& o) = default; sinsp_fdinfo& operator=(sinsp_fdinfo&& o) = default; sinsp_fdinfo(const sinsp_fdinfo& o) = default; @@ -123,8 +121,7 @@ class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry libsinsp::state::static_struct::field_infos static_fields() const override; - virtual std::unique_ptr clone() const - { + virtual std::unique_ptr clone() const { return std::make_unique(*this); } @@ -138,7 +135,8 @@ class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry /*! \brief Return an ASCII string that identifies the FD type. - Can be on of 'file', 'directory', ipv4', 'ipv6', 'unix', 'pipe', 'event', 'signalfd', 'eventpoll', 'inotify', 'signalfd'. + Can be on of 'file', 'directory', ipv4', 'ipv6', 'unix', 'pipe', 'event', 'signalfd', + 'eventpoll', 'inotify', 'signalfd'. */ const char* get_typestring() const; @@ -150,128 +148,82 @@ class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry /*! \brief Return true if this is a log device. */ - inline bool is_syslog() const - { - return m_name.find("/dev/log") != std::string::npos; - } + inline bool is_syslog() const { return m_name.find("/dev/log") != std::string::npos; } /*! \brief Returns true if this is a unix socket. */ - inline bool is_unix_socket() const - { - return m_type == SCAP_FD_UNIX_SOCK; - } + inline bool is_unix_socket() const { return m_type == SCAP_FD_UNIX_SOCK; } /*! \brief Returns true if this is an IPv4 socket. */ - inline bool is_ipv4_socket() const - { - return m_type == SCAP_FD_IPV4_SOCK; - } + inline bool is_ipv4_socket() const { return m_type == SCAP_FD_IPV4_SOCK; } /*! \brief Returns true if this is an IPv4 socket. */ - inline bool is_ipv6_socket() const - { - return m_type == SCAP_FD_IPV6_SOCK; - } + inline bool is_ipv6_socket() const { return m_type == SCAP_FD_IPV6_SOCK; } /*! \brief Returns true if this is a UDP socket. */ - inline bool is_udp_socket() const - { - return m_type == SCAP_FD_IPV4_SOCK && m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_UDP; + inline bool is_udp_socket() const { + return m_type == SCAP_FD_IPV4_SOCK && + m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_UDP; } /*! \brief Returns true if this is a unix TCP. */ - inline bool is_tcp_socket() const - { - return m_type == SCAP_FD_IPV4_SOCK && m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_TCP; + inline bool is_tcp_socket() const { + return m_type == SCAP_FD_IPV4_SOCK && + m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_TCP; } /*! \brief Returns true if this is a pipe. */ - inline bool is_pipe() const - { - return m_type == SCAP_FD_FIFO; - } + inline bool is_pipe() const { return m_type == SCAP_FD_FIFO; } /*! \brief Returns true if this is a file. */ - inline bool is_file() const - { - return m_type == SCAP_FD_FILE || m_type == SCAP_FD_FILE_V2; - } + inline bool is_file() const { return m_type == SCAP_FD_FILE || m_type == SCAP_FD_FILE_V2; } /*! \brief Returns true if this is a directory. */ - inline bool is_directory() const - { - return m_type == SCAP_FD_DIRECTORY; - } + inline bool is_directory() const { return m_type == SCAP_FD_DIRECTORY; } /*! \brief Returns true if this is a pidfd, created through pidfd_open. */ - inline bool is_pidfd() const - { - return m_type == SCAP_FD_PIDFD; - } + inline bool is_pidfd() const { return m_type == SCAP_FD_PIDFD; } - inline uint16_t get_serverport() const - { - if(m_type == SCAP_FD_IPV4_SOCK) - { + inline uint16_t get_serverport() const { + if(m_type == SCAP_FD_IPV4_SOCK) { return m_sockinfo.m_ipv4info.m_fields.m_dport; - } - else if(m_type == SCAP_FD_IPV6_SOCK) - { + } else if(m_type == SCAP_FD_IPV6_SOCK) { return m_sockinfo.m_ipv6info.m_fields.m_dport; - } - else - { + } else { return 0; } } - inline uint32_t get_device() const - { - return m_dev; - } + inline uint32_t get_device() const { return m_dev; } // see new_encode_dev in include/linux/kdev_t.h - inline uint32_t get_device_major() const - { - return (m_dev & 0xfff00) >> 8; - } + inline uint32_t get_device_major() const { return (m_dev & 0xfff00) >> 8; } // see new_encode_dev in include/linux/kdev_t.h - inline uint32_t get_device_minor() const - { - return (m_dev & 0xff) | ((m_dev >> 12) & 0xfff00); - } + inline uint32_t get_device_minor() const { return (m_dev & 0xff) | ((m_dev >> 12) & 0xfff00); } - inline uint64_t get_ino() const - { - return m_ino; - } + inline uint64_t get_ino() const { return m_ino; } - inline int64_t get_pid() const - { - return m_pid; - } + inline int64_t get_pid() const { return m_pid; } - inline void set_unix_info(uint8_t* packed_data) - { + inline void set_unix_info(uint8_t* packed_data) { memcpy(&m_sockinfo.m_unixinfo.m_fields.m_source, packed_data + 1, sizeof(uint64_t)); memcpy(&m_sockinfo.m_unixinfo.m_fields.m_dest, packed_data + 9, sizeof(uint64_t)); } @@ -284,54 +236,43 @@ class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry /*! \brief Return true if this FD is a socket server */ - inline bool is_role_server() const - { + inline bool is_role_server() const { return (m_flags & FLAGS_ROLE_SERVER) == FLAGS_ROLE_SERVER; } /*! \brief Return true if this FD is a socket client */ - inline bool is_role_client() const - { + inline bool is_role_client() const { return (m_flags & FLAGS_ROLE_CLIENT) == FLAGS_ROLE_CLIENT; } /*! \brief Return true if this FD is neither a client nor a server */ - inline bool is_role_none() const - { + inline bool is_role_none() const { return (m_flags & (FLAGS_ROLE_CLIENT | FLAGS_ROLE_SERVER)) == 0; } - inline bool is_socket_connected() const - { + inline bool is_socket_connected() const { return (m_flags & FLAGS_SOCKET_CONNECTED) == FLAGS_SOCKET_CONNECTED; } - inline bool is_socket_pending() const - { + inline bool is_socket_pending() const { return (m_flags & FLAGS_CONNECTION_PENDING) == FLAGS_CONNECTION_PENDING; } - inline bool is_socket_failed() const - { + inline bool is_socket_failed() const { return (m_flags & FLAGS_CONNECTION_FAILED) == FLAGS_CONNECTION_FAILED; } - inline bool is_cloned() const - { - return (m_flags & FLAGS_IS_CLONED) == FLAGS_IS_CLONED; - } + inline bool is_cloned() const { return (m_flags & FLAGS_IS_CLONED) == FLAGS_IS_CLONED; } - inline bool is_overlay_upper() const - { + inline bool is_overlay_upper() const { return (m_flags & FLAGS_OVERLAY_UPPER) == FLAGS_OVERLAY_UPPER; } - inline bool is_overlay_lower() const - { + inline bool is_overlay_lower() const { return (m_flags & FLAGS_OVERLAY_LOWER) == FLAGS_OVERLAY_LOWER; } @@ -339,122 +280,88 @@ class SINSP_PUBLIC sinsp_fdinfo : public libsinsp::state::table_entry void add_filename(std::string_view fullpath); - inline void set_role_server() - { - m_flags |= FLAGS_ROLE_SERVER; - } + inline void set_role_server() { m_flags |= FLAGS_ROLE_SERVER; } - inline void set_role_client() - { - m_flags |= FLAGS_ROLE_CLIENT; - } + inline void set_role_client() { m_flags |= FLAGS_ROLE_CLIENT; } bool set_net_role_by_guessing(sinsp* inspector, - sinsp_threadinfo* ptinfo, - sinsp_fdinfo* pfdinfo, - bool incoming); + sinsp_threadinfo* ptinfo, + sinsp_fdinfo* pfdinfo, + bool incoming); - inline void reset_flags() - { - m_flags = FLAGS_NONE; - } + inline void reset_flags() { m_flags = FLAGS_NONE; } - inline void set_socketpipe() - { - m_flags |= FLAGS_IS_SOCKET_PIPE; - } + inline void set_socketpipe() { m_flags |= FLAGS_IS_SOCKET_PIPE; } - inline bool is_socketpipe() const - { + inline bool is_socketpipe() const { return (m_flags & FLAGS_IS_SOCKET_PIPE) == FLAGS_IS_SOCKET_PIPE; } - inline bool has_no_role() const - { - return !is_role_client() && !is_role_server(); - } + inline bool has_no_role() const { return !is_role_client() && !is_role_server(); } - inline void set_inpipeline_r() - { - m_flags |= FLAGS_IN_BASELINE_R; - } + inline void set_inpipeline_r() { m_flags |= FLAGS_IN_BASELINE_R; } - inline void set_inpipeline_rw() - { - m_flags |= FLAGS_IN_BASELINE_RW; - } + inline void set_inpipeline_rw() { m_flags |= FLAGS_IN_BASELINE_RW; } - inline void set_inpipeline_other() - { - m_flags |= FLAGS_IN_BASELINE_OTHER; - } + inline void set_inpipeline_other() { m_flags |= FLAGS_IN_BASELINE_OTHER; } - inline void reset_inpipeline() - { + inline void reset_inpipeline() { m_flags &= ~FLAGS_IN_BASELINE_R; m_flags &= ~FLAGS_IN_BASELINE_RW; m_flags &= ~FLAGS_IN_BASELINE_OTHER; } - inline bool is_inpipeline_r() const - { + inline bool is_inpipeline_r() const { return (m_flags & FLAGS_IN_BASELINE_R) == FLAGS_IN_BASELINE_R; } - inline bool is_inpipeline_rw() const - { + inline bool is_inpipeline_rw() const { return (m_flags & FLAGS_IN_BASELINE_RW) == FLAGS_IN_BASELINE_RW; } - inline bool is_inpipeline_other() const - { + inline bool is_inpipeline_other() const { return (m_flags & FLAGS_IN_BASELINE_OTHER) == FLAGS_IN_BASELINE_OTHER; } - inline void set_socket_connected() - { + inline void set_socket_connected() { m_flags &= ~(FLAGS_CONNECTION_PENDING | FLAGS_CONNECTION_FAILED); m_flags |= FLAGS_SOCKET_CONNECTED; } - inline void set_socket_pending() - { + inline void set_socket_pending() { m_flags &= ~(FLAGS_SOCKET_CONNECTED | FLAGS_CONNECTION_FAILED); m_flags |= FLAGS_CONNECTION_PENDING; } - inline void set_socket_failed() - { + inline void set_socket_failed() { m_flags &= ~(FLAGS_SOCKET_CONNECTED | FLAGS_CONNECTION_PENDING); m_flags |= FLAGS_CONNECTION_FAILED; } - inline void set_is_cloned() - { - m_flags |= FLAGS_IS_CLONED; - } + inline void set_is_cloned() { m_flags |= FLAGS_IS_CLONED; } - inline void set_overlay_upper() - { - m_flags |= FLAGS_OVERLAY_UPPER; - } + inline void set_overlay_upper() { m_flags |= FLAGS_OVERLAY_UPPER; } - inline void set_overlay_lower() - { - m_flags |= FLAGS_OVERLAY_LOWER; - } + inline void set_overlay_lower() { m_flags |= FLAGS_OVERLAY_LOWER; } - scap_fd_type m_type = SCAP_FD_UNINITIALIZED; ///< The fd type, e.g. file, directory, IPv4 socket... - uint32_t m_openflags = 0; ///< If this FD is a file, the flags that were used when opening it. See the PPM_O_* definitions in driver/ppm_events_public.h. - sinsp_sockinfo m_sockinfo = {}; ///< Socket-specific state. This is uninitialized (zero) for non-socket FDs. - std::string m_name; ///< Human readable rendering of this FD. For files, this is the full file name. For sockets, this is the tuple. And so on. - std::string m_name_raw; // Human readable rendering of this FD. See m_name, only used if fd is a file path. Path is kept "raw" with limited sanitization and without absolute path derivation. - std::string m_oldname; // The name of this fd at the beginning of event parsing. Used to detect name changes that result from parsing an event. + scap_fd_type m_type = + SCAP_FD_UNINITIALIZED; ///< The fd type, e.g. file, directory, IPv4 socket... + uint32_t m_openflags = 0; ///< If this FD is a file, the flags that were used when opening it. + ///< See the PPM_O_* definitions in driver/ppm_events_public.h. + sinsp_sockinfo m_sockinfo = + {}; ///< Socket-specific state. This is uninitialized (zero) for non-socket FDs. + std::string m_name; ///< Human readable rendering of this FD. For files, this is the full file + ///< name. For sockets, this is the tuple. And so on. + std::string m_name_raw; // Human readable rendering of this FD. See m_name, only used if fd is + // a file path. Path is kept "raw" with limited sanitization and + // without absolute path derivation. + std::string m_oldname; // The name of this fd at the beginning of event parsing. Used to detect + // name changes that result from parsing an event. uint32_t m_flags = FLAGS_NONE; uint32_t m_dev = 0; uint32_t m_mount_id = 0; uint64_t m_ino = 0; - int64_t m_pid = 0; // only if fd is a pidfd + int64_t m_pid = 0; // only if fd is a pidfd int64_t m_fd = -1; }; @@ -466,8 +373,7 @@ struct sinsp_stats_v2; /////////////////////////////////////////////////////////////////////////////// // fd info table /////////////////////////////////////////////////////////////////////////////// -class sinsp_fdtable : public libsinsp::state::table -{ +class sinsp_fdtable : public libsinsp::state::table { public: typedef std::function fdtable_visitor_t; @@ -475,33 +381,24 @@ class sinsp_fdtable : public libsinsp::state::table sinsp_fdtable(sinsp* inspector); - inline std::unique_ptr new_fdinfo() const - { - return sinsp_fdinfo{}.clone(); - } + inline std::unique_ptr new_fdinfo() const { return sinsp_fdinfo{}.clone(); } sinsp_fdinfo* find(int64_t fd); sinsp_fdinfo* add(int64_t fd, std::unique_ptr fdinfo); - inline bool const_loop(const fdtable_const_visitor_t callback) const - { - for(auto it = m_table.begin(); it != m_table.end(); ++it) - { - if (!callback(it->first, *it->second)) - { + inline bool const_loop(const fdtable_const_visitor_t callback) const { + for(auto it = m_table.begin(); it != m_table.end(); ++it) { + if(!callback(it->first, *it->second)) { return false; } } return true; } - inline bool loop(const fdtable_visitor_t callback) - { - for(auto it = m_table.begin(); it != m_table.end(); ++it) - { - if (!callback(it->first, *it->second)) - { + inline bool loop(const fdtable_visitor_t callback) { + for(auto it = m_table.begin(); it != m_table.end(); ++it) { + if(!callback(it->first, *it->second)) { return false; } } @@ -517,46 +414,32 @@ class sinsp_fdtable : public libsinsp::state::table void reset_cache(); - inline uint64_t get_tid() const - { - return m_tid; - } + inline uint64_t get_tid() const { return m_tid; } - inline void set_tid(uint64_t v) - { - m_tid = v; - } + inline void set_tid(uint64_t v) { m_tid = v; } // ---- libsinsp::state::table implementation ---- - size_t entries_count() const override - { - return size(); - } + size_t entries_count() const override { return size(); } - void clear_entries() override - { - clear(); - } + void clear_entries() override { clear(); } std::unique_ptr new_entry() const override; - bool foreach_entry(std::function pred) override - { - return loop([&pred](int64_t i, sinsp_fdinfo& e){ return pred(e); }); + bool foreach_entry(std::function pred) override { + return loop([&pred](int64_t i, sinsp_fdinfo& e) { return pred(e); }); } std::shared_ptr get_entry(const int64_t& key) override; - std::shared_ptr add_entry(const int64_t& key, std::unique_ptr entry) override - { - if (!entry) - { + std::shared_ptr add_entry( + const int64_t& key, + std::unique_ptr entry) override { + if(!entry) { throw sinsp_exception("null entry added to fd table"); } auto fdinfo = dynamic_cast(entry.get()); - if (!fdinfo) - { + if(!fdinfo) { throw sinsp_exception("unknown entry type added to fd table"); } entry.release(); @@ -564,10 +447,7 @@ class sinsp_fdtable : public libsinsp::state::table return add_ref(key, std::unique_ptr(fdinfo)); } - bool erase_entry(const int64_t& key) override - { - return erase(key); - } + bool erase_entry(const int64_t& key) override { return erase(key); } private: sinsp* m_inspector; @@ -580,7 +460,7 @@ class sinsp_fdtable : public libsinsp::state::table int64_t m_last_accessed_fd; std::shared_ptr m_last_accessed_fdinfo; uint64_t m_tid; - std::shared_ptr m_nullptr_ret; // needed for returning a reference + std::shared_ptr m_nullptr_ret; // needed for returning a reference private: inline void lookup_device(sinsp_fdinfo* fdi, uint64_t fd); diff --git a/userspace/libsinsp/filter.cpp b/userspace/libsinsp/filter.cpp index 7a86f11e10..04d9b69d81 100644 --- a/userspace/libsinsp/filter.cpp +++ b/userspace/libsinsp/filter.cpp @@ -20,10 +20,11 @@ limitations under the License. // Why isn't this parser written using antlr or some other parser generator? // Essentially, after dealing with that stuff multiple times in the past, and fighting for a day // to configure everything with crappy documentation and code that doesn't compile, -// I decided that I agree with this http://mortoray.com/2012/07/20/why-i-dont-use-a-parser-generator/ -// and that I'm going with a manually written parser. The grammar is simple enough that it's not -// going to take more time. On the other hand I will avoid a crappy dependency that breaks my -// code at every new release, and I will have a cleaner and easier to understand code base. +// I decided that I agree with this +// http://mortoray.com/2012/07/20/why-i-dont-use-a-parser-generator/ and that I'm going with a +// manually written parser. The grammar is simple enough that it's not going to take more time. On +// the other hand I will avoid a crappy dependency that breaks my code at every new release, and I +// will have a cleaner and easier to understand code base. // #include @@ -41,27 +42,22 @@ limitations under the License. /////////////////////////////////////////////////////////////////////////////// // sinsp_filter_expression implementation /////////////////////////////////////////////////////////////////////////////// -void sinsp_filter_expression::add_check(std::unique_ptr chk) -{ +void sinsp_filter_expression::add_check(std::unique_ptr chk) { m_checks.push_back(std::move(chk)); } -bool sinsp_filter_expression::compare(sinsp_evt *evt) -{ +bool sinsp_filter_expression::compare(sinsp_evt* evt) { bool res = true; sinsp_filter_check* chk = nullptr; auto size = m_checks.size(); - for(size_t j = 0; j < size; j++) - { + for(size_t j = 0; j < size; j++) { chk = m_checks[j].get(); ASSERT(chk != NULL); - if(j == 0) - { - switch(chk->m_boolop) - { + if(j == 0) { + switch(chk->m_boolop) { case BO_NONE: res = chk->compare(evt); break; @@ -72,35 +68,28 @@ bool sinsp_filter_expression::compare(sinsp_evt *evt) ASSERT(false); break; } - } - else - { - switch(chk->m_boolop) - { + } else { + switch(chk->m_boolop) { case BO_OR: - if(res) - { + if(res) { goto done; } res = chk->compare(evt); break; case BO_AND: - if(!res) - { + if(!res) { goto done; } res = chk->compare(evt); break; case BO_ORNOT: - if(res) - { + if(res) { goto done; } res = !chk->compare(evt); break; case BO_ANDNOT: - if(!res) - { + if(!res) { goto done; } res = !chk->compare(evt); @@ -111,29 +100,24 @@ bool sinsp_filter_expression::compare(sinsp_evt *evt) } } } - done: +done: return res; } -int32_t sinsp_filter_expression::get_expr_boolop() const -{ - if(m_checks.size() <= 1) - { +int32_t sinsp_filter_expression::get_expr_boolop() const { + if(m_checks.size() <= 1) { return m_boolop; } // Reset bit 0 to remove irrelevant not boolop b0 = (boolop)((uint32_t)(m_checks.at(1)->m_boolop) & (uint32_t)~1); - if(m_checks.size() <= 2) - { + if(m_checks.size() <= 2) { return b0; } - for(uint32_t l = 2; l < m_checks.size(); l++) - { - if((boolop)((uint32_t)(m_checks.at(l)->m_boolop) & (uint32_t)~1) != b0) - { + for(uint32_t l = 2; l < m_checks.size(); l++) { + if((boolop)((uint32_t)(m_checks.at(l)->m_boolop) & (uint32_t)~1) != b0) { return -1; } } @@ -144,14 +128,12 @@ int32_t sinsp_filter_expression::get_expr_boolop() const /////////////////////////////////////////////////////////////////////////////// // sinsp_filter implementation /////////////////////////////////////////////////////////////////////////////// -sinsp_filter::sinsp_filter() -{ +sinsp_filter::sinsp_filter() { m_filter = std::make_unique(); m_curexpr = m_filter.get(); } -void sinsp_filter::push_expression(boolop op) -{ +void sinsp_filter::push_expression(boolop op) { sinsp_filter_expression* newexpr = new sinsp_filter_expression(); newexpr->m_boolop = op; newexpr->m_parent = m_curexpr; @@ -160,25 +142,22 @@ void sinsp_filter::push_expression(boolop op) m_curexpr = newexpr; } -void sinsp_filter::pop_expression() -{ +void sinsp_filter::pop_expression() { ASSERT(m_curexpr->m_parent != NULL); - if(m_curexpr->get_expr_boolop() == -1) - { - throw sinsp_exception("expression mixes 'and' and 'or' in an ambiguous way. Please use brackets."); + if(m_curexpr->get_expr_boolop() == -1) { + throw sinsp_exception( + "expression mixes 'and' and 'or' in an ambiguous way. Please use brackets."); } m_curexpr = m_curexpr->m_parent; } -bool sinsp_filter::run(sinsp_evt *evt) -{ +bool sinsp_filter::run(sinsp_evt* evt) { return m_filter->compare(evt); } -void sinsp_filter::add_check(std::unique_ptr chk) -{ +void sinsp_filter::add_check(std::unique_ptr chk) { m_curexpr->add_check(std::move(chk)); } @@ -186,58 +165,46 @@ void sinsp_filter::add_check(std::unique_ptr chk) // sinsp_filter_compiler implementation /////////////////////////////////////////////////////////////////////////////// sinsp_filter_compiler::sinsp_filter_compiler( - sinsp* inspector, - const std::string& fltstr, - const std::shared_ptr& cache_factory) - : m_flt_str(fltstr), - m_factory(std::make_shared(inspector, m_default_filterlist)), - m_cache_factory(cache_factory) -{ -} + sinsp* inspector, + const std::string& fltstr, + const std::shared_ptr& cache_factory): + m_flt_str(fltstr), + m_factory(std::make_shared(inspector, m_default_filterlist)), + m_cache_factory(cache_factory) {} sinsp_filter_compiler::sinsp_filter_compiler( - const std::shared_ptr& factory, - const std::string& fltstr, - const std::shared_ptr& cache_factory) - : m_flt_str(fltstr), - m_factory(factory), - m_cache_factory(cache_factory) -{ -} + const std::shared_ptr& factory, + const std::string& fltstr, + const std::shared_ptr& cache_factory): + m_flt_str(fltstr), + m_factory(factory), + m_cache_factory(cache_factory) {} sinsp_filter_compiler::sinsp_filter_compiler( - const std::shared_ptr& factory, - const libsinsp::filter::ast::expr* fltast, - const std::shared_ptr& cache_factory) - : m_flt_ast(fltast), - m_factory(factory), - m_cache_factory(cache_factory) -{ -} - -std::unique_ptr sinsp_filter_compiler::compile() -{ + const std::shared_ptr& factory, + const libsinsp::filter::ast::expr* fltast, + const std::shared_ptr& cache_factory): + m_flt_ast(fltast), + m_factory(factory), + m_cache_factory(cache_factory) {} + +std::unique_ptr sinsp_filter_compiler::compile() { m_warnings.clear(); // parse filter string on-the-fly if not pre-parsed AST is provided - if (m_flt_ast == NULL) - { + if(m_flt_ast == NULL) { libsinsp::filter::parser parser(m_flt_str); - try - { + try { m_internal_flt_ast = parser.parse(); m_flt_ast = m_internal_flt_ast.get(); - } - catch (const sinsp_exception& e) - { - throw sinsp_exception("filter error at " - + parser.get_pos().as_string() + ": " + e.what()); + } catch(const sinsp_exception& e) { + throw sinsp_exception("filter error at " + parser.get_pos().as_string() + ": " + + e.what()); } } // make sure the cache factory is all set - if (!m_cache_factory) - { + if(!m_cache_factory) { // by default, use a factory that enables caching m_cache_factory = std::make_shared(); } @@ -248,12 +215,9 @@ std::unique_ptr sinsp_filter_compiler::compile() m_last_boolop = BO_NONE; m_last_node_field = nullptr; m_last_node_field_is_plugin = false; - try - { + try { m_flt_ast->accept(this); - } - catch (const sinsp_exception& e) - { + } catch(const sinsp_exception& e) { m_filter = nullptr; throw e; } @@ -262,48 +226,39 @@ std::unique_ptr sinsp_filter_compiler::compile() return std::move(m_filter); } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::and_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::and_expr* e) { m_pos = e->get_pos(); bool nested = m_last_boolop != BO_AND; - if (nested) - { + if(nested) { m_filter->push_expression(m_last_boolop); m_last_boolop = BO_NONE; } - for (auto &c : e->children) - { + for(auto& c : e->children) { c->accept(this); m_last_boolop = BO_AND; } - if (nested) - { + if(nested) { m_filter->pop_expression(); } } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::or_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::or_expr* e) { m_pos = e->get_pos(); bool nested = m_last_boolop != BO_OR; - if (nested) - { + if(nested) { m_filter->push_expression(m_last_boolop); m_last_boolop = BO_NONE; } - for (auto &c : e->children) - { + for(auto& c : e->children) { c->accept(this); m_last_boolop = BO_OR; } - if (nested) - { + if(nested) { m_filter->pop_expression(); } } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::not_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::not_expr* e) { m_pos = e->get_pos(); m_last_boolop = (boolop)((uint32_t)m_last_boolop | BO_NOT); m_filter->push_expression(m_last_boolop); @@ -312,24 +267,20 @@ void sinsp_filter_compiler::visit(const libsinsp::filter::ast::not_expr* e) m_filter->pop_expression(); } -static inline void check_op_type_compatibility(sinsp_filter_check& c) -{ +static inline void check_op_type_compatibility(sinsp_filter_check& c) { std::string err; auto fi = c.get_transformed_field_info(); - if (fi && !flt_is_comparable(c.m_cmpop, fi->m_type, fi->is_list(), err)) - { + if(fi && !flt_is_comparable(c.m_cmpop, fi->m_type, fi->is_list(), err)) { throw sinsp_exception("filter error: " + err); } } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::unary_check_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::unary_check_expr* e) { m_pos = e->get_pos(); m_last_node_field = nullptr; m_last_node_field_is_plugin = false; e->left->accept(this); - if (!m_last_node_field) - { + if(!m_last_node_field) { throw sinsp_exception("filter error: missing field in left-hand of unary check"); } @@ -349,36 +300,32 @@ void sinsp_filter_compiler::visit(const libsinsp::filter::ast::unary_check_expr* m_filter->add_check(std::move(check)); } -static void add_filtercheck_value(sinsp_filter_check* chk, size_t idx, std::string_view value) -{ +static void add_filtercheck_value(sinsp_filter_check* chk, size_t idx, std::string_view value) { std::vector hex_bytes; - switch(chk->m_cmpop) - { - case CO_BCONTAINS: - case CO_BSTARTSWITH: - if(!sinsp_utils::unhex(value, hex_bytes)) - { - throw sinsp_exception("filter error: bcontains and bstartswith operator support hex strings only"); - } - chk->add_filter_value(&hex_bytes[0], hex_bytes.size(), idx); - break; - default: - chk->add_filter_value(value.data(), value.size(), idx); - break; + switch(chk->m_cmpop) { + case CO_BCONTAINS: + case CO_BSTARTSWITH: + if(!sinsp_utils::unhex(value, hex_bytes)) { + throw sinsp_exception( + "filter error: bcontains and bstartswith operator support hex strings only"); + } + chk->add_filter_value(&hex_bytes[0], hex_bytes.size(), idx); + break; + default: + chk->add_filter_value(value.data(), value.size(), idx); + break; } } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::binary_check_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::binary_check_expr* e) { m_pos = e->get_pos(); m_last_node_field = nullptr; m_last_node_field_is_plugin = false; e->left->accept(this); - if (!m_last_node_field) - { + if(!m_last_node_field) { throw sinsp_exception("filter error: missing field in left-hand of binary check"); } - + auto left_from_plugin = m_last_node_field_is_plugin; auto check = std::move(m_last_node_field); @@ -388,14 +335,13 @@ void sinsp_filter_compiler::visit(const libsinsp::filter::ast::binary_check_expr check->m_cache_metrics = m_cache_factory->new_metrics(e->left.get(), node_info); check->m_extract_cache = m_cache_factory->new_extract_cache(e->left.get(), node_info); - // if the extraction comes from a plugin-implemented ield, then + // if the extraction comes from a plugin-implemented ield, then // we need to add a storage transformer as the cache may end up storing a // shallow copy of the value pointers that are not valid anymore. Note that // this should not change the right field's eligibility for caching, as // the storage transformer does not alter the field's info. auto left_has_storage = false; - if (left_from_plugin && check->m_extract_cache) - { + if(left_from_plugin && check->m_extract_cache) { left_has_storage = true; check->add_transformer(filter_transformer_type::FTR_STORAGE); } @@ -409,52 +355,56 @@ void sinsp_filter_compiler::visit(const libsinsp::filter::ast::binary_check_expr m_field_values.clear(); e->right->accept(this); - if (m_last_node_field) - { + if(m_last_node_field) { // When the lhs is a plugin filter check and the rhs side is again a plugin filter check - // we have an issue. Even if the 2 filter checks are different the memory for extracted values is provided by the plugin. - // So when we call the second extraction on the rhs filter check the previously extracted value - // for the lhs filter check will be overridden. + // we have an issue. Even if the 2 filter checks are different the memory for extracted + // values is provided by the plugin. So when we call the second extraction on the rhs filter + // check the previously extracted value for the lhs filter check will be overridden. // - // As a workaround we add a custom internal transformer `FTR_STORAGE` to the lhs filter check. - // The only goal of this transformer is to copy the memory storage of the extracted values from the plugin to the transformer. - // In this way when we have 2 extractions on a plugin filter check, the plugin will hold only the memory of the rhs filter check, - // while the storage of the lhs will be kept by the `FTR_STORAGE` transformer. + // As a workaround we add a custom internal transformer `FTR_STORAGE` to the lhs filter + // check. The only goal of this transformer is to copy the memory storage of the extracted + // values from the plugin to the transformer. In this way when we have 2 extractions on a + // plugin filter check, the plugin will hold only the memory of the rhs filter check, while + // the storage of the lhs will be kept by the `FTR_STORAGE` transformer. // // The steps are the following: // * check if both the filter checks (lhs and rhs) are plugin filter checks. - // * if yes, check if they are associated with the same plugin instance, otherwise, this is not an issue. We use the plugin name + // * if yes, check if they are associated with the same plugin instance, otherwise, this is + // not an issue. We use the plugin name // to understand if the plugin is the same. // * if yes, add the `FTR_STORAGE` transformer to the lhs filter check. // - // Note, adding a storage layer on only one of the two sides of the comparison is enough to solve the problem. + // Note, adding a storage layer on only one of the two sides of the comparison is enough to + // solve the problem. // - // However, we may have already added a storage modifier to the left field due to issues with caching, - // in which case we are good already. + // However, we may have already added a storage modifier to the left field due to issues + // with caching, in which case we are good already. auto right_from_plugin = m_last_node_field_is_plugin; - if (!left_has_storage && left_from_plugin && right_from_plugin) - { + if(!left_has_storage && left_from_plugin && right_from_plugin) { check->add_transformer(filter_transformer_type::FTR_STORAGE); } // install cache on right-hand side extraction field auto prev_left_field_info = node_info.m_field; node_info.m_field = m_last_node_field->get_transformed_field_info(); - m_last_node_field->m_cache_metrics = m_cache_factory->new_metrics(e->right.get(), node_info); - // note: the `val(...)` transformer is a no-op and can be ignored for better extract cache reusage + m_last_node_field->m_cache_metrics = + m_cache_factory->new_metrics(e->right.get(), node_info); + // note: the `val(...)` transformer is a no-op and can be ignored for better extract cache + // reusage const auto* cacheable_expr = e->right.get(); - if (const auto* val_transf_expr = dynamic_cast(cacheable_expr); - val_transf_expr != nullptr && val_transf_expr->transformer == "val") - { + if(const auto* val_transf_expr = + dynamic_cast( + cacheable_expr); + val_transf_expr != nullptr && val_transf_expr->transformer == "val") { cacheable_expr = val_transf_expr->value.get(); } - m_last_node_field->m_extract_cache = m_cache_factory->new_extract_cache(cacheable_expr, node_info); + m_last_node_field->m_extract_cache = + m_cache_factory->new_extract_cache(cacheable_expr, node_info); // similarly as above, if the right-hand side extraction comes from a // plugin-implemented field, then we need to add an additional storage // layer on it as well - if (right_from_plugin && m_last_node_field->m_extract_cache) - { + if(right_from_plugin && m_last_node_field->m_extract_cache) { m_last_node_field->add_transformer(filter_transformer_type::FTR_STORAGE); } @@ -464,17 +414,14 @@ void sinsp_filter_compiler::visit(const libsinsp::filter::ast::binary_check_expr // We found another field as right-hand side of the comparison check->add_filter_value(std::move(m_last_node_field)); - } - else - { + } else { // We found no field as right-hand side of the comparison, so we // assume to find some constant values. // For list-related operators ('in', 'intersects', 'pmatch'), the vector // can be filled with more than 1 value, whereas in all other cases we // expect the vector to only have 1 value. We don't check this here, as // the parser is trusted to apply proper grammar checks on this constraint. - for (size_t i = 0; i < m_field_values.size(); i++) - { + for(size_t i = 0; i < m_field_values.size(); i++) { check_value_and_add_warnings(check->m_cmpop, e->right->get_pos(), m_field_values[i]); add_filtercheck_value(check.get(), i, m_field_values[i]); } @@ -489,36 +436,33 @@ void sinsp_filter_compiler::visit(const libsinsp::filter::ast::binary_check_expr m_filter->add_check(std::move(check)); } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::identifier_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::identifier_expr* e) { m_pos = e->get_pos(); throw sinsp_exception("filter error: unexpected identifier '" + e->identifier + "'"); } -void sinsp_filter_compiler::check_warnings_regex_value(const libsinsp::filter::ast::pos_info& pos, const std::string& v) -{ +void sinsp_filter_compiler::check_warnings_regex_value(const libsinsp::filter::ast::pos_info& pos, + const std::string& v) { static const char* rgx_special_chars = ".+*?^$()[]{}|\\"; static const char* rgx_occurrence_chars = "+*?"; static cmpop suggested_operators[] = {CO_EQ, CO_CONTAINS, CO_STARTSWITH, CO_ENDSWITH}; auto len = v.length(); - for (size_t i = 0; i < len; i++) - { - // skip start/end achors, they are implicitly enforced in the way we evaluate regular expressions - if ((i == 0 && v[i] == '^') || (i == len - 1 && v[i] == '$')) - { + for(size_t i = 0; i < len; i++) { + // skip start/end achors, they are implicitly enforced in the way we evaluate regular + // expressions + if((i == 0 && v[i] == '^') || (i == len - 1 && v[i] == '$')) { continue; } // skip "any-char" occurrence indicators at the start or end of the expression, // as those could potentially be implemented through other operators such as contains, // startswith, or endswith. E.g. we want to catch cases like `.*substring` and `substring.*` - // note: for simplicity we just check for wildcard occurrence indicators, and + // note: for simplicity we just check for wildcard occurrence indicators, and // not specific quantifiers (e.g. `substring.{2}`) - if (((i == 0 && len > 1) || (i == len - 2)) - && v[i] == '.' && strchr(rgx_occurrence_chars, v[i + 1]) != nullptr) - { - i++; // also skip the occurrence indicator char + if(((i == 0 && len > 1) || (i == len - 2)) && v[i] == '.' && + strchr(rgx_occurrence_chars, v[i + 1]) != nullptr) { + i++; // also skip the occurrence indicator char continue; } @@ -526,53 +470,49 @@ void sinsp_filter_compiler::check_warnings_regex_value(const libsinsp::filter::a // we still have no guarantee that a regex is the only way of implementing this // value check, however we don't have better euristics to apply and just assume // it is a necessary cost - if (strchr(rgx_special_chars, v[i]) != nullptr) - { + if(strchr(rgx_special_chars, v[i]) != nullptr) { return; } } auto msg = "regex check with '" + v + "' may be optimized with simpler operators such as "; std::string opstr; - for (size_t i = 0; i < sizeof(suggested_operators) / sizeof(suggested_operators[0]); i++) - { + for(size_t i = 0; i < sizeof(suggested_operators) / sizeof(suggested_operators[0]); i++) { cmpop_to_str(suggested_operators[i], opstr); msg.append(i == 0 ? "" : ", ").append("'").append(opstr).append("'"); } m_warnings.push_back({msg, pos}); } -void sinsp_filter_compiler::check_warnings_field_value(const libsinsp::filter::ast::pos_info& pos, const std::string& str, const std::string& strippedstr) -{ - if (m_factory->new_filtercheck(strippedstr.c_str()) == nullptr) - { +void sinsp_filter_compiler::check_warnings_field_value(const libsinsp::filter::ast::pos_info& pos, + const std::string& str, + const std::string& strippedstr) { + if(m_factory->new_filtercheck(strippedstr.c_str()) == nullptr) { return; } auto msg = "'" + str + "' may be a valid field misused as a const string value"; m_warnings.push_back({msg, pos}); } -void sinsp_filter_compiler::check_warnings_transformer_value(const libsinsp::filter::ast::pos_info& pos, const std::string& str, const std::string& strippedstr) -{ +void sinsp_filter_compiler::check_warnings_transformer_value( + const libsinsp::filter::ast::pos_info& pos, + const std::string& str, + const std::string& strippedstr) { auto transformers = libsinsp::filter::parser::supported_field_transformers(true); - for (const auto& t : transformers) - { - if (strippedstr.size() >= t.size() + 2 - && strippedstr.compare(0, t.size(), t) == 0 - && strippedstr[t.size()] == '(' - && strippedstr.back() == ')') - { - auto msg = "'" + str + "' may be a valid field transformer misused as a const string value"; + for(const auto& t : transformers) { + if(strippedstr.size() >= t.size() + 2 && strippedstr.compare(0, t.size(), t) == 0 && + strippedstr[t.size()] == '(' && strippedstr.back() == ')') { + auto msg = "'" + str + + "' may be a valid field transformer misused as a const string value"; m_warnings.push_back({msg, pos}); } } } -void sinsp_filter_compiler::check_value_and_add_warnings( - cmpop op, const libsinsp::filter::ast::pos_info& pos, const std::string& v) -{ - try - { +void sinsp_filter_compiler::check_value_and_add_warnings(cmpop op, + const libsinsp::filter::ast::pos_info& pos, + const std::string& v) { + try { // checking the string with nospaces might help reducing noise and // catching most common issues auto nospaces = v; @@ -581,8 +521,7 @@ void sinsp_filter_compiler::check_value_and_add_warnings( // checks using regex operator are the most performance expensive ones, // so we want to appply few euristics to understand if the check could // be trivially rewritten with simpler operators - if (op == CO_REGEX) - { + if(op == CO_REGEX) { check_warnings_regex_value(pos, v); } @@ -593,111 +532,95 @@ void sinsp_filter_compiler::check_value_and_add_warnings( // users may be confused with the proper usage of transformers and may // end up using one as string values in checks check_warnings_transformer_value(pos, v, nospaces); - } - catch (...) - { + } catch(...) { // parsing invalid strings as fields may cause unexpected errors. // we're not interested in any of those, we just want to catch // success cases in order to emit a warning } } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::value_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::value_expr* e) { m_pos = e->get_pos(); m_field_values.clear(); m_field_values.push_back(e->value); } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::list_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::list_expr* e) { m_pos = e->get_pos(); m_field_values = e->values; } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::field_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::field_expr* e) { m_pos = e->get_pos(); auto field_name = create_filtercheck_name(e->field, e->arg); m_last_node_field = create_filtercheck(field_name); - m_last_node_field_is_plugin = dynamic_cast(m_last_node_field.get()) != nullptr; - if (m_last_node_field->parse_field_name(field_name, true, true) == -1) - { + m_last_node_field_is_plugin = + dynamic_cast(m_last_node_field.get()) != nullptr; + if(m_last_node_field->parse_field_name(field_name, true, true) == -1) { throw sinsp_exception("filter error: can't parse field expression '" + field_name + "'"); } } -void sinsp_filter_compiler::visit(const libsinsp::filter::ast::field_transformer_expr* e) -{ +void sinsp_filter_compiler::visit(const libsinsp::filter::ast::field_transformer_expr* e) { m_pos = e->get_pos(); m_last_node_field = nullptr; m_last_node_field_is_plugin = false; e->value->accept(this); - if (!m_last_node_field) - { - throw sinsp_exception("filter error: found null child node on '" + e->transformer + "' transformer"); + if(!m_last_node_field) { + throw sinsp_exception("filter error: found null child node on '" + e->transformer + + "' transformer"); } // apply transformer, ignoring the "identity one" - if (e->transformer != "val") - { + if(e->transformer != "val") { m_last_node_field->add_transformer(filter_transformer_from_str(e->transformer)); } } -std::string sinsp_filter_compiler::create_filtercheck_name(const std::string& name, const std::string& arg) -{ +std::string sinsp_filter_compiler::create_filtercheck_name(const std::string& name, + const std::string& arg) { // The filtercheck factories parse the name + arg as a whole. // We keep this for now, but we may want to change this in the future. // todo(jasondellaluce): handle field arg parsing at compilation time std::string fld = name; - if (arg.size() > 0) - { + if(arg.size() > 0) { fld += "[" + arg + "]"; } return fld; } -std::unique_ptr sinsp_filter_compiler::create_filtercheck(std::string_view field) -{ +std::unique_ptr sinsp_filter_compiler::create_filtercheck( + std::string_view field) { auto chk = m_factory->new_filtercheck(field); - if(chk == NULL) - { + if(chk == NULL) { throw sinsp_exception("filter_check called with nonexistent field " + std::string(field)); } return chk; } -sinsp_filter_factory::sinsp_filter_factory(sinsp *inspector, - filter_check_list &available_checks) - : m_inspector(inspector), m_available_checks(available_checks) -{ -} +sinsp_filter_factory::sinsp_filter_factory(sinsp* inspector, filter_check_list& available_checks): + m_inspector(inspector), + m_available_checks(available_checks) {} -std::unique_ptr sinsp_filter_factory::new_filtercheck(std::string_view fldname) const -{ - return m_available_checks.new_filter_check_from_fldname(fldname, - m_inspector, - true); +std::unique_ptr sinsp_filter_factory::new_filtercheck( + std::string_view fldname) const { + return m_available_checks.new_filter_check_from_fldname(fldname, m_inspector, true); } -std::list sinsp_filter_factory::get_fields() const -{ +std::list sinsp_filter_factory::get_fields() const { std::vector fc_plugins; m_available_checks.get_all_fields(fc_plugins); return check_infos_to_fieldclass_infos(fc_plugins); } -std::list sinsp_filter_factory::check_infos_to_fieldclass_infos( - const std::vector &fc_plugins) -{ +std::list +sinsp_filter_factory::check_infos_to_fieldclass_infos( + const std::vector& fc_plugins) { std::list ret; - for(auto &fci : fc_plugins) - { - if(fci->m_flags & filter_check_info::FL_HIDDEN) - { + for(auto& fci : fc_plugins) { + if(fci->m_flags & filter_check_info::FL_HIDDEN) { continue; } @@ -706,51 +629,41 @@ std::list sinsp_filter_factory::ch cinfo.desc = fci->m_desc; cinfo.shortdesc = fci->m_shortdesc; - for(auto fld = fci->m_fields; fld != fci->m_fields + fci->m_nfields; ++fld) - { + for(auto fld = fci->m_fields; fld != fci->m_fields + fci->m_nfields; ++fld) { // If a field is only used to organize events, // we don't want to print it and don't return it here. - if(fld->m_flags & EPF_PRINT_ONLY) - { + if(fld->m_flags & EPF_PRINT_ONLY) { continue; } sinsp_filter_factory::filter_field_info info; info.name = fld->m_name; info.desc = fld->m_description; - info.data_type = param_type_to_string(fld->m_type); + info.data_type = param_type_to_string(fld->m_type); - if(fld->m_flags & EPF_FILTER_ONLY) - { + if(fld->m_flags & EPF_FILTER_ONLY) { info.tags.insert("FILTER_ONLY"); } - if(fld->m_flags & EPF_TABLE_ONLY) - { + if(fld->m_flags & EPF_TABLE_ONLY) { info.tags.insert("EPF_TABLE_ONLY"); } - if(fld->m_flags & EPF_DEPRECATED) - { + if(fld->m_flags & EPF_DEPRECATED) { info.tags.insert("EPF_DEPRECATED"); } - if(fld->m_flags & EPF_NO_RHS) - { + if(fld->m_flags & EPF_NO_RHS) { info.tags.insert("EPF_NO_RHS"); } - if(fld->m_flags & EPF_NO_TRANSFORMER) - { + if(fld->m_flags & EPF_NO_TRANSFORMER) { info.tags.insert("EPF_NO_TRANSFORMER"); } - if(fld->m_flags & EPF_ARG_REQUIRED) - { + if(fld->m_flags & EPF_ARG_REQUIRED) { info.tags.insert("ARG_REQUIRED"); - } - else if(fld->m_flags & EPF_ARG_ALLOWED) - { + } else if(fld->m_flags & EPF_ARG_ALLOWED) { info.tags.insert("ARG_ALLOWED"); } @@ -763,14 +676,12 @@ std::list sinsp_filter_factory::ch return ret; } -bool sinsp_filter_factory::filter_field_info::is_skippable() const -{ +bool sinsp_filter_factory::filter_field_info::is_skippable() const { // Skip fields with the EPF_TABLE_ONLY flag. return (tags.find("EPF_TABLE_ONLY") != tags.end()); } -bool sinsp_filter_factory::filter_field_info::is_deprecated() const -{ +bool sinsp_filter_factory::filter_field_info::is_deprecated() const { // Skip fields with the EPF_DEPRECATED flag. return (tags.find("EPF_DEPRECATED") != tags.end()); } @@ -778,23 +689,19 @@ bool sinsp_filter_factory::filter_field_info::is_deprecated() const uint32_t sinsp_filter_factory::filter_fieldclass_info::s_rightblock_start = 30; uint32_t sinsp_filter_factory::filter_fieldclass_info::s_width = 120; -void sinsp_filter_factory::filter_fieldclass_info::wrapstring(const std::string &in, std::ostringstream &os) -{ +void sinsp_filter_factory::filter_fieldclass_info::wrapstring(const std::string& in, + std::ostringstream& os) { std::istringstream is(in); std::string word; uint32_t len = 0; - while (is >> word) - { + while(is >> word) { // + 1 is trailing space. uint32_t wordlen = word.length() + 1; - if((len + wordlen) <= (s_width-s_rightblock_start)) - { + if((len + wordlen) <= (s_width - s_rightblock_start)) { len += wordlen; - } - else - { + } else { os << std::endl; os << std::left << std::setw(s_rightblock_start) << " "; len = wordlen; @@ -804,24 +711,22 @@ void sinsp_filter_factory::filter_fieldclass_info::wrapstring(const std::string } } -std::string sinsp_filter_factory::filter_fieldclass_info::as_markdown(const std::set& event_sources, bool include_deprecated) -{ +std::string sinsp_filter_factory::filter_fieldclass_info::as_markdown( + const std::set& event_sources, + bool include_deprecated) { std::ostringstream os; uint32_t deprecated_count = 0; os << "## Field Class: " << name << std::endl << std::endl; - if(desc != "") - { + if(desc != "") { os << desc << std::endl << std::endl; } - if(!event_sources.empty()) - { + if(!event_sources.empty()) { os << "Event Sources: "; - for(const auto &src : event_sources) - { + for(const auto& src : event_sources) { os << src << " "; } @@ -831,59 +736,54 @@ std::string sinsp_filter_factory::filter_fieldclass_info::as_markdown(const std: os << "Name | Type | Description" << std::endl; os << ":----|:-----|:-----------" << std::endl; - for(auto &fld_info : fields) - { + for(auto& fld_info : fields) { // Skip fields that should not be included // (e.g. hidden fields) - if(fld_info.is_skippable()) - { + if(fld_info.is_skippable()) { continue; } - if(!include_deprecated && fld_info.is_deprecated()) - { + if(!include_deprecated && fld_info.is_deprecated()) { deprecated_count++; continue; } - os << "`" << fld_info.name << "` | " << fld_info.data_type << " | " << fld_info.desc << std::endl; + os << "`" << fld_info.name << "` | " << fld_info.data_type << " | " << fld_info.desc + << std::endl; } - if(deprecated_count == fields.size()) - { + if(deprecated_count == fields.size()) { return ""; } return os.str(); } -std::string sinsp_filter_factory::filter_fieldclass_info::as_string(bool verbose, const std::set& event_sources, bool include_deprecated) -{ +std::string sinsp_filter_factory::filter_fieldclass_info::as_string( + bool verbose, + const std::set& event_sources, + bool include_deprecated) { std::ostringstream os; uint32_t deprecated_count = 0; os << "-------------------------------" << std::endl; os << std::left << std::setw(s_rightblock_start) << "Field Class:" << name; - if(shortdesc != "") - { + if(shortdesc != "") { os << " (" << shortdesc << ")"; } os << std::endl; - if(desc != "") - { + if(desc != "") { os << std::left << std::setw(s_rightblock_start) << "Description:"; wrapstring(desc, os); os << std::endl; } - if(!event_sources.empty()) - { + if(!event_sources.empty()) { os << std::left << std::setw(s_rightblock_start) << "Event Sources:"; - for(const auto &src : event_sources) - { + for(const auto& src : event_sources) { os << src << " "; } @@ -892,40 +792,31 @@ std::string sinsp_filter_factory::filter_fieldclass_info::as_string(bool verbose os << std::endl; - for(auto &fld_info : fields) - { + for(auto& fld_info : fields) { // Skip fields that should not be included // (e.g. hidden fields) - if(fld_info.is_skippable()) - { + if(fld_info.is_skippable()) { continue; } - if(!include_deprecated && fld_info.is_deprecated()) - { + if(!include_deprecated && fld_info.is_deprecated()) { deprecated_count++; continue; } - if(fld_info.name.length() > s_rightblock_start) - { + if(fld_info.name.length() > s_rightblock_start) { os << fld_info.name << std::endl; os << std::left << std::setw(s_rightblock_start) << " "; - } - else - { + } else { os << std::left << std::setw(s_rightblock_start) << fld_info.name; } // Append any tags, and if verbose, add the type, to the description. std::string desc = fld_info.desc; - if(!fld_info.tags.empty()) - { + if(!fld_info.tags.empty()) { std::string tagsstr = "("; - for(const auto &tag : fld_info.tags) - { - if(tagsstr != "(") - { + for(const auto& tag : fld_info.tags) { + if(tagsstr != "(") { tagsstr += ","; } @@ -937,8 +828,7 @@ std::string sinsp_filter_factory::filter_fieldclass_info::as_string(bool verbose desc = tagsstr + " " + desc; } - if(verbose) - { + if(verbose) { desc = "(Type: " + fld_info.data_type + ") " + desc; } @@ -946,8 +836,7 @@ std::string sinsp_filter_factory::filter_fieldclass_info::as_string(bool verbose os << std::endl; } - if(deprecated_count == fields.size()) - { + if(deprecated_count == fields.size()) { return ""; } diff --git a/userspace/libsinsp/filter.h b/userspace/libsinsp/filter.h index f8e18d95d2..c5bc72cbc7 100644 --- a/userspace/libsinsp/filter.h +++ b/userspace/libsinsp/filter.h @@ -37,8 +37,7 @@ limitations under the License. // A filter expression contains multiple filters connected by boolean expressions, // e.g. "check or check", "check and check and check", "not check" /////////////////////////////////////////////////////////////////////////////// -class sinsp_filter_expression : public sinsp_filter_check -{ +class sinsp_filter_expression : public sinsp_filter_check { public: sinsp_filter_expression() = default; virtual ~sinsp_filter_expression() = default; @@ -47,15 +46,13 @@ class sinsp_filter_expression : public sinsp_filter_check // The following methods are part of the filter check interface but are irrelevant // for this class, because they are used only for the leaves of the filtering tree. // - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override - { + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override { return 0; } - void add_filter_value(const char* str, uint32_t len, uint32_t i = 0) override - { - return; - } + void add_filter_value(const char* str, uint32_t len, uint32_t i = 0) override { return; } bool compare(sinsp_evt*) override; @@ -73,17 +70,15 @@ class sinsp_filter_expression : public sinsp_filter_check std::vector> m_checks; }; - /*! \brief This is the class that runs the filters. */ -class SINSP_PUBLIC sinsp_filter -{ +class SINSP_PUBLIC sinsp_filter { public: sinsp_filter(); virtual ~sinsp_filter() = default; - bool run(sinsp_evt *evt); + bool run(sinsp_evt* evt); void push_expression(boolop op); void pop_expression(); @@ -95,12 +90,10 @@ class SINSP_PUBLIC sinsp_filter sinsp_filter_expression* m_curexpr; }; -class sinsp_filter_factory -{ +class sinsp_filter_factory { public: // A struct describing a single filtercheck field ("ka.user") - struct filter_field_info - { + struct filter_field_info { // The name of the field std::string name; @@ -122,8 +115,7 @@ class sinsp_filter_factory }; // Describes a group of filtercheck fields ("ka") - class filter_fieldclass_info - { + class filter_fieldclass_info { public: // The name of the group of fields std::string name; @@ -139,12 +131,16 @@ class sinsp_filter_factory // Print a terminal-friendly representation of this // field class, including name, description, supported // event sources, and the name and description of each field. - std::string as_string(bool verbose, const std::set& event_sources = std::set(), bool include_deprecated=false); + std::string as_string(bool verbose, + const std::set& event_sources = std::set(), + bool include_deprecated = false); // Print a markdown representation of this // field class, suitable for publication on the documentation // website. - std::string as_markdown(const std::set& event_sources = std::set(), bool include_deprecated=false); + std::string as_markdown( + const std::set& event_sources = std::set(), + bool include_deprecated = false); // How far to right-justify the name/description/etc block. static uint32_t s_rightblock_start; @@ -153,10 +149,10 @@ class sinsp_filter_factory static uint32_t s_width; private: - void wrapstring(const std::string &in, std::ostringstream &os); + void wrapstring(const std::string& in, std::ostringstream& os); }; - sinsp_filter_factory(sinsp *inspector, filter_check_list &available_checks); + sinsp_filter_factory(sinsp* inspector, filter_check_list& available_checks); virtual ~sinsp_filter_factory() = default; @@ -169,77 +165,78 @@ class sinsp_filter_factory // filter_fieldclass_infos. This is useful for programs that // use filterchecks but not factories. static std::list check_infos_to_fieldclass_infos( - const std::vector &fc_plugins); + const std::vector& fc_plugins); protected: - sinsp *m_inspector; - filter_check_list &m_available_checks; + sinsp* m_inspector; + filter_check_list& m_available_checks; }; /*! \brief This is the class that compiles the filters. */ -class SINSP_PUBLIC sinsp_filter_compiler: - private libsinsp::filter::ast::const_expr_visitor -{ +class SINSP_PUBLIC sinsp_filter_compiler : private libsinsp::filter::ast::const_expr_visitor { public: - struct message - { + struct message { std::string msg; libsinsp::filter::ast::pos_info pos; }; - + /*! - \brief Constructs the compiler + \brief Constructs the compiler - \param inspector Pointer to the inspector instance that will generate - the events to be filtered - \param fltstr The filter string to compile + \param inspector Pointer to the inspector instance that will generate + the events to be filtered + \param fltstr The filter string to compile - \note This is not the primary constructor, and is only maintained for - backward compatibility + \note This is not the primary constructor, and is only maintained for + backward compatibility */ sinsp_filter_compiler( - sinsp* inspector, - const std::string& fltstr, - const std::shared_ptr& cache_factory = nullptr); + sinsp* inspector, + const std::string& fltstr, + const std::shared_ptr& cache_factory = nullptr); /*! - \brief Constructs the compiler + \brief Constructs the compiler - \param factory Pointer to a filter factory to be used to build - the filtercheck tree - \param fltstr The filter string to compile + \param factory Pointer to a filter factory to be used to build + the filtercheck tree + \param fltstr The filter string to compile */ sinsp_filter_compiler( - const std::shared_ptr& factory, - const std::string& fltstr, - const std::shared_ptr& cache_factory = nullptr); + const std::shared_ptr& factory, + const std::string& fltstr, + const std::shared_ptr& cache_factory = nullptr); /*! - \brief Constructs the compiler + \brief Constructs the compiler - \param factory Pointer to a filter factory to be used to build - the filtercheck tree - \param fltast AST of a parsed filter, used to build the filtercheck - tree + \param factory Pointer to a filter factory to be used to build + the filtercheck tree + \param fltast AST of a parsed filter, used to build the filtercheck + tree */ sinsp_filter_compiler( - const std::shared_ptr& factory, - const libsinsp::filter::ast::expr* fltast, - const std::shared_ptr& cache_factory = nullptr); + const std::shared_ptr& factory, + const libsinsp::filter::ast::expr* fltast, + const std::shared_ptr& cache_factory = nullptr); /*! - \brief Builds a filtercheck tree and bundles it in sinsp_filter - \return The resulting pointer is owned by the caller and must be deleted - by it. The pointer is automatically deleted in case of exception. - \note Throws a sinsp_exception if the filter syntax is not valid + \brief Builds a filtercheck tree and bundles it in sinsp_filter + \return The resulting pointer is owned by the caller and must be deleted + by it. The pointer is automatically deleted in case of exception. + \note Throws a sinsp_exception if the filter syntax is not valid */ std::unique_ptr compile(); - const std::shared_ptr get_filter_ast() const { return m_internal_flt_ast; } + const std::shared_ptr get_filter_ast() const { + return m_internal_flt_ast; + } - const std::shared_ptr& get_filter_ast() { return m_internal_flt_ast; } + const std::shared_ptr& get_filter_ast() { + return m_internal_flt_ast; + } const libsinsp::filter::ast::pos_info& get_pos() const { return m_pos; } @@ -258,10 +255,17 @@ class SINSP_PUBLIC sinsp_filter_compiler: void visit(const libsinsp::filter::ast::field_transformer_expr*) override; std::string create_filtercheck_name(const std::string& name, const std::string& arg); std::unique_ptr create_filtercheck(std::string_view field); - void check_value_and_add_warnings(cmpop op, const libsinsp::filter::ast::pos_info& pos, const std::string& v); - void check_warnings_regex_value(const libsinsp::filter::ast::pos_info& pos, const std::string& v); - void check_warnings_field_value(const libsinsp::filter::ast::pos_info& pos, const std::string& str, const std::string& strippedstr); - void check_warnings_transformer_value(const libsinsp::filter::ast::pos_info& pos, const std::string& str, const std::string& strippedstr); + void check_value_and_add_warnings(cmpop op, + const libsinsp::filter::ast::pos_info& pos, + const std::string& v); + void check_warnings_regex_value(const libsinsp::filter::ast::pos_info& pos, + const std::string& v); + void check_warnings_field_value(const libsinsp::filter::ast::pos_info& pos, + const std::string& str, + const std::string& strippedstr); + void check_warnings_transformer_value(const libsinsp::filter::ast::pos_info& pos, + const std::string& str, + const std::string& strippedstr); libsinsp::filter::ast::pos_info m_pos; boolop m_last_boolop; diff --git a/userspace/libsinsp/filter/ast.cpp b/userspace/libsinsp/filter/ast.cpp index 351862d7ba..9bd8c68ff1 100644 --- a/userspace/libsinsp/filter/ast.cpp +++ b/userspace/libsinsp/filter/ast.cpp @@ -21,327 +21,270 @@ limitations under the License. using namespace libsinsp::filter::ast; -void base_expr_visitor::visit(and_expr* e) -{ - for(auto &c: e->children) - { - if (m_should_stop_visit) - { - return; - } - c->accept(this); - } +void base_expr_visitor::visit(and_expr* e) { + for(auto& c : e->children) { + if(m_should_stop_visit) { + return; + } + c->accept(this); + } } -void base_expr_visitor::visit(or_expr* e) -{ - for(auto &c: e->children) - { - if (m_should_stop_visit) - { - return; - } - c->accept(this); - } +void base_expr_visitor::visit(or_expr* e) { + for(auto& c : e->children) { + if(m_should_stop_visit) { + return; + } + c->accept(this); + } } -void base_expr_visitor::visit(not_expr* e) -{ - if (!m_should_stop_visit) - { - e->child->accept(this); - } +void base_expr_visitor::visit(not_expr* e) { + if(!m_should_stop_visit) { + e->child->accept(this); + } } -void base_expr_visitor::visit(binary_check_expr* e) -{ - if (!m_should_stop_visit) - { - e->left->accept(this); - } - - if (!m_should_stop_visit) - { - e->right->accept(this); - } +void base_expr_visitor::visit(binary_check_expr* e) { + if(!m_should_stop_visit) { + e->left->accept(this); + } + + if(!m_should_stop_visit) { + e->right->accept(this); + } } -void base_expr_visitor::visit(unary_check_expr* e) -{ - if (!m_should_stop_visit) - { - e->left->accept(this); - } +void base_expr_visitor::visit(unary_check_expr* e) { + if(!m_should_stop_visit) { + e->left->accept(this); + } } -void base_expr_visitor::visit(field_transformer_expr* e) -{ - if (!m_should_stop_visit) - { - e->value->accept(this); - } +void base_expr_visitor::visit(field_transformer_expr* e) { + if(!m_should_stop_visit) { + e->value->accept(this); + } } -void base_expr_visitor::visit(identifier_expr* e) { } +void base_expr_visitor::visit(identifier_expr* e) {} -void base_expr_visitor::visit(value_expr* e) { } +void base_expr_visitor::visit(value_expr* e) {} -void base_expr_visitor::visit(list_expr* e) { } +void base_expr_visitor::visit(list_expr* e) {} -void base_expr_visitor::visit(field_expr* e) { } +void base_expr_visitor::visit(field_expr* e) {} -void const_base_expr_visitor::visit(const and_expr* e) -{ - for(auto &c: e->children) - { - if (m_should_stop_visit) - { - return; - } - c->accept(this); - } +void const_base_expr_visitor::visit(const and_expr* e) { + for(auto& c : e->children) { + if(m_should_stop_visit) { + return; + } + c->accept(this); + } } -void const_base_expr_visitor::visit(const or_expr* e) -{ - for(auto &c: e->children) - { - if (m_should_stop_visit) - { - return; - } - c->accept(this); - } +void const_base_expr_visitor::visit(const or_expr* e) { + for(auto& c : e->children) { + if(m_should_stop_visit) { + return; + } + c->accept(this); + } } -void const_base_expr_visitor::visit(const not_expr* e) -{ - if (!m_should_stop_visit) - { - e->child->accept(this); - } +void const_base_expr_visitor::visit(const not_expr* e) { + if(!m_should_stop_visit) { + e->child->accept(this); + } } -void const_base_expr_visitor::visit(const binary_check_expr* e) -{ - if (!m_should_stop_visit) - { - e->left->accept(this); - } - if (!m_should_stop_visit) - { - e->right->accept(this); - } +void const_base_expr_visitor::visit(const binary_check_expr* e) { + if(!m_should_stop_visit) { + e->left->accept(this); + } + if(!m_should_stop_visit) { + e->right->accept(this); + } } -void const_base_expr_visitor::visit(const unary_check_expr* e) -{ - if (!m_should_stop_visit) - { - e->left->accept(this); - } +void const_base_expr_visitor::visit(const unary_check_expr* e) { + if(!m_should_stop_visit) { + e->left->accept(this); + } } -void const_base_expr_visitor::visit(const field_transformer_expr* e) -{ - if (!m_should_stop_visit) - { - e->value->accept(this); - } +void const_base_expr_visitor::visit(const field_transformer_expr* e) { + if(!m_should_stop_visit) { + e->value->accept(this); + } } -void const_base_expr_visitor::visit(const identifier_expr* e) { } +void const_base_expr_visitor::visit(const identifier_expr* e) {} -void const_base_expr_visitor::visit(const value_expr* e) { } +void const_base_expr_visitor::visit(const value_expr* e) {} -void const_base_expr_visitor::visit(const list_expr* e) { } +void const_base_expr_visitor::visit(const list_expr* e) {} -void const_base_expr_visitor::visit(const field_expr* e) { } +void const_base_expr_visitor::visit(const field_expr* e) {} -void string_visitor::visit_logical_op(const char *op, const std::vector> &children) -{ - bool first = true; +void string_visitor::visit_logical_op(const char* op, + const std::vector>& children) { + bool first = true; - m_str += "("; - for (auto &c : children) - { - if(!first) - { - m_str += " "; - m_str += op; - m_str += " "; - } - first = false; - c->accept(this); - } - m_str += ")"; + m_str += "("; + for(auto& c : children) { + if(!first) { + m_str += " "; + m_str += op; + m_str += " "; + } + first = false; + c->accept(this); + } + m_str += ")"; } -void string_visitor::visit(const and_expr* e) -{ - visit_logical_op("and", e->children); +void string_visitor::visit(const and_expr* e) { + visit_logical_op("and", e->children); } -void string_visitor::visit(const or_expr* e) -{ - visit_logical_op("or", e->children); +void string_visitor::visit(const or_expr* e) { + visit_logical_op("or", e->children); } -void string_visitor::visit(const not_expr* e) -{ - m_str += "not "; - e->child->accept(this); +void string_visitor::visit(const not_expr* e) { + m_str += "not "; + e->child->accept(this); } -void string_visitor::visit(const identifier_expr* e) -{ - m_str += e->identifier; +void string_visitor::visit(const identifier_expr* e) { + m_str += e->identifier; } -void string_visitor::visit(const value_expr* e) -{ - m_str += libsinsp::filter::escape_str(e->value); +void string_visitor::visit(const value_expr* e) { + m_str += libsinsp::filter::escape_str(e->value); } -void string_visitor::visit(const list_expr* e) -{ - bool first = true; - - m_str += "("; - for(auto &val : e->values) - { - if(!first) - { - m_str += ", "; - } - first = false; - m_str += libsinsp::filter::escape_str(val); - } - m_str += ")"; +void string_visitor::visit(const list_expr* e) { + bool first = true; + + m_str += "("; + for(auto& val : e->values) { + if(!first) { + m_str += ", "; + } + first = false; + m_str += libsinsp::filter::escape_str(val); + } + m_str += ")"; } -void string_visitor::visit(const unary_check_expr* e) -{ - e->left->accept(this); - m_str += " "; - m_str += e->op; +void string_visitor::visit(const unary_check_expr* e) { + e->left->accept(this); + m_str += " "; + m_str += e->op; } -void string_visitor::visit(const binary_check_expr* e) -{ - e->left->accept(this); - m_str += " "; - m_str += e->op; - m_str += " "; - e->right->accept(this); +void string_visitor::visit(const binary_check_expr* e) { + e->left->accept(this); + m_str += " "; + m_str += e->op; + m_str += " "; + e->right->accept(this); } -void string_visitor::visit(const field_expr* e) -{ - m_str += e->field; - if(e->arg != "") - { - m_str += "[" + libsinsp::filter::escape_str(e->arg) + "]"; - } +void string_visitor::visit(const field_expr* e) { + m_str += e->field; + if(e->arg != "") { + m_str += "[" + libsinsp::filter::escape_str(e->arg) + "]"; + } } -void string_visitor::visit(const field_transformer_expr* e) -{ - m_str += e->transformer; - m_str += "("; - e->value->accept(this); - m_str += ")"; +void string_visitor::visit(const field_transformer_expr* e) { + m_str += e->transformer; + m_str += "("; + e->value->accept(this); + m_str += ")"; } -const std::string& string_visitor::as_string() -{ - return m_str; +const std::string& string_visitor::as_string() { + return m_str; } -std::string libsinsp::filter::ast::as_string(const ast::expr *e) -{ - string_visitor sv; - e->accept(&sv); - return sv.as_string(); +std::string libsinsp::filter::ast::as_string(const ast::expr* e) { + string_visitor sv; + e->accept(&sv); + return sv.as_string(); } -std::unique_ptr libsinsp::filter::ast::clone(const expr* e) -{ - struct clone_visitor: public const_expr_visitor - { - std::unique_ptr m_last_node; - - void visit(const and_expr* e) override - { - std::vector> children; - for (auto &c: e->children) - { - c->accept(this); - children.push_back(std::move(m_last_node)); - } - m_last_node = and_expr::create(children, e->get_pos()); - } - - void visit(const or_expr* e) override - { - std::vector> children; - for (auto &c: e->children) - { - c->accept(this); - children.push_back(std::move(m_last_node)); - } - m_last_node = or_expr::create(children, e->get_pos()); - } - - void visit(const not_expr* e) override - { - e->child->accept(this); - m_last_node = not_expr::create(std::move(m_last_node), e->get_pos()); - } - - void visit(const binary_check_expr* e) override - { - e->left->accept(this); - auto left = std::move(m_last_node); - e->right->accept(this); - auto right = std::move(m_last_node); - m_last_node = binary_check_expr::create(std::move(left), e->op, std::move(right), e->get_pos()); - } - - void visit(const unary_check_expr* e) override - { - e->left->accept(this); - auto left = std::move(m_last_node); - m_last_node = unary_check_expr::create(std::move(left), e->op, e->get_pos()); - } - - void visit(const identifier_expr* e) override - { - m_last_node = identifier_expr::create(e->identifier, e->get_pos()); - } - - void visit(const value_expr* e) override - { - m_last_node = value_expr::create(e->value, e->get_pos()); - } - - void visit(const list_expr* e) override - { - m_last_node = list_expr::create(e->values, e->get_pos()); - } - - void visit(const field_expr* e) override - { - m_last_node = field_expr::create(e->field, e->arg, e->get_pos()); - } - - void visit(const field_transformer_expr* e) override - { - e->value->accept(this); - auto value = std::move(m_last_node); - m_last_node = field_transformer_expr::create(e->transformer, std::move(value), e->get_pos()); - } - } visitor; - - e->accept(&visitor); - return std::move(visitor.m_last_node); +std::unique_ptr libsinsp::filter::ast::clone(const expr* e) { + struct clone_visitor : public const_expr_visitor { + std::unique_ptr m_last_node; + + void visit(const and_expr* e) override { + std::vector> children; + for(auto& c : e->children) { + c->accept(this); + children.push_back(std::move(m_last_node)); + } + m_last_node = and_expr::create(children, e->get_pos()); + } + + void visit(const or_expr* e) override { + std::vector> children; + for(auto& c : e->children) { + c->accept(this); + children.push_back(std::move(m_last_node)); + } + m_last_node = or_expr::create(children, e->get_pos()); + } + + void visit(const not_expr* e) override { + e->child->accept(this); + m_last_node = not_expr::create(std::move(m_last_node), e->get_pos()); + } + + void visit(const binary_check_expr* e) override { + e->left->accept(this); + auto left = std::move(m_last_node); + e->right->accept(this); + auto right = std::move(m_last_node); + m_last_node = binary_check_expr::create(std::move(left), + e->op, + std::move(right), + e->get_pos()); + } + + void visit(const unary_check_expr* e) override { + e->left->accept(this); + auto left = std::move(m_last_node); + m_last_node = unary_check_expr::create(std::move(left), e->op, e->get_pos()); + } + + void visit(const identifier_expr* e) override { + m_last_node = identifier_expr::create(e->identifier, e->get_pos()); + } + + void visit(const value_expr* e) override { + m_last_node = value_expr::create(e->value, e->get_pos()); + } + + void visit(const list_expr* e) override { + m_last_node = list_expr::create(e->values, e->get_pos()); + } + + void visit(const field_expr* e) override { + m_last_node = field_expr::create(e->field, e->arg, e->get_pos()); + } + + void visit(const field_transformer_expr* e) override { + e->value->accept(this); + auto value = std::move(m_last_node); + m_last_node = + field_transformer_expr::create(e->transformer, std::move(value), e->get_pos()); + } + } visitor; + + e->accept(&visitor); + return std::move(visitor.m_last_node); } diff --git a/userspace/libsinsp/filter/ast.h b/userspace/libsinsp/filter/ast.h index 1f4a4dd9d2..6ecea2efee 100644 --- a/userspace/libsinsp/filter/ast.h +++ b/userspace/libsinsp/filter/ast.h @@ -46,41 +46,35 @@ struct field_transformer_expr; relatively to the string input. For example, this can either be used to retrieve context information when an exception is thrown. */ -struct pos_info -{ - pos_info() = default; - ~pos_info() = default; - pos_info(uint32_t i, uint32_t l, uint32_t c): idx(i), line(l), col(c) { } - pos_info(pos_info&&) = default; - pos_info& operator = (pos_info&&) = default; - pos_info(const pos_info&) = default; - pos_info& operator = (const pos_info&) = default; - bool operator ==(const pos_info &b) const - { - return idx == b.idx && line == b.line && col == b.col; - } - bool operator !=(const pos_info &b) const - { - return idx != b.idx || line != b.line || col != b.col; - } - - inline void reset() - { - idx = 0; - line = 1; - col = 1; - } - - inline std::string as_string() const - { - return "index " + std::to_string(idx) - + ", line " + std::to_string(line) - + ", column " + std::to_string(col); - } - - uint32_t idx = 0; - uint32_t line = 1; - uint32_t col = 1; +struct pos_info { + pos_info() = default; + ~pos_info() = default; + pos_info(uint32_t i, uint32_t l, uint32_t c): idx(i), line(l), col(c) {} + pos_info(pos_info&&) = default; + pos_info& operator=(pos_info&&) = default; + pos_info(const pos_info&) = default; + pos_info& operator=(const pos_info&) = default; + bool operator==(const pos_info& b) const { + return idx == b.idx && line == b.line && col == b.col; + } + bool operator!=(const pos_info& b) const { + return idx != b.idx || line != b.line || col != b.col; + } + + inline void reset() { + idx = 0; + line = 1; + col = 1; + } + + inline std::string as_string() const { + return "index " + std::to_string(idx) + ", line " + std::to_string(line) + ", column " + + std::to_string(col); + } + + uint32_t idx = 0; + uint32_t line = 1; + uint32_t col = 1; }; static pos_info s_initial_pos; @@ -88,37 +82,35 @@ static pos_info s_initial_pos; /*! \brief Interface of AST visitors */ -struct SINSP_PUBLIC expr_visitor -{ - virtual ~expr_visitor() = default; - virtual void visit(and_expr*) = 0; - virtual void visit(or_expr*) = 0; - virtual void visit(not_expr*) = 0; - virtual void visit(identifier_expr*) = 0; - virtual void visit(value_expr*) = 0; - virtual void visit(list_expr*) = 0; - virtual void visit(unary_check_expr*) = 0; - virtual void visit(binary_check_expr*) = 0; - virtual void visit(field_expr*) = 0; - virtual void visit(field_transformer_expr*) = 0; +struct SINSP_PUBLIC expr_visitor { + virtual ~expr_visitor() = default; + virtual void visit(and_expr*) = 0; + virtual void visit(or_expr*) = 0; + virtual void visit(not_expr*) = 0; + virtual void visit(identifier_expr*) = 0; + virtual void visit(value_expr*) = 0; + virtual void visit(list_expr*) = 0; + virtual void visit(unary_check_expr*) = 0; + virtual void visit(binary_check_expr*) = 0; + virtual void visit(field_expr*) = 0; + virtual void visit(field_transformer_expr*) = 0; }; /*! \brief an AST visitor that does not change the ast. */ -struct SINSP_PUBLIC const_expr_visitor -{ - virtual ~const_expr_visitor() = default; - virtual void visit(const and_expr*) = 0; - virtual void visit(const or_expr*) = 0; - virtual void visit(const not_expr*) = 0; - virtual void visit(const identifier_expr*) = 0; - virtual void visit(const value_expr*) = 0; - virtual void visit(const list_expr*) = 0; - virtual void visit(const unary_check_expr*) = 0; - virtual void visit(const binary_check_expr*) = 0; - virtual void visit(const field_expr*) = 0; - virtual void visit(const field_transformer_expr*) = 0; +struct SINSP_PUBLIC const_expr_visitor { + virtual ~const_expr_visitor() = default; + virtual void visit(const and_expr*) = 0; + virtual void visit(const or_expr*) = 0; + virtual void visit(const not_expr*) = 0; + virtual void visit(const identifier_expr*) = 0; + virtual void visit(const value_expr*) = 0; + virtual void visit(const list_expr*) = 0; + virtual void visit(const unary_check_expr*) = 0; + virtual void visit(const binary_check_expr*) = 0; + virtual void visit(const field_expr*) = 0; + virtual void visit(const field_transformer_expr*) = 0; }; /*! @@ -127,518 +119,410 @@ struct SINSP_PUBLIC const_expr_visitor avoid overriding empty methods if they are not interested in a specific type of AST node */ -struct SINSP_PUBLIC base_expr_visitor: public expr_visitor -{ +struct SINSP_PUBLIC base_expr_visitor : public expr_visitor { public: - /*! - \brief Can be set to true by subclasses to instruct the - visitor that the exploration can be stopped, so - that the recursion gets rewinded and no more nodes - are explored. - */ - inline void stop(bool v) - { - m_should_stop_visit = v; - } - - virtual void visit(and_expr*) override; - virtual void visit(or_expr*) override; - virtual void visit(not_expr*) override; - virtual void visit(identifier_expr*) override; - virtual void visit(value_expr*) override; - virtual void visit(list_expr*) override; - virtual void visit(unary_check_expr*) override; - virtual void visit(binary_check_expr*) override; - virtual void visit(field_expr*) override; - virtual void visit(field_transformer_expr*) override; + /*! + \brief Can be set to true by subclasses to instruct the + visitor that the exploration can be stopped, so + that the recursion gets rewinded and no more nodes + are explored. + */ + inline void stop(bool v) { m_should_stop_visit = v; } + + virtual void visit(and_expr*) override; + virtual void visit(or_expr*) override; + virtual void visit(not_expr*) override; + virtual void visit(identifier_expr*) override; + virtual void visit(value_expr*) override; + virtual void visit(list_expr*) override; + virtual void visit(unary_check_expr*) override; + virtual void visit(binary_check_expr*) override; + virtual void visit(field_expr*) override; + virtual void visit(field_transformer_expr*) override; private: - bool m_should_stop_visit = false; + bool m_should_stop_visit = false; }; /*! \brief An analog of base_expr_visitor, but const. */ -struct SINSP_PUBLIC const_base_expr_visitor: public const_expr_visitor -{ +struct SINSP_PUBLIC const_base_expr_visitor : public const_expr_visitor { public: - /*! - \brief Can be set to true by subclasses to instruct the - visitor that the exploration can be stopped, so - that the recursion gets rewinded and no more nodes - are explored. - */ - inline void stop(bool v) - { - m_should_stop_visit = v; - } - - virtual void visit(const and_expr*) override; - virtual void visit(const or_expr*) override; - virtual void visit(const not_expr*) override; - virtual void visit(const identifier_expr*) override; - virtual void visit(const value_expr*) override; - virtual void visit(const list_expr*) override; - virtual void visit(const unary_check_expr*) override; - virtual void visit(const binary_check_expr*) override; - virtual void visit(const field_expr*) override; - virtual void visit(const field_transformer_expr*) override; + /*! + \brief Can be set to true by subclasses to instruct the + visitor that the exploration can be stopped, so + that the recursion gets rewinded and no more nodes + are explored. + */ + inline void stop(bool v) { m_should_stop_visit = v; } + + virtual void visit(const and_expr*) override; + virtual void visit(const or_expr*) override; + virtual void visit(const not_expr*) override; + virtual void visit(const identifier_expr*) override; + virtual void visit(const value_expr*) override; + virtual void visit(const list_expr*) override; + virtual void visit(const unary_check_expr*) override; + virtual void visit(const binary_check_expr*) override; + virtual void visit(const field_expr*) override; + virtual void visit(const field_transformer_expr*) override; private: - bool m_should_stop_visit = false; + bool m_should_stop_visit = false; }; /*! \brief A visitor that builds a string as it traverses the ast. Used to convert to strings. */ -struct SINSP_PUBLIC string_visitor: public const_expr_visitor -{ +struct SINSP_PUBLIC string_visitor : public const_expr_visitor { public: - virtual ~string_visitor() = default; - virtual void visit(const and_expr*) override; - virtual void visit(const or_expr*) override; - virtual void visit(const not_expr*) override; - virtual void visit(const identifier_expr*) override; - virtual void visit(const value_expr*) override; - virtual void visit(const list_expr*) override; - virtual void visit(const unary_check_expr*) override; - virtual void visit(const binary_check_expr*) override; - virtual void visit(const field_expr*) override; - virtual void visit(const field_transformer_expr*) override; - - const std::string& as_string(); + virtual ~string_visitor() = default; + virtual void visit(const and_expr*) override; + virtual void visit(const or_expr*) override; + virtual void visit(const not_expr*) override; + virtual void visit(const identifier_expr*) override; + virtual void visit(const value_expr*) override; + virtual void visit(const list_expr*) override; + virtual void visit(const unary_check_expr*) override; + virtual void visit(const binary_check_expr*) override; + virtual void visit(const field_expr*) override; + virtual void visit(const field_transformer_expr*) override; + + const std::string& as_string(); protected: + void visit_logical_op(const char* op, const std::vector>& children); - void visit_logical_op(const char *op, const std::vector> &children); - - std::string m_str; + std::string m_str; }; /*! \brief Base interface of AST hierarchy */ -class SINSP_PUBLIC expr -{ +class SINSP_PUBLIC expr { public: - virtual ~expr() = default; - virtual void accept(expr_visitor*) = 0; - virtual void accept(const_expr_visitor*) const = 0; - virtual bool is_equal(const expr* other) const = 0; + virtual ~expr() = default; + virtual void accept(expr_visitor*) = 0; + virtual void accept(const_expr_visitor*) const = 0; + virtual bool is_equal(const expr* other) const = 0; - const pos_info& get_pos() const { return m_pos; } - void set_pos(const pos_info& pos) { m_pos = pos; } + const pos_info& get_pos() const { return m_pos; } + void set_pos(const pos_info& pos) { m_pos = pos; } private: - pos_info m_pos; + pos_info m_pos; }; /*! \brief Compares two ASTs, returns true if they are deep equal */ -static inline bool compare(const expr* left, const expr* right) -{ - return left->is_equal(right); +static inline bool compare(const expr* left, const expr* right) { + return left->is_equal(right); }; -struct SINSP_PUBLIC and_expr: expr -{ - and_expr() = default; - virtual ~and_expr() = default; - - explicit and_expr(std::vector> &c): children(std::move(c)) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - if (o == nullptr || o->children.size() != children.size()) - { - return false; - } - - for (size_t i = 0; i < children.size(); i++) - { - if (!compare(children[i].get(), o->children[i].get())) - { - return false; - } - } - - return true; - } - - std::vector> children; - - static std::unique_ptr create(std::vector> &c, - const libsinsp::filter::ast::pos_info &pos = s_initial_pos) - { - auto ret = std::make_unique(c); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC and_expr : expr { + and_expr() = default; + virtual ~and_expr() = default; + + explicit and_expr(std::vector>& c): children(std::move(c)) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + if(o == nullptr || o->children.size() != children.size()) { + return false; + } + + for(size_t i = 0; i < children.size(); i++) { + if(!compare(children[i].get(), o->children[i].get())) { + return false; + } + } + + return true; + } + + std::vector> children; + + static std::unique_ptr create( + std::vector>& c, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(c); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC or_expr: expr -{ - or_expr() = default; - virtual ~or_expr() = default; - - explicit or_expr(std::vector> &c): children(std::move(c)) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - if (o == nullptr || o->children.size() != children.size()) - { - return false; - } - - for (size_t i = 0; i < children.size(); i++) - { - if (!compare(children[i].get(), o->children[i].get())) - { - return false; - } - } - - return true; - } - - std::vector> children; - - static std::unique_ptr create(std::vector> &c, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(c); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC or_expr : expr { + or_expr() = default; + virtual ~or_expr() = default; + + explicit or_expr(std::vector>& c): children(std::move(c)) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + if(o == nullptr || o->children.size() != children.size()) { + return false; + } + + for(size_t i = 0; i < children.size(); i++) { + if(!compare(children[i].get(), o->children[i].get())) { + return false; + } + } + + return true; + } + + std::vector> children; + + static std::unique_ptr create( + std::vector>& c, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(c); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC not_expr: expr -{ - not_expr() = default; - virtual ~not_expr() = default; - - explicit not_expr(std::unique_ptr c): child(std::move(c)) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr && this->child->is_equal(o->child.get()); - } - - std::unique_ptr child; - - static std::unique_ptr create(std::unique_ptr c, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(std::move(c)); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC not_expr : expr { + not_expr() = default; + virtual ~not_expr() = default; + + explicit not_expr(std::unique_ptr c): child(std::move(c)) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && this->child->is_equal(o->child.get()); + } + + std::unique_ptr child; + + static std::unique_ptr create( + std::unique_ptr c, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(std::move(c)); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC identifier_expr: expr -{ - identifier_expr() = default; - virtual ~identifier_expr() = default; - - explicit identifier_expr(const std::string& i): identifier(i) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr && identifier == o->identifier; - } - - std::string identifier; - - static std::unique_ptr create(const std::string& i, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(i); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC identifier_expr : expr { + identifier_expr() = default; + virtual ~identifier_expr() = default; + + explicit identifier_expr(const std::string& i): identifier(i) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && identifier == o->identifier; + } + + std::string identifier; + + static std::unique_ptr create( + const std::string& i, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(i); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC value_expr: expr -{ - value_expr() = default; - virtual ~value_expr() = default; - - explicit value_expr(const std::string& v): value(v) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr && value == o->value; - } - - std::string value; - - static std::unique_ptr create(const std::string& v, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(v); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC value_expr : expr { + value_expr() = default; + virtual ~value_expr() = default; + + explicit value_expr(const std::string& v): value(v) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && value == o->value; + } + + std::string value; + + static std::unique_ptr create( + const std::string& v, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(v); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC list_expr: expr -{ - list_expr() = default; - virtual ~list_expr() = default; - - explicit list_expr(const std::vector& v): values(v) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr && values == o->values; - } - - std::vector values; - - static std::unique_ptr create(const std::vector& v, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(v); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC list_expr : expr { + list_expr() = default; + virtual ~list_expr() = default; + + explicit list_expr(const std::vector& v): values(v) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && values == o->values; + } + + std::vector values; + + static std::unique_ptr create( + const std::vector& v, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(v); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC unary_check_expr: expr -{ - unary_check_expr() = default; - virtual ~unary_check_expr() = default; - - unary_check_expr( - std::unique_ptr l, - const std::string& o): left(std::move(l)), op(o) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr && left->is_equal(o->left.get()) && op == o->op; - } - - std::unique_ptr left; - std::string op; - - static std::unique_ptr create( - std::unique_ptr l, - const std::string& o, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(std::move(l), o); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC unary_check_expr : expr { + unary_check_expr() = default; + virtual ~unary_check_expr() = default; + + unary_check_expr(std::unique_ptr l, const std::string& o): left(std::move(l)), op(o) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && left->is_equal(o->left.get()) && op == o->op; + } + + std::unique_ptr left; + std::string op; + + static std::unique_ptr create( + std::unique_ptr l, + const std::string& o, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(std::move(l), o); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC binary_check_expr: expr -{ - binary_check_expr() = default; - virtual ~binary_check_expr() = default; - - binary_check_expr( - std::unique_ptr l, - const std::string& o, - std::unique_ptr r): left(std::move(l)), op(o), right(std::move(r)) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr - && left->is_equal(o->left.get()) - && op == o->op - && right->is_equal(o->right.get()); - } - - std::unique_ptr left; - std::string op; - std::unique_ptr right; - - static std::unique_ptr create( - std::unique_ptr l, - const std::string& o, - std::unique_ptr r, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(std::move(l), o, std::move(r)); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC binary_check_expr : expr { + binary_check_expr() = default; + virtual ~binary_check_expr() = default; + + binary_check_expr(std::unique_ptr l, const std::string& o, std::unique_ptr r): + left(std::move(l)), + op(o), + right(std::move(r)) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && left->is_equal(o->left.get()) && op == o->op && + right->is_equal(o->right.get()); + } + + std::unique_ptr left; + std::string op; + std::unique_ptr right; + + static std::unique_ptr create( + std::unique_ptr l, + const std::string& o, + std::unique_ptr r, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(std::move(l), o, std::move(r)); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC field_expr: expr -{ - field_expr() = default; - virtual ~field_expr() = default; - - field_expr( - const std::string& f, - const std::string& a): field(f), arg(a) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr && field == o->field && arg == o->arg; - } - - std::string field; - std::string arg; - - static std::unique_ptr create( - const std::string& f, - const std::string& a, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(f, a); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC field_expr : expr { + field_expr() = default; + virtual ~field_expr() = default; + + field_expr(const std::string& f, const std::string& a): field(f), arg(a) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && field == o->field && arg == o->arg; + } + + std::string field; + std::string arg; + + static std::unique_ptr create( + const std::string& f, + const std::string& a, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(f, a); + ret->set_pos(pos); + return ret; + } }; -struct SINSP_PUBLIC field_transformer_expr: expr -{ - field_transformer_expr() = default; - virtual ~field_transformer_expr() = default; - - field_transformer_expr( - const std::string& t, - std::unique_ptr v): transformer(t), value(std::move(v)) { } - - void accept(expr_visitor* v) override - { - v->visit(this); - }; - - void accept(const_expr_visitor* v) const override - { - v->visit(this); - }; - - bool is_equal(const expr* other) const override - { - auto o = dynamic_cast(other); - return o != nullptr && transformer == o->transformer && value->is_equal(o->value.get()); - } - - std::string transformer; - std::unique_ptr value; - - static std::unique_ptr create( - const std::string& m, - std::unique_ptr v, - const libsinsp::filter::ast::pos_info& pos = s_initial_pos) - { - auto ret = std::make_unique(m, std::move(v)); - ret->set_pos(pos); - return ret; - } +struct SINSP_PUBLIC field_transformer_expr : expr { + field_transformer_expr() = default; + virtual ~field_transformer_expr() = default; + + field_transformer_expr(const std::string& t, std::unique_ptr v): + transformer(t), + value(std::move(v)) {} + + void accept(expr_visitor* v) override { v->visit(this); }; + + void accept(const_expr_visitor* v) const override { v->visit(this); }; + + bool is_equal(const expr* other) const override { + auto o = dynamic_cast(other); + return o != nullptr && transformer == o->transformer && value->is_equal(o->value.get()); + } + + std::string transformer; + std::unique_ptr value; + + static std::unique_ptr create( + const std::string& m, + std::unique_ptr v, + const libsinsp::filter::ast::pos_info& pos = s_initial_pos) { + auto ret = std::make_unique(m, std::move(v)); + ret->set_pos(pos); + return ret; + } }; /*! \brief Return a string representation of an AST. \return A string representation of an AST. */ -std::string as_string(const ast::expr *e); +std::string as_string(const ast::expr* e); /*! \brief Creates a deep clone of a filter AST @@ -647,6 +531,6 @@ std::string as_string(const ast::expr *e); */ std::unique_ptr clone(const expr* e); -} -} -} +} // namespace ast +} // namespace filter +} // namespace libsinsp diff --git a/userspace/libsinsp/filter/escaping.cpp b/userspace/libsinsp/filter/escaping.cpp index 0cbdb26e2c..6568b1269e 100644 --- a/userspace/libsinsp/filter/escaping.cpp +++ b/userspace/libsinsp/filter/escaping.cpp @@ -22,15 +22,12 @@ limitations under the License. namespace libsinsp { namespace filter { -std::string escape_str(const std::string& str) -{ +std::string escape_str(const std::string& str) { std::string res = ""; size_t len = str.size(); bool should_escape = false; - for (size_t i = 0; i < len; i++) - { - switch(str[i]) - { + for(size_t i = 0; i < len; i++) { + switch(str[i]) { case '\b': should_escape = true; res += "\\b"; @@ -72,80 +69,69 @@ std::string escape_str(const std::string& str) } } - if(should_escape) - { + if(should_escape) { res = "\"" + res + "\""; } return res; } -std::string unescape_str(const std::string& str) -{ +std::string unescape_str(const std::string& str) { std::string res = ""; size_t len = str.size() - 1; bool escaped = false; - for (size_t i = 1; i < len; i++) - { - if (!escaped) - { - if (str[i] == '\\') - { + for(size_t i = 1; i < len; i++) { + if(!escaped) { + if(str[i] == '\\') { escaped = true; - } - else - { + } else { res += str[i]; } - } - else - { - switch(str[i]) - { - case 'b': - res += '\b'; - break; - case 'f': - res += '\f'; - break; - case 'n': - res += '\n'; - break; - case 'r': - res += '\r'; - break; - case 't': - res += '\t'; - break; - case ' ': - // NOTE: we may need to initially support this to not create breaking changes with - // some existing wrongly-escaped rules. So far, I only found one, in Falco: - // https://github.com/falcosecurity/falco/blob/204f9ff875be035e620ca1affdf374dd1c610a98/rules/falco_rules.yaml#L3046 - // todo(jasondellaluce): remove this once rules are rewritten with correct escaping - case '\\': - res += '\\'; - break; - case '/': - res += '/'; - break; - case '"': - if (str[0] != str[i]) - { - throw sinsp_exception("invalid \\\" escape in '-quoted string"); - } - res += '\"'; - break; - case '\'': - if (str[0] != str[i]) - { - throw sinsp_exception("invalid \\' escape in \"-quoted string"); - } - res += '\''; - break; - case 'x': - // todo(jasondellaluce): support hex num escaping (not needed for now) - default: - throw sinsp_exception("unsupported string escape sequence: \\" + std::string(1, str[i])); + } else { + switch(str[i]) { + case 'b': + res += '\b'; + break; + case 'f': + res += '\f'; + break; + case 'n': + res += '\n'; + break; + case 'r': + res += '\r'; + break; + case 't': + res += '\t'; + break; + case ' ': + // NOTE: we may need to initially support this to not create breaking changes with + // some existing wrongly-escaped rules. So far, I only found one, in Falco: + // https://github.com/falcosecurity/falco/blob/204f9ff875be035e620ca1affdf374dd1c610a98/rules/falco_rules.yaml#L3046 + // todo(jasondellaluce): remove this once rules are rewritten with correct escaping + case '\\': + res += '\\'; + break; + case '/': + res += '/'; + break; + case '"': + if(str[0] != str[i]) { + throw sinsp_exception("invalid \\\" escape in '-quoted string"); + } + res += '\"'; + break; + case '\'': + if(str[0] != str[i]) { + throw sinsp_exception("invalid \\' escape in \"-quoted string"); + } + res += '\''; + break; + case 'x': + // todo(jasondellaluce): support hex num escaping (not needed for now) + default: + throw sinsp_exception("unsupported string escape sequence: \\" + + std::string(1, str[i])); } escaped = false; } @@ -153,5 +139,5 @@ std::string unescape_str(const std::string& str) return res; } -} -} +} // namespace filter +} // namespace libsinsp diff --git a/userspace/libsinsp/filter/escaping.h b/userspace/libsinsp/filter/escaping.h index a41fccb9e5..5fe9beffa4 100644 --- a/userspace/libsinsp/filter/escaping.h +++ b/userspace/libsinsp/filter/escaping.h @@ -24,13 +24,12 @@ namespace libsinsp { namespace filter { /*! - \brief Methods to escape/unescape strings - \note Throws a sinsp_exception in case of parsing errors. - \return an escaped/unescaped verison of the string + \brief Methods to escape/unescape strings + \note Throws a sinsp_exception in case of parsing errors. + \return an escaped/unescaped verison of the string */ std::string escape_str(const std::string& str); std::string unescape_str(const std::string& str); - -} -} +} // namespace filter +} // namespace libsinsp diff --git a/userspace/libsinsp/filter/parser.cpp b/userspace/libsinsp/filter/parser.cpp index 4f1495c7ba..c8a9808c06 100644 --- a/userspace/libsinsp/filter/parser.cpp +++ b/userspace/libsinsp/filter/parser.cpp @@ -27,28 +27,26 @@ limitations under the License. #include // these follow the POSIX standard -#define RGX_NOTBLANK "(not[[:space:]]+)" -#define RGX_IDENTIFIER "([a-zA-Z]+[a-zA-Z0-9_]*)" -#define RGX_FIELDNAME "([a-zA-Z]+[a-zA-Z0-9_]*(\\.[a-zA-Z]+[a-zA-Z0-9_]*)+)" -#define RGX_FIELDARGBARESTR "([^][\"'[:space:]]+)" -#define RGX_HEXNUM "(0[xX][0-9a-zA-Z]+)" -#define RGX_NUMBER "([+\\-]?[0-9]+[\\.]?[0-9]*([eE][+\\-][0-9]+)?)" -#define RGX_BARESTR "([^()\"'[:space:]=,]+)" +#define RGX_NOTBLANK "(not[[:space:]]+)" +#define RGX_IDENTIFIER "([a-zA-Z]+[a-zA-Z0-9_]*)" +#define RGX_FIELDNAME "([a-zA-Z]+[a-zA-Z0-9_]*(\\.[a-zA-Z]+[a-zA-Z0-9_]*)+)" +#define RGX_FIELDARGBARESTR "([^][\"'[:space:]]+)" +#define RGX_HEXNUM "(0[xX][0-9a-zA-Z]+)" +#define RGX_NUMBER "([+\\-]?[0-9]+[\\.]?[0-9]*([eE][+\\-][0-9]+)?)" +#define RGX_BARESTR "([^()\"'[:space:]=,]+)" // small utility for monitoring the depth of parser's recursion -class depth_guard -{ +class depth_guard { public: inline ~depth_guard() { m_val--; } - inline depth_guard(uint32_t max, uint32_t& v): m_val(v) - { + inline depth_guard(uint32_t max, uint32_t& v): m_val(v) { m_val++; - if (m_val >= max) - { + if(m_val >= max) { throw sinsp_exception("exceeded max depth limit of " + std::to_string(max)); } } + private: uint32_t& m_val; }; @@ -64,69 +62,68 @@ static re2::RE2 s_rgx_barestr(RGX_BARESTR, re2::RE2::POSIX); using namespace libsinsp::filter; -static const std::vector s_unary_ops = -{ - "exists" -}; +static const std::vector s_unary_ops = {"exists"}; -static const std::vector s_binary_num_ops = -{ - "<=", "<", ">=", ">" -}; +static const std::vector s_binary_num_ops = {"<=", "<", ">=", ">"}; // todo(jasondellaluce): we should accept any blank after these (even line breaks) -static const std::vector s_binary_str_ops = -{ - "==", "=", "!=", "glob ", "iglob ", "contains ", "icontains ", - "bcontains ", "startswith ", "bstartswith ", "endswith ", "regex ", +static const std::vector s_binary_str_ops = { + "==", + "=", + "!=", + "glob ", + "iglob ", + "contains ", + "icontains ", + "bcontains ", + "startswith ", + "bstartswith ", + "endswith ", + "regex ", }; -static const std::vector s_binary_list_ops = -{ - "intersects", "in", "pmatch", +static const std::vector s_binary_list_ops = { + "intersects", + "in", + "pmatch", }; static constexpr const char* s_field_transformer_val = "val("; -static const std::vector s_field_transformers = -{ - "tolower(", "toupper(", "b64(", "basename(", +static const std::vector s_field_transformers = { + "tolower(", + "toupper(", + "b64(", + "basename(", }; -static inline void update_pos(const char c, ast::pos_info& pos) -{ +static inline void update_pos(const char c, ast::pos_info& pos) { pos.col++; - if (c == '\r' || c == '\n') - { + if(c == '\r' || c == '\n') { pos.col = 1; pos.line++; } pos.idx++; } -static void update_pos(const std::string& s, ast::pos_info& pos) -{ - for (const auto &c : s) - { +static void update_pos(const std::string& s, ast::pos_info& pos) { + for(const auto& c : s) { update_pos(c, pos); } } -template inline std::string token_list_to_str(const T& vals) -{ +template +inline std::string token_list_to_str(const T& vals) { std::string ret; - for(const auto& v : vals) - { + for(const auto& v : vals) { ret += ret.empty() ? "" : ", "; ret += "'" + v + "'"; } return ret; } -std::vector parser::supported_operators(bool list_only) -{ - if (list_only) - { +std::vector parser::supported_operators(bool list_only) { + if(list_only) { return s_binary_list_ops; } std::vector ops; @@ -138,24 +135,20 @@ std::vector parser::supported_operators(bool list_only) return ops; } -std::vector parser::supported_field_transformers(bool include_val) -{ +std::vector parser::supported_field_transformers(bool include_val) { std::vector res; - if (include_val) - { + if(include_val) { res.push_back(s_field_transformer_val); - res.back().pop_back(); // remove '(' char + res.back().pop_back(); // remove '(' char } - for (const auto& v : s_field_transformers) - { + for(const auto& v : s_field_transformers) { res.push_back(v); - res.back().pop_back(); // remove '(' char + res.back().pop_back(); // remove '(' char } return res; } -parser::parser(const std::string& input) -{ +parser::parser(const std::string& input) { m_input = input; m_pos.reset(); m_depth = 0; @@ -163,54 +156,46 @@ parser::parser(const std::string& input) m_parse_partial = false; } -void parser::get_pos(ast::pos_info& pos) const -{ +void parser::get_pos(ast::pos_info& pos) const { pos.idx = m_pos.idx; pos.col = m_pos.col; pos.line = m_pos.line; } -ast::pos_info parser::get_pos() const -{ +ast::pos_info parser::get_pos() const { ast::pos_info info; get_pos(info); return info; } -void parser::set_parse_partial(bool parse_partial) -{ +void parser::set_parse_partial(bool parse_partial) { m_parse_partial = parse_partial; } -void parser::set_max_depth(uint32_t max_depth) -{ +void parser::set_max_depth(uint32_t max_depth) { m_max_depth = max_depth; } -std::unique_ptr parser::parse() -{ - if (m_input.size() == 0) - { +std::unique_ptr parser::parse() { + if(m_input.size() == 0) { throw sinsp_exception("filter input string is empty"); } m_pos.reset(); m_last_token = ""; m_depth = 0; auto res = parse_or(); - if (m_depth > 0) - { + if(m_depth > 0) { ASSERT(false); throw sinsp_exception("parser fatal error: recursion is unbalanced"); } - if (!m_parse_partial && m_pos.idx != m_input.size()) - { - throw sinsp_exception("unexpected token after '" + m_last_token + "', expecting 'or', 'and'"); + if(!m_parse_partial && m_pos.idx != m_input.size()) { + throw sinsp_exception("unexpected token after '" + m_last_token + + "', expecting 'or', 'and'"); } return res; } -std::unique_ptr parser::parse_or() -{ +std::unique_ptr parser::parse_or() { depth_guard(m_max_depth, m_depth); auto pos = get_pos(); @@ -218,36 +203,27 @@ std::unique_ptr parser::parse_or() lex_blank(); children.push_back(parse_and()); lex_blank(); - while (lex_helper_str("or")) - { + while(lex_helper_str("or")) { std::unique_ptr child; - if (!lex_blank()) - { - if (lex_helper_str("(")) - { + if(!lex_blank()) { + if(lex_helper_str("(")) { child = parse_embedded_remainder(); - } - else - { + } else { throw sinsp_exception("expected blank or '(' after 'or'"); } - } - else - { + } else { child = parse_and(); } children.push_back(std::move(child)); lex_blank(); } - if (children.size() > 1) - { + if(children.size() > 1) { return ast::or_expr::create(children, pos); } return std::move(children[0]); } -std::unique_ptr parser::parse_and() -{ +std::unique_ptr parser::parse_and() { depth_guard(m_max_depth, m_depth); auto pos = get_pos(); @@ -256,52 +232,39 @@ std::unique_ptr parser::parse_and() lex_blank(); children.push_back(parse_not()); lex_blank(); - while (lex_helper_str("and")) - { - if (!lex_blank()) - { - if (lex_helper_str("(")) - { + while(lex_helper_str("and")) { + if(!lex_blank()) { + if(lex_helper_str("(")) { child = parse_embedded_remainder(); - } - else - { + } else { throw sinsp_exception("expected blank or '(' after 'and'"); } - } - else - { + } else { child = parse_not(); } children.push_back(std::move(child)); lex_blank(); } - if (children.size() > 1) - { + if(children.size() > 1) { return ast::and_expr::create(children, pos); } return std::move(children[0]); } -std::unique_ptr parser::parse_not() -{ +std::unique_ptr parser::parse_not() { depth_guard(m_max_depth, m_depth); auto pos = get_pos(); bool is_not = false; std::unique_ptr child; lex_blank(); - while (lex_helper_rgx(s_rgx_not_blank)) - { + while(lex_helper_rgx(s_rgx_not_blank)) { is_not = !is_not; } - if (lex_helper_str("not(")) - { + if(lex_helper_str("not(")) { is_not = !is_not; child = parse_embedded_remainder(); - } - else - { + } else { child = parse_check(); } return is_not ? ast::not_expr::create(std::move(child), pos) : std::move(child); @@ -309,73 +272,63 @@ std::unique_ptr parser::parse_not() // this is an internal helper to parse the remainder of a // self-embedding expression right after having parsed a "(" -std::unique_ptr parser::parse_embedded_remainder() -{ +std::unique_ptr parser::parse_embedded_remainder() { depth_guard(m_max_depth, m_depth); lex_blank(); std::unique_ptr child = parse_or(); lex_blank(); - if (!lex_helper_str(")")) - { + if(!lex_helper_str(")")) { throw sinsp_exception("expected a ')' token"); } return child; } -std::unique_ptr parser::parse_check() -{ +std::unique_ptr parser::parse_check() { depth_guard(m_max_depth, m_depth); auto pos = get_pos(); lex_blank(); - if (lex_helper_str("(")) - { + if(lex_helper_str("(")) { return parse_embedded_remainder(); } - if (lex_field_name()) - { + if(lex_field_name()) { auto left = parse_field_remainder(m_last_token, pos); return parse_condition(std::move(left), pos); } - if (lex_field_transformer_type()) - { + if(lex_field_transformer_type()) { lex_blank(); - m_last_token.pop_back(); // discard '(' character + m_last_token.pop_back(); // discard '(' character auto left = parse_field_or_transformer_remainder(m_last_token, pos); return parse_condition(std::move(left), pos); } - if (lex_identifier()) - { + if(lex_identifier()) { return ast::identifier_expr::create(m_last_token, pos); } throw sinsp_exception("expected a '(' token, a field check, or an identifier"); } -std::unique_ptr parser::parse_field_remainder( - std::string fieldname, const ast::pos_info& pos) -{ +std::unique_ptr parser::parse_field_remainder(std::string fieldname, + const ast::pos_info& pos) { depth_guard(m_max_depth, m_depth); auto field = std::make_unique(); field->field = fieldname; field->set_pos(pos); - if(lex_helper_str("[")) - { - if(!lex_quoted_str() && !lex_field_arg_bare_str()) - { - throw sinsp_exception("expected a valid field argument: a quoted string or a bare string"); + if(lex_helper_str("[")) { + if(!lex_quoted_str() && !lex_field_arg_bare_str()) { + throw sinsp_exception( + "expected a valid field argument: a quoted string or a bare string"); } field->arg = m_last_token; - if(!lex_helper_str("]")) - { + if(!lex_helper_str("]")) { throw sinsp_exception("expected a ']' token"); } } @@ -384,8 +337,8 @@ std::unique_ptr parser::parse_field_remainder( } inline std::unique_ptr parser::parse_field_or_transformer_remainder( - std::string transformer, const ast::pos_info& pos) -{ + std::string transformer, + const ast::pos_info& pos) { depth_guard(m_max_depth, m_depth); lex_blank(); @@ -393,40 +346,34 @@ inline std::unique_ptr parser::parse_field_or_transformer_remainder( auto arg_pos = get_pos(); std::unique_ptr child; - if (lex_field_transformer_type()) - { + if(lex_field_transformer_type()) { lex_blank(); - m_last_token.pop_back(); // discard '(' character + m_last_token.pop_back(); // discard '(' character child = parse_field_or_transformer_remainder(m_last_token, arg_pos); } - if (lex_field_name()) - { + if(lex_field_name()) { child = parse_field_remainder(m_last_token, arg_pos); } - if (!child) - { - throw sinsp_exception("expected a field or a nested valid transformer: " - + token_list_to_str(supported_field_transformers(true))); + if(!child) { + throw sinsp_exception("expected a field or a nested valid transformer: " + + token_list_to_str(supported_field_transformers(true))); } lex_blank(); - if (!lex_helper_str(")")) - { + if(!lex_helper_str(")")) { throw sinsp_exception("expected a ')' token closing the transformer"); } return ast::field_transformer_expr::create(transformer, std::move(child), pos); } -std::unique_ptr parser::parse_condition( - std::unique_ptr left, const ast::pos_info& pos) -{ +std::unique_ptr parser::parse_condition(std::unique_ptr left, + const ast::pos_info& pos) { depth_guard(m_max_depth, m_depth); lex_blank(); - if(lex_unary_op()) - { + if(lex_unary_op()) { return ast::unary_check_expr::create(std::move(left), trim_str(m_last_token), pos); } @@ -435,121 +382,97 @@ std::unique_ptr parser::parse_condition( lex_blank(); - if(lex_num_op()) - { + if(lex_num_op()) { op = m_last_token; right = parse_num_value_or_transformer(); - } - else if(lex_str_op()) - { + } else if(lex_str_op()) { op = m_last_token; right = parse_str_value_or_transformer(false); - } - else if(lex_list_op()) - { + } else if(lex_list_op()) { op = m_last_token; right = parse_list_value_or_transformer(); - } - else - { - throw sinsp_exception("expected a valid check operator: one of " - + token_list_to_str(supported_operators())); + } else { + throw sinsp_exception("expected a valid check operator: one of " + + token_list_to_str(supported_operators())); } return ast::binary_check_expr::create(std::move(left), trim_str(op), std::move(right), pos); } -std::unique_ptr parser::parse_num_value_or_transformer() -{ +std::unique_ptr parser::parse_num_value_or_transformer() { depth_guard(m_max_depth, m_depth); lex_blank(); auto pos = get_pos(); - - if (auto res = try_parse_transformer_or_val(); res != nullptr) - { + + if(auto res = try_parse_transformer_or_val(); res != nullptr) { return res; } - if (lex_hex_num() || lex_num()) - { + if(lex_hex_num() || lex_num()) { return ast::value_expr::create(m_last_token, pos); } - throw sinsp_exception("expected a number value or a field with a valid transformer: " - + token_list_to_str(supported_field_transformers(true))); + throw sinsp_exception("expected a number value or a field with a valid transformer: " + + token_list_to_str(supported_field_transformers(true))); } -std::unique_ptr parser::parse_str_value_or_transformer(bool no_transformer) -{ +std::unique_ptr parser::parse_str_value_or_transformer(bool no_transformer) { depth_guard(m_max_depth, m_depth); lex_blank(); auto pos = get_pos(); - if (!no_transformer) - { - if (auto res = try_parse_transformer_or_val(); res != nullptr) - { + if(!no_transformer) { + if(auto res = try_parse_transformer_or_val(); res != nullptr) { return res; } } - if (lex_quoted_str() || lex_bare_str()) - { + if(lex_quoted_str() || lex_bare_str()) { return ast::value_expr::create(m_last_token, pos); } - if (no_transformer) - { + if(no_transformer) { throw sinsp_exception("expected a string value"); } - throw sinsp_exception("expected a string value or a field with a valid transformer: " - + token_list_to_str(supported_field_transformers(true))); + throw sinsp_exception("expected a string value or a field with a valid transformer: " + + token_list_to_str(supported_field_transformers(true))); } -std::unique_ptr parser::parse_list_value_or_transformer() -{ +std::unique_ptr parser::parse_list_value_or_transformer() { depth_guard(m_max_depth, m_depth); lex_blank(); auto pos = get_pos(); - if (lex_helper_str("(")) - { + if(lex_helper_str("(")) { bool should_be_empty = false; ast::value_expr* value_child = nullptr; std::unique_ptr child; std::vector values; lex_blank(); - try - { + try { child = parse_str_value_or_transformer(true); - } - catch(const sinsp_exception& e) - { + } catch(const sinsp_exception& e) { should_be_empty = true; } - - if (!should_be_empty) - { + + if(!should_be_empty) { value_child = dynamic_cast(child.get()); - if (!value_child) - { + if(!value_child) { throw sinsp_exception("parser fatal error: null value expr in head of list"); } values.push_back(value_child->value); lex_blank(); - while (lex_helper_str(",")) - { + while(lex_helper_str(",")) { child = parse_str_value_or_transformer(true); value_child = dynamic_cast(child.get()); - if (!value_child) - { + if(!value_child) { throw sinsp_exception("parser fatal error: null value expr in body of list"); } values.push_back(value_child->value); @@ -557,63 +480,55 @@ std::unique_ptr parser::parse_list_value_or_transformer() } } - if (!lex_helper_str(")")) - { + if(!lex_helper_str(")")) { throw sinsp_exception("expected a ')' token"); } return ast::list_expr::create(values, pos); } - if (auto res = try_parse_transformer_or_val(); res != nullptr) - { + if(auto res = try_parse_transformer_or_val(); res != nullptr) { return res; } - if (lex_identifier()) - { + if(lex_identifier()) { return ast::value_expr::create(m_last_token, pos); } - throw sinsp_exception("expected a list, an identifier, or a field with a valid transformer: " - + token_list_to_str(supported_field_transformers(true))); + throw sinsp_exception("expected a list, an identifier, or a field with a valid transformer: " + + token_list_to_str(supported_field_transformers(true))); } // note: can return nullptr -std::unique_ptr parser::try_parse_transformer_or_val() -{ +std::unique_ptr parser::try_parse_transformer_or_val() { depth_guard(m_max_depth, m_depth); lex_blank(); auto pos = get_pos(); - if (lex_field_transformer_val()) - { + if(lex_field_transformer_val()) { lex_blank(); - m_last_token.pop_back(); // discard '(' character; + m_last_token.pop_back(); // discard '(' character; auto transformer = m_last_token; auto field_pos = get_pos(); - if (!lex_field_name()) - { + if(!lex_field_name()) { throw sinsp_exception("expected a field within '" + transformer + "' transformer"); } auto child = parse_field_remainder(m_last_token, field_pos); lex_blank(); - if (!lex_helper_str(")")) - { + if(!lex_helper_str(")")) { throw sinsp_exception("expected a ')' token closing the transformer"); } return ast::field_transformer_expr::create(transformer, std::move(child), pos); } - if (lex_field_transformer_type()) - { + if(lex_field_transformer_type()) { lex_blank(); - m_last_token.pop_back(); // discard '(' character + m_last_token.pop_back(); // discard '(' character return parse_field_or_transformer_remainder(m_last_token, pos); } @@ -621,55 +536,44 @@ std::unique_ptr parser::try_parse_transformer_or_val() } // note: lex_blank is the only lex method that does not update m_last_token. -bool parser::lex_blank() -{ +bool parser::lex_blank() { bool found = false; - while(*cursor() == ' ' || *cursor() == '\t' || *cursor() == '\b' - || *cursor() == '\r' || *cursor() == '\n') - { + while(*cursor() == ' ' || *cursor() == '\t' || *cursor() == '\b' || *cursor() == '\r' || + *cursor() == '\n') { found = true; update_pos(*cursor(), m_pos); } return found; } -inline bool parser::lex_identifier() -{ +inline bool parser::lex_identifier() { return lex_helper_rgx(s_rgx_identifier); } -inline bool parser::lex_field_name() -{ +inline bool parser::lex_field_name() { return lex_helper_rgx(s_rgx_field_name); } -inline bool parser::lex_field_arg_bare_str() -{ +inline bool parser::lex_field_arg_bare_str() { return lex_helper_rgx(s_rgx_field_arg_barestr); } -inline bool parser::lex_hex_num() -{ +inline bool parser::lex_hex_num() { return lex_helper_rgx(s_rgx_hex_num); } -inline bool parser::lex_num() -{ +inline bool parser::lex_num() { return lex_helper_rgx(s_rgx_num); } -inline bool parser::lex_quoted_str() -{ - if (*cursor() == '\'' || *cursor() == '\"') - { +inline bool parser::lex_quoted_str() { + if(*cursor() == '\'' || *cursor() == '\"') { char prev = '\\'; char delimiter = *cursor(); ast::pos_info pos = m_pos; m_last_token = ""; - while(*cursor() != '\0') - { - if (*cursor() == delimiter && prev != '\\') - { + while(*cursor() != '\0') { + if(*cursor() == delimiter && prev != '\\') { update_pos(*cursor(), m_pos); m_last_token += delimiter; m_last_token = unescape_str(m_last_token); @@ -684,57 +588,46 @@ inline bool parser::lex_quoted_str() return false; } -inline bool parser::lex_bare_str() -{ +inline bool parser::lex_bare_str() { return lex_helper_rgx(s_rgx_barestr); } -inline bool parser::lex_unary_op() -{ +inline bool parser::lex_unary_op() { return lex_helper_str_list(s_unary_ops); } -inline bool parser::lex_num_op() -{ +inline bool parser::lex_num_op() { return lex_helper_str_list(s_binary_num_ops); } -inline bool parser::lex_str_op() -{ +inline bool parser::lex_str_op() { return lex_helper_str_list(s_binary_str_ops); } -inline bool parser::lex_list_op() -{ +inline bool parser::lex_list_op() { return lex_helper_str_list(s_binary_list_ops); } -inline bool parser::lex_field_transformer_val() -{ +inline bool parser::lex_field_transformer_val() { return lex_helper_str(s_field_transformer_val); } -inline bool parser::lex_field_transformer_type() -{ +inline bool parser::lex_field_transformer_type() { return lex_helper_str_list(s_field_transformers); } -bool parser::lex_helper_rgx(const re2::RE2& rgx) -{ +bool parser::lex_helper_rgx(const re2::RE2& rgx) { ASSERT(rgx.ok()); re2::StringPiece c(cursor(), m_input.size() - m_pos.idx); - if (re2::RE2::Consume(&c, rgx, &m_last_token)) - { + if(re2::RE2::Consume(&c, rgx, &m_last_token)) { update_pos(m_last_token, m_pos); return true; } return false; } -bool parser::lex_helper_str(const std::string& str) -{ - if (strncmp(cursor(), str.c_str(), str.size()) == 0) - { +bool parser::lex_helper_str(const std::string& str) { + if(strncmp(cursor(), str.c_str(), str.size()) == 0) { m_last_token = str; update_pos(m_last_token, m_pos); return true; @@ -742,25 +635,20 @@ bool parser::lex_helper_str(const std::string& str) return false; } -bool parser::lex_helper_str_list(const std::vector& list) -{ - for (auto &op : list) - { - if (lex_helper_str(op)) - { +bool parser::lex_helper_str_list(const std::vector& list) { + for(auto& op : list) { + if(lex_helper_str(op)) { return true; } } return false; } -inline const char* parser::cursor() -{ +inline const char* parser::cursor() { return m_input.c_str() + m_pos.idx; } -inline std::string parser::trim_str(std::string str) -{ +inline std::string parser::trim_str(std::string str) { trim(str); return str; } diff --git a/userspace/libsinsp/filter/parser.h b/userspace/libsinsp/filter/parser.h index a783e592d1..92f4c9f28e 100644 --- a/userspace/libsinsp/filter/parser.h +++ b/userspace/libsinsp/filter/parser.h @@ -21,7 +21,9 @@ limitations under the License. #include #include -namespace re2 { class RE2; }; +namespace re2 { +class RE2; +}; // // Context-free Grammar for Sinsp Filters @@ -38,7 +40,7 @@ namespace re2 { class RE2; }; // NotExprTail ::= 'not(' Expr ')' // | Check // Check ::= Field Condition -// | FieldTransformer Condition +// | FieldTransformer Condition // | Identifier // | '(' Expr ')' // FieldTransformer ::= FieldTransformerType FieldTransformerTail @@ -54,21 +56,21 @@ namespace re2 { class RE2; }; // ListValue ::= '(' (StrValue (',' StrValue)*)* ')' // | Identifier // Field ::= FieldName('[' FieldArg ']')? -// FieldArg ::= QuotedStr | FieldArgBareStr +// FieldArg ::= QuotedStr | FieldArgBareStr // NumValue ::= HexNumber | Number // StrValue ::= QuotedStr | BareStr -// +// // Supported Check Operators (EBNF Syntax): // UnaryOperator ::= 'exists' -// NumOperator ::= '<=' | '<' | '>=' | '>' +// NumOperator ::= '<=' | '<' | '>=' | '>' // StrOperator ::= '==' | '=' | '!=' // | 'glob ' | 'iglob ' // | 'contains ' | 'icontains ' | 'bcontains ' // | 'startswith ' | 'bstartswith ' | 'endswith ' -// ListOperator ::= 'intersects' | 'in' | 'pmatch' +// ListOperator ::= 'intersects' | 'in' | 'pmatch' // FieldTransformerVal ::= 'val(' // FieldTransformerType ::= 'tolower(' | 'toupper(' | 'b64(' | 'basename(' -// +// // Tokens (Regular Expressions): // Identifier ::= [a-zA-Z]+[a-zA-Z0-9_]* // FieldName ::= [a-zA-Z]+[a-zA-Z0-9_]*(\.[a-zA-Z]+[a-zA-Z0-9_]*)+ @@ -83,62 +85,61 @@ namespace libsinsp { namespace filter { /*! - \brief This class parses a sinsp filter string with a context-free - formal grammar and generates an AST. + \brief This class parses a sinsp filter string with a context-free + formal grammar and generates an AST. */ -class SINSP_PUBLIC parser -{ +class SINSP_PUBLIC parser { public: /*! - \brief Returns the set of filtering operators supported by libsinsp + \brief Returns the set of filtering operators supported by libsinsp */ - static std::vector supported_operators(bool list_only=false); + static std::vector supported_operators(bool list_only = false); /*! - \brief Returns the set of field transformers supported by libsinsp + \brief Returns the set of field transformers supported by libsinsp */ - static std::vector supported_field_transformers(bool include_val=false); + static std::vector supported_field_transformers(bool include_val = false); /*! - \brief Constructs the parser with a given filter string input - \param input The filter string to parse. + \brief Constructs the parser with a given filter string input + \param input The filter string to parse. */ explicit parser(const std::string& input); /*! - \brief Retrieves the parser position info. - \param pos pos_info struct in which the info is written. + \brief Retrieves the parser position info. + \param pos pos_info struct in which the info is written. */ void get_pos(ast::pos_info& pos) const; /*! - \brief Retrieves the parser position info. - \return pos_info struct in which the info is written. + \brief Retrieves the parser position info. + \return pos_info struct in which the info is written. */ ast::pos_info get_pos() const; /*! - \brief Sets the partial parsing option. Default is true. - \note Parsing the input partially means that the parsing can succeed - without reaching the end of the input. In other word, this allows - parsing strings that have a valid filter as their prefix. + \brief Sets the partial parsing option. Default is true. + \note Parsing the input partially means that the parsing can succeed + without reaching the end of the input. In other word, this allows + parsing strings that have a valid filter as their prefix. */ void set_parse_partial(bool parse_partial); /*! - \brief Sets the max depth of the recursion. Default is 100. - \note The parser is implemented as a recursive descent parser, so the - depth of the recursion is capped to a max level to prevent stack abuse. + \brief Sets the max depth of the recursion. Default is 100. + \note The parser is implemented as a recursive descent parser, so the + depth of the recursion is capped to a max level to prevent stack abuse. */ void set_max_depth(uint32_t max_depth); /*! - \brief Parses the input and returns an AST. - \note Throws a sinsp_exception in case of parsing errors. - \return Pointer to a expr struct representing the the parsed - AST. The resulting pointer is owned by the caller and must be deleted - by it. The pointer is automatically deleted in case of exception. - On delete, each node of the AST deletes all its subnodes. + \brief Parses the input and returns an AST. + \note Throws a sinsp_exception in case of parsing errors. + \return Pointer to a expr struct representing the the parsed + AST. The resulting pointer is owned by the caller and must be deleted + by it. The pointer is automatically deleted in case of exception. + On delete, each node of the AST deletes all its subnodes. */ std::unique_ptr parse(); @@ -149,15 +150,13 @@ class SINSP_PUBLIC parser std::unique_ptr parse_embedded_remainder(); std::unique_ptr parse_check(); std::unique_ptr parse_list_value(); - std::unique_ptr parse_field_remainder( - std::string fieldname, - const libsinsp::filter::ast::pos_info& pos); + std::unique_ptr parse_field_remainder(std::string fieldname, + const libsinsp::filter::ast::pos_info& pos); std::unique_ptr parse_field_or_transformer_remainder( - std::string transformer, - const libsinsp::filter::ast::pos_info& pos); - std::unique_ptr parse_condition( - std::unique_ptr left, - const libsinsp::filter::ast::pos_info& pos); + std::string transformer, + const libsinsp::filter::ast::pos_info& pos); + std::unique_ptr parse_condition(std::unique_ptr left, + const libsinsp::filter::ast::pos_info& pos); std::unique_ptr parse_list_value_or_transformer(); std::unique_ptr parse_num_value_or_transformer(); std::unique_ptr parse_str_value_or_transformer(bool no_transformer); @@ -190,5 +189,5 @@ class SINSP_PUBLIC parser std::string m_last_token; }; -} -} +} // namespace filter +} // namespace libsinsp diff --git a/userspace/libsinsp/filter/ppm_codes.cpp b/userspace/libsinsp/filter/ppm_codes.cpp index 06d175825c..f5a885463f 100644 --- a/userspace/libsinsp/filter/ppm_codes.cpp +++ b/userspace/libsinsp/filter/ppm_codes.cpp @@ -21,12 +21,12 @@ limitations under the License. * NOTE: the following code has been ported from Falco and updated with the * new definitions and API of libsinsp::events. See previous code: * https://github.com/falcosecurity/falco/commit/2495827e0cd64452a7d696047ea1365bb0050ffa - * + * * Given a rule filtering condition (in AST form), the following logic is * responsible of returning the set of event types for which the * filtering condition can be evaluated to true. - * - * This implementation is based on the boolean algebraic properties of sets + * + * This implementation is based on the boolean algebraic properties of sets * and works as follows depending on the type of nodes: * - the evt types of "and" nodes are the intersection set of the evt types of * their children nodes. @@ -39,7 +39,7 @@ limitations under the License. * matches every evt type. * * checks non-related to evt types are neutral and match all evt types * (e.g. proc.name=cat). - * + * * The tricky part is handling negation (e.g. "not evt.type=open"). * Given a set of event types, its negation is the difference between the * "set of all events" and the set (e.g. all types but not the ones in the set). @@ -55,9 +55,8 @@ limitations under the License. * be constructed and negated depending on the different cases. */ -static bool is_evttype_operator(const std::string& op) -{ - return op == "==" || op == "=" || op == "!=" || op == "in"; +static bool is_evttype_operator(const std::string& op) { + return op == "==" || op == "=" || op == "!=" || op == "in"; } using name_set_t = std::unordered_set; @@ -65,215 +64,187 @@ using name_set_t = std::unordered_set; template -struct ppm_code_visitor: public libsinsp::filter::ast::const_expr_visitor -{ - ppm_code_visitor() = default; - virtual ~ppm_code_visitor() = default; - ppm_code_visitor(ppm_code_visitor&&) = default; - ppm_code_visitor& operator = (ppm_code_visitor&&) = default; - ppm_code_visitor(const ppm_code_visitor&) = default; - ppm_code_visitor& operator = (const ppm_code_visitor&) = default; - - bool m_last_node_is_evttype_field = false; - bool m_last_node_is_field_or_transformer = true; - bool m_inside_negation = false; - bool m_last_node_has_codes = false; - code_set_t m_last_node_codes{}; - - inline void inversion(code_set_t& types) - { - // we don't invert "neutral" checks - if (m_last_node_has_codes) - { - types = all_codes_set().diff(types); - } - } - - inline void try_inversion(code_set_t& types) - { - if (m_inside_negation) - { - inversion(types); - } - } - - inline void conjunction(const std::vector>& children) - { - code_set_t types = all_codes_set(); - for (auto &c : children) - { - c->accept(this); - types = types.intersect(m_last_node_codes); - } - m_last_node_codes = types; - m_last_node_is_evttype_field = false; - } - - inline void disjunction(const std::vector>& children) - { - code_set_t types; - for (auto &c : children) - { - c->accept(this); - types = types.merge(m_last_node_codes); - } - m_last_node_codes = types; - m_last_node_is_evttype_field = false; - } - - void visit(const libsinsp::filter::ast::and_expr* e) override - { - if (m_inside_negation) - { - disjunction(e->children); - } - else - { - conjunction(e->children); - } - } - - void visit(const libsinsp::filter::ast::or_expr* e) override - { - if (m_inside_negation) - { - conjunction(e->children); - } - else - { - disjunction(e->children); - } - } - - void visit(const libsinsp::filter::ast::not_expr* e) override - { - m_last_node_codes.clear(); - auto inside_negation = m_inside_negation; - m_inside_negation = !m_inside_negation; - e->child->accept(this); - m_inside_negation = inside_negation; - m_last_node_is_evttype_field = false; - } - - void visit(const libsinsp::filter::ast::binary_check_expr* e) override - { - m_last_node_has_codes = false; - if (is_evttype_operator(e->op)) - { - e->left->accept(this); - if (m_last_node_is_evttype_field) - { - // note: we expect m_inside_negation and m_last_node_has_codes - // to be handled and altered by the child node - m_last_node_is_field_or_transformer = false; - e->right->accept(this); - if (m_last_node_is_field_or_transformer) - { - throw sinsp_exception("right-hand field comparisons on `evt.type` checks are not supported by event code search"); - } - if (e->op == "!=") - { - // note: since we push the "negation" down to the tree leaves - // (following de morgan's laws logic), the child node may have - // already inverted the set of matched event type. As such, - // inverting here again is safe for supporting both the - // single-negation and double-negation cases. - inversion(m_last_node_codes); - } - m_last_node_is_evttype_field = false; - return; - } - } - m_last_node_codes = all_codes_set(); - m_last_node_is_evttype_field = false; - try_inversion(m_last_node_codes); - } - - void visit(const libsinsp::filter::ast::unary_check_expr* e) override - { - e->left->accept(this); - m_last_node_has_codes = m_last_node_is_evttype_field && e->op == "exists"; - m_last_node_codes = all_codes_set(); - m_last_node_is_evttype_field = false; - try_inversion(m_last_node_codes); - } - - void visit(const libsinsp::filter::ast::identifier_expr* e) override - { - // this case only happens if a macro has not yet been substituted - // with an actual condition. Should not happen, but we handle it - // for consistency. - m_last_node_has_codes = false; - m_last_node_codes = all_codes_set(); - m_last_node_is_evttype_field = false; - try_inversion(m_last_node_codes); - } - - void visit(const libsinsp::filter::ast::value_expr* e) override - { - m_last_node_has_codes = true; - m_last_node_codes = names_to_codes({e->value}); - m_last_node_is_evttype_field = false; - try_inversion(m_last_node_codes); - } - - void visit(const libsinsp::filter::ast::list_expr* e) override - { - m_last_node_has_codes = true; - name_set_t names; - for (const auto& n : e->values) - { - names.insert(n); - } - m_last_node_codes = names_to_codes(names); - m_last_node_is_evttype_field = false; - try_inversion(m_last_node_codes); - } - - void visit(const libsinsp::filter::ast::field_expr* e) override - { - m_last_node_has_codes = false; - m_last_node_is_field_or_transformer = true; - m_last_node_is_evttype_field = e->field == "evt.type" && e->arg.empty(); - m_last_node_codes = all_codes_set(); - try_inversion(m_last_node_codes); - } - - void visit(const libsinsp::filter::ast::field_transformer_expr* e) override - { - e->value->accept(this); - if (m_last_node_is_evttype_field) - { - throw sinsp_exception("event code search does not support `evt.type` checks with transformers"); - } - m_last_node_is_field_or_transformer = true; - } +struct ppm_code_visitor : public libsinsp::filter::ast::const_expr_visitor { + ppm_code_visitor() = default; + virtual ~ppm_code_visitor() = default; + ppm_code_visitor(ppm_code_visitor&&) = default; + ppm_code_visitor& operator=(ppm_code_visitor&&) = default; + ppm_code_visitor(const ppm_code_visitor&) = default; + ppm_code_visitor& operator=(const ppm_code_visitor&) = default; + + bool m_last_node_is_evttype_field = false; + bool m_last_node_is_field_or_transformer = true; + bool m_inside_negation = false; + bool m_last_node_has_codes = false; + code_set_t m_last_node_codes{}; + + inline void inversion(code_set_t& types) { + // we don't invert "neutral" checks + if(m_last_node_has_codes) { + types = all_codes_set().diff(types); + } + } + + inline void try_inversion(code_set_t& types) { + if(m_inside_negation) { + inversion(types); + } + } + + inline void conjunction( + const std::vector>& children) { + code_set_t types = all_codes_set(); + for(auto& c : children) { + c->accept(this); + types = types.intersect(m_last_node_codes); + } + m_last_node_codes = types; + m_last_node_is_evttype_field = false; + } + + inline void disjunction( + const std::vector>& children) { + code_set_t types; + for(auto& c : children) { + c->accept(this); + types = types.merge(m_last_node_codes); + } + m_last_node_codes = types; + m_last_node_is_evttype_field = false; + } + + void visit(const libsinsp::filter::ast::and_expr* e) override { + if(m_inside_negation) { + disjunction(e->children); + } else { + conjunction(e->children); + } + } + + void visit(const libsinsp::filter::ast::or_expr* e) override { + if(m_inside_negation) { + conjunction(e->children); + } else { + disjunction(e->children); + } + } + + void visit(const libsinsp::filter::ast::not_expr* e) override { + m_last_node_codes.clear(); + auto inside_negation = m_inside_negation; + m_inside_negation = !m_inside_negation; + e->child->accept(this); + m_inside_negation = inside_negation; + m_last_node_is_evttype_field = false; + } + + void visit(const libsinsp::filter::ast::binary_check_expr* e) override { + m_last_node_has_codes = false; + if(is_evttype_operator(e->op)) { + e->left->accept(this); + if(m_last_node_is_evttype_field) { + // note: we expect m_inside_negation and m_last_node_has_codes + // to be handled and altered by the child node + m_last_node_is_field_or_transformer = false; + e->right->accept(this); + if(m_last_node_is_field_or_transformer) { + throw sinsp_exception( + "right-hand field comparisons on `evt.type` checks are not supported " + "by event code search"); + } + if(e->op == "!=") { + // note: since we push the "negation" down to the tree leaves + // (following de morgan's laws logic), the child node may have + // already inverted the set of matched event type. As such, + // inverting here again is safe for supporting both the + // single-negation and double-negation cases. + inversion(m_last_node_codes); + } + m_last_node_is_evttype_field = false; + return; + } + } + m_last_node_codes = all_codes_set(); + m_last_node_is_evttype_field = false; + try_inversion(m_last_node_codes); + } + + void visit(const libsinsp::filter::ast::unary_check_expr* e) override { + e->left->accept(this); + m_last_node_has_codes = m_last_node_is_evttype_field && e->op == "exists"; + m_last_node_codes = all_codes_set(); + m_last_node_is_evttype_field = false; + try_inversion(m_last_node_codes); + } + + void visit(const libsinsp::filter::ast::identifier_expr* e) override { + // this case only happens if a macro has not yet been substituted + // with an actual condition. Should not happen, but we handle it + // for consistency. + m_last_node_has_codes = false; + m_last_node_codes = all_codes_set(); + m_last_node_is_evttype_field = false; + try_inversion(m_last_node_codes); + } + + void visit(const libsinsp::filter::ast::value_expr* e) override { + m_last_node_has_codes = true; + m_last_node_codes = names_to_codes({e->value}); + m_last_node_is_evttype_field = false; + try_inversion(m_last_node_codes); + } + + void visit(const libsinsp::filter::ast::list_expr* e) override { + m_last_node_has_codes = true; + name_set_t names; + for(const auto& n : e->values) { + names.insert(n); + } + m_last_node_codes = names_to_codes(names); + m_last_node_is_evttype_field = false; + try_inversion(m_last_node_codes); + } + + void visit(const libsinsp::filter::ast::field_expr* e) override { + m_last_node_has_codes = false; + m_last_node_is_field_or_transformer = true; + m_last_node_is_evttype_field = e->field == "evt.type" && e->arg.empty(); + m_last_node_codes = all_codes_set(); + try_inversion(m_last_node_codes); + } + + void visit(const libsinsp::filter::ast::field_transformer_expr* e) override { + e->value->accept(this); + if(m_last_node_is_evttype_field) { + throw sinsp_exception( + "event code search does not support `evt.type` checks with transformers"); + } + m_last_node_is_field_or_transformer = true; + } }; -libsinsp::events::set -libsinsp::filter::ast::ppm_sc_codes(const libsinsp::filter::ast::expr* e) -{ - ppm_code_visitor< - libsinsp::events::set, - libsinsp::events::all_sc_set, - libsinsp::events::event_names_to_sc_set> v; +libsinsp::events::set libsinsp::filter::ast::ppm_sc_codes( + const libsinsp::filter::ast::expr* e) { + ppm_code_visitor, + libsinsp::events::all_sc_set, + libsinsp::events::event_names_to_sc_set> + v; // note(jasondellaluce): ppm_sc code mappings are available for linux only so far #ifdef __linux__ - e->accept(&v); + e->accept(&v); #else - v.m_last_node_codes = { }; + v.m_last_node_codes = {}; #endif - return v.m_last_node_codes; + return v.m_last_node_codes; } // todo(jasondellaluce): should we deal with PPME_ASYNCEVENT_E at this level? -libsinsp::events::set -libsinsp::filter::ast::ppm_event_codes(const libsinsp::filter::ast::expr* e) -{ - ppm_code_visitor< - libsinsp::events::set, - libsinsp::events::all_event_set, - libsinsp::events::names_to_event_set> v; - e->accept(&v); - return v.m_last_node_codes; +libsinsp::events::set libsinsp::filter::ast::ppm_event_codes( + const libsinsp::filter::ast::expr* e) { + ppm_code_visitor, + libsinsp::events::all_event_set, + libsinsp::events::names_to_event_set> + v; + e->accept(&v); + return v.m_last_node_codes; } diff --git a/userspace/libsinsp/filter/ppm_codes.h b/userspace/libsinsp/filter/ppm_codes.h index 0f13da5f51..b4fece9004 100644 --- a/userspace/libsinsp/filter/ppm_codes.h +++ b/userspace/libsinsp/filter/ppm_codes.h @@ -38,6 +38,6 @@ libsinsp::events::set ppm_event_codes(const expr* e); */ libsinsp::events::set ppm_sc_codes(const expr* e); -} -} -} +} // namespace ast +} // namespace filter +} // namespace libsinsp diff --git a/userspace/libsinsp/filter_cache.h b/userspace/libsinsp/filter_cache.h index 8984491915..160015e75f 100644 --- a/userspace/libsinsp/filter_cache.h +++ b/userspace/libsinsp/filter_cache.h @@ -28,270 +28,236 @@ limitations under the License. /** * @brief Represents a value extracted when evaluating a filter -*/ -struct extract_value_t -{ - uint8_t* ptr = nullptr; - uint32_t len = 0; + */ +struct extract_value_t { + uint8_t* ptr = nullptr; + uint32_t len = 0; }; /** * @brief Represents a cache value storage for value extraction in filters -*/ -class sinsp_filter_extract_cache -{ + */ +class sinsp_filter_extract_cache { public: - inline void reset() - { - m_evtnum = UINT64_MAX; - } - - inline bool is_valid(const sinsp_evt* evt) const - { - return evt->get_num() != 0 && m_evtnum != UINT64_MAX && evt->get_num() == m_evtnum; - } - - inline void update(const sinsp_evt* evt, bool res, const std::vector& values, bool deepcopy = false) - { - m_evtnum = evt->get_num(); - m_result = res; - if (!deepcopy) - { - m_values = values; - return; - } - - auto len = m_values.size(); - m_values.resize(len); - resize_if_smaller(m_storage, len); - for (size_t i = 0; i < len; i++) - { - auto v = values[i]; - resize_if_smaller(m_storage[i], v.len); - if (v.len > 0) - { - ASSERT(v.ptr != nullptr); - memcpy(m_storage[i].data(), v.ptr, v.len); - } - v.ptr = m_storage[i].data(); - m_values[i] = v; - } - } - - inline const std::vector& values() const - { - return m_values; - } - - inline bool result() const - { - return m_result; - } + inline void reset() { m_evtnum = UINT64_MAX; } + + inline bool is_valid(const sinsp_evt* evt) const { + return evt->get_num() != 0 && m_evtnum != UINT64_MAX && evt->get_num() == m_evtnum; + } + + inline void update(const sinsp_evt* evt, + bool res, + const std::vector& values, + bool deepcopy = false) { + m_evtnum = evt->get_num(); + m_result = res; + if(!deepcopy) { + m_values = values; + return; + } + + auto len = m_values.size(); + m_values.resize(len); + resize_if_smaller(m_storage, len); + for(size_t i = 0; i < len; i++) { + auto v = values[i]; + resize_if_smaller(m_storage[i], v.len); + if(v.len > 0) { + ASSERT(v.ptr != nullptr); + memcpy(m_storage[i].data(), v.ptr, v.len); + } + v.ptr = m_storage[i].data(); + m_values[i] = v; + } + } + + inline const std::vector& values() const { return m_values; } + + inline bool result() const { return m_result; } private: - template static inline void resize_if_smaller(T& v, size_t len) - { - if (v.size() < len) - { - v.resize(len); - } - } - - uint64_t m_evtnum = UINT64_MAX; - bool m_result = false; - std::vector m_values; - std::vector> m_storage; + template + static inline void resize_if_smaller(T& v, size_t len) { + if(v.size() < len) { + v.resize(len); + } + } + + uint64_t m_evtnum = UINT64_MAX; + bool m_result = false; + std::vector m_values; + std::vector> m_storage; }; /** * @brief Represents a cache value storage for comparisons in filters -*/ -class sinsp_filter_compare_cache -{ + */ +class sinsp_filter_compare_cache { public: - inline void reset() - { - m_evtnum = UINT64_MAX; - } - - inline bool is_valid(const sinsp_evt* evt) const - { - return evt->get_num() != 0 && m_evtnum != UINT64_MAX && evt->get_num() == m_evtnum; - } - - inline void update(const sinsp_evt* evt, bool res) - { - m_evtnum = evt->get_num(); - m_result = res; - } - - inline bool result() const - { - return m_result; - } + inline void reset() { m_evtnum = UINT64_MAX; } + + inline bool is_valid(const sinsp_evt* evt) const { + return evt->get_num() != 0 && m_evtnum != UINT64_MAX && evt->get_num() == m_evtnum; + } + + inline void update(const sinsp_evt* evt, bool res) { + m_evtnum = evt->get_num(); + m_result = res; + } + + inline bool result() const { return m_result; } private: - uint64_t m_evtnum = UINT64_MAX; - bool m_result = false; + uint64_t m_evtnum = UINT64_MAX; + bool m_result = false; }; /** * @brief Represents a set of metrics and counters related to the usage * of cache optimizations in filters -*/ -struct sinsp_filter_cache_metrics -{ - inline void reset() - { - m_num_extract = 0; - m_num_extract_cache = 0; - m_num_compare = 0; - m_num_compare_cache = 0; - } - - // The number of times extract() was called - uint64_t m_num_extract = 0; - - // The number of times extract() could use a cached value - uint64_t m_num_extract_cache = 0; - - // The number of times compare() was called - uint64_t m_num_compare = 0; - - // The number of times compare() could use a cached value - uint64_t m_num_compare_cache = 0; + */ +struct sinsp_filter_cache_metrics { + inline void reset() { + m_num_extract = 0; + m_num_extract_cache = 0; + m_num_compare = 0; + m_num_compare_cache = 0; + } + + // The number of times extract() was called + uint64_t m_num_extract = 0; + + // The number of times extract() could use a cached value + uint64_t m_num_extract_cache = 0; + + // The number of times compare() was called + uint64_t m_num_compare = 0; + + // The number of times compare() could use a cached value + uint64_t m_num_compare_cache = 0; }; /** * @brief Interface for factories of filter cache objects -*/ -class sinsp_filter_cache_factory -{ + */ +class sinsp_filter_cache_factory { public: - using ast_expr_t = libsinsp::filter::ast::expr; - - /** - * @brief Input struct representing information about a filter AST node - */ - struct node_info_t - { - // For nodes representing a field extraction, the information about the field. - // For nodes with a comparison, the information about the left-hand side field. - // Left to null in all other cases. - const filtercheck_field_info* m_field = nullptr; - - // For nodes with a comparison, the information about the right-hand side field. - // Left to null in all other cases. - const filtercheck_field_info* m_right_field = nullptr; - - // For nodes with a comparison, the comparison operator. - // Left to CO_NONE in all other cases. - cmpop m_compare_operator = cmpop::CO_NONE; - }; - - virtual ~sinsp_filter_cache_factory() = default; - - /** - * @brief Resets the state of the given factory instance - */ - virtual void reset() - { - // do nothing - } - - /** - * @brief Given the provided AST node of a filter expression, returns a pointer - * to an extraction cache usable in the compiled filter derived from that node. - * Can return `nullptr` in case no cache is available for the node. - */ - virtual std::shared_ptr new_extract_cache(const ast_expr_t* e, node_info_t& info) - { - return nullptr; - } - - /** - * @brief Given the provided AST node of a filter expression, returns a pointer - * to an comparison cache usable in the compiled filter derived from that node. - * Can return `nullptr` in case no cache is available for the node. - */ - virtual std::shared_ptr new_compare_cache(const ast_expr_t* e, node_info_t& info) - { - return nullptr; - } - - /** - * @brief Given the provided AST node of a filter expression, returns a pointer - * to an cache metrics storage usable in the compiled filter derived from that node. - * Can return `nullptr` in case no metrics are available for the node. - */ - virtual std::shared_ptr new_metrics(const ast_expr_t* e, node_info_t& info) - { - return nullptr; - } + using ast_expr_t = libsinsp::filter::ast::expr; + + /** + * @brief Input struct representing information about a filter AST node + */ + struct node_info_t { + // For nodes representing a field extraction, the information about the field. + // For nodes with a comparison, the information about the left-hand side field. + // Left to null in all other cases. + const filtercheck_field_info* m_field = nullptr; + + // For nodes with a comparison, the information about the right-hand side field. + // Left to null in all other cases. + const filtercheck_field_info* m_right_field = nullptr; + + // For nodes with a comparison, the comparison operator. + // Left to CO_NONE in all other cases. + cmpop m_compare_operator = cmpop::CO_NONE; + }; + + virtual ~sinsp_filter_cache_factory() = default; + + /** + * @brief Resets the state of the given factory instance + */ + virtual void reset() { + // do nothing + } + + /** + * @brief Given the provided AST node of a filter expression, returns a pointer + * to an extraction cache usable in the compiled filter derived from that node. + * Can return `nullptr` in case no cache is available for the node. + */ + virtual std::shared_ptr new_extract_cache(const ast_expr_t* e, + node_info_t& info) { + return nullptr; + } + + /** + * @brief Given the provided AST node of a filter expression, returns a pointer + * to an comparison cache usable in the compiled filter derived from that node. + * Can return `nullptr` in case no cache is available for the node. + */ + virtual std::shared_ptr new_compare_cache(const ast_expr_t* e, + node_info_t& info) { + return nullptr; + } + + /** + * @brief Given the provided AST node of a filter expression, returns a pointer + * to an cache metrics storage usable in the compiled filter derived from that node. + * Can return `nullptr` in case no metrics are available for the node. + */ + virtual std::shared_ptr new_metrics(const ast_expr_t* e, + node_info_t& info) { + return nullptr; + } }; /** * @brief An implementation of sinsp_filter_cache_factory that creates shared * cache objects indexed by the string representation of AST expressions * (obtained through libsinsp::filter::ast::as_string). -*/ -class exprstr_sinsp_filter_cache_factory: public sinsp_filter_cache_factory -{ + */ +class exprstr_sinsp_filter_cache_factory : public sinsp_filter_cache_factory { public: - virtual ~exprstr_sinsp_filter_cache_factory() = default; - - void reset() override - { - m_extract_caches.clear(); - m_compare_caches.clear(); - } - - std::shared_ptr new_extract_cache(const ast_expr_t* e, node_info_t& info) override - { - // avoid caching fields for which it would be unsafe - if (info.m_field && info.m_field->m_type == PT_IPNET) - { - return nullptr; - } - auto key = libsinsp::filter::ast::as_string(e); - return get_or_insert_ptr(key, m_extract_caches); - } - - std::shared_ptr new_compare_cache(const ast_expr_t* e, node_info_t& info) override - { - // avoid caching fields for which it would be unsafe - if (info.m_field && info.m_field->m_type == PT_IPNET) - { - return nullptr; - } - auto key = libsinsp::filter::ast::as_string(e); - return get_or_insert_ptr(key, m_compare_caches); - } - - inline const std::unordered_map>& extract_cache() const - { - return m_extract_caches; - } - - inline const std::unordered_map>& compare_cache() const - { - return m_compare_caches; - } + virtual ~exprstr_sinsp_filter_cache_factory() = default; + + void reset() override { + m_extract_caches.clear(); + m_compare_caches.clear(); + } + + std::shared_ptr new_extract_cache(const ast_expr_t* e, + node_info_t& info) override { + // avoid caching fields for which it would be unsafe + if(info.m_field && info.m_field->m_type == PT_IPNET) { + return nullptr; + } + auto key = libsinsp::filter::ast::as_string(e); + return get_or_insert_ptr(key, m_extract_caches); + } + + std::shared_ptr new_compare_cache(const ast_expr_t* e, + node_info_t& info) override { + // avoid caching fields for which it would be unsafe + if(info.m_field && info.m_field->m_type == PT_IPNET) { + return nullptr; + } + auto key = libsinsp::filter::ast::as_string(e); + return get_or_insert_ptr(key, m_compare_caches); + } + + inline const std::unordered_map>& + extract_cache() const { + return m_extract_caches; + } + + inline const std::unordered_map>& + compare_cache() const { + return m_compare_caches; + } private: - template - static inline std::shared_ptr get_or_insert_ptr( - const std::string& key, - std::unordered_map>& map) - { - auto it = map.find(key); - if (it == map.end()) - { - return map.emplace(key, std::make_shared()).first->second; - } - return it->second; - } - - std::unordered_map> m_extract_caches; - std::unordered_map> m_compare_caches; + template + static inline std::shared_ptr get_or_insert_ptr( + const std::string& key, + std::unordered_map>& map) { + auto it = map.find(key); + if(it == map.end()) { + return map.emplace(key, std::make_shared()).first->second; + } + return it->second; + } + + std::unordered_map> m_extract_caches; + std::unordered_map> m_compare_caches; }; diff --git a/userspace/libsinsp/filter_check_list.cpp b/userspace/libsinsp/filter_check_list.cpp index 37ae68b4ca..85616a93f1 100644 --- a/userspace/libsinsp/filter_check_list.cpp +++ b/userspace/libsinsp/filter_check_list.cpp @@ -31,18 +31,15 @@ using namespace std; // sinsp_filter_check_list implementation /////////////////////////////////////////////////////////////////////////////// -void filter_check_list::add_filter_check(std::unique_ptr filter_check) -{ +void filter_check_list::add_filter_check(std::unique_ptr filter_check) { // If a filtercheck already exists with this name and // shortdesc, don't add it--this can occur when plugins are // loaded and set up sinsp_filter_checks to handle plugin // events. - for(const auto& chk : m_check_list) - { + for(const auto& chk : m_check_list) { if(chk->get_fields()->m_name == filter_check->get_fields()->m_name && - chk->get_fields()->m_shortdesc == filter_check->get_fields()->m_shortdesc) - { + chk->get_fields()->m_shortdesc == filter_check->get_fields()->m_shortdesc) { return; } } @@ -50,32 +47,25 @@ void filter_check_list::add_filter_check(std::unique_ptr fil m_check_list.push_back(std::move(filter_check)); } -void filter_check_list::get_all_fields(std::vector& list) const -{ - for(const auto& chk : m_check_list) - { +void filter_check_list::get_all_fields(std::vector& list) const { + for(const auto& chk : m_check_list) { list.push_back(chk->get_fields()); } } /* Craft a new filter check from the field name */ std::unique_ptr filter_check_list::new_filter_check_from_fldname( - std::string_view name, - sinsp* inspector, - bool do_exact_check) const -{ - for(const auto& chk : m_check_list) - { + std::string_view name, + sinsp* inspector, + bool do_exact_check) const { + for(const auto& chk : m_check_list) { chk->m_inspector = inspector; int32_t fldnamelen = chk->parse_field_name(name, false, true); - if(fldnamelen != -1) - { - if(do_exact_check) - { - if((int32_t)name.size() != fldnamelen) - { + if(fldnamelen != -1) { + if(do_exact_check) { + if((int32_t)name.size() != fldnamelen) { break; } } @@ -94,8 +84,7 @@ std::unique_ptr filter_check_list::new_filter_check_from_fld return nullptr; } -sinsp_filter_check_list::sinsp_filter_check_list() -{ +sinsp_filter_check_list::sinsp_filter_check_list() { ////////////////////////////////////////////////////////////////////////////// // ADD NEW FILTER CHECK CLASSES HERE ////////////////////////////////////////////////////////////////////////////// diff --git a/userspace/libsinsp/filter_check_list.h b/userspace/libsinsp/filter_check_list.h index 0ac97558aa..ee52e5fc50 100644 --- a/userspace/libsinsp/filter_check_list.h +++ b/userspace/libsinsp/filter_check_list.h @@ -30,15 +30,16 @@ class sinsp; // Global class that stores the list of filtercheck plugins and offers // functions to work with it. // -class filter_check_list -{ +class filter_check_list { public: filter_check_list() = default; virtual ~filter_check_list() = default; void add_filter_check(std::unique_ptr filter_check); void get_all_fields(std::vector&) const; - std::unique_ptr new_filter_check_from_fldname(std::string_view name, sinsp*, bool do_exact_check) const; + std::unique_ptr new_filter_check_from_fldname(std::string_view name, + sinsp*, + bool do_exact_check) const; protected: std::vector> m_check_list; @@ -46,8 +47,7 @@ class filter_check_list // // This bakes in the "default" set of filterchecks that work with syscalls -class sinsp_filter_check_list : public filter_check_list -{ +class sinsp_filter_check_list : public filter_check_list { public: sinsp_filter_check_list(); virtual ~sinsp_filter_check_list() = default; diff --git a/userspace/libsinsp/filter_compare.cpp b/userspace/libsinsp/filter_compare.cpp index 020307b433..7333e2d2aa 100644 --- a/userspace/libsinsp/filter_compare.cpp +++ b/userspace/libsinsp/filter_compare.cpp @@ -31,112 +31,132 @@ limitations under the License. #include #endif -cmpop str_to_cmpop(std::string_view str) -{ - if(str == "=" || str == "==") - { +cmpop str_to_cmpop(std::string_view str) { + if(str == "=" || str == "==") { return CO_EQ; - } - else if(str == "!=") - { + } else if(str == "!=") { return CO_NE; - } - else if(str == "<=") - { + } else if(str == "<=") { return CO_LE; - } - else if(str == "<") - { + } else if(str == "<") { return CO_LT; - } - else if(str == ">=") - { + } else if(str == ">=") { return CO_GE; - } - else if(str == ">") - { + } else if(str == ">") { return CO_GT; - } - else if(str == "contains") - { + } else if(str == "contains") { return CO_CONTAINS; - } - else if(str == "icontains") - { + } else if(str == "icontains") { return CO_ICONTAINS; - } - else if(str == "bcontains") - { + } else if(str == "bcontains") { return CO_BCONTAINS; - } - else if(str == "startswith") - { + } else if(str == "startswith") { return CO_STARTSWITH; - } - else if(str == "bstartswith") - { + } else if(str == "bstartswith") { return CO_BSTARTSWITH; - } - else if(str == "endswith") - { + } else if(str == "endswith") { return CO_ENDSWITH; - } - else if(str == "in") - { + } else if(str == "in") { return CO_IN; - } - else if(str == "intersects") - { + } else if(str == "intersects") { return CO_INTERSECTS; - } - else if(str == "pmatch") - { + } else if(str == "pmatch") { return CO_PMATCH; - } - else if(str == "exists") - { + } else if(str == "exists") { return CO_EXISTS; - } - else if(str == "glob") - { + } else if(str == "glob") { return CO_GLOB; - } - else if(str == "iglob") - { + } else if(str == "iglob") { return CO_IGLOB; - } - else if(str == "regex") - { + } else if(str == "regex") { return CO_REGEX; } throw sinsp_exception("unrecognized filter comparison operator '" + std::string(str) + "'"); } -bool cmpop_to_str(cmpop op, std::string& out) -{ - switch (op) - { - case CO_NONE: { out = "none"; return true; } - case CO_EQ: { out = "="; return true; } - case CO_NE: { out = "!="; return true; } - case CO_LT: { out = "<"; return true; } - case CO_LE: { out = "<="; return true; } - case CO_GT: { out = ">"; return true; } - case CO_GE: { out = ">="; return true; } - case CO_CONTAINS: { out = "contains"; return true; } - case CO_IN: { out = "in"; return true; } - case CO_EXISTS: { out = "exists"; return true; } - case CO_ICONTAINS: { out = "icontains"; return true; } - case CO_STARTSWITH: { out = "startswith"; return true; } - case CO_GLOB: { out = "glob"; return true; } - case CO_IGLOB: { out = "iglob"; return true; } - case CO_PMATCH: { out = "pmatch"; return true; } - case CO_ENDSWITH: { out = "endswith"; return true; } - case CO_INTERSECTS: { out = "intersects"; return true; } - case CO_BCONTAINS: { out = "bcontains"; return true; } - case CO_BSTARTSWITH: { out = "bstartswith"; return true; } - case CO_REGEX: { out = "regex"; return true; } +bool cmpop_to_str(cmpop op, std::string& out) { + switch(op) { + case CO_NONE: { + out = "none"; + return true; + } + case CO_EQ: { + out = "="; + return true; + } + case CO_NE: { + out = "!="; + return true; + } + case CO_LT: { + out = "<"; + return true; + } + case CO_LE: { + out = "<="; + return true; + } + case CO_GT: { + out = ">"; + return true; + } + case CO_GE: { + out = ">="; + return true; + } + case CO_CONTAINS: { + out = "contains"; + return true; + } + case CO_IN: { + out = "in"; + return true; + } + case CO_EXISTS: { + out = "exists"; + return true; + } + case CO_ICONTAINS: { + out = "icontains"; + return true; + } + case CO_STARTSWITH: { + out = "startswith"; + return true; + } + case CO_GLOB: { + out = "glob"; + return true; + } + case CO_IGLOB: { + out = "iglob"; + return true; + } + case CO_PMATCH: { + out = "pmatch"; + return true; + } + case CO_ENDSWITH: { + out = "endswith"; + return true; + } + case CO_INTERSECTS: { + out = "intersects"; + return true; + } + case CO_BCONTAINS: { + out = "bcontains"; + return true; + } + case CO_BSTARTSWITH: { + out = "bstartswith"; + return true; + } + case CO_REGEX: { + out = "regex"; + return true; + } default: ASSERT(false); out = "unknown"; @@ -144,40 +164,56 @@ bool cmpop_to_str(cmpop op, std::string& out) } }; -std::string std::to_string(cmpop c) -{ - switch (c) - { - case CO_NONE: return "NONE"; - case CO_EQ: return "EQ"; - case CO_NE: return "NE"; - case CO_LT: return "LT"; - case CO_LE: return "LE"; - case CO_GT: return "GT"; - case CO_GE: return "GE"; - case CO_CONTAINS: return "CONTAINS"; - case CO_IN: return "IN"; - case CO_EXISTS: return "EXISTS"; - case CO_ICONTAINS: return "ICONTAINS"; - case CO_STARTSWITH: return "STARTSWITH"; - case CO_GLOB: return "GLOB"; - case CO_IGLOB: return "IGLOB"; - case CO_PMATCH: return "PMATCH"; - case CO_ENDSWITH: return "ENDSWITH"; - case CO_INTERSECTS: return "INTERSECTS"; - case CO_BCONTAINS: return "BCONTAINS"; - case CO_BSTARTSWITH: return "BSTARTSWITH"; - case CO_REGEX: return "REGEX"; +std::string std::to_string(cmpop c) { + switch(c) { + case CO_NONE: + return "NONE"; + case CO_EQ: + return "EQ"; + case CO_NE: + return "NE"; + case CO_LT: + return "LT"; + case CO_LE: + return "LE"; + case CO_GT: + return "GT"; + case CO_GE: + return "GE"; + case CO_CONTAINS: + return "CONTAINS"; + case CO_IN: + return "IN"; + case CO_EXISTS: + return "EXISTS"; + case CO_ICONTAINS: + return "ICONTAINS"; + case CO_STARTSWITH: + return "STARTSWITH"; + case CO_GLOB: + return "GLOB"; + case CO_IGLOB: + return "IGLOB"; + case CO_PMATCH: + return "PMATCH"; + case CO_ENDSWITH: + return "ENDSWITH"; + case CO_INTERSECTS: + return "INTERSECTS"; + case CO_BCONTAINS: + return "BCONTAINS"; + case CO_BSTARTSWITH: + return "BSTARTSWITH"; + case CO_REGEX: + return "REGEX"; default: ASSERT(false); return ""; } }; -static inline bool flt_is_comparable_numeric(cmpop op, std::string& err) -{ - switch(op) - { +static inline bool flt_is_comparable_numeric(cmpop op, std::string& err) { + switch(op) { case CO_EQ: case CO_NE: case CO_LT: @@ -196,10 +232,8 @@ static inline bool flt_is_comparable_numeric(cmpop op, std::string& err) } } -static inline bool flt_is_comparable_bool(cmpop op, std::string& err) -{ - switch(op) - { +static inline bool flt_is_comparable_bool(cmpop op, std::string& err) { + switch(op) { case CO_EQ: case CO_NE: case CO_IN: @@ -214,10 +248,8 @@ static inline bool flt_is_comparable_bool(cmpop op, std::string& err) } } -static inline bool flt_is_comparable_string(cmpop op, std::string& err) -{ - switch(op) - { +static inline bool flt_is_comparable_string(cmpop op, std::string& err) { + switch(op) { case CO_EQ: case CO_NE: case CO_LT: @@ -227,7 +259,7 @@ static inline bool flt_is_comparable_string(cmpop op, std::string& err) case CO_CONTAINS: case CO_IN: case CO_EXISTS: - case CO_ICONTAINS: + case CO_ICONTAINS: case CO_STARTSWITH: case CO_GLOB: case CO_PMATCH: @@ -244,10 +276,8 @@ static inline bool flt_is_comparable_string(cmpop op, std::string& err) } } -static inline bool flt_is_comparable_buffer(cmpop op, std::string& err) -{ - switch(op) - { +static inline bool flt_is_comparable_buffer(cmpop op, std::string& err) { + switch(op) { case CO_EQ: case CO_NE: case CO_CONTAINS: @@ -267,10 +297,8 @@ static inline bool flt_is_comparable_buffer(cmpop op, std::string& err) } } -static inline bool flt_is_comparable_ip_or_net(cmpop op, std::string& err) -{ - switch(op) - { +static inline bool flt_is_comparable_ip_or_net(cmpop op, std::string& err) { + switch(op) { case CO_EQ: case CO_NE: case CO_IN: @@ -285,10 +313,8 @@ static inline bool flt_is_comparable_ip_or_net(cmpop op, std::string& err) } } -static inline bool flt_is_comparable_any_list(cmpop op, std::string& err) -{ - switch(op) - { +static inline bool flt_is_comparable_any_list(cmpop op, std::string& err) { + switch(op) { case CO_IN: case CO_EXISTS: case CO_INTERSECTS: @@ -301,17 +327,13 @@ static inline bool flt_is_comparable_any_list(cmpop op, std::string& err) } } -bool flt_is_comparable(cmpop op, ppm_param_type t, bool is_list, std::string& err) -{ - if(op == CO_EXISTS) - { +bool flt_is_comparable(cmpop op, ppm_param_type t, bool is_list, std::string& err) { + if(op == CO_EXISTS) { return true; } - if (is_list) - { - switch (t) - { + if(is_list) { + switch(t) { case PT_CHARBUF: case PT_UINT64: case PT_RELTIME: @@ -321,13 +343,13 @@ bool flt_is_comparable(cmpop op, ppm_param_type t, bool is_list, std::string& er case PT_IPNET: return flt_is_comparable_any_list(op, err); default: - err = "list filters are not supported for type '" + std::string(param_type_to_string(t)) + "'"; + err = "list filters are not supported for type '" + + std::string(param_type_to_string(t)) + "'"; return false; } } - switch(t) - { + switch(t) { case PT_INT8: case PT_INT16: case PT_INT32: @@ -371,27 +393,24 @@ bool flt_is_comparable(cmpop op, ppm_param_type t, bool is_list, std::string& er default: std::string opname; cmpop_to_str(op, opname); - err = "'" + opname + "' operator not supported for type '" + std::string(param_type_to_string(t)) + "'"; + err = "'" + opname + "' operator not supported for type '" + + std::string(param_type_to_string(t)) + "'"; return false; } } // little helper for functions below -template -static inline void _throw_if_not_comparable(cmpop op, Check c) -{ +template +static inline void _throw_if_not_comparable(cmpop op, Check c) { std::string err; - if (!c(op, err)) - { + if(!c(op, err)) { throw sinsp_exception(err); } } template -static inline bool flt_compare_numeric(cmpop op, T operand1, T operand2) -{ - switch(op) - { +static inline bool flt_compare_numeric(cmpop op, T operand1, T operand2) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -412,10 +431,8 @@ static inline bool flt_compare_numeric(cmpop op, T operand1, T operand2) } } -static inline bool flt_compare_string(cmpop op, char* operand1, char* operand2) -{ - switch(op) - { +static inline bool flt_compare_string(cmpop op, char* operand1, char* operand2) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -424,13 +441,17 @@ static inline bool flt_compare_string(cmpop op, char* operand1, char* operand2) return (strcmp(operand1, operand2) != 0); case CO_CONTAINS: return (strstr(operand1, operand2) != NULL); - case CO_ICONTAINS: + case CO_ICONTAINS: #ifdef _WIN32 { std::string s1(operand1); std::string s2(operand2); - std::transform(s1.begin(), s1.end(), s1.begin(), [](unsigned char c){ return std::tolower(c); }); - std::transform(s2.begin(), s2.end(), s2.begin(), [](unsigned char c){ return std::tolower(c); }); + std::transform(s1.begin(), s1.end(), s1.begin(), [](unsigned char c) { + return std::tolower(c); + }); + std::transform(s2.begin(), s2.end(), s2.begin(), [](unsigned char c) { + return std::tolower(c); + }); return (strstr(s1.c_str(), s2.c_str()) != NULL); } #else @@ -462,10 +483,12 @@ static inline bool flt_compare_string(cmpop op, char* operand1, char* operand2) } } -static inline bool flt_compare_buffer(cmpop op, char* operand1, char* operand2, uint32_t op1_len, uint32_t op2_len) -{ - switch(op) - { +static inline bool flt_compare_buffer(cmpop op, + char* operand1, + char* operand2, + uint32_t op1_len, + uint32_t op2_len) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -488,10 +511,8 @@ static inline bool flt_compare_buffer(cmpop op, char* operand1, char* operand2, } } -static inline bool flt_compare_bool(cmpop op, uint64_t operand1, uint64_t operand2) -{ - switch(op) - { +static inline bool flt_compare_bool(cmpop op, uint64_t operand1, uint64_t operand2) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -504,10 +525,8 @@ static inline bool flt_compare_bool(cmpop op, uint64_t operand1, uint64_t operan } } -static inline bool flt_compare_ipv4addr(cmpop op, uint64_t operand1, uint64_t operand2) -{ - switch(op) - { +static inline bool flt_compare_ipv4addr(cmpop op, uint64_t operand1, uint64_t operand2) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -520,10 +539,8 @@ static inline bool flt_compare_ipv4addr(cmpop op, uint64_t operand1, uint64_t op } } -static inline bool flt_compare_ipv6addr(cmpop op, ipv6addr* operand1, ipv6addr* operand2) -{ - switch(op) - { +static inline bool flt_compare_ipv6addr(cmpop op, ipv6addr* operand1, ipv6addr* operand2) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -536,10 +553,8 @@ static inline bool flt_compare_ipv6addr(cmpop op, ipv6addr* operand1, ipv6addr* } } -bool flt_compare_ipv4net(cmpop op, uint64_t operand1, const ipv4net* operand2) -{ - switch(op) - { +bool flt_compare_ipv4net(cmpop op, uint64_t operand1, const ipv4net* operand2) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -552,10 +567,8 @@ bool flt_compare_ipv4net(cmpop op, uint64_t operand1, const ipv4net* operand2) } } -bool flt_compare_ipv6net(cmpop op, const ipv6addr *operand1, const ipv6net *operand2) -{ - switch(op) - { +bool flt_compare_ipv6net(cmpop op, const ipv6addr* operand1, const ipv6net* operand2) { + switch(op) { case CO_EQ: case CO_IN: case CO_INTERSECTS: @@ -571,126 +584,131 @@ bool flt_compare_ipv6net(cmpop op, const ipv6addr *operand1, const ipv6net *oper // flt_cast takes a pointer to memory, dereferences it as fromT type and casts it // to a compatible toT type template -static inline toT flt_cast(const void* ptr) -{ +static inline toT flt_cast(const void* ptr) { fromT val; memcpy(&val, ptr, sizeof(fromT)); return static_cast(val); } -bool flt_compare(cmpop op, ppm_param_type type, const void* operand1, const void* operand2, uint32_t op1_len, uint32_t op2_len) -{ +bool flt_compare(cmpop op, + ppm_param_type type, + const void* operand1, + const void* operand2, + uint32_t op1_len, + uint32_t op2_len) { // // sinsp_filter_check_*::compare // already discard NULL values // - if(op == CO_EXISTS) - { + if(op == CO_EXISTS) { return true; } - switch(type) - { + switch(type) { case PT_INT8: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_INT16: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_INT32: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_INT64: case PT_FD: case PT_PID: case PT_ERRNO: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_FLAGS8: case PT_ENUMFLAGS8: case PT_UINT8: case PT_SIGTYPE: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_FLAGS16: case PT_UINT16: case PT_ENUMFLAGS16: case PT_PORT: case PT_SYSCALLID: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_UINT32: case PT_FLAGS32: case PT_ENUMFLAGS32: case PT_MODE: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_BOOL: - return flt_compare_bool(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_bool(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_IPV4ADDR: - if (op2_len != sizeof(struct in_addr)) - { + if(op2_len != sizeof(struct in_addr)) { return op == CO_NE; } - return flt_compare_ipv4addr(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_ipv4addr(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_IPV4NET: - if (op2_len != sizeof(ipv4net)) - { + if(op2_len != sizeof(ipv4net)) { return op == CO_NE; } - return flt_compare_ipv4net(op, (uint64_t)*(uint32_t*)operand1, (ipv4net*)operand2); + return flt_compare_ipv4net(op, (uint64_t) * (uint32_t*)operand1, (ipv4net*)operand2); case PT_IPV6ADDR: - if (op2_len != sizeof(ipv6addr)) - { + if(op2_len != sizeof(ipv6addr)) { return op == CO_NE; } - return flt_compare_ipv6addr(op, (ipv6addr *)operand1, (ipv6addr *)operand2); + return flt_compare_ipv6addr(op, (ipv6addr*)operand1, (ipv6addr*)operand2); case PT_IPV6NET: - if (op2_len != sizeof(ipv6net)) - { + if(op2_len != sizeof(ipv6net)) { return op == CO_NE; } - return flt_compare_ipv6net(op, (ipv6addr *)operand1, (ipv6net*)operand2); + return flt_compare_ipv6net(op, (ipv6addr*)operand1, (ipv6net*)operand2); case PT_IPADDR: - if(op1_len == sizeof(struct in_addr)) - { - if (op2_len != sizeof(struct in_addr)) - { + if(op1_len == sizeof(struct in_addr)) { + if(op2_len != sizeof(struct in_addr)) { return op == CO_NE; } return flt_compare(op, PT_IPV4ADDR, operand1, operand2, op1_len, op2_len); - } - else if(op1_len == sizeof(struct in6_addr)) - { - if (op2_len != sizeof(ipv6addr)) - { + } else if(op1_len == sizeof(struct in6_addr)) { + if(op2_len != sizeof(ipv6addr)) { return op == CO_NE; } return flt_compare(op, PT_IPV6ADDR, operand1, operand2, op1_len, op2_len); - } - else - { - throw sinsp_exception("rawval_to_string called with IP address of incorrect size " + std::to_string(op1_len)); + } else { + throw sinsp_exception("rawval_to_string called with IP address of incorrect size " + + std::to_string(op1_len)); } case PT_IPNET: - if(op1_len == sizeof(struct in_addr)) - { - if (op2_len != sizeof(ipv4net)) - { + if(op1_len == sizeof(struct in_addr)) { + if(op2_len != sizeof(ipv4net)) { return op == CO_NE; } return flt_compare(op, PT_IPV4NET, operand1, operand2, op1_len, op2_len); - } - else if(op1_len == sizeof(struct in6_addr)) - { - if (op2_len != sizeof(ipv6net)) - { + } else if(op1_len == sizeof(struct in6_addr)) { + if(op2_len != sizeof(ipv6net)) { return op == CO_NE; } return flt_compare(op, PT_IPV6NET, operand1, operand2, op1_len, op2_len); - } - else - { - throw sinsp_exception("rawval_to_string called with IP network of incorrect size " + std::to_string(op1_len)); + } else { + throw sinsp_exception("rawval_to_string called with IP network of incorrect size " + + std::to_string(op1_len)); } case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); case PT_CHARBUF: case PT_FSPATH: case PT_FSRELPATH: @@ -698,7 +716,9 @@ bool flt_compare(cmpop op, ppm_param_type type, const void* operand1, const void case PT_BYTEBUF: return flt_compare_buffer(op, (char*)operand1, (char*)operand2, op1_len, op2_len); case PT_DOUBLE: - return flt_compare_numeric(op, flt_cast(operand1), flt_cast(operand2)); + return flt_compare_numeric(op, + flt_cast(operand1), + flt_cast(operand2)); default: ASSERT(false); return false; @@ -706,14 +726,13 @@ bool flt_compare(cmpop op, ppm_param_type type, const void* operand1, const void } bool flt_compare_avg(cmpop op, - ppm_param_type type, - const void* operand1, - const void* operand2, - uint32_t op1_len, - uint32_t op2_len, - uint32_t cnt1, - uint32_t cnt2) -{ + ppm_param_type type, + const void* operand1, + const void* operand2, + uint32_t op1_len, + uint32_t op2_len, + uint32_t cnt1, + uint32_t cnt2) { int64_t i641, i642; uint64_t u641, u642; double d1, d2; @@ -722,33 +741,30 @@ bool flt_compare_avg(cmpop op, // If count = 0 we assume that the value is zero too (there are assertions to // check that, and we just divide by 1 // - if(cnt1 == 0) - { + if(cnt1 == 0) { cnt1 = 1; } - if(cnt2 == 0) - { + if(cnt2 == 0) { cnt2 = 1; } - switch(type) - { + switch(type) { case PT_INT8: - i641 = ((int64_t)*(int8_t*)operand1) / cnt1; - i642 = ((int64_t)*(int8_t*)operand2) / cnt2; + i641 = ((int64_t) * (int8_t*)operand1) / cnt1; + i642 = ((int64_t) * (int8_t*)operand2) / cnt2; ASSERT(cnt1 != 0 || i641 == 0); ASSERT(cnt2 != 0 || i642 == 0); return flt_compare_numeric(op, i641, i642); case PT_INT16: - i641 = ((int64_t)*(int16_t*)operand1) / cnt1; - i642 = ((int64_t)*(int16_t*)operand2) / cnt2; + i641 = ((int64_t) * (int16_t*)operand1) / cnt1; + i642 = ((int64_t) * (int16_t*)operand2) / cnt2; ASSERT(cnt1 != 0 || i641 == 0); ASSERT(cnt2 != 0 || i642 == 0); return flt_compare_numeric(op, i641, i642); case PT_INT32: - i641 = ((int64_t)*(int32_t*)operand1) / cnt1; - i642 = ((int64_t)*(int32_t*)operand2) / cnt2; + i641 = ((int64_t) * (int32_t*)operand1) / cnt1; + i642 = ((int64_t) * (int32_t*)operand2) / cnt2; ASSERT(cnt1 != 0 || i641 == 0); ASSERT(cnt2 != 0 || i642 == 0); return flt_compare_numeric(op, i641, i642); @@ -756,8 +772,8 @@ bool flt_compare_avg(cmpop op, case PT_FD: case PT_PID: case PT_ERRNO: - i641 = ((int64_t)*(int64_t*)operand1) / cnt1; - i642 = ((int64_t)*(int64_t*)operand2) / cnt2; + i641 = ((int64_t) * (int64_t*)operand1) / cnt1; + i642 = ((int64_t) * (int64_t*)operand2) / cnt2; ASSERT(cnt1 != 0 || i641 == 0); ASSERT(cnt2 != 0 || i642 == 0); return flt_compare_numeric(op, i641, i642); @@ -765,8 +781,8 @@ bool flt_compare_avg(cmpop op, case PT_UINT8: case PT_ENUMFLAGS8: case PT_SIGTYPE: - u641 = ((uint64_t)*(uint8_t*)operand1) / cnt1; - u642 = ((uint64_t)*(uint8_t*)operand2) / cnt2; + u641 = ((uint64_t) * (uint8_t*)operand1) / cnt1; + u642 = ((uint64_t) * (uint8_t*)operand2) / cnt2; ASSERT(cnt1 != 0 || u641 == 0); ASSERT(cnt2 != 0 || u642 == 0); return flt_compare_numeric(op, u641, u642); @@ -775,8 +791,8 @@ bool flt_compare_avg(cmpop op, case PT_ENUMFLAGS16: case PT_PORT: case PT_SYSCALLID: - u641 = ((uint64_t)*(uint16_t*)operand1) / cnt1; - u642 = ((uint64_t)*(uint16_t*)operand2) / cnt2; + u641 = ((uint64_t) * (uint16_t*)operand1) / cnt1; + u642 = ((uint64_t) * (uint16_t*)operand2) / cnt2; ASSERT(cnt1 != 0 || u641 == 0); ASSERT(cnt2 != 0 || u642 == 0); return flt_compare_numeric(op, u641, u642); @@ -788,8 +804,8 @@ bool flt_compare_avg(cmpop op, case PT_IPV4ADDR: case PT_IPV6ADDR: // What does an average mean for ip addresses anyway? - u641 = ((uint64_t)*(uint32_t*)operand1) / cnt1; - u642 = ((uint64_t)*(uint32_t*)operand2) / cnt2; + u641 = ((uint64_t) * (uint32_t*)operand1) / cnt1; + u642 = ((uint64_t) * (uint32_t*)operand2) / cnt2; ASSERT(cnt1 != 0 || u641 == 0); ASSERT(cnt2 != 0 || u642 == 0); return flt_compare_numeric(op, u641, u642); diff --git a/userspace/libsinsp/filter_compare.h b/userspace/libsinsp/filter_compare.h index 94233274f8..ef05a52860 100644 --- a/userspace/libsinsp/filter_compare.h +++ b/userspace/libsinsp/filter_compare.h @@ -28,8 +28,7 @@ limitations under the License. /* * Operators to compare events */ -enum cmpop: uint8_t -{ +enum cmpop : uint8_t { CO_NONE = 0, CO_EQ = 1, CO_NE = 2, @@ -55,13 +54,24 @@ enum cmpop: uint8_t cmpop str_to_cmpop(std::string_view str); bool cmpop_to_str(cmpop op, std::string& out); -namespace std -{ +namespace std { std::string to_string(cmpop); } bool flt_is_comparable(cmpop op, ppm_param_type t, bool is_list, std::string& err); -bool flt_compare(cmpop op, ppm_param_type type, const void* operand1, const void* operand2, uint32_t op1_len = 0, uint32_t op2_len = 0); -bool flt_compare_avg(cmpop op, ppm_param_type type, const void* operand1, const void* operand2, uint32_t op1_len, uint32_t op2_len, uint32_t cnt1, uint32_t cnt2); +bool flt_compare(cmpop op, + ppm_param_type type, + const void* operand1, + const void* operand2, + uint32_t op1_len = 0, + uint32_t op2_len = 0); +bool flt_compare_avg(cmpop op, + ppm_param_type type, + const void* operand1, + const void* operand2, + uint32_t op1_len, + uint32_t op2_len, + uint32_t cnt1, + uint32_t cnt2); bool flt_compare_ipv4net(cmpop op, uint64_t operand1, const ipv4net* operand2); -bool flt_compare_ipv6net(cmpop op, const ipv6addr *operand1, const ipv6net *operand2); +bool flt_compare_ipv6net(cmpop op, const ipv6addr* operand1, const ipv6net* operand2); diff --git a/userspace/libsinsp/filter_field.h b/userspace/libsinsp/filter_field.h index 955b8acdb2..b46561d483 100644 --- a/userspace/libsinsp/filter_field.h +++ b/userspace/libsinsp/filter_field.h @@ -27,103 +27,90 @@ limitations under the License. /** * @brief Flags used for describing a field used in a filter or in a formatter -*/ -enum filtercheck_field_flags -{ - EPF_NONE = 0, - EPF_FILTER_ONLY = 1 << 0, ///< this field can only be used as a filter. - EPF_PRINT_ONLY = 1 << 1, ///< this field can only be printed. - EPF_ARG_REQUIRED = 1 << 2, ///< this field includes an argument, under the form 'property.argument'. - EPF_TABLE_ONLY = 1 << 3, ///< this field is designed to be used in a table and won't appear in the field listing. - EPF_INFO = 1 << 4, ///< this field contains summary information about the event. - EPF_CONVERSATION = 1 << 5, ///< this field can be used to identify conversations. - EPF_IS_LIST = 1 << 6, ///< this field is a list of values. - EPF_ARG_ALLOWED = 1 << 7, ///< this field optionally includes an argument. - EPF_ARG_INDEX = 1 << 8, ///< this field accepts numeric arguments. - EPF_ARG_KEY = 1 << 9, ///< this field accepts string arguments. - EPF_DEPRECATED = 1 << 10,///< this field is deprecated. - EPF_NO_TRANSFORMER = 1 << 11,///< this field cannot have a field transformer. - EPF_NO_RHS = 1 << 12,///< this field cannot have a right-hand side filter check, and cannot be used as a right-hand side filter check. + */ +enum filtercheck_field_flags { + EPF_NONE = 0, + EPF_FILTER_ONLY = 1 << 0, ///< this field can only be used as a filter. + EPF_PRINT_ONLY = 1 << 1, ///< this field can only be printed. + EPF_ARG_REQUIRED = + 1 << 2, ///< this field includes an argument, under the form 'property.argument'. + EPF_TABLE_ONLY = 1 << 3, ///< this field is designed to be used in a table and won't appear in + ///< the field listing. + EPF_INFO = 1 << 4, ///< this field contains summary information about the event. + EPF_CONVERSATION = 1 << 5, ///< this field can be used to identify conversations. + EPF_IS_LIST = 1 << 6, ///< this field is a list of values. + EPF_ARG_ALLOWED = 1 << 7, ///< this field optionally includes an argument. + EPF_ARG_INDEX = 1 << 8, ///< this field accepts numeric arguments. + EPF_ARG_KEY = 1 << 9, ///< this field accepts string arguments. + EPF_DEPRECATED = 1 << 10, ///< this field is deprecated. + EPF_NO_TRANSFORMER = 1 << 11, ///< this field cannot have a field transformer. + EPF_NO_RHS = 1 << 12, ///< this field cannot have a right-hand side filter check, and cannot be + ///< used as a right-hand side filter check. }; /** * @brief Information about field using in a filter or in a formatter -*/ -struct filtercheck_field_info -{ - ppm_param_type m_type = ppm_param_type::PT_NONE; ///< Field type. - uint32_t m_flags = 0; ///< Field flags. - ppm_print_format m_print_format = ppm_print_format::PF_NA; ///< If this is a numeric field, this flag specifies if it should be rendered as octal, decimal or hex. - std::string m_name; ///< Field name. - std::string m_display; ///< Field display name (short description). May be empty. - std::string m_description; ///< Field description. + */ +struct filtercheck_field_info { + ppm_param_type m_type = ppm_param_type::PT_NONE; ///< Field type. + uint32_t m_flags = 0; ///< Field flags. + ppm_print_format m_print_format = + ppm_print_format::PF_NA; ///< If this is a numeric field, this flag specifies if it + ///< should be rendered as octal, decimal or hex. + std::string m_name; ///< Field name. + std::string m_display; ///< Field display name (short description). May be empty. + std::string m_description; ///< Field description. // // Return true if this field must have an argument // - inline bool is_arg_required() const - { - return m_flags & EPF_ARG_REQUIRED; - } + inline bool is_arg_required() const { return m_flags & EPF_ARG_REQUIRED; } // // Return true if this field can optionally have an argument // - inline bool is_arg_allowed() const - { - return m_flags & EPF_ARG_REQUIRED; - } + inline bool is_arg_allowed() const { return m_flags & EPF_ARG_REQUIRED; } // // Returns true if this field can have an argument, either // optionally or mandatorily // - inline bool is_arg_supported() const - { + inline bool is_arg_supported() const { return (m_flags & EPF_ARG_REQUIRED) || (m_flags & EPF_ARG_ALLOWED); } // // Returns true if this field is a list of values // - inline bool is_list() const - { - return m_flags & EPF_IS_LIST; - } + inline bool is_list() const { return m_flags & EPF_IS_LIST; } // // Returns true if this filter check can support a rhs filter check instead of a const value. // - inline bool is_rhs_field_supported() const - { - return !(m_flags & EPF_NO_RHS); - } + inline bool is_rhs_field_supported() const { return !(m_flags & EPF_NO_RHS); } // // Returns true if this filter check can support an extraction transformer on it. // - inline bool is_transformer_supported() const - { - return !(m_flags & EPF_NO_TRANSFORMER); - } + inline bool is_transformer_supported() const { return !(m_flags & EPF_NO_TRANSFORMER); } }; /** * @brief Information about a group of filter/formatting fields. -*/ -class filter_check_info -{ + */ +class filter_check_info { public: - enum flags: uint8_t - { + enum flags : uint8_t { FL_NONE = 0, - FL_HIDDEN = (1 << 0), ///< This filter check class won't be shown by fields/filter listings. + FL_HIDDEN = + (1 << 0), ///< This filter check class won't be shown by fields/filter listings. }; - std::string m_name; ///< Field class name. - std::string m_shortdesc; ///< short (< 10 words) description of this filtercheck. Can be blank. - std::string m_desc; ///< Field class description. - int32_t m_nfields = 0; ///< Number of fields in this field group. - const filtercheck_field_info* m_fields = nullptr; ///< Array containing m_nfields field descriptions. + std::string m_name; ///< Field class name. + std::string m_shortdesc; ///< short (< 10 words) description of this filtercheck. Can be blank. + std::string m_desc; ///< Field class description. + int32_t m_nfields = 0; ///< Number of fields in this field group. + const filtercheck_field_info* m_fields = + nullptr; ///< Array containing m_nfields field descriptions. uint32_t m_flags = flags::FL_NONE; }; diff --git a/userspace/libsinsp/filter_value.h b/userspace/libsinsp/filter_value.h index 38e328288b..6f7f2e1a2c 100644 --- a/userspace/libsinsp/filter_value.h +++ b/userspace/libsinsp/filter_value.h @@ -33,16 +33,13 @@ limitations under the License. typedef std::pair filter_value_t; -struct g_hash_membuf -{ - size_t operator()(filter_value_t val) const - { +struct g_hash_membuf { + size_t operator()(filter_value_t val) const { #if defined(__GNUC__) && !defined(__clang__) return std::_Hash_impl::hash(val.first, val.second); #else size_t hash = 5381; - for(uint8_t *p = val.first; (uint32_t)(p-val.first) < val.second; p++) - { + for(uint8_t *p = val.first; (uint32_t)(p - val.first) < val.second; p++) { int c = *p; hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } @@ -51,11 +48,8 @@ struct g_hash_membuf } }; -struct g_equal_to_membuf -{ - bool operator()(filter_value_t a, filter_value_t b) const - { - return (a.second == b.second && - memcmp(a.first, b.first, a.second) == 0); +struct g_equal_to_membuf { + bool operator()(filter_value_t a, filter_value_t b) const { + return (a.second == b.second && memcmp(a.first, b.first, a.second) == 0); } }; diff --git a/userspace/libsinsp/grpc_channel_registry.cpp b/userspace/libsinsp/grpc_channel_registry.cpp index 65107a3004..00e910da0a 100644 --- a/userspace/libsinsp/grpc_channel_registry.cpp +++ b/userspace/libsinsp/grpc_channel_registry.cpp @@ -18,30 +18,23 @@ limitations under the License. #include - std::map> libsinsp::grpc_channel_registry::s_channels; -std::shared_ptr libsinsp::grpc_channel_registry::get_channel(const std::string &url, const grpc::ChannelArguments *args) -{ +std::shared_ptr libsinsp::grpc_channel_registry::get_channel( + const std::string &url, + const grpc::ChannelArguments *args) { std::shared_ptr chan; auto it = s_channels.find(url); - if(it != s_channels.end()) - { + if(it != s_channels.end()) { chan = it->second.lock(); - if (chan != nullptr) - { + if(chan != nullptr) { return chan; } } - if (args) - { - chan = grpc::CreateCustomChannel(url, - grpc::InsecureChannelCredentials(), *args); - } - else - { - chan = grpc::CreateChannel(url, - grpc::InsecureChannelCredentials()); + if(args) { + chan = grpc::CreateCustomChannel(url, grpc::InsecureChannelCredentials(), *args); + } else { + chan = grpc::CreateChannel(url, grpc::InsecureChannelCredentials()); } s_channels[url] = chan; diff --git a/userspace/libsinsp/grpc_channel_registry.h b/userspace/libsinsp/grpc_channel_registry.h index 17cc86bffe..1c73dcd066 100644 --- a/userspace/libsinsp/grpc_channel_registry.h +++ b/userspace/libsinsp/grpc_channel_registry.h @@ -20,21 +20,19 @@ limitations under the License. #include #ifdef GRPC_INCLUDE_IS_GRPCPP -# include +#include #else -# include +#include #endif -namespace libsinsp -{ -class grpc_channel_registry -{ +namespace libsinsp { +class grpc_channel_registry { public: // Return a (shared) grpc::Channel for the provided url. static std::shared_ptr get_channel(const std::string &url, - const grpc::ChannelArguments *args = nullptr); + const grpc::ChannelArguments *args = nullptr); private: static std::map> s_channels; }; -} +} // namespace libsinsp diff --git a/userspace/libsinsp/gvisor_config.cpp b/userspace/libsinsp/gvisor_config.cpp index 3569826610..273cc68b9b 100644 --- a/userspace/libsinsp/gvisor_config.cpp +++ b/userspace/libsinsp/gvisor_config.cpp @@ -22,8 +22,7 @@ limitations under the License. #include -namespace gvisor_config -{ +namespace gvisor_config { struct gvisor_point_info_t { std::string m_name; @@ -34,328 +33,165 @@ struct gvisor_point_info_t { static const std::string s_default_socket_path = "/tmp/gvisor.sock"; static const std::vector s_gvisor_points = { - {"container/start", + {"container/start", {"time", "thread_id", "container_id", "task_start_time", "credentials", "cwd"}, - {"env"}}, - {"sentry/clone", - {"time", "thread_id", "container_id", "task_start_time", - "group_id", "credentials", "cwd", "process_name"}, - {}}, - {"sentry/task_exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/open/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/open/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/openat/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/openat/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/creat/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/creat/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/close/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/close/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/read/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/read/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pread64/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pread64/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/readv/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/readv/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/preadv/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/preadv/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/connect/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/connect/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/execve/enter", - {"time", "thread_id", "container_id", "cwd"}, - {}}, - {"syscall/execve/exit", + {"env"}}, + {"sentry/clone", + {"time", + "thread_id", + "container_id", + "task_start_time", + "group_id", + "credentials", + "cwd", + "process_name"}, + {}}, + {"sentry/task_exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/open/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/open/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/openat/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/openat/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/creat/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/creat/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/close/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/close/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/read/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/read/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pread64/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pread64/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/readv/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/readv/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/preadv/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/preadv/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/connect/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/connect/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/execve/enter", {"time", "thread_id", "container_id", "cwd"}, {}}, + {"syscall/execve/exit", {"time", "thread_id", "container_id", "group_id", "credentials", "cwd"}, - {"envv"}}, - {"syscall/execveat/enter", - {"time", "thread_id", "container_id", "cwd"}, - {}}, - {"syscall/execveat/exit", + {"envv"}}, + {"syscall/execveat/enter", {"time", "thread_id", "container_id", "cwd"}, {}}, + {"syscall/execveat/exit", {"time", "thread_id", "container_id", "group_id", "credentials", "cwd"}, - {"envv"}}, - {"syscall/socket/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/socket/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/chdir/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/chdir/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/fchdir/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/fchdir/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setuid/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setuid/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setgid/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setgid/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setsid/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setsid/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setresuid/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setresuid/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setresgid/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/setresgid/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/prlimit64/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/prlimit64/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pipe/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pipe/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pipe2/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pipe2/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/fcntl/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/fcntl/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/dup/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/dup/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/dup2/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/dup2/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/dup3/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/dup3/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/signalfd/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/signalfd/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/signalfd4/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/signalfd4/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/chroot/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/chroot/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/eventfd/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/eventfd/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/eventfd2/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/eventfd2/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/clone/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/clone/exit", - {"time", "thread_id", "container_id", "task_start_time", - "group_id", "credentials", "cwd", "process_name"}, - {}}, - {"syscall/bind/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/bind/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/accept/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/accept/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/accept4/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/accept4/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/timerfd_create/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/timerfd_create/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/fork/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/fork/exit", - {"time", "thread_id", "container_id", "task_start_time", - "group_id", "credentials", "cwd", "process_name"}, - {}}, - {"syscall/vfork/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/vfork/exit", - {"time", "thread_id", "container_id", "task_start_time", - "group_id", "credentials", "cwd", "process_name"}, - {}}, - {"syscall/inotify_init/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/inotify_init/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/inotify_init1/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/inotify_init1/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/socketpair/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/socketpair/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/write/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/write/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pwrite64/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pwrite64/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/writev/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/writev/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pwritev/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/pwritev/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/sysno/9/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/sysno/9/exit", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/sysno/11/enter", - {"time", "thread_id", "container_id"}, - {}}, - {"syscall/sysno/11/exit", - {"time", "thread_id", "container_id"}, - {}} -}; + {"envv"}}, + {"syscall/socket/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/socket/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/chdir/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/chdir/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/fchdir/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/fchdir/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setuid/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setuid/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setgid/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setgid/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setsid/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setsid/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setresuid/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setresuid/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setresgid/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/setresgid/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/prlimit64/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/prlimit64/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pipe/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pipe/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pipe2/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pipe2/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/fcntl/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/fcntl/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/dup/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/dup/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/dup2/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/dup2/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/dup3/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/dup3/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/signalfd/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/signalfd/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/signalfd4/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/signalfd4/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/chroot/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/chroot/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/eventfd/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/eventfd/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/eventfd2/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/eventfd2/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/clone/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/clone/exit", + {"time", + "thread_id", + "container_id", + "task_start_time", + "group_id", + "credentials", + "cwd", + "process_name"}, + {}}, + {"syscall/bind/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/bind/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/accept/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/accept/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/accept4/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/accept4/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/timerfd_create/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/timerfd_create/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/fork/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/fork/exit", + {"time", + "thread_id", + "container_id", + "task_start_time", + "group_id", + "credentials", + "cwd", + "process_name"}, + {}}, + {"syscall/vfork/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/vfork/exit", + {"time", + "thread_id", + "container_id", + "task_start_time", + "group_id", + "credentials", + "cwd", + "process_name"}, + {}}, + {"syscall/inotify_init/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/inotify_init/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/inotify_init1/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/inotify_init1/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/socketpair/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/socketpair/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/write/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/write/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pwrite64/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pwrite64/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/writev/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/writev/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pwritev/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/pwritev/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/sysno/9/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/sysno/9/exit", {"time", "thread_id", "container_id"}, {}}, + {"syscall/sysno/11/enter", {"time", "thread_id", "container_id"}, {}}, + {"syscall/sysno/11/exit", {"time", "thread_id", "container_id"}, {}}}; constexpr unsigned int max_retries = 3; -std::string generate(const std::string& socket_path) -{ +std::string generate(const std::string &socket_path) { Json::Value jpoints; - for(const auto &point_info : s_gvisor_points) - { + for(const auto &point_info : s_gvisor_points) { Json::Value jpoint; jpoint["name"] = point_info.m_name; - if (!point_info.m_context_fields.empty()) - { + if(!point_info.m_context_fields.empty()) { Json::Value jcontext_fields; - for(const auto &context_field : point_info.m_context_fields) - { + for(const auto &context_field : point_info.m_context_fields) { jcontext_fields.append(context_field); } jpoint["context_fields"] = jcontext_fields; } - if (!point_info.m_optional_fields.empty()) - { + if(!point_info.m_optional_fields.empty()) { Json::Value joptional_fields; - for(const auto &optional_field : point_info.m_optional_fields) - { + for(const auto &optional_field : point_info.m_optional_fields) { joptional_fields.append(optional_field); } @@ -384,4 +220,4 @@ std::string generate(const std::string& socket_path) return jroot.toStyledString(); } -} // namespace gvisor_config +} // namespace gvisor_config diff --git a/userspace/libsinsp/gvisor_config.h b/userspace/libsinsp/gvisor_config.h index b0d874b9ce..c1d755dc75 100644 --- a/userspace/libsinsp/gvisor_config.h +++ b/userspace/libsinsp/gvisor_config.h @@ -20,7 +20,6 @@ limitations under the License. #include -namespace gvisor_config -{ - std::string generate(const std::string& socket_path); +namespace gvisor_config { +std::string generate(const std::string& socket_path); } diff --git a/userspace/libsinsp/ifinfo.cpp b/userspace/libsinsp/ifinfo.cpp index fc58b1bbb0..84a3f81033 100644 --- a/userspace/libsinsp/ifinfo.cpp +++ b/userspace/libsinsp/ifinfo.cpp @@ -19,44 +19,40 @@ limitations under the License. #include #include -sinsp_network_interfaces::sinsp_network_interfaces() -{ - if(inet_pton(AF_INET6, "::1", m_ipv6_loopback_addr.m_b) != 1) - { +sinsp_network_interfaces::sinsp_network_interfaces() { + if(inet_pton(AF_INET6, "::1", m_ipv6_loopback_addr.m_b) != 1) { throw sinsp_exception("Could not convert ipv6 loopback address ::1 to ipv6addr struct"); } } -sinsp_ipv4_ifinfo::sinsp_ipv4_ifinfo(uint32_t addr, uint32_t netmask, uint32_t bcast, const char* name) -{ +sinsp_ipv4_ifinfo::sinsp_ipv4_ifinfo(uint32_t addr, + uint32_t netmask, + uint32_t bcast, + const char* name) { m_addr = addr; m_netmask = netmask; m_bcast = bcast; m_name = name; } -void sinsp_ipv4_ifinfo::convert_to_string(char * dest, size_t len, const uint32_t addr) -{ +void sinsp_ipv4_ifinfo::convert_to_string(char* dest, size_t len, const uint32_t addr) { uint32_t addr_network_byte_order = htonl(addr); - snprintf( - dest, - len, - "%d.%d.%d.%d", - ((addr_network_byte_order & 0xFF000000) >> 24), - ((addr_network_byte_order & 0xFF0000) >> 16), - ((addr_network_byte_order & 0xFF00) >> 8), - (addr_network_byte_order & 0xFF)); + snprintf(dest, + len, + "%d.%d.%d.%d", + ((addr_network_byte_order & 0xFF000000) >> 24), + ((addr_network_byte_order & 0xFF0000) >> 16), + ((addr_network_byte_order & 0xFF00) >> 8), + (addr_network_byte_order & 0xFF)); } -std::string sinsp_ipv4_ifinfo::address() const -{ +std::string sinsp_ipv4_ifinfo::address() const { char str_addr[16]; convert_to_string(str_addr, sizeof(str_addr), m_addr); return std::string(str_addr); } -std::string sinsp_ipv4_ifinfo::to_string() const -{ +std::string sinsp_ipv4_ifinfo::to_string() const { char s[100]; char str_addr[16]; char s_netmask[16]; @@ -65,32 +61,33 @@ std::string sinsp_ipv4_ifinfo::to_string() const convert_to_string(str_addr, sizeof(str_addr), m_addr); convert_to_string(s_netmask, sizeof(str_addr), m_netmask); convert_to_string(s_bcast, sizeof(str_addr), m_bcast); - snprintf(s, sizeof(s), "%s inet %s netmask %s broadcast %s", m_name.c_str(), str_addr, s_netmask, s_bcast); + snprintf(s, + sizeof(s), + "%s inet %s netmask %s broadcast %s", + m_name.c_str(), + str_addr, + s_netmask, + s_bcast); return std::string(s); } -std::string sinsp_ipv4_ifinfo::addr_to_string(const uint32_t addr) -{ +std::string sinsp_ipv4_ifinfo::addr_to_string(const uint32_t addr) { char str_addr[16]; convert_to_string(str_addr, sizeof(str_addr), addr); return std::string(str_addr); } -std::string sinsp_ipv4_ifinfo::addr_to_string() const -{ +std::string sinsp_ipv4_ifinfo::addr_to_string() const { char str_addr[16]; convert_to_string(str_addr, sizeof(str_addr), m_addr); return std::string(str_addr); } -std::string sinsp_ipv6_ifinfo::addr_to_string() const -{ +std::string sinsp_ipv6_ifinfo::addr_to_string() const { std::ostringstream oss; const uint16_t* words = reinterpret_cast(m_net.m_b); - for (int i = 0; i < 8; ++i) - { - if (i != 0) - { + for(int i = 0; i < 8; ++i) { + if(i != 0) { oss << ':'; } oss << std::hex << ntohs(words[i]); @@ -98,123 +95,92 @@ std::string sinsp_ipv6_ifinfo::addr_to_string() const return oss.str(); } -uint32_t sinsp_network_interfaces::infer_ipv4_address(uint32_t destination_address) -{ +uint32_t sinsp_network_interfaces::infer_ipv4_address(uint32_t destination_address) { std::vector::iterator it; // first try to find exact match - for(it = m_ipv4_interfaces.begin(); it != m_ipv4_interfaces.end(); it++) - { - if(it->m_addr == destination_address) - { + for(it = m_ipv4_interfaces.begin(); it != m_ipv4_interfaces.end(); it++) { + if(it->m_addr == destination_address) { return it->m_addr; } } // try to find an interface for the same subnet - for(it = m_ipv4_interfaces.begin(); it != m_ipv4_interfaces.end(); it++) - { - if((it->m_addr & it->m_netmask) == (destination_address & it->m_netmask)) - { + for(it = m_ipv4_interfaces.begin(); it != m_ipv4_interfaces.end(); it++) { + if((it->m_addr & it->m_netmask) == (destination_address & it->m_netmask)) { return it->m_addr; } } // otherwise take the first non loopback interface - for(it = m_ipv4_interfaces.begin(); it != m_ipv4_interfaces.end(); it++) - { - if(it->m_addr != ntohl(INADDR_LOOPBACK)) - { + for(it = m_ipv4_interfaces.begin(); it != m_ipv4_interfaces.end(); it++) { + if(it->m_addr != ntohl(INADDR_LOOPBACK)) { return it->m_addr; } } return 0; } -void sinsp_network_interfaces::update_fd(sinsp_fdinfo& fd) -{ - ipv4tuple *pipv4info = &(fd.m_sockinfo.m_ipv4info); - ipv6tuple *pipv6info = &(fd.m_sockinfo.m_ipv6info); +void sinsp_network_interfaces::update_fd(sinsp_fdinfo& fd) { + ipv4tuple* pipv4info = &(fd.m_sockinfo.m_ipv4info); + ipv6tuple* pipv6info = &(fd.m_sockinfo.m_ipv6info); // // only handle ipv4/ipv6 udp sockets // - if(fd.m_type != SCAP_FD_IPV4_SOCK && - fd.m_type != SCAP_FD_IPV6_SOCK) - { + if(fd.m_type != SCAP_FD_IPV4_SOCK && fd.m_type != SCAP_FD_IPV6_SOCK) { return; } - if(fd.m_type == SCAP_FD_IPV4_SOCK) - { - - if(0 != pipv4info->m_fields.m_sip && 0 != pipv4info->m_fields.m_dip) - { + if(fd.m_type == SCAP_FD_IPV4_SOCK) { + if(0 != pipv4info->m_fields.m_sip && 0 != pipv4info->m_fields.m_dip) { return; } - if(0 == pipv4info->m_fields.m_sip) - { + if(0 == pipv4info->m_fields.m_sip) { uint32_t newaddr; newaddr = infer_ipv4_address(pipv4info->m_fields.m_dip); - if(newaddr == pipv4info->m_fields.m_dip) - { - if(pipv4info->m_fields.m_sport == pipv4info->m_fields.m_dport) - { + if(newaddr == pipv4info->m_fields.m_dip) { + if(pipv4info->m_fields.m_sport == pipv4info->m_fields.m_dport) { return; } } pipv4info->m_fields.m_sip = newaddr; - } - else - { + } else { uint32_t newaddr; newaddr = infer_ipv4_address(pipv4info->m_fields.m_sip); - if(newaddr == pipv4info->m_fields.m_sip) - { - if(pipv4info->m_fields.m_sport == pipv4info->m_fields.m_dport) - { + if(newaddr == pipv4info->m_fields.m_sip) { + if(pipv4info->m_fields.m_sport == pipv4info->m_fields.m_dport) { return; } } pipv4info->m_fields.m_dip = newaddr; } - } - else if(fd.m_type == SCAP_FD_IPV6_SOCK) - { - + } else if(fd.m_type == SCAP_FD_IPV6_SOCK) { if(ipv6addr::empty_address != pipv6info->m_fields.m_sip && - ipv6addr::empty_address != pipv6info->m_fields.m_dip) - { + ipv6addr::empty_address != pipv6info->m_fields.m_dip) { return; } - if(ipv6addr::empty_address == pipv6info->m_fields.m_sip) - { + if(ipv6addr::empty_address == pipv6info->m_fields.m_sip) { ipv6addr newaddr; newaddr = infer_ipv6_address(pipv6info->m_fields.m_dip); - if(newaddr == pipv6info->m_fields.m_dip) - { - if(pipv6info->m_fields.m_sport == pipv6info->m_fields.m_dport) - { + if(newaddr == pipv6info->m_fields.m_dip) { + if(pipv6info->m_fields.m_sport == pipv6info->m_fields.m_dport) { return; } } pipv6info->m_fields.m_sip = newaddr; - } - else - { + } else { ipv6addr newaddr; newaddr = infer_ipv6_address(pipv6info->m_fields.m_sip); - if(newaddr == pipv6info->m_fields.m_sip) - { - if(pipv6info->m_fields.m_sport == pipv6info->m_fields.m_dport) - { + if(newaddr == pipv6info->m_fields.m_sip) { + if(pipv6info->m_fields.m_sport == pipv6info->m_fields.m_dport) { return; } } @@ -224,8 +190,7 @@ void sinsp_network_interfaces::update_fd(sinsp_fdinfo& fd) } } -bool sinsp_network_interfaces::is_ipv4addr_in_subnet(uint32_t addr) const -{ +bool sinsp_network_interfaces::is_ipv4addr_in_subnet(uint32_t addr) const { // // Accept everything that comes from private internets: // - 10.0.0.0/8 @@ -235,16 +200,13 @@ bool sinsp_network_interfaces::is_ipv4addr_in_subnet(uint32_t addr) const uint32_t addr_network_byte_order = htonl(addr); if((addr_network_byte_order & 0xff000000) == 0x0a000000 || (addr_network_byte_order & 0xffff0000) == 0xc0a80000 || - (addr_network_byte_order & 0xff3f0000) == 0xac100000) - { + (addr_network_byte_order & 0xff3f0000) == 0xac100000) { return true; } // try to find an interface for the same subnet - for(auto& el : m_ipv4_interfaces) - { - if((el.m_addr & el.m_netmask) == (addr & el.m_netmask)) - { + for(auto& el : m_ipv4_interfaces) { + if((el.m_addr & el.m_netmask) == (addr & el.m_netmask)) { return true; } } @@ -252,31 +214,26 @@ bool sinsp_network_interfaces::is_ipv4addr_in_subnet(uint32_t addr) const return false; } -bool sinsp_network_interfaces::is_ipv4addr_in_local_machine(uint32_t addr, sinsp_threadinfo* tinfo) const -{ - if(!tinfo->m_container_id.empty()) - { +bool sinsp_network_interfaces::is_ipv4addr_in_local_machine(uint32_t addr, + sinsp_threadinfo* tinfo) const { + if(!tinfo->m_container_id.empty()) { const sinsp_container_info::ptr_t container_info = - tinfo->m_inspector->m_container_manager.get_container(tinfo->m_container_id); + tinfo->m_inspector->m_container_manager.get_container(tinfo->m_container_id); // // Note: if we don't have container info, any pick we make is arbitrary. - // To at least achieve consistency across client and server, we just match the host interface addresses. + // To at least achieve consistency across client and server, we just match the host + // interface addresses. // - if(container_info) - { - if(container_info->m_container_ip != 0) - { + if(container_info) { + if(container_info->m_container_ip != 0) { // // We have a container info with a valid container IP. Let's use it. // - if(addr == htonl(container_info->m_container_ip)) - { + if(addr == htonl(container_info->m_container_ip)) { return true; } - } - else - { + } else { // // Container info is valid, but the IP address is zero. // Scan the list of the containers looking for matches. @@ -284,27 +241,29 @@ bool sinsp_network_interfaces::is_ipv4addr_in_local_machine(uint32_t addr, sinsp // host interfaces. // - if(!container_info->is_successful()) - { + if(!container_info->is_successful()) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "Checking IP address of container %s with incomplete metadata (state=%d)", - tinfo->m_container_id.c_str(), container_info->get_lookup_status()); + "Checking IP address of container %s with incomplete " + "metadata (state=%d)", + tinfo->m_container_id.c_str(), + container_info->get_lookup_status()); } - const sinsp_container_manager::map_ptr_t clist = tinfo->m_inspector->m_container_manager.get_containers(); - - for(const auto& it : *clist) - { - if(!it.second->is_successful()) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "Checking IP address of container %s with incomplete metadata (in context of %s; state=%d)", - it.second->m_id.c_str(), tinfo->m_container_id.c_str(), - it.second->get_lookup_status()); + const sinsp_container_manager::map_ptr_t clist = + tinfo->m_inspector->m_container_manager.get_containers(); + + for(const auto& it : *clist) { + if(!it.second->is_successful()) { + libsinsp_logger()->format( + sinsp_logger::SEV_DEBUG, + "Checking IP address of container %s with incomplete metadata (in " + "context of %s; state=%d)", + it.second->m_id.c_str(), + tinfo->m_container_id.c_str(), + it.second->get_lookup_status()); } - if(htonl(it.second->m_container_ip) == addr) - { + if(htonl(it.second->m_container_ip) == addr) { return true; } } @@ -313,10 +272,8 @@ bool sinsp_network_interfaces::is_ipv4addr_in_local_machine(uint32_t addr, sinsp } // try to find an interface that has the given IP as address - for(const auto& ipv4interface : m_ipv4_interfaces) - { - if(ipv4interface.m_addr == addr) - { + for(const auto& ipv4interface : m_ipv4_interfaces) { + if(ipv4interface.m_addr == addr) { return true; } } @@ -324,14 +281,11 @@ bool sinsp_network_interfaces::is_ipv4addr_in_local_machine(uint32_t addr, sinsp return false; } -void sinsp_network_interfaces::import_ipv4_ifaddr_list(uint32_t count, scap_ifinfo_ipv4* plist) -{ - if (count == 0) - { +void sinsp_network_interfaces::import_ipv4_ifaddr_list(uint32_t count, scap_ifinfo_ipv4* plist) { + if(count == 0) { return; } - for(uint32_t j = 0; j < count; j++) - { + for(uint32_t j = 0; j < count; j++) { sinsp_ipv4_ifinfo info; info.m_addr = plist->addr; info.m_netmask = plist->netmask; @@ -342,33 +296,26 @@ void sinsp_network_interfaces::import_ipv4_ifaddr_list(uint32_t count, scap_ifin } } -ipv6addr sinsp_network_interfaces::infer_ipv6_address(ipv6addr &destination_address) -{ +ipv6addr sinsp_network_interfaces::infer_ipv6_address(ipv6addr& destination_address) { std::vector::iterator it; // first try to find exact match - for(it = m_ipv6_interfaces.begin(); it != m_ipv6_interfaces.end(); it++) - { - if(destination_address == it->m_net) - { + for(it = m_ipv6_interfaces.begin(); it != m_ipv6_interfaces.end(); it++) { + if(destination_address == it->m_net) { return it->m_net; } } // try to find an interface for the same subnet - for(it = m_ipv6_interfaces.begin(); it != m_ipv6_interfaces.end(); it++) - { - if(it->m_net.in_subnet(destination_address)) - { + for(it = m_ipv6_interfaces.begin(); it != m_ipv6_interfaces.end(); it++) { + if(it->m_net.in_subnet(destination_address)) { return it->m_net; } } // otherwise take the first non loopback interface - for(it = m_ipv6_interfaces.begin(); it != m_ipv6_interfaces.end(); it++) - { - if(it->m_net != m_ipv6_loopback_addr) - { + for(it = m_ipv6_interfaces.begin(); it != m_ipv6_interfaces.end(); it++) { + if(it->m_net != m_ipv6_loopback_addr) { return it->m_net; } } @@ -376,19 +323,16 @@ ipv6addr sinsp_network_interfaces::infer_ipv6_address(ipv6addr &destination_addr return ipv6addr::empty_address; } -bool sinsp_network_interfaces::is_ipv6addr_in_local_machine(ipv6addr &addr, sinsp_threadinfo* tinfo) const -{ - if(!tinfo->m_container_id.empty()) - { +bool sinsp_network_interfaces::is_ipv6addr_in_local_machine(ipv6addr& addr, + sinsp_threadinfo* tinfo) const { + if(!tinfo->m_container_id.empty()) { // For now, not supporting ipv6 networking for containers. So always return false; return false; } // try to find an interface that has the given IP as address - for(const auto& ipv6interface : m_ipv6_interfaces) - { - if(addr.in_subnet(ipv6interface.m_net)) - { + for(const auto& ipv6interface : m_ipv6_interfaces) { + if(addr.in_subnet(ipv6interface.m_net)) { return true; } } @@ -396,14 +340,11 @@ bool sinsp_network_interfaces::is_ipv6addr_in_local_machine(ipv6addr &addr, sins return false; } -void sinsp_network_interfaces::import_ipv6_ifaddr_list(uint32_t count, scap_ifinfo_ipv6* plist) -{ - if (count == 0) - { +void sinsp_network_interfaces::import_ipv6_ifaddr_list(uint32_t count, scap_ifinfo_ipv6* plist) { + if(count == 0) { return; } - for(uint32_t j = 0; j < count; j++) - { + for(uint32_t j = 0; j < count; j++) { sinsp_ipv6_ifinfo info; // Only saving the address portion. (Assumes @@ -417,32 +358,26 @@ void sinsp_network_interfaces::import_ipv6_ifaddr_list(uint32_t count, scap_ifin } } -void sinsp_network_interfaces::import_interfaces(scap_addrlist* paddrlist) -{ - if(NULL != paddrlist) - { +void sinsp_network_interfaces::import_interfaces(scap_addrlist* paddrlist) { + if(NULL != paddrlist) { clear(); import_ipv4_ifaddr_list(paddrlist->n_v4_addrs, paddrlist->v4list); import_ipv6_ifaddr_list(paddrlist->n_v6_addrs, paddrlist->v6list); } } -void sinsp_network_interfaces::import_ipv4_interface(const sinsp_ipv4_ifinfo& ifinfo) -{ +void sinsp_network_interfaces::import_ipv4_interface(const sinsp_ipv4_ifinfo& ifinfo) { m_ipv4_interfaces.push_back(ifinfo); } -void sinsp_network_interfaces::import_ipv6_interface(const sinsp_ipv6_ifinfo& ifinfo) -{ +void sinsp_network_interfaces::import_ipv6_interface(const sinsp_ipv6_ifinfo& ifinfo) { m_ipv6_interfaces.push_back(ifinfo); } -std::vector* sinsp_network_interfaces::get_ipv4_list() -{ +std::vector* sinsp_network_interfaces::get_ipv4_list() { return &m_ipv4_interfaces; } -std::vector* sinsp_network_interfaces::get_ipv6_list() -{ +std::vector* sinsp_network_interfaces::get_ipv6_list() { return &m_ipv6_interfaces; } diff --git a/userspace/libsinsp/ifinfo.h b/userspace/libsinsp/ifinfo.h index 0968c3a281..0b6e303223 100644 --- a/userspace/libsinsp/ifinfo.h +++ b/userspace/libsinsp/ifinfo.h @@ -34,8 +34,7 @@ class sinsp_threadinfo; // // network interface info ipv4 // -class SINSP_PUBLIC sinsp_ipv4_ifinfo -{ +class SINSP_PUBLIC sinsp_ipv4_ifinfo { public: sinsp_ipv4_ifinfo() = default; sinsp_ipv4_ifinfo(uint32_t addr, uint32_t netmask, uint32_t bcast, const char* name); @@ -51,14 +50,13 @@ class SINSP_PUBLIC sinsp_ipv4_ifinfo std::string m_name; private: - static void convert_to_string(char * dest, size_t len, const uint32_t addr); + static void convert_to_string(char* dest, size_t len, const uint32_t addr); }; // // network interface info ipv6 // -class SINSP_PUBLIC sinsp_ipv6_ifinfo -{ +class SINSP_PUBLIC sinsp_ipv6_ifinfo { public: sinsp_ipv6_ifinfo() = default; @@ -68,8 +66,7 @@ class SINSP_PUBLIC sinsp_ipv6_ifinfo std::string m_name; }; -class SINSP_PUBLIC sinsp_network_interfaces -{ +class SINSP_PUBLIC sinsp_network_interfaces { public: sinsp_network_interfaces(); @@ -79,14 +76,14 @@ class SINSP_PUBLIC sinsp_network_interfaces bool is_ipv4addr_in_subnet(uint32_t addr) const; bool is_ipv4addr_in_local_machine(uint32_t addr, sinsp_threadinfo* tinfo) const; void import_ipv6_interface(const sinsp_ipv6_ifinfo& ifinfo); - bool is_ipv6addr_in_local_machine(ipv6addr &addr, sinsp_threadinfo* tinfo) const; + bool is_ipv6addr_in_local_machine(ipv6addr& addr, sinsp_threadinfo* tinfo) const; std::vector* get_ipv4_list(); std::vector* get_ipv6_list(); inline void clear(); uint32_t infer_ipv4_address(uint32_t destination_address); void import_ipv4_ifaddr_list(uint32_t count, scap_ifinfo_ipv4* plist); - ipv6addr infer_ipv6_address(ipv6addr &destination_address); + ipv6addr infer_ipv6_address(ipv6addr& destination_address); void import_ipv6_ifaddr_list(uint32_t count, scap_ifinfo_ipv6* plist); private: @@ -95,8 +92,7 @@ class SINSP_PUBLIC sinsp_network_interfaces std::vector m_ipv6_interfaces; }; -void sinsp_network_interfaces::clear() -{ +void sinsp_network_interfaces::clear() { m_ipv4_interfaces.clear(); m_ipv6_interfaces.clear(); } diff --git a/userspace/libsinsp/logger.cpp b/userspace/libsinsp/logger.cpp index f6b4b4388f..ebcb5b32fc 100644 --- a/userspace/libsinsp/logger.cpp +++ b/userspace/libsinsp/logger.cpp @@ -27,91 +27,77 @@ limitations under the License. #endif #include -namespace -{ +namespace { thread_local char s_tbuf[16384]; const size_t ENCODE_LEN = sizeof(uint64_t); -} // end namespace +} // end namespace sinsp_logger sinsp_logger::s_logger; -sinsp_logger* sinsp_logger::instance() -{ +sinsp_logger* sinsp_logger::instance() { return &s_logger; } -const uint32_t sinsp_logger::OT_NONE = 0; -const uint32_t sinsp_logger::OT_STDOUT = 1; -const uint32_t sinsp_logger::OT_STDERR = (OT_STDOUT << 1); -const uint32_t sinsp_logger::OT_FILE = (OT_STDERR << 1); -const uint32_t sinsp_logger::OT_CALLBACK = (OT_FILE << 1); -const uint32_t sinsp_logger::OT_NOTS = (OT_CALLBACK << 1); -const uint32_t sinsp_logger::OT_ENCODE_SEV = (OT_NOTS << 1); +const uint32_t sinsp_logger::OT_NONE = 0; +const uint32_t sinsp_logger::OT_STDOUT = 1; +const uint32_t sinsp_logger::OT_STDERR = (OT_STDOUT << 1); +const uint32_t sinsp_logger::OT_FILE = (OT_STDERR << 1); +const uint32_t sinsp_logger::OT_CALLBACK = (OT_FILE << 1); +const uint32_t sinsp_logger::OT_NOTS = (OT_CALLBACK << 1); +const uint32_t sinsp_logger::OT_ENCODE_SEV = (OT_NOTS << 1); sinsp_logger::sinsp_logger(): - m_file(nullptr), - m_callback(nullptr), - m_flags(OT_NONE), - m_sev(SEV_INFO) -{ } - -sinsp_logger::~sinsp_logger() -{ - if(m_file) - { + m_file(nullptr), + m_callback(nullptr), + m_flags(OT_NONE), + m_sev(SEV_INFO) {} + +sinsp_logger::~sinsp_logger() { + if(m_file) { ASSERT(m_flags & sinsp_logger::OT_FILE); fclose(m_file); } } -bool sinsp_logger::is_callback() const -{ - return (m_flags & sinsp_logger::OT_CALLBACK) != 0; +bool sinsp_logger::is_callback() const { + return (m_flags & sinsp_logger::OT_CALLBACK) != 0; } -uint32_t sinsp_logger::get_log_output_type() const -{ +uint32_t sinsp_logger::get_log_output_type() const { return m_flags; } -void sinsp_logger::add_stdout_log() -{ +void sinsp_logger::add_stdout_log() { m_flags |= sinsp_logger::OT_STDOUT; } -void sinsp_logger::add_stderr_log() -{ +void sinsp_logger::add_stderr_log() { m_flags |= sinsp_logger::OT_STDERR; } -void sinsp_logger::add_file_log(const std::string& filename) -{ +void sinsp_logger::add_file_log(const std::string& filename) { ASSERT(m_file == nullptr); m_file = fopen(filename.c_str(), "w"); - if(!m_file) - { + if(!m_file) { throw sinsp_exception("Unable to open file " + filename + " for writing"); } m_flags |= sinsp_logger::OT_FILE; } -void sinsp_logger::disable_timestamps() -{ +void sinsp_logger::disable_timestamps() { m_flags |= sinsp_logger::OT_NOTS; } -void sinsp_logger::add_encoded_severity() -{ +void sinsp_logger::add_encoded_severity() { m_flags |= sinsp_logger::OT_ENCODE_SEV; } -void sinsp_logger::add_callback_log(const sinsp_logger_callback callback) -{ +void sinsp_logger::add_callback_log(const sinsp_logger_callback callback) { const sinsp_logger_callback old_cb = m_callback.exchange(callback); ASSERT(old_cb == nullptr); @@ -123,43 +109,35 @@ void sinsp_logger::add_callback_log(const sinsp_logger_callback callback) m_flags |= sinsp_logger::OT_CALLBACK; } -void sinsp_logger::remove_callback_log() -{ +void sinsp_logger::remove_callback_log() { m_callback = nullptr; m_flags &= ~sinsp_logger::OT_CALLBACK; } -void sinsp_logger::set_severity(const severity sev) -{ - if(sev < SEV_MIN || sev > SEV_MAX) - { +void sinsp_logger::set_severity(const severity sev) { + if(sev < SEV_MIN || sev > SEV_MAX) { throw sinsp_exception("Invalid log severity"); } m_sev = sev; } -sinsp_logger::severity sinsp_logger::get_severity() const -{ +sinsp_logger::severity sinsp_logger::get_severity() const { return m_sev; } -void sinsp_logger::log(const std::string& m, const severity sev) -{ +void sinsp_logger::log(const std::string& m, const severity sev) { sinsp_logger_callback cb = nullptr; - if(sev > m_sev) - { + if(sev > m_sev) { return; } std::string msg = m; - if((m_flags & sinsp_logger::OT_NOTS) == 0) - { + if((m_flags & sinsp_logger::OT_NOTS) == 0) { struct timeval ts = {}; - if(gettimeofday(&ts, nullptr) == 0) - { + if(gettimeofday(&ts, nullptr) == 0) { #ifdef _WIN32 tm* ti = _gmtime32((__time32_t*)&ts.tv_sec); #else @@ -167,57 +145,48 @@ void sinsp_logger::log(const std::string& m, const severity sev) gmtime_r(&ts.tv_sec, &time_info); tm* ti = &time_info; #endif - char ts_buf[80]; // holds date/time string: "31-12 23:59:59.999999 " - snprintf(ts_buf, sizeof(ts_buf), "%.2d-%.2d %.2d:%.2d:%.2d.%.6d ", - ti->tm_mon + 1, - ti->tm_mday, - ti->tm_hour, - ti->tm_min, - ti->tm_sec, - (int)ts.tv_usec); + char ts_buf[80]; // holds date/time string: "31-12 23:59:59.999999 " + snprintf(ts_buf, + sizeof(ts_buf), + "%.2d-%.2d %.2d:%.2d:%.2d.%.6d ", + ti->tm_mon + 1, + ti->tm_mday, + ti->tm_hour, + ti->tm_min, + ti->tm_sec, + (int)ts.tv_usec); ts_buf[sizeof(ts_buf) - 1] = '\0'; msg.insert(0, ts_buf); } } - if(m_flags & sinsp_logger::OT_ENCODE_SEV) - { + if(m_flags & sinsp_logger::OT_ENCODE_SEV) { char sev_buf[ENCODE_LEN + 1]; strlcpy(sev_buf, encode_severity(sev), sizeof(sev_buf)); msg.insert(0, sev_buf); } - if(is_callback()) - { + if(is_callback()) { cb = m_callback; } - if(cb != nullptr) - { + if(cb != nullptr) { cb(std::move(msg), sev); - } - else if((m_flags & sinsp_logger::OT_FILE) && m_file) - { + } else if((m_flags & sinsp_logger::OT_FILE) && m_file) { fprintf(m_file, "%s\n", msg.c_str()); fflush(m_file); - } - else if(m_flags & sinsp_logger::OT_STDOUT) - { + } else if(m_flags & sinsp_logger::OT_STDOUT) { fprintf(stdout, "%s\n", msg.c_str()); fflush(stdout); - } - else if(m_flags & sinsp_logger::OT_STDERR) - { + } else if(m_flags & sinsp_logger::OT_STDERR) { fprintf(stderr, "%s\n", msg.c_str()); fflush(stderr); } } -void sinsp_logger::format(const severity sev, const char* const fmt, ...) -{ - if(sev > m_sev) - { +void sinsp_logger::format(const severity sev, const char* const fmt, ...) { + if(sev > m_sev) { return; } @@ -230,8 +199,7 @@ void sinsp_logger::format(const severity sev, const char* const fmt, ...) log(s_tbuf, sev); } -void sinsp_logger::format(const char* const fmt, ...) -{ +void sinsp_logger::format(const char* const fmt, ...) { va_list ap; va_start(ap, fmt); @@ -241,8 +209,7 @@ void sinsp_logger::format(const char* const fmt, ...) log(s_tbuf, SEV_INFO); } -const char* sinsp_logger::format_and_return(const severity sev, const char* const fmt, ...) -{ +const char* sinsp_logger::format_and_return(const severity sev, const char* const fmt, ...) { va_list ap; va_start(ap, fmt); @@ -256,28 +223,24 @@ const char* sinsp_logger::format_and_return(const severity sev, const char* cons namespace { // All severity strings should be ENCODE_LEN chars long -const char* SEV_LEVELS[] = { - "SEV_DEF ", - "SEV_FAT ", - "SEV_CRI ", - "SEV_ERR ", - "SEV_WAR ", - "SEV_NOT ", - "SEV_INF ", - "SEV_DEB ", - "SEV_TRA " -}; +const char* SEV_LEVELS[] = {"SEV_DEF ", + "SEV_FAT ", + "SEV_CRI ", + "SEV_ERR ", + "SEV_WAR ", + "SEV_NOT ", + "SEV_INF ", + "SEV_DEB ", + "SEV_TRA "}; static_assert(sizeof(SEV_LEVELS) == sizeof(*SEV_LEVELS) * ((size_t)(sinsp_logger::SEV_MAX) + 1), - "severity array must have SEV_MAX+1 elements"); -} + "severity array must have SEV_MAX+1 elements"); +} // namespace -const char* sinsp_logger::encode_severity(const sinsp_logger::severity sev) -{ +const char* sinsp_logger::encode_severity(const sinsp_logger::severity sev) { const char* ret; auto sev_int = (size_t)sev; - if (sev_int > SEV_MAX) - { + if(sev_int > SEV_MAX) { sev_int = 0; } @@ -286,20 +249,16 @@ const char* sinsp_logger::encode_severity(const sinsp_logger::severity sev) return ret; } -size_t sinsp_logger::decode_severity(const std::string &str, severity& sev) -{ - if(str.length() < ENCODE_LEN) - { +size_t sinsp_logger::decode_severity(const std::string& str, severity& sev) { + if(str.length() < ENCODE_LEN) { return 0; } const char* msg = str.c_str(); // we don't really expect "SEV_DEF " messages so skip severity 0 - for(size_t i = SEV_MIN; i <= SEV_MAX; ++i) - { - if(!strncmp(msg, SEV_LEVELS[i], ENCODE_LEN)) - { + for(size_t i = SEV_MIN; i <= SEV_MAX; ++i) { + if(!strncmp(msg, SEV_LEVELS[i], ENCODE_LEN)) { sev = static_cast(i); return ENCODE_LEN; } @@ -308,12 +267,10 @@ size_t sinsp_logger::decode_severity(const std::string &str, severity& sev) return 0; } -void sinsp_logger::reset() -{ +void sinsp_logger::reset() { m_callback = nullptr; m_sev = SEV_INFO; - if(m_file) - { + if(m_file) { ASSERT(m_flags & sinsp_logger::OT_FILE); fclose(m_file); m_file = nullptr; @@ -321,7 +278,6 @@ void sinsp_logger::reset() m_flags = OT_NONE; } -sinsp_logger* libsinsp_logger() -{ +sinsp_logger* libsinsp_logger() { return sinsp_logger::instance(); } diff --git a/userspace/libsinsp/logger.h b/userspace/libsinsp/logger.h index 80425486b1..e8aeb87162 100644 --- a/userspace/libsinsp/logger.h +++ b/userspace/libsinsp/logger.h @@ -33,11 +33,9 @@ limitations under the License. * callback function, (2) a registered file, (3) standard output, and * (4) standard error. */ -class SINSP_PUBLIC sinsp_logger -{ +class SINSP_PUBLIC sinsp_logger { public: - enum severity - { + enum severity { SEV_FATAL = FALCOSECURITY_LOG_SEV_FATAL, SEV_CRITICAL = FALCOSECURITY_LOG_SEV_CRITICAL, SEV_ERROR = FALCOSECURITY_LOG_SEV_ERROR, @@ -154,7 +152,7 @@ class SINSP_PUBLIC sinsp_logger * Returns the length of the severity string on success * and 0 in case of errors */ - static size_t decode_severity(const std::string &s, severity& sev); + static size_t decode_severity(const std::string& s, severity& sev); /** * Reset the logger instance to its defaults. @@ -179,7 +177,6 @@ class SINSP_PUBLIC sinsp_logger /** Returns true if the callback log sync is enabled, false otherwise. */ bool is_callback() const; - /** Returns a string containing encoded severity, for OT_ENCODE_SEV. */ static const char* encode_severity(severity sev); std::atomic m_file; diff --git a/userspace/libsinsp/logger_macros.h b/userspace/libsinsp/logger_macros.h index 2052d6497d..1eee4ac69b 100644 --- a/userspace/libsinsp/logger_macros.h +++ b/userspace/libsinsp/logger_macros.h @@ -16,78 +16,72 @@ limitations under the License. */ -#define SINSP_LOG_(severity, fmt, ...) \ - do \ - { \ - if(libsinsp_logger()->is_enabled(severity)) \ - { \ - libsinsp_logger()->format((severity), ("" fmt), ##__VA_ARGS__); \ - } \ - } \ - while(false) +#define SINSP_LOG_(severity, fmt, ...) \ + do { \ + if(libsinsp_logger()->is_enabled(severity)) { \ + libsinsp_logger()->format((severity), ("" fmt), ##__VA_ARGS__); \ + } \ + } while(false) -#define SINSP_LOG_STR_(severity, msg) \ - do \ - { \ - if(libsinsp_logger()->is_enabled(severity)) \ - { \ - libsinsp_logger()->log((msg), (severity)); \ - } \ - } \ - while(false) +#define SINSP_LOG_STR_(severity, msg) \ + do { \ + if(libsinsp_logger()->is_enabled(severity)) { \ + libsinsp_logger()->log((msg), (severity)); \ + } \ + } while(false) -#define SINSP_FATAL(...) SINSP_LOG_(sinsp_logger::SEV_FATAL, ##__VA_ARGS__) +#define SINSP_FATAL(...) SINSP_LOG_(sinsp_logger::SEV_FATAL, ##__VA_ARGS__) #define SINSP_CRITICAL(...) SINSP_LOG_(sinsp_logger::SEV_CRITICAL, ##__VA_ARGS__) -#define SINSP_ERROR(...) SINSP_LOG_(sinsp_logger::SEV_ERROR, ##__VA_ARGS__) -#define SINSP_WARNING(...) SINSP_LOG_(sinsp_logger::SEV_WARNING, ##__VA_ARGS__) -#define SINSP_NOTICE(...) SINSP_LOG_(sinsp_logger::SEV_NOTICE, ##__VA_ARGS__) -#define SINSP_INFO(...) SINSP_LOG_(sinsp_logger::SEV_INFO, ##__VA_ARGS__) -#define SINSP_DEBUG(...) SINSP_LOG_(sinsp_logger::SEV_DEBUG, ##__VA_ARGS__) -#define SINSP_TRACE(...) SINSP_LOG_(sinsp_logger::SEV_TRACE, ##__VA_ARGS__) +#define SINSP_ERROR(...) SINSP_LOG_(sinsp_logger::SEV_ERROR, ##__VA_ARGS__) +#define SINSP_WARNING(...) SINSP_LOG_(sinsp_logger::SEV_WARNING, ##__VA_ARGS__) +#define SINSP_NOTICE(...) SINSP_LOG_(sinsp_logger::SEV_NOTICE, ##__VA_ARGS__) +#define SINSP_INFO(...) SINSP_LOG_(sinsp_logger::SEV_INFO, ##__VA_ARGS__) +#define SINSP_DEBUG(...) SINSP_LOG_(sinsp_logger::SEV_DEBUG, ##__VA_ARGS__) +#define SINSP_TRACE(...) SINSP_LOG_(sinsp_logger::SEV_TRACE, ##__VA_ARGS__) -#define SINSP_STR_FATAL(str) SINSP_LOG_STR_(sinsp_logger::SEV_FATAL, (str)) -#define SINSP_STR_CRITICAL(str) SINSP_LOG_STR_(sinsp_logger::SEV_CRITICAL,(str)) -#define SINSP_STR_ERROR(str) SINSP_LOG_STR_(sinsp_logger::SEV_ERROR, (str)) -#define SINSP_STR_WARNING(str) SINSP_LOG_STR_(sinsp_logger::SEV_WARNING, (str)) -#define SINSP_STR_NOTICE(str) SINSP_LOG_STR_(sinsp_logger::SEV_NOTICE, (str)) -#define SINSP_STR_INFO(str) SINSP_LOG_STR_(sinsp_logger::SEV_INFO, (str)) -#define SINSP_STR_DEBUG(str) SINSP_LOG_STR_(sinsp_logger::SEV_DEBUG, (str)) -#define SINSP_STR_TRACE(str) SINSP_LOG_STR_(sinsp_logger::SEV_TRACE, (str)) +#define SINSP_STR_FATAL(str) SINSP_LOG_STR_(sinsp_logger::SEV_FATAL, (str)) +#define SINSP_STR_CRITICAL(str) SINSP_LOG_STR_(sinsp_logger::SEV_CRITICAL, (str)) +#define SINSP_STR_ERROR(str) SINSP_LOG_STR_(sinsp_logger::SEV_ERROR, (str)) +#define SINSP_STR_WARNING(str) SINSP_LOG_STR_(sinsp_logger::SEV_WARNING, (str)) +#define SINSP_STR_NOTICE(str) SINSP_LOG_STR_(sinsp_logger::SEV_NOTICE, (str)) +#define SINSP_STR_INFO(str) SINSP_LOG_STR_(sinsp_logger::SEV_INFO, (str)) +#define SINSP_STR_DEBUG(str) SINSP_LOG_STR_(sinsp_logger::SEV_DEBUG, (str)) +#define SINSP_STR_TRACE(str) SINSP_LOG_STR_(sinsp_logger::SEV_TRACE, (str)) #if _DEBUG -# define DBG_SINSP_FATAL(...) SINSP_FATAL( __VA_ARGS__) -# define DBG_SINSP_CRITICAL(...) SINSP_CRITICAL(__VA_ARGS__) -# define DBG_SINSP_ERROR(...) SINSP_ERROR( __VA_ARGS__) -# define DBG_SINSP_WARNING(...) SINSP_WARNING( __VA_ARGS__) -# define DBG_SINSP_NOTICE(...) SINSP_NOTICE( __VA_ARGS__) -# define DBG_SINSP_INFO(...) SINSP_INFO( __VA_ARGS__) -# define DBG_SINSP_DEBUG(...) SINSP_DEBUG( __VA_ARGS__) -# define DBG_SINSP_TRACE(...) SINSP_TRACE( __VA_ARGS__) +#define DBG_SINSP_FATAL(...) SINSP_FATAL(__VA_ARGS__) +#define DBG_SINSP_CRITICAL(...) SINSP_CRITICAL(__VA_ARGS__) +#define DBG_SINSP_ERROR(...) SINSP_ERROR(__VA_ARGS__) +#define DBG_SINSP_WARNING(...) SINSP_WARNING(__VA_ARGS__) +#define DBG_SINSP_NOTICE(...) SINSP_NOTICE(__VA_ARGS__) +#define DBG_SINSP_INFO(...) SINSP_INFO(__VA_ARGS__) +#define DBG_SINSP_DEBUG(...) SINSP_DEBUG(__VA_ARGS__) +#define DBG_SINSP_TRACE(...) SINSP_TRACE(__VA_ARGS__) -# define DBG_SINSP_STR_FATAL(str) SINSP_STR_FATAL(str) -# define DBG_SINSP_STR_CRITICAL(str) SINSP_STR_CRITICAL(str) -# define DBG_SINSP_STR_ERROR(str) SINSP_STR_ERROR(str) -# define DBG_SINSP_STR_WARNING(str) SINSP_STR_WARNING(str) -# define DBG_SINSP_STR_NOTICE(str) SINSP_STR_NOTICE(str) -# define DBG_SINSP_STR_INFO(str) SINSP_STR_INFO(str) -# define DBG_SINSP_STR_DEBUG(str) SINSP_STR_DEBUG(str) -# define DBG_SINSP_STR_TRACE(str) SINSP_STR_TRACE(str) +#define DBG_SINSP_STR_FATAL(str) SINSP_STR_FATAL(str) +#define DBG_SINSP_STR_CRITICAL(str) SINSP_STR_CRITICAL(str) +#define DBG_SINSP_STR_ERROR(str) SINSP_STR_ERROR(str) +#define DBG_SINSP_STR_WARNING(str) SINSP_STR_WARNING(str) +#define DBG_SINSP_STR_NOTICE(str) SINSP_STR_NOTICE(str) +#define DBG_SINSP_STR_INFO(str) SINSP_STR_INFO(str) +#define DBG_SINSP_STR_DEBUG(str) SINSP_STR_DEBUG(str) +#define DBG_SINSP_STR_TRACE(str) SINSP_STR_TRACE(str) #else -# define DBG_SINSP_FATAL(fmt, ...) -# define DBG_SINSP_CRITICAL(fmt, ...) -# define DBG_SINSP_ERROR(fmt, ...) -# define DBG_SINSP_WARNING(fmt, ...) -# define DBG_SINSP_NOTICE(fmt, ...) -# define DBG_SINSP_INFO(fmt, ...) -# define DBG_SINSP_DEBUG(fmt, ...) -# define DBG_SINSP_TRACE(fmt, ...) +#define DBG_SINSP_FATAL(fmt, ...) +#define DBG_SINSP_CRITICAL(fmt, ...) +#define DBG_SINSP_ERROR(fmt, ...) +#define DBG_SINSP_WARNING(fmt, ...) +#define DBG_SINSP_NOTICE(fmt, ...) +#define DBG_SINSP_INFO(fmt, ...) +#define DBG_SINSP_DEBUG(fmt, ...) +#define DBG_SINSP_TRACE(fmt, ...) -# define DBG_SINSP_STR_FATAL(str) -# define DBG_SINSP_STR_CRITICAL(str) -# define DBG_SINSP_STR_ERROR(str) -# define DBG_SINSP_STR_WARNING(str) -# define DBG_SINSP_STR_NOTICE(str) -# define DBG_SINSP_STR_INFO(str) -# define DBG_SINSP_STR_DEBUG(str) -# define DBG_SINSP_STR_TRACE(str) +#define DBG_SINSP_STR_FATAL(str) +#define DBG_SINSP_STR_CRITICAL(str) +#define DBG_SINSP_STR_ERROR(str) +#define DBG_SINSP_STR_WARNING(str) +#define DBG_SINSP_STR_NOTICE(str) +#define DBG_SINSP_STR_INFO(str) +#define DBG_SINSP_STR_DEBUG(str) +#define DBG_SINSP_STR_TRACE(str) #endif diff --git a/userspace/libsinsp/memmem.h b/userspace/libsinsp/memmem.h index 987907559a..922b2009d7 100644 --- a/userspace/libsinsp/memmem.h +++ b/userspace/libsinsp/memmem.h @@ -22,27 +22,24 @@ limitations under the License. #if !defined(_GNU_SOURCE) && !defined(__APPLE__) #include -static inline void *memmem(const void *haystack, size_t haystacklen, - const void *needle, size_t needlelen) -{ +static inline void *memmem(const void *haystack, + size_t haystacklen, + const void *needle, + size_t needlelen) { const unsigned char *ptr; const unsigned char *end; - if(needlelen == 0) - { + if(needlelen == 0) { return (void *)haystack; } - if(haystacklen < needlelen) - { + if(haystacklen < needlelen) { return NULL; } end = (const unsigned char *)haystack + haystacklen - needlelen; - for(ptr = (const unsigned char *)haystack; ptr <= end; ptr++) - { - if(!memcmp(ptr, needle, needlelen)) - { + for(ptr = (const unsigned char *)haystack; ptr <= end; ptr++) { + if(!memcmp(ptr, needle, needlelen)) { return (void *)ptr; } } diff --git a/userspace/libsinsp/metrics_collector.cpp b/userspace/libsinsp/metrics_collector.cpp index 1ff68279d6..e5e64d8289 100644 --- a/userspace/libsinsp/metrics_collector.cpp +++ b/userspace/libsinsp/metrics_collector.cpp @@ -26,42 +26,46 @@ limitations under the License. #include #include -static re2::RE2 s_libs_metrics_units_suffix_pre_prometheus_text_conversion("(_kb|_bytes|_mb|_perc|_percentage|_ratio|_ns|_ts|_sec|_total)", re2::RE2::POSIX); +static re2::RE2 s_libs_metrics_units_suffix_pre_prometheus_text_conversion( + "(_kb|_bytes|_mb|_perc|_percentage|_ratio|_ns|_ts|_sec|_total)", + re2::RE2::POSIX); static re2::RE2 s_libs_metrics_units_memory_suffix("(_kb|_bytes)", re2::RE2::POSIX); static re2::RE2 s_libs_metrics_units_perc_suffix("(_perc)", re2::RE2::POSIX); // For simplicity, needs to stay in sync w/ typedef enum metrics_v2_value_unit -// https://prometheus.io/docs/practices/naming/ or https://prometheus.io/docs/practices/naming/#base-units. -static const char *const metrics_unit_name_mappings_prometheus[] = { - [METRIC_VALUE_UNIT_COUNT] = "total", - [METRIC_VALUE_UNIT_RATIO] = "ratio", - [METRIC_VALUE_UNIT_PERC] = "percentage", - [METRIC_VALUE_UNIT_MEMORY_BYTES] = "bytes", - [METRIC_VALUE_UNIT_MEMORY_KIBIBYTES] = "kibibytes", - [METRIC_VALUE_UNIT_MEMORY_MEGABYTES] = "megabytes", - [METRIC_VALUE_UNIT_TIME_NS] = "nanoseconds", - [METRIC_VALUE_UNIT_TIME_S] = "seconds", - [METRIC_VALUE_UNIT_TIME_NS_COUNT] = "nanoseconds_total", - [METRIC_VALUE_UNIT_TIME_S_COUNT] = "seconds_total", - [METRIC_VALUE_UNIT_TIME_TIMESTAMP_NS] = "timestamp_nanoseconds", +// https://prometheus.io/docs/practices/naming/ or +// https://prometheus.io/docs/practices/naming/#base-units. +static const char* const metrics_unit_name_mappings_prometheus[] = { + [METRIC_VALUE_UNIT_COUNT] = "total", + [METRIC_VALUE_UNIT_RATIO] = "ratio", + [METRIC_VALUE_UNIT_PERC] = "percentage", + [METRIC_VALUE_UNIT_MEMORY_BYTES] = "bytes", + [METRIC_VALUE_UNIT_MEMORY_KIBIBYTES] = "kibibytes", + [METRIC_VALUE_UNIT_MEMORY_MEGABYTES] = "megabytes", + [METRIC_VALUE_UNIT_TIME_NS] = "nanoseconds", + [METRIC_VALUE_UNIT_TIME_S] = "seconds", + [METRIC_VALUE_UNIT_TIME_NS_COUNT] = "nanoseconds_total", + [METRIC_VALUE_UNIT_TIME_S_COUNT] = "seconds_total", + [METRIC_VALUE_UNIT_TIME_TIMESTAMP_NS] = "timestamp_nanoseconds", }; -static_assert(sizeof(metrics_unit_name_mappings_prometheus) / sizeof(metrics_unit_name_mappings_prometheus[0]) == METRIC_VALUE_UNIT_MAX, "metrics_unit_name_mappings_prometheus array size does not match expected size"); +static_assert(sizeof(metrics_unit_name_mappings_prometheus) / + sizeof(metrics_unit_name_mappings_prometheus[0]) == + METRIC_VALUE_UNIT_MAX, + "metrics_unit_name_mappings_prometheus array size does not match expected size"); // For simplicity, needs to stay in sync w/ typedef enum metrics_v2_metric_type // https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md -static const char *const metrics_metric_type_name_mappings_prometheus[] = { - [METRIC_VALUE_METRIC_TYPE_MONOTONIC] = "counter", - [METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT] = "gauge", +static const char* const metrics_metric_type_name_mappings_prometheus[] = { + [METRIC_VALUE_METRIC_TYPE_MONOTONIC] = "counter", + [METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT] = "gauge", }; namespace libs::metrics { -std::string metric_value_to_text(const metrics_v2& metric) -{ +std::string metric_value_to_text(const metrics_v2& metric) { std::string value_text; - switch (metric.type) - { + switch(metric.type) { case METRIC_VALUE_TYPE_U32: value_text = std::to_string(metric.value.u32); break; @@ -90,93 +94,86 @@ std::string metric_value_to_text(const metrics_v2& metric) return value_text; } -std::string prometheus_sanitize_metric_name(const std::string& name, const RE2& invalid_chars = RE2("[^a-zA-Z0-9_:]")) -{ +std::string prometheus_sanitize_metric_name(const std::string& name, + const RE2& invalid_chars = RE2("[^a-zA-Z0-9_:]")) { // https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels std::string sanitized_name = name; RE2::GlobalReplace(&sanitized_name, invalid_chars, "_"); RE2::GlobalReplace(&sanitized_name, "_+", "_"); // Ensure it starts with a letter or underscore (if empty after sanitizing, set to "_") - if (sanitized_name.empty() || (!std::isalpha(sanitized_name.front()) && sanitized_name.front() != '_')) - { + if(sanitized_name.empty() || + (!std::isalpha(sanitized_name.front()) && sanitized_name.front() != '_')) { sanitized_name = "_" + sanitized_name; } return sanitized_name; } -std::string prometheus_qualifier(std::string_view prometheus_namespace, std::string_view prometheus_subsystem) -{ +std::string prometheus_qualifier(std::string_view prometheus_namespace, + std::string_view prometheus_subsystem) { std::string qualifier; - if (!prometheus_namespace.empty()) - { + if(!prometheus_namespace.empty()) { qualifier += std::string(prometheus_namespace) + "_"; } - if (!prometheus_subsystem.empty()) - { + if(!prometheus_subsystem.empty()) { qualifier += std::string(prometheus_subsystem) + "_"; } return qualifier; } - -std::string prometheus_exposition_text(std::string_view metric_qualified_name, std::string_view metric_name, std::string_view metric_type_name, std::string_view metric_value, const std::map& const_labels) -{ +std::string prometheus_exposition_text(std::string_view metric_qualified_name, + std::string_view metric_name, + std::string_view metric_type_name, + std::string_view metric_value, + const std::map& const_labels) { std::string fqn = prometheus_sanitize_metric_name(std::string(metric_qualified_name)); std::string prometheus_text = "# HELP " + fqn + " https://falco.org/docs/metrics/\n"; prometheus_text += "# TYPE " + fqn + " " + std::string(metric_type_name) + "\n"; prometheus_text += fqn; - if (!const_labels.empty()) - { + if(!const_labels.empty()) { static const RE2 label_invalid_chars("[^a-zA-Z0-9_]"); prometheus_text += "{"; bool first_label = true; - for (const auto& [key, value] : const_labels) - { - if (key.empty()) - { + for(const auto& [key, value] : const_labels) { + if(key.empty()) { continue; } - if (!first_label) - { + if(!first_label) { prometheus_text += ","; - } else - { + } else { first_label = false; } - prometheus_text += prometheus_sanitize_metric_name(key, label_invalid_chars) + "=\"" + value + "\""; + prometheus_text += prometheus_sanitize_metric_name(key, label_invalid_chars) + "=\"" + + value + "\""; } - prometheus_text += "} "; // the white space at the end is important! - } else - { - prometheus_text += " "; // the white space at the end is important! + prometheus_text += "} "; // the white space at the end is important! + } else { + prometheus_text += " "; // the white space at the end is important! } prometheus_text += std::string(metric_value); prometheus_text += "\n"; return prometheus_text; } -std::string metrics_converter::convert_metric_to_text(const metrics_v2& metric) const -{ +std::string metrics_converter::convert_metric_to_text(const metrics_v2& metric) const { return std::string(metric.name) + " " + metric_value_to_text(metric) + "\n"; } -void metrics_converter::convert_metric_to_unit_convention(metrics_v2& /*metric*/) const -{ +void metrics_converter::convert_metric_to_unit_convention(metrics_v2& /*metric*/) const { // Default does nothing } -void output_rule_metrics_converter::convert_metric_to_unit_convention(metrics_v2& metric) const -{ - if((metric.unit == METRIC_VALUE_UNIT_MEMORY_BYTES || metric.unit == METRIC_VALUE_UNIT_MEMORY_KIBIBYTES) && - (metric.type == METRIC_VALUE_TYPE_U32 || metric.type == METRIC_VALUE_TYPE_U64)) - { - if(metric.type == METRIC_VALUE_TYPE_U32) - { - metric.value.d = libs::metrics::convert_memory(metric.unit, METRIC_VALUE_UNIT_MEMORY_MEGABYTES, metric.value.u32); - } - else if(metric.type == METRIC_VALUE_TYPE_U64) - { - metric.value.d = libs::metrics::convert_memory(metric.unit, METRIC_VALUE_UNIT_MEMORY_MEGABYTES, metric.value.u64); +void output_rule_metrics_converter::convert_metric_to_unit_convention(metrics_v2& metric) const { + if((metric.unit == METRIC_VALUE_UNIT_MEMORY_BYTES || + metric.unit == METRIC_VALUE_UNIT_MEMORY_KIBIBYTES) && + (metric.type == METRIC_VALUE_TYPE_U32 || metric.type == METRIC_VALUE_TYPE_U64)) { + if(metric.type == METRIC_VALUE_TYPE_U32) { + metric.value.d = libs::metrics::convert_memory(metric.unit, + METRIC_VALUE_UNIT_MEMORY_MEGABYTES, + metric.value.u32); + } else if(metric.type == METRIC_VALUE_TYPE_U64) { + metric.value.d = libs::metrics::convert_memory(metric.unit, + METRIC_VALUE_UNIT_MEMORY_MEGABYTES, + metric.value.u64); } std::string metric_name_str(metric.name); RE2::GlobalReplace(&metric_name_str, s_libs_metrics_units_memory_suffix, "_mb"); @@ -186,49 +183,61 @@ void output_rule_metrics_converter::convert_metric_to_unit_convention(metrics_v2 } } -std::string prometheus_metrics_converter::convert_metric_to_text_prometheus(const metrics_v2& metric, std::string_view prometheus_namespace, std::string_view prometheus_subsystem, const std::map& const_labels) const -{ - std::string prometheus_metric_name_fully_qualified = prometheus_qualifier(prometheus_namespace, prometheus_subsystem) + std::string(metric.name) + "_"; +std::string prometheus_metrics_converter::convert_metric_to_text_prometheus( + const metrics_v2& metric, + std::string_view prometheus_namespace, + std::string_view prometheus_subsystem, + const std::map& const_labels) const { + std::string prometheus_metric_name_fully_qualified = + prometheus_qualifier(prometheus_namespace, prometheus_subsystem) + + std::string(metric.name) + "_"; // Remove native libs unit suffixes if applicable. - RE2::GlobalReplace(&prometheus_metric_name_fully_qualified, s_libs_metrics_units_suffix_pre_prometheus_text_conversion, ""); - prometheus_metric_name_fully_qualified += std::string(metrics_unit_name_mappings_prometheus[metric.unit]); - return prometheus_exposition_text(prometheus_metric_name_fully_qualified, - metric.name, - metrics_metric_type_name_mappings_prometheus[metric.metric_type], - metric_value_to_text(metric), - const_labels); + RE2::GlobalReplace(&prometheus_metric_name_fully_qualified, + s_libs_metrics_units_suffix_pre_prometheus_text_conversion, + ""); + prometheus_metric_name_fully_qualified += + std::string(metrics_unit_name_mappings_prometheus[metric.unit]); + return prometheus_exposition_text( + prometheus_metric_name_fully_qualified, + metric.name, + metrics_metric_type_name_mappings_prometheus[metric.metric_type], + metric_value_to_text(metric), + const_labels); } -std::string prometheus_metrics_converter::convert_metric_to_text_prometheus(std::string_view metric_name, std::string_view prometheus_namespace, std::string_view prometheus_subsystem, const std::map& const_labels) const -{ - return prometheus_exposition_text(prometheus_qualifier(prometheus_namespace, prometheus_subsystem) + std::string(metric_name) + "_info", - metric_name, - "gauge", - "1", - const_labels); +std::string prometheus_metrics_converter::convert_metric_to_text_prometheus( + std::string_view metric_name, + std::string_view prometheus_namespace, + std::string_view prometheus_subsystem, + const std::map& const_labels) const { + return prometheus_exposition_text( + prometheus_qualifier(prometheus_namespace, prometheus_subsystem) + + std::string(metric_name) + "_info", + metric_name, + "gauge", + "1", + const_labels); } -void prometheus_metrics_converter::convert_metric_to_unit_convention(metrics_v2& metric) const -{ - if((metric.unit == METRIC_VALUE_UNIT_MEMORY_BYTES || metric.unit == METRIC_VALUE_UNIT_MEMORY_KIBIBYTES) && - (metric.type == METRIC_VALUE_TYPE_U32 || metric.type == METRIC_VALUE_TYPE_U64)) - { - if(metric.type == METRIC_VALUE_TYPE_U32) - { - metric.value.d = libs::metrics::convert_memory(metric.unit, METRIC_VALUE_UNIT_MEMORY_BYTES, metric.value.u32); - } - else if(metric.type == METRIC_VALUE_TYPE_U64) - { - metric.value.d = libs::metrics::convert_memory(metric.unit, METRIC_VALUE_UNIT_MEMORY_BYTES, metric.value.u64); +void prometheus_metrics_converter::convert_metric_to_unit_convention(metrics_v2& metric) const { + if((metric.unit == METRIC_VALUE_UNIT_MEMORY_BYTES || + metric.unit == METRIC_VALUE_UNIT_MEMORY_KIBIBYTES) && + (metric.type == METRIC_VALUE_TYPE_U32 || metric.type == METRIC_VALUE_TYPE_U64)) { + if(metric.type == METRIC_VALUE_TYPE_U32) { + metric.value.d = libs::metrics::convert_memory(metric.unit, + METRIC_VALUE_UNIT_MEMORY_BYTES, + metric.value.u32); + } else if(metric.type == METRIC_VALUE_TYPE_U64) { + metric.value.d = libs::metrics::convert_memory(metric.unit, + METRIC_VALUE_UNIT_MEMORY_BYTES, + metric.value.u64); } std::string metric_name_str(metric.name); RE2::GlobalReplace(&metric_name_str, s_libs_metrics_units_memory_suffix, "_bytes"); strlcpy(metric.name, metric_name_str.c_str(), METRIC_NAME_MAX); metric.type = METRIC_VALUE_TYPE_D; metric.unit = METRIC_VALUE_UNIT_MEMORY_BYTES; - } - else if(metric.unit == METRIC_VALUE_UNIT_PERC && metric.type == METRIC_VALUE_TYPE_D) - { + } else if(metric.unit == METRIC_VALUE_UNIT_PERC && metric.type == METRIC_VALUE_TYPE_D) { metric.value.d = metric.value.d / 100.0; std::string metric_name_str(metric.name); RE2::GlobalReplace(&metric_name_str, s_libs_metrics_units_perc_suffix, "_ratio"); @@ -238,49 +247,42 @@ void prometheus_metrics_converter::convert_metric_to_unit_convention(metrics_v2& } } -void libs_resource_utilization::get_rss_vsz_pss_total_memory_and_open_fds() -{ +void libs_resource_utilization::get_rss_vsz_pss_total_memory_and_open_fds() { FILE* f; char filepath[512]; char line[512]; /* * Get memory usage of the agent itself (referred to as calling process meaning /proc/self/) - */ + */ - // No need for scap_get_host_root since we look at the agents' own process, accessible from it's own pid namespace (if applicable) + // No need for scap_get_host_root since we look at the agents' own process, accessible from + // it's own pid namespace (if applicable) f = fopen("/proc/self/status", "r"); - if(!f) - { + if(!f) { return; } - while(fgets(line, sizeof(line), f) != nullptr) - { - if(strncmp(line, "VmSize:", 7) == 0) - { - sscanf(line, "VmSize: %" SCNu32, &m_vsz); /* memory size returned in kb */ - } - else if(strncmp(line, "VmRSS:", 6) == 0) - { - sscanf(line, "VmRSS: %" SCNu32, &m_rss); /* memory size returned in kb */ + while(fgets(line, sizeof(line), f) != nullptr) { + if(strncmp(line, "VmSize:", 7) == 0) { + sscanf(line, "VmSize: %" SCNu32, &m_vsz); /* memory size returned in kb */ + } else if(strncmp(line, "VmRSS:", 6) == 0) { + sscanf(line, "VmRSS: %" SCNu32, &m_rss); /* memory size returned in kb */ } } fclose(f); - // No need for scap_get_host_root since we look at the agents' own process, accessible from it's own pid namespace (if applicable) + // No need for scap_get_host_root since we look at the agents' own process, accessible from + // it's own pid namespace (if applicable) f = fopen("/proc/self/smaps_rollup", "r"); - if(!f) - { + if(!f) { ASSERT(false); return; } - while(fgets(line, sizeof(line), f) != NULL) - { - if(strncmp(line, "Pss:", 4) == 0) - { - sscanf(line, "Pss: %" SCNu32, &m_pss); /* memory size returned in kb */ + while(fgets(line, sizeof(line), f) != NULL) { + if(strncmp(line, "Pss:", 4) == 0) { + sscanf(line, "Pss: %" SCNu32, &m_pss); /* memory size returned in kb */ break; } } @@ -288,36 +290,27 @@ void libs_resource_utilization::get_rss_vsz_pss_total_memory_and_open_fds() /* * Get total host memory usage - */ + */ // Using scap_get_host_root since we look at the memory usage of the underlying host snprintf(filepath, sizeof(filepath), "%s/proc/meminfo", scap_get_host_root()); f = fopen(filepath, "r"); - if(!f) - { + if(!f) { ASSERT(false); return; } uint64_t mem_total, mem_free, mem_buff, mem_cache = 0; - while(fgets(line, sizeof(line), f) != NULL) - { - if(strncmp(line, "MemTotal:", 9) == 0) - { - sscanf(line, "MemTotal: %" SCNu64, &mem_total); /* memory size returned in kb */ - } - else if(strncmp(line, "MemFree:", 8) == 0) - { - sscanf(line, "MemFree: %" SCNu64, &mem_free); /* memory size returned in kb */ - } - else if(strncmp(line, "Buffers:", 8) == 0) - { - sscanf(line, "Buffers: %" SCNu64, &mem_buff); /* memory size returned in kb */ - } - else if(strncmp(line, "Cached:", 7) == 0) - { - sscanf(line, "Cached: %" SCNu64, &mem_cache); /* memory size returned in kb */ + while(fgets(line, sizeof(line), f) != NULL) { + if(strncmp(line, "MemTotal:", 9) == 0) { + sscanf(line, "MemTotal: %" SCNu64, &mem_total); /* memory size returned in kb */ + } else if(strncmp(line, "MemFree:", 8) == 0) { + sscanf(line, "MemFree: %" SCNu64, &mem_free); /* memory size returned in kb */ + } else if(strncmp(line, "Buffers:", 8) == 0) { + sscanf(line, "Buffers: %" SCNu64, &mem_buff); /* memory size returned in kb */ + } else if(strncmp(line, "Cached:", 7) == 0) { + sscanf(line, "Cached: %" SCNu64, &mem_cache); /* memory size returned in kb */ } } fclose(f); @@ -326,42 +319,38 @@ void libs_resource_utilization::get_rss_vsz_pss_total_memory_and_open_fds() /* * Get total number of allocated file descriptors (not all open files!) * File descriptor is a data structure used by a program to get a handle on a file - */ + */ // Using scap_get_host_root since we look at the total open fds of the underlying host snprintf(filepath, sizeof(filepath), "%s/proc/sys/fs/file-nr", scap_get_host_root()); f = fopen(filepath, "r"); - if(!f) - { + if(!f) { ASSERT(false); return; } int matched_fds = fscanf(f, "%" SCNu64, &m_host_open_fds); fclose(f); - if (matched_fds != 1) { + if(matched_fds != 1) { ASSERT(false); return; } } -void libs_resource_utilization::get_cpu_usage_and_total_procs(double start_time) -{ +void libs_resource_utilization::get_cpu_usage_and_total_procs(double start_time) { FILE* f; char filepath[512]; char line[512]; struct tms time; - if (times (&time) == (clock_t) -1) - { + if(times(&time) == (clock_t)-1) { return; } /* Number of clock ticks per second, often referred to as USER_HZ / jiffies. */ long hz = 100; #ifdef _SC_CLK_TCK - if ((hz = sysconf(_SC_CLK_TCK)) < 0) - { + if((hz = sysconf(_SC_CLK_TCK)) < 0) { ASSERT(false); hz = 100; } @@ -373,8 +362,7 @@ void libs_resource_utilization::get_cpu_usage_and_total_procs(double start_time) // Using scap_get_host_root since we look at the uptime of the underlying host snprintf(filepath, sizeof(filepath), "%s/proc/uptime", scap_get_host_root()); f = fopen(filepath, "r"); - if(!f) - { + if(!f) { ASSERT(false); return; } @@ -383,173 +371,174 @@ void libs_resource_utilization::get_cpu_usage_and_total_procs(double start_time) int matched_uptime = fscanf(f, "%lf", &machine_uptime_sec); fclose(f); - if (matched_uptime != 1) { + if(matched_uptime != 1) { ASSERT(false); return; } /* * Get CPU usage of the agent itself (referred to as calling process meaning /proc/self/) - */ + */ - /* Current utime is amount of processor time in user mode of calling process. Convert to seconds. */ + /* Current utime is amount of processor time in user mode of calling process. Convert to + * seconds. */ double user_sec = (double)time.tms_utime / hz; - /* Current stime is amount of time the calling process has been scheduled in kernel mode. Convert to seconds. */ + /* Current stime is amount of time the calling process has been scheduled in kernel mode. + * Convert to seconds. */ double system_sec = (double)time.tms_stime / hz; - /* CPU usage as percentage is computed by dividing the time the process uses the CPU by the * currently elapsed time of the calling process. Compare to `ps` linux util. */ double elapsed_sec = machine_uptime_sec - start_time; - if (elapsed_sec > 0) - { + if(elapsed_sec > 0) { m_cpu_usage_perc = (double)100.0 * (user_sec + system_sec) / elapsed_sec; - m_cpu_usage_perc = std::round(m_cpu_usage_perc * 10.0) / 10.0; // round to 1 decimal + m_cpu_usage_perc = std::round(m_cpu_usage_perc * 10.0) / 10.0; // round to 1 decimal } /* - * Get total host CPU usage (all CPUs) as percentage and retrieve number of procs currently running. - */ + * Get total host CPU usage (all CPUs) as percentage and retrieve number of procs currently + * running. + */ // Using scap_get_host_root since we look at the total CPU usage of the underlying host snprintf(filepath, sizeof(filepath), "%s/proc/stat", scap_get_host_root()); f = fopen(filepath, "r"); - if(!f) - { + if(!f) { ASSERT(false); return; } /* Need only first 7 columns of /proc/stat cpu line */ uint64_t user, nice, system, idle, iowait, irq, softirq = 0; - while(fgets(line, sizeof(line), f) != NULL) - { - if(strncmp(line, "cpu ", 4) == 0) - { + while(fgets(line, sizeof(line), f) != NULL) { + if(strncmp(line, "cpu ", 4) == 0) { /* Always first line in /proc/stat file, unit: jiffies */ - sscanf(line, "cpu %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64, &user, &nice, &system, &idle, &iowait, &irq, &softirq); - } - else if(strncmp(line, "procs_running ", 14) == 0) - { + sscanf(line, + "cpu %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 + " %" SCNu64, + &user, + &nice, + &system, + &idle, + &iowait, + &irq, + &softirq); + } else if(strncmp(line, "procs_running ", 14) == 0) { sscanf(line, "procs_running %" SCNu32, &m_host_procs_running); break; } } fclose(f); auto sum = user + nice + system + idle + iowait + irq + softirq; - if (sum > 0) - { + if(sum > 0) { m_host_cpu_usage_perc = 100.0 - ((idle * 100.0) / sum); - m_host_cpu_usage_perc = std::round(m_host_cpu_usage_perc * 10.0) / 10.0; // round to 1 decimal + m_host_cpu_usage_perc = + std::round(m_host_cpu_usage_perc * 10.0) / 10.0; // round to 1 decimal } } -std::vector libs_resource_utilization::to_metrics() -{ +std::vector libs_resource_utilization::to_metrics() { std::vector metrics; metrics.emplace_back(new_metric("cpu_usage_perc", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_D, - METRIC_VALUE_UNIT_PERC, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_cpu_usage_perc)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_D, + METRIC_VALUE_UNIT_PERC, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_cpu_usage_perc)); metrics.emplace_back(new_metric("memory_rss_kb", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_rss)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_rss)); metrics.emplace_back(new_metric("memory_vsz_kb", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_vsz)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_vsz)); metrics.emplace_back(new_metric("memory_pss_kb", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_pss)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_pss)); metrics.emplace_back(new_metric("container_memory_used_bytes", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_MEMORY_BYTES, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_container_memory_used)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_MEMORY_BYTES, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_container_memory_used)); metrics.emplace_back(new_metric("host_cpu_usage_perc", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_D, - METRIC_VALUE_UNIT_PERC, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_host_cpu_usage_perc)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_D, + METRIC_VALUE_UNIT_PERC, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_host_cpu_usage_perc)); metrics.emplace_back(new_metric("host_memory_used_kb", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_host_memory_used)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_host_memory_used)); metrics.emplace_back(new_metric("host_procs_running", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_host_procs_running)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_host_procs_running)); metrics.emplace_back(new_metric("host_open_fds", - METRICS_V2_RESOURCE_UTILIZATION, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_host_open_fds)); + METRICS_V2_RESOURCE_UTILIZATION, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_host_open_fds)); return metrics; } -void libs_resource_utilization::get_container_memory_used() -{ +void libs_resource_utilization::get_container_memory_used() { /* In Kubernetes `container_memory_working_set_bytes` is the memory measure the OOM killer uses * and values from `/sys/fs/cgroup/memory/memory.usage_in_bytes` are close enough. * * Please note that `kubectl top pod` numbers would reflect the sum of containers in a pod and * typically libs clients (e.g. Falco) pods contain sidekick containers that use memory as well. * This metric accounts only for the container with the security monitoring agent running. - */ + */ const char* filepath = getenv(SINSP_AGENT_CGROUP_MEM_PATH_ENV_VAR); - if (filepath == nullptr) - { - // No need for scap_get_host_root since we look at the container pid namespace (if applicable) - // Known collision for VM memory usage, but this default value is configurable + if(filepath == nullptr) { + // No need for scap_get_host_root since we look at the container pid namespace (if + // applicable) Known collision for VM memory usage, but this default value is configurable filepath = "/sys/fs/cgroup/memory/memory.usage_in_bytes"; } FILE* f = fopen(filepath, "r"); - if(!f) - { + if(!f) { return; } /* memory size returned in bytes */ int fscanf_matched = fscanf(f, "%" SCNu64, &m_container_memory_used); - if (fscanf_matched != 1) - { + if(fscanf_matched != 1) { m_container_memory_used = 0; } fclose(f); } -libs_state_counters::libs_state_counters(const std::shared_ptr& sinsp_stats_v2, sinsp_thread_manager* thread_manager) : m_sinsp_stats_v2(sinsp_stats_v2), m_n_fds(0), m_n_threads(0) { - if (thread_manager != nullptr) - { +libs_state_counters::libs_state_counters(const std::shared_ptr& sinsp_stats_v2, + sinsp_thread_manager* thread_manager): + m_sinsp_stats_v2(sinsp_stats_v2), + m_n_fds(0), + m_n_threads(0) { + if(thread_manager != nullptr) { m_n_threads = thread_manager->get_thread_count(); threadinfo_map_t* threadtable = thread_manager->get_threads(); - if (threadtable != nullptr) - { - threadtable->loop([this] (sinsp_threadinfo& tinfo) { + if(threadtable != nullptr) { + threadtable->loop([this](sinsp_threadinfo& tinfo) { sinsp_fdtable* fdtable = tinfo.get_fd_table(); - if (fdtable != nullptr) - { + if(fdtable != nullptr) { this->m_n_fds += fdtable->size(); } return true; @@ -558,137 +547,134 @@ libs_state_counters::libs_state_counters(const std::shared_ptr& } } -std::vector libs_state_counters::to_metrics() -{ +std::vector libs_state_counters::to_metrics() { std::vector metrics; metrics.emplace_back(new_metric("n_threads", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_n_threads)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_n_threads)); metrics.emplace_back(new_metric("n_fds", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_n_fds)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_n_fds)); - if (m_sinsp_stats_v2 == nullptr) { + if(m_sinsp_stats_v2 == nullptr) { return metrics; } metrics.emplace_back(new_metric("n_noncached_fd_lookups", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_noncached_fd_lookups)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_noncached_fd_lookups)); metrics.emplace_back(new_metric("n_cached_fd_lookups", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_cached_fd_lookups)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_cached_fd_lookups)); metrics.emplace_back(new_metric("n_failed_fd_lookups", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_failed_fd_lookups)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_failed_fd_lookups)); metrics.emplace_back(new_metric("n_added_fds", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_added_fds)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_added_fds)); metrics.emplace_back(new_metric("n_removed_fds", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_removed_fds)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_removed_fds)); metrics.emplace_back(new_metric("n_stored_evts", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_stored_evts)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_stored_evts)); metrics.emplace_back(new_metric("n_store_evts_drops", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_store_evts_drops)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_store_evts_drops)); metrics.emplace_back(new_metric("n_retrieved_evts", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_retrieved_evts)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_retrieved_evts)); metrics.emplace_back(new_metric("n_retrieve_evts_drops", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_retrieve_evts_drops)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_retrieve_evts_drops)); metrics.emplace_back(new_metric("n_noncached_thread_lookups", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_noncached_thread_lookups)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_noncached_thread_lookups)); metrics.emplace_back(new_metric("n_cached_thread_lookups", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_cached_thread_lookups)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_cached_thread_lookups)); metrics.emplace_back(new_metric("n_failed_thread_lookups", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_failed_thread_lookups)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_failed_thread_lookups)); metrics.emplace_back(new_metric("n_added_threads", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_added_threads)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_added_threads)); metrics.emplace_back(new_metric("n_removed_threads", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_removed_threads)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_removed_threads)); metrics.emplace_back(new_metric("n_drops_full_threadtable", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - m_sinsp_stats_v2->m_n_drops_full_threadtable)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + m_sinsp_stats_v2->m_n_drops_full_threadtable)); metrics.emplace_back(new_metric("n_missing_container_images", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_sinsp_stats_v2->m_n_missing_container_images)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_sinsp_stats_v2->m_n_missing_container_images)); metrics.emplace_back(new_metric("n_containers", - METRICS_V2_STATE_COUNTERS, - METRIC_VALUE_TYPE_U32, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - m_sinsp_stats_v2->m_n_containers)); + METRICS_V2_STATE_COUNTERS, + METRIC_VALUE_TYPE_U32, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + m_sinsp_stats_v2->m_n_containers)); return metrics; } -void libs_metrics_collector::snapshot() -{ +void libs_metrics_collector::snapshot() { m_metrics.clear(); - if (!m_inspector) - { + if(!m_inspector) { return; } @@ -696,15 +682,17 @@ void libs_metrics_collector::snapshot() * libscap metrics */ - if((m_metrics_flags & METRICS_V2_KERNEL_COUNTERS) || (m_metrics_flags & METRICS_V2_LIBBPF_STATS) || (m_metrics_flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) - { + if((m_metrics_flags & METRICS_V2_KERNEL_COUNTERS) || + (m_metrics_flags & METRICS_V2_LIBBPF_STATS) || + (m_metrics_flags & METRICS_V2_KERNEL_COUNTERS_PER_CPU)) { uint32_t nstats = 0; int32_t rc = 0; // libscap metrics: m_metrics_flags are pushed down from consumers' input, - // libbpf stats only collected when ENGINE_FLAG_BPF_STATS_ENABLED aka `kernel.bpf_stats_enabled = 1` - const metrics_v2* metrics_v2_scap_snapshot = m_inspector->get_capture_stats_v2(m_metrics_flags, &nstats, &rc); - if (metrics_v2_scap_snapshot && nstats > 0 && rc == 0) - { + // libbpf stats only collected when ENGINE_FLAG_BPF_STATS_ENABLED aka + // `kernel.bpf_stats_enabled = 1` + const metrics_v2* metrics_v2_scap_snapshot = + m_inspector->get_capture_stats_v2(m_metrics_flags, &nstats, &rc); + if(metrics_v2_scap_snapshot && nstats > 0 && rc == 0) { // Move existing scap metrics raw buffer into m_metrics vector m_metrics.assign(metrics_v2_scap_snapshot, metrics_v2_scap_snapshot + nstats); } @@ -713,58 +701,48 @@ void libs_metrics_collector::snapshot() /* * libsinsp metrics */ - if((m_metrics_flags & METRICS_V2_RESOURCE_UTILIZATION)) - { + if((m_metrics_flags & METRICS_V2_RESOURCE_UTILIZATION)) { const scap_agent_info* agent_info = m_inspector->get_agent_info(); libs_resource_utilization resource_utilization(agent_info->start_time); std::vector ru_metrics = resource_utilization.to_metrics(); m_metrics.insert(m_metrics.end(), ru_metrics.begin(), ru_metrics.end()); } - if((m_metrics_flags & METRICS_V2_STATE_COUNTERS)) - { + if((m_metrics_flags & METRICS_V2_STATE_COUNTERS)) { libs_state_counters state_counters(m_sinsp_stats_v2, m_inspector->m_thread_manager.get()); std::vector sc_metrics = state_counters.to_metrics(); m_metrics.insert(m_metrics.end(), sc_metrics.begin(), sc_metrics.end()); } /* - * plugins metrics - */ - if(m_metrics_flags & METRICS_V2_PLUGINS) - { - for (auto& p : m_inspector->get_plugin_manager()->plugins()) - { + * plugins metrics + */ + if(m_metrics_flags & METRICS_V2_PLUGINS) { + for(auto& p : m_inspector->get_plugin_manager()->plugins()) { std::vector plugin_metrics = p->get_metrics(); m_metrics.insert(m_metrics.end(), plugin_metrics.begin(), plugin_metrics.end()); } } } -const std::vector& libs_metrics_collector::get_metrics() const -{ +const std::vector& libs_metrics_collector::get_metrics() const { return m_metrics; } -std::vector& libs_metrics_collector::get_metrics() -{ +std::vector& libs_metrics_collector::get_metrics() { return m_metrics; } -libs_metrics_collector::libs_metrics_collector(sinsp* inspector, uint32_t flags) : - m_inspector(inspector), - m_metrics_flags(flags) -{ - if (m_inspector != nullptr) - { +libs_metrics_collector::libs_metrics_collector(sinsp* inspector, uint32_t flags): + m_inspector(inspector), + m_metrics_flags(flags) { + if(m_inspector != nullptr) { m_sinsp_stats_v2 = m_inspector->get_sinsp_stats_v2(); - } - else - { + } else { m_sinsp_stats_v2 = nullptr; } } -} // namespace libs::metrics +} // namespace libs::metrics #endif diff --git a/userspace/libsinsp/metrics_collector.h b/userspace/libsinsp/metrics_collector.h index 654081336b..34669d4e73 100644 --- a/userspace/libsinsp/metrics_collector.h +++ b/userspace/libsinsp/metrics_collector.h @@ -27,8 +27,7 @@ limitations under the License. #include #include -struct sinsp_stats_v2 -{ +struct sinsp_stats_v2 { ///@( /** fdtable state related counters, unit: count. */ uint64_t m_n_noncached_fd_lookups; @@ -52,22 +51,26 @@ struct sinsp_stats_v2 uint64_t m_n_added_threads; uint64_t m_n_removed_threads; ///@) - uint32_t m_n_drops_full_threadtable; ///< Number of drops due to full threadtable, unit: count. - uint32_t m_n_missing_container_images; ///< Number of cached containers (cgroups) without container info such as image, hijacked sinsp_container_manager::remove_inactive_containers() -> every flush snapshot update, unit: count. - uint32_t m_n_containers; ///< Number of containers (cgroups) currently cached by sinsp_container_manager, hijacked sinsp_container_manager::remove_inactive_containers() -> every flush snapshot update, unit: count. + uint32_t m_n_drops_full_threadtable; ///< Number of drops due to full threadtable, unit: count. + uint32_t + m_n_missing_container_images; ///< Number of cached containers (cgroups) without + ///< container info such as image, hijacked + ///< sinsp_container_manager::remove_inactive_containers() + ///< -> every flush snapshot update, unit: count. + uint32_t m_n_containers; ///< Number of containers (cgroups) currently cached by + ///< sinsp_container_manager, hijacked + ///< sinsp_container_manager::remove_inactive_containers() -> every + ///< flush snapshot update, unit: count. }; #ifdef __linux__ -namespace libs::metrics -{ +namespace libs::metrics { -template -double convert_memory(metrics_v2_value_unit source_unit, metrics_v2_value_unit dest_unit, T val) -{ +template +double convert_memory(metrics_v2_value_unit source_unit, metrics_v2_value_unit dest_unit, T val) { double factor = 1; - switch(source_unit) - { + switch(source_unit) { case METRIC_VALUE_UNIT_MEMORY_BYTES: factor = 1; break; @@ -82,21 +85,19 @@ double convert_memory(metrics_v2_value_unit source_unit, metrics_v2_value_unit d } double bytes_val = val * factor; - switch(dest_unit) - { + switch(dest_unit) { case METRIC_VALUE_UNIT_MEMORY_BYTES: return bytes_val; case METRIC_VALUE_UNIT_MEMORY_KIBIBYTES: - return std::round((bytes_val / 1024.) * 10.) / 10.; // round to 1 decimal + return std::round((bytes_val / 1024.) * 10.) / 10.; // round to 1 decimal case METRIC_VALUE_UNIT_MEMORY_MEGABYTES: - return std::round((bytes_val / 1024. / 1024.) * 10.) / 10.; // round to 1 decimal + return std::round((bytes_val / 1024. / 1024.) * 10.) / 10.; // round to 1 decimal default: return 0; } } -class metrics_converter -{ +class metrics_converter { public: virtual ~metrics_converter() = default; @@ -106,32 +107,42 @@ class metrics_converter }; // Subclass for Prometheus-specific metric conversion -class prometheus_metrics_converter : public metrics_converter -{ +class prometheus_metrics_converter : public metrics_converter { public: - /*! \brief Method to convert a metrics_v2 metric to the text-based Prometheus exposition format. * - * Reference: https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md - * Note: The design idea is to expose Prometheus metrics by piping text-based formats to new line-delimited fields - * exposed at /metrics in Falco's existing HTTP webserver (w/ optional mTLS support), eliminating the need for implementing + * Reference: + https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md + * Note: The design idea is to expose Prometheus metrics by piping text-based formats to new + line-delimited fields + * exposed at /metrics in Falco's existing HTTP webserver (w/ optional mTLS support), + eliminating the need for implementing * a complete Prometheus client. * - * We exclusively support counter and gauge Prometheus metric types, covering metrics from kernel driver tracepoints - * to linsinsp and client metrics. Introducing a registry seems excessive, especially given the dynamic nature of the final + * We exclusively support counter and gauge Prometheus metric types, covering metrics from + kernel driver tracepoints + * to linsinsp and client metrics. Introducing a registry seems excessive, especially given the + dynamic nature of the final * metric string names, such as variations in tracepoints across architectures. - * Considering the simplistic use case, adding another dependency to the project does not seem justified. Furthermore, for C++ - * (compared to Go for example), there appear to be fewer formal client library projects available. Plus, we need to think + * Considering the simplistic use case, adding another dependency to the project does not seem + justified. Furthermore, for C++ + * (compared to Go for example), there appear to be fewer formal client library projects + available. Plus, we need to think * about stability and long-term support before adding any new dependency. * - * The final fully qualified Prometheus metric name partially follows https://prometheus.io/docs/practices/naming/ - * Prepend namespace and subsystem with "_" delimiter to create a fully qualified metric name according to - * https://pkg.go.dev/github.com/prometheus/client_golang/prometheus#Opts + append unit with "_" delimiter - * We do not strictly follow and enforce the concept of base_units, but guarantee no units are mixed per unique + * The final fully qualified Prometheus metric name partially follows + https://prometheus.io/docs/practices/naming/ + * Prepend namespace and subsystem with "_" delimiter to create a fully qualified metric name + according to + * https://pkg.go.dev/github.com/prometheus/client_golang/prometheus#Opts + append unit with "_" + delimiter + * We do not strictly follow and enforce the concept of base_units, but guarantee no units are + mixed per unique * `prometheus_metric_name_fully_qualified` * - * We are monitoring updates wrt https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md + * We are monitoring updates wrt + https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md * * Example: * @@ -145,22 +156,33 @@ class prometheus_metrics_converter : public metrics_converter * This method is a work in progress. * * @param metric metrics_v2 metric - * @param prometheus_namespace first component of `prometheus_metric_name_fully_qualified` (optional) - * @param prometheus_subsystem second component of `prometheus_metric_name_fully_qualified` (optional) + * @param prometheus_namespace first component of `prometheus_metric_name_fully_qualified` + (optional) + * @param prometheus_subsystem second component of `prometheus_metric_name_fully_qualified` + (optional) * @param const_labels map of additional labels (rarely used for a metrics_v2 metric) * @return Complete new line delimited text-based Prometheus exposition format metric string - * w/ a `prometheus_metric_name_fully_qualified` - optional components prepended to and unit appended to. - * 3-lines including # HELP and # TYPE lines followed by the metric line, raw metric name always present as label. + * w/ a `prometheus_metric_name_fully_qualified` - optional components prepended to and unit + appended to. + * 3-lines including # HELP and # TYPE lines followed by the metric line, raw metric name always + present as label. */ - std::string convert_metric_to_text_prometheus(const metrics_v2& metric, std::string_view prometheus_namespace = "", std::string_view prometheus_subsystem = "", const std::map& const_labels = {}) const; + std::string convert_metric_to_text_prometheus( + const metrics_v2& metric, + std::string_view prometheus_namespace = "", + std::string_view prometheus_subsystem = "", + const std::map& const_labels = {}) const; /*! - \brief Overloaded method to convert a pseudo-metric / software version like metric_name to the text-based Prometheus exposition format. + \brief Overloaded method to convert a pseudo-metric / software version like metric_name to the + text-based Prometheus exposition format. * * Note: Instead of using const_labels, which is a rare use case according to * https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels, - * exposing an overload to support metrics similar to https://www.robustperception.io/exposing-the-software-version-to-prometheus/. - * This approach is applicable to https://falco.org/docs/metrics/, such as Falco's "Base Fields" like + * exposing an overload to support metrics similar to + https://www.robustperception.io/exposing-the-software-version-to-prometheus/. + * This approach is applicable to https://falco.org/docs/metrics/, such as Falco's "Base Fields" + like * falco.kernel_release and falco.version. * * Example: @@ -170,37 +192,46 @@ class prometheus_metrics_converter : public metrics_converter * testns_falco_kernel_release_info{raw_name="kernel_release",kernel_release="6.6.7-200.fc39.x86_64"} 1 * * @param metric_name raw metric name - * @param prometheus_namespace first component of `prometheus_metric_name_fully_qualified` (optional) - * @param prometheus_subsystem second component of `prometheus_metric_name_fully_qualified` (optional) - * @param const_labels map of additional labels (typically used in software version like metrics) + * @param prometheus_namespace first component of `prometheus_metric_name_fully_qualified` + (optional) + * @param prometheus_subsystem second component of `prometheus_metric_name_fully_qualified` + (optional) + * @param const_labels map of additional labels (typically used in software version like + metrics) * @return Complete new line delimited text-based Prometheus exposition format metric string - * w/ a `prometheus_metric_name_fully_qualified` - optional components prepended to and unit appended to. - * 3-lines including # HELP and # TYPE lines followed by the metric line, raw metric name always present as label. + * w/ a `prometheus_metric_name_fully_qualified` - optional components prepended to and unit + appended to. + * 3-lines including # HELP and # TYPE lines followed by the metric line, raw metric name always + present as label. */ - std::string convert_metric_to_text_prometheus(std::string_view metric_name, std::string_view prometheus_namespace = "", std::string_view prometheus_subsystem = "", const std::map& const_labels = {}) const; + std::string convert_metric_to_text_prometheus( + std::string_view metric_name, + std::string_view prometheus_namespace = "", + std::string_view prometheus_subsystem = "", + const std::map& const_labels = {}) const; /*! - * \brief Method to convert metric units to Prometheus base units. - * - * \note Metric names shall be updated within this method, and the respective Prometheus-compliant - * unit suffix shall be added. Prometheus compliance means every metric name has a unit suffix, see - * https://prometheus.io/docs/practices/naming/ or https://prometheus.io/docs/practices/naming/#base-units. - * We conform to the best practices except for keeping libbpf stats metrics and timestamps in nanoseconds - * to avoid precision loss when converting them to seconds. - * Please note that, for example, even cAdvisor sometimes deviates from the standards, e.g., - * `container_memory_rss` instead of `container_memory_rss_bytes`. - * `metric.unit` is also modified and always matches the metric name unit suffix. - * - * In summary, effectively for Falco/libs, it just means converting all memory to bytes and CPU usage to a ratio. - */ + * \brief Method to convert metric units to Prometheus base units. + * + * \note Metric names shall be updated within this method, and the respective + * Prometheus-compliant unit suffix shall be added. Prometheus compliance means every metric + * name has a unit suffix, see https://prometheus.io/docs/practices/naming/ or + * https://prometheus.io/docs/practices/naming/#base-units. We conform to the best practices + * except for keeping libbpf stats metrics and timestamps in nanoseconds to avoid precision loss + * when converting them to seconds. Please note that, for example, even cAdvisor sometimes + * deviates from the standards, e.g., `container_memory_rss` instead of + * `container_memory_rss_bytes`. `metric.unit` is also modified and always matches the metric + * name unit suffix. + * + * In summary, effectively for Falco/libs, it just means converting all memory to bytes and CPU + * usage to a ratio. + */ void convert_metric_to_unit_convention(metrics_v2& metric) const override; }; // Subclass for output_rule-specific metric conversion -class output_rule_metrics_converter : public metrics_converter -{ +class output_rule_metrics_converter : public metrics_converter { public: - /*! \brief Method to convert metric units of memory-related metrics to mb * @@ -211,36 +242,33 @@ class output_rule_metrics_converter : public metrics_converter void convert_metric_to_unit_convention(metrics_v2& metric) const override; }; -class libsinsp_metrics -{ +class libsinsp_metrics { public: - template - static void set_metric_value(metrics_v2& metric, metrics_v2_value_type type, T val) - { - switch (type) - { - case METRIC_VALUE_TYPE_U32: - metric.value.u32 = static_cast(val); + template + static void set_metric_value(metrics_v2& metric, metrics_v2_value_type type, T val) { + switch(type) { + case METRIC_VALUE_TYPE_U32: + metric.value.u32 = static_cast(val); break; - case METRIC_VALUE_TYPE_S32: - metric.value.s32 = static_cast(val); + case METRIC_VALUE_TYPE_S32: + metric.value.s32 = static_cast(val); break; - case METRIC_VALUE_TYPE_U64: - metric.value.u64 = static_cast(val); + case METRIC_VALUE_TYPE_U64: + metric.value.u64 = static_cast(val); break; - case METRIC_VALUE_TYPE_S64: - metric.value.s64 = static_cast(val); + case METRIC_VALUE_TYPE_S64: + metric.value.s64 = static_cast(val); break; - case METRIC_VALUE_TYPE_D: - metric.value.d = static_cast(val); + case METRIC_VALUE_TYPE_D: + metric.value.d = static_cast(val); break; - case METRIC_VALUE_TYPE_F: - metric.value.f = static_cast(val); + case METRIC_VALUE_TYPE_F: + metric.value.f = static_cast(val); break; - case METRIC_VALUE_TYPE_I: - metric.value.i = static_cast(val); + case METRIC_VALUE_TYPE_I: + metric.value.i = static_cast(val); break; - default: + default: break; } } @@ -248,9 +276,13 @@ class libsinsp_metrics /*! \brief Method to create a new metrics_v2 */ - template - static inline metrics_v2 new_metric(const char* name, uint32_t flags, metrics_v2_value_type type, metrics_v2_value_unit unit, metrics_v2_metric_type metric_type, T val) - { + template + static inline metrics_v2 new_metric(const char* name, + uint32_t flags, + metrics_v2_value_type type, + metrics_v2_value_unit unit, + metrics_v2_metric_type metric_type, + T val) { metrics_v2 metric; strlcpy(metric.name, name, METRIC_NAME_MAX); metric.flags = flags; @@ -268,14 +300,11 @@ class libsinsp_metrics libsinsp_metrics& operator=(libsinsp_metrics&&) = delete; virtual ~libsinsp_metrics() = default; virtual std::vector to_metrics() = 0; - }; -class libs_resource_utilization : libsinsp_metrics -{ +class libs_resource_utilization : libsinsp_metrics { public: - libs_resource_utilization(double start_time) - { + libs_resource_utilization(double start_time) { get_cpu_usage_and_total_procs(start_time); get_rss_vsz_pss_total_memory_and_open_fds(); get_container_memory_used(); @@ -288,41 +317,55 @@ class libs_resource_utilization : libsinsp_metrics void get_rss_vsz_pss_total_memory_and_open_fds(); void get_container_memory_used(); - double m_cpu_usage_perc{}; ///< Current CPU usage, `ps` util like calculation for the calling process (/proc/self), unit: percentage of one CPU. - - uint32_t m_rss{}; ///< Current RSS (Resident Set Size), calculated based on /proc/self/status info, unit: kb. - uint32_t m_vsz{}; ///< Current VSZ (Virtual Memory Size), calculated based on /proc/self/status info, unit: kb. - uint32_t m_pss{}; ///< Current PSS (Proportional Set Size), calculated based on /proc/self/smaps_rollup info, unit: kb. - - uint64_t m_container_memory_used{}; ///< Cgroup current memory used, default Kubernetes /sys/fs/cgroup/memory/memory.usage_in_bytes, unit: bytes. - - double m_host_cpu_usage_perc{}; ///< Current total host CPU usage (all CPUs), calculated based on ${HOST_ROOT}/proc/stat info, unit: percentage. - uint64_t m_host_memory_used{}; ///< Current total memory used out of available host memory, calculated based on ${HOST_ROOT}/proc/meminfo info, unit: kb. - uint32_t m_host_procs_running{}; ///< Number of processes currently running on CPUs on the host, retrieved from ${HOST_ROOT}/proc/stat line `procs_running`, unit: count. - uint64_t m_host_open_fds{}; ///< Number of allocated fds on the host, retrieved from ${HOST_ROOT}/proc/sys/fs/file-nr, unit: count. + double m_cpu_usage_perc{}; ///< Current CPU usage, `ps` util like calculation for the calling + ///< process (/proc/self), unit: percentage of one CPU. + + uint32_t m_rss{}; ///< Current RSS (Resident Set Size), calculated based on /proc/self/status + ///< info, unit: kb. + uint32_t m_vsz{}; ///< Current VSZ (Virtual Memory Size), calculated based on /proc/self/status + ///< info, unit: kb. + uint32_t m_pss{}; ///< Current PSS (Proportional Set Size), calculated based on + ///< /proc/self/smaps_rollup info, unit: kb. + + uint64_t m_container_memory_used{}; ///< Cgroup current memory used, default Kubernetes + ///< /sys/fs/cgroup/memory/memory.usage_in_bytes, unit: + ///< bytes. + + double m_host_cpu_usage_perc{}; ///< Current total host CPU usage (all CPUs), calculated based + ///< on ${HOST_ROOT}/proc/stat info, unit: percentage. + uint64_t m_host_memory_used{}; ///< Current total memory used out of available host memory, + ///< calculated based on ${HOST_ROOT}/proc/meminfo info, unit: + ///< kb. + uint32_t m_host_procs_running{}; ///< Number of processes currently running on CPUs on the + ///< host, retrieved from ${HOST_ROOT}/proc/stat line + ///< `procs_running`, unit: count. + uint64_t m_host_open_fds{}; ///< Number of allocated fds on the host, retrieved from + ///< ${HOST_ROOT}/proc/sys/fs/file-nr, unit: count. }; -class libs_state_counters : libsinsp_metrics -{ +class libs_state_counters : libsinsp_metrics { public: - libs_state_counters(const std::shared_ptr& sinsp_stats_v2, sinsp_thread_manager* thread_manager); + libs_state_counters(const std::shared_ptr& sinsp_stats_v2, + sinsp_thread_manager* thread_manager); std::vector to_metrics() override; private: std::shared_ptr m_sinsp_stats_v2; - uint64_t m_n_fds; ///< Total number of fds currently stored across all threadtables associated with each active thread in the sinsp state thread table, unit: count. - uint64_t m_n_threads; ///< Total number of threads currently stored in the sinsp state thread table, unit: count. + uint64_t m_n_fds; ///< Total number of fds currently stored across all threadtables associated + ///< with each active thread in the sinsp state thread table, unit: count. + uint64_t m_n_threads; ///< Total number of threads currently stored in the sinsp state thread + ///< table, unit: count. }; -class libs_metrics_collector -{ +class libs_metrics_collector { public: libs_metrics_collector(sinsp* inspector, uint32_t flags); /*! - \brief Method to fill up m_metrics_buffer with metrics; refreshes m_metrics with up-to-date metrics on each call + \brief Method to fill up m_metrics_buffer with metrics; refreshes m_metrics with up-to-date + metrics on each call */ void snapshot(); @@ -339,10 +382,12 @@ class libs_metrics_collector private: sinsp* m_inspector; std::shared_ptr m_sinsp_stats_v2; - uint32_t m_metrics_flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | METRICS_V2_RESOURCE_UTILIZATION | METRICS_V2_STATE_COUNTERS | METRICS_V2_PLUGINS | METRICS_V2_KERNEL_COUNTERS_PER_CPU; + uint32_t m_metrics_flags = METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | + METRICS_V2_RESOURCE_UTILIZATION | METRICS_V2_STATE_COUNTERS | + METRICS_V2_PLUGINS | METRICS_V2_KERNEL_COUNTERS_PER_CPU; std::vector m_metrics; }; -} // namespace libs::metrics +} // namespace libs::metrics #endif diff --git a/userspace/libsinsp/mpsc_priority_queue.h b/userspace/libsinsp/mpsc_priority_queue.h index ee41d53422..7e014163e7 100644 --- a/userspace/libsinsp/mpsc_priority_queue.h +++ b/userspace/libsinsp/mpsc_priority_queue.h @@ -34,16 +34,14 @@ limitations under the License. * follow the temporal order with which they have been pushed. */ template -class mpsc_priority_queue -{ +class mpsc_priority_queue { // limit the implementation of Elm to std::shared_ptr | std::unique_ptr - static_assert( - std::is_same>::value || - std::is_same>::value, - "mpsc_priority_queue requires std::shared_ptr or std::unique_ptr elements"); + static_assert(std::is_same>::value || + std::is_same>::value, + "mpsc_priority_queue requires std::shared_ptr or std::unique_ptr elements"); public: - explicit mpsc_priority_queue(size_t capacity = 0) : m_capacity(capacity){} + explicit mpsc_priority_queue(size_t capacity = 0): m_capacity(capacity) {} /** * @brief Returns true if the queue contains no elements. @@ -54,11 +52,9 @@ class mpsc_priority_queue * @brief Push an element into queue, and returns false in case the * maximum queue capacity is met. */ - inline bool push(Elm&& e) - { + inline bool push(Elm&& e) { std::scoped_lock lk(m_mtx); - if (m_capacity == 0 || m_queue.size() < m_capacity) - { + if(m_capacity == 0 || m_queue.size() < m_capacity) { m_queue.push(queue_elm{std::move(e), m_elem_counter++}); m_queue_top = m_queue.top().elm.get(); return true; @@ -70,11 +66,9 @@ class mpsc_priority_queue * @brief Pops the highest priority element from the queue. Returns false * in case of empty queue. */ - inline bool try_pop(Elm& res) - { + inline bool try_pop(Elm& res) { // we check that the queue is not empty before acquiring the lock - if (m_queue_top == nullptr) - { + if(m_queue_top == nullptr) { return false; } @@ -94,17 +88,14 @@ class mpsc_priority_queue * a predicate before returning it. If the predicate returns false, the * element is not popped from the queue and this method returns false. */ - template - inline bool try_pop_if(Elm& res, const Callable& pred) - { + template + inline bool try_pop_if(Elm& res, const Callable& pred) { // we check that the queue is not empty before acquiring the lock - if (m_queue_top == nullptr) - { + if(m_queue_top == nullptr) { return false; } - while (true) - { + while(true) { // we need to evaluate the top element against the predicate, but // we must be careful in case other producers push a new element in // the queue, which can potentially have more priority than the one @@ -113,12 +104,10 @@ class mpsc_priority_queue auto should_pop = pred(*top); // we must not pop the element - if (!should_pop) - { + if(!should_pop) { // check that the top-priority element ha not changed since // we evaluated it, otherwise keep looping - if (top == m_queue_top.load()) - { + if(top == m_queue_top.load()) { return false; } continue; @@ -127,8 +116,7 @@ class mpsc_priority_queue // check that the top-priority elem has changed since evaluating it, // otherwise keep looping. We check this before acquiring the lock // as an extra concurrency optimization. - if (top != m_queue_top.load()) - { + if(top != m_queue_top.load()) { continue; } @@ -141,8 +129,7 @@ class mpsc_priority_queue // our checks, so we verify one last time that the actual // top element is the one we wish to pop, otherwise release // the lock and keep looping - if (m_queue.top().elm.get() != top) - { + if(m_queue.top().elm.get() != top) { continue; } @@ -163,11 +150,9 @@ class mpsc_priority_queue * it sets 'm_capacity' which is the valued to used to bound the queue's * size when pushing. */ - inline bool set_capacity(size_t capacity) - { + inline bool set_capacity(size_t capacity) { std::scoped_lock lk(m_mtx); - if(m_queue.size() <= capacity) - { + if(m_queue.size() <= capacity) { m_capacity = capacity; return true; } @@ -178,17 +163,14 @@ class mpsc_priority_queue private: using elm_ptr = typename Elm::element_type*; - struct queue_elm - { - inline bool operator < (const queue_elm& r) const - { + struct queue_elm { + inline bool operator<(const queue_elm& r) const { // we check if this elem is less than the other. If the comparison // gives the same result when inverting the operands, then we can // assume them being equal. Cmp c{}; auto res = c(*elm, *r.elm); - if (res == c(*r.elm, *elm)) - { + if(res == c(*r.elm, *elm)) { // if elements have the same priority, order them by // temporal order of arrival in the queue by using an atomic // logical clock (counter). diff --git a/userspace/libsinsp/mutex.h b/userspace/libsinsp/mutex.h index 4cdaf75217..14d8349171 100644 --- a/userspace/libsinsp/mutex.h +++ b/userspace/libsinsp/mutex.h @@ -38,31 +38,23 @@ class ConstMutexGuard; template class MutexGuard { public: - MutexGuard(std::unique_lock lock, T *inner) : m_lock(std::move(lock)), m_inner(inner) {} + MutexGuard(std::unique_lock lock, T *inner): + m_lock(std::move(lock)), + m_inner(inner) {} // we cannot copy a MutexGuard, only move MutexGuard(MutexGuard &rhs) = delete; - MutexGuard& operator=(MutexGuard &rhs) = delete; - MutexGuard(MutexGuard &&rhs) noexcept : m_lock(std::move(rhs.m_lock)), - m_inner(rhs.m_inner) {} + MutexGuard &operator=(MutexGuard &rhs) = delete; + MutexGuard(MutexGuard &&rhs) noexcept: m_lock(std::move(rhs.m_lock)), m_inner(rhs.m_inner) {} - T *operator->() - { - return m_inner; - } + T *operator->() { return m_inner; } - T &operator*() - { - return *m_inner; - } + T &operator*() { return *m_inner; } /** * Validate that the guarded object exists. */ - bool valid() - { - return m_inner != nullptr; - } + bool valid() { return m_inner != nullptr; } private: std::unique_lock m_lock; @@ -82,38 +74,31 @@ class MutexGuard { template class ConstMutexGuard { public: - ConstMutexGuard(std::unique_lock lock, const T *inner) : m_lock(std::move(lock)), - m_inner(inner) { - } + ConstMutexGuard(std::unique_lock lock, const T *inner): + m_lock(std::move(lock)), + m_inner(inner) {} // we cannot copy a ConstMutexGuard, only move ConstMutexGuard(ConstMutexGuard &rhs) = delete; - ConstMutexGuard& operator=(ConstMutexGuard &rhs) = delete; - ConstMutexGuard(ConstMutexGuard &&rhs) noexcept : m_lock(std::move(rhs.m_lock)), - m_inner(rhs.m_inner) {} + ConstMutexGuard &operator=(ConstMutexGuard &rhs) = delete; + ConstMutexGuard(ConstMutexGuard &&rhs) noexcept: + m_lock(std::move(rhs.m_lock)), + m_inner(rhs.m_inner) {} // a writable guard can be demoted to a read-only one, but *not* the other way around - ConstMutexGuard(MutexGuard &&rhs) noexcept : m_lock(std::move(rhs.m_lock)), - m_inner(rhs.m_inner) // NOLINT(google-explicit-constructor) + ConstMutexGuard(MutexGuard &&rhs) noexcept: + m_lock(std::move(rhs.m_lock)), + m_inner(rhs.m_inner) // NOLINT(google-explicit-constructor) {} - const T *operator->() const - { - return m_inner; - } + const T *operator->() const { return m_inner; } - const T &operator*() const - { - return *m_inner; - } + const T &operator*() const { return *m_inner; } /** * Validate that the guarded object exists. */ - bool valid() - { - return m_inner != nullptr; - } + bool valid() { return m_inner != nullptr; } private: std::unique_lock m_lock; @@ -129,21 +114,19 @@ class ConstMutexGuard { * It works by simply holding a `std::unique_lock` object that keeps the shared_mutex * exclusively locked while it exists, and unlocks it upon destruction */ -template class SharedMutexGuard -{ +template +class SharedMutexGuard { public: SharedMutexGuard(std::unique_lock wlock, T *inner): - m_write_lock(std::move(wlock)), m_inner(inner) - { - } + m_write_lock(std::move(wlock)), + m_inner(inner) {} // we cannot copy a SharedMutexGuard, only move SharedMutexGuard(SharedMutexGuard &rhs) = delete; SharedMutexGuard &operator=(SharedMutexGuard &rhs) = delete; SharedMutexGuard(SharedMutexGuard &&rhs) noexcept: - m_write_lock(std::move(rhs.m_write_lock)), m_inner(rhs.m_inner) - { - } + m_write_lock(std::move(rhs.m_write_lock)), + m_inner(rhs.m_inner) {} T *operator->() { return m_inner; } @@ -167,21 +150,19 @@ template class SharedMutexGuard * It works by simply holding a `std::shared_lock` object that keeps the shared_mutex * read locked while it exists, and unlocks it upon destruction */ -template class ConstSharedMutexGuard -{ +template +class ConstSharedMutexGuard { public: ConstSharedMutexGuard(std::shared_lock rlock, const T *inner): - m_read_lock(std::move(rlock)), m_inner(inner) - { - } + m_read_lock(std::move(rlock)), + m_inner(inner) {} // we cannot copy a ConstSharedMutexGuard, only move ConstSharedMutexGuard(ConstSharedMutexGuard &rhs) = delete; ConstSharedMutexGuard &operator=(ConstSharedMutexGuard &rhs) = delete; ConstSharedMutexGuard(ConstSharedMutexGuard &&rhs) noexcept: - m_read_lock(std::move(rhs.m_read_lock)), m_inner(rhs.m_inner) - { - } + m_read_lock(std::move(rhs.m_read_lock)), + m_inner(rhs.m_inner) {} const T *operator->() const { return m_inner; } @@ -225,7 +206,7 @@ class Mutex { public: Mutex() = default; - Mutex(T inner) : m_inner(std::move(inner)) {} + Mutex(T inner): m_inner(std::move(inner)) {} /** * \brief Lock the mutex, allowing access to the stored object @@ -234,10 +215,7 @@ class Mutex { * via operator * or -> and ensures the lock is held as long as * the guard object exists */ - MutexGuard lock() - { - return MutexGuard(std::unique_lock(m_lock), &m_inner); - } + MutexGuard lock() { return MutexGuard(std::unique_lock(m_lock), &m_inner); } /** * \brief Lock the mutex, allowing access to the stored object @@ -248,8 +226,7 @@ class Mutex { * * `const Mutex` only allows read-only access to the protected object */ - ConstMutexGuard lock() const - { + ConstMutexGuard lock() const { return ConstMutexGuard(std::unique_lock(m_lock), &m_inner); } @@ -259,7 +236,8 @@ class Mutex { }; /** - * \brief Wrap a value of type T, enforcing synchronized access while allowing for simultaneous readers + * \brief Wrap a value of type T, enforcing synchronized access while allowing for simultaneous + * readers * * @tparam T type of the wrapped value * @@ -271,7 +249,8 @@ class Mutex { * * SharedMutex> m_locked_map; * - * Then, to exclusively access the variable for writes, call .write_lock() on the SharedMutex object: + * Then, to exclusively access the variable for writes, call .write_lock() on the SharedMutex + * object: * * SharedMutexGuard> locked = m_locked_map.write_lock(); * @@ -285,8 +264,8 @@ class Mutex { * ConstSharedMutexGuard> locked = m_locked_map.read_lock(); * */ -template class SharedMutex -{ +template +class SharedMutex { public: using time_type = decltype(sinsp_utils::get_current_time_ns()); SharedMutex() = default; @@ -302,10 +281,11 @@ template class SharedMutex * * `ConstSharedMutexGuard` only allows read-only access to the protected object */ - ConstSharedMutexGuard read_lock() const - { + ConstSharedMutexGuard read_lock() const { auto start_ns = sinsp_utils::get_current_time_ns(); - auto mux_guard = ConstSharedMutexGuard(std::shared_lock(m_shared_lock), &m_inner); + auto mux_guard = + ConstSharedMutexGuard(std::shared_lock(m_shared_lock), + &m_inner); auto end_ns = sinsp_utils::get_current_time_ns(); m_read_lock_wait_time += (end_ns - start_ns); m_read_lock_wait_count++; @@ -319,19 +299,23 @@ template class SharedMutex * via operator * or -> and ensures the lock is held as long as * the guard object exists */ - SharedMutexGuard write_lock() - { + SharedMutexGuard write_lock() { auto start_ns = sinsp_utils::get_current_time_ns(); - auto mux_guard = SharedMutexGuard(std::unique_lock(m_shared_lock), &m_inner); + auto mux_guard = + SharedMutexGuard(std::unique_lock(m_shared_lock), &m_inner); auto end_ns = sinsp_utils::get_current_time_ns(); m_write_lock_wait_time += (end_ns - start_ns); m_write_lock_wait_count++; return mux_guard; } - time_type get_avg_read_lock_wait_time() const { return (m_read_lock_wait_time / m_read_lock_wait_count); } + time_type get_avg_read_lock_wait_time() const { + return (m_read_lock_wait_time / m_read_lock_wait_count); + } - time_type get_avg_write_lock_wait_time() const { return (m_write_lock_wait_time / m_write_lock_wait_count); } + time_type get_avg_write_lock_wait_time() const { + return (m_write_lock_wait_time / m_write_lock_wait_count); + } private: mutable std::shared_mutex m_shared_lock; @@ -342,4 +326,4 @@ template class SharedMutex mutable time_type m_write_lock_wait_count = 0; }; -} // namespace libsinsp +} // namespace libsinsp diff --git a/userspace/libsinsp/parsers.cpp b/userspace/libsinsp/parsers.cpp index cc3808ea8d..21c9773885 100644 --- a/userspace/libsinsp/parsers.cpp +++ b/userspace/libsinsp/parsers.cpp @@ -23,7 +23,7 @@ limitations under the License. #include #include #include -#endif // _WIN32 +#endif // _WIN32 #include #include @@ -46,41 +46,33 @@ limitations under the License. #include #endif -sinsp_parser::sinsp_parser(sinsp *inspector) : - m_inspector(inspector), - m_tmp_evt(m_inspector), - m_syscall_event_source_idx(sinsp_no_event_source_idx) -{ - if (m_inspector != nullptr) - { +sinsp_parser::sinsp_parser(sinsp *inspector): + m_inspector(inspector), + m_tmp_evt(m_inspector), + m_syscall_event_source_idx(sinsp_no_event_source_idx) { + if(m_inspector != nullptr) { m_sinsp_stats_v2 = m_inspector->get_sinsp_stats_v2(); - } - else - { + } else { m_sinsp_stats_v2 = nullptr; } } -sinsp_parser::~sinsp_parser() -{ - while(!m_tmp_events_buffer.empty()) - { +sinsp_parser::~sinsp_parser() { + while(!m_tmp_events_buffer.empty()) { auto ptr = m_tmp_events_buffer.top(); free(ptr); m_tmp_events_buffer.pop(); } } -void sinsp_parser::set_track_connection_status(bool enabled) -{ +void sinsp_parser::set_track_connection_status(bool enabled) { m_track_connection_status = enabled; } /////////////////////////////////////////////////////////////////////////////// // PROCESSING ENTRY POINT /////////////////////////////////////////////////////////////////////////////// -void sinsp_parser::process_event(sinsp_evt *evt) -{ +void sinsp_parser::process_event(sinsp_evt *evt) { uint16_t etype = evt->get_scap_evt()->type; bool is_live = m_inspector->is_live() || m_inspector->is_syscall_plugin(); @@ -92,18 +84,11 @@ void sinsp_parser::process_event(sinsp_evt *evt) // // When debug mode is not enabled, filter out events about itself // - if(is_live && !m_inspector->is_debug_enabled()) - { - if(evt->get_tid() == m_inspector->m_self_pid && - etype != PPME_SCHEDSWITCH_1_E && - etype != PPME_SCHEDSWITCH_6_E && - etype != PPME_DROP_E && - etype != PPME_DROP_X && - etype != PPME_SCAPEVENT_E && - etype != PPME_PROCINFO_E && - etype != PPME_CPU_HOTPLUG_E && - m_inspector->m_self_pid) - { + if(is_live && !m_inspector->is_debug_enabled()) { + if(evt->get_tid() == m_inspector->m_self_pid && etype != PPME_SCHEDSWITCH_1_E && + etype != PPME_SCHEDSWITCH_6_E && etype != PPME_DROP_E && etype != PPME_DROP_X && + etype != PPME_SCAPEVENT_E && etype != PPME_PROCINFO_E && etype != PPME_CPU_HOTPLUG_E && + m_inspector->m_self_pid) { evt->set_filtered_out(true); return; } @@ -114,22 +99,15 @@ void sinsp_parser::process_event(sinsp_evt *evt) // bool do_filter_later = false; - if(m_inspector->m_filter) - { + if(m_inspector->m_filter) { ppm_event_flags eflags = evt->get_info_flags(); - if(eflags & EF_MODIFIES_STATE) - { + if(eflags & EF_MODIFIES_STATE) { do_filter_later = true; - } - else - { - if(m_inspector->run_filters_on_evt(evt) == false) - { - if(evt->get_tinfo() != NULL) - { - if(!(eflags & EF_SKIPPARSERESET || etype == PPME_SCHEDSWITCH_6_E)) - { + } else { + if(m_inspector->run_filters_on_evt(evt) == false) { + if(evt->get_tinfo() != NULL) { + if(!(eflags & EF_SKIPPARSERESET || etype == PPME_SCHEDSWITCH_6_E)) { evt->get_tinfo()->set_lastevent_type(PPM_EVENT_MAX); } } @@ -145,11 +123,9 @@ void sinsp_parser::process_event(sinsp_evt *evt) // // Route the event to the proper function // - switch(etype) - { + switch(etype) { case PPME_SOCKET_SENDTO_E: - if((evt->get_fd_info() == nullptr) && (evt->get_tinfo() != nullptr)) - { + if((evt->get_fd_info() == nullptr) && (evt->get_tinfo() != nullptr)) { infer_sendto_fdinfo(evt); } @@ -187,8 +163,7 @@ void sinsp_parser::process_event(sinsp_evt *evt) store_event(evt); break; case PPME_SYSCALL_WRITE_E: - if(!m_inspector->is_dumping() && evt->get_tinfo() != nullptr) - { + if(!m_inspector->is_dumping() && evt->get_tinfo() != nullptr) { // note(jasondellaluce): this may be useless now that we removed tracers support evt->set_fd_info(evt->get_tinfo()->get_fd(evt->get_tinfo()->m_lastevent_fd)); } @@ -279,7 +254,7 @@ void sinsp_parser::process_event(sinsp_evt *evt) case PPME_SYSCALL_EXECVE_17_X: case PPME_SYSCALL_EXECVE_18_X: case PPME_SYSCALL_EXECVE_19_X: - case PPME_SYSCALL_EXECVEAT_X: + case PPME_SYSCALL_EXECVEAT_X: parse_execve_exit(evt); break; case PPME_PROCEXIT_E: @@ -407,7 +382,7 @@ void sinsp_parser::process_event(sinsp_evt *evt) parse_setgid_exit(evt); break; case PPME_CONTAINER_E: - parse_container_evt(evt); // deprecated, only here for backwards compatibility + parse_container_evt(evt); // deprecated, only here for backwards compatibility break; case PPME_CONTAINER_JSON_E: case PPME_CONTAINER_JSON_2_E: @@ -423,8 +398,7 @@ void sinsp_parser::process_event(sinsp_evt *evt) parse_setsid_exit(evt); break; case PPME_SOCKET_GETSOCKOPT_X: - if(evt->get_num_params() > 0) - { + if(evt->get_num_params() > 0) { parse_getsockopt_exit(evt); } break; @@ -447,22 +421,18 @@ void sinsp_parser::process_event(sinsp_evt *evt) case PPME_SYSCALL_FCHMODAT_X: case PPME_SYSCALL_MKDIRAT_X: case PPME_SYSCALL_UNLINKAT_2_X: - case PPME_SYSCALL_MKNODAT_X: - { + case PPME_SYSCALL_MKNODAT_X: { auto res = evt->get_param(0)->as(); - if (res >= 0) - { + if(res >= 0) { // Only if successful auto dirfd = evt->get_param(1)->as(); evt->set_fd_info(evt->get_tinfo()->get_fd(dirfd)); } break; } - case PPME_SYSCALL_SYMLINKAT_X: - { + case PPME_SYSCALL_SYMLINKAT_X: { auto res = evt->get_param(0)->as(); - if (res >= 0) - { + if(res >= 0) { // Only if successful auto dirfd = evt->get_param(2)->as(); evt->set_fd_info(evt->get_tinfo()->get_fd(dirfd)); @@ -477,10 +447,8 @@ void sinsp_parser::process_event(sinsp_evt *evt) // With some state-changing events like clone, execve and open, we do the // filtering after having updated the state // - if(do_filter_later) - { - if(!m_inspector->run_filters_on_evt(evt)) - { + if(do_filter_later) { + if(!m_inspector->run_filters_on_evt(evt)) { evt->set_filtered_out(true); return; } @@ -491,10 +459,8 @@ void sinsp_parser::process_event(sinsp_evt *evt) // supposed to go through the engine, but they must be filtered out before // reaching the user. // - if(m_inspector->is_capture()) - { - if(evt->get_dump_flags() & SCAP_DF_STATE_ONLY) - { + if(m_inspector->is_capture()) { + if(evt->get_dump_flags() & SCAP_DF_STATE_ONLY) { evt->set_filtered_out(true); } } @@ -502,17 +468,14 @@ void sinsp_parser::process_event(sinsp_evt *evt) // Check to see if the name changed as a side-effect of // parsing this event. Try to avoid the overhead of a string // compare for every event. - if(evt->get_fd_info()) - { + if(evt->get_fd_info()) { evt->set_fdinfo_name_changed(evt->get_fd_info()->m_name != evt->get_fd_info()->m_oldname); } } -void sinsp_parser::event_cleanup(sinsp_evt *evt) -{ - if(evt->get_direction() == SCAP_ED_OUT && - evt->get_tinfo() && evt->get_tinfo()->get_last_event_data()) - { +void sinsp_parser::event_cleanup(sinsp_evt *evt) { + if(evt->get_direction() == SCAP_ED_OUT && evt->get_tinfo() && + evt->get_tinfo()->get_last_event_data()) { free_event_buffer(evt->get_tinfo()->get_last_event_data()); evt->get_tinfo()->set_last_event_data(NULL); evt->get_tinfo()->set_lastevent_data_validity(false); @@ -527,8 +490,7 @@ void sinsp_parser::event_cleanup(sinsp_evt *evt) // Called before starting the parsing. // Returns false in case of issues resetting the state. // -bool sinsp_parser::reset(sinsp_evt *evt) -{ +bool sinsp_parser::reset(sinsp_evt *evt) { m_syslog_decoder.reset(); uint16_t etype = evt->get_type(); @@ -548,21 +510,19 @@ bool sinsp_parser::reset(sinsp_evt *evt) // containers. // bool keep_threadinfo = false; - if (!m_inspector->is_capture() && (etype == PPME_CONTAINER_JSON_E || etype == PPME_CONTAINER_JSON_2_E) && evt->get_tinfo_ref() != nullptr) - { + if(!m_inspector->is_capture() && + (etype == PPME_CONTAINER_JSON_E || etype == PPME_CONTAINER_JSON_2_E) && + evt->get_tinfo_ref() != nullptr) { // this is a synthetic event generated by the container manager // the threadinfo should already be set properly evt->init_keep_threadinfo(); keep_threadinfo = true; - } - else - { + } else { evt->init(); } uint32_t plugin_id = 0; - if (evt->get_type() == PPME_PLUGINEVENT_E || evt->get_type() == PPME_ASYNCEVENT_E) - { + if(evt->get_type() == PPME_PLUGINEVENT_E || evt->get_type() == PPME_ASYNCEVENT_E) { // note: async events can potentially encode a non-zero plugin ID // to indicate that they've been produced by a plugin with // a specific event source. If an async event has a zero plugin ID, then @@ -572,37 +532,28 @@ bool sinsp_parser::reset(sinsp_evt *evt) plugin_id = evt->get_param(0)->as(); } - if (plugin_id != 0) - { + if(plugin_id != 0) { bool pfound = false; auto srcidx = m_inspector->get_plugin_manager()->source_idx_by_plugin_id(plugin_id, pfound); - if (!pfound) - { + if(!pfound) { evt->set_source_idx(sinsp_no_event_source_idx); evt->set_source_name(sinsp_no_event_source_name); - } - else - { + } else { evt->set_source_idx(srcidx); evt->set_source_name(m_inspector->event_sources()[srcidx].c_str()); } - } - else - { + } else { // every other event falls under the "syscall" event source umbrella // cache index of "syscall" event source in case we haven't already - if (m_syscall_event_source_idx == sinsp_no_event_source_idx) - { + if(m_syscall_event_source_idx == sinsp_no_event_source_idx) { // note: the current inspector's implementation guarantees // that the "syscall" event source is always at index 0, being // the first one in the list. However we don't want to leak // that knowledge down to this level, so we search for it // in order to be resilient to future changes. // The search happens only once. - for (size_t i = 0; i < m_inspector->event_sources().size(); i++) - { - if (m_inspector->event_sources()[i] == sinsp_syscall_event_source_name) - { + for(size_t i = 0; i < m_inspector->event_sources().size(); i++) { + if(m_inspector->event_sources()[i] == sinsp_syscall_event_source_name) { m_syscall_event_source_idx = i; break; } @@ -610,11 +561,11 @@ bool sinsp_parser::reset(sinsp_evt *evt) } evt->set_source_idx(m_syscall_event_source_idx); evt->set_source_name((m_syscall_event_source_idx != sinsp_no_event_source_idx) - ? sinsp_syscall_event_source_name : sinsp_no_event_source_name); + ? sinsp_syscall_event_source_name + : sinsp_no_event_source_name); } - if (keep_threadinfo) - { + if(keep_threadinfo) { return true; } @@ -627,14 +578,11 @@ bool sinsp_parser::reset(sinsp_evt *evt) // // Ignore scheduler events // - if(eflags & EF_SKIPPARSERESET) - { - if(etype == PPME_PROCINFO_E) - { - evt->set_tinfo(m_inspector->get_thread_ref(evt->get_scap_evt()->tid, false, false).get()); - } - else - { + if(eflags & EF_SKIPPARSERESET) { + if(etype == PPME_PROCINFO_E) { + evt->set_tinfo( + m_inspector->get_thread_ref(evt->get_scap_evt()->tid, false, false).get()); + } else { evt->set_tinfo(NULL); } @@ -650,88 +598,59 @@ bool sinsp_parser::reset(sinsp_evt *evt) // (many kernel thread), we don't look for /proc // bool query_os; - if(etype == PPME_SYSCALL_CLONE_11_X || - etype == PPME_SYSCALL_CLONE_16_X || - etype == PPME_SYSCALL_CLONE_17_X || - etype == PPME_SYSCALL_CLONE_20_X || - etype == PPME_SYSCALL_FORK_X || - etype == PPME_SYSCALL_FORK_17_X || - etype == PPME_SYSCALL_FORK_20_X || - etype == PPME_SYSCALL_VFORK_X || - etype == PPME_SYSCALL_VFORK_17_X || - etype == PPME_SYSCALL_VFORK_20_X || - etype == PPME_SYSCALL_CLONE3_X || - etype == PPME_SCHEDSWITCH_6_E || - /* If we received a `procexit` event it means that the process - * is dead in the kernel, `query_os==true` would just generate fake entries. - */ - etype == PPME_PROCEXIT_E || - etype == PPME_PROCEXIT_1_E) - { + if(etype == PPME_SYSCALL_CLONE_11_X || etype == PPME_SYSCALL_CLONE_16_X || + etype == PPME_SYSCALL_CLONE_17_X || etype == PPME_SYSCALL_CLONE_20_X || + etype == PPME_SYSCALL_FORK_X || etype == PPME_SYSCALL_FORK_17_X || + etype == PPME_SYSCALL_FORK_20_X || etype == PPME_SYSCALL_VFORK_X || + etype == PPME_SYSCALL_VFORK_17_X || etype == PPME_SYSCALL_VFORK_20_X || + etype == PPME_SYSCALL_CLONE3_X || etype == PPME_SCHEDSWITCH_6_E || + /* If we received a `procexit` event it means that the process + * is dead in the kernel, `query_os==true` would just generate fake entries. + */ + etype == PPME_PROCEXIT_E || etype == PPME_PROCEXIT_1_E) { query_os = false; - } - else - { + } else { query_os = true; } // todo(jasondellaluce): should we do this for all meta-events in general? - if(etype == PPME_CONTAINER_JSON_E || - etype == PPME_CONTAINER_JSON_2_E || - etype == PPME_USER_ADDED_E || - etype == PPME_USER_DELETED_E || - etype == PPME_GROUP_ADDED_E || - etype == PPME_GROUP_DELETED_E || - etype == PPME_PLUGINEVENT_E || - etype == PPME_ASYNCEVENT_E) - { + if(etype == PPME_CONTAINER_JSON_E || etype == PPME_CONTAINER_JSON_2_E || + etype == PPME_USER_ADDED_E || etype == PPME_USER_DELETED_E || etype == PPME_GROUP_ADDED_E || + etype == PPME_GROUP_DELETED_E || etype == PPME_PLUGINEVENT_E || etype == PPME_ASYNCEVENT_E) { evt->set_tinfo(nullptr); return true; - } - else - { - evt->set_tinfo(m_inspector->get_thread_ref(evt->get_scap_evt()->tid, query_os, false).get()); + } else { + evt->set_tinfo( + m_inspector->get_thread_ref(evt->get_scap_evt()->tid, query_os, false).get()); } - if(etype == PPME_SCHEDSWITCH_6_E) - { + if(etype == PPME_SCHEDSWITCH_6_E) { return false; } - if(!evt->get_tinfo()) - { - if(etype == PPME_SYSCALL_CLONE_11_X || - etype == PPME_SYSCALL_CLONE_16_X || - etype == PPME_SYSCALL_CLONE_17_X || - etype == PPME_SYSCALL_CLONE_20_X || - etype == PPME_SYSCALL_FORK_X || - etype == PPME_SYSCALL_FORK_17_X || - etype == PPME_SYSCALL_FORK_20_X || - etype == PPME_SYSCALL_VFORK_X || - etype == PPME_SYSCALL_VFORK_17_X || - etype == PPME_SYSCALL_VFORK_20_X || - etype == PPME_SYSCALL_CLONE3_X) - { - if (m_sinsp_stats_v2 != nullptr) - { + if(!evt->get_tinfo()) { + if(etype == PPME_SYSCALL_CLONE_11_X || etype == PPME_SYSCALL_CLONE_16_X || + etype == PPME_SYSCALL_CLONE_17_X || etype == PPME_SYSCALL_CLONE_20_X || + etype == PPME_SYSCALL_FORK_X || etype == PPME_SYSCALL_FORK_17_X || + etype == PPME_SYSCALL_FORK_20_X || etype == PPME_SYSCALL_VFORK_X || + etype == PPME_SYSCALL_VFORK_17_X || etype == PPME_SYSCALL_VFORK_20_X || + etype == PPME_SYSCALL_CLONE3_X) { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_failed_thread_lookups--; } } return false; } - if(query_os) - { + if(query_os) { evt->get_tinfo()->m_flags |= PPM_CL_ACTIVE; } - if(PPME_IS_ENTER(etype)) - { + if(PPME_IS_ENTER(etype)) { evt->get_tinfo()->m_lastevent_fd = -1; evt->get_tinfo()->set_lastevent_type(etype); - if(eflags & EF_USES_FD) - { + if(eflags & EF_USES_FD) { // // Get the fd. // An fd will usually be the first parameter of the enter event, @@ -745,37 +664,26 @@ bool sinsp_parser::reset(sinsp_evt *evt) evt->get_tinfo()->m_latency = 0; evt->get_tinfo()->m_last_latency_entertime = evt->get_ts(); - } - else - { - sinsp_threadinfo* tinfo = evt->get_tinfo(); + } else { + sinsp_threadinfo *tinfo = evt->get_tinfo(); // // event latency // - if(tinfo->m_last_latency_entertime != 0) - { + if(tinfo->m_last_latency_entertime != 0) { tinfo->m_latency = evt->get_ts() - tinfo->m_last_latency_entertime; ASSERT((int64_t)tinfo->m_latency >= 0); } - if((etype==PPME_SYSCALL_EXECVE_18_X || - etype==PPME_SYSCALL_EXECVE_19_X) - && - tinfo->get_lastevent_type() == PPME_SYSCALL_EXECVEAT_E) - { + if((etype == PPME_SYSCALL_EXECVE_18_X || etype == PPME_SYSCALL_EXECVE_19_X) && + tinfo->get_lastevent_type() == PPME_SYSCALL_EXECVEAT_E) { tinfo->set_lastevent_data_validity(true); - } - else if(etype == tinfo->get_lastevent_type() + 1) - { + } else if(etype == tinfo->get_lastevent_type() + 1) { tinfo->set_lastevent_data_validity(true); - } - else - { + } else { tinfo->set_lastevent_data_validity(false); - if(tinfo->get_lastevent_type() != PPME_TRACER_E) - { + if(tinfo->get_lastevent_type() != PPME_TRACER_E) { return false; } } @@ -783,19 +691,16 @@ bool sinsp_parser::reset(sinsp_evt *evt) // // Error detection logic // - if(evt->get_num_params() != 0 && - ((evt->get_info()->params[0].name[0] == 'r' && - evt->get_info()->params[0].name[1] == 'e' && - evt->get_info()->params[0].name[2] == 's' && - evt->get_info()->params[0].name[3] == '\0') || - (evt->get_info()->params[0].name[0] == 'f' && - evt->get_info()->params[0].name[1] == 'd' && - evt->get_info()->params[0].name[2] == '\0'))) - { + if(evt->get_num_params() != 0 && ((evt->get_info()->params[0].name[0] == 'r' && + evt->get_info()->params[0].name[1] == 'e' && + evt->get_info()->params[0].name[2] == 's' && + evt->get_info()->params[0].name[3] == '\0') || + (evt->get_info()->params[0].name[0] == 'f' && + evt->get_info()->params[0].name[1] == 'd' && + evt->get_info()->params[0].name[2] == '\0'))) { int64_t res = evt->get_param(0)->as(); - if(res < 0) - { + if(res < 0) { evt->set_errorcode(-(int32_t)res); } } @@ -803,31 +708,26 @@ bool sinsp_parser::reset(sinsp_evt *evt) // // Retrieve the fd // - if(eflags & EF_USES_FD) - { + if(eflags & EF_USES_FD) { // // The copy_file_range syscall has the peculiarity of using two fds // Set as m_lastevent_fd the output fd // - if(etype == PPME_SYSCALL_COPY_FILE_RANGE_X) - { + if(etype == PPME_SYSCALL_COPY_FILE_RANGE_X) { tinfo->m_lastevent_fd = evt->get_param(1)->as(); } evt->set_fd_info(tinfo->get_fd(tinfo->m_lastevent_fd)); - if(evt->get_fd_info() == NULL) - { + if(evt->get_fd_info() == NULL) { return false; } - if(evt->get_errorcode() != 0 && m_inspector->get_observer()) - { + if(evt->get_errorcode() != 0 && m_inspector->get_observer()) { m_inspector->get_observer()->on_error(evt); } - if(evt->get_fd_info()->m_flags & sinsp_fdinfo::FLAGS_CLOSE_CANCELED) - { + if(evt->get_fd_info()->m_flags & sinsp_fdinfo::FLAGS_CLOSE_CANCELED) { // // A close gets canceled when the same fd is created successfully between // close enter and close exit. @@ -854,17 +754,14 @@ bool sinsp_parser::reset(sinsp_evt *evt) return true; } -void sinsp_parser::store_event(sinsp_evt *evt) -{ - if(evt->get_tinfo() == nullptr) - { +void sinsp_parser::store_event(sinsp_evt *evt) { + if(evt->get_tinfo() == nullptr) { // // No thread in the table. We won't store this event, which mean that // we won't be able to parse the corresponding exit event and we'll have // to drop the information it carries. // - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_store_evts_drops++; } return; @@ -877,8 +774,7 @@ void sinsp_parser::store_event(sinsp_evt *evt) // elen = scap_event_getlen(evt->get_scap_evt()); - if(elen > SP_EVT_BUF_SIZE) - { + if(elen > SP_EVT_BUF_SIZE) { ASSERT(false); return; } @@ -887,11 +783,9 @@ void sinsp_parser::store_event(sinsp_evt *evt) // Copy the data // auto tinfo = evt->get_tinfo(); - if(tinfo->get_last_event_data() == NULL) - { + if(tinfo->get_last_event_data() == NULL) { tinfo->set_last_event_data(reserve_event_buffer()); - if(tinfo->get_last_event_data() == NULL) - { + if(tinfo->get_last_event_data() == NULL) { throw sinsp_exception("cannot reserve event buffer in sinsp_parser::store_event."); return; } @@ -899,39 +793,36 @@ void sinsp_parser::store_event(sinsp_evt *evt) memcpy(tinfo->get_last_event_data(), evt->get_scap_evt(), elen); tinfo->set_lastevent_cpuid(evt->get_cpuid()); - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_stored_evts++; } } -bool sinsp_parser::retrieve_enter_event(sinsp_evt *enter_evt, sinsp_evt *exit_evt) -{ +bool sinsp_parser::retrieve_enter_event(sinsp_evt *enter_evt, sinsp_evt *exit_evt) { // // Make sure there's a valid thread info // - if(!exit_evt->get_tinfo()) - { + if(!exit_evt->get_tinfo()) { return false; } // // Retrieve the copy of the enter event and initialize it // - if(!(exit_evt->get_tinfo()->is_lastevent_data_valid() && exit_evt->get_tinfo()->get_last_event_data())) - { + if(!(exit_evt->get_tinfo()->is_lastevent_data_valid() && + exit_evt->get_tinfo()->get_last_event_data())) { // // This happen especially at the beginning of trace files, where events // can be truncated // - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_retrieve_evts_drops++; } return false; } - enter_evt->init(exit_evt->get_tinfo()->get_last_event_data(), exit_evt->get_tinfo()->get_lastevent_cpuid()); + enter_evt->init(exit_evt->get_tinfo()->get_last_event_data(), + exit_evt->get_tinfo()->get_lastevent_cpuid()); /* The `execveat` syscall is a wrapper of `execve`, when the call * succeeds the event returned is simply an `execve` exit event. @@ -943,12 +834,9 @@ bool sinsp_parser::retrieve_enter_event(sinsp_evt *enter_evt, sinsp_evt *exit_ev * we have also to check for the `PPME_SYSCALL_EXECVEAT_E`. */ if((exit_evt->get_type() == PPME_SYSCALL_EXECVE_18_X || - exit_evt->get_type() == PPME_SYSCALL_EXECVE_19_X) - && - enter_evt->get_type() == PPME_SYSCALL_EXECVEAT_E) - { - if (m_sinsp_stats_v2 != nullptr) - { + exit_evt->get_type() == PPME_SYSCALL_EXECVE_19_X) && + enter_evt->get_type() == PPME_SYSCALL_EXECVEAT_E) { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_retrieved_evts++; } return true; @@ -958,18 +846,15 @@ bool sinsp_parser::retrieve_enter_event(sinsp_evt *enter_evt, sinsp_evt *exit_ev // Make sure that we're using the right enter event, to prevent inconsistencies when events // are dropped // - if(enter_evt->get_type() != (exit_evt->get_type() - 1)) - { - //ASSERT(false); + if(enter_evt->get_type() != (exit_evt->get_type() - 1)) { + // ASSERT(false); exit_evt->get_tinfo()->set_lastevent_data_validity(false); - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_retrieve_evts_drops++; } return false; } - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_retrieved_evts++; } @@ -980,8 +865,7 @@ bool sinsp_parser::retrieve_enter_event(sinsp_evt *enter_evt, sinsp_evt *exit_ev // PARSERS /////////////////////////////////////////////////////////////////////////////// -void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) -{ +void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) { uint16_t etype = evt->get_type(); int64_t caller_tid = evt->get_tid(); @@ -1002,17 +886,17 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) * 2. create a new thread info for the child if necessary. (resilience to event drops) */ - /*=============================== ENRICH/CREATE ESSENTIAL CALLER STATE ===========================*/ + /*=============================== ENRICH/CREATE ESSENTIAL CALLER STATE + * ===========================*/ /* Let's see if we have some info regarding the caller */ auto caller_tinfo = m_inspector->get_thread_ref(caller_tid, true); - /* This happens only if we reach the max entries in our table otherwise we should obtain a new fresh empty - * thread info to populate even if we are not able to recover any information! - * If `caller_tinfo == nullptr` we return, we won't have enough space for the child in the table! + /* This happens only if we reach the max entries in our table otherwise we should obtain a new + * fresh empty thread info to populate even if we are not able to recover any information! If + * `caller_tinfo == nullptr` we return, we won't have enough space for the child in the table! */ - if(caller_tinfo == nullptr) - { + if(caller_tinfo == nullptr) { /* Invalidate the thread info associated with this event */ evt->set_tinfo(nullptr); return; @@ -1022,9 +906,9 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) * 1. The process is dead and we are not able to find it in /proc. * 2. We have done too much /proc scan and we cannot recover it. */ - if(caller_tinfo->is_invalid()) - { - /* In case of invalid thread we enrich it with fresh info and we obtain a sort of valid thread info */ + if(caller_tinfo->is_invalid()) { + /* In case of invalid thread we enrich it with fresh info and we obtain a sort of valid + * thread info */ valid_caller = false; /* pid. */ @@ -1037,8 +921,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /* We preset them for old scap-files compatibility. */ caller_tinfo->m_vtid = caller_tid; caller_tinfo->m_vpid = -1; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: case PPME_SYSCALL_CLONE_16_X: case PPME_SYSCALL_CLONE_17_X: @@ -1066,9 +949,11 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /* Update the evt->get_tinfo() of the caller. */ evt->set_tinfo(caller_tinfo.get()); - /// todo(@Andreagit97): here we could update `comm` `exe` and `args` with fresh info from the event + /// todo(@Andreagit97): here we could update `comm` `exe` and `args` with fresh info from the + /// event - /*=============================== ENRICH/CREATE ESSENTIAL CALLER STATE ===========================*/ + /*=============================== ENRICH/CREATE ESSENTIAL CALLER STATE + * ===========================*/ /*=============================== CHILD IN CONTAINER CASE ===========================*/ @@ -1078,8 +963,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) */ uint32_t flags = 0; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: flags = evt->get_param(8)->as(); break; @@ -1125,11 +1009,8 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) * This is not a strict requirement (leave it here for compatibility with old * scap-files) */ - if(flags & PPM_CL_CHILD_IN_PIDNS || - flags & PPM_CL_CLONE_NEWPID || - flags & PPM_CL_CLONE_PARENT || - caller_tid != caller_tinfo->m_vtid) - { + if(flags & PPM_CL_CHILD_IN_PIDNS || flags & PPM_CL_CLONE_NEWPID || + flags & PPM_CL_CLONE_PARENT || caller_tid != caller_tinfo->m_vtid) { return; } @@ -1138,20 +1019,17 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /*=============================== CHILD ALREADY THERE ===========================*/ /* See if the child is already there, if yes and it is valid we return immediately */ - sinsp_threadinfo* existing_child_tinfo = m_inspector->get_thread_ref(child_tid, false, true).get(); - if(existing_child_tinfo != nullptr) - { + sinsp_threadinfo *existing_child_tinfo = + m_inspector->get_thread_ref(child_tid, false, true).get(); + if(existing_child_tinfo != nullptr) { /* If this was an inverted clone, all is fine, we've already taken care * of adding the thread table entry in the child. * Otherwise, we assume that the entry is there because we missed the proc exit event * for a previous thread and we replace the tinfo. */ - if(existing_child_tinfo->m_flags & PPM_CL_CLONE_INVERTED) - { + if(existing_child_tinfo->m_flags & PPM_CL_CLONE_INVERTED) { return; - } - else - { + } else { m_inspector->remove_thread(child_tid); tid_collision = child_tid; } @@ -1180,26 +1058,24 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) child_tinfo->m_tid = child_tid; /* Thread-leader case */ - if(!(child_tinfo->m_flags & PPM_CL_CLONE_THREAD)) - { + if(!(child_tinfo->m_flags & PPM_CL_CLONE_THREAD)) { /* We populate fdtable, cwd and env only if we are * a new leader thread, all not leader threads will use the same information * of the main thread. */ - if(valid_caller) - { + if(valid_caller) { /* Copy the fd list: - * XXX this is a gross oversimplification that will need to be fixed. - * What we do is: if the child is NOT a thread, we copy all the parent fds. - * The right thing to do is looking at PPM_CL_CLONE_FILES, but there are - * syscalls like open and pipe2 that can override PPM_CL_CLONE_FILES with the O_CLOEXEC flag - */ - sinsp_fdtable* fd_table_ptr = caller_tinfo->get_fd_table(); - if(fd_table_ptr != NULL) - { + * XXX this is a gross oversimplification that will need to be fixed. + * What we do is: if the child is NOT a thread, we copy all the parent fds. + * The right thing to do is looking at PPM_CL_CLONE_FILES, but there are + * syscalls like open and pipe2 that can override PPM_CL_CLONE_FILES with the O_CLOEXEC + * flag + */ + sinsp_fdtable *fd_table_ptr = caller_tinfo->get_fd_table(); + if(fd_table_ptr != NULL) { child_tinfo->get_fdtable().clear(); child_tinfo->get_fdtable().set_tid(child_tinfo->m_tid); - fd_table_ptr->const_loop([&child_tinfo](int64_t fd, const sinsp_fdinfo& info) { + fd_table_ptr->const_loop([&child_tinfo](int64_t fd, const sinsp_fdinfo &info) { /* Track down that those are cloned fds */ auto newinfo = info.clone(); newinfo->set_is_cloned(); @@ -1208,14 +1084,13 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) }); /* It's important to reset the cache of the child thread, to prevent it from - * referring to an element in the parent's table. - */ + * referring to an element in the parent's table. + */ child_tinfo->get_fdtable().reset_cache(); - } - else - { + } else { /* This should never happen */ - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "cannot get fd table in sinsp_parser::parse_clone_exit."); + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "cannot get fd table in sinsp_parser::parse_clone_exit."); ASSERT(false); } @@ -1233,8 +1108,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /* The child parent is the calling process */ child_tinfo->m_ptid = caller_tinfo->m_tid; - } - else /* Simple thread case */ + } else /* Simple thread case */ { /* pid */ child_tinfo->m_pid = caller_tinfo->m_pid; @@ -1243,10 +1117,12 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /* The parent is the parent of the calling process */ child_tinfo->m_ptid = caller_tinfo->m_ptid; - /* Please note this is not the right behavior, it is something we do to be compliant with `/proc` scan. + /* Please note this is not the right behavior, it is something we do to be compliant with + * `/proc` scan. * - * In our approximation threads will never have their `fdtable` they will use the main thread one, for - * this reason, we keep the main thread alive until we have some threads in the group. + * In our approximation threads will never have their `fdtable` they will use the main + * thread one, for this reason, we keep the main thread alive until we have some threads in + * the group. */ child_tinfo->m_flags |= PPM_CL_CLONE_FILES; @@ -1273,8 +1149,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) child_tinfo->set_args(evt->get_param(2)->as>()); /* comm */ - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: case PPME_SYSCALL_CLONE_16_X: case PPME_SYSCALL_FORK_X: @@ -1298,8 +1173,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) child_tinfo->m_fdlimit = evt->get_param(7)->as(); /* Generic memory info */ - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: break; case PPME_SYSCALL_CLONE_16_X: @@ -1333,8 +1207,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /* uid */ int32_t uid = 0; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: uid = evt->get_param(9)->as(); break; @@ -1361,8 +1234,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /* gid */ int32_t gid = 0; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: gid = evt->get_param(10)->as(); break; @@ -1388,15 +1260,16 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) child_tinfo->set_group(gid); /* Set cgroups and heuristically detect container id */ - switch(etype) - { - case PPME_SYSCALL_FORK_20_X: - case PPME_SYSCALL_VFORK_20_X: - case PPME_SYSCALL_CLONE_20_X: - case PPME_SYSCALL_CLONE3_X: - child_tinfo->set_cgroups(evt->get_param(14)->as>()); - m_inspector->m_container_manager.resolve_container(child_tinfo.get(), m_inspector->is_live() || m_inspector->is_syscall_plugin()); - break; + switch(etype) { + case PPME_SYSCALL_FORK_20_X: + case PPME_SYSCALL_VFORK_20_X: + case PPME_SYSCALL_CLONE_20_X: + case PPME_SYSCALL_CLONE3_X: + child_tinfo->set_cgroups(evt->get_param(14)->as>()); + m_inspector->m_container_manager.resolve_container( + child_tinfo.get(), + m_inspector->is_live() || m_inspector->is_syscall_plugin()); + break; } /* Initialize the thread clone time */ @@ -1406,8 +1279,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) child_tinfo->m_pidns_init_start_ts = m_inspector->get_machine_info()->boot_ts_epoch; /* Take some further info from the caller */ - if(valid_caller) - { + if(valid_caller) { /* We should trust the info we obtain from the caller, if it is valid */ child_tinfo->m_exepath = caller_tinfo->m_exepath; @@ -1441,10 +1313,9 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) child_tinfo->m_exe_ino_mtime = caller_tinfo->m_exe_ino_mtime; - child_tinfo->m_exe_ino_ctime_duration_clone_ts = caller_tinfo->m_exe_ino_ctime_duration_clone_ts; - } - else - { + child_tinfo->m_exe_ino_ctime_duration_clone_ts = + caller_tinfo->m_exe_ino_ctime_duration_clone_ts; + } else { /* exe */ caller_tinfo->m_exe = child_tinfo->m_exe; @@ -1461,23 +1332,20 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) /* Until we use the shared pointer we need it here, after we can move it at the end */ auto new_child = m_inspector->add_thread(std::move(child_tinfo)); - if (!new_child) - { + if(!new_child) { // note: we expect the thread manager to log a warning already return; } /* Refresh user / loginuser / group */ - if(new_child->m_container_id.empty() == false) - { + if(new_child->m_container_id.empty() == false) { new_child->set_user(new_child->m_user.uid()); new_child->set_loginuser(new_child->m_loginuser.uid()); new_child->set_group(new_child->m_group.gid()); } /* If there's a listener, invoke it */ - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_clone(evt, new_child.get(), tid_collision); } @@ -1485,8 +1353,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) * make sure we reinitialize the tinfo pointer for this event, as the thread * generating it might have gone away. */ - if(tid_collision != -1) - { + if(tid_collision != -1) { reset(evt); DBG_SINSP_INFO("tid collision for %" PRIu64 "(%s)", tid_collision, @@ -1497,8 +1364,7 @@ void sinsp_parser::parse_clone_exit_caller(sinsp_evt *evt, int64_t child_tid) return; } -void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) -{ +void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) { uint16_t etype = evt->get_type(); int64_t child_tid = evt->get_tid(); @@ -1514,10 +1380,8 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) * Please note that the thread info is associated with the event * in `sinsp_parser::reset` method. */ - if(evt->get_tinfo() != nullptr && evt->get_tinfo()->m_clone_ts != 0) - { - if(evt->get_ts() - evt->get_tinfo()->m_clone_ts < CLONE_STALE_TIME_NS) - { + if(evt->get_tinfo() != nullptr && evt->get_tinfo()->m_clone_ts != 0) { + if(evt->get_ts() - evt->get_tinfo()->m_clone_ts < CLONE_STALE_TIME_NS) { /* This is a valid thread-info, the caller populated it so we * have nothing to do here. Note that if we are in a container the caller * will never generate the child thread-info because it doesn't have @@ -1570,8 +1434,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) */ child_tinfo->m_vtid = child_tinfo->m_tid; child_tinfo->m_vpid = -1; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: case PPME_SYSCALL_CLONE_16_X: case PPME_SYSCALL_CLONE_17_X: @@ -1594,8 +1457,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) /* flags */ uint32_t flags = 0; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: flags = evt->get_param(8)->as(); break; @@ -1632,48 +1494,44 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) * * Note that the lookup thread could be different from the caller one! * If they are different we cannot completely trust the info we obtain from lookup thread - * becuase they could be stale! For example the caller may have called `prctl` changing its comm, - * while the lookup thread still have the old `comm`. + * becuase they could be stale! For example the caller may have called `prctl` changing its + * comm, while the lookup thread still have the old `comm`. */ int64_t lookup_tid; bool is_thread_leader = !(child_tinfo->m_flags & PPM_CL_CLONE_THREAD); - if(is_thread_leader) - { + if(is_thread_leader) { /* We need to copy data from the parent */ lookup_tid = child_tinfo->m_ptid; - } - else - { + } else { /* We need to copy data from the thread leader */ lookup_tid = child_tinfo->m_pid; - /* Please note this is not the right behavior, it is something we do to be compliant with `/proc` scan. + /* Please note this is not the right behavior, it is something we do to be compliant with + * `/proc` scan. * - * In our approximation threads will never have their `fdtable` they will use the main thread one, for this reason, we keep - * the main thread alive until we have some threads in the group. + * In our approximation threads will never have their `fdtable` they will use the main + * thread one, for this reason, we keep the main thread alive until we have some threads in + * the group. */ child_tinfo->m_flags |= PPM_CL_CLONE_FILES; } auto lookup_tinfo = m_inspector->get_thread_ref(lookup_tid, true); - /* This happens only if we reach the max entries in our table otherwise we should obtain a new fresh empty - * thread info to populate even if we are not able to recover any information! - * If `caller_tinfo == nullptr` we return, we won't have enough space for the child in the table! + /* This happens only if we reach the max entries in our table otherwise we should obtain a new + * fresh empty thread info to populate even if we are not able to recover any information! If + * `caller_tinfo == nullptr` we return, we won't have enough space for the child in the table! */ - if(lookup_tinfo == nullptr) - { + if(lookup_tinfo == nullptr) { /* Invalidate the thread_info associated with this event */ evt->set_tinfo(nullptr); return; } - if(lookup_tinfo->is_invalid()) - { + if(lookup_tinfo->is_invalid()) { valid_lookup_thread = false; - if(!is_thread_leader) - { + if(!is_thread_leader) { /* If the main thread was invalid we should be able to recover some info */ /* pid. */ @@ -1705,8 +1563,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) child_tinfo->m_exe = evt->get_param(1)->as(); /* comm */ - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: case PPME_SYSCALL_CLONE_16_X: case PPME_SYSCALL_FORK_X: @@ -1729,8 +1586,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) /* args */ child_tinfo->set_args(evt->get_param(2)->as>()); - if(valid_lookup_thread) - { + if(valid_lookup_thread) { /* Please note that these data could be wrong if the lookup thread * is not the caller! for example, if the child is created by a thread * the thread could have different info with respect to the thread leader, @@ -1770,11 +1626,11 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) child_tinfo->m_exe_ino_mtime = lookup_tinfo->m_exe_ino_mtime; - child_tinfo->m_exe_ino_ctime_duration_clone_ts = lookup_tinfo->m_exe_ino_ctime_duration_clone_ts; + child_tinfo->m_exe_ino_ctime_duration_clone_ts = + lookup_tinfo->m_exe_ino_ctime_duration_clone_ts; /* We are a new thread leader */ - if(is_thread_leader) - { + if(is_thread_leader) { /* We populate fdtable, cwd and env only if we are * a new leader thread, all not leader threads will use the same information * of the main thread. @@ -1784,17 +1640,17 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) * XXX this is a gross oversimplification that will need to be fixed. * What we do is: if the child is NOT a thread, we copy all the parent fds. * The right thing to do is looking at PPM_CL_CLONE_FILES, but there are - * syscalls like open and pipe2 that can override PPM_CL_CLONE_FILES with the O_CLOEXEC flag + * syscalls like open and pipe2 that can override PPM_CL_CLONE_FILES with the O_CLOEXEC + * flag */ sinsp_fdtable *fd_table_ptr = lookup_tinfo->get_fd_table(); - if(fd_table_ptr != NULL) - { + if(fd_table_ptr != NULL) { child_tinfo->get_fdtable().clear(); child_tinfo->get_fdtable().set_tid(child_tinfo->m_tid); - fd_table_ptr->const_loop([&child_tinfo](int64_t fd, const sinsp_fdinfo& info) { + fd_table_ptr->const_loop([&child_tinfo](int64_t fd, const sinsp_fdinfo &info) { /* Track down that those are cloned fds. - * This flag `FLAGS_IS_CLONED` seems to be never used... - */ + * This flag `FLAGS_IS_CLONED` seems to be never used... + */ auto newinfo = info.clone(); newinfo->set_is_cloned(); child_tinfo->get_fdtable().add(fd, std::move(newinfo)); @@ -1805,12 +1661,10 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) * referring to an element in the parent's table. */ child_tinfo->get_fdtable().reset_cache(); - } - else - { + } else { /* This should never happen */ libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "cannot get fd table in sinsp_parser::parse_clone_exit."); + "cannot get fd table in sinsp_parser::parse_clone_exit."); ASSERT(false); } @@ -1819,19 +1673,14 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) /* Not a thread, copy env */ child_tinfo->m_env = lookup_tinfo->m_env; - } - else - { + } else { /* If we are a new thread we keep the same lastexec time of the main thread */ child_tinfo->m_lastexec_ts = lookup_tinfo->m_lastexec_ts; } - } - else - { - /* Please note that here `comm`, `exe`, ... could be different from our thread, so this is an - * approximation */ - if(!is_thread_leader) - { + } else { + /* Please note that here `comm`, `exe`, ... could be different from our thread, so this is + * an approximation */ + if(!is_thread_leader) { /* exe */ lookup_tinfo->m_exe = child_tinfo->m_exe; @@ -1847,8 +1696,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) child_tinfo->m_fdlimit = evt->get_param(7)->as(); /* Generic memory info */ - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: break; case PPME_SYSCALL_CLONE_16_X: @@ -1882,8 +1730,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) /* uid */ int32_t uid = 0; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: uid = evt->get_param(9)->as(); break; @@ -1910,8 +1757,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) /* gid */ int32_t gid = 0; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_CLONE_11_X: gid = evt->get_param(10)->as(); break; @@ -1937,14 +1783,14 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) child_tinfo->set_group(gid); /* Set cgroups and heuristically detect container id */ - switch(etype) - { + switch(etype) { case PPME_SYSCALL_FORK_20_X: case PPME_SYSCALL_VFORK_20_X: case PPME_SYSCALL_CLONE_20_X: case PPME_SYSCALL_CLONE3_X: child_tinfo->set_cgroups(evt->get_param(14)->as>()); - m_inspector->m_container_manager.resolve_container(child_tinfo.get(), m_inspector->is_live()); + m_inspector->m_container_manager.resolve_container(child_tinfo.get(), + m_inspector->is_live()); break; } @@ -1952,18 +1798,14 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) child_tinfo->m_clone_ts = evt->get_ts(); /* Get pid namespace start ts - convert monotonic time in ns to epoch ts */ - if(evt->get_num_params() > 20) - { + if(evt->get_num_params() > 20) { /* If we are in container! */ if(child_tinfo->m_flags & PPM_CL_CHILD_IN_PIDNS || - child_tinfo->m_flags & PPM_CL_CLONE_NEWPID || - child_tinfo->m_tid != child_tinfo->m_vtid) - { - child_tinfo->m_pidns_init_start_ts = - evt->get_param(20)->as() + m_inspector->get_machine_info()->boot_ts_epoch; - } - else - { + child_tinfo->m_flags & PPM_CL_CLONE_NEWPID || + child_tinfo->m_tid != child_tinfo->m_vtid) { + child_tinfo->m_pidns_init_start_ts = evt->get_param(20)->as() + + m_inspector->get_machine_info()->boot_ts_epoch; + } else { child_tinfo->m_pidns_init_start_ts = m_inspector->get_machine_info()->boot_ts_epoch; } } @@ -1972,8 +1814,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) /* Add the new thread to the table */ auto new_child = m_inspector->add_thread(std::move(child_tinfo)); - if (!new_child) - { + if(!new_child) { // note: we expect the thread manager to log a warning already evt->set_tinfo(nullptr); return; @@ -1986,8 +1827,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) evt->set_tinfo(new_child.get()); /* Refresh user / loginuser / group */ - if(new_child->m_container_id.empty() == false) - { + if(new_child->m_container_id.empty() == false) { new_child->set_user(new_child->m_user.uid()); new_child->set_loginuser(new_child->m_loginuser.uid()); new_child->set_group(new_child->m_group.gid()); @@ -1996,8 +1836,7 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) // // If there's a listener, invoke it // - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_clone(evt, new_child.get(), tid_collision); } @@ -2006,44 +1845,38 @@ void sinsp_parser::parse_clone_exit_child(sinsp_evt *evt) * generating it might have gone away. */ - if(tid_collision != -1) - { + if(tid_collision != -1) { reset(evt); /* Right now we have collisions only on the clone() caller */ - DBG_SINSP_INFO("tid collision for %" PRIu64 "(%s)", tid_collision, new_child->m_comm.c_str()); + DBG_SINSP_INFO("tid collision for %" PRIu64 "(%s)", + tid_collision, + new_child->m_comm.c_str()); } /*=============================== CREATE NEW THREAD-INFO ===========================*/ return; } -void sinsp_parser::parse_clone_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_clone_exit(sinsp_evt *evt) { int64_t childtid = evt->get_param(0)->as(); /* Please note that if the child is in a namespace different from the init one * we should never use this `childtid` otherwise we will use a thread id referred to * an internal namespace and not to the init one! */ - if(childtid < 0) - { + if(childtid < 0) { // // clone() failed. Do nothing and keep going. // return; - } - else if(childtid == 0) - { + } else if(childtid == 0) { parse_clone_exit_child(evt); - } - else - { + } else { parse_clone_exit_caller(evt, childtid); } return; } -void sinsp_parser::parse_execve_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_execve_exit(sinsp_evt *evt) { const sinsp_evt_param *parinfo; int64_t retval; uint16_t etype = evt->get_type(); @@ -2056,23 +1889,21 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) * when the `execveat` syscall succeeds, for this reason, we need to manage also * this event in the parser. */ - if(retval < 0) - { + if(retval < 0) { return; } // - // We get here when `execve` or `execveat` return. The thread has already been added by a previous fork or clone, - // and we just update the entry with the new information. + // We get here when `execve` or `execveat` return. The thread has already been added by a + // previous fork or clone, and we just update the entry with the new information. // - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { // // No thread to update? // We probably missed the start event, so we will just do nothing // - //fprintf(stderr, "comm = %s, args = %s\n",evt->get_param(1)->m_val,evt->get_param(1)->m_val); - //ASSERT(false); + // fprintf(stderr, "comm = %s, args = + // %s\n",evt->get_param(1)->m_val,evt->get_param(1)->m_val); ASSERT(false); return; } @@ -2084,8 +1915,7 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) * a new PROC_EXIT event will kill it again. * This is what happens with `stress-ng --exec`. */ - if(evt->get_tinfo()->is_dead()) - { + if(evt->get_tinfo()->is_dead()) { evt->get_tinfo()->resurrect_thread(); } @@ -2096,8 +1926,7 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) auto container_id = evt->get_tinfo()->m_container_id; - switch(etype) - { + switch(etype) { case PPME_SYSCALL_EXECVE_8_X: case PPME_SYSCALL_EXECVE_13_X: case PPME_SYSCALL_EXECVE_14_X: @@ -2128,13 +1957,11 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) // try to at least patch the parent, since // we have it from the execve event // - if(evt->get_tinfo()->is_invalid()) - { + if(evt->get_tinfo()->is_invalid()) { evt->get_tinfo()->m_ptid = evt->get_param(5)->as(); /* We are not in a namespace we recover also vtid and vpid */ - if((evt->get_tinfo()->m_flags & PPM_CL_CHILD_IN_PIDNS) == 0) - { + if((evt->get_tinfo()->m_flags & PPM_CL_CHILD_IN_PIDNS) == 0) { evt->get_tinfo()->m_vtid = evt->get_tinfo()->m_tid; evt->get_tinfo()->m_vpid = evt->get_tinfo()->m_pid; } @@ -2147,8 +1974,7 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) // Get the fdlimit evt->get_tinfo()->m_fdlimit = evt->get_param(7)->as(); - switch(etype) - { + switch(etype) { case PPME_SYSCALL_EXECVE_8_X: break; case PPME_SYSCALL_EXECVE_13_X: @@ -2178,8 +2004,7 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) ASSERT(false); } - switch(etype) - { + switch(etype) { case PPME_SYSCALL_EXECVE_8_X: case PPME_SYSCALL_EXECVE_13_X: break; @@ -2217,14 +2042,15 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) // 2. docker-runc changes cgroup hierarchy of it // 3. vpid=1 execve to the real process the user wants to run inside the container // - m_inspector->m_container_manager.resolve_container(evt->get_tinfo(), m_inspector->is_live() || m_inspector->is_syscall_plugin()); + m_inspector->m_container_manager.resolve_container( + evt->get_tinfo(), + m_inspector->is_live() || m_inspector->is_syscall_plugin()); break; default: ASSERT(false); } - switch(etype) - { + switch(etype) { case PPME_SYSCALL_EXECVE_8_X: case PPME_SYSCALL_EXECVE_13_X: case PPME_SYSCALL_EXECVE_14_X: @@ -2245,18 +2071,15 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) /* * Get `exepath` */ - if(evt->get_num_params() > 27) - { - /* In new event versions, with 28 parameters, we can obtain the full exepath with resolved symlinks - * directly from the kernel. + if(evt->get_num_params() > 27) { + /* In new event versions, with 28 parameters, we can obtain the full exepath with resolved + * symlinks directly from the kernel. */ /* Parameter 28: trusted_exepath (type: PT_FSPATH) */ parinfo = evt->get_param(27); evt->get_tinfo()->m_exepath = parinfo->m_val; - } - else - { + } else { /* ONLY VALID FOR OLD SCAP-FILES: * In older event versions we can only rely on our userspace reconstruction */ @@ -2266,104 +2089,93 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) * Moreover if we are not able to retrieve the enter event * we can do nothing. */ - if((etype == PPME_SYSCALL_EXECVE_18_X || - etype == PPME_SYSCALL_EXECVE_19_X || - etype == PPME_SYSCALL_EXECVEAT_X) - && - retrieve_enter_event(enter_evt, evt)) - { + if((etype == PPME_SYSCALL_EXECVE_18_X || etype == PPME_SYSCALL_EXECVE_19_X || + etype == PPME_SYSCALL_EXECVEAT_X) && + retrieve_enter_event(enter_evt, evt)) { std::string fullpath; /* We need to manage the 2 possible cases: - * - enter event is an `EXECVE` - * - enter event is an `EXECVEAT` - */ + * - enter event is an `EXECVE` + * - enter event is an `EXECVEAT` + */ if(enter_evt->get_type() == PPME_SYSCALL_EXECVE_18_E || - enter_evt->get_type() == PPME_SYSCALL_EXECVE_19_E) - { + enter_evt->get_type() == PPME_SYSCALL_EXECVE_19_E) { /* - * Get filename - */ + * Get filename + */ std::string_view filename = enter_evt->get_param(0)->as(); /* This could happen only if we are not able to get the info from the kernel, - * because if the syscall was successful the pathname was surely here the problem - * is that for some reason we were not able to get it with our instrumentation, - * for example when the `bpf_probe_read()` call fails in BPF. - */ - if(filename == "") - { + * because if the syscall was successful the pathname was surely here the problem + * is that for some reason we were not able to get it with our instrumentation, + * for example when the `bpf_probe_read()` call fails in BPF. + */ + if(filename == "") { fullpath = ""; - } - else - { + } else { /* Here the filename can be relative or absolute. */ - fullpath = sinsp_utils::concatenate_paths(evt->get_tinfo()->get_cwd(), filename); + fullpath = + sinsp_utils::concatenate_paths(evt->get_tinfo()->get_cwd(), filename); } - } - else if(enter_evt->get_type() == PPME_SYSCALL_EXECVEAT_E) - { + } else if(enter_evt->get_type() == PPME_SYSCALL_EXECVEAT_E) { /* - * Get dirfd - */ + * Get dirfd + */ int64_t dirfd = enter_evt->get_param(0)->as(); /* - * Get flags - */ + * Get flags + */ uint32_t flags = enter_evt->get_param(2)->as(); /* - * Get pathname - */ + * Get pathname + */ /* The pathname could be: - * - (1) relative (to dirfd). - * - (2) absolute. - * - (3) empty in the kernel because the user specified the `AT_EMPTY_PATH` flag. - * In this case, `dirfd` must refer to a file. - * Please note: - * The path is empty in the kernel but in userspace, we will obtain a ``. - * - (4) empty in the kernel because we fail to recover it from the registries. - * Please note: - * The path is empty in the kernel but in userspace, we will obtain a ``. - */ + * - (1) relative (to dirfd). + * - (2) absolute. + * - (3) empty in the kernel because the user specified the `AT_EMPTY_PATH` flag. + * In this case, `dirfd` must refer to a file. + * Please note: + * The path is empty in the kernel but in userspace, we will obtain a ``. + * - (4) empty in the kernel because we fail to recover it from the registries. + * Please note: + * The path is empty in the kernel but in userspace, we will obtain a ``. + */ std::string_view pathname = enter_evt->get_param(1)->as(); /* If the pathname is `` here we shouldn't have problems during `parse_dirfd`. - * It doesn't start with "/" so it is not considered an absolute path. - */ + * It doesn't start with "/" so it is not considered an absolute path. + */ std::string sdir = parse_dirfd(evt, pathname, dirfd); // Update event fdinfo since parse_dirfd is stateless - if (sdir != "." && sdir != "") - { + if(sdir != "." && sdir != "") { evt->set_fd_info(evt->get_tinfo()->get_fd(dirfd)); } /* (4) In this case, we were not able to recover the pathname from the kernel or - * we are not able to recover information about `dirfd` in our `sinsp` state. - * Fallback to ``. - */ - if((!(flags & PPM_EXVAT_AT_EMPTY_PATH) && pathname == "") || sdir == "") - { + * we are not able to recover information about `dirfd` in our `sinsp` state. + * Fallback to ``. + */ + if((!(flags & PPM_EXVAT_AT_EMPTY_PATH) && pathname == "") || + sdir == "") { fullpath = ""; } - /* (3) In this case we have already obtained the `exepath` and it is `sdir`, we just need - * to sanitize it. - */ - else if(flags & PPM_EXVAT_AT_EMPTY_PATH) - { + /* (3) In this case we have already obtained the `exepath` and it is `sdir`, we just + * need to sanitize it. + */ + else if(flags & PPM_EXVAT_AT_EMPTY_PATH) { /* In this case `sdir` will always be an absolute path. * concatenate_paths takes care of resolving the path - */ + */ fullpath = sinsp_utils::concatenate_paths("", sdir); } /* (2)/(1) If it is relative or absolute we craft the `fullpath` as usual: - * - `sdir` + `pathname` - */ - else - { + * - `sdir` + `pathname` + */ + else { fullpath = sinsp_utils::concatenate_paths(sdir, pathname); } } @@ -2371,8 +2183,7 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) } } - switch(etype) - { + switch(etype) { case PPME_SYSCALL_EXECVE_8_X: case PPME_SYSCALL_EXECVE_13_X: case PPME_SYSCALL_EXECVE_14_X: @@ -2402,14 +2213,12 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) // } // Get the loginuid - if(evt->get_num_params() > 18) - { + if(evt->get_num_params() > 18) { evt->get_tinfo()->set_loginuser(evt->get_param(18)->as()); } // Get execve flags - if(evt->get_num_params() > 19) - { + if(evt->get_num_params() > 19) { uint32_t flags = evt->get_param(19)->as(); evt->get_tinfo()->m_exe_writable = ((flags & PPM_EXE_WRITABLE) != 0); @@ -2419,10 +2228,8 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) } // Get capabilities - if(evt->get_num_params() > 22) - { - if(etype == PPME_SYSCALL_EXECVE_19_X || etype == PPME_SYSCALL_EXECVEAT_X) - { + if(evt->get_num_params() > 22) { + if(etype == PPME_SYSCALL_EXECVE_19_X || etype == PPME_SYSCALL_EXECVEAT_X) { evt->get_tinfo()->m_cap_inheritable = evt->get_param(20)->as(); evt->get_tinfo()->m_cap_permitted = evt->get_param(21)->as(); @@ -2432,28 +2239,27 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) } // Get exe ino fields - if(evt->get_num_params() > 25) - { + if(evt->get_num_params() > 25) { evt->get_tinfo()->m_exe_ino = evt->get_param(23)->as(); evt->get_tinfo()->m_exe_ino_ctime = evt->get_param(24)->as(); evt->get_tinfo()->m_exe_ino_mtime = evt->get_param(25)->as(); - if(evt->get_tinfo()->m_clone_ts != 0) - { - evt->get_tinfo()->m_exe_ino_ctime_duration_clone_ts = evt->get_tinfo()->m_clone_ts - evt->get_tinfo()->m_exe_ino_ctime; + if(evt->get_tinfo()->m_clone_ts != 0) { + evt->get_tinfo()->m_exe_ino_ctime_duration_clone_ts = + evt->get_tinfo()->m_clone_ts - evt->get_tinfo()->m_exe_ino_ctime; } - if(evt->get_tinfo()->m_pidns_init_start_ts != 0 && (evt->get_tinfo()->m_exe_ino_ctime > evt->get_tinfo()->m_pidns_init_start_ts)) - { - evt->get_tinfo()->m_exe_ino_ctime_duration_pidns_start = evt->get_tinfo()->m_exe_ino_ctime - evt->get_tinfo()->m_pidns_init_start_ts; + if(evt->get_tinfo()->m_pidns_init_start_ts != 0 && + (evt->get_tinfo()->m_exe_ino_ctime > evt->get_tinfo()->m_pidns_init_start_ts)) { + evt->get_tinfo()->m_exe_ino_ctime_duration_pidns_start = + evt->get_tinfo()->m_exe_ino_ctime - evt->get_tinfo()->m_pidns_init_start_ts; } } // Get uid - if(evt->get_num_params() > 26) - { + if(evt->get_num_params() > 26) { evt->get_tinfo()->m_user.set_uid(evt->get_param(26)->as()); } @@ -2469,14 +2275,14 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) // and shell pipe flags // - auto spf = evt->get_tinfo()->m_flags & (PPM_CL_PIPE_SRC | PPM_CL_PIPE_DST | PPM_CL_IS_MAIN_THREAD); + auto spf = + evt->get_tinfo()->m_flags & (PPM_CL_PIPE_SRC | PPM_CL_PIPE_DST | PPM_CL_IS_MAIN_THREAD); bool inverted = ((evt->get_tinfo()->m_flags & PPM_CL_CLONE_INVERTED) != 0); evt->get_tinfo()->m_flags = PPM_CL_ACTIVE; evt->get_tinfo()->m_flags |= spf; - if(inverted) - { + if(inverted) { evt->get_tinfo()->m_flags |= PPM_CL_CLONE_INVERTED; } @@ -2494,8 +2300,7 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) // Refresh user / loginuser / group // if we happen to change container id // - if(container_id != evt->get_tinfo()->m_container_id) - { + if(container_id != evt->get_tinfo()->m_container_id) { evt->get_tinfo()->set_user(evt->get_tinfo()->m_user.uid()); evt->get_tinfo()->set_loginuser(evt->get_tinfo()->m_loginuser.uid()); evt->get_tinfo()->set_group(evt->get_tinfo()->m_group.gid()); @@ -2504,8 +2309,7 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) // // If there's a listener, invoke it // - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_execve(evt); } @@ -2517,16 +2321,14 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) * if `evt->get_tinfo()->m_tginfo->get_thread_count() > 1` it means * we still have some not leader threads in the group. */ - if(evt->get_tinfo()->m_tginfo != nullptr && evt->get_tinfo()->m_tginfo->get_thread_count() > 1) - { - for(const auto& thread : evt->get_tinfo()->m_tginfo->get_thread_list()) - { + if(evt->get_tinfo()->m_tginfo != nullptr && + evt->get_tinfo()->m_tginfo->get_thread_count() > 1) { + for(const auto &thread : evt->get_tinfo()->m_tginfo->get_thread_list()) { auto thread_ptr = thread.lock().get(); /* we don't want to remove the main thread since it is the one * running in this parser! */ - if(thread_ptr == nullptr || thread_ptr->is_main_thread()) - { + if(thread_ptr == nullptr || thread_ptr->is_main_thread()) { continue; } m_inspector->remove_thread(thread_ptr->m_tid); @@ -2542,17 +2344,14 @@ void sinsp_parser::parse_execve_exit(sinsp_evt *evt) * - if we have no information about `dirfd` -> sdir = "". * - if `dirfd` has a valid vaule for us -> sdir = path + "/" at the end. */ -std::string sinsp_parser::parse_dirfd(sinsp_evt *evt, std::string_view name, int64_t dirfd) -{ +std::string sinsp_parser::parse_dirfd(sinsp_evt *evt, std::string_view name, int64_t dirfd) { bool is_absolute = false; /* This should never happen but just to be sure. */ - if(name.data() != nullptr) - { + if(name.data() != nullptr) { is_absolute = (!name.empty() && name[0] == '/'); } - if(is_absolute) - { + if(is_absolute) { // // The path is absolute. // Some processes (e.g. irqbalance) actually do this: they pass an invalid fd and @@ -2561,34 +2360,29 @@ std::string sinsp_parser::parse_dirfd(sinsp_evt *evt, std::string_view name, int return "."; } - if(evt->get_tinfo() == NULL) - { + if(evt->get_tinfo() == NULL) { // In this case we can // - neither retrieve the cwd when dirfd == PPM_AT_FDCWD // - nor attempt to query the threadtable for the dirfd fd_info return ""; } - if(dirfd == PPM_AT_FDCWD) - { + if(dirfd == PPM_AT_FDCWD) { return evt->get_tinfo()->get_cwd(); } auto fdinfo = evt->get_tinfo()->get_fd(dirfd); - if(fdinfo == NULL) - { + if(fdinfo == NULL) { return ""; } - if(fdinfo->m_name.back() == '/') - { + if(fdinfo->m_name.back() == '/') { return fdinfo->m_name; } return fdinfo->m_name + '/'; } -void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) { int64_t fd; std::string_view name; std::string_view enter_evt_name; @@ -2601,13 +2395,11 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) uint64_t ino = 0; bool lastevent_retrieved = false; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } - if(etype != PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) - { + if(etype != PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) { // // Load the enter event so we can access its arguments // @@ -2622,16 +2414,13 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) // // Parse the parameters, based on the event type // - if(etype == PPME_SYSCALL_OPEN_X) - { + if(etype == PPME_SYSCALL_OPEN_X) { name = evt->get_param(1)->as(); flags = evt->get_param(2)->as(); - if(evt->get_num_params() > 4) - { + if(evt->get_num_params() > 4) { dev = evt->get_param(4)->as(); - if (evt->get_num_params() > 5) - { + if(evt->get_num_params() > 5) { ino = evt->get_param(5)->as(); } } @@ -2639,13 +2428,11 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) // // Compare with enter event parameters // - if(lastevent_retrieved && enter_evt->get_num_params() >= 2) - { + if(lastevent_retrieved && enter_evt->get_num_params() >= 2) { enter_evt_name = enter_evt->get_param(0)->as(); enter_evt_flags = enter_evt->get_param(1)->as(); - if(enter_evt_name.data() != nullptr && enter_evt_name != "") - { + if(enter_evt_name.data() != nullptr && enter_evt_name != "") { name = enter_evt_name; // keep flags added by the syscall exit probe if present @@ -2656,43 +2443,34 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) } sdir = evt->get_tinfo()->get_cwd(); - } - else if(etype == PPME_SYSCALL_CREAT_X) - { + } else if(etype == PPME_SYSCALL_CREAT_X) { name = evt->get_param(1)->as(); flags = 0; - if(evt->get_num_params() > 3) - { + if(evt->get_num_params() > 3) { dev = evt->get_param(3)->as(); - if (evt->get_num_params() > 4) - { + if(evt->get_num_params() > 4) { ino = evt->get_param(4)->as(); - if (evt->get_num_params() > 5) - { + if(evt->get_num_params() > 5) { uint16_t creat_flags = evt->get_param(5)->as(); - // creat is a special case becuase it has no flags parameter, so the layer info bits arrive from probe - // in a separate creat_flags parameter and flags need to be constructed from it - if (creat_flags & PPM_FD_UPPER_LAYER_CREAT) - { + // creat is a special case becuase it has no flags parameter, so the layer info + // bits arrive from probe in a separate creat_flags parameter and flags need to + // be constructed from it + if(creat_flags & PPM_FD_UPPER_LAYER_CREAT) { flags |= PPM_FD_UPPER_LAYER; - } - else if (creat_flags & PPM_FD_LOWER_LAYER_CREAT) - { + } else if(creat_flags & PPM_FD_LOWER_LAYER_CREAT) { flags |= PPM_FD_LOWER_LAYER; } } } } - if(lastevent_retrieved && enter_evt->get_num_params() >= 1) - { + if(lastevent_retrieved && enter_evt->get_num_params() >= 1) { enter_evt_name = enter_evt->get_param(0)->as(); enter_evt_flags = 0; - if(enter_evt_name.data() != nullptr && enter_evt_name != "") - { + if(enter_evt_name.data() != nullptr && enter_evt_name != "") { name = enter_evt_name; flags |= enter_evt_flags; @@ -2700,9 +2478,7 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) } sdir = evt->get_tinfo()->get_cwd(); - } - else if(etype == PPME_SYSCALL_OPENAT_X) - { + } else if(etype == PPME_SYSCALL_OPENAT_X) { name = enter_evt->get_param(1)->as(); flags = enter_evt->get_param(2)->as(); @@ -2710,28 +2486,21 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) int64_t dirfd = enter_evt->get_param(0)->as(); sdir = parse_dirfd(evt, name, dirfd); - } - else if(etype == PPME_SYSCALL_OPENAT_2_X || etype == PPME_SYSCALL_OPENAT2_X) - { + } else if(etype == PPME_SYSCALL_OPENAT_2_X || etype == PPME_SYSCALL_OPENAT2_X) { name = evt->get_param(2)->as(); flags = evt->get_param(3)->as(); int64_t dirfd = evt->get_param(1)->as(); - if(etype == PPME_SYSCALL_OPENAT_2_X && evt->get_num_params() > 5) - { + if(etype == PPME_SYSCALL_OPENAT_2_X && evt->get_num_params() > 5) { dev = evt->get_param(5)->as(); - if (evt->get_num_params() > 6) - { + if(evt->get_num_params() > 6) { ino = evt->get_param(6)->as(); } - } - else if(etype == PPME_SYSCALL_OPENAT2_X && evt->get_num_params() > 6) - { + } else if(etype == PPME_SYSCALL_OPENAT2_X && evt->get_num_params() > 6) { dev = evt->get_param(6)->as(); - if (evt->get_num_params() > 7) - { + if(evt->get_num_params() > 7) { ino = evt->get_param(7)->as(); } } @@ -2739,14 +2508,12 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) // // Compare with enter event parameters // - if(lastevent_retrieved && enter_evt->get_num_params() >= 3) - { + if(lastevent_retrieved && enter_evt->get_num_params() >= 3) { enter_evt_name = enter_evt->get_param(1)->as(); enter_evt_flags = enter_evt->get_param(2)->as(); int64_t enter_evt_dirfd = enter_evt->get_param(0)->as(); - if(enter_evt_name.data() != nullptr && enter_evt_name != "") - { + if(enter_evt_name.data() != nullptr && enter_evt_name != "") { name = enter_evt_name; // keep flags added by the syscall exit probe if present @@ -2759,51 +2526,41 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) } sdir = parse_dirfd(evt, name, dirfd); - } - else if (etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) - { + } else if(etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) { flags = evt->get_param(2)->as(); name = evt->get_param(3)->as(); - if(evt->get_num_params() > 4) - { + if(evt->get_num_params() > 4) { dev = evt->get_param(4)->as(); - if (evt->get_num_params() > 5) - { + if(evt->get_num_params() > 5) { ino = evt->get_param(5)->as(); } } - // The driver implementation always serves an absolute path for open_by_handle_at using dpath traversal; - // hence there is no need to interpret the path relative to mountfd. + // The driver implementation always serves an absolute path for open_by_handle_at using + // dpath traversal; hence there is no need to interpret the path relative to mountfd. sdir = ""; - } - else - { + } else { ASSERT(false); return; } // XXX not implemented yet - //parinfo = evt->get_param(2); - //ASSERT(parinfo->m_len == sizeof(uint32_t)); - //mode = *(uint32_t*)parinfo->m_val; + // parinfo = evt->get_param(2); + // ASSERT(parinfo->m_len == sizeof(uint32_t)); + // mode = *(uint32_t*)parinfo->m_val; std::string fullpath = sinsp_utils::concatenate_paths(sdir, name); - if(fd >= 0) - { + if(fd >= 0) { // // Populate the new fdi // auto fdi = m_inspector->build_fdinfo(); - if(flags & PPM_O_DIRECTORY) - { + if(flags & PPM_O_DIRECTORY) { fdi->m_type = SCAP_FD_DIRECTORY; - } - else - { + } else { fdi->m_type = SCAP_FD_FILE_V2; } @@ -2813,12 +2570,10 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) fdi->m_ino = ino; fdi->add_filename_raw(name); fdi->add_filename(fullpath); - if(flags & PPM_FD_UPPER_LAYER) - { + if(flags & PPM_FD_UPPER_LAYER) { fdi->set_overlay_upper(); } - if(flags & PPM_FD_LOWER_LAYER) - { + if(flags & PPM_FD_LOWER_LAYER) { fdi->set_overlay_lower(); } @@ -2828,20 +2583,16 @@ void sinsp_parser::parse_open_openat_creat_exit(sinsp_evt *evt) evt->set_fd_info(evt->get_tinfo()->add_fd(fd, std::move(fdi))); } - if(m_inspector->get_observer() && !(flags & PPM_O_DIRECTORY)) - { + if(m_inspector->get_observer() && !(flags & PPM_O_DIRECTORY)) { m_inspector->get_observer()->on_file_open(evt, fullpath, flags); } } -void sinsp_parser::parse_fchmod_fchown_exit(sinsp_evt *evt) -{ - +void sinsp_parser::parse_fchmod_fchown_exit(sinsp_evt *evt) { // Both of these syscalls act on fds although they do not // create them. Take the fd argument and attempt to look up // the fd from the thread. - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -2852,10 +2603,14 @@ void sinsp_parser::parse_fchmod_fchown_exit(sinsp_evt *evt) } // -// Helper function to allocate a socket fd, initialize it by parsing its parameters and add it to the fd table of the given thread. +// Helper function to allocate a socket fd, initialize it by parsing its parameters and add it to +// the fd table of the given thread. // -inline void sinsp_parser::add_socket(sinsp_evt *evt, int64_t fd, uint32_t domain, uint32_t type, uint32_t protocol) -{ +inline void sinsp_parser::add_socket(sinsp_evt *evt, + int64_t fd, + uint32_t domain, + uint32_t type, + uint32_t protocol) { // // Populate the new fdi // @@ -2864,73 +2619,49 @@ inline void sinsp_parser::add_socket(sinsp_evt *evt, int64_t fd, uint32_t domain fdi->m_type = SCAP_FD_UNKNOWN; fdi->m_sockinfo.m_ipv4info.m_fields.m_l4proto = SCAP_L4_UNKNOWN; - if(domain == PPM_AF_UNIX) - { + if(domain == PPM_AF_UNIX) { fdi->m_type = SCAP_FD_UNIX_SOCK; - } - else if(domain == PPM_AF_INET || domain == PPM_AF_INET6) - { - fdi->m_type = (domain == PPM_AF_INET)? SCAP_FD_IPV4_SOCK : SCAP_FD_IPV6_SOCK; + } else if(domain == PPM_AF_INET || domain == PPM_AF_INET6) { + fdi->m_type = (domain == PPM_AF_INET) ? SCAP_FD_IPV4_SOCK : SCAP_FD_IPV6_SOCK; uint8_t l4proto = SCAP_L4_UNKNOWN; - if(protocol == IPPROTO_TCP) - { - l4proto = (type == SOCK_RAW)? SCAP_L4_RAW : SCAP_L4_TCP; - } - else if(protocol == IPPROTO_UDP) - { - l4proto = (type == SOCK_RAW)? SCAP_L4_RAW : SCAP_L4_UDP; - } - else if(protocol == IPPROTO_IP) - { + if(protocol == IPPROTO_TCP) { + l4proto = (type == SOCK_RAW) ? SCAP_L4_RAW : SCAP_L4_TCP; + } else if(protocol == IPPROTO_UDP) { + l4proto = (type == SOCK_RAW) ? SCAP_L4_RAW : SCAP_L4_UDP; + } else if(protocol == IPPROTO_IP) { // // XXX: we mask type because, starting from linux 2.6.27, type can be ORed with // SOCK_NONBLOCK and SOCK_CLOEXEC. We need to validate that byte masking is // acceptable // - if((type & 0xff) == SOCK_STREAM) - { + if((type & 0xff) == SOCK_STREAM) { l4proto = SCAP_L4_TCP; - } - else if((type & 0xff) == SOCK_DGRAM) - { + } else if((type & 0xff) == SOCK_DGRAM) { l4proto = SCAP_L4_UDP; - } - else - { + } else { ASSERT(false); } - } - else if(protocol == IPPROTO_ICMP) - { - l4proto = (type == SOCK_RAW)? SCAP_L4_RAW : SCAP_L4_ICMP; - } - else if(protocol == IPPROTO_RAW) - { + } else if(protocol == IPPROTO_ICMP) { + l4proto = (type == SOCK_RAW) ? SCAP_L4_RAW : SCAP_L4_ICMP; + } else if(protocol == IPPROTO_RAW) { l4proto = SCAP_L4_RAW; } - if(domain == PPM_AF_INET) - { + if(domain == PPM_AF_INET) { fdi->m_sockinfo.m_ipv4info.m_fields.m_l4proto = l4proto; - } - else - { + } else { memset(&(fdi->m_sockinfo.m_ipv6info), 0, sizeof(fdi->m_sockinfo.m_ipv6info)); fdi->m_sockinfo.m_ipv6info.m_fields.m_l4proto = l4proto; } - } - else if(domain == PPM_AF_NETLINK) - { + } else if(domain == PPM_AF_NETLINK) { fdi->m_type = SCAP_FD_NETLINK; - } - else - { - if(domain != 10 && // IPv6 + } else { + if(domain != 10 && // IPv6 #ifdef _WIN32 - domain != AF_INET6 && // IPv6 on Windows + domain != AF_INET6 && // IPv6 on Windows #endif - domain != 17) // AF_PACKET, used for packet capture + domain != 17) // AF_PACKET, used for packet capture { // // IPv6 will go here @@ -2939,11 +2670,9 @@ inline void sinsp_parser::add_socket(sinsp_evt *evt, int64_t fd, uint32_t domain } } - if(fdi->m_type == SCAP_FD_UNKNOWN) - { + if(fdi->m_type == SCAP_FD_UNKNOWN) { SINSP_STR_DEBUG("Unknown fd fd=" + std::to_string(fd) + - " domain=" + std::to_string(domain) + - " type=" + std::to_string(type) + + " domain=" + std::to_string(domain) + " type=" + std::to_string(type) + " protocol=" + std::to_string(protocol) + " pid=" + std::to_string(evt->get_tinfo()->m_pid) + " comm=" + evt->get_tinfo()->m_comm); @@ -2965,45 +2694,39 @@ inline void sinsp_parser::add_socket(sinsp_evt *evt, int64_t fd, uint32_t domain * evt->get_tinfo() != nullptr * */ -inline void sinsp_parser::infer_sendto_fdinfo(sinsp_evt* const evt) -{ - if((evt->get_fd_info() != nullptr) || (evt->get_tinfo() == nullptr)) - { +inline void sinsp_parser::infer_sendto_fdinfo(sinsp_evt *const evt) { + if((evt->get_fd_info() != nullptr) || (evt->get_tinfo() == nullptr)) { return; } const uint32_t FILE_DESCRIPTOR_PARAM = 0; const uint32_t SOCKET_TUPLE_PARAM = 2; - const sinsp_evt_param* parinfo = nullptr; + const sinsp_evt_param *parinfo = nullptr; ASSERT(evt->get_param_info(FILE_DESCRIPTOR_PARAM)->type == PT_FD); int64_t fd = evt->get_param(FILE_DESCRIPTOR_PARAM)->as(); - if(fd < 0) - { + if(fd < 0) { // Call to sendto() with an invalid file descriptor return; } parinfo = evt->get_param(SOCKET_TUPLE_PARAM); - const char addr_family = *((char*) parinfo->m_val); + const char addr_family = *((char *)parinfo->m_val); - if((addr_family == AF_INET) || (addr_family == AF_INET6)) - { - const uint32_t domain = (addr_family == AF_INET) - ? PPM_AF_INET - : PPM_AF_INET6; + if((addr_family == AF_INET) || (addr_family == AF_INET6)) { + const uint32_t domain = (addr_family == AF_INET) ? PPM_AF_INET : PPM_AF_INET6; #ifndef _WIN32 - SINSP_DEBUG("Call to sendto() with fd=%d; missing socket() " - "data. Adding socket %s/SOCK_DGRAM/IPPROTO_UDP " - "for command '%s', pid %d", - fd, - (domain == PPM_AF_INET) ? "PPM_AF_INET" - : "PPM_AF_INET6", - evt->get_tinfo()->get_comm().c_str(), - evt->get_tinfo()->m_pid); + SINSP_DEBUG( + "Call to sendto() with fd=%d; missing socket() " + "data. Adding socket %s/SOCK_DGRAM/IPPROTO_UDP " + "for command '%s', pid %d", + fd, + (domain == PPM_AF_INET) ? "PPM_AF_INET" : "PPM_AF_INET6", + evt->get_tinfo()->get_comm().c_str(), + evt->get_tinfo()->m_pid); #endif // Here we're assuming sendto() means SOCK_DGRAM/UDP, but it @@ -3013,8 +2736,7 @@ inline void sinsp_parser::infer_sendto_fdinfo(sinsp_evt* const evt) } } -void sinsp_parser::parse_socket_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_socket_exit(sinsp_evt *evt) { int64_t fd; uint32_t domain; uint32_t type; @@ -3022,31 +2744,29 @@ void sinsp_parser::parse_socket_exit(sinsp_evt *evt) sinsp_evt *enter_evt = &m_tmp_evt; // - // NOTE: we don't check the return value of get_param() because we know the arguments we need are there. + // NOTE: we don't check the return value of get_param() because we know the arguments we need + // are there. // XXX this extraction would be much faster if we parsed the event manually to extract the // parameters in one scan. We don't care too much because we assume that we get here // seldom enough that saving few tens of CPU cycles is not important. // fd = evt->get_param(0)->as(); - if(fd < 0) - { + if(fd < 0) { // // socket() failed. Nothing to add to the table. // return; } - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } // // Load the enter event so we can access its arguments // - if(!retrieve_enter_event(enter_evt, evt)) - { + if(!retrieve_enter_event(enter_evt, evt)) { return; } @@ -3063,29 +2783,25 @@ void sinsp_parser::parse_socket_exit(sinsp_evt *evt) add_socket(evt, fd, domain, type, protocol); } -void sinsp_parser::parse_bind_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_bind_exit(sinsp_evt *evt) { const sinsp_evt_param *parinfo; int64_t retval; const char *parstr; uint8_t *packed_data; uint8_t family; - if(evt->get_fd_info() == NULL) - { + if(evt->get_fd_info() == NULL) { return; } retval = evt->get_param(0)->as(); - if(retval < 0) - { + if(retval < 0) { return; } parinfo = evt->get_param(1); - if(parinfo->m_len == 0) - { + if(parinfo->m_len == 0) { // // No address, there's nothing we can really do with this. // This happens for socket types that we don't support, so we have the assertion @@ -3095,7 +2811,7 @@ void sinsp_parser::parse_bind_exit(sinsp_evt *evt) return; } - packed_data = (uint8_t*)parinfo->m_val; + packed_data = (uint8_t *)parinfo->m_val; family = *packed_data; @@ -3103,44 +2819,40 @@ void sinsp_parser::parse_bind_exit(sinsp_evt *evt) // Update the FD info with this tuple, assume that if port > 0, means that // the socket is used for listening // - if(family == PPM_AF_INET) - { + if(family == PPM_AF_INET) { uint32_t ip; uint16_t port; memcpy(&ip, packed_data + 1, sizeof(ip)); memcpy(&port, packed_data + 5, sizeof(port)); - if(port > 0) - { + if(port > 0) { evt->get_fd_info()->m_type = SCAP_FD_IPV4_SERVSOCK; evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_ip = ip; evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_port = port; evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_l4proto = - evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_l4proto; + evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_l4proto; evt->get_fd_info()->set_role_server(); } - } - else if (family == PPM_AF_INET6) - { - uint8_t* ip = packed_data + 1; + } else if(family == PPM_AF_INET6) { + uint8_t *ip = packed_data + 1; uint16_t port; memcpy(&port, packed_data + 17, sizeof(uint16_t)); - if(port > 0) - { - if(sinsp_utils::is_ipv4_mapped_ipv6(ip)) - { + if(port > 0) { + if(sinsp_utils::is_ipv4_mapped_ipv6(ip)) { evt->get_fd_info()->m_type = SCAP_FD_IPV4_SERVSOCK; evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_l4proto = - evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_l4proto; - memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_ip, packed_data + 13, sizeof(uint32_t)); + evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_l4proto; + memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_ip, + packed_data + 13, + sizeof(uint32_t)); evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_port = port; - } - else - { + } else { evt->get_fd_info()->m_type = SCAP_FD_IPV6_SERVSOCK; evt->get_fd_info()->m_sockinfo.m_ipv6serverinfo.m_port = port; - memcpy(evt->get_fd_info()->m_sockinfo.m_ipv6serverinfo.m_ip.m_b, ip, sizeof(ipv6addr)); + memcpy(evt->get_fd_info()->m_sockinfo.m_ipv6serverinfo.m_ip.m_b, + ip, + sizeof(ipv6addr)); evt->get_fd_info()->m_sockinfo.m_ipv6serverinfo.m_l4proto = - evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_l4proto; + evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_l4proto; } evt->get_fd_info()->set_role_server(); } @@ -3153,8 +2865,7 @@ void sinsp_parser::parse_bind_exit(sinsp_evt *evt) // // If there's a listener callback, invoke it // - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_bind(evt); } } @@ -3162,24 +2873,21 @@ void sinsp_parser::parse_bind_exit(sinsp_evt *evt) /** * Register a socket in pending state */ -void sinsp_parser::parse_connect_enter(sinsp_evt *evt){ - const sinsp_evt_param *parinfo; - const char *parstr; - uint8_t *packed_data; +void sinsp_parser::parse_connect_enter(sinsp_evt *evt) { + const sinsp_evt_param *parinfo; + const char *parstr; + uint8_t *packed_data; - if(evt->get_fd_info() == NULL) - { - return; - } + if(evt->get_fd_info() == NULL) { + return; + } - if (m_track_connection_status) { + if(m_track_connection_status) { evt->get_fd_info()->set_socket_pending(); } - if(evt->get_num_params() < 2) - { - switch(evt->get_fd_info()->m_type) - { + if(evt->get_num_params() < 2) { + switch(evt->get_fd_info()->m_type) { case SCAP_FD_IPV4_SOCK: evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dip = 0; evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dport = 0; @@ -3192,185 +2900,179 @@ void sinsp_parser::parse_connect_enter(sinsp_evt *evt){ break; } sinsp_utils::sockinfo_to_str(&evt->get_fd_info()->m_sockinfo, - evt->get_fd_info()->m_type, &evt->get_paramstr_storage()[0], - (uint32_t)evt->get_paramstr_storage().size(), - m_inspector->is_hostname_and_port_resolution_enabled()); + evt->get_fd_info()->m_type, + &evt->get_paramstr_storage()[0], + (uint32_t)evt->get_paramstr_storage().size(), + m_inspector->is_hostname_and_port_resolution_enabled()); evt->get_fd_info()->m_name = &evt->get_paramstr_storage()[0]; return; } - parinfo = evt->get_param(1); - if(parinfo->m_len == 0) - { + parinfo = evt->get_param(1); + if(parinfo->m_len == 0) { // // Address can be NULL: // sk is a TCP fastopen active socket and // TCP_FASTOPEN_CONNECT sockopt is set and // we already have a valid cookie for this socket. // - return; - } + return; + } - packed_data = (uint8_t*)parinfo->m_val; + packed_data = (uint8_t *)parinfo->m_val; uint8_t family = *packed_data; - if(family == PPM_AF_INET) - { + if(family == PPM_AF_INET) { evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; - memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dip, packed_data + 1, sizeof(uint32_t)); - memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dport, packed_data + 5, sizeof(uint16_t)); - } - else if (family == PPM_AF_INET6) - { + memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dip, + packed_data + 1, + sizeof(uint32_t)); + memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dport, + packed_data + 5, + sizeof(uint16_t)); + } else if(family == PPM_AF_INET6) { uint16_t port; memcpy(&port, packed_data + 17, sizeof(uint16_t)); - uint8_t* ip = packed_data + 1; - if(sinsp_utils::is_ipv4_mapped_ipv6(ip)) - { + uint8_t *ip = packed_data + 1; + if(sinsp_utils::is_ipv4_mapped_ipv6(ip)) { evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; - memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dip, packed_data + 13, sizeof(uint32_t)); + memcpy(&evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dip, + packed_data + 13, + sizeof(uint32_t)); evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_dport = port; - } - else - { + } else { evt->get_fd_info()->m_type = SCAP_FD_IPV6_SOCK; evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_dport = port; - memcpy(evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b, ip, sizeof(ipv6addr)); + memcpy(evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b, + ip, + sizeof(ipv6addr)); } } else { - - // - // Add the friendly name to the fd info - // - evt->get_fd_info()->m_name = evt->get_param_as_str(1, &parstr, sinsp_evt::PF_SIMPLE); + // + // Add the friendly name to the fd info + // + evt->get_fd_info()->m_name = evt->get_param_as_str(1, &parstr, sinsp_evt::PF_SIMPLE); } - // - // If there's a listener callback and we're tracking connection status, invoke it - // - if(m_track_connection_status && m_inspector->get_observer()) - { - m_inspector->get_observer()->on_connect(evt, packed_data); - } + // + // If there's a listener callback and we're tracking connection status, invoke it + // + if(m_track_connection_status && m_inspector->get_observer()) { + m_inspector->get_observer()->on_connect(evt, packed_data); + } } -inline void sinsp_parser::fill_client_socket_info(sinsp_evt *evt, uint8_t *packed_data, bool overwrite_dest) { - uint8_t family; - const char *parstr; - bool changed; - - // - // Validate the family - // - family = *packed_data; - - // - // Fill the fd with the socket info - // - if(family == PPM_AF_INET || family == PPM_AF_INET6) - { - if(family == PPM_AF_INET6) - { - // - // Check to see if it's an IPv4-mapped IPv6 address - // (http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses) - // - uint8_t* sip = packed_data + 1; - uint8_t* dip = packed_data + 19; - - if(!(sinsp_utils::is_ipv4_mapped_ipv6(sip) && sinsp_utils::is_ipv4_mapped_ipv6(dip))) - { - evt->get_fd_info()->m_type = SCAP_FD_IPV6_SOCK; - changed = m_inspector->get_parser()->set_ipv6_addresses_and_ports(evt->get_fd_info(), packed_data, overwrite_dest); - } - else - { - evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; - changed = m_inspector->get_parser()->set_ipv4_mapped_ipv6_addresses_and_ports(evt->get_fd_info(), packed_data, overwrite_dest); - } - } - else - { - evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; - - // - // Update the FD info with this tuple - // - changed = m_inspector->get_parser()->set_ipv4_addresses_and_ports(evt->get_fd_info(), packed_data, overwrite_dest); - } - - if(changed && evt->get_fd_info()->is_role_server() && evt->get_fd_info()->is_udp_socket()) - { - // connect done by a udp server, swap the addresses - swap_addresses(evt->get_fd_info()); - } - - // - // Add the friendly name to the fd info - // +inline void sinsp_parser::fill_client_socket_info(sinsp_evt *evt, + uint8_t *packed_data, + bool overwrite_dest) { + uint8_t family; + const char *parstr; + bool changed; + + // + // Validate the family + // + family = *packed_data; + + // + // Fill the fd with the socket info + // + if(family == PPM_AF_INET || family == PPM_AF_INET6) { + if(family == PPM_AF_INET6) { + // + // Check to see if it's an IPv4-mapped IPv6 address + // (http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses) + // + uint8_t *sip = packed_data + 1; + uint8_t *dip = packed_data + 19; + + if(!(sinsp_utils::is_ipv4_mapped_ipv6(sip) && sinsp_utils::is_ipv4_mapped_ipv6(dip))) { + evt->get_fd_info()->m_type = SCAP_FD_IPV6_SOCK; + changed = + m_inspector->get_parser()->set_ipv6_addresses_and_ports(evt->get_fd_info(), + packed_data, + overwrite_dest); + } else { + evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; + changed = m_inspector->get_parser()->set_ipv4_mapped_ipv6_addresses_and_ports( + evt->get_fd_info(), + packed_data, + overwrite_dest); + } + } else { + evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; + + // + // Update the FD info with this tuple + // + changed = m_inspector->get_parser()->set_ipv4_addresses_and_ports(evt->get_fd_info(), + packed_data, + overwrite_dest); + } + + if(changed && evt->get_fd_info()->is_role_server() && evt->get_fd_info()->is_udp_socket()) { + // connect done by a udp server, swap the addresses + swap_addresses(evt->get_fd_info()); + } + + // + // Add the friendly name to the fd info + // sinsp_utils::sockinfo_to_str(&evt->get_fd_info()->m_sockinfo, - evt->get_fd_info()->m_type, &evt->get_paramstr_storage()[0], - (uint32_t)evt->get_paramstr_storage().size(), - m_inspector->is_hostname_and_port_resolution_enabled()); + evt->get_fd_info()->m_type, + &evt->get_paramstr_storage()[0], + (uint32_t)evt->get_paramstr_storage().size(), + m_inspector->is_hostname_and_port_resolution_enabled()); evt->get_fd_info()->m_name = &evt->get_paramstr_storage()[0]; - } - else - { - if(!evt->get_fd_info()->is_unix_socket()) - { - // - // This should happen only in case of a bug in our code, because I'm assuming that the OS - // causes a connect with the wrong socket type to fail. - // Assert in debug mode and just keep going in release mode. - // - ASSERT(false); - } - - // - // Add the friendly name to the fd info - // - evt->get_fd_info()->m_name = evt->get_param_as_str(1, &parstr, sinsp_evt::PF_SIMPLE); - - // - // Update the FD with this tuple - // - evt->get_fd_info()->set_unix_info(packed_data); - } - - if(evt->get_fd_info()->is_role_none()) - { - // - // Mark this fd as a client - // - evt->get_fd_info()->set_role_client(); - } + } else { + if(!evt->get_fd_info()->is_unix_socket()) { + // + // This should happen only in case of a bug in our code, because I'm assuming that the + // OS causes a connect with the wrong socket type to fail. Assert in debug mode and just + // keep going in release mode. + // + ASSERT(false); + } + + // + // Add the friendly name to the fd info + // + evt->get_fd_info()->m_name = evt->get_param_as_str(1, &parstr, sinsp_evt::PF_SIMPLE); + + // + // Update the FD with this tuple + // + evt->get_fd_info()->set_unix_info(packed_data); + } + + if(evt->get_fd_info()->is_role_none()) { + // + // Mark this fd as a client + // + evt->get_fd_info()->set_role_client(); + } } -void sinsp_parser::parse_connect_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_connect_exit(sinsp_evt *evt) { const sinsp_evt_param *parinfo; uint8_t *packed_data; int64_t retval; int64_t fd; bool force_overwrite_stale_data = false; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } - if(evt->get_fd_info() == nullptr) - { + if(evt->get_fd_info() == nullptr) { // Perhaps we dropped the connect enter event. // try harder to be resilient. - if(evt->get_num_params() > 2) - { + if(evt->get_num_params() > 2) { fd = evt->get_param(2)->as(); - if(fd < 0) - { + if(fd < 0) { // // Accept failure. // Do nothing. @@ -3379,8 +3081,7 @@ void sinsp_parser::parse_connect_exit(sinsp_evt *evt) } evt->get_tinfo()->m_lastevent_fd = fd; evt->set_fd_info(evt->get_tinfo()->get_fd(evt->get_tinfo()->m_lastevent_fd)); - if (evt->get_fd_info() == nullptr) - { + if(evt->get_fd_info() == nullptr) { // Ok this is a completely new fd; // we probably lost too many events. // Bye. @@ -3389,40 +3090,31 @@ void sinsp_parser::parse_connect_exit(sinsp_evt *evt) // ok we got stale data; we probably missed the connect enter event on this thread. // Force overwrite existing fdinfo socket data force_overwrite_stale_data = true; - } - else - { + } else { return; } } retval = evt->get_param(0)->as(); - if (m_track_connection_status) - { - if (retval == -SE_EINPROGRESS) { + if(m_track_connection_status) { + if(retval == -SE_EINPROGRESS) { evt->get_fd_info()->set_socket_pending(); } else if(retval < 0) { evt->get_fd_info()->set_socket_failed(); } else { evt->get_fd_info()->set_socket_connected(); } - } - else - { - if (retval < 0 && retval != -SE_EINPROGRESS) - { + } else { + if(retval < 0 && retval != -SE_EINPROGRESS) { return; - } - else - { + } else { evt->get_fd_info()->set_socket_connected(); } } parinfo = evt->get_param(1); - if(parinfo->m_len == 0) - { + if(parinfo->m_len == 0) { // // Address can be NULL: // sk is a TCP fastopen active socket and @@ -3432,31 +3124,28 @@ void sinsp_parser::parse_connect_exit(sinsp_evt *evt) return; } - packed_data = (uint8_t*)parinfo->m_val; + packed_data = (uint8_t *)parinfo->m_val; - fill_client_socket_info(evt, packed_data, force_overwrite_stale_data); + fill_client_socket_info(evt, packed_data, force_overwrite_stale_data); // // If there's a listener callback, invoke it // - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_connect(evt, packed_data); } } -void sinsp_parser::parse_accept_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_accept_exit(sinsp_evt *evt) { const sinsp_evt_param *parinfo; int64_t fd; - uint8_t* packed_data; + uint8_t *packed_data; const char *parstr; // // Lookup the thread // - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -3465,8 +3154,7 @@ void sinsp_parser::parse_accept_exit(sinsp_evt *evt) // fd = evt->get_param(0)->as(); - if(fd < 0) - { + if(fd < 0) { // // Accept failure. // Do nothing. @@ -3483,8 +3171,7 @@ void sinsp_parser::parse_accept_exit(sinsp_evt *evt) // Extract the address // parinfo = evt->get_param(1); - if(parinfo->m_len == 0) - { + if(parinfo->m_len == 0) { // // No address, there's nothing we can really do with this. // This happens for socket types that we don't support, so we have the assertion @@ -3493,47 +3180,37 @@ void sinsp_parser::parse_accept_exit(sinsp_evt *evt) return; } - packed_data = (uint8_t*)parinfo->m_val; + packed_data = (uint8_t *)parinfo->m_val; // // Populate the fd info class // auto fdi = m_inspector->build_fdinfo(); - if(*packed_data == PPM_AF_INET) - { + if(*packed_data == PPM_AF_INET) { set_ipv4_addresses_and_ports(fdi.get(), packed_data); fdi->m_type = SCAP_FD_IPV4_SOCK; fdi->m_sockinfo.m_ipv4info.m_fields.m_l4proto = SCAP_L4_TCP; - } - else if(*packed_data == PPM_AF_INET6) - { + } else if(*packed_data == PPM_AF_INET6) { // // Check to see if it's an IPv4-mapped IPv6 address // (http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses) // - uint8_t* sip = packed_data + 1; - uint8_t* dip = packed_data + 19; + uint8_t *sip = packed_data + 1; + uint8_t *dip = packed_data + 19; - if(sinsp_utils::is_ipv4_mapped_ipv6(sip) && sinsp_utils::is_ipv4_mapped_ipv6(dip)) - { + if(sinsp_utils::is_ipv4_mapped_ipv6(sip) && sinsp_utils::is_ipv4_mapped_ipv6(dip)) { set_ipv4_mapped_ipv6_addresses_and_ports(fdi.get(), packed_data); fdi->m_type = SCAP_FD_IPV4_SOCK; fdi->m_sockinfo.m_ipv4info.m_fields.m_l4proto = SCAP_L4_TCP; - } - else - { + } else { set_ipv6_addresses_and_ports(fdi.get(), packed_data); fdi->m_type = SCAP_FD_IPV6_SOCK; fdi->m_sockinfo.m_ipv6info.m_fields.m_l4proto = SCAP_L4_TCP; } - } - else if(*packed_data == PPM_AF_UNIX) - { + } else if(*packed_data == PPM_AF_UNIX) { fdi->m_type = SCAP_FD_UNIX_SOCK; fdi->set_unix_info(packed_data); - } - else - { + } else { // // Unsupported family // @@ -3543,8 +3220,7 @@ void sinsp_parser::parse_accept_exit(sinsp_evt *evt) fdi->m_name = evt->get_param_as_str(1, &parstr, sinsp_evt::PF_SIMPLE); fdi->m_flags = 0; - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_accept(evt, fd, packed_data, fdi.get()); } @@ -3564,16 +3240,13 @@ void sinsp_parser::parse_accept_exit(sinsp_evt *evt) evt->set_fd_info(evt->get_tinfo()->add_fd(fd, std::move(fdi))); } -void sinsp_parser::parse_close_enter(sinsp_evt *evt) -{ - if(evt->get_tinfo() == nullptr) - { +void sinsp_parser::parse_close_enter(sinsp_evt *evt) { + if(evt->get_tinfo() == nullptr) { return; } evt->set_fd_info(evt->get_tinfo()->get_fd(evt->get_tinfo()->m_lastevent_fd)); - if(evt->get_fd_info() == NULL) - { + if(evt->get_fd_info() == NULL) { return; } @@ -3585,10 +3258,8 @@ void sinsp_parser::parse_close_enter(sinsp_evt *evt) // (process FD table, connection table...). // It's invoked when a close() or a thread exit happens. // -void sinsp_parser::erase_fd(erase_fd_params* params) -{ - if(params->m_fdinfo == NULL) - { +void sinsp_parser::erase_fd(erase_fd_params *params) { + if(params->m_fdinfo == NULL) { // // This happens when more than one close has been canceled at the same time for // this thread. Since we currently handle just one canceling at at time (we @@ -3605,20 +3276,17 @@ void sinsp_parser::erase_fd(erase_fd_params* params) // // Schedule the fd for removal // - if(params->m_remove_from_table) - { + if(params->m_remove_from_table) { m_inspector->set_tid_of_fd_to_remove(params->m_tinfo->m_tid); m_inspector->get_fds_to_remove().push_back(params->m_fd); } - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_erase_fd(params); } } -void sinsp_parser::parse_close_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_close_exit(sinsp_evt *evt) { int64_t retval; // @@ -3629,10 +3297,8 @@ void sinsp_parser::parse_close_exit(sinsp_evt *evt) // // If the close() was successful, do the cleanup // - if(retval >= 0) - { - if(evt->get_fd_info() == nullptr || evt->get_tinfo() == nullptr) - { + if(retval >= 0) { + if(evt->get_fd_info() == nullptr || evt->get_tinfo() == nullptr) { return; } @@ -3642,14 +3308,11 @@ void sinsp_parser::parse_close_exit(sinsp_evt *evt) // erase_fd_params eparams; - if(evt->get_fd_info()->m_flags & sinsp_fdinfo::FLAGS_CLOSE_CANCELED) - { + if(evt->get_fd_info()->m_flags & sinsp_fdinfo::FLAGS_CLOSE_CANCELED) { evt->get_fd_info()->m_flags &= ~sinsp_fdinfo::FLAGS_CLOSE_CANCELED; eparams.m_fd = CANCELED_FD_NUMBER; eparams.m_fdinfo = evt->get_tinfo()->get_fd(CANCELED_FD_NUMBER); - } - else - { + } else { eparams.m_fd = evt->get_tinfo()->m_lastevent_fd; eparams.m_fdinfo = evt->get_fd_info(); } @@ -3662,11 +3325,8 @@ void sinsp_parser::parse_close_exit(sinsp_evt *evt) eparams.m_ts = evt->get_ts(); erase_fd(&eparams); - } - else - { - if(evt->get_fd_info() != NULL) - { + } else { + if(evt->get_fd_info() != NULL) { evt->get_fd_info()->m_flags &= ~sinsp_fdinfo::FLAGS_CLOSE_IN_PROGRESS; } @@ -3674,27 +3334,22 @@ void sinsp_parser::parse_close_exit(sinsp_evt *evt) // It is normal when a close fails that the fd lookup failed, so we revert the // increment of m_n_failed_fd_lookups (for the enter event too if there's one). // - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_failed_fd_lookups--; } - if(evt->get_tinfo() && evt->get_tinfo()->is_lastevent_data_valid()) - { - if (m_sinsp_stats_v2 != nullptr) - { + if(evt->get_tinfo() && evt->get_tinfo()->is_lastevent_data_valid()) { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_failed_fd_lookups--; } } } } -void sinsp_parser::add_pipe(sinsp_evt *evt, int64_t fd, uint64_t ino, uint32_t openflags) -{ +void sinsp_parser::add_pipe(sinsp_evt *evt, int64_t fd, uint64_t ino, uint32_t openflags) { // // lookup the thread info // - if(!evt->get_tinfo()) - { + if(!evt->get_tinfo()) { return; } @@ -3712,8 +3367,7 @@ void sinsp_parser::add_pipe(sinsp_evt *evt, int64_t fd, uint64_t ino, uint32_t o evt->set_fd_info(evt->get_tinfo()->add_fd(fd, std::move(fdi))); } -void sinsp_parser::parse_socketpair_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_socketpair_exit(sinsp_evt *evt) { int64_t fd1, fd2; int64_t retval; uint64_t source_address; @@ -3721,16 +3375,14 @@ void sinsp_parser::parse_socketpair_exit(sinsp_evt *evt) retval = evt->get_param(0)->as(); - if(retval < 0) - { + if(retval < 0) { // // socketpair() failed. Nothing to add to the table. // return; } - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { // There is nothing we can do here if tinfo is missing return; } @@ -3742,8 +3394,7 @@ void sinsp_parser::parse_socketpair_exit(sinsp_evt *evt) /* ** In the case of 2 equal fds we ignore them (e.g. both equal to -1). */ - if(fd1 == fd2) - { + if(fd1 == fd2) { evt->set_fd_info(NULL); return; } @@ -3761,8 +3412,7 @@ void sinsp_parser::parse_socketpair_exit(sinsp_evt *evt) evt->get_tinfo()->add_fd(fd2, std::move(fdi2)); } -void sinsp_parser::parse_pipe_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_pipe_exit(sinsp_evt *evt) { int64_t fd1, fd2; int64_t retval; uint64_t ino; @@ -3770,8 +3420,7 @@ void sinsp_parser::parse_pipe_exit(sinsp_evt *evt) retval = evt->get_param(0)->as(); - if(retval < 0) - { + if(retval < 0) { // // pipe() failed. Nothing to add to the table. // @@ -3784,8 +3433,7 @@ void sinsp_parser::parse_pipe_exit(sinsp_evt *evt) ino = evt->get_param(3)->as(); - if(evt->get_type() == PPME_SYSCALL_PIPE2_X) - { + if(evt->get_type() == PPME_SYSCALL_PIPE2_X) { openflags = evt->get_param(4)->as(); } @@ -3793,14 +3441,11 @@ void sinsp_parser::parse_pipe_exit(sinsp_evt *evt) add_pipe(evt, fd2, ino, openflags); } - -void sinsp_parser::parse_thread_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_thread_exit(sinsp_evt *evt) { /* We set the `m_tinfo` in `reset()`. * If we don't have the thread info we do nothing, this thread is already deleted */ - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -3811,8 +3456,7 @@ void sinsp_parser::parse_thread_exit(sinsp_evt *evt) * necessary at all since here we shouldn't receive dead threads. * This is first place where we mark threads as dead. */ - if(evt->get_tinfo()->m_tginfo != nullptr && !evt->get_tinfo()->is_dead()) - { + if(evt->get_tinfo()->m_tginfo != nullptr && !evt->get_tinfo()->is_dead()) { evt->get_tinfo()->m_tginfo->decrement_thread_count(); } evt->get_tinfo()->set_dead(); @@ -3825,39 +3469,35 @@ void sinsp_parser::parse_thread_exit(sinsp_evt *evt) /* If this thread has no children we don't send the reaper info from the kernel, * so we do nothing. */ - if(evt->get_tinfo()->m_children.size() == 0) - { + if(evt->get_tinfo()->m_children.size() == 0) { return; } /* [Set the reaper to the current thread] * We need to set the reaper for this thread */ - if(evt->get_type() == PPME_PROCEXIT_1_E && evt->get_num_params() > 4) - { + if(evt->get_type() == PPME_PROCEXIT_1_E && evt->get_num_params() > 4) { evt->get_tinfo()->m_reaper_tid = evt->get_param(4)->as(); - } - else - { + } else { evt->get_tinfo()->m_reaper_tid = -1; } } -inline bool sinsp_parser::update_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, - uint32_t tsip, uint16_t tsport, uint32_t tdip, uint16_t tdport, bool overwrite_dest) -{ - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) - { +inline bool sinsp_parser::update_ipv4_addresses_and_ports(sinsp_fdinfo *fdinfo, + uint32_t tsip, + uint16_t tsport, + uint32_t tdip, + uint16_t tdport, + bool overwrite_dest) { + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) { if((tsip == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip && - tsport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport && - tdip == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip && - tdport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport) || - (tdip == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip && - tdport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport && - tsip == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip && - tsport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport) - ) - { + tsport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport && + tdip == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip && + tdport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport) || + (tdip == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip && + tdport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport && + tsip == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip && + tsport == fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport)) { return false; } } @@ -3875,13 +3515,13 @@ inline bool sinsp_parser::update_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, } if(fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip == 0 || - (overwrite_dest && fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip != tdip)) { + (overwrite_dest && fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip != tdip)) { fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip = tdip; changed = true; } if(fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport == 0 || - (overwrite_dest && fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport != tdport)) { + (overwrite_dest && fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport != tdport)) { fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport = tdport; changed = true; } @@ -3889,8 +3529,9 @@ inline bool sinsp_parser::update_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, return changed; } -bool sinsp_parser::set_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* packed_data, bool overwrite_dest) -{ +bool sinsp_parser::set_ipv4_addresses_and_ports(sinsp_fdinfo *fdinfo, + uint8_t *packed_data, + bool overwrite_dest) { uint32_t tsip, tdip; uint16_t tsport, tdport; @@ -3902,8 +3543,9 @@ bool sinsp_parser::set_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* p return update_ipv4_addresses_and_ports(fdinfo, tsip, tsport, tdip, tdport, overwrite_dest); } -bool sinsp_parser::set_ipv4_mapped_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* packed_data, bool overwrite_dest) -{ +bool sinsp_parser::set_ipv4_mapped_ipv6_addresses_and_ports(sinsp_fdinfo *fdinfo, + uint8_t *packed_data, + bool overwrite_dest) { uint32_t tsip, tdip; uint16_t tsport, tdport; @@ -3915,29 +3557,27 @@ bool sinsp_parser::set_ipv4_mapped_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo return update_ipv4_addresses_and_ports(fdinfo, tsip, tsport, tdip, tdport, overwrite_dest); } -bool sinsp_parser::set_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* packed_data, bool overwrite_dest) -{ +bool sinsp_parser::set_ipv6_addresses_and_ports(sinsp_fdinfo *fdinfo, + uint8_t *packed_data, + bool overwrite_dest) { ipv6addr tsip, tdip; uint16_t tsport, tdport; - memcpy((uint8_t *) tsip.m_b, packed_data + 1, sizeof(tsip.m_b)); + memcpy((uint8_t *)tsip.m_b, packed_data + 1, sizeof(tsip.m_b)); memcpy(&tsport, packed_data + 17, sizeof(tsport)); - memcpy((uint8_t *) tdip.m_b, packed_data + 19, sizeof(tdip.m_b)); + memcpy((uint8_t *)tdip.m_b, packed_data + 19, sizeof(tdip.m_b)); memcpy(&tdport, packed_data + 35, sizeof(tdport)); - if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) - { + if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) { if((tsip == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip && - tsport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport && - tdip == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip && - tdport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport) || - (tdip == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip && - tdport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport && - tsip == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip && - tsport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport) - ) - { + tsport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport && + tdip == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip && + tdport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport) || + (tdip == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip && + tdport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport && + tsip == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip && + tsport == fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport)) { return false; } } @@ -3955,13 +3595,13 @@ bool sinsp_parser::set_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* p } if(fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip == ipv6addr::empty_address || - (overwrite_dest && fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip != tdip)) { + (overwrite_dest && fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip != tdip)) { fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip = tdip; changed = true; } if(fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport == 0 || - (overwrite_dest && fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport != tdport)) { + (overwrite_dest && fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport != tdport)) { fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport = tdport; changed = true; } @@ -3969,67 +3609,52 @@ bool sinsp_parser::set_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* p return changed; } - // Return false if the update didn't happen (for example because the tuple is NULL) -bool sinsp_parser::update_fd(sinsp_evt *evt, const sinsp_evt_param *parinfo) -{ - uint8_t* packed_data = (uint8_t*)parinfo->m_val; +bool sinsp_parser::update_fd(sinsp_evt *evt, const sinsp_evt_param *parinfo) { + uint8_t *packed_data = (uint8_t *)parinfo->m_val; uint8_t family = *packed_data; - if(parinfo->m_len == 0) - { + if(parinfo->m_len == 0) { return false; } - if(family == PPM_AF_INET) - { - if(evt->get_fd_info()->m_type == SCAP_FD_IPV4_SERVSOCK) - { + if(family == PPM_AF_INET) { + if(evt->get_fd_info()->m_type == SCAP_FD_IPV4_SERVSOCK) { // // If this was previously a server socket, propagate the L4 protocol // evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_l4proto = - evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_l4proto; + evt->get_fd_info()->m_sockinfo.m_ipv4serverinfo.m_l4proto; } evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; - if(set_ipv4_addresses_and_ports(evt->get_fd_info(), packed_data) == false) - { + if(set_ipv4_addresses_and_ports(evt->get_fd_info(), packed_data) == false) { return false; } - } - else if(family == PPM_AF_INET6) - { + } else if(family == PPM_AF_INET6) { // // Check to see if it's an IPv4-mapped IPv6 address // (http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses) // - uint8_t* sip = packed_data + 1; - uint8_t* dip = packed_data + 19; + uint8_t *sip = packed_data + 1; + uint8_t *dip = packed_data + 19; - if(sinsp_utils::is_ipv4_mapped_ipv6(sip) && sinsp_utils::is_ipv4_mapped_ipv6(dip)) - { + if(sinsp_utils::is_ipv4_mapped_ipv6(sip) && sinsp_utils::is_ipv4_mapped_ipv6(dip)) { evt->get_fd_info()->m_type = SCAP_FD_IPV4_SOCK; - if(set_ipv4_mapped_ipv6_addresses_and_ports(evt->get_fd_info(), packed_data) == false) - { + if(set_ipv4_mapped_ipv6_addresses_and_ports(evt->get_fd_info(), packed_data) == false) { return false; } - } - else - { + } else { // It's not an ipv4-mapped ipv6 address. Extract it as a normal address. - if(set_ipv6_addresses_and_ports(evt->get_fd_info(), packed_data) == false) - { + if(set_ipv6_addresses_and_ports(evt->get_fd_info(), packed_data) == false) { return false; } } - } - else if(family == PPM_AF_UNIX) - { + } else if(family == PPM_AF_UNIX) { evt->get_fd_info()->m_type = SCAP_FD_UNIX_SOCK; evt->get_fd_info()->set_unix_info(packed_data); - evt->get_fd_info()->m_name = ((char*)packed_data) + 17; + evt->get_fd_info()->m_name = ((char *)packed_data) + 17; return true; } @@ -4039,17 +3664,12 @@ bool sinsp_parser::update_fd(sinsp_evt *evt, const sinsp_evt_param *parinfo) // connection is UDP, because TCP would fail if the address is changed in // the middle of a connection. // - if(evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK) - { - if(evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_UNKNOWN) - { + if(evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK) { + if(evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_l4proto == SCAP_L4_UNKNOWN) { evt->get_fd_info()->m_sockinfo.m_ipv4info.m_fields.m_l4proto = SCAP_L4_UDP; } - } - else if(evt->get_fd_info()->m_type == SCAP_FD_IPV6_SOCK) - { - if(evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_l4proto == SCAP_L4_UNKNOWN) - { + } else if(evt->get_fd_info()->m_type == SCAP_FD_IPV6_SOCK) { + if(evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_l4proto == SCAP_L4_UNKNOWN) { evt->get_fd_info()->m_sockinfo.m_ipv6info.m_fields.m_l4proto = SCAP_L4_UDP; } } @@ -4062,22 +3682,19 @@ bool sinsp_parser::update_fd(sinsp_evt *evt, const sinsp_evt_param *parinfo) return true; } -void sinsp_parser::swap_addresses(sinsp_fdinfo* fdinfo) -{ - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) - { +void sinsp_parser::swap_addresses(sinsp_fdinfo *fdinfo) { + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) { uint32_t tip; uint16_t tport; tip = fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip; tport = fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport; fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip = fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip; - fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport = fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; + fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport = + fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip = tip; fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport = tport; - } - else - { + } else { ipv6addr tip; uint16_t tport; @@ -4085,24 +3702,22 @@ void sinsp_parser::swap_addresses(sinsp_fdinfo* fdinfo) tport = fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport; fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip = fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip; - fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport = fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; + fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport = + fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip = tip; fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport = tport; } } -void sinsp_parser::parse_fspath_related_exit(sinsp_evt* evt) -{ +void sinsp_parser::parse_fspath_related_exit(sinsp_evt *evt) { sinsp_evt *enter_evt = &m_tmp_evt; - if(retrieve_enter_event(enter_evt, evt)) - { + if(retrieve_enter_event(enter_evt, evt)) { evt->save_enter_event_params(enter_evt); } } -void sinsp_parser::parse_rw_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_rw_exit(sinsp_evt *evt) { const sinsp_evt_param *parinfo; int64_t retval; int64_t tid = evt->get_tid(); @@ -4114,78 +3729,68 @@ void sinsp_parser::parse_rw_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(evt->get_fd_info() == NULL) - { + if(evt->get_fd_info() == NULL) { return; } // // If the operation was successful, validate that the fd exists // - if(retval >= 0) - { + if(retval >= 0) { uint16_t etype = evt->get_type(); - if (evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK || - evt->get_fd_info()->m_type == SCAP_FD_IPV6_SOCK) { + if(evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK || + evt->get_fd_info()->m_type == SCAP_FD_IPV6_SOCK) { evt->get_fd_info()->set_socket_connected(); } - if(eflags & EF_READS_FROM_FD) - { + if(eflags & EF_READS_FROM_FD) { const char *data; uint32_t datalen; int32_t tupleparam = -1; - if(etype == PPME_SOCKET_RECVFROM_X) - { + if(etype == PPME_SOCKET_RECVFROM_X) { tupleparam = 2; - } - else if(etype == PPME_SOCKET_RECVMSG_X) - { + } else if(etype == PPME_SOCKET_RECVMSG_X) { tupleparam = 3; } - if(tupleparam != -1 && (evt->get_fd_info()->m_name.length() == 0 || !evt->get_fd_info()->is_tcp_socket())) - { + if(tupleparam != -1 && + (evt->get_fd_info()->m_name.length() == 0 || !evt->get_fd_info()->is_tcp_socket())) { // // recvfrom contains tuple info. // If the fd still doesn't contain tuple info (because the socket is a // datagram one or because some event was lost), // add it here. // - if(update_fd(evt, evt->get_param(tupleparam))) - { + if(update_fd(evt, evt->get_param(tupleparam))) { const char *parstr; scap_fd_type fdtype = evt->get_fd_info()->m_type; - if(fdtype == SCAP_FD_IPV4_SOCK || - fdtype == SCAP_FD_IPV6_SOCK) - { - if(evt->get_fd_info()->is_role_none()) - { - evt->get_fd_info()->set_net_role_by_guessing(m_inspector, - evt->get_tinfo(), - evt->get_fd_info(), - true); + if(fdtype == SCAP_FD_IPV4_SOCK || fdtype == SCAP_FD_IPV6_SOCK) { + if(evt->get_fd_info()->is_role_none()) { + evt->get_fd_info()->set_net_role_by_guessing(m_inspector, + evt->get_tinfo(), + evt->get_fd_info(), + true); } - if(evt->get_fd_info()->is_role_client()) - { + if(evt->get_fd_info()->is_role_client()) { swap_addresses(evt->get_fd_info()); } - sinsp_utils::sockinfo_to_str(&evt->get_fd_info()->m_sockinfo, - fdtype, &evt->get_paramstr_storage()[0], - (uint32_t)evt->get_paramstr_storage().size(), - m_inspector->is_hostname_and_port_resolution_enabled()); + sinsp_utils::sockinfo_to_str( + &evt->get_fd_info()->m_sockinfo, + fdtype, + &evt->get_paramstr_storage()[0], + (uint32_t)evt->get_paramstr_storage().size(), + m_inspector->is_hostname_and_port_resolution_enabled()); evt->get_fd_info()->m_name = &evt->get_paramstr_storage()[0]; - } - else - { - evt->get_fd_info()->m_name = evt->get_param_as_str(tupleparam, &parstr, sinsp_evt::PF_SIMPLE); + } else { + evt->get_fd_info()->m_name = + evt->get_param_as_str(tupleparam, &parstr, sinsp_evt::PF_SIMPLE); } } } @@ -4193,12 +3798,10 @@ void sinsp_parser::parse_rw_exit(sinsp_evt *evt) // // Extract the data buffer // - if(etype == PPME_SYSCALL_READV_X || etype == PPME_SYSCALL_PREADV_X || etype == PPME_SOCKET_RECVMSG_X) - { + if(etype == PPME_SYSCALL_READV_X || etype == PPME_SYSCALL_PREADV_X || + etype == PPME_SOCKET_RECVMSG_X) { parinfo = evt->get_param(2); - } - else - { + } else { parinfo = evt->get_param(1); } @@ -4208,10 +3811,14 @@ void sinsp_parser::parse_rw_exit(sinsp_evt *evt) // // If there's an fd listener, call it now // - if(m_inspector->get_observer()) - { - m_inspector->get_observer()->on_read(evt, tid, evt->get_tinfo()->m_lastevent_fd, evt->get_fd_info(), - data, (uint32_t)retval, datalen); + if(m_inspector->get_observer()) { + m_inspector->get_observer()->on_read(evt, + tid, + evt->get_tinfo()->m_lastevent_fd, + evt->get_fd_info(), + data, + (uint32_t)retval, + datalen); } // @@ -4220,40 +3827,38 @@ void sinsp_parser::parse_rw_exit(sinsp_evt *evt) // accordingly via procfs scan. // #ifndef _WIN32 - if(etype == PPME_SOCKET_RECVMSG_X && evt->get_num_params() >= 5) - { + if(etype == PPME_SOCKET_RECVMSG_X && evt->get_num_params() >= 5) { parinfo = evt->get_param(4); - if(parinfo->m_len > sizeof(cmsghdr)) - { + if(parinfo->m_len > sizeof(cmsghdr)) { cmsghdr cmsg; memcpy(&cmsg, parinfo->m_val, sizeof(cmsghdr)); - if(cmsg.cmsg_type == SCM_RIGHTS) - { + if(cmsg.cmsg_type == SCM_RIGHTS) { char error[SCAP_LASTERR_SIZE]; - scap_threadinfo scap_tinfo {}; + scap_threadinfo scap_tinfo{}; memset(&scap_tinfo, 0, sizeof(scap_tinfo)); - m_inspector->m_thread_manager->thread_to_scap(*evt->get_tinfo(), &scap_tinfo); + m_inspector->m_thread_manager->thread_to_scap(*evt->get_tinfo(), + &scap_tinfo); // Store current fd; it might get changed by scap_get_fdlist below. int64_t fd = -1; - if (evt->get_fd_info()) - { + if(evt->get_fd_info()) { fd = evt->get_fd_info()->m_fd; } // Get the new fds. The callbacks we have registered populate the fd table // with the new file descriptors. - if (scap_get_fdlist(m_inspector->get_scap_platform(), &scap_tinfo, error) != SCAP_SUCCESS) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "scap_get_fdlist failed: %s, proc table will not be updated with new fds.", - error); + if(scap_get_fdlist(m_inspector->get_scap_platform(), &scap_tinfo, error) != + SCAP_SUCCESS) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "scap_get_fdlist failed: %s, proc table will " + "not be updated with new fds.", + error); } // Force refresh event fdinfo - if (fd != -1) - { + if(fd != -1) { evt->set_fd_info(evt->get_tinfo()->get_fd(fd)); } } @@ -4261,62 +3866,56 @@ void sinsp_parser::parse_rw_exit(sinsp_evt *evt) } #endif - } - else - { + } else { const char *data; uint32_t datalen; int32_t tupleparam = -1; - if(etype == PPME_SOCKET_SENDTO_X || etype == PPME_SOCKET_SENDMSG_X) - { + if(etype == PPME_SOCKET_SENDTO_X || etype == PPME_SOCKET_SENDMSG_X) { tupleparam = 2; } - if(tupleparam != -1 && (evt->get_fd_info()->m_name.length() == 0 || !evt->get_fd_info()->is_tcp_socket())) - { + if(tupleparam != -1 && + (evt->get_fd_info()->m_name.length() == 0 || !evt->get_fd_info()->is_tcp_socket())) { // // sendto contains tuple info in the enter event. - // If the fd still doesn't contain tuple info (because the socket is a datagram one or because some event was lost), - // add it here. + // If the fd still doesn't contain tuple info (because the socket is a datagram one + // or because some event was lost), add it here. // - if(!retrieve_enter_event(enter_evt, evt)) - { + if(!retrieve_enter_event(enter_evt, evt)) { return; } - if(update_fd(evt, enter_evt->get_param(tupleparam))) - { + if(update_fd(evt, enter_evt->get_param(tupleparam))) { const char *parstr; scap_fd_type fdtype = evt->get_fd_info()->m_type; - if(fdtype == SCAP_FD_IPV4_SOCK || - fdtype == SCAP_FD_IPV6_SOCK) - { - if(evt->get_fd_info()->is_role_none()) - { - evt->get_fd_info()->set_net_role_by_guessing(m_inspector, - evt->get_tinfo(), - evt->get_fd_info(), - false); + if(fdtype == SCAP_FD_IPV4_SOCK || fdtype == SCAP_FD_IPV6_SOCK) { + if(evt->get_fd_info()->is_role_none()) { + evt->get_fd_info()->set_net_role_by_guessing(m_inspector, + evt->get_tinfo(), + evt->get_fd_info(), + false); } - if(evt->get_fd_info()->is_role_server()) - { + if(evt->get_fd_info()->is_role_server()) { swap_addresses(evt->get_fd_info()); } - sinsp_utils::sockinfo_to_str(&evt->get_fd_info()->m_sockinfo, - fdtype, &evt->get_paramstr_storage()[0], - (uint32_t)evt->get_paramstr_storage().size(), - m_inspector->is_hostname_and_port_resolution_enabled()); + sinsp_utils::sockinfo_to_str( + &evt->get_fd_info()->m_sockinfo, + fdtype, + &evt->get_paramstr_storage()[0], + (uint32_t)evt->get_paramstr_storage().size(), + m_inspector->is_hostname_and_port_resolution_enabled()); evt->get_fd_info()->m_name = &evt->get_paramstr_storage()[0]; - } - else - { - evt->get_fd_info()->m_name = enter_evt->get_param_as_str(tupleparam, &parstr, sinsp_evt::PF_SIMPLE); + } else { + evt->get_fd_info()->m_name = + enter_evt->get_param_as_str(tupleparam, + &parstr, + sinsp_evt::PF_SIMPLE); } } } @@ -4331,36 +3930,36 @@ void sinsp_parser::parse_rw_exit(sinsp_evt *evt) // // If there's an fd listener, call it now // - if(m_inspector->get_observer()) - { - m_inspector->get_observer()->on_write(evt, tid, evt->get_tinfo()->m_lastevent_fd, evt->get_fd_info(), - data, (uint32_t)retval, datalen); + if(m_inspector->get_observer()) { + m_inspector->get_observer()->on_write(evt, + tid, + evt->get_tinfo()->m_lastevent_fd, + evt->get_fd_info(), + data, + (uint32_t)retval, + datalen); } // perform syslog decoding if applicable - if (evt->get_fd_info()->is_syslog()) - { + if(evt->get_fd_info()->is_syslog()) { m_syslog_decoder.parse_data(data, datalen); } } - } else if (m_track_connection_status) { - if (evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK || - evt->get_fd_info()->m_type == SCAP_FD_IPV6_SOCK) { + } else if(m_track_connection_status) { + if(evt->get_fd_info()->m_type == SCAP_FD_IPV4_SOCK || + evt->get_fd_info()->m_type == SCAP_FD_IPV6_SOCK) { evt->get_fd_info()->set_socket_failed(); - if (m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_socket_status_changed(evt); } } } } -void sinsp_parser::parse_sendfile_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_sendfile_exit(sinsp_evt *evt) { int64_t retval; - if(!evt->get_fd_info()) - { + if(!evt->get_fd_info()) { return; } @@ -4372,13 +3971,11 @@ void sinsp_parser::parse_sendfile_exit(sinsp_evt *evt) // // If the operation was successful, validate that the fd exists // - if(retval >= 0) - { + if(retval >= 0) { sinsp_evt *enter_evt = &m_tmp_evt; int64_t fdin; - if(!retrieve_enter_event(enter_evt, evt)) - { + if(!retrieve_enter_event(enter_evt, evt)) { return; } @@ -4390,29 +3987,25 @@ void sinsp_parser::parse_sendfile_exit(sinsp_evt *evt) // // If there's an fd listener, call it now // - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_sendfile(evt, fdin, (uint32_t)retval); } } } -void sinsp_parser::parse_eventfd_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_eventfd_exit(sinsp_evt *evt) { int64_t fd; // // lookup the thread info // - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } fd = evt->get_param(0)->as(); - if(fd < 0) - { + if(fd < 0) { // // eventfd() failed. Nothing to add to the table. // @@ -4425,8 +4018,7 @@ void sinsp_parser::parse_eventfd_exit(sinsp_evt *evt) auto fdi = m_inspector->build_fdinfo(); fdi->m_type = SCAP_FD_EVENT; - if(evt->get_type() == PPME_SYSCALL_EVENTFD2_X) - { + if(evt->get_type() == PPME_SYSCALL_EVENTFD2_X) { fdi->m_openflags = evt->get_param(1)->as(); } @@ -4436,12 +4028,10 @@ void sinsp_parser::parse_eventfd_exit(sinsp_evt *evt) evt->set_fd_info(evt->get_tinfo()->add_fd(fd, std::move(fdi))); } -void sinsp_parser::parse_chdir_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_chdir_exit(sinsp_evt *evt) { int64_t retval; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -4453,15 +4043,13 @@ void sinsp_parser::parse_chdir_exit(sinsp_evt *evt) // // In case of success, update the thread working dir // - if(retval >= 0) - { + if(retval >= 0) { // Update the thread working directory evt->get_tinfo()->update_cwd(evt->get_param(1)->as()); } } -void sinsp_parser::parse_fchdir_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_fchdir_exit(sinsp_evt *evt) { int64_t retval; // @@ -4472,13 +4060,11 @@ void sinsp_parser::parse_fchdir_exit(sinsp_evt *evt) // // In case of success, update the thread working dir // - if(retval >= 0) - { + if(retval >= 0) { // // Find the fd name // - if(evt->get_fd_info() == nullptr || evt->get_tinfo() == nullptr) - { + if(evt->get_fd_info() == nullptr || evt->get_tinfo() == nullptr) { return; } @@ -4487,8 +4073,7 @@ void sinsp_parser::parse_fchdir_exit(sinsp_evt *evt) } } -void sinsp_parser::parse_getcwd_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_getcwd_exit(sinsp_evt *evt) { int64_t retval; // @@ -4499,10 +4084,8 @@ void sinsp_parser::parse_getcwd_exit(sinsp_evt *evt) // // Check if the syscall was successful // - if(retval >= 0) - { - if(evt->get_tinfo() == nullptr) - { + if(retval >= 0) { + if(evt->get_tinfo() == nullptr) { // // No thread in the table. We won't store this event, which mean that // we won't be able to parse the corresponding exit event and we'll have @@ -4514,10 +4097,8 @@ void sinsp_parser::parse_getcwd_exit(sinsp_evt *evt) std::string cwd = evt->get_param(1)->as(); #ifdef _DEBUG - if(cwd != "/") - { - if(cwd + "/" != evt->get_tinfo()->get_cwd()) - { + if(cwd != "/") { + if(cwd + "/" != evt->get_tinfo()->get_cwd()) { // // This shouldn't happen, because we should be able to stay in synch by // following chdir(). If it does, it's almost sure there was an event drop. @@ -4527,15 +4108,11 @@ void sinsp_parser::parse_getcwd_exit(sinsp_evt *evt) #ifdef _DEBUG int target_res; char target_name[1024]; - target_res = readlink((cwd + "/").c_str(), - target_name, - sizeof(target_name) - 1); + target_res = readlink((cwd + "/").c_str(), target_name, sizeof(target_name) - 1); - if(target_res > 0) - { + if(target_res > 0) { target_name[target_res] = '\0'; - if(target_name != evt->get_tinfo()->get_cwd()) - { + if(target_name != evt->get_tinfo()->get_cwd()) { printf("%s != %s", target_name, evt->get_tinfo()->get_cwd().c_str()); ASSERT(false); } @@ -4551,8 +4128,7 @@ void sinsp_parser::parse_getcwd_exit(sinsp_evt *evt) } } -void sinsp_parser::parse_shutdown_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_shutdown_exit(sinsp_evt *evt) { int64_t retval; // @@ -4563,26 +4139,21 @@ void sinsp_parser::parse_shutdown_exit(sinsp_evt *evt) // // If the operation was successful, do the cleanup // - if(retval >= 0) - { - if(evt->get_fd_info() == NULL) - { + if(retval >= 0) { + if(evt->get_fd_info() == NULL) { return; } - if(m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_socket_shutdown(evt); } } } -void sinsp_parser::parse_dup_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_dup_exit(sinsp_evt *evt) { int64_t retval; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -4594,22 +4165,18 @@ void sinsp_parser::parse_dup_exit(sinsp_evt *evt) // // Check if the syscall was successful // - if(retval >= 0) - { + if(retval >= 0) { // // Heuristic to determine if a thread is part of a shell pipe // - if(retval == 0) - { + if(retval == 0) { evt->get_tinfo()->m_flags |= PPM_CL_PIPE_DST; } - if(retval == 1) - { + if(retval == 1) { evt->get_tinfo()->m_flags |= PPM_CL_PIPE_SRC; } - if(evt->get_fd_info() == NULL) - { + if(evt->get_fd_info() == NULL) { return; } // @@ -4618,13 +4185,12 @@ void sinsp_parser::parse_dup_exit(sinsp_evt *evt) // - dup(): fd number of a previously closed fd that has not been removed from the fd_table // and has been reassigned to the newly created fd by dup()(very rare condition); // - dup2(): fd number of an existing fd that we pass to the dup2() as the "newfd". dup2() - // will close the existing one. So we need to clean it up / overwrite; + // will close the existing one. So we need to clean it up / overwrite; // - dup3(): same as dup2(). // - sinsp_fdinfo* oldfdinfo = evt->get_tinfo()->get_fd(retval); + sinsp_fdinfo *oldfdinfo = evt->get_tinfo()->get_fd(retval); - if(oldfdinfo != NULL) - { + if(oldfdinfo != NULL) { erase_fd_params eparams; eparams.m_fd = retval; @@ -4637,9 +4203,10 @@ void sinsp_parser::parse_dup_exit(sinsp_evt *evt) } // - // If we are handling the dup3() event exit then we add the flags to the new file descriptor. + // If we are handling the dup3() event exit then we add the flags to the new file + // descriptor. // - if (evt->get_type() == PPME_SYSCALL_DUP3_X){ + if(evt->get_type() == PPME_SYSCALL_DUP3_X) { uint32_t flags; // @@ -4651,18 +4218,17 @@ void sinsp_parser::parse_dup_exit(sinsp_evt *evt) // We keep the previously flags that has been set on the original file descriptor and // just set/reset O_CLOEXEC flag base on the value received by dup3() syscall. // - if (flags){ + if(flags) { // // set the O_CLOEXEC flag. // evt->get_fd_info()->m_openflags |= flags; - }else{ + } else { // // reset the O_CLOEXEC flag. // evt->get_fd_info()->m_openflags &= ~PPM_O_CLOEXEC; } - } // @@ -4673,8 +4239,7 @@ void sinsp_parser::parse_dup_exit(sinsp_evt *evt) } } -void sinsp_parser::parse_single_param_fd_exit(sinsp_evt* evt, scap_fd_type type) -{ +void sinsp_parser::parse_single_param_fd_exit(sinsp_evt *evt, scap_fd_type type) { int64_t retval; // @@ -4682,16 +4247,14 @@ void sinsp_parser::parse_single_param_fd_exit(sinsp_evt* evt, scap_fd_type type) // retval = evt->get_param(0)->as(); - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } // // Check if the syscall was successful // - if(retval < 0) - { + if(retval < 0) { return; } @@ -4701,13 +4264,11 @@ void sinsp_parser::parse_single_param_fd_exit(sinsp_evt* evt, scap_fd_type type) auto fdi = m_inspector->build_fdinfo(); fdi->m_type = type; - if(evt->get_type() == PPME_SYSCALL_INOTIFY_INIT1_X) - { + if(evt->get_type() == PPME_SYSCALL_INOTIFY_INIT1_X) { fdi->m_openflags = evt->get_param(1)->as(); } - if(evt->get_type() == PPME_SYSCALL_SIGNALFD4_X) - { + if(evt->get_type() == PPME_SYSCALL_SIGNALFD4_X) { fdi->m_openflags = evt->get_param(1)->as(); } @@ -4717,15 +4278,13 @@ void sinsp_parser::parse_single_param_fd_exit(sinsp_evt* evt, scap_fd_type type) evt->set_fd_info(evt->get_tinfo()->add_fd(retval, std::move(fdi))); } -void sinsp_parser::parse_getrlimit_setrlimit_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_getrlimit_setrlimit_exit(sinsp_evt *evt) { int64_t retval; sinsp_evt *enter_evt = &m_tmp_evt; uint8_t resource; int64_t curval; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -4737,13 +4296,11 @@ void sinsp_parser::parse_getrlimit_setrlimit_exit(sinsp_evt *evt) // // Check if the syscall was successful // - if(retval >= 0) - { + if(retval >= 0) { // // Load the enter event so we can access its arguments // - if(!retrieve_enter_event(enter_evt, evt)) - { + if(!retrieve_enter_event(enter_evt, evt)) { return; } @@ -4752,32 +4309,26 @@ void sinsp_parser::parse_getrlimit_setrlimit_exit(sinsp_evt *evt) // resource = enter_evt->get_param(0)->as(); - if(resource == PPM_RLIMIT_NOFILE) - { + if(resource == PPM_RLIMIT_NOFILE) { // // Extract the current value for the resource // curval = evt->get_param(1)->as(); - if(curval != -1) - { + if(curval != -1) { auto main_thread = evt->get_tinfo()->get_main_thread(); - if(main_thread == nullptr) - { + if(main_thread == nullptr) { return; } main_thread->m_fdlimit = curval; - } - else - { + } else { ASSERT(false); } } } } -void sinsp_parser::parse_prlimit_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_prlimit_exit(sinsp_evt *evt) { int64_t retval; sinsp_evt *enter_evt = &m_tmp_evt; uint8_t resource; @@ -4792,13 +4343,11 @@ void sinsp_parser::parse_prlimit_exit(sinsp_evt *evt) // // Check if the syscall was successful // - if(retval >= 0) - { + if(retval >= 0) { // // Load the enter event so we can access its arguments // - if(!retrieve_enter_event(enter_evt, evt)) - { + if(!retrieve_enter_event(enter_evt, evt)) { return; } @@ -4807,31 +4356,27 @@ void sinsp_parser::parse_prlimit_exit(sinsp_evt *evt) // resource = enter_evt->get_param(1)->as(); - if(resource == PPM_RLIMIT_NOFILE) - { + if(resource == PPM_RLIMIT_NOFILE) { // // Extract the current value for the resource // newcur = evt->get_param(1)->as(); - if(newcur != -1) - { + if(newcur != -1) { // // Extract the tid and look for its process info // tid = enter_evt->get_param(0)->as(); - if(tid == 0) - { + if(tid == 0) { tid = evt->get_tid(); } - sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tid, true, true).get(); - /* If the thread info is invalid we cannot recover the main thread because we don't even - * have the `pid` of the thread. + sinsp_threadinfo *ptinfo = m_inspector->get_thread_ref(tid, true, true).get(); + /* If the thread info is invalid we cannot recover the main thread because we don't + * even have the `pid` of the thread. */ - if(ptinfo == nullptr || ptinfo->is_invalid()) - { + if(ptinfo == nullptr || ptinfo->is_invalid()) { return; } @@ -4839,8 +4384,7 @@ void sinsp_parser::parse_prlimit_exit(sinsp_evt *evt) // update the process fdlimit // auto main_thread = ptinfo->get_main_thread(); - if(main_thread == nullptr) - { + if(main_thread == nullptr) { return; } main_thread->m_fdlimit = newcur; @@ -4849,40 +4393,34 @@ void sinsp_parser::parse_prlimit_exit(sinsp_evt *evt) } } -void sinsp_parser::parse_select_poll_epollwait_enter(sinsp_evt *evt) -{ - if(evt->get_tinfo() == nullptr) - { +void sinsp_parser::parse_select_poll_epollwait_enter(sinsp_evt *evt) { + if(evt->get_tinfo() == nullptr) { return; } - if(evt->get_tinfo()->get_last_event_data() == NULL) - { + if(evt->get_tinfo()->get_last_event_data() == NULL) { evt->get_tinfo()->set_last_event_data(reserve_event_buffer()); - if(evt->get_tinfo()->get_last_event_data() == NULL) - { - throw sinsp_exception("cannot reserve event buffer in sinsp_parser::parse_select_poll_epollwait_enter."); + if(evt->get_tinfo()->get_last_event_data() == NULL) { + throw sinsp_exception( + "cannot reserve event buffer in " + "sinsp_parser::parse_select_poll_epollwait_enter."); } } - *(uint64_t*)evt->get_tinfo()->get_last_event_data() = evt->get_ts(); + *(uint64_t *)evt->get_tinfo()->get_last_event_data() = evt->get_ts(); } -void sinsp_parser::parse_fcntl_enter(sinsp_evt *evt) -{ - if(evt->get_tinfo() == nullptr) - { +void sinsp_parser::parse_fcntl_enter(sinsp_evt *evt) { + if(evt->get_tinfo() == nullptr) { return; } uint8_t cmd = evt->get_param(1)->as(); - if(cmd == PPM_FCNTL_F_DUPFD || cmd == PPM_FCNTL_F_DUPFD_CLOEXEC) - { + if(cmd == PPM_FCNTL_F_DUPFD || cmd == PPM_FCNTL_F_DUPFD_CLOEXEC) { store_event(evt); } } -void sinsp_parser::parse_fcntl_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_fcntl_exit(sinsp_evt *evt) { int64_t retval; sinsp_evt *enter_evt = &m_tmp_evt; @@ -4894,18 +4432,15 @@ void sinsp_parser::parse_fcntl_exit(sinsp_evt *evt) // // If this is not a F_DUPFD or F_DUPFD_CLOEXEC command, ignore it // - if(!retrieve_enter_event(enter_evt, evt)) - { + if(!retrieve_enter_event(enter_evt, evt)) { return; } // // Check if the syscall was successful // - if(retval >= 0) - { - if(evt->get_fd_info() == NULL) - { + if(retval >= 0) { + if(evt->get_fd_info() == NULL) { return; } @@ -4918,10 +4453,8 @@ void sinsp_parser::parse_fcntl_exit(sinsp_evt *evt) } } -void sinsp_parser::parse_context_switch(sinsp_evt* evt) -{ - if(evt->get_tinfo() == nullptr) - { +void sinsp_parser::parse_context_switch(sinsp_evt *evt) { + if(evt->get_tinfo() == nullptr) { return; } @@ -4930,8 +4463,7 @@ void sinsp_parser::parse_context_switch(sinsp_evt* evt) evt->get_tinfo()->m_pfminor = evt->get_param(2)->as(); auto main_tinfo = evt->get_tinfo()->get_main_thread(); - if(main_tinfo) - { + if(main_tinfo) { main_tinfo->m_vmsize_kb = evt->get_param(3)->as(); main_tinfo->m_vmrss_kb = evt->get_param(4)->as(); @@ -4940,10 +4472,8 @@ void sinsp_parser::parse_context_switch(sinsp_evt* evt) } } -void sinsp_parser::parse_brk_munmap_mmap_exit(sinsp_evt* evt) -{ - if(evt->get_tinfo() == nullptr) - { +void sinsp_parser::parse_brk_munmap_mmap_exit(sinsp_evt *evt) { + if(evt->get_tinfo() == nullptr) { return; } @@ -4952,8 +4482,7 @@ void sinsp_parser::parse_brk_munmap_mmap_exit(sinsp_evt* evt) evt->get_tinfo()->m_vmswap_kb = evt->get_param(3)->as(); } -void sinsp_parser::parse_setresuid_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_setresuid_exit(sinsp_evt *evt) { int64_t retval; sinsp_evt *enter_evt = &m_tmp_evt; @@ -4962,22 +4491,19 @@ void sinsp_parser::parse_setresuid_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval == 0 && retrieve_enter_event(enter_evt, evt)) - { + if(retval == 0 && retrieve_enter_event(enter_evt, evt)) { uint32_t new_euid = enter_evt->get_param(1)->as(); - if(new_euid < std::numeric_limits::max()) - { - sinsp_threadinfo* ti = evt->get_thread_info(); - if (ti) { + if(new_euid < std::numeric_limits::max()) { + sinsp_threadinfo *ti = evt->get_thread_info(); + if(ti) { ti->set_user(new_euid); } } } } -void sinsp_parser::parse_setreuid_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_setreuid_exit(sinsp_evt *evt) { int64_t retval; // @@ -4985,22 +4511,19 @@ void sinsp_parser::parse_setreuid_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval == 0) - { + if(retval == 0) { uint32_t new_euid = evt->get_param(1)->as(); - if(new_euid < std::numeric_limits::max()) - { - sinsp_threadinfo* ti = evt->get_thread_info(); - if (ti) { + if(new_euid < std::numeric_limits::max()) { + sinsp_threadinfo *ti = evt->get_thread_info(); + if(ti) { ti->set_user(new_euid); } } } } -void sinsp_parser::parse_setresgid_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_setresgid_exit(sinsp_evt *evt) { int64_t retval; sinsp_evt *enter_evt = &m_tmp_evt; @@ -5009,22 +4532,19 @@ void sinsp_parser::parse_setresgid_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval == 0 && retrieve_enter_event(enter_evt, evt)) - { + if(retval == 0 && retrieve_enter_event(enter_evt, evt)) { uint32_t new_egid = enter_evt->get_param(1)->as(); - if(new_egid < std::numeric_limits::max()) - { - sinsp_threadinfo* ti = evt->get_thread_info(); - if (ti) { + if(new_egid < std::numeric_limits::max()) { + sinsp_threadinfo *ti = evt->get_thread_info(); + if(ti) { ti->set_group(new_egid); } } } } -void sinsp_parser::parse_setregid_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_setregid_exit(sinsp_evt *evt) { int64_t retval; // @@ -5032,22 +4552,19 @@ void sinsp_parser::parse_setregid_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval == 0) - { + if(retval == 0) { uint32_t new_egid = evt->get_param(1)->as(); - if(new_egid < std::numeric_limits::max()) - { - sinsp_threadinfo* ti = evt->get_thread_info(); - if (ti) { + if(new_egid < std::numeric_limits::max()) { + sinsp_threadinfo *ti = evt->get_thread_info(); + if(ti) { ti->set_group(new_egid); } } } } -void sinsp_parser::parse_setuid_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_setuid_exit(sinsp_evt *evt) { int64_t retval; sinsp_evt *enter_evt = &m_tmp_evt; @@ -5056,18 +4573,16 @@ void sinsp_parser::parse_setuid_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval == 0 && retrieve_enter_event(enter_evt, evt)) - { + if(retval == 0 && retrieve_enter_event(enter_evt, evt)) { uint32_t new_euid = enter_evt->get_param(0)->as(); - sinsp_threadinfo* ti = evt->get_thread_info(); - if (ti) { + sinsp_threadinfo *ti = evt->get_thread_info(); + if(ti) { ti->set_user(new_euid); } } } -void sinsp_parser::parse_setgid_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_setgid_exit(sinsp_evt *evt) { int64_t retval; sinsp_evt *enter_evt = &m_tmp_evt; @@ -5076,72 +4591,72 @@ void sinsp_parser::parse_setgid_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval == 0 && retrieve_enter_event(enter_evt, evt)) - { + if(retval == 0 && retrieve_enter_event(enter_evt, evt)) { uint32_t new_egid = enter_evt->get_param(0)->as(); - sinsp_threadinfo* ti = evt->get_thread_info(); - if (ti) { + sinsp_threadinfo *ti = evt->get_thread_info(); + if(ti) { ti->set_group(new_egid); } } } -namespace -{ - std::string generate_error_message(const Json::Value& value, const char* field) { - std::string val_as_string = value.isConvertibleTo(Json::stringValue) ? value.asString().c_str() : "value not convertible to string"; - std::string err_msg = "Unable to convert json value '" + val_as_string + "' for the field: '" + field +"'"; +namespace { +std::string generate_error_message(const Json::Value &value, const char *field) { + std::string val_as_string = value.isConvertibleTo(Json::stringValue) + ? value.asString().c_str() + : "value not convertible to string"; + std::string err_msg = + "Unable to convert json value '" + val_as_string + "' for the field: '" + field + "'"; - return err_msg; - } + return err_msg; +} - bool check_int64_json_is_convertible(const Json::Value& value, const char* field) { - if(!value.isNull()) - { - // isConvertibleTo doesn't seem to work on large 64 bit numbers - if(value.isInt64()) { - return true; - } else { - std::string err_msg = generate_error_message(value, field); - SINSP_DEBUG("%s",err_msg.c_str()); - } +bool check_int64_json_is_convertible(const Json::Value &value, const char *field) { + if(!value.isNull()) { + // isConvertibleTo doesn't seem to work on large 64 bit numbers + if(value.isInt64()) { + return true; + } else { + std::string err_msg = generate_error_message(value, field); + SINSP_DEBUG("%s", err_msg.c_str()); } - return false; } + return false; +} - bool check_json_val_is_convertible(const Json::Value& value, Json::ValueType other, const char* field, bool log_message=false) - { - if(value.isNull()) { - return false; - } +bool check_json_val_is_convertible(const Json::Value &value, + Json::ValueType other, + const char *field, + bool log_message = false) { + if(value.isNull()) { + return false; + } - if(!value.isConvertibleTo(other)) { - std::string err_msg; + if(!value.isConvertibleTo(other)) { + std::string err_msg; - if(log_message) { + if(log_message) { + err_msg = generate_error_message(value, field); + SINSP_WARNING("%s", err_msg.c_str()); + } else { + if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) { err_msg = generate_error_message(value, field); - SINSP_WARNING("%s",err_msg.c_str()); - } else { - if(libsinsp_logger()->get_severity() >= sinsp_logger::SEV_DEBUG) { - err_msg = generate_error_message(value, field); - SINSP_DEBUG("%s",err_msg.c_str()); - } + SINSP_DEBUG("%s", err_msg.c_str()); } - return false; } - return true; + return false; } + return true; } +} // namespace -void sinsp_parser::parse_container_json_evt(sinsp_evt *evt) -{ - if(evt->get_tinfo_ref() != nullptr) - { - const auto& container_id = evt->get_tinfo_ref()->m_container_id; +void sinsp_parser::parse_container_json_evt(sinsp_evt *evt) { + if(evt->get_tinfo_ref() != nullptr) { + const auto &container_id = evt->get_tinfo_ref()->m_container_id; const auto container = m_inspector->m_container_manager.get_container(container_id); - if(container != nullptr && container->is_successful()) - { - SINSP_DEBUG("Ignoring container event for already successful lookup of %s", container_id.c_str()); + if(container != nullptr && container->is_successful()) { + SINSP_DEBUG("Ignoring container event for already successful lookup of %s", + container_id.c_str()); evt->set_filtered_out(true); return; } @@ -5153,73 +4668,60 @@ void sinsp_parser::parse_container_json_evt(sinsp_evt *evt) std::string json(parinfo->m_val, parinfo->m_len); SINSP_DEBUG("Parsing Container JSON=%s", json.c_str()); Json::Value root; - if(Json::Reader().parse(json, root)) - { + if(Json::Reader().parse(json, root)) { auto container_info = std::make_shared(); - const Json::Value& container = root["container"]; - const Json::Value& id = container["id"]; - if(check_json_val_is_convertible(id, Json::stringValue, "id")) - { + const Json::Value &container = root["container"]; + const Json::Value &id = container["id"]; + if(check_json_val_is_convertible(id, Json::stringValue, "id")) { container_info->m_id = id.asString(); } - const Json::Value& full_id = container["full_id"]; - if(check_json_val_is_convertible(full_id, Json::stringValue, "full_id")) - { + const Json::Value &full_id = container["full_id"]; + if(check_json_val_is_convertible(full_id, Json::stringValue, "full_id")) { container_info->m_full_id = full_id.asString(); } - const Json::Value& type = container["type"]; - if(check_json_val_is_convertible(type, Json::uintValue, "type")) - { + const Json::Value &type = container["type"]; + if(check_json_val_is_convertible(type, Json::uintValue, "type")) { container_info->m_type = static_cast(type.asUInt()); } - const Json::Value& name = container["name"]; - if(check_json_val_is_convertible(name, Json::stringValue, "name")) - { + const Json::Value &name = container["name"]; + if(check_json_val_is_convertible(name, Json::stringValue, "name")) { container_info->m_name = name.asString(); } - const Json::Value& is_pod_sandbox = container["is_pod_sandbox"]; - if(check_json_val_is_convertible(is_pod_sandbox, Json::booleanValue, "is_pod_sandbox")) - { + const Json::Value &is_pod_sandbox = container["is_pod_sandbox"]; + if(check_json_val_is_convertible(is_pod_sandbox, Json::booleanValue, "is_pod_sandbox")) { container_info->m_is_pod_sandbox = is_pod_sandbox.asBool(); } - const Json::Value& image = container["image"]; - if(check_json_val_is_convertible(image, Json::stringValue, "image")) - { + const Json::Value &image = container["image"]; + if(check_json_val_is_convertible(image, Json::stringValue, "image")) { container_info->m_image = image.asString(); } - const Json::Value& imageid = container["imageid"]; - if(check_json_val_is_convertible(imageid, Json::stringValue, "imageid")) - { + const Json::Value &imageid = container["imageid"]; + if(check_json_val_is_convertible(imageid, Json::stringValue, "imageid")) { container_info->m_imageid = imageid.asString(); } - const Json::Value& imagerepo = container["imagerepo"]; - if(check_json_val_is_convertible(imagerepo, Json::stringValue, "imagerepo")) - { + const Json::Value &imagerepo = container["imagerepo"]; + if(check_json_val_is_convertible(imagerepo, Json::stringValue, "imagerepo")) { container_info->m_imagerepo = imagerepo.asString(); } - const Json::Value& imagetag = container["imagetag"]; - if(check_json_val_is_convertible(imagetag, Json::stringValue, "imagetag")) - { + const Json::Value &imagetag = container["imagetag"]; + if(check_json_val_is_convertible(imagetag, Json::stringValue, "imagetag")) { container_info->m_imagetag = imagetag.asString(); } - const Json::Value& imagedigest = container["imagedigest"]; - if(check_json_val_is_convertible(imagedigest, Json::stringValue, "imagedigest")) - { + const Json::Value &imagedigest = container["imagedigest"]; + if(check_json_val_is_convertible(imagedigest, Json::stringValue, "imagedigest")) { container_info->m_imagedigest = imagedigest.asString(); } - const Json::Value& privileged = container["privileged"]; - if(check_json_val_is_convertible(privileged, Json::booleanValue, "privileged")) - { + const Json::Value &privileged = container["privileged"]; + if(check_json_val_is_convertible(privileged, Json::booleanValue, "privileged")) { container_info->m_privileged = privileged.asBool(); } - const Json::Value& lookup_state = container["lookup_state"]; - if(check_json_val_is_convertible(lookup_state, Json::uintValue, "lookup_state")) - { - container_info->set_lookup_status(static_cast(lookup_state.asUInt())); - switch(container_info->get_lookup_status()) - { + const Json::Value &lookup_state = container["lookup_state"]; + if(check_json_val_is_convertible(lookup_state, Json::uintValue, "lookup_state")) { + container_info->set_lookup_status( + static_cast(lookup_state.asUInt())); + switch(container_info->get_lookup_status()) { case sinsp_container_lookup::state::STARTED: case sinsp_container_lookup::state::SUCCESSFUL: case sinsp_container_lookup::state::FAILED: @@ -5230,157 +4732,148 @@ void sinsp_parser::parse_container_json_evt(sinsp_evt *evt) // state == STARTED doesn't make sense in a scap file // as there's no actual lookup that would ever finish - if(!evt->get_tinfo_ref() && container_info->get_lookup_status() == sinsp_container_lookup::state::STARTED) - { - SINSP_DEBUG("Rewriting lookup_state = STARTED from scap file to FAILED for container %s", - container_info->m_id.c_str()); + if(!evt->get_tinfo_ref() && + container_info->get_lookup_status() == sinsp_container_lookup::state::STARTED) { + SINSP_DEBUG( + "Rewriting lookup_state = STARTED from scap file to FAILED for container " + "%s", + container_info->m_id.c_str()); container_info->set_lookup_status(sinsp_container_lookup::state::FAILED); } - } - else - { + } else { // Fallback at successful state container_info->set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); } - const Json::Value& created_time = container["created_time"]; - if(check_int64_json_is_convertible(created_time, "created_time")) - { + const Json::Value &created_time = container["created_time"]; + if(check_int64_json_is_convertible(created_time, "created_time")) { container_info->m_created_time = created_time.asInt64(); } #if !defined(MINIMAL_BUILD) && !defined(_WIN32) && !defined(__EMSCRIPTEN__) - libsinsp::container_engine::docker_async_source::parse_json_mounts(container["Mounts"], container_info->m_mounts); + libsinsp::container_engine::docker_async_source::parse_json_mounts( + container["Mounts"], + container_info->m_mounts); #endif - const Json::Value& user = container["User"]; - if(check_json_val_is_convertible(user, Json::stringValue, "User")) - { + const Json::Value &user = container["User"]; + if(check_json_val_is_convertible(user, Json::stringValue, "User")) { container_info->m_container_user = user.asString(); } - sinsp_container_info::container_health_probe::parse_health_probes(container, container_info->m_health_probes); + sinsp_container_info::container_health_probe::parse_health_probes( + container, + container_info->m_health_probes); - const Json::Value& contip = container["ip"]; - if(check_json_val_is_convertible(contip, Json::stringValue, "ip")) - { + const Json::Value &contip = container["ip"]; + if(check_json_val_is_convertible(contip, Json::stringValue, "ip")) { uint32_t ip; - if(inet_pton(AF_INET, contip.asString().c_str(), &ip) == -1) - { + if(inet_pton(AF_INET, contip.asString().c_str(), &ip) == -1) { throw sinsp_exception("Invalid 'ip' field while parsing container info: " + json); } container_info->m_container_ip = ntohl(ip); } - const Json::Value& cniresult = container["cni_json"]; - if(check_json_val_is_convertible(cniresult, Json::stringValue, "cni_json")) - { + const Json::Value &cniresult = container["cni_json"]; + if(check_json_val_is_convertible(cniresult, Json::stringValue, "cni_json")) { container_info->m_pod_sandbox_cniresult = cniresult.asString(); } - const Json::Value& pod_sandbox_id = container["pod_sandbox_id"]; - if(check_json_val_is_convertible(pod_sandbox_id, Json::stringValue, "pod_sandbox_id")) - { + const Json::Value &pod_sandbox_id = container["pod_sandbox_id"]; + if(check_json_val_is_convertible(pod_sandbox_id, Json::stringValue, "pod_sandbox_id")) { container_info->m_pod_sandbox_id = pod_sandbox_id.asString(); } const Json::Value &port_mappings = container["port_mappings"]; - if(check_json_val_is_convertible(port_mappings, Json::arrayValue, "port_mappings")) - { - for (Json::Value::ArrayIndex i = 0; i != port_mappings.size(); i++) - { + if(check_json_val_is_convertible(port_mappings, Json::arrayValue, "port_mappings")) { + for(Json::Value::ArrayIndex i = 0; i != port_mappings.size(); i++) { sinsp_container_info::container_port_mapping map; const Json::Value &host_ip = port_mappings[i]["HostIp"]; // We log message for HostIp conversion failure at Warning level if(check_json_val_is_convertible(host_ip, Json::intValue, "HostIp", true)) { map.m_host_ip = host_ip.asInt(); } - const Json::Value& host_port = port_mappings[i]["HostPort"]; + const Json::Value &host_port = port_mappings[i]["HostPort"]; // We log message for HostPort conversion failure at Warning level if(check_json_val_is_convertible(host_port, Json::intValue, "HostPort", true)) { - map.m_host_port = (uint16_t) host_port.asInt(); + map.m_host_port = (uint16_t)host_port.asInt(); } - const Json::Value& container_port = port_mappings[i]["ContainerPort"]; + const Json::Value &container_port = port_mappings[i]["ContainerPort"]; // We log message for ContainerPort conversion failure at Warning level - if(check_json_val_is_convertible(container_port, Json::intValue, "ContainerPort", true)) { - map.m_container_port = (uint16_t) container_port.asInt(); + if(check_json_val_is_convertible(container_port, + Json::intValue, + "ContainerPort", + true)) { + map.m_container_port = (uint16_t)container_port.asInt(); } container_info->m_port_mappings.push_back(map); } } std::vector labels = container["labels"].getMemberNames(); - for(std::vector::const_iterator it = labels.begin(); it != labels.end(); ++it) - { + for(std::vector::const_iterator it = labels.begin(); it != labels.end(); + ++it) { std::string val = container["labels"][*it].asString(); container_info->m_labels[*it] = val; } - std::vector pod_sandbox_labels = container["pod_sandbox_labels"].getMemberNames(); - for(std::vector::const_iterator it = pod_sandbox_labels.begin(); it != pod_sandbox_labels.end(); ++it) - { + std::vector pod_sandbox_labels = + container["pod_sandbox_labels"].getMemberNames(); + for(std::vector::const_iterator it = pod_sandbox_labels.begin(); + it != pod_sandbox_labels.end(); + ++it) { std::string val = container["pod_sandbox_labels"][*it].asString(); container_info->m_pod_sandbox_labels[*it] = val; } - const Json::Value& env_vars = container["env"]; + const Json::Value &env_vars = container["env"]; - for(const auto& env_var : env_vars) - { - if(env_var.isString()) - { + for(const auto &env_var : env_vars) { + if(env_var.isString()) { container_info->m_env.emplace_back(env_var.asString()); } } - const Json::Value& memory_limit = container["memory_limit"]; - if(check_int64_json_is_convertible(memory_limit, "memory_limit")) - { + const Json::Value &memory_limit = container["memory_limit"]; + if(check_int64_json_is_convertible(memory_limit, "memory_limit")) { container_info->m_memory_limit = memory_limit.asInt64(); } - const Json::Value& swap_limit = container["swap_limit"]; - if(check_int64_json_is_convertible(swap_limit, "swap_limit")) - { + const Json::Value &swap_limit = container["swap_limit"]; + if(check_int64_json_is_convertible(swap_limit, "swap_limit")) { container_info->m_swap_limit = swap_limit.asInt64(); } - const Json::Value& cpu_shares = container["cpu_shares"]; - if(check_int64_json_is_convertible(cpu_shares, "cpu_shares")) - { + const Json::Value &cpu_shares = container["cpu_shares"]; + if(check_int64_json_is_convertible(cpu_shares, "cpu_shares")) { container_info->m_cpu_shares = cpu_shares.asInt64(); } - const Json::Value& cpu_quota = container["cpu_quota"]; - if(check_int64_json_is_convertible(cpu_quota, "cpu_quota")) - { + const Json::Value &cpu_quota = container["cpu_quota"]; + if(check_int64_json_is_convertible(cpu_quota, "cpu_quota")) { container_info->m_cpu_quota = cpu_quota.asInt64(); } - const Json::Value& cpu_period = container["cpu_period"]; - if(check_int64_json_is_convertible(cpu_period, "cpu_period")) - { + const Json::Value &cpu_period = container["cpu_period"]; + if(check_int64_json_is_convertible(cpu_period, "cpu_period")) { container_info->m_cpu_period = cpu_period.asInt64(); } - const Json::Value& cpuset_cpu_count = container["cpuset_cpu_count"]; - if(check_json_val_is_convertible(cpuset_cpu_count, Json::intValue, "cpuset_cpu_count")) - { + const Json::Value &cpuset_cpu_count = container["cpuset_cpu_count"]; + if(check_json_val_is_convertible(cpuset_cpu_count, Json::intValue, "cpuset_cpu_count")) { container_info->m_cpuset_cpu_count = cpuset_cpu_count.asInt(); } - const Json::Value& mesos_task_id = container["mesos_task_id"]; - if(check_json_val_is_convertible(mesos_task_id, Json::stringValue, "mesos_task_id")) - { + const Json::Value &mesos_task_id = container["mesos_task_id"]; + if(check_json_val_is_convertible(mesos_task_id, Json::stringValue, "mesos_task_id")) { container_info->m_mesos_task_id = mesos_task_id.asString(); } - const Json::Value& metadata_deadline = container["metadata_deadline"]; - if(!metadata_deadline.isNull()) - { + const Json::Value &metadata_deadline = container["metadata_deadline"]; + if(!metadata_deadline.isNull()) { // isConvertibleTo doesn't seem to work on large 64 bit numbers if(metadata_deadline.isUInt64()) { container_info->m_metadata_deadline = metadata_deadline.asUInt64(); @@ -5389,9 +4882,11 @@ void sinsp_parser::parse_container_json_evt(sinsp_evt *evt) } } - if(!container_info->is_successful()) - { - SINSP_DEBUG("Filtering container event for failed lookup of %s (but calling callbacks anyway)", container_info->m_id.c_str()); + if(!container_info->is_successful()) { + SINSP_DEBUG( + "Filtering container event for failed lookup of %s (but calling callbacks " + "anyway)", + container_info->m_id.c_str()); evt->set_filtered_out(true); } evt->set_tinfo_ref(container_info->get_tinfo(m_inspector)); @@ -5404,24 +4899,22 @@ void sinsp_parser::parse_container_json_evt(sinsp_evt *evt) "\nImage: " + container_info.m_image + "\nMesos Task ID: " + container_info.m_mesos_task_id); */ - } - else - { + } else { std::string errstr; errstr = Json::Reader().getFormattedErrorMessages(); - throw sinsp_exception("Invalid JSON encountered while parsing container info: " + json + "error=" + errstr); + throw sinsp_exception("Invalid JSON encountered while parsing container info: " + json + + "error=" + errstr); } } -void sinsp_parser::parse_container_evt(sinsp_evt *evt) -{ +void sinsp_parser::parse_container_evt(sinsp_evt *evt) { const sinsp_evt_param *parinfo; auto container = std::make_shared(); parinfo = evt->get_param(0); container->m_id = parinfo->m_val; - container->m_type = (sinsp_container_type) evt->get_param(1)->as(); + container->m_type = (sinsp_container_type)evt->get_param(1)->as(); parinfo = evt->get_param(2); container->m_name = parinfo->m_val; @@ -5432,8 +4925,7 @@ void sinsp_parser::parse_container_evt(sinsp_evt *evt) m_inspector->m_container_manager.add_container(container, evt->get_thread_info(true)); } -void sinsp_parser::parse_user_evt(sinsp_evt *evt) -{ +void sinsp_parser::parse_user_evt(sinsp_evt *evt) { uint32_t uid, gid; std::string_view name, home, shell, container_id; @@ -5446,47 +4938,39 @@ void sinsp_parser::parse_user_evt(sinsp_evt *evt) shell = evt->get_param(4)->as(); container_id = evt->get_param(5)->as(); - if (evt->get_scap_evt()->type == PPME_USER_ADDED_E) - { - m_inspector->m_usergroup_manager.add_user(std::string(container_id), -1, uid, gid, name, home, shell); - } else - { + if(evt->get_scap_evt()->type == PPME_USER_ADDED_E) { + m_inspector->m_usergroup_manager + .add_user(std::string(container_id), -1, uid, gid, name, home, shell); + } else { m_inspector->m_usergroup_manager.rm_user(std::string(container_id), uid); } } -void sinsp_parser::parse_group_evt(sinsp_evt *evt) -{ +void sinsp_parser::parse_group_evt(sinsp_evt *evt) { uint32_t gid = evt->get_param(0)->as(); std::string_view name = evt->get_param(1)->as(); std::string_view container_id = evt->get_param(2)->as(); - if ( evt->get_scap_evt()->type == PPME_GROUP_ADDED_E) - { + if(evt->get_scap_evt()->type == PPME_GROUP_ADDED_E) { m_inspector->m_usergroup_manager.add_group(container_id.data(), -1, gid, name.data()); - } else - { + } else { m_inspector->m_usergroup_manager.rm_group(container_id.data(), gid); } } -void sinsp_parser::parse_cpu_hotplug_enter(sinsp_evt *evt) -{ - if(m_inspector->is_live() || m_inspector->is_syscall_plugin()) - { +void sinsp_parser::parse_cpu_hotplug_enter(sinsp_evt *evt) { + if(m_inspector->is_live() || m_inspector->is_syscall_plugin()) { throw sinsp_exception("CPU " + evt->get_param_value_str("cpu") + - " configuration change detected. Aborting."); + " configuration change detected. Aborting."); } } -void sinsp_parser::parse_prctl_exit_event(sinsp_evt *evt) -{ +void sinsp_parser::parse_prctl_exit_event(sinsp_evt *evt) { /* Parameter 1: res (type: PT_ERRNO) */ int64_t retval = evt->get_param(0)->as(); - if(retval < 0) - { + if(retval < 0) { /* we are not interested in parsing something if the syscall fails */ return; } @@ -5494,8 +4978,7 @@ void sinsp_parser::parse_prctl_exit_event(sinsp_evt *evt) /* prctl could be called by the main thread but also by a secondary thread */ auto caller_tinfo = evt->get_thread_info(); /* only invalid threads have `caller_tinfo->m_tginfo == nullptr` */ - if(caller_tinfo == nullptr || caller_tinfo->is_invalid()) - { + if(caller_tinfo == nullptr || caller_tinfo->is_invalid()) { return; } @@ -5503,74 +4986,63 @@ void sinsp_parser::parse_prctl_exit_event(sinsp_evt *evt) /* Parameter 2: option (type: PT_ENUMFLAGS32) */ uint32_t option = evt->get_param(1)->as(); - switch(option) - { - case PPM_PR_SET_CHILD_SUBREAPER: - /* Parameter 4: arg2_int (type: PT_INT64) */ - /* If the user provided an arg2 != 0, we set the child_subreaper - * attribute for the calling process. If arg2 is zero, unset the attribute - */ - child_subreaper = (evt->get_param(3)->as()) != 0 ? true : false; - caller_tinfo->m_tginfo->set_reaper(child_subreaper); - break; + switch(option) { + case PPM_PR_SET_CHILD_SUBREAPER: + /* Parameter 4: arg2_int (type: PT_INT64) */ + /* If the user provided an arg2 != 0, we set the child_subreaper + * attribute for the calling process. If arg2 is zero, unset the attribute + */ + child_subreaper = (evt->get_param(3)->as()) != 0 ? true : false; + caller_tinfo->m_tginfo->set_reaper(child_subreaper); + break; - case PPM_PR_GET_CHILD_SUBREAPER: - /* Parameter 4: arg2_int (type: PT_INT64) */ - /* arg2 != 0 means the calling process is a child_subreaper */ - child_subreaper = (evt->get_param(3)->as()) != 0 ? true : false; - caller_tinfo->m_tginfo->set_reaper(child_subreaper); - break; + case PPM_PR_GET_CHILD_SUBREAPER: + /* Parameter 4: arg2_int (type: PT_INT64) */ + /* arg2 != 0 means the calling process is a child_subreaper */ + child_subreaper = (evt->get_param(3)->as()) != 0 ? true : false; + caller_tinfo->m_tginfo->set_reaper(child_subreaper); + break; - default: - break; + default: + break; } } - -uint8_t* sinsp_parser::reserve_event_buffer() -{ - if(m_tmp_events_buffer.empty()) - { - return (uint8_t*)malloc(sizeof(uint8_t)*SP_EVT_BUF_SIZE); - } - else - { +uint8_t *sinsp_parser::reserve_event_buffer() { + if(m_tmp_events_buffer.empty()) { + return (uint8_t *)malloc(sizeof(uint8_t) * SP_EVT_BUF_SIZE); + } else { auto ptr = m_tmp_events_buffer.top(); m_tmp_events_buffer.pop(); return ptr; } } -void sinsp_parser::parse_chroot_exit(sinsp_evt *evt) -{ - if(evt->get_tinfo() == nullptr) - { +void sinsp_parser::parse_chroot_exit(sinsp_evt *evt) { + if(evt->get_tinfo() == nullptr) { return; } int64_t retval = evt->get_param(0)->as(); - if(retval == 0) - { - const char* resolved_path; + if(retval == 0) { + const char *resolved_path; auto path = evt->get_param_as_str(1, &resolved_path); - if(resolved_path[0] == 0) - { + if(resolved_path[0] == 0) { evt->get_tinfo()->m_root = path; - } - else - { + } else { evt->get_tinfo()->m_root = resolved_path; } // Root change, let's detect if we are on a container auto container_id = evt->get_tinfo()->m_container_id; - m_inspector->m_container_manager.resolve_container(evt->get_tinfo(), m_inspector->is_live() || m_inspector->is_syscall_plugin()); + m_inspector->m_container_manager.resolve_container( + evt->get_tinfo(), + m_inspector->is_live() || m_inspector->is_syscall_plugin()); // // Refresh user / loginuser / group // if we happen to change container id // - if(container_id != evt->get_tinfo()->m_container_id) - { + if(container_id != evt->get_tinfo()->m_container_id) { evt->get_tinfo()->set_user(evt->get_tinfo()->m_user.uid()); evt->get_tinfo()->set_loginuser(evt->get_tinfo()->m_loginuser.uid()); evt->get_tinfo()->set_group(evt->get_tinfo()->m_group.gid()); @@ -5578,8 +5050,7 @@ void sinsp_parser::parse_chroot_exit(sinsp_evt *evt) } } -void sinsp_parser::parse_setsid_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_setsid_exit(sinsp_evt *evt) { int64_t retval; // @@ -5587,24 +5058,21 @@ void sinsp_parser::parse_setsid_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval >= 0) - { - if (evt->get_thread_info()) { + if(retval >= 0) { + if(evt->get_thread_info()) { evt->get_thread_info()->m_sid = retval; } } } -void sinsp_parser::parse_getsockopt_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_getsockopt_exit(sinsp_evt *evt) { const sinsp_evt_param *parinfo; int64_t retval; int64_t err; int64_t fd; int8_t level, optname; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -5615,8 +5083,7 @@ void sinsp_parser::parse_getsockopt_exit(sinsp_evt *evt) // right now we only parse getsockopt() for SO_ERROR options // if that ever changes, move this check inside // the `if (level == PPM_SOCKOPT_LEVEL_SOL_SOCKET ...)` block - if (!m_track_connection_status) - { + if(!m_track_connection_status) { return; } @@ -5625,8 +5092,7 @@ void sinsp_parser::parse_getsockopt_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval < 0) - { + if(retval < 0) { return; } @@ -5634,42 +5100,34 @@ void sinsp_parser::parse_getsockopt_exit(sinsp_evt *evt) optname = evt->get_param(3)->as(); - if(level == PPM_SOCKOPT_LEVEL_SOL_SOCKET && optname == PPM_SOCKOPT_SO_ERROR) - { + if(level == PPM_SOCKOPT_LEVEL_SOL_SOCKET && optname == PPM_SOCKOPT_SO_ERROR) { auto main_thread = evt->get_tinfo()->get_main_thread(); - if(main_thread == nullptr) - { + if(main_thread == nullptr) { return; } evt->set_fd_info(main_thread->get_fd(fd)); - if (!evt->get_fd_info()) - { + if(!evt->get_fd_info()) { return; } parinfo = evt->get_param(4); ASSERT(*parinfo->m_val == PPM_SOCKOPT_IDX_ERRNO); ASSERT(parinfo->m_len == sizeof(int64_t) + 1); - err = *(int64_t *)(parinfo->m_val + 1); // add 1 byte to skip over PT_DYN param index + err = *(int64_t *)(parinfo->m_val + 1); // add 1 byte to skip over PT_DYN param index evt->set_errorcode((int32_t)err); - if (err < 0) - { + if(err < 0) { evt->get_fd_info()->set_socket_failed(); - } - else - { + } else { evt->get_fd_info()->set_socket_connected(); } - if (m_inspector->get_observer()) - { + if(m_inspector->get_observer()) { m_inspector->get_observer()->on_socket_status_changed(evt); } } } -void sinsp_parser::parse_capset_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_capset_exit(sinsp_evt *evt) { sinsp_threadinfo *tinfo; int64_t retval; @@ -5678,8 +5136,7 @@ void sinsp_parser::parse_capset_exit(sinsp_evt *evt) // retval = evt->get_param(0)->as(); - if(retval < 0 || evt->get_tinfo() == nullptr) - { + if(retval < 0 || evt->get_tinfo() == nullptr) { return; } @@ -5695,8 +5152,7 @@ void sinsp_parser::parse_capset_exit(sinsp_evt *evt) tinfo->m_cap_effective = evt->get_param(3)->as(); } -void sinsp_parser::parse_unshare_setns_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_unshare_setns_exit(sinsp_evt *evt) { sinsp_evt *enter_evt = &m_tmp_evt; sinsp_threadinfo *tinfo; int64_t retval; @@ -5704,13 +5160,11 @@ void sinsp_parser::parse_unshare_setns_exit(sinsp_evt *evt) retval = evt->get_param(0)->as(); - if(retval < 0 || evt->get_tinfo() == nullptr) - { + if(retval < 0 || evt->get_tinfo() == nullptr) { return; } - if(!retrieve_enter_event(enter_evt, evt)) - { + if(!retrieve_enter_event(enter_evt, evt)) { return; } @@ -5719,20 +5173,16 @@ void sinsp_parser::parse_unshare_setns_exit(sinsp_evt *evt) // // Retrieve flags from enter event // - if(etype == PPME_SYSCALL_UNSHARE_X) - { + if(etype == PPME_SYSCALL_UNSHARE_X) { flags = enter_evt->get_param(0)->as(); - } - else if(etype == PPME_SYSCALL_SETNS_X) - { + } else if(etype == PPME_SYSCALL_SETNS_X) { flags = enter_evt->get_param(1)->as(); } // // Update capabilities // - if(flags & PPM_CL_CLONE_NEWUSER) - { + if(flags & PPM_CL_CLONE_NEWUSER) { tinfo = evt->get_tinfo(); uint64_t max_caps = sinsp_utils::get_max_caps(); tinfo->m_cap_inheritable = max_caps; @@ -5741,25 +5191,19 @@ void sinsp_parser::parse_unshare_setns_exit(sinsp_evt *evt) } } -void sinsp_parser::free_event_buffer(uint8_t *ptr) -{ - if(m_tmp_events_buffer.size() < m_inspector->m_thread_manager->get_threads()->size()) - { +void sinsp_parser::free_event_buffer(uint8_t *ptr) { + if(m_tmp_events_buffer.size() < m_inspector->m_thread_manager->get_threads()->size()) { m_tmp_events_buffer.push(ptr); - } - else - { + } else { free(ptr); } } -void sinsp_parser::parse_memfd_create_exit(sinsp_evt *evt, scap_fd_type type) -{ +void sinsp_parser::parse_memfd_create_exit(sinsp_evt *evt, scap_fd_type type) { int64_t fd; uint32_t flags; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -5778,8 +5222,7 @@ void sinsp_parser::parse_memfd_create_exit(sinsp_evt *evt, scap_fd_type type) flags = evt->get_param(2)->as(); auto fdi = m_inspector->build_fdinfo(); - if(fd >= 0) - { + if(fd >= 0) { fdi->m_type = type; fdi->add_filename(name); fdi->m_openflags = flags; @@ -5788,14 +5231,12 @@ void sinsp_parser::parse_memfd_create_exit(sinsp_evt *evt, scap_fd_type type) evt->set_fd_info(evt->get_tinfo()->add_fd(fd, std::move(fdi))); } -void sinsp_parser::parse_pidfd_open_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_pidfd_open_exit(sinsp_evt *evt) { int64_t fd; int64_t pid; int64_t flags; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -5811,8 +5252,7 @@ void sinsp_parser::parse_pidfd_open_exit(sinsp_evt *evt) flags = evt->get_param(2)->as(); auto fdi = m_inspector->build_fdinfo(); - if(fd >= 0) - { + if(fd >= 0) { // note: approximating equivalent filename as in: // https://man7.org/linux/man-pages/man2/pidfd_getfd.2.html std::string fname = std::string(scap_get_host_root()) + "/proc/" + std::to_string(pid); @@ -5825,14 +5265,12 @@ void sinsp_parser::parse_pidfd_open_exit(sinsp_evt *evt) evt->set_fd_info(evt->get_tinfo()->add_fd(fd, std::move(fdi))); } -void sinsp_parser::parse_pidfd_getfd_exit(sinsp_evt *evt) -{ +void sinsp_parser::parse_pidfd_getfd_exit(sinsp_evt *evt) { int64_t fd; int64_t pidfd; int64_t targetfd; - if(evt->get_tinfo() == nullptr) - { + if(evt->get_tinfo() == nullptr) { return; } @@ -5852,30 +5290,25 @@ void sinsp_parser::parse_pidfd_getfd_exit(sinsp_evt *evt) // currently unused: https://man7.org/linux/man-pages/man2/pidfd_getfd.2.html auto pidfd_fdinfo = evt->get_tinfo()->get_fd(pidfd); - if (pidfd_fdinfo == nullptr || !pidfd_fdinfo->is_pidfd()) - { + if(pidfd_fdinfo == nullptr || !pidfd_fdinfo->is_pidfd()) { return; } auto pidfd_tinfo = m_inspector->get_thread_ref(pidfd_fdinfo->m_pid); - if (pidfd_tinfo == nullptr) - { + if(pidfd_tinfo == nullptr) { return; } auto targetfd_fdinfo = pidfd_tinfo->get_fd(targetfd); - if (targetfd_fdinfo == nullptr) - { + if(targetfd_fdinfo == nullptr) { return; } evt->get_tinfo()->add_fd(fd, targetfd_fdinfo->clone()); } -int sinsp_parser::get_fd_location(uint16_t etype) -{ +int sinsp_parser::get_fd_location(uint16_t etype) { int location; - switch (etype) - { + switch(etype) { case PPME_SYSCALL_MMAP_E: case PPME_SYSCALL_MMAP2_E: location = 4; diff --git a/userspace/libsinsp/parsers.h b/userspace/libsinsp/parsers.h index 51ad9c9fb7..7c69c96e5f 100644 --- a/userspace/libsinsp/parsers.h +++ b/userspace/libsinsp/parsers.h @@ -25,8 +25,7 @@ limitations under the License. #include #include -class sinsp_parser -{ +class sinsp_parser { public: sinsp_parser(sinsp* inspector); ~sinsp_parser(); @@ -47,21 +46,18 @@ class sinsp_parser // // Combine the openat arguments into a full file name // - std::string parse_dirfd(sinsp_evt *evt, std::string_view name, int64_t dirfd); + std::string parse_dirfd(sinsp_evt* evt, std::string_view name, int64_t dirfd); void set_track_connection_status(bool enabled); bool get_track_connection_status() const { return m_track_connection_status; } - inline sinsp_syslog_decoder& get_syslog_decoder() - { - return m_syslog_decoder; - } + inline sinsp_syslog_decoder& get_syslog_decoder() { return m_syslog_decoder; } private: // // Helpers // - bool reset(sinsp_evt *evt); + bool reset(sinsp_evt* evt); inline void store_event(sinsp_evt* evt); // @@ -84,7 +80,7 @@ class sinsp_parser void parse_close_exit(sinsp_evt* evt); void parse_thread_exit(sinsp_evt* evt); void parse_memfd_create_exit(sinsp_evt* evt, scap_fd_type type); - void parse_pidfd_open_exit(sinsp_evt *evt); + void parse_pidfd_open_exit(sinsp_evt* evt); void parse_pidfd_getfd_exit(sinsp_evt* evt); void parse_fspath_related_exit(sinsp_evt* evt); inline void parse_rw_exit(sinsp_evt* evt); @@ -99,10 +95,10 @@ class sinsp_parser void parse_single_param_fd_exit(sinsp_evt* evt, scap_fd_type type); void parse_getrlimit_setrlimit_exit(sinsp_evt* evt); void parse_prlimit_exit(sinsp_evt* evt); - void parse_select_poll_epollwait_enter(sinsp_evt *evt); + void parse_select_poll_epollwait_enter(sinsp_evt* evt); void parse_fcntl_enter(sinsp_evt* evt); void parse_fcntl_exit(sinsp_evt* evt); - void parse_prctl_exit_event(sinsp_evt *evt); + void parse_prctl_exit_event(sinsp_evt* evt); void parse_context_switch(sinsp_evt* evt); void parse_brk_munmap_mmap_exit(sinsp_evt* evt); void parse_setresuid_exit(sinsp_evt* evt); @@ -111,30 +107,45 @@ class sinsp_parser void parse_setregid_exit(sinsp_evt* evt); void parse_setuid_exit(sinsp_evt* evt); void parse_setgid_exit(sinsp_evt* evt); - void parse_container_evt(sinsp_evt* evt); // deprecated, only for backward-compatibility - void parse_container_json_evt(sinsp_evt *evt); - void parse_user_evt(sinsp_evt *evt); - void parse_group_evt(sinsp_evt *evt); + void parse_container_evt(sinsp_evt* evt); // deprecated, only for backward-compatibility + void parse_container_json_evt(sinsp_evt* evt); + void parse_user_evt(sinsp_evt* evt); + void parse_group_evt(sinsp_evt* evt); void parse_cpu_hotplug_enter(sinsp_evt* evt); - void parse_chroot_exit(sinsp_evt *evt); - void parse_setsid_exit(sinsp_evt *evt); - void parse_getsockopt_exit(sinsp_evt *evt); - void parse_capset_exit(sinsp_evt *evt); - void parse_unshare_setns_exit(sinsp_evt *evt); + void parse_chroot_exit(sinsp_evt* evt); + void parse_setsid_exit(sinsp_evt* evt); + void parse_getsockopt_exit(sinsp_evt* evt); + void parse_capset_exit(sinsp_evt* evt); + void parse_unshare_setns_exit(sinsp_evt* evt); inline bool update_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, - uint32_t tsip, uint16_t tsport, uint32_t tdip, uint16_t tdport, bool overwrite_dest=true); + uint32_t tsip, + uint16_t tsport, + uint32_t tdip, + uint16_t tdport, + bool overwrite_dest = true); inline void fill_client_socket_info(sinsp_evt* evt, uint8_t* packed_data, bool overwrite_dest); - inline void add_socket(sinsp_evt* evt, int64_t fd, uint32_t domain, uint32_t type, uint32_t protocol); - inline void infer_sendto_fdinfo(sinsp_evt *evt); - inline void add_pipe(sinsp_evt *evt, int64_t fd, uint64_t ino, uint32_t openflags); + inline void add_socket(sinsp_evt* evt, + int64_t fd, + uint32_t domain, + uint32_t type, + uint32_t protocol); + inline void infer_sendto_fdinfo(sinsp_evt* evt); + inline void add_pipe(sinsp_evt* evt, int64_t fd, uint64_t ino, uint32_t openflags); // Return false if the update didn't happen (for example because the tuple is NULL) - bool update_fd(sinsp_evt *evt, const sinsp_evt_param* parinfo); - - // Next 4 return false if the update didn't happen because the tuple is identical to the given address - bool set_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* packed_data, bool overwrite_dest=true); - bool set_ipv4_mapped_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* packed_data, bool overwrite_dest=true); - bool set_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, uint8_t* packed_data, bool overwrite_dest=true); + bool update_fd(sinsp_evt* evt, const sinsp_evt_param* parinfo); + + // Next 4 return false if the update didn't happen because the tuple is identical to the given + // address + bool set_ipv4_addresses_and_ports(sinsp_fdinfo* fdinfo, + uint8_t* packed_data, + bool overwrite_dest = true); + bool set_ipv4_mapped_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, + uint8_t* packed_data, + bool overwrite_dest = true); + bool set_ipv6_addresses_and_ports(sinsp_fdinfo* fdinfo, + uint8_t* packed_data, + bool overwrite_dest = true); bool set_unix_info(sinsp_fdinfo* fdinfo, uint8_t* packed_data); void swap_addresses(sinsp_fdinfo* fdinfo); diff --git a/userspace/libsinsp/plugin.cpp b/userspace/libsinsp/plugin.cpp old mode 100755 new mode 100644 index 1a777b8c0a..d4e621cd86 --- a/userspace/libsinsp/plugin.cpp +++ b/userspace/libsinsp/plugin.cpp @@ -16,7 +16,6 @@ limitations under the License. */ - #include #include #include @@ -49,62 +48,57 @@ static constexpr const char* s_init_twice_err = "plugin has been initialized twi // Plugin Type Look Up Table // const std::unordered_map s_pt_lut = { - {"string", PT_CHARBUF}, - {"uint64", PT_UINT64}, - {"reltime", PT_RELTIME}, - {"abstime", PT_ABSTIME}, - {"bool", PT_BOOL}, - {"ipaddr", PT_IPADDR}, - {"ipnet", PT_IPNET}, + {"string", PT_CHARBUF}, + {"uint64", PT_UINT64}, + {"reltime", PT_RELTIME}, + {"abstime", PT_ABSTIME}, + {"bool", PT_BOOL}, + {"ipaddr", PT_IPADDR}, + {"ipnet", PT_IPNET}, }; // Used below--set a std::string from the provided allocated charbuf -static std::string str_from_alloc_charbuf(const char* charbuf) -{ +static std::string str_from_alloc_charbuf(const char* charbuf) { std::string str; - if(charbuf != NULL) - { + if(charbuf != NULL) { str = charbuf; } return str; } -const char* sinsp_plugin::get_owner_last_error(ss_plugin_owner_t* o) -{ +const char* sinsp_plugin::get_owner_last_error(ss_plugin_owner_t* o) { auto t = static_cast(o); - if (t->m_last_owner_err.empty()) - { + if(t->m_last_owner_err.empty()) { return NULL; } return t->m_last_owner_err.c_str(); } -static void plugin_log_fn(ss_plugin_owner_t* o, const char* component, const char* msg, ss_plugin_log_severity sev) -{ +static void plugin_log_fn(ss_plugin_owner_t* o, + const char* component, + const char* msg, + ss_plugin_log_severity sev) { auto t = static_cast(o); std::string prefix = (component == NULL) ? t->name() : std::string(component); libsinsp_logger()->log(prefix + ": " + msg, (sinsp_logger::severity)sev); } std::shared_ptr sinsp_plugin::create( - const plugin_api* api, - const std::shared_ptr& treg, - const std::shared_ptr& tpool, - std::string& errstr) -{ + const plugin_api* api, + const std::shared_ptr& treg, + const std::shared_ptr& tpool, + std::string& errstr) { char loadererr[PLUGIN_MAX_ERRLEN]; auto handle = plugin_load_api(api, loadererr); - if (handle == NULL) - { + if(handle == NULL) { errstr = loadererr; return nullptr; } auto plugin = std::make_shared(handle, treg, tpool); - if (!plugin->resolve_dylib_symbols(errstr)) - { + if(!plugin->resolve_dylib_symbols(errstr)) { // plugin and handle get deleted here by shared_ptr return nullptr; } @@ -113,22 +107,19 @@ std::shared_ptr sinsp_plugin::create( } std::shared_ptr sinsp_plugin::create( - const std::string &filepath, - const std::shared_ptr& treg, - const std::shared_ptr& tpool, - std::string& errstr) -{ + const std::string& filepath, + const std::shared_ptr& treg, + const std::shared_ptr& tpool, + std::string& errstr) { char loadererr[PLUGIN_MAX_ERRLEN]; auto handle = plugin_load(filepath.c_str(), loadererr); - if (handle == NULL) - { + if(handle == NULL) { errstr = loadererr; return nullptr; } auto plugin = std::make_shared(handle, treg, tpool); - if (!plugin->resolve_dylib_symbols(errstr)) - { + if(!plugin->resolve_dylib_symbols(errstr)) { // plugin and handle get deleted here by shared_ptr return nullptr; } @@ -136,34 +127,28 @@ std::shared_ptr sinsp_plugin::create( return plugin; } -bool sinsp_plugin::is_plugin_loaded(const std::string &filepath) -{ +bool sinsp_plugin::is_plugin_loaded(const std::string& filepath) { return plugin_is_loaded(filepath.c_str()); } -sinsp_plugin::~sinsp_plugin() -{ +sinsp_plugin::~sinsp_plugin() { destroy(); plugin_unload(m_handle); auto cur_async_handler = m_async_evt_handler.load(); - if (cur_async_handler) - { + if(cur_async_handler) { m_async_evt_handler.store(nullptr); delete cur_async_handler; } } -bool sinsp_plugin::init(const std::string &config, std::string &errstr) -{ - if (m_inited) - { +bool sinsp_plugin::init(const std::string& config, std::string& errstr) { + if(m_inited) { errstr = std::string(s_init_twice_err) + ": " + m_name; return false; } - if (!m_handle->api.init) - { + if(!m_handle->api.init) { errstr = string("init api symbol not found"); return false; } @@ -182,13 +167,12 @@ bool sinsp_plugin::init(const std::string &config, std::string &errstr) ss_plugin_init_tables_input tables_in = {}; ss_plugin_table_fields_vtable_ext table_fields_ext = {}; - ss_plugin_table_reader_vtable reader_deprecated = {}; // unused + ss_plugin_table_reader_vtable reader_deprecated = {}; // unused ss_plugin_table_reader_vtable_ext table_reader_ext = {}; - ss_plugin_table_writer_vtable writer_deprecated = {}; // unused + ss_plugin_table_writer_vtable writer_deprecated = {}; // unused ss_plugin_table_writer_vtable_ext table_writer_ext = {}; - if (m_caps & (CAP_PARSING | CAP_EXTRACTION)) - { + if(m_caps & (CAP_PARSING | CAP_EXTRACTION)) { tables_in.fields_ext = &table_fields_ext; tables_in.reader_ext = &table_reader_ext; tables_in.writer_ext = &table_writer_ext; @@ -200,9 +184,8 @@ bool sinsp_plugin::init(const std::string &config, std::string &errstr) tables_in.add_table = sinsp_plugin::table_api_add_table; in.tables = &tables_in; } - ss_plugin_t *state = m_handle->api.init(&in, &rc); - if (state != NULL) - { + ss_plugin_t* state = m_handle->api.init(&in, &rc); + if(state != NULL) { // Plugins can return a state even if the result code is // SS_PLUGIN_FAILURE, which can be useful to set an init // error that can later be retrieved through get_last_error(). @@ -210,24 +193,25 @@ bool sinsp_plugin::init(const std::string &config, std::string &errstr) } m_inited = true; - if (rc != SS_PLUGIN_SUCCESS) - { + if(rc != SS_PLUGIN_SUCCESS) { errstr = "could not initialize plugin: " + get_last_error(); return false; } // resolve post-init event code filters - if (m_caps & CAP_EXTRACTION) - { - /* Here we populate the `m_extract_event_codes` for the plugin, while `m_extract_event_sources` is already populated in the plugin_init */ + if(m_caps & CAP_EXTRACTION) { + /* Here we populate the `m_extract_event_codes` for the plugin, while + * `m_extract_event_sources` is already populated in the plugin_init */ resolve_dylib_compatible_codes(m_handle->api.get_extract_event_types, - m_extract_event_sources, m_extract_event_codes); + m_extract_event_sources, + m_extract_event_codes); } - if (m_caps & CAP_PARSING) - { - /* Here we populate the `m_parse_event_codes` for the plugin, while `m_parse_event_sources` is already populated in the plugin_init */ + if(m_caps & CAP_PARSING) { + /* Here we populate the `m_parse_event_codes` for the plugin, while `m_parse_event_sources` + * is already populated in the plugin_init */ resolve_dylib_compatible_codes(m_handle->api.get_parse_event_types, - m_parse_event_sources, m_parse_event_codes); + m_parse_event_sources, + m_parse_event_codes); } // do some defensive garbage collection @@ -237,213 +221,177 @@ bool sinsp_plugin::init(const std::string &config, std::string &errstr) return true; } -void sinsp_plugin::destroy() -{ +void sinsp_plugin::destroy() { m_inited = false; - if(m_state && m_handle->api.destroy) - { + if(m_state && m_handle->api.destroy) { m_handle->api.destroy(m_state); m_state = NULL; } } -std::string sinsp_plugin::get_last_error() const -{ - if (!m_inited) - { +std::string sinsp_plugin::get_last_error() const { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } std::string ret; - if(m_state) - { + if(m_state) { ret = str_from_alloc_charbuf(m_handle->api.get_last_error(m_state)); - } - else - { + } else { ret = "plugin handle or 'get_last_error' function not defined"; } return ret; } -void sinsp_plugin::resolve_dylib_field_arg(Json::Value root, filtercheck_field_info &tf) -{ - if (root.isNull()) - { +void sinsp_plugin::resolve_dylib_field_arg(Json::Value root, filtercheck_field_info& tf) { + if(root.isNull()) { return; } - const Json::Value &isRequired = root.get("isRequired", Json::Value::null); - if (!isRequired.isNull()) - { - if (!isRequired.isBool()) - { - throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + " isRequired property is not boolean"); + const Json::Value& isRequired = root.get("isRequired", Json::Value::null); + if(!isRequired.isNull()) { + if(!isRequired.isBool()) { + throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + + " isRequired property is not boolean"); } - if (isRequired.asBool() == true) - { + if(isRequired.asBool() == true) { // All the extra casting is because this is the one flags value // that is strongly typed and not just an int. - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_ARG_REQUIRED); + tf.m_flags = (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags::EPF_ARG_REQUIRED); } } - const Json::Value &isIndex = root.get("isIndex", Json::Value::null); - if (!isIndex.isNull()) - { - if (!isIndex.isBool()) - { - throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + " isIndex property is not boolean"); + const Json::Value& isIndex = root.get("isIndex", Json::Value::null); + if(!isIndex.isNull()) { + if(!isIndex.isBool()) { + throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + + " isIndex property is not boolean"); } - if (isIndex.asBool() == true) - { + if(isIndex.asBool() == true) { // We set `EPF_ARG_ALLOWED` implicitly. - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_ARG_INDEX); - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_ARG_ALLOWED); + tf.m_flags = (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags::EPF_ARG_INDEX); + tf.m_flags = (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags::EPF_ARG_ALLOWED); } } - const Json::Value &isKey = root.get("isKey", Json::Value::null); - if (!isKey.isNull()) - { - if (!isKey.isBool()) - { - throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + " isKey property is not boolean"); + const Json::Value& isKey = root.get("isKey", Json::Value::null); + if(!isKey.isNull()) { + if(!isKey.isBool()) { + throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + + " isKey property is not boolean"); } - if (isKey.asBool() == true) - { + if(isKey.asBool() == true) { // We set `EPF_ARG_ALLOWED` implicitly. - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_ARG_KEY); - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_ARG_ALLOWED); + tf.m_flags = (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags::EPF_ARG_KEY); + tf.m_flags = (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags::EPF_ARG_ALLOWED); } } - if((tf.m_flags & filtercheck_field_flags::EPF_ARG_REQUIRED) - && !(tf.m_flags & filtercheck_field_flags::EPF_ARG_INDEX - || tf.m_flags & filtercheck_field_flags::EPF_ARG_KEY)) - { - throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + " arg has isRequired true, but none of isKey nor isIndex is true"); + if((tf.m_flags & filtercheck_field_flags::EPF_ARG_REQUIRED) && + !(tf.m_flags & filtercheck_field_flags::EPF_ARG_INDEX || + tf.m_flags & filtercheck_field_flags::EPF_ARG_KEY)) { + throw sinsp_exception(string("error in plugin ") + m_name + ": field " + tf.m_name + + " arg has isRequired true, but none of isKey nor isIndex is true"); } return; } // this logic is shared between the field extraction and event parsing caps -void sinsp_plugin::resolve_dylib_compatible_codes( - uint16_t *(*get_codes)(uint32_t*,ss_plugin_t*), - const std::unordered_set& sources, - libsinsp::events::set& codes) -{ +void sinsp_plugin::resolve_dylib_compatible_codes(uint16_t* (*get_codes)(uint32_t*, ss_plugin_t*), + const std::unordered_set& sources, + libsinsp::events::set& codes) { codes.clear(); - if (get_codes != NULL) - { + if(get_codes != NULL) { uint32_t ntypes = 0; auto types = get_codes(&ntypes, m_state); - if (types) - { - for (uint32_t i = 0; i < ntypes; i++) - { - codes.insert((ppm_event_code) types[i]); + if(types) { + for(uint32_t i = 0; i < ntypes; i++) { + codes.insert((ppm_event_code)types[i]); } } } - if (codes.empty()) - { - if (is_source_compatible(sources, sinsp_syscall_event_source_name)) - { + if(codes.empty()) { + if(is_source_compatible(sources, sinsp_syscall_event_source_name)) { codes = libsinsp::events::all_event_set(); - } - else - { + } else { codes.insert(ppm_event_code::PPME_PLUGINEVENT_E); } } } -static void resolve_dylib_json_strlist( - const std::string& plname, - const std::string& symbol, - const char *(*get_list)(), - std::unordered_set& out, - bool allow_empty) -{ +static void resolve_dylib_json_strlist(const std::string& plname, + const std::string& symbol, + const char* (*get_list)(), + std::unordered_set& out, + bool allow_empty) { out.clear(); - if(get_list == NULL) - { + if(get_list == NULL) { return; } std::string jsonstr = str_from_alloc_charbuf(get_list()); - if(jsonstr.empty()) - { - if(allow_empty) - { + if(jsonstr.empty()) { + if(allow_empty) { // Do nothing, we allow an empty json string. return; - } - else - { - throw sinsp_exception("error in plugin " + plname + ": '" - + symbol + "' did not return a json array but it should"); + } else { + throw sinsp_exception("error in plugin " + plname + ": '" + symbol + + "' did not return a json array but it should"); } } Json::Value root; - if (!Json::Reader().parse(jsonstr, root) || root.type() != Json::arrayValue) - { - throw sinsp_exception("error in plugin " + plname + ": '" - + symbol + "' did not return a json array"); - } - for (const auto& j : root) - { - if (!j.isConvertibleTo(Json::stringValue)) - { - throw sinsp_exception("error in plugin " + plname + ": '" - + symbol + "' did not return a json array"); + if(!Json::Reader().parse(jsonstr, root) || root.type() != Json::arrayValue) { + throw sinsp_exception("error in plugin " + plname + ": '" + symbol + + "' did not return a json array"); + } + for(const auto& j : root) { + if(!j.isConvertibleTo(Json::stringValue)) { + throw sinsp_exception("error in plugin " + plname + ": '" + symbol + + "' did not return a json array"); } auto src = j.asString(); - if (!src.empty()) - { + if(!src.empty()) { out.insert(src); } } } // this logic is shared between the field extraction and event parsing caps -void sinsp_plugin::resolve_dylib_compatible_sources( - const std::string& symbol, - const char *(*get_sources)(), - std::unordered_set& sources) -{ +void sinsp_plugin::resolve_dylib_compatible_sources(const std::string& symbol, + const char* (*get_sources)(), + std::unordered_set& sources) { resolve_dylib_json_strlist(name(), symbol, get_sources, sources, true); // A plugin with source capability extracts/parses events // from its own specific source (if no other sources are specified) - if (m_caps & CAP_SOURCING && !m_event_source.empty()) - { + if(m_caps & CAP_SOURCING && !m_event_source.empty()) { sources.insert(m_event_source); } } -bool sinsp_plugin::resolve_dylib_symbols(std::string &errstr) -{ +bool sinsp_plugin::resolve_dylib_symbols(std::string& errstr) { char err[PLUGIN_MAX_ERRLEN]; // Before doing anything else, check the required api version - if (!plugin_check_required_api_version(m_handle, err)) - { + if(!plugin_check_required_api_version(m_handle, err)) { errstr = err; return false; } // check that the API requirements are satisfied // These are the minimum APIs that all plugins should implement - if (!plugin_check_required_symbols(m_handle, err)) - { + if(!plugin_check_required_symbols(m_handle, err)) { errstr = err; return false; } @@ -454,94 +402,88 @@ bool sinsp_plugin::resolve_dylib_symbols(std::string &errstr) m_contact = str_from_alloc_charbuf(m_handle->api.get_contact()); std::string version_str = str_from_alloc_charbuf(m_handle->api.get_version()); m_plugin_version = sinsp_version(version_str); - if(!m_plugin_version.is_valid()) - { + if(!m_plugin_version.is_valid()) { errstr = "plugin provided an invalid version string: '" + version_str + "'"; return false; } - std::string req_api_version_str = str_from_alloc_charbuf(m_handle->api.get_required_api_version()); + std::string req_api_version_str = + str_from_alloc_charbuf(m_handle->api.get_required_api_version()); m_required_api_version = sinsp_version(req_api_version_str); - if(!m_required_api_version.is_valid()) - { - errstr = "plugin provided an invalid required api version string: '" + req_api_version_str + "'"; + if(!m_required_api_version.is_valid()) { + errstr = "plugin provided an invalid required api version string: '" + req_api_version_str + + "'"; return false; } // read capabilities and process their info m_caps = plugin_get_capabilities(m_handle, err); - if (m_caps & CAP_BROKEN) - { + if(m_caps & CAP_BROKEN) { errstr = "broken plugin capabilities: " + std::string(err); return false; } - if (m_caps == CAP_NONE) - { + if(m_caps == CAP_NONE) { errstr = "plugin does not implement any capability"; return false; } - if(m_caps & CAP_SOURCING) - { + if(m_caps & CAP_SOURCING) { /* Default case: no id and no source */ m_id = 0; m_event_source.clear(); - if (m_handle->api.get_id != NULL - && m_handle->api.get_event_source != NULL - && m_handle->api.get_id() != 0) - { + if(m_handle->api.get_id != NULL && m_handle->api.get_event_source != NULL && + m_handle->api.get_id() != 0) { m_id = m_handle->api.get_id(); m_event_source = str_from_alloc_charbuf(m_handle->api.get_event_source()); - if (m_event_source == sinsp_syscall_event_source_name) - { - errstr = "plugin can't implement the reserved event source '" + m_event_source + "'"; + if(m_event_source == sinsp_syscall_event_source_name) { + errstr = + "plugin can't implement the reserved event source '" + m_event_source + "'"; return false; } } } - if(m_caps & CAP_EXTRACTION) - { + if(m_caps & CAP_EXTRACTION) { // // If filter fields are exported by the plugin, get the json from get_fields(), // parse it, create our list of fields, and create a filtercheck from the fields. // - const char *sfields = m_handle->api.get_fields(); - if (sfields == NULL) { - throw sinsp_exception( - string("error in plugin ") + name() + ": get_fields returned a null string"); + const char* sfields = m_handle->api.get_fields(); + if(sfields == NULL) { + throw sinsp_exception(string("error in plugin ") + name() + + ": get_fields returned a null string"); } string json(sfields); Json::Value root; - if (Json::Reader().parse(json, root) == false || root.type() != Json::arrayValue) { - throw sinsp_exception( - string("error in plugin ") + name() + ": get_fields returned an invalid JSON"); + if(Json::Reader().parse(json, root) == false || root.type() != Json::arrayValue) { + throw sinsp_exception(string("error in plugin ") + name() + + ": get_fields returned an invalid JSON"); } m_fields.clear(); - for (Json::Value::ArrayIndex j = 0; j < root.size(); j++) { + for(Json::Value::ArrayIndex j = 0; j < root.size(); j++) { filtercheck_field_info tf; tf.m_flags = EPF_NONE; - const Json::Value &jvtype = root[j]["type"]; + const Json::Value& jvtype = root[j]["type"]; string ftype = jvtype.asString(); - if (ftype == "") { - throw sinsp_exception( - string("error in plugin ") + name() + ": field JSON entry has no type"); + if(ftype == "") { + throw sinsp_exception(string("error in plugin ") + name() + + ": field JSON entry has no type"); } - const Json::Value &jvname = root[j]["name"]; + const Json::Value& jvname = root[j]["name"]; string fname = jvname.asString(); - if (fname == "") { - throw sinsp_exception( - string("error in plugin ") + name() + ": field JSON entry has no name"); + if(fname == "") { + throw sinsp_exception(string("error in plugin ") + name() + + ": field JSON entry has no name"); } - const Json::Value &jvdisplay = root[j]["display"]; + const Json::Value& jvdisplay = root[j]["display"]; string fdisplay = jvdisplay.asString(); - const Json::Value &jvdesc = root[j]["desc"]; + const Json::Value& jvdesc = root[j]["desc"]; string fdesc = jvdesc.asString(); - if (fdesc == "") { - throw sinsp_exception( - string("error in plugin ") + name() + ": field JSON entry has no desc"); + if(fdesc == "") { + throw sinsp_exception(string("error in plugin ") + name() + + ": field JSON entry has no desc"); } tf.m_name = fname; @@ -551,50 +493,55 @@ bool sinsp_plugin::resolve_dylib_symbols(std::string &errstr) if(s_pt_lut.find(ftype) != s_pt_lut.end()) { tf.m_type = s_pt_lut.at(ftype); } else { - throw sinsp_exception( - string("error in plugin ") + name() + ": invalid field type " + ftype); + throw sinsp_exception(string("error in plugin ") + name() + + ": invalid field type " + ftype); } - const Json::Value &jvIsList = root[j].get("isList", Json::Value::null); - if (!jvIsList.isNull()) { - if (!jvIsList.isBool()) { + const Json::Value& jvIsList = root[j].get("isList", Json::Value::null); + if(!jvIsList.isNull()) { + if(!jvIsList.isBool()) { throw sinsp_exception(string("error in plugin ") + name() + ": field " + fname + " isList property is not boolean "); } - if (jvIsList.asBool()) { - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | - (int) filtercheck_field_flags::EPF_IS_LIST); + if(jvIsList.asBool()) { + tf.m_flags = + (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags::EPF_IS_LIST); } } resolve_dylib_field_arg(root[j].get("arg", Json::Value::null), tf); - const Json::Value &jvProperties = root[j].get("properties", Json::Value::null); - if (!jvProperties.isNull()) { - if (!jvProperties.isArray()) { + const Json::Value& jvProperties = root[j].get("properties", Json::Value::null); + if(!jvProperties.isNull()) { + if(!jvProperties.isArray()) { throw sinsp_exception(string("error in plugin ") + name() + ": field " + fname + " properties property is not array "); } - for (const auto & prop : jvProperties) { - if (!prop.isString()) { - throw sinsp_exception(string("error in plugin ") + name() + ": field " + fname + - " properties value is not string "); + for(const auto& prop : jvProperties) { + if(!prop.isString()) { + throw sinsp_exception(string("error in plugin ") + name() + ": field " + + fname + " properties value is not string "); } - const std::string &str = prop.asString(); - - // "hidden" is used inside and outside libs. "info" and "conversation" are used outside libs. - if (str == "hidden") { - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | - (int) filtercheck_field_flags::EPF_TABLE_ONLY); - } else if (str == "info") { - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | - (int) filtercheck_field_flags::EPF_INFO); - } else if (str == "conversation") { - tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | - (int) filtercheck_field_flags::EPF_CONVERSATION); + const std::string& str = prop.asString(); + + // "hidden" is used inside and outside libs. "info" and "conversation" are used + // outside libs. + if(str == "hidden") { + tf.m_flags = (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags:: + EPF_TABLE_ONLY); + } else if(str == "info") { + tf.m_flags = + (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags::EPF_INFO); + } else if(str == "conversation") { + tf.m_flags = (filtercheck_field_flags)((int)tf.m_flags | + (int)filtercheck_field_flags:: + EPF_CONVERSATION); } } } @@ -603,105 +550,90 @@ bool sinsp_plugin::resolve_dylib_symbols(std::string &errstr) // populate fields info m_fields_info.m_name = name() + string(" (plugin)"); - m_fields_info.m_fields = &m_fields[0]; // we use a vector so this should be safe + m_fields_info.m_fields = &m_fields[0]; // we use a vector so this should be safe m_fields_info.m_nfields = m_fields.size(); m_fields_info.m_flags = filter_check_info::FL_NONE; // This API is not compulsory for the extraction capability resolve_dylib_compatible_sources("get_extract_event_sources", - m_handle->api.get_extract_event_sources, m_extract_event_sources); + m_handle->api.get_extract_event_sources, + m_extract_event_sources); } - if(m_caps & CAP_PARSING) - { + if(m_caps & CAP_PARSING) { resolve_dylib_compatible_sources("get_parse_event_sources", - m_handle->api.get_parse_event_sources, m_parse_event_sources); + m_handle->api.get_parse_event_sources, + m_parse_event_sources); } - if(m_caps & CAP_ASYNC) - { + if(m_caps & CAP_ASYNC) { resolve_dylib_compatible_sources("get_async_event_sources", - m_handle->api.get_async_event_sources, m_async_event_sources); - resolve_dylib_json_strlist(name(), "get_async_events", - m_handle->api.get_async_events, m_async_event_names, false); + m_handle->api.get_async_event_sources, + m_async_event_sources); + resolve_dylib_json_strlist(name(), + "get_async_events", + m_handle->api.get_async_events, + m_async_event_names, + false); } return true; } -std::string sinsp_plugin::get_init_schema(ss_plugin_schema_type& schema_type) const -{ +std::string sinsp_plugin::get_init_schema(ss_plugin_schema_type& schema_type) const { schema_type = SS_PLUGIN_SCHEMA_NONE; - if (m_handle->api.get_init_schema != NULL) - { + if(m_handle->api.get_init_schema != NULL) { return str_from_alloc_charbuf(m_handle->api.get_init_schema(&schema_type)); } return std::string(""); } -const libsinsp::events::set& sinsp_plugin::extract_event_codes() const -{ - if (!m_inited) - { +const libsinsp::events::set& sinsp_plugin::extract_event_codes() const { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } return m_extract_event_codes; } -const libsinsp::events::set& sinsp_plugin::parse_event_codes() const -{ - if (!m_inited) - { +const libsinsp::events::set& sinsp_plugin::parse_event_codes() const { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } return m_parse_event_codes; } -void sinsp_plugin::validate_config(std::string& config) -{ +void sinsp_plugin::validate_config(std::string& config) { ss_plugin_schema_type schema_type; std::string schema = get_init_schema(schema_type); - if (!schema.empty() && schema_type != SS_PLUGIN_SCHEMA_NONE) - { - switch (schema_type) - { - case SS_PLUGIN_SCHEMA_JSON: - validate_config_json_schema(config, schema); - break; - default: - ASSERT(false); - throw sinsp_exception( - string("error in plugin ") - + name() - + ": get_init_schema returned an unknown schema type " - + to_string(schema_type)); + if(!schema.empty() && schema_type != SS_PLUGIN_SCHEMA_NONE) { + switch(schema_type) { + case SS_PLUGIN_SCHEMA_JSON: + validate_config_json_schema(config, schema); + break; + default: + ASSERT(false); + throw sinsp_exception(string("error in plugin ") + name() + + ": get_init_schema returned an unknown schema type " + + to_string(schema_type)); } } } -void sinsp_plugin::validate_config_json_schema(std::string& config, std::string &schema) -{ +void sinsp_plugin::validate_config_json_schema(std::string& config, std::string& schema) { Json::Value schemaJson; - if(!Json::Reader().parse(schema, schemaJson) || schemaJson.type() != Json::objectValue) - { - throw sinsp_exception( - string("error in plugin ") - + name() - + ": get_init_schema did not return a json object"); + if(!Json::Reader().parse(schema, schemaJson) || schemaJson.type() != Json::objectValue) { + throw sinsp_exception(string("error in plugin ") + name() + + ": get_init_schema did not return a json object"); } // stub empty configs to an empty json object - if (config.size() == 0) - { + if(config.size() == 0) { config = "{}"; } Json::Value configJson; - if(!Json::Reader().parse(config, configJson)) - { - throw sinsp_exception( - string("error in plugin ") - + name() - + ": init config is not a valid json"); + if(!Json::Reader().parse(config, configJson)) { + throw sinsp_exception(string("error in plugin ") + name() + + ": init config is not a valid json"); } // validate config with json schema @@ -712,32 +644,23 @@ void sinsp_plugin::validate_config_json_schema(std::string& config, std::string valijson::adapters::JsonCppAdapter configAdapter(configJson); valijson::adapters::JsonCppAdapter schemaAdapter(schemaJson); schemaParser.populateSchema(schemaAdapter, schemaDef); - if (!validator.validate(schemaDef, configAdapter, &validationResults)) - { + if(!validator.validate(schemaDef, configAdapter, &validationResults)) { valijson::ValidationResults::Error error; // report only the top-most error - if (validationResults.popError(error)) - { + if(validationResults.popError(error)) { throw sinsp_exception( - string("error in plugin ") - + name() - + " init config: In " - + std::accumulate(error.context.begin(), error.context.end(), std::string("")) - + ", " - + error.description); + string("error in plugin ") + name() + " init config: In " + + std::accumulate(error.context.begin(), error.context.end(), std::string("")) + + ", " + error.description); } // validation failed with no specific error - throw sinsp_exception( - string("error in plugin ") - + name() - + " init config: failed parsing with provided schema"); + throw sinsp_exception(string("error in plugin ") + name() + + " init config: failed parsing with provided schema"); } } -bool sinsp_plugin::set_config(const std::string& config) -{ - if(!m_inited) - { +bool sinsp_plugin::set_config(const std::string& config) { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } @@ -747,18 +670,17 @@ bool sinsp_plugin::set_config(const std::string& config) ss_plugin_set_config_input input; input.config = conf.c_str(); - if(!m_handle->api.set_config) - { + if(!m_handle->api.set_config) { return false; } return m_handle->api.set_config(m_state, &input) == SS_PLUGIN_SUCCESS; } -static void set_plugin_metric_value(metrics_v2& metric, metrics_v2_value_type type, ss_plugin_metric_value val) -{ - switch (type) - { +static void set_plugin_metric_value(metrics_v2& metric, + metrics_v2_value_type type, + ss_plugin_metric_value val) { + switch(type) { case METRIC_VALUE_TYPE_U32: metric.value.u32 = val.u32; break; @@ -785,29 +707,25 @@ static void set_plugin_metric_value(metrics_v2& metric, metrics_v2_value_type ty } } -std::vector sinsp_plugin::get_metrics() const -{ - if(!m_inited) - { +std::vector sinsp_plugin::get_metrics() const { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } std::vector metrics; uint32_t num_metrics = 0; - if(!m_handle->api.get_metrics) - { + if(!m_handle->api.get_metrics) { return metrics; } - ss_plugin_metric *plugin_metrics = m_handle->api.get_metrics(m_state, &num_metrics); - for (uint32_t i = 0; i < num_metrics; i++) - { - ss_plugin_metric *plugin_metric = plugin_metrics + i; + ss_plugin_metric* plugin_metrics = m_handle->api.get_metrics(m_state, &num_metrics); + for(uint32_t i = 0; i < num_metrics; i++) { + ss_plugin_metric* plugin_metric = plugin_metrics + i; metrics_v2 metric; - - //copy plugin name + + // copy plugin name snprintf(metric.name, METRIC_NAME_MAX, "%s.%s", m_name.c_str(), plugin_metric->name); metric.flags = METRICS_V2_PLUGINS; @@ -822,10 +740,10 @@ std::vector sinsp_plugin::get_metrics() const return metrics; } -thread_pool::routine_id_t sinsp_plugin::subscribe_routine(ss_plugin_routine_fn_t routine_fn, ss_plugin_routine_state_t* routine_state) -{ - if(!m_thread_pool) - { +thread_pool::routine_id_t sinsp_plugin::subscribe_routine( + ss_plugin_routine_fn_t routine_fn, + ss_plugin_routine_state_t* routine_state) { + if(!m_thread_pool) { return reinterpret_cast(nullptr); } @@ -836,41 +754,36 @@ thread_pool::routine_id_t sinsp_plugin::subscribe_routine(ss_plugin_routine_fn_t return m_thread_pool->subscribe(f); } -bool sinsp_plugin::unsubscribe_routine(thread_pool::routine_id_t routine_id) -{ - if(!m_thread_pool || !routine_id) - { +bool sinsp_plugin::unsubscribe_routine(thread_pool::routine_id_t routine_id) { + if(!m_thread_pool || !routine_id) { return false; } return m_thread_pool->unsubscribe(routine_id); } -ss_plugin_routine_t* plugin_subscribe_routine(ss_plugin_owner_t* o, ss_plugin_routine_fn_t r, ss_plugin_routine_state_t* s) -{ +ss_plugin_routine_t* plugin_subscribe_routine(ss_plugin_owner_t* o, + ss_plugin_routine_fn_t r, + ss_plugin_routine_state_t* s) { auto t = static_cast(o); auto res = t->subscribe_routine(r, s); return reinterpret_cast(res); } -ss_plugin_rc plugin_unsubscribe_routine(ss_plugin_owner_t* o, ss_plugin_routine_t* r) -{ +ss_plugin_rc plugin_unsubscribe_routine(ss_plugin_owner_t* o, ss_plugin_routine_t* r) { auto t = static_cast(o); auto id = reinterpret_cast(r); return t->unsubscribe_routine(id) ? SS_PLUGIN_SUCCESS : SS_PLUGIN_FAILURE; } -bool sinsp_plugin::capture_open() -{ - if(!m_inited) - { +bool sinsp_plugin::capture_open() { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } - if(!m_handle->api.capture_open) - { + if(!m_handle->api.capture_open) { return false; } @@ -884,7 +797,7 @@ bool sinsp_plugin::capture_open() ss_plugin_table_reader_vtable table_reader; ss_plugin_table_writer_vtable table_writer; - in.owner = (ss_plugin_owner_t *) this; + in.owner = (ss_plugin_owner_t*)this; in.table_reader_ext = &table_reader_ext; in.table_writer_ext = &table_writer_ext; in.routine = &routine_vtable; @@ -895,15 +808,12 @@ bool sinsp_plugin::capture_open() return m_handle->api.capture_open(m_state, &in) == SS_PLUGIN_SUCCESS; } -bool sinsp_plugin::capture_close() -{ - if(!m_inited) - { +bool sinsp_plugin::capture_close() { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } - if(!m_handle->api.capture_close) - { + if(!m_handle->api.capture_close) { return false; } @@ -917,7 +827,7 @@ bool sinsp_plugin::capture_close() ss_plugin_table_reader_vtable table_reader; ss_plugin_table_writer_vtable table_writer; - in.owner = (ss_plugin_owner_t *) this; + in.owner = (ss_plugin_owner_t*)this; in.table_reader_ext = &table_reader_ext; in.table_writer_ext = &table_writer_ext; in.routine = &routine_vtable; @@ -930,16 +840,14 @@ bool sinsp_plugin::capture_close() /** Event Source CAP **/ -scap_source_plugin& sinsp_plugin::as_scap_source() -{ - if (!m_inited) - { +scap_source_plugin& sinsp_plugin::as_scap_source() { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } - if (!(caps() & CAP_SOURCING)) - { - throw sinsp_exception("can't create scap_source_plugin from a plugin without CAP_SOURCING capability."); + if(!(caps() & CAP_SOURCING)) { + throw sinsp_exception( + "can't create scap_source_plugin from a plugin without CAP_SOURCING capability."); } m_scap_source_plugin.state = m_state; @@ -952,105 +860,90 @@ scap_source_plugin& sinsp_plugin::as_scap_source() return m_scap_source_plugin; } -std::string sinsp_plugin::get_progress(uint32_t &progress_pct) const -{ - if (!m_inited) - { +std::string sinsp_plugin::get_progress(uint32_t& progress_pct) const { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } std::string ret; progress_pct = 0; - if(!m_handle->api.get_progress || !m_scap_source_plugin.handle) - { + if(!m_handle->api.get_progress || !m_scap_source_plugin.handle) { return ret; } uint32_t ppct; - ret = str_from_alloc_charbuf(m_handle->api.get_progress(m_state, m_scap_source_plugin.handle, &ppct)); + ret = str_from_alloc_charbuf( + m_handle->api.get_progress(m_state, m_scap_source_plugin.handle, &ppct)); progress_pct = ppct; return ret; } -std::string sinsp_plugin::event_to_string(sinsp_evt* evt) const -{ - if (!m_inited) - { +std::string sinsp_plugin::event_to_string(sinsp_evt* evt) const { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } - if (evt->get_type() != PPME_PLUGINEVENT_E || evt->get_param(0)->as() != m_id) - { + if(evt->get_type() != PPME_PLUGINEVENT_E || evt->get_param(0)->as() != m_id) { throw sinsp_exception("can't format unknown non-plugin event to string"); } string ret = ""; auto datalen = evt->get_param(1)->m_len; - auto data = (const uint8_t *) evt->get_param(1)->m_val; - if (m_state && m_handle->api.event_to_string) - { + auto data = (const uint8_t*)evt->get_param(1)->m_val; + if(m_state && m_handle->api.event_to_string) { ss_plugin_event_input input; - input.evt = (const ss_plugin_event*) evt->get_scap_evt(); + input.evt = (const ss_plugin_event*)evt->get_scap_evt(); input.evtnum = evt->get_num(); input.evtsrc = evt->get_source_name(); ret = str_from_alloc_charbuf(m_handle->api.event_to_string(m_state, &input)); } - if (ret.empty()) - { + if(ret.empty()) { ret += "datalen="; ret += std::to_string(datalen); ret += " data="; - for (size_t i = 0; i < std::min(datalen, uint32_t(50)); ++i) - { - if (!std::isprint(data[i])) - { + for(size_t i = 0; i < std::min(datalen, uint32_t(50)); ++i) { + if(!std::isprint(data[i])) { ret += ""; return ret; } } - ret.append((char*) data, std::min(datalen, uint32_t(50))); - if (datalen > 50) - { + ret.append((char*)data, std::min(datalen, uint32_t(50))); + if(datalen > 50) { ret += "..."; } } return ret; } -std::vector sinsp_plugin::list_open_params() const -{ - if (!m_inited) - { +std::vector sinsp_plugin::list_open_params() const { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } std::vector list; - if(m_state && m_handle->api.list_open_params) - { + if(m_state && m_handle->api.list_open_params) { ss_plugin_rc rc; string jsonString = str_from_alloc_charbuf(m_handle->api.list_open_params(m_state, &rc)); - if (rc != SS_PLUGIN_SUCCESS) - { - throw sinsp_exception(string("error in plugin ") + name() + ": list_open_params has error " + get_last_error()); + if(rc != SS_PLUGIN_SUCCESS) { + throw sinsp_exception(string("error in plugin ") + name() + + ": list_open_params has error " + get_last_error()); } - if (jsonString.size() > 0) - { + if(jsonString.size() > 0) { Json::Value root; - if(Json::Reader().parse(jsonString, root) == false || root.type() != Json::arrayValue) - { - throw sinsp_exception(string("error in plugin ") + name() + ": list_open_params returned a non-array JSON"); + if(Json::Reader().parse(jsonString, root) == false || root.type() != Json::arrayValue) { + throw sinsp_exception(string("error in plugin ") + name() + + ": list_open_params returned a non-array JSON"); } - for(Json::Value::ArrayIndex i = 0; i < root.size(); i++) - { + for(Json::Value::ArrayIndex i = 0; i < root.size(); i++) { open_param param; param.value = root[i]["value"].asString(); - if(param.value == "") - { - throw sinsp_exception(string("error in plugin ") + name() + ": list_open_params has entry with no value"); + if(param.value == "") { + throw sinsp_exception(string("error in plugin ") + name() + + ": list_open_params has entry with no value"); } param.desc = root[i]["desc"].asString(); param.separator = root[i]["separator"].asString(); @@ -1066,20 +959,20 @@ std::vector sinsp_plugin::list_open_params() const /** Field Extraction CAP **/ -std::unique_ptr sinsp_plugin::new_filtercheck(const std::shared_ptr& plugin) -{ +std::unique_ptr sinsp_plugin::new_filtercheck( + const std::shared_ptr& plugin) { return std::make_unique(plugin); } -bool sinsp_plugin::extract_fields(sinsp_evt* evt, uint32_t num_fields, ss_plugin_extract_field *fields) -{ - if (!m_inited) - { +bool sinsp_plugin::extract_fields(sinsp_evt* evt, + uint32_t num_fields, + ss_plugin_extract_field* fields) { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } ss_plugin_event_input ev; - ev.evt = (const ss_plugin_event*) evt->get_scap_evt(); + ev.evt = (const ss_plugin_event*)evt->get_scap_evt(); ev.evtnum = evt->get_num(); ev.evtsrc = evt->get_source_name(); @@ -1087,7 +980,7 @@ bool sinsp_plugin::extract_fields(sinsp_evt* evt, uint32_t num_fields, ss_plugin ss_plugin_table_reader_vtable_ext table_reader_ext; in.num_fields = num_fields; in.fields = fields; - in.owner = (ss_plugin_owner_t *) this; + in.owner = (ss_plugin_owner_t*)this; in.get_owner_last_error = sinsp_plugin::get_owner_last_error; in.table_reader_ext = &table_reader_ext; sinsp_plugin::table_read_api(in.table_reader, table_reader_ext); @@ -1104,22 +997,20 @@ bool sinsp_plugin::extract_fields(sinsp_evt* evt, uint32_t num_fields, ss_plugin /** Event Parsing CAP **/ -bool sinsp_plugin::parse_event(sinsp_evt* evt) -{ - if (!m_inited) - { +bool sinsp_plugin::parse_event(sinsp_evt* evt) { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } ss_plugin_event_input ev; - ev.evt = (const ss_plugin_event*) evt->get_scap_evt(); + ev.evt = (const ss_plugin_event*)evt->get_scap_evt(); ev.evtnum = evt->get_num(); ev.evtsrc = evt->get_source_name(); ss_plugin_event_parse_input in; ss_plugin_table_reader_vtable_ext table_reader_ext; ss_plugin_table_writer_vtable_ext table_writer_ext; - in.owner = (ss_plugin_owner_t *) this; + in.owner = (ss_plugin_owner_t*)this; in.get_owner_last_error = sinsp_plugin::get_owner_last_error; in.table_reader_ext = &table_reader_ext; in.table_writer_ext = &table_writer_ext; @@ -1138,79 +1029,67 @@ bool sinsp_plugin::parse_event(sinsp_evt* evt) /** Async Events CAP **/ -ss_plugin_rc sinsp_plugin::handle_plugin_async_event(ss_plugin_owner_t *o, const ss_plugin_event* e, char* err) -{ +ss_plugin_rc sinsp_plugin::handle_plugin_async_event(ss_plugin_owner_t* o, + const ss_plugin_event* e, + char* err) { // note: this function can be invoked from different plugin threads, // so we need to make sure that every variable we read is either constant // during the lifetime of those threads, or that it is atomic. auto p = static_cast(o); auto handler = p->m_async_evt_handler.load(); - if (!(p->caps() & CAP_ASYNC)) - { - if (err) - { - strlcpy(err, "plugin without async events cap used as async handler", PLUGIN_MAX_ERRLEN); + if(!(p->caps() & CAP_ASYNC)) { + if(err) { + strlcpy(err, + "plugin without async events cap used as async handler", + PLUGIN_MAX_ERRLEN); } return SS_PLUGIN_FAILURE; } - if (!handler) - { - if (err) - { + if(!handler) { + if(err) { auto e = "async event sent with NULL handler: " + p->name(); strlcpy(err, e.c_str(), PLUGIN_MAX_ERRLEN); } return SS_PLUGIN_FAILURE; } - if (e->type != PPME_ASYNCEVENT_E || e->nparams != 3) - { - if (err) - { + if(e->type != PPME_ASYNCEVENT_E || e->nparams != 3) { + if(err) { auto e = "malformed async event produced by plugin: " + p->name(); strlcpy(err, e.c_str(), PLUGIN_MAX_ERRLEN); } return SS_PLUGIN_FAILURE; } - auto name = (const char*) ((uint8_t*) e + sizeof(ss_plugin_event) + 4+4+4+4); - if (p->async_event_names().find(name) == p->async_event_names().end()) - { - if (err) - { - auto e = "incompatible async event '" + std::string(name) - + "' produced by plugin: " + p->name(); + auto name = (const char*)((uint8_t*)e + sizeof(ss_plugin_event) + 4 + 4 + 4 + 4); + if(p->async_event_names().find(name) == p->async_event_names().end()) { + if(err) { + auto e = "incompatible async event '" + std::string(name) + + "' produced by plugin: " + p->name(); strlcpy(err, e.c_str(), PLUGIN_MAX_ERRLEN); } return SS_PLUGIN_FAILURE; } - try - { + try { auto evt = std::make_unique(); ASSERT(evt->get_scap_evt_storage() == nullptr); evt->set_scap_evt_storage(new char[e->len]); memcpy(evt->get_scap_evt_storage(), e, e->len); evt->set_cpuid(0); evt->set_num(0); - evt->set_scap_evt((scap_evt *) evt->get_scap_evt_storage()); + evt->set_scap_evt((scap_evt*)evt->get_scap_evt_storage()); evt->init(); // note: plugin ID and timestamp will be set by the inspector (*handler)(*p, std::move(evt)); - } - catch (const std::exception& _e) - { - if (err) - { + } catch(const std::exception& _e) { + if(err) { strlcpy(err, _e.what(), PLUGIN_MAX_ERRLEN); } return SS_PLUGIN_FAILURE; - } - catch (...) - { - if (err) - { + } catch(...) { + if(err) { strlcpy(err, "unknwon error in pushing async event", PLUGIN_MAX_ERRLEN); } return SS_PLUGIN_FAILURE; @@ -1219,10 +1098,8 @@ ss_plugin_rc sinsp_plugin::handle_plugin_async_event(ss_plugin_owner_t *o, const return SS_PLUGIN_SUCCESS; } -bool sinsp_plugin::set_async_event_handler(async_event_handler_t handler) -{ - if (!m_inited) - { +bool sinsp_plugin::set_async_event_handler(async_event_handler_t handler) { + if(!m_inited) { throw sinsp_exception(std::string(s_not_init_err) + ": " + m_name); } @@ -1251,10 +1128,8 @@ bool sinsp_plugin::set_async_event_handler(async_event_handler_t handler) auto cur_handler = m_async_evt_handler.load(); auto new_handler = (handler != nullptr) ? new async_event_handler_t(handler) : nullptr; - if (new_handler != nullptr) - { - if (cur_handler != nullptr) - { + if(new_handler != nullptr) { + if(cur_handler != nullptr) { delete new_handler; throw sinsp_exception("must reset the async event handler before setting a new one"); } @@ -1264,20 +1139,16 @@ bool sinsp_plugin::set_async_event_handler(async_event_handler_t handler) auto callback = (handler != nullptr) ? sinsp_plugin::handle_plugin_async_event : NULL; auto rc = m_handle->api.set_async_event_handler(m_state, this, callback); - if (cur_handler == nullptr && new_handler != nullptr) - { - if (rc != SS_PLUGIN_SUCCESS) - { + if(cur_handler == nullptr && new_handler != nullptr) { + if(rc != SS_PLUGIN_SUCCESS) { // new handler rejected, restore current one delete new_handler; m_async_evt_handler.store(cur_handler); } } - if (cur_handler != nullptr && new_handler == nullptr) - { - if (rc == SS_PLUGIN_SUCCESS) - { + if(cur_handler != nullptr && new_handler == nullptr) { + if(rc == SS_PLUGIN_SUCCESS) { // new handler accepted, delete current one delete cur_handler; m_async_evt_handler.store(new_handler); diff --git a/userspace/libsinsp/plugin.h b/userspace/libsinsp/plugin.h old mode 100755 new mode 100644 index 9976b3f957..0ab97de21f --- a/userspace/libsinsp/plugin.h +++ b/userspace/libsinsp/plugin.h @@ -40,17 +40,15 @@ limitations under the License. /** * @brief An object-oriented representation of a plugin. */ -class sinsp_plugin -{ +class sinsp_plugin { public: - struct open_param - { + struct open_param { open_param() = default; ~open_param() = default; open_param(open_param&&) = default; - open_param& operator = (open_param&&) = default; + open_param& operator=(open_param&&) = default; open_param(const open_param& s) = default; - open_param& operator = (const open_param& s) = default; + open_param& operator=(const open_param& s) = default; std::string value; std::string desc; @@ -62,20 +60,20 @@ class sinsp_plugin * On error, the shared_ptr will == nullptr and errstr is set with an error. */ static std::shared_ptr create( - const std::string& path, - const std::shared_ptr& treg, - const std::shared_ptr& tpool, - std::string& errstr); + const std::string& path, + const std::shared_ptr& treg, + const std::shared_ptr& tpool, + std::string& errstr); /** * @brief Create a plugin from the provided api vtable. * On error, the shared_ptr will == nullptr and errstr is set with an error. */ static std::shared_ptr create( - const plugin_api* api, - const std::shared_ptr& treg, - const std::shared_ptr& tpool, - std::string& errstr); + const plugin_api* api, + const std::shared_ptr& treg, + const std::shared_ptr& tpool, + std::string& errstr); /** * @brief Return whether a filesystem dynamic library object is loaded. @@ -88,88 +86,69 @@ class sinsp_plugin * * todo(jasondellaluce): make this return a unique_ptr */ - static std::unique_ptr new_filtercheck(const std::shared_ptr& plugin); + static std::unique_ptr new_filtercheck( + const std::shared_ptr& plugin); /** * @brief Returns true if the source is compatible with the given set * of sources. */ - static inline bool is_source_compatible( - const std::unordered_set& sources, const std::string& source) - { + static inline bool is_source_compatible(const std::unordered_set& sources, + const std::string& source) { return sources.empty() || sources.find(source) != sources.end(); } - sinsp_plugin(plugin_handle_t* - handle, - const std::shared_ptr& treg, - const std::shared_ptr& tpool): - m_caps(CAP_NONE), - m_name(), - m_description(), - m_contact(), - m_plugin_version(), - m_required_api_version(), - m_id(0), - m_event_source(), - m_inited(false), - m_state(nullptr), - m_handle(handle), - m_last_owner_err(), - m_scap_source_plugin(), - m_fields_info(), - m_fields(), - m_extract_event_sources(), - m_extract_event_codes(), - m_parse_event_sources(), - m_parse_event_codes(), - m_async_event_sources(), - m_async_event_names(), - m_async_evt_handler(nullptr), - m_table_registry(treg), - m_table_infos(), - m_owned_tables(), - m_accessed_tables(), - m_accessed_entries(), - m_accessed_table_fields(), - m_ephemeral_tables(), - m_ephemeral_tables_clear(false), - m_accessed_entries_clear(false), - m_thread_pool(tpool) { } + sinsp_plugin(plugin_handle_t* handle, + const std::shared_ptr& treg, + const std::shared_ptr& tpool): + m_caps(CAP_NONE), + m_name(), + m_description(), + m_contact(), + m_plugin_version(), + m_required_api_version(), + m_id(0), + m_event_source(), + m_inited(false), + m_state(nullptr), + m_handle(handle), + m_last_owner_err(), + m_scap_source_plugin(), + m_fields_info(), + m_fields(), + m_extract_event_sources(), + m_extract_event_codes(), + m_parse_event_sources(), + m_parse_event_codes(), + m_async_event_sources(), + m_async_event_names(), + m_async_evt_handler(nullptr), + m_table_registry(treg), + m_table_infos(), + m_owned_tables(), + m_accessed_tables(), + m_accessed_entries(), + m_accessed_table_fields(), + m_ephemeral_tables(), + m_ephemeral_tables_clear(false), + m_accessed_entries_clear(false), + m_thread_pool(tpool) {} virtual ~sinsp_plugin(); sinsp_plugin(const sinsp_plugin& s) = delete; - sinsp_plugin& operator = (const sinsp_plugin& s) = delete; + sinsp_plugin& operator=(const sinsp_plugin& s) = delete; /** Common API **/ - inline plugin_caps_t caps() const - { - return m_caps; - } + inline plugin_caps_t caps() const { return m_caps; } - inline const std::string& name() const - { - return m_name; - } + inline const std::string& name() const { return m_name; } - inline const std::string& description() const - { - return m_description; - } + inline const std::string& description() const { return m_description; } - inline const std::string& contact() const - { - return m_contact; - } + inline const std::string& contact() const { return m_contact; } - inline const sinsp_version& plugin_version() const - { - return m_plugin_version; - } + inline const sinsp_version& plugin_version() const { return m_plugin_version; } - inline const sinsp_version& required_api_version() const - { - return m_required_api_version; - } + inline const sinsp_version& required_api_version() const { return m_required_api_version; } bool init(const std::string& config, std::string& errstr); void destroy(); @@ -179,19 +158,14 @@ class sinsp_plugin std::vector get_metrics() const; bool capture_open(); bool capture_close(); - thread_pool::routine_id_t subscribe_routine(ss_plugin_routine_fn_t routine_fn, ss_plugin_routine_state_t* routine_state); + thread_pool::routine_id_t subscribe_routine(ss_plugin_routine_fn_t routine_fn, + ss_plugin_routine_state_t* routine_state); bool unsubscribe_routine(thread_pool::routine_id_t routine_id); /** Event Sourcing **/ - inline uint32_t id() const - { - return m_id; - } + inline uint32_t id() const { return m_id; } - inline const std::string& event_source() const - { - return m_event_source; - } + inline const std::string& event_source() const { return m_event_source; } scap_source_plugin& as_scap_source(); std::string get_progress(uint32_t& progress_pct) const; @@ -199,28 +173,20 @@ class sinsp_plugin std::vector list_open_params() const; /** Field Extraction **/ - inline const std::unordered_set& extract_event_sources() const - { + inline const std::unordered_set& extract_event_sources() const { return m_extract_event_sources; } const libsinsp::events::set& extract_event_codes() const; - inline const filter_check_info* fields_info() const - { - return &m_fields_info; - } + inline const filter_check_info* fields_info() const { return &m_fields_info; } - inline const std::vector& fields() const - { - return m_fields; - } + inline const std::vector& fields() const { return m_fields; } - bool extract_fields(sinsp_evt* evt, uint32_t num_fields, ss_plugin_extract_field *fields); + bool extract_fields(sinsp_evt* evt, uint32_t num_fields, ss_plugin_extract_field* fields); /** Event Parsing **/ - inline const std::unordered_set& parse_event_sources() const - { + inline const std::unordered_set& parse_event_sources() const { return m_parse_event_sources; } @@ -229,23 +195,22 @@ class sinsp_plugin bool parse_event(sinsp_evt* evt); /** Async Events **/ - inline const std::unordered_set& async_event_sources() const - { + inline const std::unordered_set& async_event_sources() const { return m_async_event_sources; } - inline const std::unordered_set& async_event_names() const - { + inline const std::unordered_set& async_event_names() const { return m_async_event_names; } - using async_event_handler_t = std::function)>; + using async_event_handler_t = + std::function)>; bool set_async_event_handler(async_event_handler_t handler); -// note(jasondellaluce): we set these as protected in order to allow unit -// testing mocking these values, without having to declare their accessors -// as virtual (thus avoiding performance loss in some hot paths). + // note(jasondellaluce): we set these as protected in order to allow unit + // testing mocking these values, without having to declare their accessors + // as virtual (thus avoiding performance loss in some hot paths). protected: plugin_caps_t m_caps; std::string m_name; @@ -281,30 +246,30 @@ class sinsp_plugin /** Async Events state and helpers **/ std::unordered_set m_async_event_sources; std::unordered_set m_async_event_names; - std::atomic m_async_evt_handler; // note: we don't have thread-safe smart pointers - static ss_plugin_rc handle_plugin_async_event(ss_plugin_owner_t *o, const ss_plugin_event* evt, char* err); + std::atomic + m_async_evt_handler; // note: we don't have thread-safe smart pointers + static ss_plugin_rc handle_plugin_async_event(ss_plugin_owner_t* o, + const ss_plugin_event* evt, + char* err); /** Generic helpers **/ void validate_config(std::string& config); bool resolve_dylib_symbols(std::string& errstr); void resolve_dylib_field_arg(Json::Value root, filtercheck_field_info& tf); - void resolve_dylib_compatible_sources( - const std::string& symbol, - const char *(*get_sources)(), - std::unordered_set& sources); - void resolve_dylib_compatible_codes( - uint16_t *(*get_codes)(uint32_t* numtypes,ss_plugin_t* s), - const std::unordered_set& sources, - libsinsp::events::set& codes); + void resolve_dylib_compatible_sources(const std::string& symbol, + const char* (*get_sources)(), + std::unordered_set& sources); + void resolve_dylib_compatible_codes(uint16_t* (*get_codes)(uint32_t* numtypes, ss_plugin_t* s), + const std::unordered_set& sources, + libsinsp::events::set& codes); void validate_config_json_schema(std::string& config, std::string& schema); static const char* get_owner_last_error(ss_plugin_owner_t* o); /** Table API state and helpers **/ - // wraps instances of libsinsp::state::XXX_struct::field_accessor and + // wraps instances of libsinsp::state::XXX_struct::field_accessor and // help making them comply to the plugin API state tables definitions - struct sinsp_field_accessor_wrapper - { + struct sinsp_field_accessor_wrapper { // depending on the value of `dynamic`, one of: // - libsinsp::state::static_struct::field_accessor // - libsinsp::state::dynamic_struct::field_accessor @@ -316,20 +281,21 @@ class sinsp_plugin inline sinsp_field_accessor_wrapper() = default; ~sinsp_field_accessor_wrapper(); inline sinsp_field_accessor_wrapper(const sinsp_field_accessor_wrapper& s) = delete; - inline sinsp_field_accessor_wrapper& operator = (const sinsp_field_accessor_wrapper& s) = delete; + inline sinsp_field_accessor_wrapper& operator=(const sinsp_field_accessor_wrapper& s) = + delete; inline sinsp_field_accessor_wrapper(sinsp_field_accessor_wrapper&& s); - inline sinsp_field_accessor_wrapper& operator = (sinsp_field_accessor_wrapper&& s); + inline sinsp_field_accessor_wrapper& operator=(sinsp_field_accessor_wrapper&& s); }; // wraps instances of libsinsp::state::table and help making them comply // to the plugin API state tables definitions - struct sinsp_table_wrapper - { + struct sinsp_table_wrapper { ss_plugin_state_type m_key_type = ss_plugin_state_type::SS_PLUGIN_ST_INT8; sinsp_plugin* m_owner_plugin = nullptr; libsinsp::state::base_table* m_table = nullptr; std::vector m_field_list; - std::unordered_map m_field_accessors; + std::unordered_map + m_field_accessors; // used to optimize cases where this wraps a plugin-defined table directly const sinsp_plugin* m_table_plugin_owner = nullptr; @@ -338,35 +304,54 @@ class sinsp_plugin inline sinsp_table_wrapper() = default; virtual ~sinsp_table_wrapper() = default; inline sinsp_table_wrapper(const sinsp_table_wrapper& s) = delete; - inline sinsp_table_wrapper& operator = (const sinsp_table_wrapper& s) = delete; + inline sinsp_table_wrapper& operator=(const sinsp_table_wrapper& s) = delete; void unset(); bool is_set() const; - template void set(sinsp_plugin* p, libsinsp::state::table* t); + template + void set(sinsp_plugin* p, libsinsp::state::table* t); // static functions, will be used to populate vtable functions where // ss_plugin_table_t* will be represented by a sinsp_table_wrapper* - static inline const ss_plugin_table_fieldinfo* list_fields(ss_plugin_table_t* _t, uint32_t* nfields); - static inline ss_plugin_table_field_t* get_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type); - static inline ss_plugin_table_field_t* add_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type); + static inline const ss_plugin_table_fieldinfo* list_fields(ss_plugin_table_t* _t, + uint32_t* nfields); + static inline ss_plugin_table_field_t* get_field(ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type); + static inline ss_plugin_table_field_t* add_field(ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type); static inline const char* get_name(ss_plugin_table_t* _t); static inline uint64_t get_size(ss_plugin_table_t* _t); - static inline ss_plugin_table_entry_t* get_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key); - static inline ss_plugin_rc read_entry_field(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e, const ss_plugin_table_field_t* f, ss_plugin_state_data* out);; + static inline ss_plugin_table_entry_t* get_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key); + static inline ss_plugin_rc read_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* _e, + const ss_plugin_table_field_t* f, + ss_plugin_state_data* out); + ; static inline void release_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e); - static inline ss_plugin_bool iterate_entries(ss_plugin_table_t* _t, ss_plugin_table_iterator_func_t it, ss_plugin_table_iterator_state_t* s); + static inline ss_plugin_bool iterate_entries(ss_plugin_table_t* _t, + ss_plugin_table_iterator_func_t it, + ss_plugin_table_iterator_state_t* s); static inline ss_plugin_rc clear(ss_plugin_table_t* _t); - static inline ss_plugin_rc erase_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key); + static inline ss_plugin_rc erase_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key); static inline ss_plugin_table_entry_t* create_table_entry(ss_plugin_table_t* _t); static inline void destroy_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e); - static inline ss_plugin_table_entry_t* add_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key, ss_plugin_table_entry_t* _e); - static inline ss_plugin_rc write_entry_field(ss_plugin_table_t* _t, ss_plugin_table_entry_t* e, const ss_plugin_table_field_t* f, const ss_plugin_state_data* in);; + static inline ss_plugin_table_entry_t* add_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key, + ss_plugin_table_entry_t* _e); + static inline ss_plugin_rc write_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* e, + const ss_plugin_table_field_t* f, + const ss_plugin_state_data* in); + ; }; // a wrapper around sinsp_table_wrapper (yes...) that makes it comply to the // ss_plugin_table_input facade, thus being accessible through plugin API - struct sinsp_table_input - { + struct sinsp_table_input { ss_plugin_table_input input; ss_plugin_table_fields_vtable_ext fields_vtable; ss_plugin_table_reader_vtable_ext reader_vtable; @@ -386,53 +371,45 @@ class sinsp_plugin std::unordered_map> m_owned_tables; /* contains tables that the plugin accessed at least once */ std::unordered_map m_accessed_tables; - std::list> m_accessed_entries; // using lists for ptr stability - std::list m_accessed_table_fields; // note: lists have pointer stability - std::list m_ephemeral_tables; // note: lists have pointer stability + std::list> + m_accessed_entries; // using lists for ptr stability + std::list + m_accessed_table_fields; // note: lists have pointer stability + std::list m_ephemeral_tables; // note: lists have pointer stability bool m_ephemeral_tables_clear; bool m_accessed_entries_clear; - inline void clear_ephemeral_tables() - { - if (m_ephemeral_tables_clear) - { + inline void clear_ephemeral_tables() { + if(m_ephemeral_tables_clear) { // quick break-out that prevents us from looping over the // whole list in the critical path, in case of no accessed table return; } - for (auto& et : m_ephemeral_tables) - { + for(auto& et : m_ephemeral_tables) { et.wrapper.unset(); et.update(); } m_ephemeral_tables_clear = true; } - inline sinsp_table_input& find_unset_ephemeral_table() - { + inline sinsp_table_input& find_unset_ephemeral_table() { m_ephemeral_tables_clear = false; - for (auto& et : m_ephemeral_tables) - { - if (!et.wrapper.is_set()) - { + for(auto& et : m_ephemeral_tables) { + if(!et.wrapper.is_set()) { return et; } } return m_ephemeral_tables.emplace_back(); } - inline void clear_accessed_entries() - { - if (m_accessed_entries_clear) - { + inline void clear_accessed_entries() { + if(m_accessed_entries_clear) { // quick break-out that prevents us from looping over the // whole list in the critical path return; } - for (auto& et : m_accessed_entries) - { - if (et != nullptr) - { + for(auto& et : m_accessed_entries) { + if(et != nullptr) { // if we get here, it means that the plugin did not // release some of the entries it acquired ASSERT(false); @@ -442,25 +419,27 @@ class sinsp_plugin m_accessed_entries_clear = true; } - inline std::shared_ptr* find_unset_accessed_table_entry() - { + inline std::shared_ptr* find_unset_accessed_table_entry() { m_accessed_entries_clear = false; - for (auto& et : m_accessed_entries) - { - if (et == nullptr) - { + for(auto& et : m_accessed_entries) { + if(et == nullptr) { return &et; } } return &m_accessed_entries.emplace_back(); } - static void table_field_api(ss_plugin_table_fields_vtable& out, ss_plugin_table_fields_vtable_ext& extout); - static void table_read_api(ss_plugin_table_reader_vtable& out, ss_plugin_table_reader_vtable_ext& extout); - static void table_write_api(ss_plugin_table_writer_vtable& out, ss_plugin_table_writer_vtable_ext& extout); + static void table_field_api(ss_plugin_table_fields_vtable& out, + ss_plugin_table_fields_vtable_ext& extout); + static void table_read_api(ss_plugin_table_reader_vtable& out, + ss_plugin_table_reader_vtable_ext& extout); + static void table_write_api(ss_plugin_table_writer_vtable& out, + ss_plugin_table_writer_vtable_ext& extout); static ss_plugin_table_info* table_api_list_tables(ss_plugin_owner_t* o, uint32_t* ntables); - static ss_plugin_table_t *table_api_get_table(ss_plugin_owner_t *o, const char *name, ss_plugin_state_type key_type); - static ss_plugin_rc table_api_add_table(ss_plugin_owner_t *o, const ss_plugin_table_input* in); + static ss_plugin_table_t* table_api_get_table(ss_plugin_owner_t* o, + const char* name, + ss_plugin_state_type key_type); + static ss_plugin_rc table_api_add_table(ss_plugin_owner_t* o, const ss_plugin_table_input* in); std::shared_ptr m_thread_pool; diff --git a/userspace/libsinsp/plugin_filtercheck.cpp b/userspace/libsinsp/plugin_filtercheck.cpp old mode 100755 new mode 100644 index 8f10751345..afa0bdb301 --- a/userspace/libsinsp/plugin_filtercheck.cpp +++ b/userspace/libsinsp/plugin_filtercheck.cpp @@ -20,33 +20,31 @@ limitations under the License. #include using namespace std; -sinsp_filter_check_plugin::sinsp_filter_check_plugin() -{ +sinsp_filter_check_plugin::sinsp_filter_check_plugin() { static const filter_check_info s_no_plugin_fields_info = {"plugin", "", "", 0, nullptr}; m_info = &s_no_plugin_fields_info; m_eplugin = nullptr; } -sinsp_filter_check_plugin::sinsp_filter_check_plugin(const std::shared_ptr& plugin) -{ - if (!(plugin->caps() & CAP_EXTRACTION)) - { - throw sinsp_exception("Creating a sinsp_filter_check_plugin with a non extraction-capable plugin."); +sinsp_filter_check_plugin::sinsp_filter_check_plugin(const std::shared_ptr& plugin) { + if(!(plugin->caps() & CAP_EXTRACTION)) { + throw sinsp_exception( + "Creating a sinsp_filter_check_plugin with a non extraction-capable plugin."); } m_info = plugin->fields_info(); m_eplugin = plugin; } -sinsp_filter_check_plugin::sinsp_filter_check_plugin(const sinsp_filter_check_plugin &p) -{ +sinsp_filter_check_plugin::sinsp_filter_check_plugin(const sinsp_filter_check_plugin& p) { m_eplugin = p.m_eplugin; m_info = p.m_info; m_compatible_plugin_sources_bitmap = p.m_compatible_plugin_sources_bitmap; } -int32_t sinsp_filter_check_plugin::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ +int32_t sinsp_filter_check_plugin::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { int32_t res = sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); m_arg_present = false; @@ -55,11 +53,9 @@ int32_t sinsp_filter_check_plugin::parse_field_name(std::string_view val, bool a m_argstr.clear(); // the field is parsed successfully - if(res != -1) - { + if(res != -1) { size_t val_end = val.find_first_of(' ', 0); - if(val_end != string::npos) - { + if(val_end != string::npos) { val = val.substr(0, val_end); } val = trim_sv(val); @@ -67,44 +63,41 @@ int32_t sinsp_filter_check_plugin::parse_field_name(std::string_view val, bool a // search for the field's argument size_t arg_len = 0; size_t arg_pos = val.find_first_of('[', 0); - if(arg_pos != string::npos) - { - if (res != (int32_t) arg_pos) - { + if(arg_pos != string::npos) { + if(res != (int32_t)arg_pos) { // check that we matched the whole field string and not just its prefix return -1; } // extract the argument string with proper boundary checks size_t argstart = arg_pos + 1; - if(argstart >= val.size()) - { - throw sinsp_exception("filter '" + string(val) + "': " + m_field->m_name + " terminates with incomplete argument brackets"); + if(argstart >= val.size()) { + throw sinsp_exception("filter '" + string(val) + "': " + m_field->m_name + + " terminates with incomplete argument brackets"); } m_argstr = val.substr(argstart); arg_len = m_argstr.find_first_of(']', 0); - if(arg_len == string::npos) - { - throw sinsp_exception("filter '" + string(val) + "': " + m_field->m_name + " has unbalanced argument brackets"); + if(arg_len == string::npos) { + throw sinsp_exception("filter '" + string(val) + "': " + m_field->m_name + + " has unbalanced argument brackets"); } m_argstr = m_argstr.substr(0, arg_len); m_arg_present = true; // we have an argument, check if the field is supposed not to have one - if (!(m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_ALLOWED - || m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_REQUIRED)) - { - throw sinsp_exception("filter '" + string(val) + "': " - + m_field->m_name + " does not allow nor require an argument but one is provided: " + m_argstr); + if(!(m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_ALLOWED || + m_info->m_fields[m_field_id].m_flags & + filtercheck_field_flags::EPF_ARG_REQUIRED)) { + throw sinsp_exception( + "filter '" + string(val) + "': " + m_field->m_name + + " does not allow nor require an argument but one is provided: " + m_argstr); } // parse the argument content, which can either be an index or a key - if(m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_INDEX) - { + if(m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_INDEX) { extract_arg_index(val); } - if(m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_KEY) - { + if(m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_KEY) { extract_arg_key(); } @@ -112,48 +105,47 @@ int32_t sinsp_filter_check_plugin::parse_field_name(std::string_view val, bool a res = arg_pos + arg_len + 2; } - if (!m_arg_present && (m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_REQUIRED)) - { - throw sinsp_exception(string("filter '") + string(val) + string("': ") + m_field->m_name + string(" requires an argument but none provided")); + if(!m_arg_present && + (m_info->m_fields[m_field_id].m_flags & filtercheck_field_flags::EPF_ARG_REQUIRED)) { + throw sinsp_exception(string("filter '") + string(val) + string("': ") + + m_field->m_name + + string(" requires an argument but none provided")); } } return res; } -std::unique_ptr sinsp_filter_check_plugin::allocate_new() -{ +std::unique_ptr sinsp_filter_check_plugin::allocate_new() { return std::make_unique(*this); } -bool sinsp_filter_check_plugin::extract_nocache(sinsp_evt *evt, std::vector& values, bool sanitize_strings) -{ +bool sinsp_filter_check_plugin::extract_nocache(sinsp_evt* evt, + std::vector& values, + bool sanitize_strings) { // reject the event if it comes from an unknown event source - if (evt->get_source_idx() == sinsp_no_event_source_idx) - { + if(evt->get_source_idx() == sinsp_no_event_source_idx) { return false; } // reject the event if its type is not compatible with the plugin - if (!m_eplugin->extract_event_codes().contains((ppm_event_code) evt->get_type())) - { + if(!m_eplugin->extract_event_codes().contains((ppm_event_code)evt->get_type())) { return false; } // lazily populate the event source compatibility bitmap - while (m_compatible_plugin_sources_bitmap.size() <= evt->get_source_idx()) - { + while(m_compatible_plugin_sources_bitmap.size() <= evt->get_source_idx()) { auto src_idx = m_compatible_plugin_sources_bitmap.size(); m_compatible_plugin_sources_bitmap.push_back(false); ASSERT(src_idx < m_inspector->event_sources().size()); const auto& source = m_inspector->event_sources()[src_idx]; - auto compatible = sinsp_plugin::is_source_compatible(m_eplugin->extract_event_sources(), source); + auto compatible = + sinsp_plugin::is_source_compatible(m_eplugin->extract_event_sources(), source); m_compatible_plugin_sources_bitmap[src_idx] = compatible; } // reject the event if its event source is not compatible with the plugin - if (!m_compatible_plugin_sources_bitmap[evt->get_source_idx()]) - { + if(!m_compatible_plugin_sources_bitmap[evt->get_source_idx()]) { return false; } @@ -172,48 +164,42 @@ bool sinsp_filter_check_plugin::extract_nocache(sinsp_evt *evt, std::vectorm_fields[m_field_id].m_flags & EPF_IS_LIST; - if (!m_eplugin->extract_fields(evt, num_fields, &efield) || efield.res_len == 0) - { + if(!m_eplugin->extract_fields(evt, num_fields, &efield) || efield.res_len == 0) { return false; } values.clear(); - for (uint32_t i = 0; i < efield.res_len; ++i) - { + for(uint32_t i = 0; i < efield.res_len; ++i) { extract_value_t res; - switch(type) - { - case PT_UINT64: - case PT_RELTIME: - case PT_ABSTIME: - { - res.len = sizeof(uint64_t); - res.ptr = (uint8_t*) &efield.res.u64[i]; - break; - } - case PT_IPADDR: - case PT_IPNET: - { - res.len = (uint32_t) efield.res.buf[i].len; - res.ptr = (uint8_t*) efield.res.buf[i].ptr; - break; - } - case PT_CHARBUF: - { - res.len = strlen(efield.res.str[i]); - res.ptr = (uint8_t*) efield.res.str[i]; - break; - } - case PT_BOOL: - { - res.len = sizeof(ss_plugin_bool); - res.ptr = (uint8_t*) &efield.res.boolean[i]; - break; - } - default: - ASSERT(false); - throw sinsp_exception("plugin extract error: unsupported field type " + to_string(type)); - break; + switch(type) { + case PT_UINT64: + case PT_RELTIME: + case PT_ABSTIME: { + res.len = sizeof(uint64_t); + res.ptr = (uint8_t*)&efield.res.u64[i]; + break; + } + case PT_IPADDR: + case PT_IPNET: { + res.len = (uint32_t)efield.res.buf[i].len; + res.ptr = (uint8_t*)efield.res.buf[i].ptr; + break; + } + case PT_CHARBUF: { + res.len = strlen(efield.res.str[i]); + res.ptr = (uint8_t*)efield.res.str[i]; + break; + } + case PT_BOOL: { + res.len = sizeof(ss_plugin_bool); + res.ptr = (uint8_t*)&efield.res.boolean[i]; + break; + } + default: + ASSERT(false); + throw sinsp_exception("plugin extract error: unsupported field type " + + to_string(type)); + break; } values.push_back(res); } @@ -221,24 +207,20 @@ bool sinsp_filter_check_plugin::extract_nocache(sinsp_evt *evt, std::vector 1 && m_argstr[0] == '0')) - { + if(length == 0 || (length > 1 && m_argstr[0] == '0')) { is_valid = false; message = " has an invalid index argument starting with 0: "; } // The index must be composed only by digits (0-9). - for(int j = 0; j < length; j++) - { - if(!isdigit(m_argstr[j])) - { + for(int j = 0; j < length; j++) { + if(!isdigit(m_argstr[j])) { is_valid = false; message = " has an invalid index argument not composed only by digits: "; break; @@ -249,25 +231,20 @@ void sinsp_filter_check_plugin::extract_arg_index(std::string_view full_field_na // Please note that `stoul` alone is not enough, since it also consider as valid // strings like "0123 i'm a number", converting them into '0123'. This is why in the // previous step we check that every character is a digit. - if(is_valid) - { - try - { + if(is_valid) { + try { m_arg_index = std::stoul(m_argstr); return; - } - catch(...) - { + } catch(...) { message = " has an invalid index argument not representable on 64 bit: "; } } - throw sinsp_exception(string("filter ") + string(full_field_name) + string(" ") - + m_field->m_name + message + m_argstr); + throw sinsp_exception(string("filter ") + string(full_field_name) + string(" ") + + m_field->m_name + message + m_argstr); } // extract_arg_key() extracts a valid string from the argument. If we pass // a numeric argument, it will be converted to string. -void sinsp_filter_check_plugin::extract_arg_key() -{ +void sinsp_filter_check_plugin::extract_arg_key() { m_arg_key = (char*)m_argstr.c_str(); } diff --git a/userspace/libsinsp/plugin_filtercheck.h b/userspace/libsinsp/plugin_filtercheck.h old mode 100755 new mode 100644 index 55adc4c478..852eff4417 --- a/userspace/libsinsp/plugin_filtercheck.h +++ b/userspace/libsinsp/plugin_filtercheck.h @@ -27,32 +27,29 @@ limitations under the License. #include /** - \brief This class implements a dynamic filter check that acts as a - bridge to the plugin simplified field extraction implementations + \brief This class implements a dynamic filter check that acts as a + bridge to the plugin simplified field extraction implementations */ -class sinsp_filter_check_plugin : public sinsp_filter_check -{ +class sinsp_filter_check_plugin : public sinsp_filter_check { public: sinsp_filter_check_plugin(); explicit sinsp_filter_check_plugin(const std::shared_ptr& plugin); - explicit sinsp_filter_check_plugin(const sinsp_filter_check_plugin &p); + explicit sinsp_filter_check_plugin(const sinsp_filter_check_plugin& p); virtual ~sinsp_filter_check_plugin() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name( - std::string_view, - bool alloc_state, - bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; protected: - bool extract_nocache( - sinsp_evt *evt, - std::vector& values, - bool sanitize_strings = true) override; + bool extract_nocache(sinsp_evt* evt, + std::vector& values, + bool sanitize_strings = true) override; private: std::string m_argstr; diff --git a/userspace/libsinsp/plugin_manager.h b/userspace/libsinsp/plugin_manager.h old mode 100755 new mode 100644 index a635ab86a8..3d4f31ea69 --- a/userspace/libsinsp/plugin_manager.h +++ b/userspace/libsinsp/plugin_manager.h @@ -29,70 +29,61 @@ limitations under the License. /** * @brief Manager for plugins loaded at runtime. */ -class sinsp_plugin_manager -{ +class sinsp_plugin_manager { public: sinsp_plugin_manager(std::vector& event_sources): - m_event_sources(event_sources), - m_plugins(), - m_plugins_id_index(), - m_plugins_id_source_index(), - m_last_id_in(-1), - m_last_id_out(-1), - m_last_source_in(-1), - m_last_source_out(-1) { } + m_event_sources(event_sources), + m_plugins(), + m_plugins_id_index(), + m_plugins_id_source_index(), + m_last_id_in(-1), + m_last_id_out(-1), + m_last_source_in(-1), + m_last_source_out(-1) {} virtual ~sinsp_plugin_manager() = default; sinsp_plugin_manager(sinsp_plugin_manager&&) = default; sinsp_plugin_manager(const sinsp_plugin_manager& s) = delete; - sinsp_plugin_manager& operator = (const sinsp_plugin_manager& s) = delete; + sinsp_plugin_manager& operator=(const sinsp_plugin_manager& s) = delete; /** * @brief Adds a plugin in the manager. */ - void add(const std::shared_ptr& plugin) - { - for(auto& it : m_plugins) - { + void add(const std::shared_ptr& plugin) { + for(auto& it : m_plugins) { // todo(jasondellaluce): we may consider dropping this constraint in the future - if(it->name() == plugin->name()) - { - throw sinsp_exception( - "found another plugin with name " + it->name() + ". Aborting."); + if(it->name() == plugin->name()) { + throw sinsp_exception("found another plugin with name " + it->name() + + ". Aborting."); } - /* Every plugin with event sourcing capability requires its own unique plugin event ID unless the ID is `0` - * in that case there could be multiple plugins with sourcing capabilities loaded + /* Every plugin with event sourcing capability requires its own unique plugin event ID + * unless the ID is `0` in that case there could be multiple plugins with sourcing + * capabilities loaded */ - if (it->caps() & CAP_SOURCING - && plugin->caps() & CAP_SOURCING - && plugin->id() != 0 - && it->id() == plugin->id()) - { - throw sinsp_exception( - "found another plugin with ID " + std::to_string(it->id()) + ". Aborting."); + if(it->caps() & CAP_SOURCING && plugin->caps() & CAP_SOURCING && plugin->id() != 0 && + it->id() == plugin->id()) { + throw sinsp_exception("found another plugin with ID " + std::to_string(it->id()) + + ". Aborting."); } } - if (plugin->caps() & CAP_SOURCING && plugin->id() != 0) - { + if(plugin->caps() & CAP_SOURCING && plugin->id() != 0) { // note: we avoid duplicate entries in the evt sources list bool existing = false; /* Get the source index: * - First we search it in the array to see if it is already present - * - if not present the new source position will be the first available in the `m_event_sources` array + * - if not present the new source position will be the first available in the + * `m_event_sources` array */ auto source_index = m_event_sources.size(); - for (size_t i = 0; i < m_event_sources.size(); i++) - { - if (m_event_sources[i] == plugin->event_source()) - { + for(size_t i = 0; i < m_event_sources.size(); i++) { + if(m_event_sources[i] == plugin->event_source()) { existing = true; source_index = i; break; } } - if (!existing) - { + if(!existing) { /* Push the source in the array if it doesn't already exist */ m_event_sources.push_back(plugin->event_source()); } @@ -107,23 +98,17 @@ class sinsp_plugin_manager /** * @brief Returns all the plugins in the manager. */ - inline const std::vector>& plugins() const - { - return m_plugins; - } + inline const std::vector>& plugins() const { return m_plugins; } /** * @brief Returns a plugin given its ID. The plugin is guaranteed to have * the CAP_EVENT_SOURCE capability. Returns nullptr if no plugin exists * with the given ID. */ - inline const std::shared_ptr& plugin_by_id(uint32_t plugin_id) const - { - if (plugin_id != m_last_id_in) - { + inline const std::shared_ptr& plugin_by_id(uint32_t plugin_id) const { + if(plugin_id != m_last_id_in) { auto it = m_plugins_id_index.find(plugin_id); - if(it == m_plugins_id_index.end()) - { + if(it == m_plugins_id_index.end()) { return m_nullptr_ret; } m_last_id_in = plugin_id; @@ -136,10 +121,8 @@ class sinsp_plugin_manager * @brief Returns a plugin given an event. The plugin is guaranteed to have * the CAP_EVENT_SOURCE capability. */ - inline const std::shared_ptr& plugin_by_evt(sinsp_evt* evt) const - { - if(evt && evt->get_type() == PPME_PLUGINEVENT_E) - { + inline const std::shared_ptr& plugin_by_evt(sinsp_evt* evt) const { + if(evt && evt->get_type() == PPME_PLUGINEVENT_E) { return plugin_by_id(evt->get_param(0)->as()); } return m_nullptr_ret; @@ -151,13 +134,10 @@ class sinsp_plugin_manager * with `true` if a plugin with a given ID is found in the manager, * otherwise it is filled with `false`. */ - inline std::size_t source_idx_by_plugin_id(uint32_t plugin_id, bool& found) const - { - if (plugin_id != m_last_source_in) - { + inline std::size_t source_idx_by_plugin_id(uint32_t plugin_id, bool& found) const { + if(plugin_id != m_last_source_in) { auto it = m_plugins_id_source_index.find(plugin_id); - if(it == m_plugins_id_source_index.end()) - { + if(it == m_plugins_id_source_index.end()) { found = false; return sinsp_no_event_source_idx; } @@ -180,7 +160,8 @@ class sinsp_plugin_manager /* The key is the plugin id the value is the index of the plugin in the `m_plugins` vector */ std::unordered_map m_plugins_id_index; - /* The key is the plugin id the value is the index of the plugin source in the `m_event_sources` vector */ + /* The key is the plugin id the value is the index of the plugin source in the `m_event_sources` + * vector */ std::unordered_map m_plugins_id_source_index; mutable size_t m_last_id_in; mutable size_t m_last_id_out; diff --git a/userspace/libsinsp/plugin_parser.h b/userspace/libsinsp/plugin_parser.h index c60a9180a4..00f20d814e 100644 --- a/userspace/libsinsp/plugin_parser.h +++ b/userspace/libsinsp/plugin_parser.h @@ -26,65 +26,57 @@ limitations under the License. * a plugin that has event parsing capability. The parser is guaranteed to * process all the event of a given capture, once and only once. */ -class sinsp_plugin_parser -{ +class sinsp_plugin_parser { public: sinsp_plugin_parser(const std::shared_ptr& p): - m_plugin(p), - m_compatible_plugin_sources_bitmap() - { - if (!(p->caps() & CAP_PARSING)) - { - throw sinsp_exception("can't create a sinsp_plugin_parser with a plugin that has no event parsing capability"); + m_plugin(p), + m_compatible_plugin_sources_bitmap() { + if(!(p->caps() & CAP_PARSING)) { + throw sinsp_exception( + "can't create a sinsp_plugin_parser with a plugin that has no event parsing " + "capability"); } } - virtual ~sinsp_plugin_parser() = default; - sinsp_plugin_parser(sinsp_plugin_parser&&) = default; - sinsp_plugin_parser& operator = (sinsp_plugin_parser&&) = default; - sinsp_plugin_parser(const sinsp_plugin_parser& s) = default; - sinsp_plugin_parser& operator = (const sinsp_plugin_parser& s) = default; + virtual ~sinsp_plugin_parser() = default; + sinsp_plugin_parser(sinsp_plugin_parser&&) = default; + sinsp_plugin_parser& operator=(sinsp_plugin_parser&&) = default; + sinsp_plugin_parser(const sinsp_plugin_parser& s) = default; + sinsp_plugin_parser& operator=(const sinsp_plugin_parser& s) = default; - inline bool process_event(sinsp_evt* evt, const std::vector& evt_sources) - { + inline bool process_event(sinsp_evt* evt, const std::vector& evt_sources) { // reject the event if it comes from an unknown event source - if (evt->get_source_idx() == sinsp_no_event_source_idx) - { - return false; - } + if(evt->get_source_idx() == sinsp_no_event_source_idx) { + return false; + } - // reject the event if its type is not compatible with the plugin - if (!m_plugin->parse_event_codes().contains((ppm_event_code) evt->get_type())) - { - return false; - } + // reject the event if its type is not compatible with the plugin + if(!m_plugin->parse_event_codes().contains((ppm_event_code)evt->get_type())) { + return false; + } - // lazily populate the event source compatibility bitmap - while (m_compatible_plugin_sources_bitmap.size() <= evt->get_source_idx()) - { - auto src_idx = m_compatible_plugin_sources_bitmap.size(); - m_compatible_plugin_sources_bitmap.push_back(false); - ASSERT(src_idx < evt_sources.size()); - const auto& source = evt_sources[src_idx]; - auto compatible = sinsp_plugin::is_source_compatible(m_plugin->parse_event_sources(), source); - m_compatible_plugin_sources_bitmap[src_idx] = compatible; - } + // lazily populate the event source compatibility bitmap + while(m_compatible_plugin_sources_bitmap.size() <= evt->get_source_idx()) { + auto src_idx = m_compatible_plugin_sources_bitmap.size(); + m_compatible_plugin_sources_bitmap.push_back(false); + ASSERT(src_idx < evt_sources.size()); + const auto& source = evt_sources[src_idx]; + auto compatible = + sinsp_plugin::is_source_compatible(m_plugin->parse_event_sources(), source); + m_compatible_plugin_sources_bitmap[src_idx] = compatible; + } - // reject the event if its event source is not compatible with the plugin - if (!m_compatible_plugin_sources_bitmap[evt->get_source_idx()]) - { - return false; - } + // reject the event if its event source is not compatible with the plugin + if(!m_compatible_plugin_sources_bitmap[evt->get_source_idx()]) { + return false; + } return m_plugin->parse_event(evt); } - inline const std::shared_ptr& plugin() const - { - return m_plugin; - } + inline const std::shared_ptr& plugin() const { return m_plugin; } private: - std::shared_ptr m_plugin; + std::shared_ptr m_plugin; std::vector m_compatible_plugin_sources_bitmap; }; diff --git a/userspace/libsinsp/plugin_table_api.cpp b/userspace/libsinsp/plugin_table_api.cpp old mode 100755 new mode 100644 index ec62b4cdc5..f5b8985289 --- a/userspace/libsinsp/plugin_table_api.cpp +++ b/userspace/libsinsp/plugin_table_api.cpp @@ -18,109 +18,120 @@ limitations under the License. #include -#define __CATCH_ERR_MSG(_ERR, _F) \ -{ \ - try { _F; } \ - catch (const std::exception& _e) { _ERR = _e.what(); } \ - catch (...) { _ERR = "unknown error"; } \ -} +#define __CATCH_ERR_MSG(_ERR, _F) \ + { \ + try { \ + _F; \ + } catch(const std::exception& _e) { \ + _ERR = _e.what(); \ + } catch(...) { \ + _ERR = "unknown error"; \ + } \ + } -#define __PLUGIN_STATETYPE_SWITCH(_kt) \ -{ \ - switch (_kt) \ - { \ - case ss_plugin_state_type::SS_PLUGIN_ST_INT8: \ - _X(int8_t, s8); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_INT16: \ - _X(int16_t, s16); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_INT32: \ - _X(int32_t, s32); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_INT64: \ - _X(int64_t, s64); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_UINT8: \ - _X(uint8_t, u8); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_UINT16: \ - _X(uint16_t, u16); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_UINT32: \ - _X(uint32_t, u32); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_UINT64: \ - _X(uint64_t, u64); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_STRING: \ - _X(std::string, str); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_BOOL: \ - _X(bool, b); break; \ - case ss_plugin_state_type::SS_PLUGIN_ST_TABLE: \ - _X(libsinsp::state::base_table*, table); break; \ - default: \ - throw sinsp_exception("can't convert plugin state type to typeinfo: " + std::to_string(_kt)); \ - } \ -} +#define __PLUGIN_STATETYPE_SWITCH(_kt) \ + { \ + switch(_kt) { \ + case ss_plugin_state_type::SS_PLUGIN_ST_INT8: \ + _X(int8_t, s8); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_INT16: \ + _X(int16_t, s16); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_INT32: \ + _X(int32_t, s32); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_INT64: \ + _X(int64_t, s64); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_UINT8: \ + _X(uint8_t, u8); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_UINT16: \ + _X(uint16_t, u16); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_UINT32: \ + _X(uint32_t, u32); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_UINT64: \ + _X(uint64_t, u64); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_STRING: \ + _X(std::string, str); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_BOOL: \ + _X(bool, b); \ + break; \ + case ss_plugin_state_type::SS_PLUGIN_ST_TABLE: \ + _X(libsinsp::state::base_table*, table); \ + break; \ + default: \ + throw sinsp_exception("can't convert plugin state type to typeinfo: " + \ + std::to_string(_kt)); \ + } \ + } -static inline ss_plugin_state_type typeinfo_to_state_type(const libsinsp::state::typeinfo& i) -{ - switch(i.index()) - { - case libsinsp::state::typeinfo::index_t::TI_INT8: - return ss_plugin_state_type::SS_PLUGIN_ST_INT8; - case libsinsp::state::typeinfo::index_t::TI_INT16: - return ss_plugin_state_type::SS_PLUGIN_ST_INT16; - case libsinsp::state::typeinfo::index_t::TI_INT32: - return ss_plugin_state_type::SS_PLUGIN_ST_INT32; - case libsinsp::state::typeinfo::index_t::TI_INT64: - return ss_plugin_state_type::SS_PLUGIN_ST_INT64; - case libsinsp::state::typeinfo::index_t::TI_UINT8: - return ss_plugin_state_type::SS_PLUGIN_ST_UINT8; - case libsinsp::state::typeinfo::index_t::TI_UINT16: - return ss_plugin_state_type::SS_PLUGIN_ST_UINT16; - case libsinsp::state::typeinfo::index_t::TI_UINT32: - return ss_plugin_state_type::SS_PLUGIN_ST_UINT32; - case libsinsp::state::typeinfo::index_t::TI_UINT64: - return ss_plugin_state_type::SS_PLUGIN_ST_UINT64; - case libsinsp::state::typeinfo::index_t::TI_STRING: - return ss_plugin_state_type::SS_PLUGIN_ST_STRING; - case libsinsp::state::typeinfo::index_t::TI_BOOL: - return ss_plugin_state_type::SS_PLUGIN_ST_BOOL; - case libsinsp::state::typeinfo::index_t::TI_TABLE: - return ss_plugin_state_type::SS_PLUGIN_ST_TABLE; - default: - throw sinsp_exception("can't convert typeinfo to plugin state type: " + std::to_string(i.index())); +static inline ss_plugin_state_type typeinfo_to_state_type(const libsinsp::state::typeinfo& i) { + switch(i.index()) { + case libsinsp::state::typeinfo::index_t::TI_INT8: + return ss_plugin_state_type::SS_PLUGIN_ST_INT8; + case libsinsp::state::typeinfo::index_t::TI_INT16: + return ss_plugin_state_type::SS_PLUGIN_ST_INT16; + case libsinsp::state::typeinfo::index_t::TI_INT32: + return ss_plugin_state_type::SS_PLUGIN_ST_INT32; + case libsinsp::state::typeinfo::index_t::TI_INT64: + return ss_plugin_state_type::SS_PLUGIN_ST_INT64; + case libsinsp::state::typeinfo::index_t::TI_UINT8: + return ss_plugin_state_type::SS_PLUGIN_ST_UINT8; + case libsinsp::state::typeinfo::index_t::TI_UINT16: + return ss_plugin_state_type::SS_PLUGIN_ST_UINT16; + case libsinsp::state::typeinfo::index_t::TI_UINT32: + return ss_plugin_state_type::SS_PLUGIN_ST_UINT32; + case libsinsp::state::typeinfo::index_t::TI_UINT64: + return ss_plugin_state_type::SS_PLUGIN_ST_UINT64; + case libsinsp::state::typeinfo::index_t::TI_STRING: + return ss_plugin_state_type::SS_PLUGIN_ST_STRING; + case libsinsp::state::typeinfo::index_t::TI_BOOL: + return ss_plugin_state_type::SS_PLUGIN_ST_BOOL; + case libsinsp::state::typeinfo::index_t::TI_TABLE: + return ss_plugin_state_type::SS_PLUGIN_ST_TABLE; + default: + throw sinsp_exception("can't convert typeinfo to plugin state type: " + + std::to_string(i.index())); } } -template static inline void convert_types(const From& from, To& to) -{ +template +static inline void convert_types(const From& from, To& to) { to = from; } // special cases for strings -template<> inline void convert_types(const std::string& from, const char*& to) -{ +template<> +inline void convert_types(const std::string& from, const char*& to) { to = from.c_str(); } -template<> inline void convert_types(libsinsp::state::base_table* const& from, ss_plugin_table_t*& to) -{ +template<> +inline void convert_types(libsinsp::state::base_table* const& from, ss_plugin_table_t*& to) { to = static_cast(from); } -template<> inline void convert_types(ss_plugin_table_t* const& from, libsinsp::state::base_table*& to) -{ +template<> +inline void convert_types(ss_plugin_table_t* const& from, libsinsp::state::base_table*& to) { to = static_cast(from); } -static void noop_release_table_entry(ss_plugin_table_t*, ss_plugin_table_entry_t*) -{ -} +static void noop_release_table_entry(ss_plugin_table_t*, ss_plugin_table_entry_t*) {} -static ss_plugin_bool noop_iterate_entries(ss_plugin_table_t*, ss_plugin_table_iterator_func_t, ss_plugin_table_iterator_state_t*) -{ +static ss_plugin_bool noop_iterate_entries(ss_plugin_table_t*, + ss_plugin_table_iterator_func_t, + ss_plugin_table_iterator_state_t*) { return 0; } -struct owned_table_input_deleter -{ - void operator()(ss_plugin_table_input* in) - { +struct owned_table_input_deleter { + void operator()(ss_plugin_table_input* in) { delete in->reader_ext; delete in->writer_ext; delete in->fields_ext; @@ -133,20 +144,17 @@ using owned_table_input_t = std::shared_ptr; // note(jasondellaluce): here we assume that the api version has major number v3 // todo(jasondellaluce): update the repairing logic and safety checks // when switching to a v4 minor/major plugin API version -static inline owned_table_input_t copy_and_check_table_input(const sinsp_plugin* p, const ss_plugin_table_input* in) -{ +static inline owned_table_input_t copy_and_check_table_input(const sinsp_plugin* p, + const ss_plugin_table_input* in) { std::string errprefix = "failure in adding state table defined by plugin '" + p->name() + "': "; - if (!in) - { + if(!in) { throw sinsp_exception(errprefix + "input is null"); } - if (!in->name) - { + if(!in->name) { throw sinsp_exception(errprefix + "name is null"); } - owned_table_input_t res( - new ss_plugin_table_input(), owned_table_input_deleter()); + owned_table_input_t res(new ss_plugin_table_input(), owned_table_input_deleter()); res->name = in->name; res->key_type = in->key_type; res->table = in->table; @@ -160,8 +168,7 @@ static inline owned_table_input_t copy_and_check_table_input(const sinsp_plugin* res->reader_ext = new ss_plugin_table_reader_vtable_ext(); res->writer_ext = new ss_plugin_table_writer_vtable_ext(); res->fields_ext = new ss_plugin_table_fields_vtable_ext(); - if (p->required_api_version().minor() < 1) - { + if(p->required_api_version().minor() < 1) { res->reader_ext->get_table_name = res->reader.get_table_name; res->reader_ext->get_table_size = res->reader.get_table_size; res->reader_ext->get_table_entry = res->reader.get_table_entry; @@ -179,11 +186,8 @@ static inline owned_table_input_t copy_and_check_table_input(const sinsp_plugin* res->fields_ext->list_table_fields = res->fields.list_table_fields; res->fields_ext->get_table_field = res->fields.get_table_field; res->fields_ext->add_table_field = res->fields.add_table_field; - } - else - { - if (!in->reader_ext || !in->writer_ext || !in->fields_ext) - { + } else { + if(!in->reader_ext || !in->writer_ext || !in->fields_ext) { throw sinsp_exception(errprefix + "extended vtables must all be defined"); } @@ -206,76 +210,83 @@ static inline owned_table_input_t copy_and_check_table_input(const sinsp_plugin* res->fields_ext->add_table_field = in->fields_ext->add_table_field; } - if ((!res->reader_ext->get_table_name || res->reader_ext->get_table_name != res->reader.get_table_name) || - (!res->reader_ext->get_table_size || res->reader_ext->get_table_size != res->reader.get_table_size) || - (!res->reader_ext->get_table_entry || res->reader_ext->get_table_entry != res->reader.get_table_entry) || - (!res->reader_ext->read_entry_field || res->reader_ext->read_entry_field != res->reader.read_entry_field) || - !res->reader_ext->release_table_entry || - !res->reader_ext->iterate_entries) - { + if((!res->reader_ext->get_table_name || + res->reader_ext->get_table_name != res->reader.get_table_name) || + (!res->reader_ext->get_table_size || + res->reader_ext->get_table_size != res->reader.get_table_size) || + (!res->reader_ext->get_table_entry || + res->reader_ext->get_table_entry != res->reader.get_table_entry) || + (!res->reader_ext->read_entry_field || + res->reader_ext->read_entry_field != res->reader.read_entry_field) || + !res->reader_ext->release_table_entry || !res->reader_ext->iterate_entries) { throw sinsp_exception(errprefix + "broken or inconsistent reader vtables"); } if((!res->writer_ext->clear_table || res->writer_ext->clear_table != res->writer.clear_table) || - (!res->writer_ext->erase_table_entry || res->writer_ext->erase_table_entry != res->writer.erase_table_entry) || - (!res->writer_ext->create_table_entry || res->writer_ext->create_table_entry != res->writer.create_table_entry) || - (!res->writer_ext->destroy_table_entry || res->writer_ext->destroy_table_entry != res->writer.destroy_table_entry) || - (!res->writer_ext->add_table_entry || res->writer_ext->add_table_entry != res->writer.add_table_entry) || - (!res->writer_ext->write_entry_field || res->writer_ext->write_entry_field != res->writer.write_entry_field)) - { + (!res->writer_ext->erase_table_entry || + res->writer_ext->erase_table_entry != res->writer.erase_table_entry) || + (!res->writer_ext->create_table_entry || + res->writer_ext->create_table_entry != res->writer.create_table_entry) || + (!res->writer_ext->destroy_table_entry || + res->writer_ext->destroy_table_entry != res->writer.destroy_table_entry) || + (!res->writer_ext->add_table_entry || + res->writer_ext->add_table_entry != res->writer.add_table_entry) || + (!res->writer_ext->write_entry_field || + res->writer_ext->write_entry_field != res->writer.write_entry_field)) { throw sinsp_exception(errprefix + "broken or inconsistent writer vtables"); } - if((!res->fields_ext->list_table_fields || res->fields_ext->list_table_fields != res->fields.list_table_fields) || - (!res->fields_ext->get_table_field || res->fields_ext->get_table_field != res->fields.get_table_field) || - (!res->fields_ext->add_table_field || res->fields_ext->add_table_field != res->fields.add_table_field)) - { + if((!res->fields_ext->list_table_fields || + res->fields_ext->list_table_fields != res->fields.list_table_fields) || + (!res->fields_ext->get_table_field || + res->fields_ext->get_table_field != res->fields.get_table_field) || + (!res->fields_ext->add_table_field || + res->fields_ext->add_table_field != res->fields.add_table_field)) { throw sinsp_exception(errprefix + "broken or inconsistent fields vtables"); } return res; } -static inline std::string table_input_error_prefix(const sinsp_plugin* o, ss_plugin_table_input* i) -{ - return "error in state table '" + std::string(i->name) + "' defined by plugin '" + o->name() + "': "; +static inline std::string table_input_error_prefix(const sinsp_plugin* o, + ss_plugin_table_input* i) { + return "error in state table '" + std::string(i->name) + "' defined by plugin '" + o->name() + + "': "; } static const libsinsp::state::static_struct::field_infos s_empty_static_infos; // wraps instances of ss_plugin_table_input and makes them comply // to the libsinsp::state::table state tables definition. -template -struct plugin_table_wrapper: public libsinsp::state::table -{ +template +struct plugin_table_wrapper : public libsinsp::state::table { using ss = libsinsp::state::static_struct; using ds = libsinsp::state::dynamic_struct; - - struct plugin_field_infos: public ds::field_infos - { - plugin_field_infos( - const sinsp_plugin* o, - const owned_table_input_t& i) - : field_infos(), m_owner(o), m_input(i), m_accessors() {}; + + struct plugin_field_infos : public ds::field_infos { + plugin_field_infos(const sinsp_plugin* o, const owned_table_input_t& i): + field_infos(), + m_owner(o), + m_input(i), + m_accessors() {}; plugin_field_infos(plugin_field_infos&&) = default; - plugin_field_infos& operator = (plugin_field_infos&&) = default; + plugin_field_infos& operator=(plugin_field_infos&&) = default; plugin_field_infos(const plugin_field_infos& s) = delete; - plugin_field_infos& operator = (const plugin_field_infos& s) = delete; + plugin_field_infos& operator=(const plugin_field_infos& s) = delete; virtual ~plugin_field_infos() = default; const sinsp_plugin* m_owner; owned_table_input_t m_input; std::vector m_accessors; - virtual const std::unordered_map& fields() override - { + virtual const std::unordered_map& fields() override { // list all the fields of the plugin table uint32_t nfields = 0; auto res = m_input->fields_ext->list_table_fields(m_input->table, &nfields); - if (res == NULL) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "list fields failure: " + m_owner->get_last_error()); + if(res == NULL) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "list fields failure: " + m_owner->get_last_error()); } // if there's a different number of fields that in our local copy, @@ -284,17 +295,13 @@ struct plugin_table_wrapper: public libsinsp::state::table // index of the first time we received it from the plugin. This is // relevant because the plugin API does not give guarantees about // order stability of the returned array of field infos. - if (nfields != ds::field_infos::fields().size()) - { - for (uint32_t i = 0; i < nfields; i++) - { + if(nfields != ds::field_infos::fields().size()) { + for(uint32_t i = 0; i < nfields; i++) { ds::field_info f; - #define _X(_type, _dtype) \ - { \ - f = ds::field_info::build<_type>(res[i].name, i, (uintptr_t) this, res[i].read_only); \ - } +#define _X(_type, _dtype) \ + { f = ds::field_info::build<_type>(res[i].name, i, (uintptr_t)this, res[i].read_only); } __PLUGIN_STATETYPE_SWITCH(res[i].field_type); - #undef _X +#undef _X ds::field_infos::add_field_info(f); } } @@ -306,19 +313,20 @@ struct plugin_table_wrapper: public libsinsp::state::table // This will be used later for instant retrieval of the accessors // during read-write operations. const auto& ret = ds::field_infos::fields(); - for (const auto& it : ret) - { + for(const auto& it : ret) { const auto& f = it.second; - while (m_accessors.size() <= f.index()) - { + while(m_accessors.size() <= f.index()) { m_accessors.push_back(nullptr); } - if (m_accessors[f.index()] == nullptr) - { - auto facc = m_input->fields_ext->get_table_field(m_input->table, f.name().c_str(), typeinfo_to_state_type(f.info())); - if (facc == NULL) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "get table field failure: " + m_owner->get_last_error()); + if(m_accessors[f.index()] == nullptr) { + auto facc = + m_input->fields_ext->get_table_field(m_input->table, + f.name().c_str(), + typeinfo_to_state_type(f.info())); + if(facc == NULL) { + throw sinsp_exception( + table_input_error_prefix(m_owner, m_input.get()) + + "get table field failure: " + m_owner->get_last_error()); } m_accessors[f.index()] = facc; } @@ -326,12 +334,13 @@ struct plugin_table_wrapper: public libsinsp::state::table return ret; } - virtual const ds::field_info& add_field_info(const ds::field_info& field) override - { - auto ret = m_input->fields_ext->add_table_field(m_input->table, field.name().c_str(), typeinfo_to_state_type(field.info())); - if (ret == NULL) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "add table field failure: " + m_owner->get_last_error()); + virtual const ds::field_info& add_field_info(const ds::field_info& field) override { + auto ret = m_input->fields_ext->add_table_field(m_input->table, + field.name().c_str(), + typeinfo_to_state_type(field.info())); + if(ret == NULL) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "add table field failure: " + m_owner->get_last_error()); } // after adding a new field, we retrieve the whole list again @@ -347,33 +356,26 @@ struct plugin_table_wrapper: public libsinsp::state::table } }; - struct plugin_table_entry: public libsinsp::state::table_entry - { - plugin_table_entry( - sinsp_plugin* o, - const owned_table_input_t& i, - const std::shared_ptr& fields, - ss_plugin_table_entry_t* e, - bool detached): - table_entry(fields), - m_owner(o), - m_input(i), - m_entry(e), - m_detached(detached) {}; + struct plugin_table_entry : public libsinsp::state::table_entry { + plugin_table_entry(sinsp_plugin* o, + const owned_table_input_t& i, + const std::shared_ptr& fields, + ss_plugin_table_entry_t* e, + bool detached): + table_entry(fields), + m_owner(o), + m_input(i), + m_entry(e), + m_detached(detached) {}; plugin_table_entry(const plugin_table_entry& o) = delete; - plugin_table_entry& operator = (const plugin_table_entry& o) = delete; + plugin_table_entry& operator=(const plugin_table_entry& o) = delete; plugin_table_entry(plugin_table_entry&& o) = default; - plugin_table_entry& operator = (plugin_table_entry&& o) = default; - virtual ~plugin_table_entry() - { - if (m_entry) - { - if (m_detached) - { + plugin_table_entry& operator=(plugin_table_entry&& o) = default; + virtual ~plugin_table_entry() { + if(m_entry) { + if(m_detached) { m_input->writer_ext->destroy_table_entry(m_input->table, m_entry); - } - else - { + } else { m_input->reader_ext->release_table_entry(m_input->table, m_entry); } } @@ -388,27 +390,28 @@ struct plugin_table_wrapper: public libsinsp::state::table // to ever be ever invoked, because we set the fields shared pointer // at construction time. This is just here as a consistency fence in // case of misuse. - virtual void set_dynamic_fields(const std::shared_ptr& defs) override - { - if (defs && dynamic_cast(defs.get()) == nullptr) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "plugin table can only be set with plugin dynamic fields"); + virtual void set_dynamic_fields(const std::shared_ptr& defs) override { + if(defs && dynamic_cast(defs.get()) == nullptr) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "plugin table can only be set with plugin dynamic fields"); } table_entry::set_dynamic_fields(defs); } - virtual void get_dynamic_field(const ds::field_info& i, void* out) override - { - if (i.info().index() == libsinsp::state::typeinfo::index_t::TI_TABLE) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "read field failure: dynamic table fields not supported"); + virtual void get_dynamic_field(const ds::field_info& i, void* out) override { + if(i.info().index() == libsinsp::state::typeinfo::index_t::TI_TABLE) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "read field failure: dynamic table fields not supported"); } const auto& infos = get_plugin_field_infos(); ss_plugin_state_data dout; - auto rc = m_input->reader_ext->read_entry_field(m_input->table, m_entry, infos.m_accessors[i.index()], &dout); - if (rc != SS_PLUGIN_SUCCESS) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "read field failure: " + m_owner->get_last_error()); + auto rc = m_input->reader_ext->read_entry_field(m_input->table, + m_entry, + infos.m_accessors[i.index()], + &dout); + if(rc != SS_PLUGIN_SUCCESS) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "read field failure: " + m_owner->get_last_error()); } // note: strings are the only exception to the switch case below, @@ -416,23 +419,17 @@ struct plugin_table_wrapper: public libsinsp::state::table // and as const char*s by the plugin API. // todo(jasondellaluce): maybe find a common place for all this // type conversions knowledge (also leaked in dynamic_struct.h) - if (i.info().index() == libsinsp::state::typeinfo::index_t::TI_STRING) - { - *(const char**) out = dout.str; - } - else - { - #define _X(_type, _dtype) \ - { \ - convert_types(dout._dtype, *((_type*) out)); \ - } + if(i.info().index() == libsinsp::state::typeinfo::index_t::TI_STRING) { + *(const char**)out = dout.str; + } else { +#define _X(_type, _dtype) \ + { convert_types(dout._dtype, *((_type*)out)); } __PLUGIN_STATETYPE_SWITCH(typeinfo_to_state_type(i.info())); - #undef _X +#undef _X } } - virtual void set_dynamic_field(const ds::field_info& i, const void* in) override - { + virtual void set_dynamic_field(const ds::field_info& i, const void* in) override { const auto& infos = get_plugin_field_infos(); ss_plugin_state_data v; @@ -441,32 +438,30 @@ struct plugin_table_wrapper: public libsinsp::state::table // and as const char*s by the plugin API. // todo(jasondellaluce): maybe find a common place for all this // type conversions knowledge (also leaked in dynamic_struct.h) - if (i.info().index() == libsinsp::state::typeinfo::index_t::TI_STRING) - { - v.str = *(const char**) in; - } - else - { - #define _X(_type, _dtype) \ - { \ - convert_types(*((_type*) in), v._dtype); \ - } + if(i.info().index() == libsinsp::state::typeinfo::index_t::TI_STRING) { + v.str = *(const char**)in; + } else { +#define _X(_type, _dtype) \ + { convert_types(*((_type*)in), v._dtype); } __PLUGIN_STATETYPE_SWITCH(typeinfo_to_state_type(i.info())); - #undef _X +#undef _X } - auto rc = m_input->writer_ext->write_entry_field(m_input->table, m_entry, infos.m_accessors[i.index()], &v); - if (rc != SS_PLUGIN_SUCCESS) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "write field failure: " + m_owner->get_last_error()); + auto rc = m_input->writer_ext->write_entry_field(m_input->table, + m_entry, + infos.m_accessors[i.index()], + &v); + if(rc != SS_PLUGIN_SUCCESS) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "write field failure: " + m_owner->get_last_error()); } } + private: - const plugin_field_infos& get_plugin_field_infos() const - { - if (dynamic_fields() == nullptr) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "local fields definitions not set"); + const plugin_field_infos& get_plugin_field_infos() const { + if(dynamic_fields() == nullptr) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "local fields definitions not set"); } // note: casting should be safe because we force the // plugin_field_infos subtype both the constructor and the setter @@ -475,95 +470,85 @@ struct plugin_table_wrapper: public libsinsp::state::table } }; - plugin_table_wrapper(sinsp_plugin* o, const ss_plugin_table_input* i) - : libsinsp::state::table(i->name, &s_empty_static_infos), - m_owner(o), - m_input(copy_and_check_table_input(o, i)), - m_dyn_fields(std::make_shared(o, m_input)), - m_dyn_fields_as_base_class(m_dyn_fields) - { + plugin_table_wrapper(sinsp_plugin* o, const ss_plugin_table_input* i): + libsinsp::state::table(i->name, &s_empty_static_infos), + m_owner(o), + m_input(copy_and_check_table_input(o, i)), + m_dyn_fields(std::make_shared(o, m_input)), + m_dyn_fields_as_base_class(m_dyn_fields) { auto t = libsinsp::state::typeinfo::of(); - if (m_input->key_type != typeinfo_to_state_type(t)) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "invalid key type: " + std::string(t.name())); + if(m_input->key_type != typeinfo_to_state_type(t)) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "invalid key type: " + std::string(t.name())); } } virtual ~plugin_table_wrapper() = default; plugin_table_wrapper(plugin_table_wrapper&&) = default; - plugin_table_wrapper& operator = (plugin_table_wrapper&&) = default; + plugin_table_wrapper& operator=(plugin_table_wrapper&&) = default; plugin_table_wrapper(const plugin_table_wrapper& s) = delete; - plugin_table_wrapper& operator = (const plugin_table_wrapper& s) = delete; + plugin_table_wrapper& operator=(const plugin_table_wrapper& s) = delete; sinsp_plugin* m_owner; owned_table_input_t m_input; std::shared_ptr m_dyn_fields; std::shared_ptr m_dyn_fields_as_base_class; - const libsinsp::state::static_struct::field_infos* static_fields() const override - { + const libsinsp::state::static_struct::field_infos* static_fields() const override { // note: always empty, plugin-defined table have no "static" fields, // all of them are dynamically-discovered at runtime return &s_empty_static_infos; } - const std::shared_ptr& dynamic_fields() const override - { + const std::shared_ptr& dynamic_fields() const override { return m_dyn_fields_as_base_class; } - size_t entries_count() const override - { + size_t entries_count() const override { auto res = m_input->reader_ext->get_table_size(m_input->table); - if (res == (uint64_t) -1) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "get size failure: " + m_owner->get_last_error()); + if(res == (uint64_t)-1) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "get size failure: " + m_owner->get_last_error()); } - return (size_t) res; + return (size_t)res; } - void clear_entries() override - { + void clear_entries() override { auto res = m_input->writer_ext->clear_table(m_input->table); - if (res != SS_PLUGIN_SUCCESS) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "clear entries failure: " + m_owner->get_last_error()); + if(res != SS_PLUGIN_SUCCESS) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "clear entries failure: " + m_owner->get_last_error()); } } // used only for foreach_entry below - struct table_iterator_state - { + struct table_iterator_state { std::string err; plugin_table_entry* m_entry; std::function* m_it; }; // used only for foreach_entry below - static ss_plugin_bool table_iterator_func(ss_plugin_table_iterator_state_t *s, ss_plugin_table_entry_t *_e) - { + static ss_plugin_bool table_iterator_func(ss_plugin_table_iterator_state_t* s, + ss_plugin_table_entry_t* _e) { auto state = static_cast(s); state->m_entry->m_entry = _e; - __CATCH_ERR_MSG(state->err, { - return (*state->m_it)(*state->m_entry) ? 1 : 0; - }); + __CATCH_ERR_MSG(state->err, { return (*state->m_it)(*state->m_entry) ? 1 : 0; }); return 0; } - bool foreach_entry(std::function pred) override - { + bool foreach_entry(std::function pred) override { plugin_table_entry entry(m_owner, m_input, m_dyn_fields, NULL, false); table_iterator_state state; state.m_it = &pred; state.m_entry = &entry; auto s = static_cast(&state); - if (m_input->reader_ext->iterate_entries(m_input->table, table_iterator_func, s) == 0) - { + if(m_input->reader_ext->iterate_entries(m_input->table, table_iterator_func, s) == 0) { // avoids invoking release_table_entry entry.m_entry = NULL; - if (!state.err.empty()) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "iterate entries failure: " + state.err); + if(!state.err.empty()) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "iterate entries failure: " + state.err); } return false; } @@ -572,23 +557,20 @@ struct plugin_table_wrapper: public libsinsp::state::table return true; } - std::unique_ptr new_entry() const override - { + std::unique_ptr new_entry() const override { auto res = m_input->writer_ext->create_table_entry(m_input->table); - if (res == NULL) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "create entry failure: " + m_owner->get_last_error()); + if(res == NULL) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "create entry failure: " + m_owner->get_last_error()); } return std::make_unique(m_owner, m_input, m_dyn_fields, res, true); } - std::shared_ptr get_entry(const KeyType& key) override - { + std::shared_ptr get_entry(const KeyType& key) override { ss_plugin_state_data keydata; get_key_as_data(key, keydata); auto res = m_input->reader_ext->get_table_entry(m_input->table, &keydata); - if (res == NULL) - { + if(res == NULL) { // note: libsinsp::state::table expects nullptr to be returned // instead of an error exception return nullptr; @@ -601,11 +583,12 @@ struct plugin_table_wrapper: public libsinsp::state::table return std::make_shared(m_owner, m_input, m_dyn_fields, res, false); } - std::shared_ptr add_entry(const KeyType& key, std::unique_ptr e) override - { - if (!e) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "add entry invoked with null entry"); + std::shared_ptr add_entry( + const KeyType& key, + std::unique_ptr e) override { + if(!e) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "add entry invoked with null entry"); } // we have no formal way for checking for misuses in which the invoker @@ -619,17 +602,16 @@ struct plugin_table_wrapper: public libsinsp::state::table ss_plugin_state_data keydata; get_key_as_data(key, keydata); auto res = m_input->writer_ext->add_table_entry(m_input->table, &keydata, entry->m_entry); - if (res == NULL) - { - throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + "add entry failure: " + m_owner->get_last_error()); + if(res == NULL) { + throw sinsp_exception(table_input_error_prefix(m_owner, m_input.get()) + + "add entry failure: " + m_owner->get_last_error()); } entry->m_entry = res; entry->m_detached = false; return std::shared_ptr(std::move(e)); } - bool erase_entry(const KeyType& key) override - { + bool erase_entry(const KeyType& key) override { ss_plugin_state_data keydata; get_key_as_data(key, keydata); auto res = m_input->writer_ext->erase_table_entry(m_input->table, &keydata); @@ -638,95 +620,94 @@ struct plugin_table_wrapper: public libsinsp::state::table return res == SS_PLUGIN_SUCCESS; } - private: +private: static void get_key_as_data(const KeyType& key, ss_plugin_state_data& out); }; -template<> void plugin_table_wrapper::get_key_as_data(const int8_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const int8_t& key, ss_plugin_state_data& out) { out.s8 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const int16_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const int16_t& key, ss_plugin_state_data& out) { out.s16 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const int32_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const int32_t& key, ss_plugin_state_data& out) { out.s32 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const int64_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const int64_t& key, ss_plugin_state_data& out) { out.s64 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const uint8_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const uint8_t& key, ss_plugin_state_data& out) { out.u8 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const uint16_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const uint16_t& key, + ss_plugin_state_data& out) { out.u16 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const uint32_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const uint32_t& key, + ss_plugin_state_data& out) { out.u32 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const uint64_t& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const uint64_t& key, + ss_plugin_state_data& out) { out.u64 = key; } -template<> void plugin_table_wrapper::get_key_as_data(const std::string& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const std::string& key, + ss_plugin_state_data& out) { out.str = key.c_str(); } -template<> void plugin_table_wrapper::get_key_as_data(const bool& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data(const bool& key, ss_plugin_state_data& out) { out.b = key; } -template<> void plugin_table_wrapper::get_key_as_data(libsinsp::state::base_table* const& key, ss_plugin_state_data& out) -{ +template<> +void plugin_table_wrapper::get_key_as_data( + libsinsp::state::base_table* const& key, + ss_plugin_state_data& out) { out.table = static_cast(key); } // // sinsp_field_accessor_wrapper implementation // -sinsp_plugin::sinsp_field_accessor_wrapper::~sinsp_field_accessor_wrapper() -{ - if (!accessor) - { +sinsp_plugin::sinsp_field_accessor_wrapper::~sinsp_field_accessor_wrapper() { + if(!accessor) { return; } - #define _X(_type, _dtype) \ - { \ - if (dynamic) \ - { \ +#define _X(_type, _dtype) \ + { \ + if(dynamic) { \ delete static_cast*>(accessor); \ - } \ - else \ - { \ - delete static_cast*>(accessor); \ - } \ - break; \ + } else { \ + delete static_cast*>(accessor); \ + } \ + break; \ } std::string tmp; - __CATCH_ERR_MSG(tmp, { - __PLUGIN_STATETYPE_SWITCH(data_type); - }); - #undef _X + __CATCH_ERR_MSG(tmp, { __PLUGIN_STATETYPE_SWITCH(data_type); }); +#undef _X } -sinsp_plugin::sinsp_field_accessor_wrapper::sinsp_field_accessor_wrapper(sinsp_plugin::sinsp_field_accessor_wrapper&& s) -{ +sinsp_plugin::sinsp_field_accessor_wrapper::sinsp_field_accessor_wrapper( + sinsp_plugin::sinsp_field_accessor_wrapper&& s) { this->accessor = s.accessor; this->dynamic = s.dynamic; this->data_type = s.data_type; @@ -734,8 +715,8 @@ sinsp_plugin::sinsp_field_accessor_wrapper::sinsp_field_accessor_wrapper(sinsp_p s.accessor = nullptr; } -sinsp_plugin::sinsp_field_accessor_wrapper& sinsp_plugin::sinsp_field_accessor_wrapper::operator=(sinsp_plugin::sinsp_field_accessor_wrapper&& s) -{ +sinsp_plugin::sinsp_field_accessor_wrapper& sinsp_plugin::sinsp_field_accessor_wrapper::operator=( + sinsp_plugin::sinsp_field_accessor_wrapper&& s) { this->accessor = s.accessor; this->dynamic = s.dynamic; this->data_type = s.data_type; @@ -747,15 +728,12 @@ sinsp_plugin::sinsp_field_accessor_wrapper& sinsp_plugin::sinsp_field_accessor_w // // sinsp_table_wrapper implementation // -template -void sinsp_plugin::sinsp_table_wrapper::set(sinsp_plugin* p, libsinsp::state::table* t) -{ - if (!t) - { +template +void sinsp_plugin::sinsp_table_wrapper::set(sinsp_plugin* p, libsinsp::state::table* t) { + if(!t) { throw sinsp_exception("null table assigned to sinsp table wrapper"); } - if (!p) - { + if(!p) { throw sinsp_exception("null plugin assigned to sinsp table wrapper"); } @@ -772,15 +750,13 @@ void sinsp_plugin::sinsp_table_wrapper::set(sinsp_plugin* p, libsinsp::state::ta // because the current C++ wrapper for plugin-defined tables is just // a non-functional stub used only for complying to the registry interfaces. auto pt = dynamic_cast*>(t); - if (pt) - { + if(pt) { m_table_plugin_owner = pt->m_owner; m_table_plugin_input = pt->m_input.get(); } } -void sinsp_plugin::sinsp_table_wrapper::unset() -{ +void sinsp_plugin::sinsp_table_wrapper::unset() { m_owner_plugin = nullptr; m_key_type = ss_plugin_state_type::SS_PLUGIN_ST_INT8; m_table = nullptr; @@ -789,21 +765,19 @@ void sinsp_plugin::sinsp_table_wrapper::unset() m_table_plugin_input = nullptr; } -bool sinsp_plugin::sinsp_table_wrapper::is_set() const -{ +bool sinsp_plugin::sinsp_table_wrapper::is_set() const { return m_table_plugin_input != nullptr || m_table != nullptr; } -const ss_plugin_table_fieldinfo* sinsp_plugin::sinsp_table_wrapper::list_fields(ss_plugin_table_t* _t, uint32_t* nfields) -{ +const ss_plugin_table_fieldinfo* sinsp_plugin::sinsp_table_wrapper::list_fields( + ss_plugin_table_t* _t, + uint32_t* nfields) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->fields_ext->list_table_fields(pt, nfields); - if (ret == NULL) - { + if(ret == NULL) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; @@ -811,16 +785,14 @@ const ss_plugin_table_fieldinfo* sinsp_plugin::sinsp_table_wrapper::list_fields( __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { t->m_field_list.clear(); - for (auto& info : *t->m_table->static_fields()) - { + for(auto& info : *t->m_table->static_fields()) { ss_plugin_table_fieldinfo i; i.name = info.second.name().c_str(); i.field_type = typeinfo_to_state_type(info.second.info()); i.read_only = info.second.readonly(); t->m_field_list.push_back(i); } - for (auto& info : t->m_table->dynamic_fields()->fields()) - { + for(auto& info : t->m_table->dynamic_fields()->fields()) { ss_plugin_table_fieldinfo i; i.name = info.second.name().c_str(); i.field_type = typeinfo_to_state_type(info.second.info()); @@ -833,217 +805,202 @@ const ss_plugin_table_fieldinfo* sinsp_plugin::sinsp_table_wrapper::list_fields( return NULL; } -ss_plugin_table_field_t* sinsp_plugin::sinsp_table_wrapper::get_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type) -{ +ss_plugin_table_field_t* sinsp_plugin::sinsp_table_wrapper::get_field( + ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->fields_ext->get_table_field(pt, name, data_type); - if (ret == NULL) - { + if(ret == NULL) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; } libsinsp::state::static_struct::field_infos::const_iterator fixed_it; - std::unordered_map::const_iterator dyn_it; + std::unordered_map::const_iterator + dyn_it; __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { auto it = t->m_field_accessors.find(name); - if (it != t->m_field_accessors.end()) - { + if(it != t->m_field_accessors.end()) { return static_cast(it->second); } fixed_it = t->m_table->static_fields()->find(name); dyn_it = t->m_table->dynamic_fields()->fields().find(name); - if (fixed_it != t->m_table->static_fields()->end() - && dyn_it != t->m_table->dynamic_fields()->fields().end()) - { + if(fixed_it != t->m_table->static_fields()->end() && + dyn_it != t->m_table->dynamic_fields()->fields().end()) { // todo(jasondellaluce): plugins are not aware of the difference // between static and dynamic fields. Do we want to enforce // this limitation in the sinsp tables implementation as well? - throw sinsp_exception("field is defined as both static and dynamic: " + std::string(name)); + throw sinsp_exception("field is defined as both static and dynamic: " + + std::string(name)); } }); - #define _X(_type, _dtype) \ - { \ - auto acc = fixed_it->second.new_accessor<_type>(); \ - sinsp_plugin::sinsp_field_accessor_wrapper acc_wrap; \ - acc_wrap.dynamic = false; \ - acc_wrap.data_type = data_type; \ +#define _X(_type, _dtype) \ + { \ + auto acc = fixed_it->second.new_accessor<_type>(); \ + sinsp_plugin::sinsp_field_accessor_wrapper acc_wrap; \ + acc_wrap.dynamic = false; \ + acc_wrap.data_type = data_type; \ acc_wrap.accessor = new libsinsp::state::static_struct::field_accessor<_type>(acc); \ - t->m_owner_plugin->m_accessed_table_fields.push_back(std::move(acc_wrap)); \ - t->m_field_accessors[name] = &t->m_owner_plugin->m_accessed_table_fields.back(); \ - return t->m_field_accessors[name]; \ + t->m_owner_plugin->m_accessed_table_fields.push_back(std::move(acc_wrap)); \ + t->m_field_accessors[name] = &t->m_owner_plugin->m_accessed_table_fields.back(); \ + return t->m_field_accessors[name]; \ } __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - if (fixed_it != t->m_table->static_fields()->end()) - { - if (data_type != typeinfo_to_state_type(fixed_it->second.info())) - { - throw sinsp_exception("incompatible data types for static field: " + std::string(name)); - } + if(fixed_it != t->m_table->static_fields()->end()) { + if(data_type != typeinfo_to_state_type(fixed_it->second.info())) { + throw sinsp_exception("incompatible data types for static field: " + + std::string(name)); + } __PLUGIN_STATETYPE_SWITCH(data_type); } }); - #undef _X - - #define _X(_type, _dtype) \ - { \ - auto acc = dyn_it->second.new_accessor<_type>(); \ - sinsp_plugin::sinsp_field_accessor_wrapper acc_wrap; \ - acc_wrap.dynamic = true; \ - acc_wrap.data_type = data_type; \ +#undef _X + +#define _X(_type, _dtype) \ + { \ + auto acc = dyn_it->second.new_accessor<_type>(); \ + sinsp_plugin::sinsp_field_accessor_wrapper acc_wrap; \ + acc_wrap.dynamic = true; \ + acc_wrap.data_type = data_type; \ acc_wrap.accessor = new libsinsp::state::dynamic_struct::field_accessor<_type>(acc); \ - t->m_owner_plugin->m_accessed_table_fields.push_back(std::move(acc_wrap)); \ - t->m_field_accessors[name] = &t->m_owner_plugin->m_accessed_table_fields.back(); \ - return t->m_field_accessors[name]; \ + t->m_owner_plugin->m_accessed_table_fields.push_back(std::move(acc_wrap)); \ + t->m_field_accessors[name] = &t->m_owner_plugin->m_accessed_table_fields.back(); \ + return t->m_field_accessors[name]; \ } __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - if (dyn_it != t->m_table->dynamic_fields()->fields().end()) - { - if (data_type != typeinfo_to_state_type(dyn_it->second.info())) - { - throw sinsp_exception("incompatible data types for dynamic field: " + std::string(name)); + if(dyn_it != t->m_table->dynamic_fields()->fields().end()) { + if(data_type != typeinfo_to_state_type(dyn_it->second.info())) { + throw sinsp_exception("incompatible data types for dynamic field: " + + std::string(name)); } __PLUGIN_STATETYPE_SWITCH(data_type); } - throw sinsp_exception("undefined field '" + std::string(name) + "' in table '" + t->m_table->name() + "'"); + throw sinsp_exception("undefined field '" + std::string(name) + "' in table '" + + t->m_table->name() + "'"); }); - #undef _X +#undef _X return NULL; } -ss_plugin_table_field_t* sinsp_plugin::sinsp_table_wrapper::add_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type) -{ +ss_plugin_table_field_t* sinsp_plugin::sinsp_table_wrapper::add_field( + ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type) { auto t = static_cast(_t); - if (data_type == ss_plugin_state_type::SS_PLUGIN_ST_TABLE) - { - t->m_owner_plugin->m_last_owner_err = "can't add dynamic field of type table: " + std::string(name); + if(data_type == ss_plugin_state_type::SS_PLUGIN_ST_TABLE) { + t->m_owner_plugin->m_last_owner_err = + "can't add dynamic field of type table: " + std::string(name); return NULL; } - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->fields_ext->add_table_field(pt, name, data_type); - if (ret == NULL) - { + if(ret == NULL) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; } - if (t->m_table->static_fields()->find(name) != t->m_table->static_fields()->end()) - { - t->m_owner_plugin->m_last_owner_err = "can't add dynamic field already defined as static: " + std::string(name); + if(t->m_table->static_fields()->find(name) != t->m_table->static_fields()->end()) { + t->m_owner_plugin->m_last_owner_err = + "can't add dynamic field already defined as static: " + std::string(name); return NULL; } - - #define _X(_type, _dtype) \ - { \ + +#define _X(_type, _dtype) \ + { \ t->m_table->dynamic_fields()->add_field<_type>(name); \ - break; \ + break; \ } __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { __PLUGIN_STATETYPE_SWITCH(data_type); return get_field(_t, name, data_type); }); - #undef _X +#undef _X return NULL; } -const char* sinsp_plugin::sinsp_table_wrapper::get_name(ss_plugin_table_t* _t) -{ +const char* sinsp_plugin::sinsp_table_wrapper::get_name(ss_plugin_table_t* _t) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { return t->m_table_plugin_input->name; } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - return t->m_table->name().c_str(); - }); + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { return t->m_table->name().c_str(); }); return NULL; } -uint64_t sinsp_plugin::sinsp_table_wrapper::get_size(ss_plugin_table_t* _t) -{ +uint64_t sinsp_plugin::sinsp_table_wrapper::get_size(ss_plugin_table_t* _t) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->reader_ext->get_table_size(pt); - if (ret == ((uint64_t) -1)) - { + if(ret == ((uint64_t)-1)) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - return t->m_table->entries_count(); - }); - return ((uint64_t) -1); + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { return t->m_table->entries_count(); }); + return ((uint64_t)-1); } -ss_plugin_table_entry_t* sinsp_plugin::sinsp_table_wrapper::get_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key) -{ +ss_plugin_table_entry_t* sinsp_plugin::sinsp_table_wrapper::get_entry( + ss_plugin_table_t* _t, + const ss_plugin_state_data* key) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->reader_ext->get_table_entry(pt, key); - if (ret == NULL) - { + if(ret == NULL) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; } - // note: the C++ API returns a shared pointer, but in plugins we only - // use raw pointers without increasing/decreasing/owning the refcount. - // How can we do better than this? - // todo(jasondellaluce): should we actually make plugins own some memory, - // to guarantee that the shared_ptr returned is properly refcounted? - #define _X(_type, _dtype) \ - { \ - auto tt = static_cast*>(t->m_table); \ - _type kk; \ - convert_types(key->_dtype, kk); \ - auto ret = tt->get_entry(kk); \ - if (ret != nullptr) \ - { \ +// note: the C++ API returns a shared pointer, but in plugins we only +// use raw pointers without increasing/decreasing/owning the refcount. +// How can we do better than this? +// todo(jasondellaluce): should we actually make plugins own some memory, +// to guarantee that the shared_ptr returned is properly refcounted? +#define _X(_type, _dtype) \ + { \ + auto tt = static_cast*>(t->m_table); \ + _type kk; \ + convert_types(key->_dtype, kk); \ + auto ret = tt->get_entry(kk); \ + if(ret != nullptr) { \ auto owned_ptr = t->m_owner_plugin->find_unset_accessed_table_entry(); \ - *owned_ptr = ret; \ - return static_cast(owned_ptr); \ - } \ - throw sinsp_exception("get_entry found no element at given key"); \ - return NULL; \ + *owned_ptr = ret; \ + return static_cast(owned_ptr); \ + } \ + throw sinsp_exception("get_entry found no element at given key"); \ + return NULL; \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(t->m_key_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(t->m_key_type); }); +#undef _X return NULL; } - -void sinsp_plugin::sinsp_table_wrapper::release_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e) -{ +void sinsp_plugin::sinsp_table_wrapper::release_table_entry(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* _e) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; t->m_table_plugin_input->reader_ext->release_table_entry(pt, _e); return; @@ -1052,46 +1009,42 @@ void sinsp_plugin::sinsp_table_wrapper::release_table_entry(ss_plugin_table_t* _ static_cast*>(_e)->reset(); } -ss_plugin_bool sinsp_plugin::sinsp_table_wrapper::iterate_entries(ss_plugin_table_t* _t, ss_plugin_table_iterator_func_t it, ss_plugin_table_iterator_state_t* s) -{ +ss_plugin_bool sinsp_plugin::sinsp_table_wrapper::iterate_entries( + ss_plugin_table_t* _t, + ss_plugin_table_iterator_func_t it, + ss_plugin_table_iterator_state_t* s) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; return t->m_table_plugin_input->reader_ext->iterate_entries(pt, it, s); } std::shared_ptr owned_ptr; - std::function iter = [&owned_ptr, &it, &s](auto& e) - { - owned_ptr.reset(&e, [](libsinsp::state::table_entry* p) { }); + std::function iter = [&owned_ptr, &it, &s](auto& e) { + owned_ptr.reset(&e, [](libsinsp::state::table_entry* p) {}); return it(s, static_cast(&owned_ptr)) != 0; }; - #define _X(_type, _dtype) \ - { \ +#define _X(_type, _dtype) \ + { \ auto tt = static_cast*>(t->m_table); \ - return tt->foreach_entry(iter); \ + return tt->foreach_entry(iter); \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(t->m_key_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(t->m_key_type); }); +#undef _X return false; } - -ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::clear(ss_plugin_table_t* _t) -{ + +ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::clear(ss_plugin_table_t* _t) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->writer_ext->clear_table(pt); - if (ret == SS_PLUGIN_FAILURE) - { + if(ret == SS_PLUGIN_FAILURE) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; @@ -1104,140 +1057,128 @@ ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::clear(ss_plugin_table_t* _t) return SS_PLUGIN_FAILURE; } -ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::erase_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key) -{ +ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::erase_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->writer_ext->erase_table_entry(pt, key); - if (ret == SS_PLUGIN_FAILURE) - { + if(ret == SS_PLUGIN_FAILURE) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; } - #define _X(_type, _dtype) \ - { \ - _type kk; \ - convert_types(key->_dtype, kk); \ - if (static_cast*>(t->m_table)->erase_entry(kk)) \ - { \ - return SS_PLUGIN_SUCCESS; \ - } \ - else \ - { \ - t->m_owner_plugin->m_last_owner_err = "table entry not found"; \ - return SS_PLUGIN_FAILURE; \ - } \ +#define _X(_type, _dtype) \ + { \ + _type kk; \ + convert_types(key->_dtype, kk); \ + if(static_cast*>(t->m_table)->erase_entry(kk)) { \ + return SS_PLUGIN_SUCCESS; \ + } else { \ + t->m_owner_plugin->m_last_owner_err = "table entry not found"; \ + return SS_PLUGIN_FAILURE; \ + } \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(t->m_key_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(t->m_key_type); }); +#undef _X return SS_PLUGIN_FAILURE; } -ss_plugin_table_entry_t* sinsp_plugin::sinsp_table_wrapper::create_table_entry(ss_plugin_table_t* _t) -{ +ss_plugin_table_entry_t* sinsp_plugin::sinsp_table_wrapper::create_table_entry( + ss_plugin_table_t* _t) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->writer_ext->create_table_entry(pt); - if (ret == NULL) - { + if(ret == NULL) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; } - #define _X(_type, _dtype) \ - { \ - auto tt = static_cast*>(t->m_table); \ - auto ret = tt->new_entry().release(); \ - auto owned_ptr = t->m_owner_plugin->find_unset_accessed_table_entry(); \ +#define _X(_type, _dtype) \ + { \ + auto tt = static_cast*>(t->m_table); \ + auto ret = tt->new_entry().release(); \ + auto owned_ptr = t->m_owner_plugin->find_unset_accessed_table_entry(); \ owned_ptr->reset(ret, [](libsinsp::state::table_entry* p) { /* do nothing */ }); \ - return static_cast(owned_ptr); \ + return static_cast(owned_ptr); \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(t->m_key_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(t->m_key_type); }); +#undef _X return NULL; } -void sinsp_plugin::sinsp_table_wrapper::destroy_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e) -{ +void sinsp_plugin::sinsp_table_wrapper::destroy_table_entry(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* _e) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; t->m_table_plugin_input->writer_ext->destroy_table_entry(pt, _e); return; } - #define _X(_type, _dtype) \ - { \ +#define _X(_type, _dtype) \ + { \ auto e = static_cast*>(_e); \ - auto ptr = std::unique_ptr(e->get()); \ - e->reset(); \ - break; \ + auto ptr = std::unique_ptr(e->get()); \ + e->reset(); \ + break; \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(t->m_key_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(t->m_key_type); }); +#undef _X } -ss_plugin_table_entry_t* sinsp_plugin::sinsp_table_wrapper::add_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key, ss_plugin_table_entry_t* _e) -{ +ss_plugin_table_entry_t* sinsp_plugin::sinsp_table_wrapper::add_entry( + ss_plugin_table_t* _t, + const ss_plugin_state_data* key, + ss_plugin_table_entry_t* _e) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->writer_ext->add_table_entry(pt, key, _e); - if (ret == NULL) - { + if(ret == NULL) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; } - #define _X(_type, _dtype) \ - { \ +#define _X(_type, _dtype) \ + { \ auto e = static_cast*>(_e); \ - auto ptr = std::unique_ptr(e->get()); \ - e->reset(); \ - auto tt = static_cast*>(t->m_table); \ - _type kk; \ - convert_types(key->_dtype, kk); \ - auto owned_ptr = t->m_owner_plugin->find_unset_accessed_table_entry(); \ - *owned_ptr = tt->add_entry(kk, std::move(ptr)); \ - return static_cast(owned_ptr); \ + auto ptr = std::unique_ptr(e->get()); \ + e->reset(); \ + auto tt = static_cast*>(t->m_table); \ + _type kk; \ + convert_types(key->_dtype, kk); \ + auto owned_ptr = t->m_owner_plugin->find_unset_accessed_table_entry(); \ + *owned_ptr = tt->add_entry(kk, std::move(ptr)); \ + return static_cast(owned_ptr); \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(t->m_key_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(t->m_key_type); }); +#undef _X return NULL; } -ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::read_entry_field(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e, const ss_plugin_table_field_t* f, ss_plugin_state_data* out) -{ +ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::read_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* _e, + const ss_plugin_table_field_t* f, + ss_plugin_state_data* out) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->reader_ext->read_entry_field(pt, _e, f, out); - if (ret == SS_PLUGIN_FAILURE) - { + if(ret == SS_PLUGIN_FAILURE) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; @@ -1247,56 +1188,52 @@ ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::read_entry_field(ss_plugin_table auto e = static_cast*>(_e); auto res = SS_PLUGIN_FAILURE; - #define _X(_type, _dtype) \ - { \ - if (a->dynamic) \ - { \ - auto aa = static_cast*>(a->accessor); \ - e->get()->get_dynamic_field<_type>(*aa, out->_dtype); \ - } \ - else \ - { \ - auto aa = static_cast*>(a->accessor); \ - e->get()->get_static_field<_type>(*aa, out->_dtype); \ - } \ - res = SS_PLUGIN_SUCCESS; \ - break; \ +#define _X(_type, _dtype) \ + { \ + if(a->dynamic) { \ + auto aa = static_cast*>( \ + a->accessor); \ + e->get()->get_dynamic_field<_type>(*aa, out->_dtype); \ + } else { \ + auto aa = static_cast*>( \ + a->accessor); \ + e->get()->get_static_field<_type>(*aa, out->_dtype); \ + } \ + res = SS_PLUGIN_SUCCESS; \ + break; \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(a->data_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(a->data_type); }); +#undef _X - #define _X(_type, _dtype) \ - { \ +#define _X(_type, _dtype) \ + { \ auto st = static_cast*>(subtable_ptr); \ - auto& slot = t->m_owner_plugin->find_unset_ephemeral_table(); \ - slot.wrapper.set<_type>(t->m_owner_plugin, st); \ - slot.update(); \ - out->table = &slot.input; \ + auto& slot = t->m_owner_plugin->find_unset_ephemeral_table(); \ + slot.wrapper.set<_type>(t->m_owner_plugin, st); \ + slot.update(); \ + out->table = &slot.input; \ }; - if (a->data_type == ss_plugin_state_type::SS_PLUGIN_ST_TABLE) - { + if(a->data_type == ss_plugin_state_type::SS_PLUGIN_ST_TABLE) { auto* subtable_ptr = out->table; - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(a->subtable_key_type); - }); + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(a->subtable_key_type); }); } - #undef _X +#undef _X return res; } -ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::write_entry_field(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e, const ss_plugin_table_field_t* f, const ss_plugin_state_data* in) -{ +ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::write_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* _e, + const ss_plugin_table_field_t* f, + const ss_plugin_state_data* in) { auto t = static_cast(_t); - if (t->m_table_plugin_input) - { + if(t->m_table_plugin_input) { auto pt = t->m_table_plugin_input->table; auto ret = t->m_table_plugin_input->writer_ext->write_entry_field(pt, _e, f, in); - if (ret == SS_PLUGIN_FAILURE) - { + if(ret == SS_PLUGIN_FAILURE) { t->m_owner_plugin->m_last_owner_err = t->m_table_plugin_owner->get_last_error(); } return ret; @@ -1306,42 +1243,38 @@ ss_plugin_rc sinsp_plugin::sinsp_table_wrapper::write_entry_field(ss_plugin_tabl auto e = static_cast*>(_e); // todo(jasondellaluce): drop this check once we start supporting this - if (a->data_type == ss_plugin_state_type::SS_PLUGIN_ST_TABLE) - { + if(a->data_type == ss_plugin_state_type::SS_PLUGIN_ST_TABLE) { t->m_owner_plugin->m_last_owner_err = "writing to table fields is currently not supported"; return SS_PLUGIN_FAILURE; } - #define _X(_type, _dtype) \ - { \ - if (a->dynamic) \ - { \ - auto aa = static_cast*>(a->accessor); \ - _type val; \ - convert_types(in->_dtype, val); \ - e->get()->set_dynamic_field<_type>(*aa, val); \ - } \ - else \ - { \ - auto aa = static_cast*>(a->accessor); \ - _type val; \ - convert_types(in->_dtype, val); \ - e->get()->set_static_field<_type>(*aa, val); \ - } \ - return SS_PLUGIN_SUCCESS; \ +#define _X(_type, _dtype) \ + { \ + if(a->dynamic) { \ + auto aa = static_cast*>( \ + a->accessor); \ + _type val; \ + convert_types(in->_dtype, val); \ + e->get()->set_dynamic_field<_type>(*aa, val); \ + } else { \ + auto aa = static_cast*>( \ + a->accessor); \ + _type val; \ + convert_types(in->_dtype, val); \ + e->get()->set_static_field<_type>(*aa, val); \ + } \ + return SS_PLUGIN_SUCCESS; \ } - __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, { - __PLUGIN_STATETYPE_SWITCH(a->data_type); - }); - #undef _X + __CATCH_ERR_MSG(t->m_owner_plugin->m_last_owner_err, + { __PLUGIN_STATETYPE_SWITCH(a->data_type); }); +#undef _X return SS_PLUGIN_FAILURE; } // // sinsp_table_input implementation // -sinsp_plugin::sinsp_table_input::sinsp_table_input() -{ +sinsp_plugin::sinsp_table_input::sinsp_table_input() { // populate vtables reader_vtable.get_table_name = sinsp_plugin::sinsp_table_wrapper::get_name; reader_vtable.get_table_size = sinsp_plugin::sinsp_table_wrapper::get_size; @@ -1385,120 +1318,115 @@ sinsp_plugin::sinsp_table_input::sinsp_table_input() input.key_type = wrapper.m_key_type; } -void sinsp_plugin::sinsp_table_input::update() -{ +void sinsp_plugin::sinsp_table_input::update() { input.name = nullptr; input.table = nullptr; - if (!wrapper.is_set()) - { + if(!wrapper.is_set()) { return; } input.table = &wrapper; - if (wrapper.m_table) - { + if(wrapper.m_table) { input.key_type = wrapper.m_key_type; input.name = wrapper.m_table->name().c_str(); - } - else if (wrapper.m_table_plugin_input) - { + } else if(wrapper.m_table_plugin_input) { input.key_type = wrapper.m_table_plugin_input->key_type; input.name = wrapper.m_table_plugin_input->name; } } - // the following table api symbols act as dispatcher for the table API // interface, which is implemented through the type ss_plugin_table_input. // For sinsp-defined tables, the ss_plugin_table_input is a wrapper around // the libsinsp::state::table interface. For plugin-defined tables, the // ss_plugin_table_input is provided by the table-owner plugin itself. -static const ss_plugin_table_fieldinfo* dispatch_list_fields(ss_plugin_table_t *_t, uint32_t *nfields) -{ +static const ss_plugin_table_fieldinfo* dispatch_list_fields(ss_plugin_table_t* _t, + uint32_t* nfields) { auto t = static_cast(_t); return t->fields_ext->list_table_fields(t->table, nfields); } -static ss_plugin_table_field_t* dispatch_get_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type) -{ +static ss_plugin_table_field_t* dispatch_get_field(ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type) { auto t = static_cast(_t); return t->fields_ext->get_table_field(t->table, name, data_type); } -static ss_plugin_table_field_t* dispatch_add_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type) -{ +static ss_plugin_table_field_t* dispatch_add_field(ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type) { auto t = static_cast(_t); return t->fields_ext->add_table_field(t->table, name, data_type); } -static const char* dispatch_get_name(ss_plugin_table_t* _t) -{ +static const char* dispatch_get_name(ss_plugin_table_t* _t) { auto t = static_cast(_t); return t->reader_ext->get_table_name(t->table); } -static uint64_t dispatch_get_size(ss_plugin_table_t* _t) -{ +static uint64_t dispatch_get_size(ss_plugin_table_t* _t) { auto t = static_cast(_t); return t->reader_ext->get_table_size(t->table); } -static ss_plugin_table_entry_t* dispatch_get_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key) -{ +static ss_plugin_table_entry_t* dispatch_get_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key) { auto t = static_cast(_t); return t->reader_ext->get_table_entry(t->table, key); } -static ss_plugin_rc dispatch_read_entry_field(ss_plugin_table_t* _t, ss_plugin_table_entry_t* e, const ss_plugin_table_field_t* f, ss_plugin_state_data* out) -{ +static ss_plugin_rc dispatch_read_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* e, + const ss_plugin_table_field_t* f, + ss_plugin_state_data* out) { auto t = static_cast(_t); return t->reader_ext->read_entry_field(t->table, e, f, out); } -static void dispatch_release_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* e) -{ +static void dispatch_release_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* e) { auto t = static_cast(_t); t->reader_ext->release_table_entry(t->table, e); } -static ss_plugin_bool dispatch_iterate_entries(ss_plugin_table_t* _t, ss_plugin_table_iterator_func_t it, ss_plugin_table_iterator_state_t* s) -{ +static ss_plugin_bool dispatch_iterate_entries(ss_plugin_table_t* _t, + ss_plugin_table_iterator_func_t it, + ss_plugin_table_iterator_state_t* s) { auto t = static_cast(_t); return t->reader_ext->iterate_entries(t->table, it, s); } -static ss_plugin_rc dispatch_clear(ss_plugin_table_t* _t) -{ +static ss_plugin_rc dispatch_clear(ss_plugin_table_t* _t) { auto t = static_cast(_t); return t->writer_ext->clear_table(t->table); } -static ss_plugin_rc dispatch_erase_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key) -{ +static ss_plugin_rc dispatch_erase_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key) { auto t = static_cast(_t); return t->writer_ext->erase_table_entry(t->table, key); } -static ss_plugin_table_entry_t* dispatch_create_table_entry(ss_plugin_table_t* _t) -{ +static ss_plugin_table_entry_t* dispatch_create_table_entry(ss_plugin_table_t* _t) { auto t = static_cast(_t); return t->writer_ext->create_table_entry(t->table); } -static void dispatch_destroy_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* e) -{ +static void dispatch_destroy_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* e) { auto t = static_cast(_t); return t->writer_ext->destroy_table_entry(t->table, e); } -static ss_plugin_table_entry_t* dispatch_add_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key, ss_plugin_table_entry_t* entry) -{ +static ss_plugin_table_entry_t* dispatch_add_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key, + ss_plugin_table_entry_t* entry) { auto t = static_cast(_t); return t->writer_ext->add_table_entry(t->table, key, entry); } -static ss_plugin_rc dispatch_write_entry_field(ss_plugin_table_t* _t, ss_plugin_table_entry_t* e, const ss_plugin_table_field_t* f, const ss_plugin_state_data* in) -{ +static ss_plugin_rc dispatch_write_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* e, + const ss_plugin_table_field_t* f, + const ss_plugin_state_data* in) { auto t = static_cast(_t); return t->writer_ext->write_entry_field(t->table, e, f, in); } @@ -1506,8 +1434,8 @@ static ss_plugin_rc dispatch_write_entry_field(ss_plugin_table_t* _t, ss_plugin_ // // sinsp_plugin table helpers implementation // -void sinsp_plugin::table_field_api(ss_plugin_table_fields_vtable& out, ss_plugin_table_fields_vtable_ext& extout) -{ +void sinsp_plugin::table_field_api(ss_plugin_table_fields_vtable& out, + ss_plugin_table_fields_vtable_ext& extout) { extout.list_table_fields = dispatch_list_fields; extout.add_table_field = dispatch_add_field; extout.get_table_field = dispatch_get_field; @@ -1517,8 +1445,8 @@ void sinsp_plugin::table_field_api(ss_plugin_table_fields_vtable& out, ss_plugin out.get_table_field = extout.get_table_field; } -void sinsp_plugin::table_read_api(ss_plugin_table_reader_vtable& out, ss_plugin_table_reader_vtable_ext& extout) -{ +void sinsp_plugin::table_read_api(ss_plugin_table_reader_vtable& out, + ss_plugin_table_reader_vtable_ext& extout) { extout.get_table_name = dispatch_get_name; extout.get_table_size = dispatch_get_size; extout.get_table_entry = dispatch_get_entry; @@ -1532,8 +1460,8 @@ void sinsp_plugin::table_read_api(ss_plugin_table_reader_vtable& out, ss_plugin_ out.read_entry_field = extout.read_entry_field; } -void sinsp_plugin::table_write_api(ss_plugin_table_writer_vtable& out, ss_plugin_table_writer_vtable_ext& extout) -{ +void sinsp_plugin::table_write_api(ss_plugin_table_writer_vtable& out, + ss_plugin_table_writer_vtable_ext& extout) { extout.clear_table = dispatch_clear; extout.erase_table_entry = dispatch_erase_entry; extout.create_table_entry = dispatch_create_table_entry; @@ -1548,14 +1476,12 @@ void sinsp_plugin::table_write_api(ss_plugin_table_writer_vtable& out, ss_plugin out.write_entry_field = extout.write_entry_field; } -ss_plugin_table_info* sinsp_plugin::table_api_list_tables(ss_plugin_owner_t* o, uint32_t* ntables) -{ +ss_plugin_table_info* sinsp_plugin::table_api_list_tables(ss_plugin_owner_t* o, uint32_t* ntables) { auto p = static_cast(o); __CATCH_ERR_MSG(p->m_last_owner_err, { *ntables = 0; p->m_table_infos.clear(); - for (const auto &d : p->m_table_registry->tables()) - { + for(const auto& d : p->m_table_registry->tables()) { ss_plugin_table_info info; info.name = d.second->name().c_str(); info.key_type = typeinfo_to_state_type(d.second->key_info()); @@ -1567,54 +1493,53 @@ ss_plugin_table_info* sinsp_plugin::table_api_list_tables(ss_plugin_owner_t* o, return NULL; } -ss_plugin_table_t* sinsp_plugin::table_api_get_table(ss_plugin_owner_t *o, const char *name, ss_plugin_state_type key_type) -{ +ss_plugin_table_t* sinsp_plugin::table_api_get_table(ss_plugin_owner_t* o, + const char* name, + ss_plugin_state_type key_type) { auto p = static_cast(o); - // if a plugin is accessing a plugin-owned table, we return it as-is - // instead of wrapping it. This is both more performant and safer from - // a memory ownership perspective, because the other plugin is the actual - // total owner of the table's memory. Note, even though dynamic_cast is - // generally quite expensive, the "get_table" primitive can only be - // used during plugin initialization, so it's not in the hot path. - #define _X(_type, _dtype) \ - { \ - auto t = p->m_table_registry->get_table<_type>(name); \ - if (!t) \ - { \ - return NULL; \ - } \ - p->m_accessed_tables[name].wrapper.set(p, t); \ - p->m_accessed_tables[name].update(); \ +// if a plugin is accessing a plugin-owned table, we return it as-is +// instead of wrapping it. This is both more performant and safer from +// a memory ownership perspective, because the other plugin is the actual +// total owner of the table's memory. Note, even though dynamic_cast is +// generally quite expensive, the "get_table" primitive can only be +// used during plugin initialization, so it's not in the hot path. +#define _X(_type, _dtype) \ + { \ + auto t = p->m_table_registry->get_table<_type>(name); \ + if(!t) { \ + return NULL; \ + } \ + p->m_accessed_tables[name].wrapper.set(p, t); \ + p->m_accessed_tables[name].update(); \ return static_cast(&p->m_accessed_tables[name].input); \ }; __CATCH_ERR_MSG(p->m_last_owner_err, { auto& tables = p->m_accessed_tables; auto it = tables.find(name); - if (it == tables.end()) - { + if(it == tables.end()) { __PLUGIN_STATETYPE_SWITCH(key_type); } return static_cast(&it->second.input); }); - #undef _X +#undef _X return NULL; } -ss_plugin_rc sinsp_plugin::table_api_add_table(ss_plugin_owner_t *o, const ss_plugin_table_input* in) -{ +ss_plugin_rc sinsp_plugin::table_api_add_table(ss_plugin_owner_t* o, + const ss_plugin_table_input* in) { auto p = static_cast(o); - #define _X(_type, _dtype) \ - { \ - auto t = new plugin_table_wrapper<_type>(p, in); \ - p->m_table_registry->add_table(t); \ +#define _X(_type, _dtype) \ + { \ + auto t = new plugin_table_wrapper<_type>(p, in); \ + p->m_table_registry->add_table(t); \ p->m_owned_tables[in->name] = std::unique_ptr(t); \ - break; \ + break; \ } __CATCH_ERR_MSG(p->m_last_owner_err, { __PLUGIN_STATETYPE_SWITCH(in->key_type); return SS_PLUGIN_SUCCESS; }); - #undef _X +#undef _X return SS_PLUGIN_FAILURE; } diff --git a/userspace/libsinsp/prefix_search.cpp b/userspace/libsinsp/prefix_search.cpp index 918e9e2bfe..0453c7fca7 100644 --- a/userspace/libsinsp/prefix_search.cpp +++ b/userspace/libsinsp/prefix_search.cpp @@ -22,65 +22,52 @@ limitations under the License. using namespace std; -void path_prefix_search::add_search_path(const char *path) -{ +void path_prefix_search::add_search_path(const char *path) { bool dummy = true; return path_prefix_map::add_search_path(path, dummy); } -void path_prefix_search::add_search_path(const filter_value_t &path) -{ +void path_prefix_search::add_search_path(const filter_value_t &path) { bool dummy = true; return path_prefix_map::add_search_path(path, dummy); } -void path_prefix_search::add_search_path(const std::string &str) -{ +void path_prefix_search::add_search_path(const std::string &str) { bool dummy = true; return path_prefix_map::add_search_path(str, dummy); } -bool path_prefix_search::match(const char *path) -{ +bool path_prefix_search::match(const char *path) { const bool *val = path_prefix_map::match(path); return (val != NULL); } -bool path_prefix_search::match(const filter_value_t &path) -{ +bool path_prefix_search::match(const filter_value_t &path) { const bool *val = path_prefix_map::match(path); return (val != NULL); } -std::string path_prefix_search::as_string() -{ +std::string path_prefix_search::as_string() { return path_prefix_map::as_string(false); } -void path_prefix_map_ut::split_path(const filter_value_t &path, filter_components_t &components) -{ +void path_prefix_map_ut::split_path(const filter_value_t &path, filter_components_t &components) { components.clear(); uint8_t *pos = path.first; - while (pos < path.first + path.second) - { - uint8_t *sep = (uint8_t *) memchr((char *) pos, '/', path.second - (pos - path.first)); + while(pos < path.first + path.second) { + uint8_t *sep = (uint8_t *)memchr((char *)pos, '/', path.second - (pos - path.first)); - if (sep) - { - if (sep-pos > 0) - { - components.emplace_back(std::string((const char *) pos, sep-pos)); + if(sep) { + if(sep - pos > 0) { + components.emplace_back(std::string((const char *)pos, sep - pos)); } pos = sep + 1; - } - else - { - components.emplace_back(std::string((const char *) pos, path.second - (pos - path.first))); + } else { + components.emplace_back( + std::string((const char *)pos, path.second - (pos - path.first))); pos = path.first + path.second + 1; } } } - - diff --git a/userspace/libsinsp/prefix_search.h b/userspace/libsinsp/prefix_search.h index 322fc1cac6..ffc0d5c3b4 100644 --- a/userspace/libsinsp/prefix_search.h +++ b/userspace/libsinsp/prefix_search.h @@ -29,13 +29,13 @@ limitations under the License. #include #include -namespace path_prefix_map_ut -{ - typedef std::list filter_components_t; +namespace path_prefix_map_ut { +typedef std::list filter_components_t; - // Split path /var/log/messages into a list of components (var, log, messages). Empty components are skipped. - void split_path(const filter_value_t &path, filter_components_t &components); -}; +// Split path /var/log/messages into a list of components (var, log, messages). Empty components are +// skipped. +void split_path(const filter_value_t &path, filter_components_t &components); +}; // namespace path_prefix_map_ut // // A data structure that allows testing a path P against a set of @@ -55,8 +55,7 @@ namespace path_prefix_map_ut // /var is a partial match but the search path is /var/run, not /var. template -class path_prefix_map -{ +class path_prefix_map { public: path_prefix_map(); virtual ~path_prefix_map(); @@ -68,53 +67,52 @@ class path_prefix_map // Similar to add_search_path, but takes a path already split // into a list of components. This allows for custom splitting // of paths other than on '/' boundaries. - void add_search_path_components(const path_prefix_map_ut::filter_components_t &components, Value &v); + void add_search_path_components(const path_prefix_map_ut::filter_components_t &components, + Value &v); // If non-NULL, Value is not allocated. It points to memory // held within this path_prefix_map() and is only valid as // long as the map exists. - Value * match(const char *path); - Value * match(const filter_value_t &path); + Value *match(const char *path); + Value *match(const filter_value_t &path); Value *match_components(const path_prefix_map_ut::filter_components_t &components); std::string as_string(bool include_vals); private: - std::string as_string(const std::string &prefix, bool include_vals); - std::string as_string(const std::string &prefix, bool include_vals, - const std::string& key, - std::pair& val); + std::string as_string(const std::string &prefix, + bool include_vals, + const std::string &key, + std::pair &val); - typedef std::unordered_map> path_map_t; + typedef std::unordered_map> path_map_t; // Only used for as_string() and consistent outputs - typedef std::map> ordered_path_map_t; + typedef std::map> ordered_path_map_t; void add_search_path_components(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp, - Value &v); + path_prefix_map_ut::filter_components_t::const_iterator comp, + Value &v); void add_search_path_components(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp, - Value &v, - path_map_t& dirs); + path_prefix_map_ut::filter_components_t::const_iterator comp, + Value &v, + path_map_t &dirs); Value *match_components(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp); + path_prefix_map_ut::filter_components_t::const_iterator comp); Value *match_components_direct(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp); + path_prefix_map_ut::filter_components_t::const_iterator comp); Value *match_components_glob(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp); + path_prefix_map_ut::filter_components_t::const_iterator comp); - Value *check_match_value(std::pair& val, - const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp); + Value *check_match_value(std::pair &val, + const path_prefix_map_ut::filter_components_t &components, + path_prefix_map_ut::filter_components_t::const_iterator comp); // This is used *only* for components that do not contain glob // characters. @@ -142,43 +140,35 @@ class path_prefix_map }; template -path_prefix_map::path_prefix_map() -{ -} +path_prefix_map::path_prefix_map() {} template -path_prefix_map::~path_prefix_map() -{ - for (auto &ent : m_dirs) - { +path_prefix_map::~path_prefix_map() { + for(auto &ent : m_dirs) { delete(ent.second.first); delete(ent.second.second); } - for (auto &ent : m_glob_dirs) - { + for(auto &ent : m_glob_dirs) { delete(ent.second.first); delete(ent.second.second); } } template -void path_prefix_map::add_search_path(const char *path, Value &v) -{ - filter_value_t mem((uint8_t *) path, (uint32_t) strlen(path)); +void path_prefix_map::add_search_path(const char *path, Value &v) { + filter_value_t mem((uint8_t *)path, (uint32_t)strlen(path)); return add_search_path(mem, v); } template -void path_prefix_map::add_search_path(const std::string &str, Value &v) -{ - filter_value_t mem((uint8_t *) str.c_str(), (uint32_t) str.length()); +void path_prefix_map::add_search_path(const std::string &str, Value &v) { + filter_value_t mem((uint8_t *)str.c_str(), (uint32_t)str.length()); return add_search_path(mem, v); } template -void path_prefix_map::add_search_path(const filter_value_t &path, Value &v) -{ +void path_prefix_map::add_search_path(const filter_value_t &path, Value &v) { path_prefix_map_ut::filter_components_t components; path_prefix_map_ut::split_path(path, components); @@ -193,34 +183,32 @@ void path_prefix_map::add_search_path(const filter_value_t &path, Value & } template -void path_prefix_map::add_search_path_components(const path_prefix_map_ut::filter_components_t &components, Value &v) -{ +void path_prefix_map::add_search_path_components( + const path_prefix_map_ut::filter_components_t &components, + Value &v) { add_search_path_components(components, components.begin(), v); } template -void path_prefix_map::add_search_path_components(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp, - Value &v) -{ +void path_prefix_map::add_search_path_components( + const path_prefix_map_ut::filter_components_t &components, + path_prefix_map_ut::filter_components_t::const_iterator comp, + Value &v) { // If the component contains glob wildcard characters, add it // to m_glob_dirs - if(comp->find_first_of("?*[") != std::string::npos) - { + if(comp->find_first_of("?*[") != std::string::npos) { add_search_path_components(components, comp, v, m_glob_dirs); - } - else - { + } else { add_search_path_components(components, comp, v, m_dirs); } } template -void path_prefix_map::add_search_path_components(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp, - Value &v, - path_prefix_map::path_map_t& dirs) -{ +void path_prefix_map::add_search_path_components( + const path_prefix_map_ut::filter_components_t &components, + path_prefix_map_ut::filter_components_t::const_iterator comp, + Value &v, + path_prefix_map::path_map_t &dirs) { path_prefix_map *subtree = NULL; // If the component contains glob wildcard characters, add it to m_glob_dirs @@ -229,44 +217,37 @@ void path_prefix_map::add_search_path_components(const path_prefix_map_ut auto cur = comp; comp++; - if(it == dirs.end()) - { + if(it == dirs.end()) { // This path component doesn't match any existing // dirent. We need to add one and its subtree. - if(comp != components.end()) - { + if(comp != components.end()) { subtree = new path_prefix_map(); subtree->add_search_path_components(components, comp, v); } // If the path doesn't have anything remaining, we // also add the value here. - dirs[*cur] = std::pair(subtree, (comp == components.end() ? new Value(v) : NULL)); - } - else - { + dirs[*cur] = std::pair( + subtree, + (comp == components.end() ? new Value(v) : NULL)); + } else { // An entry for this dirent already exists. We will // either add a new entry to the subtree, do nothing, // or get rid of the existing subtree. - if(comp == components.end()) - { + if(comp == components.end()) { // This path is a prefix of the current path and we // can drop the existing subtree. For example, we can // drop /usr/lib when adding /usr. delete(it->second.first); delete(it->second.second); dirs.erase(*cur); - dirs[*cur] = std::pair(NULL, new Value(v)); - } - else if(it->second.first == NULL) - { + dirs[*cur] = std::pair(NULL, new Value(v)); + } else if(it->second.first == NULL) { // The existing path is shorter than the // current path, in which case we don't have // to do anything. For example, no need to add // /usr/lib when /usr exists. - } - else - { + } else { // We need to add the remainder to the // sub-tree's search path. it->second.first->add_search_path_components(components, comp, v); @@ -275,15 +256,13 @@ void path_prefix_map::add_search_path_components(const path_prefix_map_ut } template -Value *path_prefix_map::match(const char *path) -{ - filter_value_t mem((uint8_t *) path, (uint32_t) strlen(path)); +Value *path_prefix_map::match(const char *path) { + filter_value_t mem((uint8_t *)path, (uint32_t)strlen(path)); return match(mem); } template -Value *path_prefix_map::match(const filter_value_t &path) -{ +Value *path_prefix_map::match(const filter_value_t &path) { path_prefix_map_ut::filter_components_t components; path_prefix_map_ut::split_path(path, components); @@ -298,20 +277,18 @@ Value *path_prefix_map::match(const filter_value_t &path) } template -Value *path_prefix_map::match_components(const path_prefix_map_ut::filter_components_t &components) -{ +Value *path_prefix_map::match_components( + const path_prefix_map_ut::filter_components_t &components) { return match_components(components, components.begin()); } template -Value *path_prefix_map::match_components(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp) -{ - +Value *path_prefix_map::match_components( + const path_prefix_map_ut::filter_components_t &components, + path_prefix_map_ut::filter_components_t::const_iterator comp) { Value *ret = match_components_direct(components, comp); - if (ret != NULL) - { + if(ret != NULL) { return ret; } @@ -319,32 +296,26 @@ Value *path_prefix_map::match_components(const path_prefix_map_ut::filter } template -Value *path_prefix_map::match_components_direct(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp) -{ +Value *path_prefix_map::match_components_direct( + const path_prefix_map_ut::filter_components_t &components, + path_prefix_map_ut::filter_components_t::const_iterator comp) { auto it = m_dirs.find(*comp); - if(it == m_dirs.end()) - { + if(it == m_dirs.end()) { return NULL; - } - else - { + } else { return check_match_value(it->second, components, ++comp); } } template -Value *path_prefix_map::match_components_glob(const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp) -{ - for(auto& it : m_glob_dirs) - { - if(sinsp_utils::glob_match(it.first.c_str(), comp->c_str(), false)) - { +Value *path_prefix_map::match_components_glob( + const path_prefix_map_ut::filter_components_t &components, + path_prefix_map_ut::filter_components_t::const_iterator comp) { + for(auto &it : m_glob_dirs) { + if(sinsp_utils::glob_match(it.first.c_str(), comp->c_str(), false)) { Value *v = check_match_value(it.second, components, ++comp); - if(v != NULL) - { + if(v != NULL) { return v; } } @@ -354,62 +325,50 @@ Value *path_prefix_map::match_components_glob(const path_prefix_map_ut::f } template -Value *path_prefix_map::check_match_value(std::pair& val, - const path_prefix_map_ut::filter_components_t &components, - path_prefix_map_ut::filter_components_t::const_iterator comp) -{ +Value *path_prefix_map::check_match_value( + std::pair &val, + const path_prefix_map_ut::filter_components_t &components, + path_prefix_map_ut::filter_components_t::const_iterator comp) { // If there is nothing left in the match path, the // subtree must be null. This ensures that /var // matches only /var and not /var/lib - if(comp == components.end()) - { - if(val.first == NULL) - { + if(comp == components.end()) { + if(val.first == NULL) { return val.second; - } - else - { + } else { return NULL; } - } - else if(val.first == NULL) - { + } else if(val.first == NULL) { // /foo/bar matched a prefix /foo, so we're // done. return val.second; - } - else - { + } else { return val.first->match_components(components, comp); } } - template -std::string path_prefix_map::as_string(bool include_vals) -{ +std::string path_prefix_map::as_string(bool include_vals) { return as_string(std::string(""), include_vals); } template -std::string path_prefix_map::as_string(const std::string& prefix, - bool include_vals, - const std::string& key, - std::pair& val) +std::string path_prefix_map::as_string(const std::string &prefix, + bool include_vals, + const std::string &key, + std::pair &val) { std::ostringstream os; os << prefix << key << " ->"; - if (include_vals && val.first == NULL) - { + if(include_vals && val.first == NULL) { os << " v=" << (*val.second); } os << std::endl; - if(val.first) - { + if(val.first) { std::string indent = prefix; indent += " "; os << val.first->as_string(indent, include_vals); @@ -419,27 +378,23 @@ std::string path_prefix_map::as_string(const std::string& prefix, }; template -std::string path_prefix_map::as_string(const std::string &prefix, bool include_vals) -{ +std::string path_prefix_map::as_string(const std::string &prefix, bool include_vals) { std::ostringstream os; ordered_path_map_t ordered_dirs(m_dirs.begin(), m_dirs.end()); - for (auto &it : ordered_dirs) - { + for(auto &it : ordered_dirs) { os << as_string(prefix, include_vals, it.first, it.second); } ordered_path_map_t ordered_glob_dirs(m_glob_dirs.begin(), m_glob_dirs.end()); - for (auto &it : ordered_glob_dirs) - { + for(auto &it : ordered_glob_dirs) { os << as_string(prefix, include_vals, it.first, it.second); } return os.str(); } -class path_prefix_search : public path_prefix_map -{ +class path_prefix_search : public path_prefix_map { public: path_prefix_search() = default; virtual ~path_prefix_search() = default; diff --git a/userspace/libsinsp/procfs_utils.cpp b/userspace/libsinsp/procfs_utils.cpp index 070303d9e5..c2a1715a56 100644 --- a/userspace/libsinsp/procfs_utils.cpp +++ b/userspace/libsinsp/procfs_utils.cpp @@ -22,12 +22,10 @@ limitations under the License. #include #include -int libsinsp::procfs_utils::get_userns_root_uid(std::istream& uid_map) -{ +int libsinsp::procfs_utils::get_userns_root_uid(std::istream& uid_map) { std::string uid_map_line; - while(std::getline(uid_map, uid_map_line)) - { + while(std::getline(uid_map, uid_map_line)) { int src_uid, target_uid; std::stringstream mapping(uid_map_line); mapping >> src_uid; @@ -35,8 +33,7 @@ int libsinsp::procfs_utils::get_userns_root_uid(std::istream& uid_map) // if the target uid we're looking for was anything other than 0, // we'd have to check the length of the range as well, but since // 0 is the lowest, we're good - if(src_uid != 0) - { + if(src_uid != 0) { continue; } mapping >> target_uid; @@ -47,43 +44,33 @@ int libsinsp::procfs_utils::get_userns_root_uid(std::istream& uid_map) return libsinsp::procfs_utils::NO_MATCH; } - // // ns_helper // -libsinsp::procfs_utils::ns_helper::ns_helper(const std::string& host_root): - m_host_root(host_root) -{ +libsinsp::procfs_utils::ns_helper::ns_helper(const std::string& host_root): m_host_root(host_root) { struct stat rootlink; - if(-1 == stat((m_host_root + "/proc/1/root").c_str(), &rootlink)) - { + if(-1 == stat((m_host_root + "/proc/1/root").c_str(), &rootlink)) { libsinsp_logger()->format(sinsp_logger::SEV_WARNING, - "Cannot read host init process proc root: %d", errno); + "Cannot read host init process proc root: %d", + errno); m_cannot_read_host_init_ns_mnt = true; - } - else - { + } else { m_host_init_root_inode = rootlink.st_ino; } } -bool libsinsp::procfs_utils::ns_helper::in_own_ns_mnt(int64_t pid) const -{ - if(m_cannot_read_host_init_ns_mnt) - { +bool libsinsp::procfs_utils::ns_helper::in_own_ns_mnt(int64_t pid) const { + if(m_cannot_read_host_init_ns_mnt) { return false; } struct stat rootlink; - if(-1 == stat(get_pid_root(pid).c_str(), &rootlink)) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "Cannot read process proc root"); + if(-1 == stat(get_pid_root(pid).c_str(), &rootlink)) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "Cannot read process proc root"); return false; } - if(static_cast(rootlink.st_ino) == m_host_init_root_inode) - { + if(static_cast(rootlink.st_ino) == m_host_init_root_inode) { // Still in the host namespace return false; } diff --git a/userspace/libsinsp/procfs_utils.h b/userspace/libsinsp/procfs_utils.h index e7beb259ae..fa7a48e693 100644 --- a/userspace/libsinsp/procfs_utils.h +++ b/userspace/libsinsp/procfs_utils.h @@ -24,21 +24,16 @@ int get_userns_root_uid(std::istream& uid_map); /** * @brief Access container data through proc */ -class ns_helper -{ +class ns_helper { public: ns_helper(const std::string& host_root); - bool can_read_host_init_ns_mnt() const - { - return !m_cannot_read_host_init_ns_mnt; - } + bool can_read_host_init_ns_mnt() const { return !m_cannot_read_host_init_ns_mnt; } //! Return true if not in the host init mount namespace bool in_own_ns_mnt(int64_t pid) const; - std::string get_pid_root(int64_t pid) const - { + std::string get_pid_root(int64_t pid) const { return m_host_root + "/proc/" + std::to_string(pid) + "/root"; } @@ -48,5 +43,5 @@ class ns_helper int64_t m_host_init_root_inode{-1}; }; -} // namespace procfs_utils -} // namespace libsinsp +} // namespace procfs_utils +} // namespace libsinsp diff --git a/userspace/libsinsp/runc.cpp b/userspace/libsinsp/runc.cpp index 24e97aa028..178dea09e2 100644 --- a/userspace/libsinsp/runc.cpp +++ b/userspace/libsinsp/runc.cpp @@ -27,11 +27,12 @@ namespace { const size_t CONTAINER_ID_LENGTH = 64; const size_t REPORTED_CONTAINER_ID_LENGTH = 12; -const char* CONTAINER_ID_VALID_CHARACTERS = "0123456789abcdefABCDEF"; +const char *CONTAINER_ID_VALID_CHARACTERS = "0123456789abcdefABCDEF"; -static_assert(REPORTED_CONTAINER_ID_LENGTH <= CONTAINER_ID_LENGTH, "Reported container ID length cannot be longer than actual length"); +static_assert(REPORTED_CONTAINER_ID_LENGTH <= CONTAINER_ID_LENGTH, + "Reported container ID length cannot be longer than actual length"); -} +} // namespace namespace libsinsp { namespace runc { @@ -39,29 +40,27 @@ namespace runc { // check if cgroup ends with // If true, set to a truncated version of the id and return true. // Otherwise return false and leave container_id unchanged -bool match_one_container_id(const std::string &cgroup, const std::string &prefix, const std::string &suffix, std::string &container_id) -{ +bool match_one_container_id(const std::string &cgroup, + const std::string &prefix, + const std::string &suffix, + std::string &container_id) { size_t start_pos = cgroup.rfind(prefix); - if (start_pos == std::string::npos) - { + if(start_pos == std::string::npos) { return false; } start_pos += prefix.size(); size_t end_pos = cgroup.rfind(suffix); - if (end_pos == std::string::npos) - { + if(end_pos == std::string::npos) { return false; } - if (end_pos - start_pos != CONTAINER_ID_LENGTH) - { + if(end_pos - start_pos != CONTAINER_ID_LENGTH) { return false; } size_t invalid_ch_pos = cgroup.find_first_not_of(CONTAINER_ID_VALID_CHARACTERS, start_pos); - if (invalid_ch_pos < CONTAINER_ID_LENGTH) - { + if(invalid_ch_pos < CONTAINER_ID_LENGTH) { return false; } @@ -69,25 +68,23 @@ bool match_one_container_id(const std::string &cgroup, const std::string &prefix return true; } -bool match_container_id(const std::string &cgroup, const libsinsp::runc::cgroup_layout *layout, - std::string &container_id) -{ - for(size_t i = 0; layout[i].prefix && layout[i].suffix; ++i) - { - if(match_one_container_id(cgroup, layout[i].prefix, layout[i].suffix, container_id)) - { +bool match_container_id(const std::string &cgroup, + const libsinsp::runc::cgroup_layout *layout, + std::string &container_id) { + for(size_t i = 0; layout[i].prefix && layout[i].suffix; ++i) { + if(match_one_container_id(cgroup, layout[i].prefix, layout[i].suffix, container_id)) { return true; } } return false; } -bool matches_runc_cgroups(const sinsp_threadinfo *tinfo, const cgroup_layout *layout, std::string &container_id, std::string &matching_cgroup) -{ - for(const auto &it : tinfo->cgroups()) - { - if(match_container_id(it.second, layout, container_id)) - { +bool matches_runc_cgroups(const sinsp_threadinfo *tinfo, + const cgroup_layout *layout, + std::string &container_id, + std::string &matching_cgroup) { + for(const auto &it : tinfo->cgroups()) { + if(match_container_id(it.second, layout, container_id)) { matching_cgroup = it.second; return true; } @@ -95,5 +92,5 @@ bool matches_runc_cgroups(const sinsp_threadinfo *tinfo, const cgroup_layout *la return false; } -} -} +} // namespace runc +} // namespace libsinsp diff --git a/userspace/libsinsp/runc.h b/userspace/libsinsp/runc.h index 07feeba921..8e3e52c870 100644 --- a/userspace/libsinsp/runc.h +++ b/userspace/libsinsp/runc.h @@ -39,8 +39,8 @@ namespace runc { * (the last one must be a pair of null pointers to mark the end of the array) */ struct cgroup_layout { - const char* prefix; - const char* suffix; + const char *prefix; + const char *suffix; }; /** @@ -52,7 +52,10 @@ struct cgroup_layout { * the truncated hex string (first 12 digits). Otherwise, it will remain * unchanged. */ -bool match_one_container_id(const std::string &cgroup, const std::string &prefix, const std::string &suffix, std::string &container_id); +bool match_one_container_id(const std::string &cgroup, + const std::string &prefix, + const std::string &suffix, + std::string &container_id); /** * @brief Match `cgroup` against a list of layouts using `match_one_container_id()` @@ -66,8 +69,9 @@ bool match_one_container_id(const std::string &cgroup, const std::string &prefix * the truncated hex string (first 12 digits). Otherwise, it will remain * unchanged. */ -bool match_container_id(const std::string &cgroup, const libsinsp::runc::cgroup_layout *layout, - std::string &container_id); +bool match_container_id(const std::string &cgroup, + const libsinsp::runc::cgroup_layout *layout, + std::string &container_id); /** * @brief Match all the cgroups of `tinfo` against a list of cgroup layouts @@ -80,6 +84,9 @@ bool match_container_id(const std::string &cgroup, const libsinsp::runc::cgroup_ * the truncated hex string (first 12 digits). Otherwise, it will remain * unchanged. */ -bool matches_runc_cgroups(const sinsp_threadinfo *tinfo, const cgroup_layout *layout, std::string &container_id, std::string &matching_cgroup); -} -} +bool matches_runc_cgroups(const sinsp_threadinfo *tinfo, + const cgroup_layout *layout, + std::string &container_id, + std::string &matching_cgroup); +} // namespace runc +} // namespace libsinsp diff --git a/userspace/libsinsp/scap_open_exception.h b/userspace/libsinsp/scap_open_exception.h index 8c86687a66..ac6e33b051 100644 --- a/userspace/libsinsp/scap_open_exception.h +++ b/userspace/libsinsp/scap_open_exception.h @@ -23,23 +23,17 @@ limitations under the License. \brief Instances of this exception are thrown when calls to scap_open() fail. The given scap_rc is the error value returned from scap_open(). */ -class scap_open_exception : public sinsp_exception -{ +class scap_open_exception : public sinsp_exception { public: scap_open_exception(const std::string& error_str, const int32_t scap_rc): - sinsp_exception(error_str), - m_scap_rc(scap_rc) - { } + sinsp_exception(error_str), + m_scap_rc(scap_rc) {} scap_open_exception(const char* const error_str, const int32_t scap_rc): - sinsp_exception(error_str), - m_scap_rc(scap_rc) - { } - - int32_t scap_rc() const - { - return m_scap_rc; - } + sinsp_exception(error_str), + m_scap_rc(scap_rc) {} + + int32_t scap_rc() const { return m_scap_rc; } private: int32_t m_scap_rc; diff --git a/userspace/libsinsp/settings.h b/userspace/libsinsp/settings.h index 713a1d0a08..b2725ff81a 100644 --- a/userspace/libsinsp/settings.h +++ b/userspace/libsinsp/settings.h @@ -53,4 +53,3 @@ limitations under the License. // Port range to enable larger snaplen on // #define DEFAULT_INCREASE_SNAPLEN_PORT_RANGE {0, 0} - diff --git a/userspace/libsinsp/sinsp.cpp b/userspace/libsinsp/sinsp.cpp index b5ac697fbd..048db5a3f6 100644 --- a/userspace/libsinsp/sinsp.cpp +++ b/userspace/libsinsp/sinsp.cpp @@ -39,7 +39,7 @@ limitations under the License. #include #include #include -#endif // _WIN32 +#endif // _WIN32 #include #include @@ -53,29 +53,32 @@ limitations under the License. * one of kernel events. As such, this size value is assigned to a number that's * big enough to prevent the queue to ever fill-up in standard circumstances, * while at the same time avoiding it growing uncontrollably in case of anomalies. -*/ + */ #define DEFAULT_ASYNC_EVENT_QUEUE_SIZE 1000 -int32_t on_new_entry_from_proc(void* context, char* error, int64_t tid, scap_threadinfo* tinfo, scap_fdinfo* fdinfo, - scap_threadinfo** new_tinfo); +int32_t on_new_entry_from_proc(void* context, + char* error, + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo, + scap_threadinfo** new_tinfo); /////////////////////////////////////////////////////////////////////////////// // sinsp implementation /////////////////////////////////////////////////////////////////////////////// std::atomic sinsp::instance_count{0}; -sinsp::sinsp(bool with_metrics) : - m_external_event_processor(), - m_sinsp_stats_v2(with_metrics ? std::make_shared() : nullptr), - m_evt(this), - m_lastevent_ts(0), - m_host_root(scap_get_host_root()), - m_container_manager(this), - m_usergroup_manager(this), - m_async_events_queue(DEFAULT_ASYNC_EVENT_QUEUE_SIZE), - m_suppressed_comms(), - m_inited(false) -{ +sinsp::sinsp(bool with_metrics): + m_external_event_processor(), + m_sinsp_stats_v2(with_metrics ? std::make_shared() : nullptr), + m_evt(this), + m_lastevent_ts(0), + m_host_root(scap_get_host_root()), + m_container_manager(this), + m_usergroup_manager(this), + m_async_events_queue(DEFAULT_ASYNC_EVENT_QUEUE_SIZE), + m_suppressed_comms(), + m_inited(false) { ++instance_count; #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) // used by container_manager @@ -137,91 +140,71 @@ sinsp::sinsp(bool with_metrics) : #else m_thread_pool = nullptr; #endif - } -sinsp::~sinsp() -{ +sinsp::~sinsp() { close(); m_container_manager.cleanup(); #if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__) curl_global_cleanup(); - if (--instance_count == 0) - { + if(--instance_count == 0) { sinsp_dns_manager::get().cleanup(); } #endif } -bool sinsp::is_initialstate_event(scap_evt* pevent) const -{ - return pevent->type == PPME_CONTAINER_E || - pevent->type == PPME_CONTAINER_JSON_E || - pevent->type == PPME_CONTAINER_JSON_2_E || - pevent->type == PPME_USER_ADDED_E || - pevent->type == PPME_USER_DELETED_E || - pevent->type == PPME_GROUP_ADDED_E || - pevent->type == PPME_GROUP_DELETED_E; +bool sinsp::is_initialstate_event(scap_evt* pevent) const { + return pevent->type == PPME_CONTAINER_E || pevent->type == PPME_CONTAINER_JSON_E || + pevent->type == PPME_CONTAINER_JSON_2_E || pevent->type == PPME_USER_ADDED_E || + pevent->type == PPME_USER_DELETED_E || pevent->type == PPME_GROUP_ADDED_E || + pevent->type == PPME_GROUP_DELETED_E; } -void sinsp::consume_initialstate_events() -{ +void sinsp::consume_initialstate_events() { scap_evt* pevent; uint16_t pcpuid; sinsp_evt* tevt; uint32_t flags; - if (m_external_event_processor) - { + if(m_external_event_processor) { m_external_event_processor->on_capture_start(); } // // Consume every state event we have // - while(true) - { + while(true) { int32_t res = scap_next(m_h, &pevent, &pcpuid, &flags); - if(res == SCAP_SUCCESS) - { + if(res == SCAP_SUCCESS) { // Setting these to non-null will make sinsp::next use them as a scap event // to avoid a call to scap_next. In this way, we can avoid the state parsing phase // once we reach a container-unrelated event. m_replay_scap_evt = pevent; m_replay_scap_cpuid = pcpuid; m_replay_scap_flags = flags; - if(!is_initialstate_event(pevent)) - { + if(!is_initialstate_event(pevent)) { break; - } - else - { + } else { next(&tevt); continue; } - } - else - { + } else { break; } } } -void sinsp::init() -{ +void sinsp::init() { // // Retrieve machine information // m_machine_info = scap_get_machine_info(get_scap_platform()); - if(m_machine_info != NULL) - { + if(m_machine_info != NULL) { m_num_cpus = m_machine_info->num_cpus; - } - else - { + } else { ASSERT(false); m_num_cpus = 0; } @@ -230,8 +213,7 @@ void sinsp::init() // Retrieve agent information // m_agent_info = scap_get_agent_info(get_scap_platform()); - if (m_agent_info == NULL) - { + if(m_agent_info == NULL) { ASSERT(false); } @@ -250,8 +232,7 @@ void sinsp::init() // importing the thread table, so that thread table filtering will work with // container filters // - if(is_capture()) - { + if(is_capture()) { consume_initialstate_events(); } @@ -268,16 +249,14 @@ void sinsp::init() m_thread_manager->fix_sockets_coming_from_proc(); // If we are in capture, this is already called by consume_initialstate_events - if (!is_capture() && m_external_event_processor) - { + if(!is_capture() && m_external_event_processor) { m_external_event_processor->on_capture_start(); } // // If m_snaplen was modified, we set snaplen now // - if(m_snaplen != DEFAULT_SNAPLEN) - { + if(m_snaplen != DEFAULT_SNAPLEN) { set_snaplen(m_snaplen); } @@ -285,8 +264,7 @@ void sinsp::init() // If the port range for increased snaplen was modified, set it now // #ifndef _WIN32 - if(increased_snaplen_port_range_set()) - { + if(increased_snaplen_port_range_set()) { set_fullcapture_port_range(m_increased_snaplen_port_range.range_start, m_increased_snaplen_port_range.range_end); } @@ -295,13 +273,11 @@ void sinsp::init() // // If the statsd port was modified, push it to the kernel now. // - if(m_statsd_port != -1) - { + if(m_statsd_port != -1) { set_statsd_port(m_statsd_port); } - if(is_live()) - { + if(is_live()) { int32_t res = scap_getpid_global(get_scap_platform(), &m_self_pid); ASSERT(res == SCAP_SUCCESS || res == SCAP_NOT_SUPPORTED); (void)res; @@ -309,17 +285,17 @@ void sinsp::init() m_inited = true; } -void sinsp::set_import_users(bool import_users, bool user_details) -{ +void sinsp::set_import_users(bool import_users, bool user_details) { m_usergroup_manager.m_import_users = import_users; m_usergroup_manager.m_user_details_enabled = user_details; } /*=============================== OPEN METHODS ===============================*/ -void sinsp::open_common(scap_open_args* oargs, const scap_vtable* vtable, scap_platform* platform, - sinsp_mode_t mode) -{ +void sinsp::open_common(scap_open_args* oargs, + const scap_vtable* vtable, + scap_platform* platform, + sinsp_mode_t mode) { libsinsp_logger()->log("Trying to open the right engine!"); /* Reset the thread manager */ @@ -338,14 +314,12 @@ void sinsp::open_common(scap_open_args* oargs, const scap_vtable* vtable, scap_p oargs->proc_scan_log_interval_ms = m_proc_scan_log_interval_ms; m_h = scap_alloc(); - if(m_h == NULL) - { + if(m_h == NULL) { throw scap_open_exception("failed to allocate scap handle", SCAP_FAILURE); } int32_t scap_rc = scap_init(m_h, oargs, vtable); - if(scap_rc != SCAP_SUCCESS) - { + if(scap_rc != SCAP_SUCCESS) { scap_platform_close(platform); scap_platform_free(platform); m_platform = nullptr; @@ -353,8 +327,7 @@ void sinsp::open_common(scap_open_args* oargs, const scap_vtable* vtable, scap_p std::string error = scap_getlasterr(m_h); scap_close(m_h); m_h = NULL; - if(error.empty()) - { + if(error.empty()) { error = "Initialization issues during scap_init"; } throw scap_open_exception(error, scap_rc); @@ -362,8 +335,7 @@ void sinsp::open_common(scap_open_args* oargs, const scap_vtable* vtable, scap_p m_platform = platform; scap_rc = scap_platform_init(platform, m_platform_lasterr, m_h->m_engine, oargs); - if(scap_rc != SCAP_SUCCESS) - { + if(scap_rc != SCAP_SUCCESS) { scap_platform_close(platform); scap_platform_free(platform); m_platform = nullptr; @@ -380,72 +352,58 @@ void sinsp::open_common(scap_open_args* oargs, const scap_vtable* vtable, scap_p // that capability. Meta-events are considered only during live captures, // because offline captures will have the async events already encoded // in the event stream. - if (!is_capture()) - { + if(!is_capture()) { // note(jasondellaluce,rohith-raju): for now the emscripten build does not support // tbb queues, so async event production is disabled - for (auto& p : m_plugin_manager->plugins()) - { - if (p->caps() & CAP_ASYNC) - { - auto res = p->set_async_event_handler([this](auto& p, auto e){ + for(auto& p : m_plugin_manager->plugins()) { + if(p->caps() & CAP_ASYNC) { + auto res = p->set_async_event_handler([this](auto& p, auto e) { this->handle_plugin_async_event(p, std::move(e)); }); - if (!res) - { - throw sinsp_exception("can't set async event handler for plugin '" - + p->name() + "' : " + p->get_last_error()); + if(!res) { + throw sinsp_exception("can't set async event handler for plugin '" + p->name() + + "' : " + p->get_last_error()); } } } } // notify registered plugins of capture open - for (auto& p : m_plugin_manager->plugins()) - { + for(auto& p : m_plugin_manager->plugins()) { p->capture_open(); } } -void sinsp::mark_ppm_sc_of_interest(ppm_sc_code ppm_sc, bool enable) -{ +void sinsp::mark_ppm_sc_of_interest(ppm_sc_code ppm_sc, bool enable) { /* This API must be used only after the initialization phase. */ - if (!m_inited) - { + if(!m_inited) { throw sinsp_exception("you cannot use this method before opening the inspector!"); } - if (ppm_sc >= PPM_SC_MAX) - { + if(ppm_sc >= PPM_SC_MAX) { throw sinsp_exception("inexistent ppm_sc code: " + std::to_string(ppm_sc)); } int ret = scap_set_ppm_sc(m_h, ppm_sc, enable); - if (ret != SCAP_SUCCESS) - { + if(ret != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } - -static void fill_ppm_sc_of_interest(scap_open_args *oargs, const libsinsp::events::set &ppm_sc_of_interest) -{ - for (int i = 0; i < PPM_SC_MAX; i++) - { +static void fill_ppm_sc_of_interest(scap_open_args* oargs, + const libsinsp::events::set& ppm_sc_of_interest) { + for(int i = 0; i < PPM_SC_MAX; i++) { /* If the set is empty, fallback to all interesting syscalls */ - if (ppm_sc_of_interest.empty()) - { + if(ppm_sc_of_interest.empty()) { oargs->ppm_sc_of_interest.ppm_sc[i] = true; - } - else - { + } else { oargs->ppm_sc_of_interest.ppm_sc[i] = ppm_sc_of_interest.contains((ppm_sc_code)i); } } } -void sinsp::open_kmod(unsigned long driver_buffer_bytes_dim, const libsinsp::events::set &ppm_sc_of_interest) -{ +void sinsp::open_kmod(unsigned long driver_buffer_bytes_dim, + const libsinsp::events::set& ppm_sc_of_interest) { #ifdef HAS_ENGINE_KMOD - scap_open_args oargs {}; + scap_open_args oargs{}; /* Set interesting syscalls and tracepoints. */ fill_ppm_sc_of_interest(&oargs, ppm_sc_of_interest); @@ -456,8 +414,7 @@ void sinsp::open_kmod(unsigned long driver_buffer_bytes_dim, const libsinsp::eve oargs.engine_params = ¶ms; scap_platform* platform = scap_linux_alloc_platform(::on_new_entry_from_proc, this); - if(platform) - { + if(platform) { auto linux_plat = (scap_linux_platform*)platform; linux_plat->m_linux_vtable = &scap_kmod_linux_vtable; } @@ -468,16 +425,17 @@ void sinsp::open_kmod(unsigned long driver_buffer_bytes_dim, const libsinsp::eve #endif } -void sinsp::open_bpf(const std::string& bpf_path, unsigned long driver_buffer_bytes_dim, const libsinsp::events::set &ppm_sc_of_interest) -{ +void sinsp::open_bpf(const std::string& bpf_path, + unsigned long driver_buffer_bytes_dim, + const libsinsp::events::set& ppm_sc_of_interest) { #ifdef HAS_ENGINE_BPF /* Validate the BPF path. */ - if(bpf_path.empty()) - { - throw sinsp_exception("When you use the 'BPF' engine you need to provide a path to the bpf object file."); + if(bpf_path.empty()) { + throw sinsp_exception( + "When you use the 'BPF' engine you need to provide a path to the bpf object file."); } - scap_open_args oargs {}; + scap_open_args oargs{}; /* Set interesting syscalls and tracepoints. */ fill_ppm_sc_of_interest(&oargs, ppm_sc_of_interest); @@ -495,22 +453,17 @@ void sinsp::open_bpf(const std::string& bpf_path, unsigned long driver_buffer_by #endif } -void sinsp::open_nodriver(bool full_proc_scan) -{ +void sinsp::open_nodriver(bool full_proc_scan) { #ifdef HAS_ENGINE_NODRIVER - scap_open_args oargs {}; + scap_open_args oargs{}; scap_platform* platform = scap_linux_alloc_platform(::on_new_entry_from_proc, this); - if(platform) - { - if(!full_proc_scan) - { + if(platform) { + if(!full_proc_scan) { auto linux_plat = (scap_linux_platform*)platform; linux_plat->m_fd_lookup_limit = SCAP_NODRIVER_MAX_FD_LOOKUP; linux_plat->m_minimal_scan = true; } - } - else - { + } else { platform = scap_generic_alloc_platform(::on_new_entry_from_proc, this); } @@ -520,27 +473,23 @@ void sinsp::open_nodriver(bool full_proc_scan) #endif } -void sinsp::open_savefile(const std::string& filename, int fd) -{ +void sinsp::open_savefile(const std::string& filename, int fd) { #ifdef HAS_ENGINE_SAVEFILE - scap_open_args oargs {}; + scap_open_args oargs{}; scap_savefile_engine_params params; m_input_filename = filename; m_input_fd = fd; /* default is 0. */ - if(m_input_fd != 0) - { + if(m_input_fd != 0) { /* In this case, we can't get a reliable filesize */ params.fd = m_input_fd; params.fname = NULL; m_filesize = 0; - } - else - { - if(filename.empty()) - { - throw sinsp_exception("When you use the 'savefile' engine you need to provide a path to the file."); + } else { + if(filename.empty()) { + throw sinsp_exception( + "When you use the 'savefile' engine you need to provide a path to the file."); } params.fname = filename.c_str(); @@ -548,8 +497,7 @@ void sinsp::open_savefile(const std::string& filename, int fd) char error[SCAP_LASTERR_SIZE] = {0}; m_filesize = get_file_size(params.fname, error); - if(m_filesize < 0) - { + if(m_filesize < 0) { throw sinsp_exception(error); } } @@ -566,11 +514,11 @@ void sinsp::open_savefile(const std::string& filename, int fd) #endif } -void sinsp::open_plugin(const std::string& plugin_name, const std::string& plugin_open_params, - sinsp_plugin_platform platform_type) -{ +void sinsp::open_plugin(const std::string& plugin_name, + const std::string& plugin_open_params, + sinsp_plugin_platform platform_type) { #ifdef HAS_ENGINE_SOURCE_PLUGIN - scap_open_args oargs {}; + scap_open_args oargs{}; scap_source_plugin_engine_params params; set_input_plugin(plugin_name, plugin_open_params); params.input_plugin = &m_input_plugin->as_scap_source(); @@ -579,8 +527,7 @@ void sinsp::open_plugin(const std::string& plugin_name, const std::string& plugi scap_platform* platform; sinsp_mode_t mode; - switch(platform_type) - { + switch(platform_type) { case sinsp_plugin_platform::SINSP_PLATFORM_GENERIC: mode = SINSP_MODE_PLUGIN; platform = scap_generic_alloc_platform(::on_new_entry_from_proc, this); @@ -602,15 +549,17 @@ void sinsp::open_plugin(const std::string& plugin_name, const std::string& plugi #endif } -void sinsp::open_gvisor(const std::string& config_path, const std::string& root_path, bool no_events, int epoll_timeout) -{ +void sinsp::open_gvisor(const std::string& config_path, + const std::string& root_path, + bool no_events, + int epoll_timeout) { #ifdef HAS_ENGINE_GVISOR - if(config_path.empty()) - { - throw sinsp_exception("When you use the 'gvisor' engine you need to provide a path to the config file."); + if(config_path.empty()) { + throw sinsp_exception( + "When you use the 'gvisor' engine you need to provide a path to the config file."); } - scap_open_args oargs {}; + scap_open_args oargs{}; scap_gvisor_engine_params params; params.gvisor_root_path = root_path.c_str(); params.gvisor_config_path = config_path.c_str(); @@ -630,10 +579,12 @@ void sinsp::open_gvisor(const std::string& config_path, const std::string& root_ #endif } -void sinsp::open_modern_bpf(unsigned long driver_buffer_bytes_dim, uint16_t cpus_for_each_buffer, bool online_only, const libsinsp::events::set &ppm_sc_of_interest) -{ +void sinsp::open_modern_bpf(unsigned long driver_buffer_bytes_dim, + uint16_t cpus_for_each_buffer, + bool online_only, + const libsinsp::events::set& ppm_sc_of_interest) { #ifdef HAS_ENGINE_MODERN_BPF - scap_open_args oargs {}; + scap_open_args oargs{}; /* Set interesting syscalls and tracepoints. */ fill_ppm_sc_of_interest(&oargs, ppm_sc_of_interest); @@ -652,17 +603,15 @@ void sinsp::open_modern_bpf(unsigned long driver_buffer_bytes_dim, uint16_t cpus #endif } -void sinsp::open_test_input(scap_test_input_data* data, sinsp_mode_t mode) -{ +void sinsp::open_test_input(scap_test_input_data* data, sinsp_mode_t mode) { #ifdef HAS_ENGINE_TEST_INPUT - scap_open_args oargs {}; + scap_open_args oargs{}; scap_test_input_engine_params params; params.test_input_data = data; oargs.engine_params = ¶ms; scap_platform* platform; - switch(mode) - { + switch(mode) { case SINSP_MODE_TEST: platform = scap_test_input_alloc_platform(::on_new_entry_from_proc, this); break; @@ -684,24 +633,20 @@ void sinsp::open_test_input(scap_test_input_data* data, sinsp_mode_t mode) /*=============================== Engine related ===============================*/ -bool sinsp::check_current_engine(const std::string& engine_name) const -{ +bool sinsp::check_current_engine(const std::string& engine_name) const { return scap_check_current_engine(m_h, engine_name.data()); } /*=============================== Engine related ===============================*/ -std::string sinsp::generate_gvisor_config(const std::string& socket_path) -{ +std::string sinsp::generate_gvisor_config(const std::string& socket_path) { return gvisor_config::generate(socket_path); } -int64_t sinsp::get_file_size(const std::string& fname, char *error) -{ +int64_t sinsp::get_file_size(const std::string& fname, char* error) { std::error_code ec; auto sz = std::filesystem::file_size(fname, ec); - if(ec) - { + if(ec) { strlcpy(error, ec.message().c_str(), SCAP_LASTERR_SIZE); return -1; } @@ -710,65 +655,56 @@ int64_t sinsp::get_file_size(const std::string& fname, char *error) unsigned sinsp::m_num_possible_cpus = 0; -unsigned sinsp::num_possible_cpus() -{ - if(m_num_possible_cpus == 0) - { +unsigned sinsp::num_possible_cpus() { + if(m_num_possible_cpus == 0) { m_num_possible_cpus = read_num_possible_cpus(); - if(m_num_possible_cpus == 0) - { - libsinsp_logger()->log("Unable to read num_possible_cpus, falling back to 128", sinsp_logger::SEV_WARNING); + if(m_num_possible_cpus == 0) { + libsinsp_logger()->log("Unable to read num_possible_cpus, falling back to 128", + sinsp_logger::SEV_WARNING); m_num_possible_cpus = 128; } } return m_num_possible_cpus; } -std::vector sinsp::get_n_tracepoint_hit() const -{ +std::vector sinsp::get_n_tracepoint_hit() const { std::vector ret(num_possible_cpus(), 0); - if(scap_get_n_tracepoint_hit(m_h, ret.data()) != SCAP_SUCCESS) - { + if(scap_get_n_tracepoint_hit(m_h, ret.data()) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } return ret; } -std::string sinsp::get_error_desc(const std::string& msg) -{ +std::string sinsp::get_error_desc(const std::string& msg) { #ifdef _WIN32 - DWORD err_no = GetLastError(); // first, so error is not wiped out by intermediate calls + DWORD err_no = GetLastError(); // first, so error is not wiped out by intermediate calls std::string errstr = msg; - DWORD flg = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; + DWORD flg = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS; LPTSTR msg_buf = 0; if(FormatMessageA(flg, 0, err_no, 0, (LPTSTR)&msg_buf, 0, NULL)) - if(msg_buf) - { - errstr.append(msg_buf, strlen(msg_buf)); - LocalFree(msg_buf); - } + if(msg_buf) { + errstr.append(msg_buf, strlen(msg_buf)); + LocalFree(msg_buf); + } #else - char* msg_buf = strerror(errno); // first, so error is not wiped out by intermediate calls + char* msg_buf = strerror(errno); // first, so error is not wiped out by intermediate calls std::string errstr = msg; - if(msg_buf) - { + if(msg_buf) { errstr.append(msg_buf, strlen(msg_buf)); } #endif return errstr; } -void sinsp::close() -{ - if(m_platform) - { +void sinsp::close() { + if(m_platform) { scap_platform_close(m_platform); scap_platform_free(m_platform); m_platform = nullptr; } - if(m_h) - { + if(m_h) { scap_close(m_h); m_h = NULL; } @@ -780,39 +716,32 @@ void sinsp::close() m_filter.reset(); // unset the meta-event callback to all plugins that support it - if (!is_capture() && m_mode != SINSP_MODE_NONE) - { + if(!is_capture() && m_mode != SINSP_MODE_NONE) { std::string err; - for (auto& p : m_plugin_manager->plugins()) - { - if (p->caps() & CAP_ASYNC) - { + for(auto& p : m_plugin_manager->plugins()) { + if(p->caps() & CAP_ASYNC) { // collect errors but let's make sure we reset all the handlers // event in case of one failure. auto res = p->set_async_event_handler(nullptr); - if (!res) - { + if(!res) { err += err.empty() ? "" : ", "; - err += "can't reset async event handler for plugin '" - + p->name() + "' : " + p->get_last_error(); + err += "can't reset async event handler for plugin '" + p->name() + + "' : " + p->get_last_error(); } } } - if (!err.empty()) - { + if(!err.empty()) { throw sinsp_exception(err); } } // notify registered plugins of capture close - for (auto& p : m_plugin_manager->plugins()) - { + for(auto& p : m_plugin_manager->plugins()) { p->capture_close(); } // purge pending routines and wait for the running ones - if(m_thread_pool) - { + if(m_thread_pool) { m_thread_pool->purge(); } @@ -823,62 +752,49 @@ void sinsp::close() // This deinitializes the sinsp internal state, and it's used // internally while closing or restarting the capture. // -void sinsp::deinit_state() -{ +void sinsp::deinit_state() { m_network_interfaces.clear(); m_thread_manager->clear(); } void sinsp::on_new_entry_from_proc(void* context, - int64_t tid, - scap_threadinfo* tinfo, - scap_fdinfo* fdinfo) -{ - + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo) { // // Retrieve machine information if we don't have it yet // { m_machine_info = scap_get_machine_info(get_scap_platform()); - if(m_machine_info != NULL) - { + if(m_machine_info != NULL) { m_num_cpus = m_machine_info->num_cpus; - } - else - { + } else { m_num_cpus = 0; } } - if(tinfo && m_suppress.check_suppressed_comm(tid, tinfo->comm)) - { + if(tinfo && m_suppress.check_suppressed_comm(tid, tinfo->comm)) { return; } // // Add the thread or FD // - if(fdinfo == NULL) - { + if(fdinfo == NULL) { ASSERT(tinfo != NULL); threadinfo_map_t::ptr_t sinsp_tinfo; auto newti = build_threadinfo(); newti->init(tinfo); - if(is_nodriver()) - { + if(is_nodriver()) { auto existing_tinfo = find_thread(tid, true); - if(existing_tinfo == nullptr || newti->m_clone_ts > existing_tinfo->m_clone_ts) - { + if(existing_tinfo == nullptr || newti->m_clone_ts > existing_tinfo->m_clone_ts) { sinsp_tinfo = m_thread_manager->add_thread(std::move(newti), true); } - } - else - { + } else { sinsp_tinfo = m_thread_manager->add_thread(std::move(newti), true); } - if (sinsp_tinfo) - { + if(sinsp_tinfo) { // in case the inspector is configured with an internal filter, // we filter out thread infos in case we determine them not passing // the given filter. Filtered out thread infos will not be dumped @@ -895,8 +811,7 @@ void sinsp::on_new_entry_from_proc(void* context, // ever occur, so we simulate an internal event right away and // see if it gets filtered out or not. sinsp_tinfo->m_filtered_out = false; - if(m_filter != nullptr && is_capture()) - { + if(m_filter != nullptr && is_capture()) { // note: the choice of PPME_SCAPEVENT_E is opinionated as by // nature it will always pass filters using "evt.type=scapevent". // However: @@ -933,15 +848,11 @@ void sinsp::on_new_entry_from_proc(void* context, // we shouldn't see any fds yet ASSERT(tinfo->fdlist == nullptr); } - } - else - { + } else { auto sinsp_tinfo = find_thread(tid, true); - if(!sinsp_tinfo) - { - if (tinfo == NULL) - { + if(!sinsp_tinfo) { + if(tinfo == NULL) { // we have an fd but no associated tinfo, skip it return; } @@ -950,7 +861,7 @@ void sinsp::on_new_entry_from_proc(void* context, newti->init(tinfo); sinsp_tinfo = m_thread_manager->add_thread(std::move(newti), true); - if (sinsp_tinfo == nullptr) { + if(sinsp_tinfo == nullptr) { ASSERT(false); return; } @@ -960,60 +871,59 @@ void sinsp::on_new_entry_from_proc(void* context, } } -int32_t on_new_entry_from_proc(void* context, char* error, int64_t tid, scap_threadinfo* tinfo, scap_fdinfo* fdinfo, - scap_threadinfo** new_tinfo) -{ +int32_t on_new_entry_from_proc(void* context, + char* error, + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo, + scap_threadinfo** new_tinfo) { sinsp* _this = (sinsp*)context; _this->on_new_entry_from_proc(context, tid, tinfo, fdinfo); - if(new_tinfo != NULL) - { + if(new_tinfo != NULL) { *new_tinfo = tinfo; } return SCAP_SUCCESS; } -void sinsp::import_ifaddr_list() -{ +void sinsp::import_ifaddr_list() { m_network_interfaces.clear(); m_network_interfaces.import_interfaces(scap_get_ifaddr_list(get_scap_platform())); } -const sinsp_network_interfaces& sinsp::get_ifaddr_list() const -{ +const sinsp_network_interfaces& sinsp::get_ifaddr_list() const { return m_network_interfaces; } -void sinsp::import_ipv4_interface(const sinsp_ipv4_ifinfo& ifinfo) -{ +void sinsp::import_ipv4_interface(const sinsp_ipv4_ifinfo& ifinfo) { m_network_interfaces.import_ipv4_interface(ifinfo); } -void sinsp::import_user_list() -{ +void sinsp::import_user_list() { uint32_t j; scap_userlist* ul = scap_get_user_list(get_scap_platform()); - if(ul) - { - for(j = 0; j < ul->nusers; j++) - { - m_usergroup_manager.add_user("", -1, ul->users[j].uid, ul->users[j].gid, ul->users[j].name, ul->users[j].homedir, ul->users[j].shell); + if(ul) { + for(j = 0; j < ul->nusers; j++) { + m_usergroup_manager.add_user("", + -1, + ul->users[j].uid, + ul->users[j].gid, + ul->users[j].name, + ul->users[j].homedir, + ul->users[j].shell); } - for(j = 0; j < ul->ngroups; j++) - { + for(j = 0; j < ul->ngroups; j++) { m_usergroup_manager.add_group("", -1, ul->groups[j].gid, ul->groups[j].name); } } } -void sinsp::refresh_ifaddr_list() -{ +void sinsp::refresh_ifaddr_list() { #if !defined(_WIN32) - if(is_live() || is_syscall_plugin()) - { + if(is_live() || is_syscall_plugin()) { scap_refresh_iflist(get_scap_platform()); import_ifaddr_list(); } @@ -1028,8 +938,7 @@ void sinsp::refresh_ifaddr_list() // to closing and then re-opening the capture, but avoids losing the passed // configurations and reuses the same underlying scap event source. // -void sinsp::restart_capture() -{ +void sinsp::restart_capture() { // Save state info that could be lost during de-initialization uint64_t nevts = m_nevts; @@ -1038,8 +947,7 @@ void sinsp::restart_capture() // Restart the scap capture, which also trigger a re-initialization of // scap's internal state. - if (scap_restart_capture(m_h) != SCAP_SUCCESS) - { + if(scap_restart_capture(m_h) != SCAP_SUCCESS) { throw sinsp_exception(std::string("scap error: ") + scap_getlasterr(m_h)); } @@ -1050,29 +958,22 @@ void sinsp::restart_capture() m_nevts = nevts; } -uint64_t sinsp::max_buf_used() const -{ - if(m_h) - { +uint64_t sinsp::max_buf_used() const { + if(m_h) { return scap_max_buf_used(m_h); - } - else - { + } else { return 0; } } -void sinsp::get_procs_cpu_from_driver(uint64_t ts) -{ - if(ts <= m_next_flush_time_ns) - { +void sinsp::get_procs_cpu_from_driver(uint64_t ts) { + if(ts <= m_next_flush_time_ns) { return; } uint64_t next_full_second = ts - (ts % ONE_SECOND_IN_NS) + ONE_SECOND_IN_NS; - if(m_next_flush_time_ns == 0) - { + if(m_next_flush_time_ns == 0) { m_next_flush_time_ns = next_full_second; return; } @@ -1080,8 +981,7 @@ void sinsp::get_procs_cpu_from_driver(uint64_t ts) m_next_flush_time_ns = next_full_second; uint64_t procrequest_tod = sinsp_utils::get_current_time_ns(); - if(procrequest_tod - m_last_procrequest_tod <= ONE_SECOND_IN_NS / 2) - { + if(procrequest_tod - m_last_procrequest_tod <= ONE_SECOND_IN_NS / 2) { return; } @@ -1089,30 +989,31 @@ void sinsp::get_procs_cpu_from_driver(uint64_t ts) char error[SCAP_LASTERR_SIZE]; auto* threadlist = scap_get_threadlist(get_scap_platform(), error); - if(threadlist == NULL) - { + if(threadlist == NULL) { throw sinsp_exception(std::string("scap error: ") + error); } - for (int64_t i = 0; i < threadlist->n_entries; i++) - { + for(int64_t i = 0; i < threadlist->n_entries; i++) { ppm_proc_info* pi = &(threadlist->entries[i]); - if(pi->utime == 0 && pi->stime == 0) - { + if(pi->utime == 0 && pi->stime == 0) { continue; } uint32_t evlen = sizeof(scap_evt) + 2 * sizeof(uint16_t) + 2 * sizeof(uint64_t); auto piscapevt_buf = std::unique_ptr(new uint8_t[evlen]); - auto piscapevt = (scap_evt*) piscapevt_buf.get(); + auto piscapevt = (scap_evt*)piscapevt_buf.get(); piscapevt->tid = pi->pid; piscapevt->ts = ts; - int32_t encode_res = scap_event_encode_params(scap_sized_buffer{piscapevt_buf.get(), evlen}, nullptr, error, - PPME_PROCINFO_E, 2, pi->utime, pi->stime); - - if (encode_res != SCAP_SUCCESS) - { + int32_t encode_res = scap_event_encode_params(scap_sized_buffer{piscapevt_buf.get(), evlen}, + nullptr, + error, + PPME_PROCINFO_E, + 2, + pi->utime, + pi->stime); + + if(encode_res != SCAP_SUCCESS) { throw sinsp_exception(std::string("could not encode PPME_PROCINFO_E event: ") + error); } @@ -1121,13 +1022,11 @@ void sinsp::get_procs_cpu_from_driver(uint64_t ts) } } -int32_t sinsp::fetch_next_event(sinsp_evt*& evt) -{ +int32_t sinsp::fetch_next_event(sinsp_evt*& evt) { // check if an event must be replayed, which currently happens // when a capture file is read and we discover the first "event" block // after the initial "machine state" section - if (m_replay_scap_evt != NULL) - { + if(m_replay_scap_evt != NULL) { evt->set_scap_evt(m_replay_scap_evt); evt->set_cpuid(m_replay_scap_cpuid); evt->set_dump_flags(m_replay_scap_flags); @@ -1139,8 +1038,7 @@ int32_t sinsp::fetch_next_event(sinsp_evt*& evt) // from later that has been delayed. If our current libscap event storage // is empty, attempt fetching the next event in line from the scap handle int32_t res = SCAP_SUCCESS; - if (m_delayed_scap_evt.empty()) - { + if(m_delayed_scap_evt.empty()) { res = m_delayed_scap_evt.next(m_h); } @@ -1148,12 +1046,10 @@ int32_t sinsp::fetch_next_event(sinsp_evt*& evt) // error is encountered) we attempt popping an event from the asynchronous // event queue. If none is available, we just return the timeout. // note: the queue is optimized for checking for emptyness before popping - if (res == SCAP_TIMEOUT && - !m_async_events_queue.empty() && m_async_events_queue.try_pop(m_async_evt)) - { + if(res == SCAP_TIMEOUT && !m_async_events_queue.empty() && + m_async_events_queue.try_pop(m_async_evt)) { evt = m_async_evt.get(); - if(evt->get_scap_evt()->ts == (uint64_t) -1) - { + if(evt->get_scap_evt()->ts == (uint64_t)-1) { evt->get_scap_evt()->ts = get_new_ts(); } return SCAP_SUCCESS; @@ -1163,19 +1059,15 @@ int32_t sinsp::fetch_next_event(sinsp_evt*& evt) // before, we check that if there is any event in the async event queue // that should be returned first due to having a timestamp from earlier. // the goal is to guarantee events to be fetched ordered by timestamp. - if(res == SCAP_SUCCESS) - { - if (!m_async_events_queue.empty()) - { + if(res == SCAP_SUCCESS) { + if(!m_async_events_queue.empty()) { // This is thread-safe as we're in a MPSC case in which // sinsp::next is the single consumer m_async_events_checker.ts = m_delayed_scap_evt.m_pevt->ts; - if (m_async_events_queue.try_pop_if(m_async_evt, m_async_events_checker)) - { + if(m_async_events_queue.try_pop_if(m_async_evt, m_async_events_checker)) { // the async event is the one with most priority evt = m_async_evt.get(); - if(evt->get_scap_evt()->ts == (uint64_t) -1) - { + if(evt->get_scap_evt()->ts == (uint64_t)-1) { evt->get_scap_evt()->ts = get_new_ts(); } return SCAP_SUCCESS; @@ -1189,8 +1081,7 @@ int32_t sinsp::fetch_next_event(sinsp_evt*& evt) return res; } -int32_t sinsp::next(sinsp_evt **puevt) -{ +int32_t sinsp::next(sinsp_evt** puevt) { *puevt = NULL; sinsp_evt* evt = &m_evt; @@ -1199,52 +1090,38 @@ int32_t sinsp::next(sinsp_evt **puevt) // if we fetched an event successfully, check if we need to suppress // it from userspace and update the result status - if (res == SCAP_SUCCESS) - { + if(res == SCAP_SUCCESS) { res = m_suppress.process_event(evt->get_scap_evt()); } // in case we don't succeed, handle each scenario and return - if(res != SCAP_SUCCESS) - { - if(res == SCAP_TIMEOUT) - { - if (m_external_event_processor) - { + if(res != SCAP_SUCCESS) { + if(res == SCAP_TIMEOUT) { + if(m_external_event_processor) { m_external_event_processor->process_event(NULL, libsinsp::EVENT_RETURN_TIMEOUT); } - } - else if(res == SCAP_EOF) - { - if (m_external_event_processor) - { + } else if(res == SCAP_EOF) { + if(m_external_event_processor) { m_external_event_processor->process_event(NULL, libsinsp::EVENT_RETURN_EOF); } *puevt = evt; - } - else if(res == SCAP_UNEXPECTED_BLOCK) - { + } else if(res == SCAP_UNEXPECTED_BLOCK) { // This mostly happens in concatenated scap files, where an unexpected block // represents the end of a file and the start of the next appended one. // In this case, we restart the capture so that the internal states gets reset // and the blocks coming from the next appended file get consumed. restart_capture(); res = SCAP_TIMEOUT; - } - else if(res == SCAP_FILTERED_EVENT) - { + } else if(res == SCAP_FILTERED_EVENT) { // This will happen if SCAP has filtered the event in userspace (tid suppression). // A valid event was read from the driver, but we are choosing to not report it to // the client at the client's request. // However, we still need to return here so that the client doesn't time out the // request. - if(m_external_event_processor) - { + if(m_external_event_processor) { m_external_event_processor->process_event(NULL, libsinsp::EVENT_RETURN_FILTERED); } - } - else - { + } else { m_lasterr = scap_getlasterr(m_h); } @@ -1256,17 +1133,14 @@ int32_t sinsp::next(sinsp_evt **puevt) uint64_t ts = evt->get_ts(); - if(m_firstevent_ts == 0 && - !libsinsp::events::is_metaevent((ppm_event_code) evt->get_type())) - { + if(m_firstevent_ts == 0 && !libsinsp::events::is_metaevent((ppm_event_code)evt->get_type())) { m_firstevent_ts = ts; } // // If required, retrieve the processes cpu from the kernel // - if(m_get_procs_cpu_from_driver && is_live()) - { + if(m_get_procs_cpu_from_driver && is_live()) { get_procs_cpu_from_driver(ts); } @@ -1279,30 +1153,24 @@ int32_t sinsp::next(sinsp_evt **puevt) evt->set_num(m_nevts); m_lastevent_ts = ts; - if (m_auto_threads_purging) - { + if(m_auto_threads_purging) { // // Delayed removal of threads from the thread table, so that // things like exit() or close() can be parsed. // - if(m_tid_to_remove != -1) - { + if(m_tid_to_remove != -1) { remove_thread(m_tid_to_remove); m_tid_to_remove = -1; } - if(!is_offline()) - { + if(!is_offline()) { m_thread_manager->remove_inactive_threads(); } } - if (m_auto_stats_print && is_debug_enabled() && is_live()) - { - if(ts > m_next_stats_print_time_ns) - { - if(m_next_stats_print_time_ns) - { + if(m_auto_stats_print && is_debug_enabled() && is_live()) { + if(ts > m_next_stats_print_time_ns) { + if(m_next_stats_print_time_ns) { print_capture_stats(sinsp_logger::SEV_DEBUG); } @@ -1310,13 +1178,11 @@ int32_t sinsp::next(sinsp_evt **puevt) } } - if (m_auto_containers_purging && !is_offline()) - { + if(m_auto_containers_purging && !is_offline()) { m_container_manager.remove_inactive_containers(); } - if (m_auto_usergroups_purging && !is_offline()) - { + if(m_auto_usergroups_purging && !is_offline()) { m_usergroup_manager.clear_host_users_groups(); } @@ -1325,16 +1191,13 @@ int32_t sinsp::next(sinsp_evt **puevt) // things like exit() or close() can be parsed. // uint32_t nfdr = (uint32_t)m_fds_to_remove.size(); - if(nfdr != 0) - { + if(nfdr != 0) { /* This is a removal logic we shouldn't scan /proc. If we don't have the thread * to remove we are fine. */ sinsp_threadinfo* ptinfo = get_thread_ref(m_tid_of_fd_to_remove, false).get(); - if(ptinfo) - { - for(uint32_t j = 0; j < nfdr; j++) - { + if(ptinfo) { + for(uint32_t j = 0; j < nfdr; j++) { ptinfo->remove_fd(m_fds_to_remove.at(j)); } } @@ -1352,8 +1215,7 @@ int32_t sinsp::next(sinsp_evt **puevt) // event for state updates. Sinsp understands this through the // EF_MODIFIES_STATE flag, which however is only relevant in the context of // the internal implementation of libsinsp. - for (auto& pp : m_plugin_parsers) - { + for(auto& pp : m_plugin_parsers) { // todo(jason): should we log parsing errors here? pp.process_event(evt, m_event_sources); } @@ -1361,14 +1223,12 @@ int32_t sinsp::next(sinsp_evt **puevt) // Finally set output evt; // From now on, any return must have the correct output being set. *puevt = evt; - if(evt->is_filtered_out()) - { + if(evt->is_filtered_out()) { ppm_event_category cat = evt->get_category(); // Skip the event, unless we're in internal events // mode and the category of this event is internal. - if(!(m_isinternal_events_enabled && (cat & EC_INTERNAL))) - { + if(!(m_isinternal_events_enabled && (cat & EC_INTERNAL))) { return SCAP_FILTERED_EVENT; } } @@ -1376,8 +1236,7 @@ int32_t sinsp::next(sinsp_evt **puevt) // // Run the analysis engine // - if (m_external_event_processor) - { + if(m_external_event_processor) { m_external_event_processor->process_event(evt, libsinsp::EVENT_RETURN_NONE); } @@ -1387,10 +1246,8 @@ int32_t sinsp::next(sinsp_evt **puevt) // // Update the last event time for this thread // - if(evt->get_tinfo() && - evt->get_type() != PPME_SCHEDSWITCH_1_E && - evt->get_type() != PPME_SCHEDSWITCH_6_E) - { + if(evt->get_tinfo() && evt->get_type() != PPME_SCHEDSWITCH_1_E && + evt->get_type() != PPME_SCHEDSWITCH_6_E) { evt->get_tinfo()->m_prevevent_ts = evt->get_tinfo()->m_lastevent_ts; evt->get_tinfo()->m_lastevent_ts = m_lastevent_ts; } @@ -1401,216 +1258,176 @@ int32_t sinsp::next(sinsp_evt **puevt) return res; } -uint64_t sinsp::get_num_events() const -{ - if(m_h) - { +uint64_t sinsp::get_num_events() const { + if(m_h) { return scap_event_get_num(m_h); - } - else - { + } else { return 0; } } -bool sinsp::suppress_events_comm(const std::string &comm) -{ +bool sinsp::suppress_events_comm(const std::string& comm) { m_suppress.suppress_comm(comm); return true; } -bool sinsp::suppress_events_tid(int64_t tid) -{ +bool sinsp::suppress_events_tid(int64_t tid) { m_suppress.suppress_tid(tid); return true; } -void sinsp::clear_suppress_events_comm() -{ +void sinsp::clear_suppress_events_comm() { m_suppress.clear_suppress_comm(); } -void sinsp::clear_suppress_events_tid() -{ +void sinsp::clear_suppress_events_tid() { m_suppress.clear_suppress_tid(); } -bool sinsp::check_suppressed(int64_t tid) const -{ +bool sinsp::check_suppressed(int64_t tid) const { return m_suppress.is_suppressed_tid(tid); } -void sinsp::set_docker_socket_path(std::string socket_path) -{ +void sinsp::set_docker_socket_path(std::string socket_path) { m_container_manager.set_docker_socket_path(std::move(socket_path)); } -void sinsp::set_query_docker_image_info(bool query_image_info) -{ +void sinsp::set_query_docker_image_info(bool query_image_info) { m_container_manager.set_query_docker_image_info(query_image_info); } -void sinsp::set_cri_extra_queries(bool extra_queries) -{ +void sinsp::set_cri_extra_queries(bool extra_queries) { m_container_manager.set_cri_extra_queries(extra_queries); } -void sinsp::set_cri_socket_path(const std::string& path) -{ +void sinsp::set_cri_socket_path(const std::string& path) { m_container_manager.set_cri_socket_path(path); } -void sinsp::add_cri_socket_path(const std::string& path) -{ +void sinsp::add_cri_socket_path(const std::string& path) { m_container_manager.add_cri_socket_path(path); } -void sinsp::set_cri_timeout(int64_t timeout_ms) -{ +void sinsp::set_cri_timeout(int64_t timeout_ms) { m_container_manager.set_cri_timeout(timeout_ms); } -void sinsp::set_cri_async(bool async) -{ +void sinsp::set_cri_async(bool async) { m_container_manager.set_cri_async(async); } -void sinsp::set_container_labels_max_len(uint32_t max_label_len) -{ +void sinsp::set_container_labels_max_len(uint32_t max_label_len) { m_container_manager.set_container_labels_max_len(max_label_len); } -void sinsp::set_snaplen(uint32_t snaplen) -{ +void sinsp::set_snaplen(uint32_t snaplen) { // // If set_snaplen is called before opening of the inspector, // we register the value to be set after its initialization. // - if(m_h == NULL) - { + if(m_h == NULL) { m_snaplen = snaplen; return; } - if(is_live() && scap_set_snaplen(m_h, snaplen) != SCAP_SUCCESS) - { + if(is_live() && scap_set_snaplen(m_h, snaplen) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } -void sinsp::set_dropfailed(bool dropfailed) -{ - if(is_live() && scap_set_dropfailed(m_h, dropfailed) != SCAP_SUCCESS) - { +void sinsp::set_dropfailed(bool dropfailed) { + if(is_live() && scap_set_dropfailed(m_h, dropfailed) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } -void sinsp::set_fullcapture_port_range(uint16_t range_start, uint16_t range_end) -{ +void sinsp::set_fullcapture_port_range(uint16_t range_start, uint16_t range_end) { // // If set_fullcapture_port_range is called before opening of the inspector, // we register the value to be set after its initialization. // - if(m_h == NULL) - { + if(m_h == NULL) { m_increased_snaplen_port_range = {range_start, range_end}; return; } - if(!is_live()) - { - throw sinsp_exception("set_fullcapture_port_range called on a trace file, plugin, or test engine"); + if(!is_live()) { + throw sinsp_exception( + "set_fullcapture_port_range called on a trace file, plugin, or test engine"); } - if(scap_set_fullcapture_port_range(m_h, range_start, range_end) != SCAP_SUCCESS) - { + if(scap_set_fullcapture_port_range(m_h, range_start, range_end) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } -void sinsp::set_statsd_port(const uint16_t port) -{ +void sinsp::set_statsd_port(const uint16_t port) { // // If this method is called before opening of the inspector, // we register the value to be set after its initialization. // - if(m_h == NULL) - { + if(m_h == NULL) { m_statsd_port = port; return; } - if(!is_live()) - { + if(!is_live()) { throw sinsp_exception("set_statsd_port called on a trace file, plugin, or test engine"); } - if(scap_set_statsd_port(m_h, port) != SCAP_SUCCESS) - { + if(scap_set_statsd_port(m_h, port) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } -std::shared_ptr sinsp::register_plugin(const std::string& filepath) -{ +std::shared_ptr sinsp::register_plugin(const std::string& filepath) { std::string errstr; - std::shared_ptr plugin = sinsp_plugin::create(filepath, m_table_registry, m_thread_pool, errstr); - if (!plugin) - { + std::shared_ptr plugin = + sinsp_plugin::create(filepath, m_table_registry, m_thread_pool, errstr); + if(!plugin) { throw sinsp_exception("cannot load plugin " + filepath + ": " + errstr.c_str()); } - try - { + try { m_plugin_manager->add(plugin); - if (plugin->caps() & CAP_PARSING) - { + if(plugin->caps() & CAP_PARSING) { m_plugin_parsers.push_back(sinsp_plugin_parser(plugin)); } - } - catch(sinsp_exception const& e) - { + } catch(sinsp_exception const& e) { throw sinsp_exception("cannot register plugin " + filepath + " in inspector: " + e.what()); } return plugin; } -std::shared_ptr sinsp::register_plugin(const plugin_api* api) -{ +std::shared_ptr sinsp::register_plugin(const plugin_api* api) { std::string errstr; - std::shared_ptr plugin = sinsp_plugin::create(api, m_table_registry, m_thread_pool, errstr); - if (!plugin) - { + std::shared_ptr plugin = + sinsp_plugin::create(api, m_table_registry, m_thread_pool, errstr); + if(!plugin) { throw sinsp_exception("cannot load plugin with custom vtable: " + errstr); } - try - { + try { m_plugin_manager->add(plugin); - if (plugin->caps() & CAP_PARSING) - { + if(plugin->caps() & CAP_PARSING) { m_plugin_parsers.push_back(sinsp_plugin_parser(plugin)); } - } - catch(sinsp_exception const& e) - { - throw sinsp_exception("cannot register plugin with custom vtable in inspector: " + std::string(e.what())); + } catch(sinsp_exception const& e) { + throw sinsp_exception("cannot register plugin with custom vtable in inspector: " + + std::string(e.what())); } return plugin; } -void sinsp::set_input_plugin(const std::string& name, const std::string& params) -{ - for(auto& it : m_plugin_manager->plugins()) - { - if(it->name() == name) - { - if(!(it->caps() & CAP_SOURCING)) - { - throw sinsp_exception("plugin " + name + " has not event sourcing capabilities and cannot be used as input."); +void sinsp::set_input_plugin(const std::string& name, const std::string& params) { + for(auto& it : m_plugin_manager->plugins()) { + if(it->name() == name) { + if(!(it->caps() & CAP_SOURCING)) { + throw sinsp_exception( + "plugin " + name + + " has not event sourcing capabilities and cannot be used as input."); } m_input_plugin = it; m_input_plugin_open_params = params; @@ -1620,84 +1437,70 @@ void sinsp::set_input_plugin(const std::string& name, const std::string& params) throw sinsp_exception("plugin " + name + " does not exist"); } -void sinsp::stop_capture() -{ - if(scap_stop_capture(m_h) != SCAP_SUCCESS) - { +void sinsp::stop_capture() { + if(scap_stop_capture(m_h) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } /* Print scap stats */ - if (m_auto_stats_print) - { + if(m_auto_stats_print) { print_capture_stats(sinsp_logger::SEV_DEBUG); } /* Print the number of threads and fds in our tables */ uint64_t thread_cnt = 0; uint64_t fd_cnt = 0; - m_thread_manager->get_threads()->loop([&thread_cnt, &fd_cnt] (sinsp_threadinfo& tinfo) { + m_thread_manager->get_threads()->loop([&thread_cnt, &fd_cnt](sinsp_threadinfo& tinfo) { thread_cnt++; /* Only main threads have an associated fdtable */ - if(tinfo.is_main_thread()) - { + if(tinfo.is_main_thread()) { auto fdtable_ptr = tinfo.get_fd_table(); - if(fdtable_ptr != nullptr) - { + if(fdtable_ptr != nullptr) { fd_cnt += fdtable_ptr->size(); } } return true; }); libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "total threads in the table:%" PRIu64 - ", total fds in all threads:%" PRIu64 - "\n", - thread_cnt, - fd_cnt); + "total threads in the table:%" PRIu64 + ", total fds in all threads:%" PRIu64 "\n", + thread_cnt, + fd_cnt); } -void sinsp::start_capture() -{ - if(scap_start_capture(m_h) != SCAP_SUCCESS) - { +void sinsp::start_capture() { + if(scap_start_capture(m_h) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } #ifndef _WIN32 -void sinsp::stop_dropping_mode() -{ - if(is_live()) - { +void sinsp::stop_dropping_mode() { + if(is_live()) { libsinsp_logger()->format(sinsp_logger::SEV_INFO, "stopping drop mode"); - if(scap_stop_dropping_mode(m_h) != SCAP_SUCCESS) - { + if(scap_stop_dropping_mode(m_h) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } } -void sinsp::start_dropping_mode(uint32_t sampling_ratio) -{ - if(is_live()) - { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "setting drop mode to %" PRIu32, sampling_ratio); +void sinsp::start_dropping_mode(uint32_t sampling_ratio) { + if(is_live()) { + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "setting drop mode to %" PRIu32, + sampling_ratio); - if(scap_start_dropping_mode(m_h, sampling_ratio) != SCAP_SUCCESS) - { + if(scap_start_dropping_mode(m_h, sampling_ratio) != SCAP_SUCCESS) { throw sinsp_exception(scap_getlasterr(m_h)); } } } -#endif // _WIN32 +#endif // _WIN32 -void sinsp::set_filter(std::unique_ptr filter, const std::string& filterstring) -{ - if(m_filter != NULL) - { +void sinsp::set_filter(std::unique_ptr filter, const std::string& filterstring) { + if(m_filter != NULL) { ASSERT(false); throw sinsp_exception("filter can only be set once"); } @@ -1706,10 +1509,8 @@ void sinsp::set_filter(std::unique_ptr filter, const std::string& m_filterstring = filterstring; } -void sinsp::set_filter(const std::string& filter) -{ - if(m_filter != NULL) - { +void sinsp::set_filter(const std::string& filter) { + if(m_filter != NULL) { ASSERT(false); throw sinsp_exception("filter can only be set once"); } @@ -1720,196 +1521,156 @@ void sinsp::set_filter(const std::string& filter) m_internal_flt_ast = compiler.get_filter_ast(); } -std::string sinsp::get_filter() const -{ +std::string sinsp::get_filter() const { return m_filterstring; } -bool sinsp::run_filters_on_evt(sinsp_evt *evt) -{ +bool sinsp::run_filters_on_evt(sinsp_evt* evt) { // // First run the global filter, if there is one. // - if(m_filter && m_filter->run(evt) == true) - { + if(m_filter && m_filter->run(evt) == true) { return true; } return false; } -const scap_machine_info* sinsp::get_machine_info() const -{ +const scap_machine_info* sinsp::get_machine_info() const { return m_machine_info; } -const scap_agent_info* sinsp::get_agent_info() const -{ +const scap_agent_info* sinsp::get_agent_info() const { return m_agent_info; } -std::unique_ptr sinsp::new_generic_filtercheck() -{ +std::unique_ptr sinsp::new_generic_filtercheck() { return std::make_unique(); } -void sinsp::get_capture_stats(scap_stats* stats) const -{ +void sinsp::get_capture_stats(scap_stats* stats) const { /* On purpose ignoring failures to not interrupt in case of stats retrieval failure. */ scap_get_stats(m_h, stats); stats->n_suppressed = m_suppress.get_num_suppressed_events(); stats->n_tids_suppressed = m_suppress.get_num_suppressed_tids(); } -void sinsp::print_capture_stats(sinsp_logger::severity sev) const -{ +void sinsp::print_capture_stats(sinsp_logger::severity sev) const { scap_stats stats; get_capture_stats(&stats); - libsinsp_logger()->format(sev, - "\nn_evts:%" PRIu64 - "\nn_drops:%" PRIu64 - "\nn_drops_buffer:%" PRIu64 - "\nn_drops_buffer_clone_fork_enter:%" PRIu64 - "\nn_drops_buffer_clone_fork_exit:%" PRIu64 - "\nn_drops_buffer_execve_enter:%" PRIu64 - "\nn_drops_buffer_execve_exit:%" PRIu64 - "\nn_drops_buffer_connect_enter:%" PRIu64 - "\nn_drops_buffer_connect_exit:%" PRIu64 - "\nn_drops_buffer_open_enter:%" PRIu64 - "\nn_drops_buffer_open_exit:%" PRIu64 - "\nn_drops_buffer_dir_file_enter:%" PRIu64 - "\nn_drops_buffer_dir_file_exit:%" PRIu64 - "\nn_drops_buffer_other_interest_enter:%" PRIu64 - "\nn_drops_buffer_other_interest_exit:%" PRIu64 - "\nn_drops_buffer_close_exit:%" PRIu64 - "\nn_drops_buffer_proc_exit:%" PRIu64 - "\nn_drops_scratch_map:%" PRIu64 - "\nn_drops_pf:%" PRIu64 - "\nn_drops_bug:%" PRIu64 - "\n", - stats.n_evts, - stats.n_drops, - stats.n_drops_buffer, - stats.n_drops_buffer_clone_fork_enter, - stats.n_drops_buffer_clone_fork_exit, - stats.n_drops_buffer_execve_enter, - stats.n_drops_buffer_execve_exit, - stats.n_drops_buffer_connect_enter, - stats.n_drops_buffer_connect_exit, - stats.n_drops_buffer_open_enter, - stats.n_drops_buffer_open_exit, - stats.n_drops_buffer_dir_file_enter, - stats.n_drops_buffer_dir_file_exit, - stats.n_drops_buffer_other_interest_enter, - stats.n_drops_buffer_other_interest_exit, - stats.n_drops_buffer_close_exit, - stats.n_drops_buffer_proc_exit, - stats.n_drops_scratch_map, - stats.n_drops_pf, - stats.n_drops_bug); -} - -const metrics_v2* sinsp::get_capture_stats_v2(uint32_t flags, uint32_t* nstats, int32_t* rc) const -{ + libsinsp_logger()->format( + sev, + "\nn_evts:%" PRIu64 "\nn_drops:%" PRIu64 "\nn_drops_buffer:%" PRIu64 + "\nn_drops_buffer_clone_fork_enter:%" PRIu64 "\nn_drops_buffer_clone_fork_exit:%" PRIu64 + "\nn_drops_buffer_execve_enter:%" PRIu64 "\nn_drops_buffer_execve_exit:%" PRIu64 + "\nn_drops_buffer_connect_enter:%" PRIu64 "\nn_drops_buffer_connect_exit:%" PRIu64 + "\nn_drops_buffer_open_enter:%" PRIu64 "\nn_drops_buffer_open_exit:%" PRIu64 + "\nn_drops_buffer_dir_file_enter:%" PRIu64 "\nn_drops_buffer_dir_file_exit:%" PRIu64 + "\nn_drops_buffer_other_interest_enter:%" PRIu64 + "\nn_drops_buffer_other_interest_exit:%" PRIu64 "\nn_drops_buffer_close_exit:%" PRIu64 + "\nn_drops_buffer_proc_exit:%" PRIu64 "\nn_drops_scratch_map:%" PRIu64 + "\nn_drops_pf:%" PRIu64 "\nn_drops_bug:%" PRIu64 "\n", + stats.n_evts, + stats.n_drops, + stats.n_drops_buffer, + stats.n_drops_buffer_clone_fork_enter, + stats.n_drops_buffer_clone_fork_exit, + stats.n_drops_buffer_execve_enter, + stats.n_drops_buffer_execve_exit, + stats.n_drops_buffer_connect_enter, + stats.n_drops_buffer_connect_exit, + stats.n_drops_buffer_open_enter, + stats.n_drops_buffer_open_exit, + stats.n_drops_buffer_dir_file_enter, + stats.n_drops_buffer_dir_file_exit, + stats.n_drops_buffer_other_interest_enter, + stats.n_drops_buffer_other_interest_exit, + stats.n_drops_buffer_close_exit, + stats.n_drops_buffer_proc_exit, + stats.n_drops_scratch_map, + stats.n_drops_pf, + stats.n_drops_bug); +} + +const metrics_v2* sinsp::get_capture_stats_v2(uint32_t flags, uint32_t* nstats, int32_t* rc) const { /* On purpose ignoring failures to not interrupt in case of stats retrieval failure. */ const metrics_v2* stats_v2 = scap_get_stats_v2(m_h, flags, nstats, rc); - if (!stats_v2) - { + if(!stats_v2) { *nstats = 0; return NULL; } return stats_v2; } -void sinsp::set_log_callback(sinsp_logger_callback cb) -{ - if(cb) - { +void sinsp::set_log_callback(sinsp_logger_callback cb) { + if(cb) { libsinsp_logger()->add_callback_log(cb); - } - else - { + } else { libsinsp_logger()->remove_callback_log(); } } -void sinsp::set_log_file(const std::string& filename) -{ +void sinsp::set_log_file(const std::string& filename) { libsinsp_logger()->add_file_log(filename); } -void sinsp::set_log_stderr() -{ +void sinsp::set_log_stderr() { libsinsp_logger()->add_stderr_log(); } -void sinsp::set_min_log_severity(sinsp_logger::severity sev) -{ +void sinsp::set_min_log_severity(sinsp_logger::severity sev) { libsinsp_logger()->set_severity(sev); } -sinsp_evttables* sinsp::get_event_info_tables() -{ +sinsp_evttables* sinsp::get_event_info_tables() { return &g_infotables; } -void sinsp::set_buffer_format(sinsp_evt::param_fmt format) -{ +void sinsp::set_buffer_format(sinsp_evt::param_fmt format) { m_buffer_format = format; } -sinsp_evt::param_fmt sinsp::get_buffer_format() const -{ +sinsp_evt::param_fmt sinsp::get_buffer_format() const { return m_buffer_format; } -void sinsp::set_large_envs(bool enable) -{ +void sinsp::set_large_envs(bool enable) { m_large_envs_enabled = enable; } -void sinsp::set_debug_mode(bool enable_debug) -{ +void sinsp::set_debug_mode(bool enable_debug) { m_isdebug_enabled = enable_debug; } -void sinsp::set_print_container_data(bool print_container_data) -{ +void sinsp::set_print_container_data(bool print_container_data) { m_print_container_data = print_container_data; } -void sinsp::set_fatfile_dump_mode(bool enable_fatfile) -{ +void sinsp::set_fatfile_dump_mode(bool enable_fatfile) { m_isfatfile_enabled = enable_fatfile; } -void sinsp::set_internal_events_mode(bool enable_internal_events) -{ +void sinsp::set_internal_events_mode(bool enable_internal_events) { m_isinternal_events_enabled = enable_internal_events; } -void sinsp::set_hostname_and_port_resolution_mode(bool enable) -{ +void sinsp::set_hostname_and_port_resolution_mode(bool enable) { m_hostname_and_port_resolution_enabled = enable; } -void sinsp::set_max_evt_output_len(uint32_t len) -{ +void sinsp::set_max_evt_output_len(uint32_t len) { m_max_evt_output_len = len; } -double sinsp::get_read_progress_file() const -{ - if(m_input_fd != 0) - { +double sinsp::get_read_progress_file() const { + if(m_input_fd != 0) { // We can't get a reliable file size, so we can't get // any reliable progress return 0; } - if(m_filesize == -1) - { + if(m_filesize == -1) { throw sinsp_exception(scap_getlasterr(m_h)); } @@ -1917,25 +1678,21 @@ double sinsp::get_read_progress_file() const int64_t fpos = scap_get_readfile_offset(m_h); - if(fpos == -1) - { + if(fpos == -1) { throw sinsp_exception(scap_getlasterr(m_h)); } return (double)fpos * 100 / m_filesize; } -void sinsp::get_read_progress_plugin(double* nres, std::string* sres) const -{ +void sinsp::get_read_progress_plugin(double* nres, std::string* sres) const { ASSERT(nres != NULL); ASSERT(sres != NULL); - if(!nres || !sres) - { + if(!nres || !sres) { return; } - if (!m_input_plugin) - { + if(!m_input_plugin) { *nres = -1; *sres = "No Input Plugin"; @@ -1948,52 +1705,40 @@ void sinsp::get_read_progress_plugin(double* nres, std::string* sres) const *nres = ((double)nplg) / 100; } -double sinsp::get_read_progress() const -{ - if(is_plugin()) - { +double sinsp::get_read_progress() const { + if(is_plugin()) { double res = 0; get_read_progress_plugin(&res, NULL); return res; - } - else - { + } else { return get_read_progress_file(); } } -double sinsp::get_read_progress_with_str(std::string* progress_str) const -{ - if(is_plugin()) - { +double sinsp::get_read_progress_with_str(std::string* progress_str) const { + if(is_plugin()) { double res = 0; get_read_progress_plugin(&res, progress_str); return res; - } - else - { + } else { *progress_str = ""; return get_read_progress_file(); } } -bool sinsp::remove_inactive_threads() -{ +bool sinsp::remove_inactive_threads() { return m_thread_manager->remove_inactive_threads(); } -void sinsp::set_thread_timeout_s(uint32_t val) -{ +void sinsp::set_thread_timeout_s(uint32_t val) { m_thread_timeout_ns = (uint64_t)val * ONE_SECOND_IN_NS; } -void sinsp::set_proc_scan_timeout_ms(uint64_t val) -{ +void sinsp::set_proc_scan_timeout_ms(uint64_t val) { m_proc_scan_timeout_ms = val; } -void sinsp::set_proc_scan_log_interval_ms(uint64_t val) -{ +void sinsp::set_proc_scan_log_interval_ms(uint64_t val) { m_proc_scan_log_interval_ms = val; } @@ -2002,29 +1747,24 @@ void sinsp::set_proc_scan_log_interval_ms(uint64_t val) /////////////////////////////////////////////////////////////////////////////// /* Returns true when we scan the table */ -bool sinsp_thread_manager::remove_inactive_threads() -{ - if(m_last_flush_time_ns == 0) - { +bool sinsp_thread_manager::remove_inactive_threads() { + if(m_last_flush_time_ns == 0) { // - // Set the first table scan for 30 seconds in, so that we can spot bugs in the logic without having - // to wait for tens of minutes + // Set the first table scan for 30 seconds in, so that we can spot bugs in the logic without + // having to wait for tens of minutes // - if(m_inspector->m_threads_purging_scan_time_ns > 30 * ONE_SECOND_IN_NS) - { + if(m_inspector->m_threads_purging_scan_time_ns > 30 * ONE_SECOND_IN_NS) { m_last_flush_time_ns = - (m_inspector->get_lastevent_ts() - m_inspector->m_threads_purging_scan_time_ns + 30 * ONE_SECOND_IN_NS); - } - else - { + (m_inspector->get_lastevent_ts() - m_inspector->m_threads_purging_scan_time_ns + + 30 * ONE_SECOND_IN_NS); + } else { m_last_flush_time_ns = - (m_inspector->get_lastevent_ts() - m_inspector->m_threads_purging_scan_time_ns); + (m_inspector->get_lastevent_ts() - m_inspector->m_threads_purging_scan_time_ns); } } if(m_inspector->get_lastevent_ts() > - m_last_flush_time_ns + m_inspector->m_threads_purging_scan_time_ns) - { + m_last_flush_time_ns + m_inspector->m_threads_purging_scan_time_ns) { std::unordered_set to_delete; m_last_flush_time_ns = m_inspector->get_lastevent_ts(); @@ -2035,18 +1775,19 @@ bool sinsp_thread_manager::remove_inactive_threads() * 1. Invalid threads. * 2. Threads that we are not using and that are no more alive in /proc. */ - m_threadtable.loop([&] (sinsp_threadinfo& tinfo) { - if(tinfo.is_invalid() || - ((m_inspector->get_lastevent_ts() > tinfo.m_lastaccess_ts + m_inspector->m_thread_timeout_ns) && - !scap_is_thread_alive(m_inspector->get_scap_platform(), tinfo.m_pid, tinfo.m_tid, tinfo.m_comm.c_str()))) - { + m_threadtable.loop([&](sinsp_threadinfo& tinfo) { + if(tinfo.is_invalid() || ((m_inspector->get_lastevent_ts() > + tinfo.m_lastaccess_ts + m_inspector->m_thread_timeout_ns) && + !scap_is_thread_alive(m_inspector->get_scap_platform(), + tinfo.m_pid, + tinfo.m_tid, + tinfo.m_comm.c_str()))) { to_delete.insert(tinfo.m_tid); } return true; }); - for(const auto& tid_to_remove : to_delete) - { + for(const auto& tid_to_remove : to_delete) { remove_thread(tid_to_remove); } @@ -2058,38 +1799,30 @@ bool sinsp_thread_manager::remove_inactive_threads() return false; } -std::unique_ptr -libsinsp::event_processor::build_threadinfo(sinsp* inspector) -{ +std::unique_ptr libsinsp::event_processor::build_threadinfo(sinsp* inspector) { return std::make_unique(inspector); } -std::unique_ptr -libsinsp::event_processor::build_fdinfo(sinsp* inspector) -{ +std::unique_ptr libsinsp::event_processor::build_fdinfo(sinsp* inspector) { return std::make_unique(); } -void sinsp::handle_async_event(std::unique_ptr evt) -{ +void sinsp::handle_async_event(std::unique_ptr evt) { // see comments in handle_plugin_async_event ASSERT(!is_capture()); evt->set_inspector(this); if(evt->get_scap_evt()->ts != (uint64_t)-1 && - evt->get_scap_evt()->ts > sinsp_utils::get_current_time_ns() + ONE_SECOND_IN_NS * 10) - { + evt->get_scap_evt()->ts > sinsp_utils::get_current_time_ns() + ONE_SECOND_IN_NS * 10) { libsinsp_logger()->log("async event ts too far in future", sinsp_logger::SEV_WARNING); return; } - if(!m_async_events_queue.push(std::move(evt))) - { + if(!m_async_events_queue.push(std::move(evt))) { libsinsp_logger()->log("async event queue is full", sinsp_logger::SEV_WARNING); } } -void sinsp::handle_plugin_async_event(const sinsp_plugin& p, std::unique_ptr evt) -{ +void sinsp::handle_plugin_async_event(const sinsp_plugin& p, std::unique_ptr evt) { // note: this function can be invoked from different plugin threads, // so we need to make sure that every variable we read is either constant // during the lifetime of those threads, or that it is atomic. @@ -2098,8 +1831,7 @@ void sinsp::handle_plugin_async_event(const sinsp_plugin& p, std::unique_ptrid(); - if (cur_plugin_id != 0) - { + if(cur_plugin_id != 0) { bool found = false; cur_evtsrc_idx = m_plugin_manager->source_idx_by_plugin_id(cur_plugin_id, found); - if (!found) - { - throw sinsp_exception("can't find event source for plugin ID: " - + std::to_string(cur_plugin_id)); + if(!found) { + throw sinsp_exception("can't find event source for plugin ID: " + + std::to_string(cur_plugin_id)); } } } ASSERT(cur_evtsrc_idx < m_event_sources.size()); const auto& cur_evtsrc = m_event_sources[cur_evtsrc_idx]; - if (!sinsp_plugin::is_source_compatible(p.async_event_sources(), cur_evtsrc)) - { - throw sinsp_exception("async events of plugin '" + p.name() - + "' are not compatible with open event source '" + cur_evtsrc + "'"); + if(!sinsp_plugin::is_source_compatible(p.async_event_sources(), cur_evtsrc)) { + throw sinsp_exception("async events of plugin '" + p.name() + + "' are not compatible with open event source '" + cur_evtsrc + + "'"); } // if the async event is generated by a non-syscall event source, then // async events must have no thread associated. - if (cur_plugin_id != 0 && evt->get_scap_evt()->tid != (uint64_t) -1) - { - throw sinsp_exception("async events of plugin '" + p.name() - + "' can have no thread associated with open event source '" + cur_evtsrc + "'"); + if(cur_plugin_id != 0 && evt->get_scap_evt()->tid != (uint64_t)-1) { + throw sinsp_exception("async events of plugin '" + p.name() + + "' can have no thread associated with open event source '" + + cur_evtsrc + "'"); } // write plugin ID and timestamp in the event and kick it in the queue - auto plid = (uint32_t*)((uint8_t*) evt->get_scap_evt() + sizeof(scap_evt) + 4+4+4); + auto plid = (uint32_t*)((uint8_t*)evt->get_scap_evt() + sizeof(scap_evt) + 4 + 4 + 4); memcpy(plid, &cur_plugin_id, sizeof(cur_plugin_id)); handle_async_event(std::move(evt)); } } -bool sinsp::get_track_connection_status() const -{ +bool sinsp::get_track_connection_status() const { return m_parser->get_track_connection_status(); } -void sinsp::set_track_connection_status(bool enabled) -{ +void sinsp::set_track_connection_status(bool enabled) { m_parser->set_track_connection_status(enabled); } -std::shared_ptr sinsp::get_thread_pool() -{ +std::shared_ptr sinsp::get_thread_pool() { return m_thread_pool; } -bool sinsp::set_thread_pool(std::shared_ptr tpool) -{ - if(!m_thread_pool) - { +bool sinsp::set_thread_pool(std::shared_ptr tpool) { + if(!m_thread_pool) { m_thread_pool = tpool; return true; } return false; } - diff --git a/userspace/libsinsp/sinsp.h b/userspace/libsinsp/sinsp.h index a6b1b9c808..28f6edac70 100644 --- a/userspace/libsinsp/sinsp.h +++ b/userspace/libsinsp/sinsp.h @@ -17,27 +17,27 @@ limitations under the License. */ /*! - \mainpage libsinsp documentation - - \section Introduction - - libsinsp is a system inspection library written in C++ and implementing high level - functionality like: - - live capture control (start/stop/pause...) - - event capture from file or the live OS - - OS state reconstruction. By parsing /proc and inspecting the live event stream, - libsinsp is capable of mirroring the OS process state and putting context around - key OS primitives like process IDs and file descriptors. That way, these primitives - can be treated like programs, files, connections and users. - - parsing of OS events and conversion of events into human-readable strings - - event filtering - - This manual includes the following sections: - - \ref inspector - - \ref event - - \ref dump - - \ref filter - - \ref state + \mainpage libsinsp documentation + + \section Introduction + + libsinsp is a system inspection library written in C++ and implementing high level + functionality like: + - live capture control (start/stop/pause...) + - event capture from file or the live OS + - OS state reconstruction. By parsing /proc and inspecting the live event stream, + libsinsp is capable of mirroring the OS process state and putting context around + key OS primitives like process IDs and file descriptors. That way, these primitives + can be treated like programs, files, connections and users. + - parsing of OS events and conversion of events into human-readable strings + - event filtering + + This manual includes the following sections: + - \ref inspector + - \ref event + - \ref dump + - \ref filter + - \ref state */ #pragma once @@ -98,43 +98,43 @@ class sinsp_observer; #if !defined(LIBSINSP_USER_AGENT) #define LIBSINSP_USER_AGENT "falcosecurity-libs" -#endif // LIBSINSP_USER_AGENT +#endif // LIBSINSP_USER_AGENT /*! \brief The default way an event is converted to string by the library */ -#define DEFAULT_OUTPUT_STR "*%evt.num %evt.time %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.args" +#define DEFAULT_OUTPUT_STR \ + "*%evt.num %evt.time %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.args" /*! \brief Sinsp possible modes */ -enum sinsp_mode_t -{ +enum sinsp_mode_t { /*! - * Default value that mostly exists so that sinsp can have a valid value - * before it is initialized. + * Default value that mostly exists so that sinsp can have a valid value + * before it is initialized. */ SINSP_MODE_NONE = 0, /*! - * Read system call data from a capture file. + * Read system call data from a capture file. */ SINSP_MODE_CAPTURE, /*! - * Read system call data from the underlying operating system. + * Read system call data from the underlying operating system. */ SINSP_MODE_LIVE, /*! - * Do not read system call data. If next is called, a dummy event is - * returned. + * Do not read system call data. If next is called, a dummy event is + * returned. */ SINSP_MODE_NODRIVER, /*! - * Do not read system call data. Events come from the configured input plugin. + * Do not read system call data. Events come from the configured input plugin. */ SINSP_MODE_PLUGIN, /*! - * Read system call and event data from the test event generator. - * Do not attempt to query the underlying system. + * Read system call and event data from the test event generator. + * Do not attempt to query the underlying system. */ SINSP_MODE_TEST, }; @@ -142,11 +142,10 @@ enum sinsp_mode_t /** * @brief Possible platforms to use with plugins */ -enum class sinsp_plugin_platform -{ - SINSP_PLATFORM_GENERIC, //!< generic platform, no system information collected - SINSP_PLATFORM_HOSTINFO, //!< basic host information collected, for non-syscall source plugins - SINSP_PLATFORM_FULL, //!< full system information collected, for syscall source plugins +enum class sinsp_plugin_platform { + SINSP_PLATFORM_GENERIC, //!< generic platform, no system information collected + SINSP_PLATFORM_HOSTINFO, //!< basic host information collected, for non-syscall source plugins + SINSP_PLATFORM_FULL, //!< full system information collected, for syscall source plugins }; /** @defgroup inspector Main library @@ -161,36 +160,44 @@ enum class sinsp_plugin_platform - event retrieval - setting capture filters */ -class SINSP_PUBLIC sinsp : public capture_stats_source -{ +class SINSP_PUBLIC sinsp : public capture_stats_source { public: sinsp(bool with_metrics = false); virtual ~sinsp() override; /* Wrappers to open a specific engine. */ - virtual void open_kmod(unsigned long driver_buffer_bytes_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM, const libsinsp::events::set &ppm_sc_of_interest = {}); - virtual void open_bpf(const std::string &bpf_path, unsigned long driver_buffer_bytes_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM, const libsinsp::events::set &ppm_sc_of_interest = {}); + virtual void open_kmod(unsigned long driver_buffer_bytes_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM, + const libsinsp::events::set& ppm_sc_of_interest = {}); + virtual void open_bpf(const std::string& bpf_path, + unsigned long driver_buffer_bytes_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM, + const libsinsp::events::set& ppm_sc_of_interest = {}); virtual void open_nodriver(bool full_proc_scan = false); - virtual void open_savefile(const std::string &filename, int fd = 0); - virtual void open_plugin(const std::string& plugin_name, const std::string& plugin_open_params, - sinsp_plugin_platform platform_type); - virtual void open_gvisor(const std::string &config_path, const std::string &root_path, bool no_events = false, int epoll_timeout = -1); - /*[EXPERIMENTAL] This API could change between releases, we are trying to find the right configuration to deploy the modern bpf probe: - * `cpus_for_each_buffer` and `online_only` are the 2 experimental params. The first one allows associating more than one CPU to a single ring buffer. - * The last one allows allocating ring buffers only for online CPUs and not for all system-available CPUs. + virtual void open_savefile(const std::string& filename, int fd = 0); + virtual void open_plugin(const std::string& plugin_name, + const std::string& plugin_open_params, + sinsp_plugin_platform platform_type); + virtual void open_gvisor(const std::string& config_path, + const std::string& root_path, + bool no_events = false, + int epoll_timeout = -1); + /*[EXPERIMENTAL] This API could change between releases, we are trying to find the right + * configuration to deploy the modern bpf probe: `cpus_for_each_buffer` and `online_only` are + * the 2 experimental params. The first one allows associating more than one CPU to a single + * ring buffer. The last one allows allocating ring buffers only for online CPUs and not for all + * system-available CPUs. */ - virtual void open_modern_bpf(unsigned long driver_buffer_bytes_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM, uint16_t cpus_for_each_buffer = DEFAULT_CPU_FOR_EACH_BUFFER, bool online_only = true, const libsinsp::events::set &ppm_sc_of_interest = {}); + virtual void open_modern_bpf( + unsigned long driver_buffer_bytes_dim = DEFAULT_DRIVER_BUFFER_BYTES_DIM, + uint16_t cpus_for_each_buffer = DEFAULT_CPU_FOR_EACH_BUFFER, + bool online_only = true, + const libsinsp::events::set& ppm_sc_of_interest = {}); virtual void open_test_input(scap_test_input_data* data, sinsp_mode_t mode = SINSP_MODE_TEST); - void fseek(uint64_t filepos) - { - scap_fseek(m_h, filepos); - } + void fseek(uint64_t filepos) { scap_fseek(m_h, filepos); } std::string generate_gvisor_config(const std::string& socket_path); - /*! \brief Ends a capture and release all resources. */ @@ -211,11 +218,11 @@ class SINSP_PUBLIC sinsp : public capture_stats_source \note: the returned event can be considered valid only until the next call to \ref) */ - virtual int32_t next(sinsp_evt **evt); + virtual int32_t next(sinsp_evt** evt); /*! \brief Get the maximum number of bytes currently in use by any CPU buffer - */ + */ uint64_t max_buf_used() const; /*! @@ -247,7 +254,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source /*! * \brief (Un)Set the drop failed feature of the drivers. - When enabled, drivers will stop sending failed syscalls (exit) events. + When enabled, drivers will stop sending failed syscalls (exit) events. * @param dropfailed whether to enable the feature */ @@ -322,14 +329,14 @@ class SINSP_PUBLIC sinsp : public capture_stats_source /*! \brief Return the AST (wrapped in a shared pointer) for the filter set for this capture. - \return the AST (wrapped in a shared pointer) corresponding to the filter previously set with \ref set_filter().. + \return the AST (wrapped in a shared pointer) corresponding to the filter previously set with + \ref set_filter().. */ - inline const std::shared_ptr& get_filter_ast() - { + inline const std::shared_ptr& get_filter_ast() { return m_internal_flt_ast; } - bool run_filters_on_evt(sinsp_evt *evt); + bool run_filters_on_evt(sinsp_evt* evt); /*! \brief This method can be used to specify a function to collect the library @@ -362,17 +369,13 @@ class SINSP_PUBLIC sinsp : public capture_stats_source * When the routine is run, then the purge interval and thread timeout * change defaults, but with no observable effect. */ - void set_auto_threads_purging(bool enabled) - { - m_auto_threads_purging = enabled; - } + void set_auto_threads_purging(bool enabled) { m_auto_threads_purging = enabled; } /*! * \brief Sets the interval (in seconds) at which the automatic threads * purging routine runs (if enabled). */ - inline void set_auto_threads_purging_interval_s(uint32_t val) - { + inline void set_auto_threads_purging_interval_s(uint32_t val) { m_threads_purging_scan_time_ns = (uint64_t)val * ONE_SECOND_IN_NS; } @@ -381,17 +384,13 @@ class SINSP_PUBLIC sinsp : public capture_stats_source * thread infos from the internal state. If disabled, the client is * responsible of manually-handling the lifetime of containers. */ - void set_auto_containers_purging(bool enabled) - { - m_auto_containers_purging = enabled; - } + void set_auto_containers_purging(bool enabled) { m_auto_containers_purging = enabled; } /*! * \brief Sets the interval (in seconds) at which the automatic containers * purging routine runs (if enabled). */ - inline void set_auto_containers_purging_interval_s(uint32_t val) - { + inline void set_auto_containers_purging_interval_s(uint32_t val) { m_containers_purging_scan_time_ns = (uint64_t)val * ONE_SECOND_IN_NS; } @@ -400,17 +399,13 @@ class SINSP_PUBLIC sinsp : public capture_stats_source * users and groups infos from the internal state. If disabled, the client * is responsible of manually-handling the lifetime of users and groups. */ - void set_auto_usergroups_purging(bool enabled) - { - m_auto_usergroups_purging = enabled; - } + void set_auto_usergroups_purging(bool enabled) { m_auto_usergroups_purging = enabled; } /*! * \brief Sets the interval (in seconds) at which the automatic * users and groups purging routine runs (if enabled). */ - inline void set_auto_usergroups_purging_interval_s(uint32_t val) - { + inline void set_auto_usergroups_purging_interval_s(uint32_t val) { m_usergroups_purging_scan_time_ns = (uint64_t)val * ONE_SECOND_IN_NS; } @@ -418,10 +413,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source * \brief Enables or disables an automatic routine that periodically logs * the current capture stats. */ - inline void set_auto_stats_print(bool enabled) - { - m_auto_stats_print = enabled; - } + inline void set_auto_stats_print(bool enabled) { m_auto_stats_print = enabled; } /*! * \brief sets the amount of time after which a thread which has seen no events @@ -459,10 +451,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source */ const scap_machine_info* get_machine_info() const; - inline void set_machine_info(const scap_machine_info *v) - { - m_machine_info = v; - } + inline void set_machine_info(const scap_machine_info* v) { m_machine_info = v; } /*! \brief Return information about the agent based on start up conditions. @@ -472,16 +461,13 @@ class SINSP_PUBLIC sinsp : public capture_stats_source const scap_agent_info* get_agent_info() const; /*! - \brief Return sinsp stats v2 containing continually updated counters around thread and fd state tables. + \brief Return sinsp stats v2 containing continually updated counters around thread and fd + state tables. */ - inline const std::shared_ptr& get_sinsp_stats_v2() - { - return m_sinsp_stats_v2; - } + inline const std::shared_ptr& get_sinsp_stats_v2() { return m_sinsp_stats_v2; } - inline std::shared_ptr get_sinsp_stats_v2() const - { + inline std::shared_ptr get_sinsp_stats_v2() const { return m_sinsp_stats_v2; } @@ -504,9 +490,14 @@ class SINSP_PUBLIC sinsp : public capture_stats_source @throws a sinsp_exception containing the error string is thrown in case of failure. */ - inline const threadinfo_map_t::ptr_t& get_thread_ref(int64_t tid, bool query_os_if_not_found = false, bool lookup_only = true, bool main_thread = false) - { - return m_thread_manager->get_thread_ref(tid, query_os_if_not_found, lookup_only, main_thread); + inline const threadinfo_map_t::ptr_t& get_thread_ref(int64_t tid, + bool query_os_if_not_found = false, + bool lookup_only = true, + bool main_thread = false) { + return m_thread_manager->get_thread_ref(tid, + query_os_if_not_found, + lookup_only, + main_thread); } /*! @@ -530,38 +521,36 @@ class SINSP_PUBLIC sinsp : public capture_stats_source \return Pointer to a \ref metrics_v2 structure filled with the statistics. */ - const struct metrics_v2* get_capture_stats_v2(uint32_t flags, uint32_t* nstats, int32_t* rc) const override; + const struct metrics_v2* get_capture_stats_v2(uint32_t flags, + uint32_t* nstats, + int32_t* rc) const override; libsinsp::event_processor* m_external_event_processor; - inline std::unique_ptr build_threadinfo() - { - auto ret = m_external_event_processor ? m_external_event_processor->build_threadinfo(this) - : m_thread_manager->new_threadinfo(); + inline std::unique_ptr build_threadinfo() { + auto ret = m_external_event_processor ? m_external_event_processor->build_threadinfo(this) + : m_thread_manager->new_threadinfo(); m_thread_manager->set_tinfo_shared_dynamic_fields(*ret); return ret; - } + } - inline std::unique_ptr build_fdinfo() - { - auto ret = m_external_event_processor ? m_external_event_processor->build_fdinfo(this) - : m_thread_manager->new_fdinfo(); + inline std::unique_ptr build_fdinfo() { + auto ret = m_external_event_processor ? m_external_event_processor->build_fdinfo(this) + : m_thread_manager->new_fdinfo(); m_thread_manager->set_fdinfo_shared_dynamic_fields(*ret); return ret; - } + } /*! \brief registers external event processor. After this, callbacks on libsinsp::event_processor will happen at the appropriate times. This registration must happen before calling open. */ - void register_external_event_processor(libsinsp::event_processor& processor) - { + void register_external_event_processor(libsinsp::event_processor& processor) { m_external_event_processor = &processor; } - libsinsp::event_processor* get_external_event_processor() const - { + libsinsp::event_processor* get_external_event_processor() const { return m_external_event_processor; } @@ -576,10 +565,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source /*! \brief get last library error. */ - std::string getlasterr() const - { - return m_lasterr; - } + std::string getlasterr() const { return m_lasterr; } /*! \brief Get the list of machine network interfaces. @@ -588,15 +574,9 @@ class SINSP_PUBLIC sinsp : public capture_stats_source */ const sinsp_network_interfaces& get_ifaddr_list() const; - inline sinsp_network_interfaces& get_ifaddr_list() - { - return m_network_interfaces; - } + inline sinsp_network_interfaces& get_ifaddr_list() { return m_network_interfaces; } - inline void set_ifaddr_list(const sinsp_network_interfaces& v) - { - m_network_interfaces = v; - } + inline void set_ifaddr_list(const sinsp_network_interfaces& v) { m_network_interfaces = v; } /*! \brief Set the format used to render event data @@ -613,96 +593,66 @@ class SINSP_PUBLIC sinsp : public capture_stats_source /*! \brief Returns true if the current capture is happening from a scap file */ - inline bool is_capture() const - { - return m_mode == SINSP_MODE_CAPTURE; - } + inline bool is_capture() const { return m_mode == SINSP_MODE_CAPTURE; } /*! \brief Returns true if the current capture is offline */ - inline bool is_offline() const - { - return is_capture() || m_mode == SINSP_MODE_TEST; - } + inline bool is_offline() const { return is_capture() || m_mode == SINSP_MODE_TEST; } /*! \brief Returns true if the current capture is live */ - inline bool is_live() const - { - return m_mode == SINSP_MODE_LIVE; - } + inline bool is_live() const { return m_mode == SINSP_MODE_LIVE; } /*! \brief Returns true if the kernel module is not loaded */ - inline bool is_nodriver() const - { - return m_mode == SINSP_MODE_NODRIVER; - } + inline bool is_nodriver() const { return m_mode == SINSP_MODE_NODRIVER; } /*! \brief Returns true if the current capture has a plugin producing events. */ - inline bool is_plugin() const - { + inline bool is_plugin() const { return m_mode == SINSP_MODE_PLUGIN && m_input_plugin != nullptr; } /*! \brief Returns true if the current capture has a plugin producing syscall events. */ - inline bool is_syscall_plugin() const - { - return is_plugin() && m_input_plugin->id() == 0; - } + inline bool is_syscall_plugin() const { return is_plugin() && m_input_plugin->id() == 0; } /*! \brief Returns the framework plugin api version as a string with static storage */ - inline const char *get_plugin_api_version() const - { - return PLUGIN_API_VERSION_STR; - } + inline const char* get_plugin_api_version() const { return PLUGIN_API_VERSION_STR; } /*! \brief Returns the API version supported by the driver */ - inline uint64_t get_driver_api_version() const - { - return scap_get_driver_api_version(m_h); - } + inline uint64_t get_driver_api_version() const { return scap_get_driver_api_version(m_h); } /*! \brief Returns the minimum API version required by the userspace library */ - inline uint64_t get_scap_api_version() const - { - return SCAP_MINIMUM_DRIVER_API_VERSION; - } + inline uint64_t get_scap_api_version() const { return SCAP_MINIMUM_DRIVER_API_VERSION; } /*! \brief Returns the schema version supported by the driver */ - inline uint64_t get_driver_schema_version() const - { + inline uint64_t get_driver_schema_version() const { return scap_get_driver_schema_version(m_h); } /*! \brief Returns the minimum schema version required by the userspace library */ - inline uint64_t get_scap_schema_version() const - { - return SCAP_MINIMUM_DRIVER_SCHEMA_VERSION; - } + inline uint64_t get_scap_schema_version() const { return SCAP_MINIMUM_DRIVER_SCHEMA_VERSION; } /*! \brief Returns true if truncated environments should be loaded from /proc */ - inline bool large_envs_enabled() const - { + inline bool large_envs_enabled() const { return (is_live() || is_syscall_plugin()) && m_large_envs_enabled; } @@ -732,21 +682,18 @@ class SINSP_PUBLIC sinsp : public capture_stats_source */ void set_fatfile_dump_mode(bool enable_fatfile); - inline bool is_fatfile_enabled() const - { - return m_isfatfile_enabled; - } + inline bool is_fatfile_enabled() const { return m_isfatfile_enabled; } /*! \brief Set internal events mode. \note By default, internal events, such as events that note - when new containers or orchestration entities have - been created, are not returned in sinsp::next(). (They - are always written to capture files, to ensure that - the full state can be reconstructed when capture files - are read). Enabling internal events mode will result - in these events being returned. + when new containers or orchestration entities have + been created, are not returned in sinsp::next(). (They + are always written to capture files, to ensure that + the full state can be reconstructed when capture files + are read). Enabling internal events mode will result + in these events being returned. */ void set_internal_events_mode(bool enable_internal_events); @@ -761,8 +708,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source */ void set_hostname_and_port_resolution_mode(bool enable); - inline bool is_hostname_and_port_resolution_enabled() const - { + inline bool is_hostname_and_port_resolution_enabled() const { return m_hostname_and_port_resolution_enabled; } @@ -772,15 +718,9 @@ class SINSP_PUBLIC sinsp : public capture_stats_source \param flag Can be 'h', 'a', 'r', 'd', 'D' as documented in the manual. */ - inline void set_time_output_mode(char flag) - { - m_output_time_flag = flag; - } + inline void set_time_output_mode(char flag) { m_output_time_flag = flag; } - inline char get_time_output_mode() const - { - return m_output_time_flag; - } + inline char get_time_output_mode() const { return m_output_time_flag; } /*! \brief Sets the max length of event argument strings. @@ -791,26 +731,17 @@ class SINSP_PUBLIC sinsp : public capture_stats_source */ void set_max_evt_output_len(uint32_t len); - inline uint32_t get_max_evt_output_len() const - { - return m_max_evt_output_len; - } + inline uint32_t get_max_evt_output_len() const { return m_max_evt_output_len; } /*! \brief Returns true if the debug mode is enabled. */ - inline bool is_debug_enabled() const - { - return m_isdebug_enabled; - } + inline bool is_debug_enabled() const { return m_isdebug_enabled; } /*! \brief Returns true if extended user information is collected. */ - inline bool is_user_details_enabled() - { - return m_usergroup_manager.m_user_details_enabled; - } + inline bool is_user_details_enabled() { return m_usergroup_manager.m_user_details_enabled; } /*! \brief Set a flag indicating if the command line requested to show container information. @@ -819,23 +750,16 @@ class SINSP_PUBLIC sinsp : public capture_stats_source */ void set_print_container_data(bool print_container_data); - /*! \brief Returns true if the command line argument is set to show container information. */ - inline bool is_print_container_data() const - { - return m_print_container_data; - } + inline bool is_print_container_data() const { return m_print_container_data; } /*! \brief If this is an offline capture, return the name of the file that is being read, otherwise return an empty string. */ - std::string get_input_filename() const - { - return m_input_filename; - } + std::string get_input_filename() const { return m_input_filename; } /*! \brief When reading events from a trace file or a plugin, this function @@ -856,14 +780,10 @@ class SINSP_PUBLIC sinsp : public capture_stats_source \brief Make the amount of data gathered for a syscall to be determined by the number of parameters. */ - virtual int /*SCAP_X*/ dynamic_snaplen(bool enable) - { - if(enable) - { + virtual int /*SCAP_X*/ dynamic_snaplen(bool enable) { + if(enable) { return scap_enable_dynamic_snaplen(m_h); - } - else - { + } else { return scap_disable_dynamic_snaplen(m_h); } } @@ -873,37 +793,35 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // void stop_dropping_mode(); void start_dropping_mode(uint32_t sampling_ratio); - void on_new_entry_from_proc(void* context, int64_t tid, scap_threadinfo* tinfo, scap_fdinfo* fdinfo); - void set_get_procs_cpu_from_driver(bool get_procs_cpu_from_driver) - { + void on_new_entry_from_proc(void* context, + int64_t tid, + scap_threadinfo* tinfo, + scap_fdinfo* fdinfo); + void set_get_procs_cpu_from_driver(bool get_procs_cpu_from_driver) { m_get_procs_cpu_from_driver = get_procs_cpu_from_driver; } - inline sinsp_parser* get_parser() - { - return m_parser.get(); - } + inline sinsp_parser* get_parser() { return m_parser.get(); } - inline const sinsp_parser* get_parser() const - { - return m_parser.get(); - } + inline const sinsp_parser* get_parser() const { return m_parser.get(); } - /*=============================== PPM_SC set related (ppm_sc.cpp) ===============================*/ + /*=============================== PPM_SC set related (ppm_sc.cpp) + * ===============================*/ /*! - \brief Mark desired scap code as (un)interesting, enabling or disabling its collection. - Note that the same ppm_code can match multiple system syscalls or tracepoints. + \brief Mark desired scap code as (un)interesting, enabling or disabling its collection. + Note that the same ppm_code can match multiple system syscalls or tracepoints. - Please note that this method must be called when the inspector is already open to - modify at runtime the interesting syscall set. + Please note that this method must be called when the inspector is already open to + modify at runtime the interesting syscall set. - WARNING: playing with this API could break `libsinsp` state collection, this is only - useful in advanced cases where the client needs to know what it is doing! + WARNING: playing with this API could break `libsinsp` state collection, this is only + useful in advanced cases where the client needs to know what it is doing! */ void mark_ppm_sc_of_interest(ppm_sc_code ppm_sc, bool enabled = true); - /*=============================== PPM_SC set related (ppm_sc.cpp) ===============================*/ + /*=============================== PPM_SC set related (ppm_sc.cpp) + * ===============================*/ /*=============================== Engine related ===============================*/ @@ -919,31 +837,27 @@ class SINSP_PUBLIC sinsp : public capture_stats_source void import_ipv4_interface(const sinsp_ipv4_ifinfo& ifinfo); - uint64_t get_bytes_read() const - { - return scap_ftell(m_h); - } + uint64_t get_bytes_read() const { return scap_ftell(m_h); } void refresh_ifaddr_list(); - void refresh_proc_list() { - scap_refresh_proc_table(get_scap_platform()); - } + void refresh_proc_list() { scap_refresh_proc_table(get_scap_platform()); } std::vector get_n_tracepoint_hit() const; static unsigned num_possible_cpus(); - inline void set_container_engine_mask(uint64_t mask) - { + inline void set_container_engine_mask(uint64_t mask) { m_container_manager.set_container_engine_mask(mask); } - inline void set_static_container(const std::string& id, const std::string& name, const std::string& image) { + inline void set_static_container(const std::string& id, + const std::string& name, + const std::string& image) { m_container_manager.set_static_container(id, name, image); } // Add comm to the list of comms for which the inspector // should not return events. - bool suppress_events_comm(const std::string &comm); + bool suppress_events_comm(const std::string& comm); bool suppress_events_tid(int64_t tid); @@ -969,7 +883,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source /*! \brief Pushed a new path to the list of crio socket paths */ - void add_cri_socket_path(const std::string &path); + void add_cri_socket_path(const std::string& path); void set_cri_timeout(int64_t timeout_ms); void set_cri_async(bool async); @@ -985,21 +899,16 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // internally. std::shared_ptr register_plugin(const plugin_api* api); - inline std::shared_ptr get_plugin_manager() const - { + inline std::shared_ptr get_plugin_manager() const { return m_plugin_manager; } void handle_async_event(std::unique_ptr evt); void handle_plugin_async_event(const sinsp_plugin& p, std::unique_ptr evt); - inline const std::vector& event_sources() const - { - return m_event_sources; - } + inline const std::vector& event_sources() const { return m_event_sources; } - inline const std::shared_ptr& get_table_registry() const - { + inline const std::shared_ptr& get_table_registry() const { return m_table_registry; } @@ -1027,102 +936,56 @@ class SINSP_PUBLIC sinsp : public capture_stats_source * \return The current time in nanoseconds if the last event timestamp is 0, * otherwise, the last event timestamp. */ - inline uint64_t get_new_ts() const - { + inline uint64_t get_new_ts() const { // m_lastevent_ts = 0 at startup when containers are // being created as a part of the initial process // scan. - return (m_lastevent_ts == 0) - ? sinsp_utils::get_current_time_ns() - : m_lastevent_ts; + return (m_lastevent_ts == 0) ? sinsp_utils::get_current_time_ns() : m_lastevent_ts; } bool remove_inactive_threads(); - inline const std::shared_ptr& add_thread(std::unique_ptr ptinfo) - { + inline const std::shared_ptr& add_thread( + std::unique_ptr ptinfo) { return m_thread_manager->add_thread(std::move(ptinfo), false); } - void set_mode(sinsp_mode_t value) - { - m_mode = value; - } + void set_mode(sinsp_mode_t value) { m_mode = value; } - inline void remove_thread(int64_t tid) - { - m_thread_manager->remove_thread(tid); - } + inline void remove_thread(int64_t tid) { m_thread_manager->remove_thread(tid); } - inline const struct scap_platform* get_scap_platform() const - { - return m_platform; - } + inline const struct scap_platform* get_scap_platform() const { return m_platform; } - inline struct scap_platform* get_scap_platform() - { - return m_platform; - } + inline struct scap_platform* get_scap_platform() { return m_platform; } - inline const scap_t* get_scap_handle() const - { - return m_h; - } + inline const scap_t* get_scap_handle() const { return m_h; } - inline scap_t* get_scap_handle() - { - return m_h; - } + inline scap_t* get_scap_handle() { return m_h; } - inline int64_t get_tid_to_remove() const - { - return m_tid_to_remove; - } + inline int64_t get_tid_to_remove() const { return m_tid_to_remove; } - inline void set_tid_to_remove(int64_t v) - { - m_tid_to_remove = v; - } + inline void set_tid_to_remove(int64_t v) { m_tid_to_remove = v; } - inline bool is_dumping() const - { - return m_is_dumping; - } + inline bool is_dumping() const { return m_is_dumping; } - inline void set_dumping(bool v) - { - m_is_dumping = v; - } + inline void set_dumping(bool v) { m_is_dumping = v; } - inline int64_t get_tid_of_fd_to_remove() const - { - return m_tid_of_fd_to_remove; - } + inline int64_t get_tid_of_fd_to_remove() const { return m_tid_of_fd_to_remove; } - inline void set_tid_of_fd_to_remove(int64_t v) - { - m_tid_of_fd_to_remove = v; - } + inline void set_tid_of_fd_to_remove(int64_t v) { m_tid_of_fd_to_remove = v; } - inline uint32_t get_num_cpus() const - { - return m_num_cpus; - } + inline uint32_t get_num_cpus() const { return m_num_cpus; } - inline const std::vector& get_fds_to_remove() const - { - return m_fds_to_remove; - } + inline const std::vector& get_fds_to_remove() const { return m_fds_to_remove; } - inline std::vector& get_fds_to_remove() - { - return m_fds_to_remove; - } + inline std::vector& get_fds_to_remove() { return m_fds_to_remove; } private: void set_input_plugin(const std::string& name, const std::string& params); - void open_common(scap_open_args* oargs, const struct scap_vtable* vtable, struct scap_platform* platform, - sinsp_mode_t mode); + void open_common(scap_open_args* oargs, + const struct scap_vtable* vtable, + struct scap_platform* platform, + sinsp_mode_t mode); void init(); void deinit_state(); void consume_initialstate_events(); @@ -1137,18 +1000,16 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // just for lookup reason. In that case, m_lastaccess_ts is not updated // and m_last_tinfo is not set. // - inline const threadinfo_map_t::ptr_t& find_thread(int64_t tid, bool lookup_only) - { + inline const threadinfo_map_t::ptr_t& find_thread(int64_t tid, bool lookup_only) { return m_thread_manager->find_thread(tid, lookup_only); } - static int64_t get_file_size(const std::string& fname, char *error); + static int64_t get_file_size(const std::string& fname, char* error); static std::string get_error_desc(const std::string& msg = ""); void restart_capture(); - bool increased_snaplen_port_range_set() const - { + bool increased_snaplen_port_range_set() const { return m_increased_snaplen_port_range.range_start > 0 && m_increased_snaplen_port_range.range_end > 0; } @@ -1161,14 +1022,13 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // regulates the logic behind event timestamp ordering. // returns true if left "comes first" than right, and false otherwise. // UINT64_MAX stands for max time priority -- as early as possible. - static inline bool compare_evt_timestamps(uint64_t left, uint64_t right) - { + static inline bool compare_evt_timestamps(uint64_t left, uint64_t right) { return left == static_cast(-1) || left <= right; } std::shared_ptr m_sinsp_stats_v2; scap_t* m_h; - struct scap_platform* m_platform {}; + struct scap_platform* m_platform{}; char m_platform_lasterr[SCAP_LASTERR_SIZE]; uint64_t m_nevts; int64_t m_filesize; @@ -1200,7 +1060,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source uint32_t m_num_cpus; bool m_large_envs_enabled; - sinsp_network_interfaces m_network_interfaces {}; + sinsp_network_interfaces m_network_interfaces{}; std::string m_host_root; @@ -1234,8 +1094,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // // Saved increased capture range // - struct - { + struct { uint16_t range_start; uint16_t range_end; } m_increased_snaplen_port_range; @@ -1277,10 +1136,8 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // m_injected_evts comparator using sinsp_evt_ptr = std::unique_ptr; - struct state_evts_less - { - bool operator()(const sinsp_evt& l, const sinsp_evt& r) - { + struct state_evts_less { + bool operator()(const sinsp_evt& l, const sinsp_evt& r) { // order events in reverse-order as the lowest timestamp // has the highest priority return !compare_evt_timestamps(l.get_ts(), r.get_ts()); @@ -1293,12 +1150,10 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // predicate struct for checking the head of the async events queue. // keeping a struct in the internal state makes sure that we don't do // any extra allocation by creating a lambda and its closure - struct - { + struct { uint64_t ts{0}; - bool operator()(const sinsp_evt& evt) const - { + bool operator()(const sinsp_evt& evt) const { return compare_evt_timestamps(evt.get_scap_evt()->ts, ts); }; } m_async_events_checker; @@ -1308,38 +1163,30 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // temp storage for scap_next // stores top scap_evt while qualified events from m_async_events_queue are being processed - struct - { - inline auto next(scap_t* h) - { + struct { + inline auto next(scap_t* h) { auto res = scap_next(h, &m_pevt, &m_cpuid, &m_dump_flags); - if (res != SCAP_SUCCESS) - { + if(res != SCAP_SUCCESS) { clear(); } return res; } - inline void move(sinsp_evt * evt) - { + inline void move(sinsp_evt* evt) { evt->set_scap_evt(m_pevt); evt->set_cpuid(m_cpuid); evt->set_dump_flags(m_dump_flags); clear(); } - inline bool empty() const - { - return m_pevt == nullptr; - } - inline void clear() - { + inline bool empty() const { return m_pevt == nullptr; } + inline void clear() { m_pevt = nullptr; m_cpuid = 0; m_dump_flags = 0; } scap_evt* m_pevt{nullptr}; - uint16_t m_cpuid{0}; - uint32_t m_dump_flags; + uint16_t m_cpuid{0}; + uint32_t m_dump_flags; } m_delayed_scap_evt; // @@ -1359,7 +1206,6 @@ class SINSP_PUBLIC sinsp : public capture_stats_source int64_t m_self_pid; - // // /proc scan parameters // @@ -1398,7 +1244,7 @@ class SINSP_PUBLIC sinsp : public capture_stats_source // If non-null, sinsp::next will use this pointer instead of invoking scap_next(). // After using this event, sinsp::next() will set this back to NULL. // This is used internally during the state initialization phase. - scap_evt *m_replay_scap_evt; + scap_evt* m_replay_scap_evt; // // This is related to m_replay_scap_evt, and is used to store the additional cpuid // information of the replayed scap event. diff --git a/userspace/libsinsp/sinsp_cgroup.cpp b/userspace/libsinsp/sinsp_cgroup.cpp index cc7064bc04..8506d4b4c2 100644 --- a/userspace/libsinsp/sinsp_cgroup.cpp +++ b/userspace/libsinsp/sinsp_cgroup.cpp @@ -21,33 +21,27 @@ limitations under the License. #include #include -sinsp_cgroup::sinsp_cgroup(bool with_self_cg) : - sinsp_cgroup(scap_get_host_root(), with_self_cg) -{ -} +sinsp_cgroup::sinsp_cgroup(bool with_self_cg): sinsp_cgroup(scap_get_host_root(), with_self_cg) {} -sinsp_cgroup::sinsp_cgroup(std::string &&root, bool with_self_cg) : - m_root(std::move(root)), - m_scap_cgroup({}) -{ +sinsp_cgroup::sinsp_cgroup(std::string &&root, bool with_self_cg): + m_root(std::move(root)), + m_scap_cgroup({}) { char error[SCAP_LASTERR_SIZE]; scap_cgroup_interface_init(&m_scap_cgroup, m_root.c_str(), error, with_self_cg); } -std::shared_ptr sinsp_cgroup::lookup_cgroup_dir(const std::string &subsys, int &version) -{ +std::shared_ptr sinsp_cgroup::lookup_cgroup_dir(const std::string &subsys, + int &version) { const char *scap_cgroup_dir; const auto &it = m_cgroup_dir_cache.find(subsys); - if(it != m_cgroup_dir_cache.end()) - { + if(it != m_cgroup_dir_cache.end()) { version = it->second.second; return it->second.first; } scap_cgroup_dir = scap_cgroup_get_subsys_mount(&m_scap_cgroup, subsys.c_str(), &version); - if(scap_cgroup_dir != nullptr) - { + if(scap_cgroup_dir != nullptr) { auto cgroup_dir = std::make_shared(scap_cgroup_dir); m_cgroup_dir_cache[subsys] = std::make_pair(cgroup_dir, version); return cgroup_dir; @@ -56,49 +50,41 @@ std::shared_ptr sinsp_cgroup::lookup_cgroup_dir(const std::string & return nullptr; } -void sinsp_cgroup::lookup_cgroups(sinsp_threadinfo& tinfo) -{ +void sinsp_cgroup::lookup_cgroups(sinsp_threadinfo &tinfo) { std::string procdirname = m_root + "/proc/" + std::to_string(tinfo.m_tid) + '/'; scap_cgroup_set thread_cgroups = {}; char error[SCAP_LASTERR_SIZE]; int ret = scap_cgroup_get_thread(&m_scap_cgroup, procdirname.c_str(), &thread_cgroups, error); - if(ret != SCAP_SUCCESS) - { + if(ret != SCAP_SUCCESS) { return; } tinfo.set_cgroups(thread_cgroups.path, thread_cgroups.len); } -sinsp_cgroup &sinsp_cgroup::instance() -{ +sinsp_cgroup &sinsp_cgroup::instance() { static std::unique_ptr instance; - if(instance == nullptr) - { + if(instance == nullptr) { instance = std::make_unique(); } return *instance; } -sinsp_cgroup::~sinsp_cgroup() -{ +sinsp_cgroup::~sinsp_cgroup() { #ifdef __linux__ scap_cgroup_clear_cache(&m_scap_cgroup); -#endif // __linux__ +#endif // __linux__ } -bool sinsp_cgroup::in_cgroupns() const -{ +bool sinsp_cgroup::in_cgroupns() const { return m_scap_cgroup.m_in_cgroupns; } -std::string sinsp_cgroup::self_v2() const -{ - if(!m_scap_cgroup.m_self_v2[0]) - { +std::string sinsp_cgroup::self_v2() const { + if(!m_scap_cgroup.m_self_v2[0]) { return {}; } return m_scap_cgroup.m_self_v2; diff --git a/userspace/libsinsp/sinsp_cgroup.h b/userspace/libsinsp/sinsp_cgroup.h index c68edec89b..8a0d4105bb 100644 --- a/userspace/libsinsp/sinsp_cgroup.h +++ b/userspace/libsinsp/sinsp_cgroup.h @@ -36,7 +36,7 @@ class sinsp_cgroup { std::shared_ptr lookup_cgroup_dir(const std::string &subsys, int &version); - void lookup_cgroups(sinsp_threadinfo& tinfo); + void lookup_cgroups(sinsp_threadinfo &tinfo); static sinsp_cgroup &instance(); @@ -47,5 +47,6 @@ class sinsp_cgroup { protected: std::string m_root; struct scap_cgroup_interface m_scap_cgroup; - std::unordered_map, int>> m_cgroup_dir_cache; + std::unordered_map, int>> + m_cgroup_dir_cache; }; diff --git a/userspace/libsinsp/sinsp_cycledumper.cpp b/userspace/libsinsp/sinsp_cycledumper.cpp index 47c6c5f412..158817e60c 100644 --- a/userspace/libsinsp/sinsp_cycledumper.cpp +++ b/userspace/libsinsp/sinsp_cycledumper.cpp @@ -19,88 +19,76 @@ limitations under the License. #include #include - -sinsp_cycledumper::sinsp_cycledumper(sinsp* inspector, const std::string& base_filename, - const int& rollover_mb, const int& duration_seconds, - const int& file_limit, const unsigned long& event_limit, - const bool& compress): - m_last_time(0), - m_file_count_total(0), - m_file_index(0), - m_has_started(false), - m_event_count(0L), - m_past_names(NULL), - m_limit_format("") -{ +sinsp_cycledumper::sinsp_cycledumper(sinsp* inspector, + const std::string& base_filename, + const int& rollover_mb, + const int& duration_seconds, + const int& file_limit, + const unsigned long& event_limit, + const bool& compress): + m_last_time(0), + m_file_count_total(0), + m_file_index(0), + m_has_started(false), + m_event_count(0L), + m_past_names(NULL), + m_limit_format("") { m_base_filename = base_filename; m_rollover_mb = rollover_mb * 1000000L; m_duration_seconds = duration_seconds; m_file_limit = file_limit; m_event_limit = event_limit; - m_inspector = inspector; - m_compress = compress; + m_inspector = inspector; + m_compress = compress; - if(duration_seconds > 0 && file_limit > 0) - { + if(duration_seconds > 0 && file_limit > 0) { m_past_names = new std::string[file_limit]; - for(int32_t j = 0; j < file_limit; j++) - { + for(int32_t j = 0; j < file_limit; j++) { m_past_names[j] = ""; } } } -sinsp_cycledumper::~sinsp_cycledumper() -{ - if(m_dumper != nullptr) - { +sinsp_cycledumper::~sinsp_cycledumper() { + if(m_dumper != nullptr) { m_dumper->close(); m_dumper.reset(); } - if(m_past_names != nullptr) - { + if(m_past_names != nullptr) { delete[] m_past_names; } } -void sinsp_cycledumper::dump(sinsp_evt* evt) -{ - if(is_new_file_needed(evt)) - { +void sinsp_cycledumper::dump(sinsp_evt* evt) { + if(is_new_file_needed(evt)) { autodump_next_file(); - } - m_dumper->dump(evt); + } + m_dumper->dump(evt); } -void sinsp_cycledumper::close() -{ +void sinsp_cycledumper::close() { autodump_stop(); } void sinsp_cycledumper::set_callbacks(std::vector open_cbs, - std::vector close_cbs) -{ + std::vector close_cbs) { m_open_file_callbacks = open_cbs; m_close_file_callbacks = close_cbs; } -void sinsp_cycledumper::autodump_next_file() -{ +void sinsp_cycledumper::autodump_next_file() { autodump_stop(); autodump_start(m_current_filename); } -void sinsp_cycledumper::autodump_stop() -{ - if(!m_inspector) - { +void sinsp_cycledumper::autodump_stop() { + if(!m_inspector) { throw sinsp_exception("inspector not opened yet"); } - if(m_dumper) - { + if(m_dumper) { m_dumper->close(); m_dumper.reset(); } @@ -110,56 +98,45 @@ void sinsp_cycledumper::autodump_stop() std::for_each(m_close_file_callbacks.begin(), m_close_file_callbacks.end(), std::ref(*this)); } -void sinsp_cycledumper::autodump_start(const std::string& dump_filename) -{ - if(!m_inspector) - { +void sinsp_cycledumper::autodump_start(const std::string& dump_filename) { + if(!m_inspector) { throw sinsp_exception("inspector not opened yet"); } - if(!m_dumper) - { + if(!m_dumper) { m_dumper = std::make_unique(); } std::for_each(m_open_file_callbacks.begin(), m_open_file_callbacks.end(), std::ref(*this)); - m_dumper->open(m_inspector, dump_filename.c_str(), - m_compress ? SCAP_COMPRESSION_GZIP : SCAP_COMPRESSION_NONE); + m_dumper->open(m_inspector, + dump_filename.c_str(), + m_compress ? SCAP_COMPRESSION_GZIP : SCAP_COMPRESSION_NONE); m_inspector->set_dumping(true); } -void sinsp_cycledumper::next_file() -{ - if (m_file_limit > 0 && m_file_index >= m_file_limit) - { +void sinsp_cycledumper::next_file() { + if(m_file_limit > 0 && m_file_index >= m_file_limit) { m_file_index = 0; } - - if(m_duration_seconds > 0) - { + if(m_duration_seconds > 0) { // if the user has specified a format then use it - if(m_base_filename.find("%") != std::string::npos) - { + if(m_base_filename.find("%") != std::string::npos) { const size_t our_size = 4096; char filename[our_size]; - const struct tm *our_time = localtime(&m_last_time); - if(our_time == nullptr) - { + const struct tm* our_time = localtime(&m_last_time); + if(our_time == nullptr) { throw sinsp_exception("cannot get localtime in cycle_writer::next_file"); } - if(!strftime(filename, our_size, m_base_filename.c_str(), our_time)) - { + if(!strftime(filename, our_size, m_base_filename.c_str(), our_time)) { throw sinsp_exception("filename too long!"); } - if(m_file_limit > 0) - { - if(m_past_names[m_file_index] != "") - { + if(m_file_limit > 0) { + if(m_past_names[m_file_index] != "") { remove(m_past_names[m_file_index].c_str()); } @@ -167,27 +144,20 @@ void sinsp_cycledumper::next_file() } m_current_filename = filename; - } - else // if no format is provided, then use a counter + } else // if no format is provided, then use a counter { m_current_filename = m_base_filename + std::to_string(m_file_index); } - } - else - { + } else { m_current_filename = m_base_filename; } - if(m_rollover_mb > 0) - { - - if(m_limit_format.empty()) - { + if(m_rollover_mb > 0) { + if(m_limit_format.empty()) { int digit_count = 0; int our_file_limit = m_file_limit; - while(our_file_limit > 0) - { + while(our_file_limit > 0) { digit_count++; our_file_limit /= 10; } @@ -204,8 +174,7 @@ void sinsp_cycledumper::next_file() m_current_filename += index; } - if(m_event_limit > 0) - { + if(m_event_limit > 0) { m_current_filename = m_base_filename + std::to_string(m_file_index); } @@ -213,32 +182,26 @@ void sinsp_cycledumper::next_file() m_file_index++; } -bool sinsp_cycledumper::is_new_file_needed(sinsp_evt* evt) -{ +bool sinsp_cycledumper::is_new_file_needed(sinsp_evt* evt) { m_event_count++; - if(m_has_started == false) - { + if(m_has_started == false) { m_has_started = true; - if(m_duration_seconds > 0) - { - // timer setup - m_last_time = evt->get_ts() / ONE_SECOND_IN_NS; // 10^(-9) because it's nanoseconds - } - - if(!m_inspector->is_live()) - { - m_last_time = time(NULL); - } - next_file(); + if(m_duration_seconds > 0) { + // timer setup + m_last_time = evt->get_ts() / ONE_SECOND_IN_NS; // 10^(-9) because it's nanoseconds + } + + if(!m_inspector->is_live()) { + m_last_time = time(NULL); + } + next_file(); return true; } - if(m_duration_seconds > 0) - { - if((int)difftime(evt->get_ts() / ONE_SECOND_IN_NS, m_last_time) >= m_duration_seconds) - { + if(m_duration_seconds > 0) { + if((int)difftime(evt->get_ts() / ONE_SECOND_IN_NS, m_last_time) >= m_duration_seconds) { m_last_time = evt->get_ts() / ONE_SECOND_IN_NS; m_last_reason = "Maximum Time Reached"; next_file(); @@ -246,16 +209,14 @@ bool sinsp_cycledumper::is_new_file_needed(sinsp_evt* evt) } } - if(m_rollover_mb > 0 && m_dumper->written_bytes() > (uint64_t)m_rollover_mb) - { + if(m_rollover_mb > 0 && m_dumper->written_bytes() > (uint64_t)m_rollover_mb) { m_last_reason = "Maximum File Size Reached"; next_file(); return true; } // Event limit - if(m_event_limit > 0 && m_event_count >= m_event_limit) - { + if(m_event_limit > 0 && m_event_count >= m_event_limit) { m_event_count = 0L; m_last_reason = "Maximum Event Number Reached"; next_file(); diff --git a/userspace/libsinsp/sinsp_cycledumper.h b/userspace/libsinsp/sinsp_cycledumper.h index 496a0ea8f6..22525e087a 100644 --- a/userspace/libsinsp/sinsp_cycledumper.h +++ b/userspace/libsinsp/sinsp_cycledumper.h @@ -23,100 +23,101 @@ limitations under the License. #include -class SINSP_PUBLIC sinsp_cycledumper -{ - - typedef std::function callback; +class SINSP_PUBLIC sinsp_cycledumper { + typedef std::function callback; public: - sinsp_cycledumper(sinsp* inspector, const std::string& base_filename, - const int& rollover_mb, const int& duration_seconds, - const int& file_limit, const unsigned long& event_limit, - const bool& compress); - ~sinsp_cycledumper(); + sinsp_cycledumper(sinsp* inspector, + const std::string& base_filename, + const int& rollover_mb, + const int& duration_seconds, + const int& file_limit, + const unsigned long& event_limit, + const bool& compress); + ~sinsp_cycledumper(); - /*! - \brief Dumper the event to the scap file. + /*! + \brief Dumper the event to the scap file. - \param evt Pointer to an event. - */ - void dump(sinsp_evt* evt); + \param evt Pointer to an event. + */ + void dump(sinsp_evt* evt); - /*! - \brief Close the dumper. + /*! + \brief Close the dumper. - \note This has to be called once the capture is ended. - */ - void close(); + \note This has to be called once the capture is ended. + */ + void close(); - /*! - \brief Set open and close file callbacks - */ - void set_callbacks(std::vector open_cbs, std::vector close_cbs); + /*! + \brief Set open and close file callbacks + */ + void set_callbacks(std::vector open_cbs, std::vector close_cbs); - void operator() (callback cb) { cb(); } + void operator()(callback cb) { cb(); } private: - sinsp* m_inspector; - std::unique_ptr m_dumper; //!< Underlying sinsp_dumper used. - - std::string m_base_filename; //!< The base name of the scap file. - int m_rollover_mb; //!< Max scap file size in MB. - int m_duration_seconds; //!< Max duration for each capture in seconds. - int m_file_limit; //!< Max number of scap file generated. - unsigned long m_event_limit; //!< Max number of events for each catpure. - time_t m_last_time; //!< Last time of a capture. - int m_file_count_total; //!< Total number of files written. - int m_file_index; //!< Current file index. - bool m_has_started; //!< Indicates if the cycledumper has started for the first time. - unsigned long m_event_count; //!< Number of events of the current scap file. - std::string *m_past_names; //!< Ring buffer to maintain the file names for scap rotation. - std::string m_limit_format; //!< Format string for adding left padding zeros in scap filename. - std::string m_current_filename; //!< Current file filename. - bool m_compress; //!< Indicates if the scap file has to be compressed with zlib. - std::string m_last_reason; //!< Last reason for a new file. - std::vector m_open_file_callbacks; - std::vector m_close_file_callbacks; - - /*! - \brief Check if a new file is needed. - - \param evt Pointer to an event. - - \note to determine if a new file is needed it considers the fize size - at the current time. The reason for the return code is written to - m_last_reason. - */ - bool is_new_file_needed(sinsp_evt* evt); - - /*! - \brief Setups the new current filename. - - \note In \ref get_current_filename() will contain the new capture file - name that will be used. - */ - void next_file(); - - /*! - \brief Cycles the file pointer to a new capture file - */ - void autodump_next_file(); - - /*! - \brief Stops an event dump that was started with \ref autodump_start(). - - @throws a sinsp_exception containing the error string is thrown in case - of failure. - */ - void autodump_stop(); - - /*! - \brief Start writing the captured events to file. - - \param dump_filename the destination trace file. - - @throws a sinsp_exception containing the error string is thrown in case - of failure. - */ - void autodump_start(const std::string& dump_filename); + sinsp* m_inspector; + std::unique_ptr m_dumper; //!< Underlying sinsp_dumper used. + + std::string m_base_filename; //!< The base name of the scap file. + int m_rollover_mb; //!< Max scap file size in MB. + int m_duration_seconds; //!< Max duration for each capture in seconds. + int m_file_limit; //!< Max number of scap file generated. + unsigned long m_event_limit; //!< Max number of events for each catpure. + time_t m_last_time; //!< Last time of a capture. + int m_file_count_total; //!< Total number of files written. + int m_file_index; //!< Current file index. + bool m_has_started; //!< Indicates if the cycledumper has started for the first time. + unsigned long m_event_count; //!< Number of events of the current scap file. + std::string* m_past_names; //!< Ring buffer to maintain the file names for scap rotation. + std::string m_limit_format; //!< Format string for adding left padding zeros in scap filename. + std::string m_current_filename; //!< Current file filename. + bool m_compress; //!< Indicates if the scap file has to be compressed with zlib. + std::string m_last_reason; //!< Last reason for a new file. + std::vector m_open_file_callbacks; + std::vector m_close_file_callbacks; + + /*! + \brief Check if a new file is needed. + + \param evt Pointer to an event. + + \note to determine if a new file is needed it considers the fize size + at the current time. The reason for the return code is written to + m_last_reason. + */ + bool is_new_file_needed(sinsp_evt* evt); + + /*! + \brief Setups the new current filename. + + \note In \ref get_current_filename() will contain the new capture file + name that will be used. + */ + void next_file(); + + /*! + \brief Cycles the file pointer to a new capture file + */ + void autodump_next_file(); + + /*! + \brief Stops an event dump that was started with \ref autodump_start(). + + @throws a sinsp_exception containing the error string is thrown in case + of failure. + */ + void autodump_stop(); + + /*! + \brief Start writing the captured events to file. + + \param dump_filename the destination trace file. + + @throws a sinsp_exception containing the error string is thrown in case + of failure. + */ + void autodump_start(const std::string& dump_filename); }; diff --git a/userspace/libsinsp/sinsp_debug/CMakeLists.txt b/userspace/libsinsp/sinsp_debug/CMakeLists.txt index 336a22a620..5ce8fb6407 100644 --- a/userspace/libsinsp/sinsp_debug/CMakeLists.txt +++ b/userspace/libsinsp/sinsp_debug/CMakeLists.txt @@ -2,39 +2,32 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # -add_executable(sinsp-debug - sinsp_debug.cpp -) +add_executable(sinsp-debug sinsp_debug.cpp) -target_link_libraries(sinsp-debug - PRIVATE - sinsp -) +target_link_libraries(sinsp-debug PRIVATE sinsp) -if (EMSCRIPTEN) +if(EMSCRIPTEN) target_compile_options(sinsp-debug PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0") target_link_options(sinsp-debug PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0") target_link_options(sinsp-debug PRIVATE "-sALLOW_MEMORY_GROWTH=1") target_link_options(sinsp-debug PRIVATE "-sEXPORTED_FUNCTIONS=['_main','_htons','_ntohs']") - # note(jasondellaluce): since we run tests with node, we need to add this - # for reading from local capture files. + # note(jasondellaluce): since we run tests with node, we need to add this for reading from local + # capture files. target_link_options(sinsp-debug PRIVATE "-sNODERAWFS=1") endif() -if (APPLE AND NOT MINIMAL_BUILD) +if(APPLE AND NOT MINIMAL_BUILD) # Needed when linking libcurl set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -framework Foundation -framework SystemConfiguration") endif() diff --git a/userspace/libsinsp/sinsp_debug/sinsp_debug.cpp b/userspace/libsinsp/sinsp_debug/sinsp_debug.cpp index 69825a336a..0e6cbb9286 100644 --- a/userspace/libsinsp/sinsp_debug/sinsp_debug.cpp +++ b/userspace/libsinsp/sinsp_debug/sinsp_debug.cpp @@ -5,34 +5,31 @@ static bool g_interrupted = false; -static void sigint_handler(int signum) { g_interrupted = true; } +static void sigint_handler(int signum) { + g_interrupted = true; +} -std::string thread_info_to_string(sinsp_threadinfo* tinfo) -{ +std::string thread_info_to_string(sinsp_threadinfo* tinfo) { std::ostringstream out; - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { /* Main thread notation */ out << "[" << tinfo->get_comm() << "]"; - } - else - { + } else { /* Secondary thread notation */ out << "{" << tinfo->get_comm() << "}"; } /* if it is a reaper add (R)*/ - if(tinfo->m_tginfo && tinfo->m_tginfo->is_reaper()) - { + if(tinfo->m_tginfo && tinfo->m_tginfo->is_reaper()) { out << "💀"; } out << " t: " << tinfo->m_tid; out << ", p: " << tinfo->m_pid; - out << ", rpt: " << tinfo->m_ptid; // rpt (real parent tid) + out << ", rpt: " << tinfo->m_ptid; // rpt (real parent tid) out << ", vt: " << tinfo->m_vtid; out << ", vp: " << tinfo->m_vpid; - out << ", vs: " << tinfo->m_sid; // vs (we call it sid but it is a vsid) + out << ", vs: " << tinfo->m_sid; // vs (we call it sid but it is a vsid) out << ", vpg: " << tinfo->m_vpgid; out << ", ct: " << tinfo->is_in_pid_namespace(); out << ", e: " << tinfo->get_exepath(); @@ -40,20 +37,16 @@ std::string thread_info_to_string(sinsp_threadinfo* tinfo) return out.str(); } -void display_thread_lineage(sinsp_threadinfo* tinfo) -{ - sinsp_threadinfo::visitor_func_t scap_file_visitor = [](sinsp_threadinfo* pt) - { - if(pt == nullptr) - { +void display_thread_lineage(sinsp_threadinfo* tinfo) { + sinsp_threadinfo::visitor_func_t scap_file_visitor = [](sinsp_threadinfo* pt) { + if(pt == nullptr) { printf("X - Null thread info detected\n"); } printf("⬇️ %s\n", thread_info_to_string(pt).c_str()); /* The parent could be 0 when we don't find the real parent */ - if(pt->m_tid == 1 || pt->m_ptid == 0 || pt->is_invalid()) - { + if(pt->m_tid == 1 || pt->m_ptid == 0 || pt->is_invalid()) { printf("END\n\n"); return false; } @@ -64,8 +57,7 @@ void display_thread_lineage(sinsp_threadinfo* tinfo) printf("⬇️ %s\n", thread_info_to_string(tinfo).c_str()); /* If the thread is invalid it has no parent */ - if(tinfo->is_invalid() || tinfo->m_ptid == 0) - { + if(tinfo->is_invalid() || tinfo->m_ptid == 0) { printf("END\n\n"); return; } @@ -73,13 +65,11 @@ void display_thread_lineage(sinsp_threadinfo* tinfo) tinfo->traverse_parent_state(scap_file_visitor); } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { signal(SIGINT, sigint_handler); signal(SIGTERM, sigint_handler); - if(argc != 2) - { + if(argc != 2) { std::cerr << "You need to provide the scap-file path. Bye!" << std::endl; exit(EXIT_FAILURE); } @@ -94,12 +84,10 @@ int main(int argc, char** argv) std::cout << "ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ ℹ️ " << std::endl << std::endl; // Print lineage for all threads in the table - inspector.m_thread_manager->get_threads()->loop( - [&](sinsp_threadinfo& tinfo) - { - printf("* %s\n", thread_info_to_string(&tinfo).c_str()); - return true; - }); + inspector.m_thread_manager->get_threads()->loop([&](sinsp_threadinfo& tinfo) { + printf("* %s\n", thread_info_to_string(&tinfo).c_str()); + return true; + }); std::cout << std::endl << std::endl << "-- Start capture" << std::endl; @@ -109,31 +97,26 @@ int main(int argc, char** argv) sinsp_evt* ev = nullptr; int32_t res = 0; - while(!g_interrupted) - { + while(!g_interrupted) { res = inspector.next(&ev); - if(res == SCAP_EOF) - { + if(res == SCAP_EOF) { std::cout << "-- EOF" << std::endl; g_interrupted = true; break; } - if(res != SCAP_SUCCESS) - { + if(res != SCAP_SUCCESS) { continue; } auto tinfo = ev->get_thread_info(); - if(tinfo == nullptr) - { + if(tinfo == nullptr) { continue; } // Print all interesting events uint16_t evt_type = ev->get_type(); - switch(evt_type) - { + switch(evt_type) { case PPME_SYSCALL_CLONE_11_X: case PPME_SYSCALL_CLONE_16_X: case PPME_SYSCALL_CLONE_17_X: @@ -144,21 +127,17 @@ int main(int argc, char** argv) case PPME_SYSCALL_VFORK_X: case PPME_SYSCALL_VFORK_17_X: case PPME_SYSCALL_VFORK_20_X: - case PPME_SYSCALL_CLONE3_X: - { + case PPME_SYSCALL_CLONE3_X: { int64_t child_tid = ev->get_param(0)->as(); - if(child_tid == 0) - { + if(child_tid == 0) { printf("🧵 CLONE CHILD EXIT: evt_num(%ld)\n", ev->get_num()); - } - else - { - printf("🧵 CLONE CALLER EXIT for child (%ld): evt_num(%ld)\n", child_tid, + } else { + printf("🧵 CLONE CALLER EXIT for child (%ld): evt_num(%ld)\n", + child_tid, ev->get_num()); } display_thread_lineage(tinfo); - } - break; + } break; case PPME_SYSCALL_EXECVE_8_X: case PPME_SYSCALL_EXECVE_13_X: @@ -176,13 +155,12 @@ int main(int argc, char** argv) case PPME_PROCEXIT_E: case PPME_PROCEXIT_1_E: printf("💥 THREAD EXIT: evt_num(%ld)\n", ev->get_num()); - for(const auto& child : tinfo->m_children) - { - if(!child.expired()) - { + for(const auto& child : tinfo->m_children) { + if(!child.expired()) { auto child_shr = child.lock().get(); printf("- move child, tid: %ld, ptid: %ld (dead) to a new reaper.\n", - child_shr->m_tid, child_shr->m_ptid); + child_shr->m_tid, + child_shr->m_ptid); } } display_thread_lineage(tinfo); @@ -204,12 +182,10 @@ int main(int argc, char** argv) std::cout << "📜📜📜📜📜📜📜📜📜📜📜📜📜📜📜📜📜📜📜" << std::endl << std::endl; // Print lineage for all threads in the table - inspector.m_thread_manager->get_threads()->loop( - [&](sinsp_threadinfo& tinfo) - { - display_thread_lineage(&tinfo); - return true; - }); + inspector.m_thread_manager->get_threads()->loop([&](sinsp_threadinfo& tinfo) { + display_thread_lineage(&tinfo); + return true; + }); return 0; } diff --git a/userspace/libsinsp/sinsp_errno.h b/userspace/libsinsp/sinsp_errno.h index cbc6c45fe8..8cb56a6ab1 100644 --- a/userspace/libsinsp/sinsp_errno.h +++ b/userspace/libsinsp/sinsp_errno.h @@ -16,147 +16,147 @@ limitations under the License. */ -#define SE_EPERM 1 /* Operation not permitted */ -#define SE_ENOENT 2 /* No such file or directory */ -#define SE_ESRCH 3 /* No such process */ -#define SE_EINTR 4 /* Interrupted system call */ -#define SE_EIO 5 /* I/O error */ -#define SE_ENXIO 6 /* No such device or address */ -#define SE_E2BIG 7 /* Arg list too long */ -#define SE_ENOEXEC 8 /* Exec format error */ -#define SE_EBADF 9 /* Bad file number */ -#define SE_ECHILD 10 /* No child processes */ -#define SE_EAGAIN 11 /* Try again */ -#define SE_ENOMEM 12 /* Out of memory */ -#define SE_EACCES 13 /* Permission denied */ -#define SE_EFAULT 14 /* Bad address */ -#define SE_ENOTBLK 15 /* Block device required */ -#define SE_EBUSY 16 /* Device or resource busy */ -#define SE_EEXIST 17 /* File exists */ -#define SE_EXDEV 18 /* Cross-device link */ -#define SE_ENODEV 19 /* No such device */ -#define SE_ENOTDIR 20 /* Not a directory */ -#define SE_EISDIR 21 /* Is a directory */ -#define SE_EINVAL 22 /* Invalid argument */ -#define SE_ENFILE 23 /* File table overflow */ -#define SE_EMFILE 24 /* Too many open files */ -#define SE_ENOTTY 25 /* Not a typewriter */ -#define SE_ETXTBSY 26 /* Text file busy */ -#define SE_EFBIG 27 /* File too large */ -#define SE_ENOSPC 28 /* No space left on device */ -#define SE_ESPIPE 29 /* Illegal seek */ -#define SE_EROFS 30 /* Read-only file system */ -#define SE_EMLINK 31 /* Too many links */ -#define SE_EPIPE 32 /* Broken pipe */ -#define SE_EDOM 33 /* Math argument out of domain of func */ -#define SE_ERANGE 34 /* Math result not representable */ -#define SE_EDEADLK 35 /* Resource deadlock would occur */ -#define SE_ENAMETOOLONG 36 /* File name too long */ -#define SE_ENOLCK 37 /* No record locks available */ -#define SE_ENOSYS 38 /* Function not implemented */ -#define SE_ENOTEMPTY 39 /* Directory not empty */ -#define SE_ELOOP 40 /* Too many symbolic links encountered */ -#define SE_EWOULDBLOCK EAGAIN /* Operation would block */ -#define SE_ENOMSG 42 /* No message of desired type */ -#define SE_EIDRM 43 /* Identifier removed */ -#define SE_ECHRNG 44 /* Channel number out of range */ -#define SE_EL2NSYNC 45 /* Level 2 not synchronized */ -#define SE_EL3HLT 46 /* Level 3 halted */ -#define SE_EL3RST 47 /* Level 3 reset */ -#define SE_ELNRNG 48 /* Link number out of range */ -#define SE_EUNATCH 49 /* Protocol driver not attached */ -#define SE_ENOCSI 50 /* No CSI structure available */ -#define SE_EL2HLT 51 /* Level 2 halted */ -#define SE_EBADE 52 /* Invalid exchange */ -#define SE_EBADR 53 /* Invalid request descriptor */ -#define SE_EXFULL 54 /* Exchange full */ -#define SE_ENOANO 55 /* No anode */ -#define SE_EBADRQC 56 /* Invalid request code */ -#define SE_EBADSLT 57 /* Invalid slot */ -#define SE_EDEADLOCK EDEADLK -#define SE_EBFONT 59 /* Bad font file format */ -#define SE_ENOSTR 60 /* Device not a stream */ -#define SE_ENODATA 61 /* No data available */ -#define SE_ETIME 62 /* Timer expired */ -#define SE_ENOSR 63 /* Out of streams resources */ -#define SE_ENONET 64 /* Machine is not on the network */ -#define SE_ENOPKG 65 /* Package not installed */ -#define SE_EREMOTE 66 /* Object is remote */ -#define SE_ENOLINK 67 /* Link has been severed */ -#define SE_EADV 68 /* Advertise error */ -#define SE_ESRMNT 69 /* Srmount error */ -#define SE_ECOMM 70 /* Communication error on send */ -#define SE_EPROTO 71 /* Protocol error */ -#define SE_EMULTIHOP 72 /* Multihop attempted */ -#define SE_EDOTDOT 73 /* RFS specific error */ -#define SE_EBADMSG 74 /* Not a data message */ -#define SE_EOVERFLOW 75 /* Value too large for defined data type */ -#define SE_ENOTUNIQ 76 /* Name not unique on network */ -#define SE_EBADFD 77 /* File descriptor in bad state */ -#define SE_EREMCHG 78 /* Remote address changed */ -#define SE_ELIBACC 79 /* Can not access a needed shared library */ -#define SE_ELIBBAD 80 /* Accessing a corrupted shared library */ -#define SE_ELIBSCN 81 /* .lib section in a.out corrupted */ -#define SE_ELIBMAX 82 /* Attempting to link in too many shared libraries */ -#define SE_ELIBEXEC 83 /* Cannot exec a shared library directly */ -#define SE_EILSEQ 84 /* Illegal byte sequence */ -#define SE_ERESTART 85 /* Interrupted system call should be restarted */ -#define SE_ESTRPIPE 86 /* Streams pipe error */ -#define SE_EUSERS 87 /* Too many users */ -#define SE_ENOTSOCK 88 /* Socket operation on non-socket */ -#define SE_EDESTADDRREQ 89 /* Destination address required */ -#define SE_EMSGSIZE 90 /* Message too long */ -#define SE_EPROTOTYPE 91 /* Protocol wrong type for socket */ -#define SE_ENOPROTOOPT 92 /* Protocol not available */ -#define SE_EPROTONOSUPPORT 93 /* Protocol not supported */ -#define SE_ESOCKTNOSUPPORT 94 /* Socket type not supported */ -#define SE_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define SE_EPFNOSUPPORT 96 /* Protocol family not supported */ -#define SE_EAFNOSUPPORT 97 /* Address family not supported by protocol */ -#define SE_EADDRINUSE 98 /* Address already in use */ -#define SE_EADDRNOTAVAIL 99 /* Cannot assign requested address */ -#define SE_ENETDOWN 100 /* Network is down */ -#define SE_ENETUNREACH 101 /* Network is unreachable */ -#define SE_ENETRESET 102 /* Network dropped connection because of reset */ -#define SE_ECONNABORTED 103 /* Software caused connection abort */ -#define SE_ECONNRESET 104 /* Connection reset by peer */ -#define SE_ENOBUFS 105 /* No buffer space available */ -#define SE_EISCONN 106 /* Transport endpoint is already connected */ -#define SE_ENOTCONN 107 /* Transport endpoint is not connected */ -#define SE_ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ -#define SE_ETOOMANYREFS 109 /* Too many references: cannot splice */ -#define SE_ETIMEDOUT 110 /* Connection timed out */ -#define SE_ECONNREFUSED 111 /* Connection refused */ -#define SE_EHOSTDOWN 112 /* Host is down */ -#define SE_EHOSTUNREACH 113 /* No route to host */ -#define SE_EALREADY 114 /* Operation already in progress */ -#define SE_EINPROGRESS 115 /* Operation now in progress */ -#define SE_ESTALE 116 /* Stale NFS file handle */ -#define SE_EUCLEAN 117 /* Structure needs cleaning */ -#define SE_ENOTNAM 118 /* Not a XENIX named type file */ -#define SE_ENAVAIL 119 /* No XENIX semaphores available */ -#define SE_EISNAM 120 /* Is a named type file */ -#define SE_EREMOTEIO 121 /* Remote I/O error */ -#define SE_EDQUOT 122 /* Quota exceeded */ -#define SE_ENOMEDIUM 123 /* No medium found */ -#define SE_EMEDIUMTYPE 124 /* Wrong medium type */ -#define SE_ECANCELED 125 -#define SE_ERESTARTSYS 512 /* Interrupted system call */ -#define SE_ERESTARTNOINTR 513 -#define SE_ERESTARTNOHAND 514 /* restart if no handler.. */ -#define SE_ENOIOCTLCMD 515 /* No ioctl command */ -#define SE_ERESTART_RESTARTBLOCK 516 /* restart by calling sys_restart_syscall */ +#define SE_EPERM 1 /* Operation not permitted */ +#define SE_ENOENT 2 /* No such file or directory */ +#define SE_ESRCH 3 /* No such process */ +#define SE_EINTR 4 /* Interrupted system call */ +#define SE_EIO 5 /* I/O error */ +#define SE_ENXIO 6 /* No such device or address */ +#define SE_E2BIG 7 /* Arg list too long */ +#define SE_ENOEXEC 8 /* Exec format error */ +#define SE_EBADF 9 /* Bad file number */ +#define SE_ECHILD 10 /* No child processes */ +#define SE_EAGAIN 11 /* Try again */ +#define SE_ENOMEM 12 /* Out of memory */ +#define SE_EACCES 13 /* Permission denied */ +#define SE_EFAULT 14 /* Bad address */ +#define SE_ENOTBLK 15 /* Block device required */ +#define SE_EBUSY 16 /* Device or resource busy */ +#define SE_EEXIST 17 /* File exists */ +#define SE_EXDEV 18 /* Cross-device link */ +#define SE_ENODEV 19 /* No such device */ +#define SE_ENOTDIR 20 /* Not a directory */ +#define SE_EISDIR 21 /* Is a directory */ +#define SE_EINVAL 22 /* Invalid argument */ +#define SE_ENFILE 23 /* File table overflow */ +#define SE_EMFILE 24 /* Too many open files */ +#define SE_ENOTTY 25 /* Not a typewriter */ +#define SE_ETXTBSY 26 /* Text file busy */ +#define SE_EFBIG 27 /* File too large */ +#define SE_ENOSPC 28 /* No space left on device */ +#define SE_ESPIPE 29 /* Illegal seek */ +#define SE_EROFS 30 /* Read-only file system */ +#define SE_EMLINK 31 /* Too many links */ +#define SE_EPIPE 32 /* Broken pipe */ +#define SE_EDOM 33 /* Math argument out of domain of func */ +#define SE_ERANGE 34 /* Math result not representable */ +#define SE_EDEADLK 35 /* Resource deadlock would occur */ +#define SE_ENAMETOOLONG 36 /* File name too long */ +#define SE_ENOLCK 37 /* No record locks available */ +#define SE_ENOSYS 38 /* Function not implemented */ +#define SE_ENOTEMPTY 39 /* Directory not empty */ +#define SE_ELOOP 40 /* Too many symbolic links encountered */ +#define SE_EWOULDBLOCK EAGAIN /* Operation would block */ +#define SE_ENOMSG 42 /* No message of desired type */ +#define SE_EIDRM 43 /* Identifier removed */ +#define SE_ECHRNG 44 /* Channel number out of range */ +#define SE_EL2NSYNC 45 /* Level 2 not synchronized */ +#define SE_EL3HLT 46 /* Level 3 halted */ +#define SE_EL3RST 47 /* Level 3 reset */ +#define SE_ELNRNG 48 /* Link number out of range */ +#define SE_EUNATCH 49 /* Protocol driver not attached */ +#define SE_ENOCSI 50 /* No CSI structure available */ +#define SE_EL2HLT 51 /* Level 2 halted */ +#define SE_EBADE 52 /* Invalid exchange */ +#define SE_EBADR 53 /* Invalid request descriptor */ +#define SE_EXFULL 54 /* Exchange full */ +#define SE_ENOANO 55 /* No anode */ +#define SE_EBADRQC 56 /* Invalid request code */ +#define SE_EBADSLT 57 /* Invalid slot */ +#define SE_EDEADLOCK EDEADLK +#define SE_EBFONT 59 /* Bad font file format */ +#define SE_ENOSTR 60 /* Device not a stream */ +#define SE_ENODATA 61 /* No data available */ +#define SE_ETIME 62 /* Timer expired */ +#define SE_ENOSR 63 /* Out of streams resources */ +#define SE_ENONET 64 /* Machine is not on the network */ +#define SE_ENOPKG 65 /* Package not installed */ +#define SE_EREMOTE 66 /* Object is remote */ +#define SE_ENOLINK 67 /* Link has been severed */ +#define SE_EADV 68 /* Advertise error */ +#define SE_ESRMNT 69 /* Srmount error */ +#define SE_ECOMM 70 /* Communication error on send */ +#define SE_EPROTO 71 /* Protocol error */ +#define SE_EMULTIHOP 72 /* Multihop attempted */ +#define SE_EDOTDOT 73 /* RFS specific error */ +#define SE_EBADMSG 74 /* Not a data message */ +#define SE_EOVERFLOW 75 /* Value too large for defined data type */ +#define SE_ENOTUNIQ 76 /* Name not unique on network */ +#define SE_EBADFD 77 /* File descriptor in bad state */ +#define SE_EREMCHG 78 /* Remote address changed */ +#define SE_ELIBACC 79 /* Can not access a needed shared library */ +#define SE_ELIBBAD 80 /* Accessing a corrupted shared library */ +#define SE_ELIBSCN 81 /* .lib section in a.out corrupted */ +#define SE_ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define SE_ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define SE_EILSEQ 84 /* Illegal byte sequence */ +#define SE_ERESTART 85 /* Interrupted system call should be restarted */ +#define SE_ESTRPIPE 86 /* Streams pipe error */ +#define SE_EUSERS 87 /* Too many users */ +#define SE_ENOTSOCK 88 /* Socket operation on non-socket */ +#define SE_EDESTADDRREQ 89 /* Destination address required */ +#define SE_EMSGSIZE 90 /* Message too long */ +#define SE_EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define SE_ENOPROTOOPT 92 /* Protocol not available */ +#define SE_EPROTONOSUPPORT 93 /* Protocol not supported */ +#define SE_ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define SE_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define SE_EPFNOSUPPORT 96 /* Protocol family not supported */ +#define SE_EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define SE_EADDRINUSE 98 /* Address already in use */ +#define SE_EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define SE_ENETDOWN 100 /* Network is down */ +#define SE_ENETUNREACH 101 /* Network is unreachable */ +#define SE_ENETRESET 102 /* Network dropped connection because of reset */ +#define SE_ECONNABORTED 103 /* Software caused connection abort */ +#define SE_ECONNRESET 104 /* Connection reset by peer */ +#define SE_ENOBUFS 105 /* No buffer space available */ +#define SE_EISCONN 106 /* Transport endpoint is already connected */ +#define SE_ENOTCONN 107 /* Transport endpoint is not connected */ +#define SE_ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define SE_ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define SE_ETIMEDOUT 110 /* Connection timed out */ +#define SE_ECONNREFUSED 111 /* Connection refused */ +#define SE_EHOSTDOWN 112 /* Host is down */ +#define SE_EHOSTUNREACH 113 /* No route to host */ +#define SE_EALREADY 114 /* Operation already in progress */ +#define SE_EINPROGRESS 115 /* Operation now in progress */ +#define SE_ESTALE 116 /* Stale NFS file handle */ +#define SE_EUCLEAN 117 /* Structure needs cleaning */ +#define SE_ENOTNAM 118 /* Not a XENIX named type file */ +#define SE_ENAVAIL 119 /* No XENIX semaphores available */ +#define SE_EISNAM 120 /* Is a named type file */ +#define SE_EREMOTEIO 121 /* Remote I/O error */ +#define SE_EDQUOT 122 /* Quota exceeded */ +#define SE_ENOMEDIUM 123 /* No medium found */ +#define SE_EMEDIUMTYPE 124 /* Wrong medium type */ +#define SE_ECANCELED 125 +#define SE_ERESTARTSYS 512 /* Interrupted system call */ +#define SE_ERESTARTNOINTR 513 +#define SE_ERESTARTNOHAND 514 /* restart if no handler.. */ +#define SE_ENOIOCTLCMD 515 /* No ioctl command */ +#define SE_ERESTART_RESTARTBLOCK 516 /* restart by calling sys_restart_syscall */ /* Defined for the NFSv3 protocol */ -#define SE_EBADHANDLE 521 /* Illegal NFS file handle */ -#define SE_ENOTSYNC 522 /* Update synchronization mismatch */ -#define SE_EBADCOOKIE 523 /* Cookie is stale */ -#define SE_ENOTSUPP 524 /* Operation is not supported */ -#define SE_ETOOSMALL 525 /* Buffer or request is too small */ -#define SE_ESERVERFAULT 526 /* An untranslatable error occurred */ -#define SE_EBADTYPE 527 /* Type not supported by server */ -#define SE_EJUKEBOX 528 /* Request initiated, but will not complete before timeout */ -#define SE_EIOCBQUEUED 529 /* iocb queued, will get completion event */ -#define SE_EIOCBRETRY 530 /* iocb queued, will trigger a retry */ +#define SE_EBADHANDLE 521 /* Illegal NFS file handle */ +#define SE_ENOTSYNC 522 /* Update synchronization mismatch */ +#define SE_EBADCOOKIE 523 /* Cookie is stale */ +#define SE_ENOTSUPP 524 /* Operation is not supported */ +#define SE_ETOOSMALL 525 /* Buffer or request is too small */ +#define SE_ESERVERFAULT 526 /* An untranslatable error occurred */ +#define SE_EBADTYPE 527 /* Type not supported by server */ +#define SE_EJUKEBOX 528 /* Request initiated, but will not complete before timeout */ +#define SE_EIOCBQUEUED 529 /* iocb queued, will get completion event */ +#define SE_EIOCBRETRY 530 /* iocb queued, will trigger a retry */ // note: any new error here will need to have a mapping // in utils.cpp under sinsp_utils::errno_to_str diff --git a/userspace/libsinsp/sinsp_exception.h b/userspace/libsinsp/sinsp_exception.h index 432990d7b7..e96e1b5a7d 100644 --- a/userspace/libsinsp/sinsp_exception.h +++ b/userspace/libsinsp/sinsp_exception.h @@ -23,14 +23,9 @@ limitations under the License. /*! \brief sinsp library exception. */ -class sinsp_exception : public std::runtime_error -{ +class sinsp_exception : public std::runtime_error { public: - sinsp_exception(const std::string& error_str): - std::runtime_error(error_str) - { } + sinsp_exception(const std::string& error_str): std::runtime_error(error_str) {} - sinsp_exception(const char* const error_str): - std::runtime_error(error_str) - { } + sinsp_exception(const char* const error_str): std::runtime_error(error_str) {} }; diff --git a/userspace/libsinsp/sinsp_external_processor.h b/userspace/libsinsp/sinsp_external_processor.h index f854e734d6..5251015d01 100644 --- a/userspace/libsinsp/sinsp_external_processor.h +++ b/userspace/libsinsp/sinsp_external_processor.h @@ -11,18 +11,15 @@ class sinsp; class threadinfo; -namespace libsinsp -{ -enum event_return -{ +namespace libsinsp { +enum event_return { EVENT_RETURN_TIMEOUT, EVENT_RETURN_EOF, EVENT_RETURN_NONE, EVENT_RETURN_FILTERED }; -class event_processor -{ +class event_processor { public: virtual ~event_processor() = default; diff --git a/userspace/libsinsp/sinsp_filter_transformer.cpp b/userspace/libsinsp/sinsp_filter_transformer.cpp index 9febfd6bd8..4b32596b82 100644 --- a/userspace/libsinsp/sinsp_filter_transformer.cpp +++ b/userspace/libsinsp/sinsp_filter_transformer.cpp @@ -16,199 +16,172 @@ limitations under the License. #include #include -static void throw_unsupported_err(filter_transformer_type t) -{ - throw sinsp_exception("transformer '" + std::to_string(t) + "' is not supported"); +static void throw_unsupported_err(filter_transformer_type t) { + throw sinsp_exception("transformer '" + std::to_string(t) + "' is not supported"); } -static void throw_type_incompatibility_err(ppm_param_type t, const std::string& trname) -{ - throw sinsp_exception("field type '" + std::to_string(t) + "' is not supported by '" + trname + "' transformer"); +static void throw_type_incompatibility_err(ppm_param_type t, const std::string& trname) { + throw sinsp_exception("field type '" + std::to_string(t) + "' is not supported by '" + trname + + "' transformer"); } -bool sinsp_filter_transformer::string_transformer(std::vector& vec, ppm_param_type t, str_transformer_func_t f) -{ - m_storage_values.resize(vec.size()); - for(std::size_t i = 0; i < vec.size(); i++) - { - storage_t& buf = m_storage_values[i]; - - buf.clear(); - if(vec[i].ptr == nullptr) - { - continue; - } - - // we don't know whether this will come as a string or a byte buf, - // so we sanitize by skipping all terminator characters - size_t in_len = vec[i].len; - while (in_len > 0 && vec[i].ptr[in_len - 1] == '\0') - { - in_len--; - } - - // each function can assume that the input size does NOT include - // the terminator character, and should not assume that the string - // is null-terminated - std::string_view in{(const char*) vec[i].ptr, in_len}; - if (!f(in, buf)) - { - return false; - } - - // we insert a null terminator in case we miss one, just to stay safe - if (buf.size() == 0 || buf[buf.size() - 1] != '\0') - { - buf.push_back('\0'); - } - - vec[i].ptr = (uint8_t*) &buf[0]; - vec[i].len = buf.size(); - } - return true; +bool sinsp_filter_transformer::string_transformer(std::vector& vec, + ppm_param_type t, + str_transformer_func_t f) { + m_storage_values.resize(vec.size()); + for(std::size_t i = 0; i < vec.size(); i++) { + storage_t& buf = m_storage_values[i]; + + buf.clear(); + if(vec[i].ptr == nullptr) { + continue; + } + + // we don't know whether this will come as a string or a byte buf, + // so we sanitize by skipping all terminator characters + size_t in_len = vec[i].len; + while(in_len > 0 && vec[i].ptr[in_len - 1] == '\0') { + in_len--; + } + + // each function can assume that the input size does NOT include + // the terminator character, and should not assume that the string + // is null-terminated + std::string_view in{(const char*)vec[i].ptr, in_len}; + if(!f(in, buf)) { + return false; + } + + // we insert a null terminator in case we miss one, just to stay safe + if(buf.size() == 0 || buf[buf.size() - 1] != '\0') { + buf.push_back('\0'); + } + + vec[i].ptr = (uint8_t*)&buf[0]; + vec[i].len = buf.size(); + } + return true; } -bool sinsp_filter_transformer::transform_type(ppm_param_type& t) const -{ - switch(m_type) - { - case FTR_TOUPPER: - { - switch(t) - { - case PT_CHARBUF: - case PT_FSPATH: - case PT_FSRELPATH: - // for TOUPPER, the transformed type is the same as the input type - return true; - default: - return false; - } - } - case FTR_TOLOWER: - { - switch(t) - { - case PT_CHARBUF: - case PT_FSPATH: - case PT_FSRELPATH: - // for TOLOWER, the transformed type is the same as the input type - return true; - default: - return false; - } - } - case FTR_BASE64: - { - switch(t) - { - case PT_CHARBUF: - case PT_BYTEBUF: - // for BASE64, the transformed type is the same as the input type - return true; - default: - return false; - } - } - case FTR_STORAGE: - { - // for STORAGE, the transformed type is the same as the input type - return true; - } - case FTR_BASENAME: - { - switch(t) - { - case PT_CHARBUF: - case PT_FSPATH: - case PT_FSRELPATH: - // for BASENAME, the transformed type is the same as the input type - return true; - default: - return false; - } - } - default: - throw_unsupported_err(m_type); - return false; - } +bool sinsp_filter_transformer::transform_type(ppm_param_type& t) const { + switch(m_type) { + case FTR_TOUPPER: { + switch(t) { + case PT_CHARBUF: + case PT_FSPATH: + case PT_FSRELPATH: + // for TOUPPER, the transformed type is the same as the input type + return true; + default: + return false; + } + } + case FTR_TOLOWER: { + switch(t) { + case PT_CHARBUF: + case PT_FSPATH: + case PT_FSRELPATH: + // for TOLOWER, the transformed type is the same as the input type + return true; + default: + return false; + } + } + case FTR_BASE64: { + switch(t) { + case PT_CHARBUF: + case PT_BYTEBUF: + // for BASE64, the transformed type is the same as the input type + return true; + default: + return false; + } + } + case FTR_STORAGE: { + // for STORAGE, the transformed type is the same as the input type + return true; + } + case FTR_BASENAME: { + switch(t) { + case PT_CHARBUF: + case PT_FSPATH: + case PT_FSRELPATH: + // for BASENAME, the transformed type is the same as the input type + return true; + default: + return false; + } + } + default: + throw_unsupported_err(m_type); + return false; + } } -bool sinsp_filter_transformer::transform_values(std::vector& vec, ppm_param_type& t) -{ - if (!transform_type(t)) - { - throw_type_incompatibility_err(t, filter_transformer_type_str(m_type)); - } - - switch(m_type) - { - case FTR_TOUPPER: - { - return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { - for (auto c : in) - { - out.push_back(toupper(c)); - } - return true; - }); - } - case FTR_TOLOWER: - { - return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { - for (auto c : in) - { - out.push_back(tolower(c)); - } - return true; - }); - } - case FTR_BASE64: - { - return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { - return Base64::decodeWithoutPadding(in, out); - }); - } - case FTR_STORAGE: - { - // note: for STORAGE, the transformed type is the same as the input type - m_storage_values.resize(vec.size()); - for (std::size_t i = 0; i < vec.size(); i++) - { - storage_t& buf = m_storage_values[i]; - - buf.clear(); - if(vec[i].ptr == nullptr) - { - continue; - } - - // We reserve one extra chat for the null terminator - buf.resize(vec[i].len+1); - memcpy(&(buf[0]), vec[i].ptr, vec[i].len); - // We put the string terminator in any case - buf[vec[i].len] = '\0'; - vec[i].ptr = &(buf[0]); - // `vec[i].len` is the same as before - } - return true; - } - case FTR_BASENAME: - { - return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { - auto last_slash_pos = in.find_last_of("/"); - std::string_view::size_type start_idx = last_slash_pos == std::string_view::npos ? 0 : last_slash_pos + 1; - - for (std::string_view::size_type i = start_idx; i < in.length(); i++) - { - out.push_back(in[i]); - } - - return true; - }); - } - default: - throw_unsupported_err(m_type); - return false; - } +bool sinsp_filter_transformer::transform_values(std::vector& vec, + ppm_param_type& t) { + if(!transform_type(t)) { + throw_type_incompatibility_err(t, filter_transformer_type_str(m_type)); + } + + switch(m_type) { + case FTR_TOUPPER: { + return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { + for(auto c : in) { + out.push_back(toupper(c)); + } + return true; + }); + } + case FTR_TOLOWER: { + return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { + for(auto c : in) { + out.push_back(tolower(c)); + } + return true; + }); + } + case FTR_BASE64: { + return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { + return Base64::decodeWithoutPadding(in, out); + }); + } + case FTR_STORAGE: { + // note: for STORAGE, the transformed type is the same as the input type + m_storage_values.resize(vec.size()); + for(std::size_t i = 0; i < vec.size(); i++) { + storage_t& buf = m_storage_values[i]; + + buf.clear(); + if(vec[i].ptr == nullptr) { + continue; + } + + // We reserve one extra chat for the null terminator + buf.resize(vec[i].len + 1); + memcpy(&(buf[0]), vec[i].ptr, vec[i].len); + // We put the string terminator in any case + buf[vec[i].len] = '\0'; + vec[i].ptr = &(buf[0]); + // `vec[i].len` is the same as before + } + return true; + } + case FTR_BASENAME: { + return string_transformer(vec, t, [](std::string_view in, storage_t& out) -> bool { + auto last_slash_pos = in.find_last_of("/"); + std::string_view::size_type start_idx = + last_slash_pos == std::string_view::npos ? 0 : last_slash_pos + 1; + + for(std::string_view::size_type i = start_idx; i < in.length(); i++) { + out.push_back(in[i]); + } + + return true; + }); + } + default: + throw_unsupported_err(m_type); + return false; + } } diff --git a/userspace/libsinsp/sinsp_filter_transformer.h b/userspace/libsinsp/sinsp_filter_transformer.h index f01ca41bb7..0b9a379501 100644 --- a/userspace/libsinsp/sinsp_filter_transformer.h +++ b/userspace/libsinsp/sinsp_filter_transformer.h @@ -22,19 +22,16 @@ limitations under the License. #include #include -enum filter_transformer_type: uint8_t -{ +enum filter_transformer_type : uint8_t { FTR_TOUPPER = 0, FTR_TOLOWER = 1, FTR_BASE64 = 2, - FTR_STORAGE = 3, // This transformer is only used internally + FTR_STORAGE = 3, // This transformer is only used internally FTR_BASENAME = 4, }; -static inline std::string filter_transformer_type_str(filter_transformer_type m) -{ - switch(m) - { +static inline std::string filter_transformer_type_str(filter_transformer_type m) { + switch(m) { case FTR_TOUPPER: return "toupper"; case FTR_TOLOWER: @@ -50,37 +47,30 @@ static inline std::string filter_transformer_type_str(filter_transformer_type m) } } -static inline filter_transformer_type filter_transformer_from_str(const std::string& str) -{ - if (str == "tolower") - { +static inline filter_transformer_type filter_transformer_from_str(const std::string& str) { + if(str == "tolower") { return filter_transformer_type::FTR_TOLOWER; } - if (str == "toupper") - { + if(str == "toupper") { return filter_transformer_type::FTR_TOUPPER; } - if (str == "b64") - { + if(str == "b64") { return filter_transformer_type::FTR_BASE64; } - if (str == "storage") - { + if(str == "storage") { return filter_transformer_type::FTR_STORAGE; } - if (str == "basename") - { + if(str == "basename") { return filter_transformer_type::FTR_BASENAME; } throw sinsp_exception("unknown field transfomer '" + str + "'"); } -class sinsp_filter_transformer -{ +class sinsp_filter_transformer { public: using storage_t = std::vector; - sinsp_filter_transformer(filter_transformer_type t): m_type(t) { }; + sinsp_filter_transformer(filter_transformer_type t): m_type(t) {}; bool transform_type(ppm_param_type& t) const; @@ -89,7 +79,9 @@ class sinsp_filter_transformer private: using str_transformer_func_t = std::function; - bool string_transformer(std::vector& vec, ppm_param_type t, str_transformer_func_t mod); + bool string_transformer(std::vector& vec, + ppm_param_type t, + str_transformer_func_t mod); filter_transformer_type m_type; std::vector m_storage_values; diff --git a/userspace/libsinsp/sinsp_filtercheck.cpp b/userspace/libsinsp/sinsp_filtercheck.cpp index f4e92a862d..55f831a4a4 100644 --- a/userspace/libsinsp/sinsp_filtercheck.cpp +++ b/userspace/libsinsp/sinsp_filtercheck.cpp @@ -25,12 +25,10 @@ limitations under the License. #include -#define STRPROPERTY_STORAGE_SIZE 1024 +#define STRPROPERTY_STORAGE_SIZE 1024 -std::string std::to_string(boolop b) -{ - switch (b) - { +std::string std::to_string(boolop b) { + switch(b) { case BO_NONE: return "NONE"; case BO_NOT: @@ -47,25 +45,20 @@ std::string std::to_string(boolop b) return ""; } -void sinsp_filter_check::default_re2_deleter::operator()(re2::RE2* __ptr) const -{ +void sinsp_filter_check::default_re2_deleter::operator()(re2::RE2* __ptr) const { std::default_delete{}(__ptr); } -template -static inline void ensure_unique_ptr_allocated(Ptr& p, Params... args) -{ - if (!p) - { +template +static inline void ensure_unique_ptr_allocated(Ptr& p, Params... args) { + if(!p) { p = std::make_unique(args...); } } -template -static inline void ensure_unique_ptr_allocated_deleter(Ptr& p, Params... args) -{ - if (!p) - { +template +static inline void ensure_unique_ptr_allocated_deleter(Ptr& p, Params... args) { + if(!p) { p.reset(new typename Ptr::element_type(args...)); } } @@ -73,8 +66,7 @@ static inline void ensure_unique_ptr_allocated_deleter(Ptr& p, Params... args) /////////////////////////////////////////////////////////////////////////////// // sinsp_filter_check implementation /////////////////////////////////////////////////////////////////////////////// -sinsp_filter_check::sinsp_filter_check() -{ +sinsp_filter_check::sinsp_filter_check() { m_boolop = BO_NONE; m_cmpop = CO_NONE; m_inspector = NULL; @@ -83,521 +75,383 @@ sinsp_filter_check::sinsp_filter_check() m_val_storages_max_size = (std::numeric_limits::min)(); } -void sinsp_filter_check::set_inspector(sinsp* inspector) -{ +void sinsp_filter_check::set_inspector(sinsp* inspector) { m_inspector = inspector; } -template -static inline T rawval_cast(uint8_t *rawval) -{ +template +static inline T rawval_cast(uint8_t* rawval) { T val; memcpy(&val, rawval, sizeof(T)); return val; } Json::Value sinsp_filter_check::rawval_to_json(uint8_t* rawval, - ppm_param_type ptype, - ppm_print_format print_format, - uint32_t len) -{ + ppm_param_type ptype, + ppm_print_format print_format, + uint32_t len) { ASSERT(rawval != NULL); - switch(ptype) - { - case PT_INT8: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return *(int8_t *)rawval; - } - else if(print_format == PF_OCT || - print_format == PF_HEX) - { - return rawval_to_string(rawval, ptype, print_format, len); - } - else - { - ASSERT(false); - return Json::nullValue; - } - - case PT_INT16: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return rawval_cast(rawval); - } - else if(print_format == PF_OCT || - print_format == PF_HEX) - { - return rawval_to_string(rawval, ptype, print_format, len); - } - else - { - ASSERT(false); - return Json::nullValue; - } - - case PT_INT32: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return rawval_cast(rawval); - } - else if(print_format == PF_OCT || - print_format == PF_HEX) - { - return rawval_to_string(rawval, ptype, print_format, len); - } - else - { - ASSERT(false); - return Json::nullValue; - } - case PT_DOUBLE: - if(print_format == PF_DEC) - { - return (Json::Value::Int64)(int64_t)rawval_cast(rawval); - } - else - { - return (Json::Value)rawval_cast(rawval); - } - case PT_INT64: - case PT_PID: - case PT_FD: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return (Json::Value::Int64)rawval_cast(rawval); - } - else - { - return rawval_to_string(rawval, ptype, print_format, len); - } - - case PT_L4PROTO: // This can be resolved in the future - case PT_UINT8: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return *(uint8_t *)rawval; - } - else if(print_format == PF_OCT || - print_format == PF_HEX) - { - return rawval_to_string(rawval, ptype, print_format, len); - } - else - { - ASSERT(false); - return Json::nullValue; - } + switch(ptype) { + case PT_INT8: + if(print_format == PF_DEC || print_format == PF_ID) { + return *(int8_t*)rawval; + } else if(print_format == PF_OCT || print_format == PF_HEX) { + return rawval_to_string(rawval, ptype, print_format, len); + } else { + ASSERT(false); + return Json::nullValue; + } - case PT_PORT: // This can be resolved in the future - case PT_UINT16: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return *(uint16_t *)rawval; - } - else if(print_format == PF_OCT || - print_format == PF_HEX) - { - return rawval_to_string(rawval, ptype, print_format, len); - } - else - { - ASSERT(false); - return Json::nullValue; - } + case PT_INT16: + if(print_format == PF_DEC || print_format == PF_ID) { + return rawval_cast(rawval); + } else if(print_format == PF_OCT || print_format == PF_HEX) { + return rawval_to_string(rawval, ptype, print_format, len); + } else { + ASSERT(false); + return Json::nullValue; + } - case PT_UINT32: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return *(uint32_t *)rawval; - } - else if(print_format == PF_OCT || - print_format == PF_HEX) - { - return rawval_to_string(rawval, ptype, print_format, len); - } - else - { - ASSERT(false); - return Json::nullValue; - } + case PT_INT32: + if(print_format == PF_DEC || print_format == PF_ID) { + return rawval_cast(rawval); + } else if(print_format == PF_OCT || print_format == PF_HEX) { + return rawval_to_string(rawval, ptype, print_format, len); + } else { + ASSERT(false); + return Json::nullValue; + } + case PT_DOUBLE: + if(print_format == PF_DEC) { + return (Json::Value::Int64)(int64_t)rawval_cast(rawval); + } else { + return (Json::Value)rawval_cast(rawval); + } + case PT_INT64: + case PT_PID: + case PT_FD: + if(print_format == PF_DEC || print_format == PF_ID) { + return (Json::Value::Int64)rawval_cast(rawval); + } else { + return rawval_to_string(rawval, ptype, print_format, len); + } - case PT_UINT64: - case PT_RELTIME: - case PT_ABSTIME: - if(print_format == PF_DEC || - print_format == PF_ID) - { - return (Json::Value::UInt64)rawval_cast(rawval); - } - else if( - print_format == PF_10_PADDED_DEC || - print_format == PF_OCT || - print_format == PF_HEX) - { - return rawval_to_string(rawval, ptype, print_format, len); - } - else - { - ASSERT(false); - return Json::nullValue; - } + case PT_L4PROTO: // This can be resolved in the future + case PT_UINT8: + if(print_format == PF_DEC || print_format == PF_ID) { + return *(uint8_t*)rawval; + } else if(print_format == PF_OCT || print_format == PF_HEX) { + return rawval_to_string(rawval, ptype, print_format, len); + } else { + ASSERT(false); + return Json::nullValue; + } - case PT_SOCKADDR: - case PT_SOCKFAMILY: + case PT_PORT: // This can be resolved in the future + case PT_UINT16: + if(print_format == PF_DEC || print_format == PF_ID) { + return *(uint16_t*)rawval; + } else if(print_format == PF_OCT || print_format == PF_HEX) { + return rawval_to_string(rawval, ptype, print_format, len); + } else { ASSERT(false); return Json::nullValue; + } - case PT_BOOL: - return Json::Value((bool)(rawval_cast(rawval) != 0)); + case PT_UINT32: + if(print_format == PF_DEC || print_format == PF_ID) { + return *(uint32_t*)rawval; + } else if(print_format == PF_OCT || print_format == PF_HEX) { + return rawval_to_string(rawval, ptype, print_format, len); + } else { + ASSERT(false); + return Json::nullValue; + } - case PT_CHARBUF: - case PT_FSPATH: - case PT_BYTEBUF: - case PT_IPV4ADDR: - case PT_IPV6ADDR: - case PT_IPADDR: - case PT_IPNET: - case PT_FSRELPATH: + case PT_UINT64: + case PT_RELTIME: + case PT_ABSTIME: + if(print_format == PF_DEC || print_format == PF_ID) { + return (Json::Value::UInt64)rawval_cast(rawval); + } else if(print_format == PF_10_PADDED_DEC || print_format == PF_OCT || + print_format == PF_HEX) { return rawval_to_string(rawval, ptype, print_format, len); - default: + } else { ASSERT(false); - throw sinsp_exception("wrong param type " + std::to_string((long long) ptype)); + return Json::nullValue; + } + + case PT_SOCKADDR: + case PT_SOCKFAMILY: + ASSERT(false); + return Json::nullValue; + + case PT_BOOL: + return Json::Value((bool)(rawval_cast(rawval) != 0)); + + case PT_CHARBUF: + case PT_FSPATH: + case PT_BYTEBUF: + case PT_IPV4ADDR: + case PT_IPV6ADDR: + case PT_IPADDR: + case PT_IPNET: + case PT_FSRELPATH: + return rawval_to_string(rawval, ptype, print_format, len); + default: + ASSERT(false); + throw sinsp_exception("wrong param type " + std::to_string((long long)ptype)); } } char* sinsp_filter_check::rawval_to_string(uint8_t* rawval, - ppm_param_type ptype, - ppm_print_format print_format, - uint32_t len) -{ + ppm_param_type ptype, + ppm_print_format print_format, + uint32_t len) { char* prfmt; ASSERT(rawval != NULL); - switch(ptype) - { - case PT_INT8: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo8; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRId8; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIX8; - } - else - { - ASSERT(false); - return NULL; - } - - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, *(int8_t *)rawval); - return m_getpropertystr_storage.data(); - case PT_INT16: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo16; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRId16; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIX16; - } - else - { - ASSERT(false); - return NULL; - } - - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, rawval_cast(rawval)); - return m_getpropertystr_storage.data(); - case PT_INT32: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo32; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRId32; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIX32; - } - else - { - ASSERT(false); - return NULL; - } + switch(ptype) { + case PT_INT8: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo8; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRId8; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIX8; + } else { + ASSERT(false); + return NULL; + } - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, rawval_cast(rawval)); - return m_getpropertystr_storage.data(); - case PT_INT64: - case PT_PID: - case PT_ERRNO: - case PT_FD: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo64; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRId64; - } - else if(print_format == PF_10_PADDED_DEC) - { - prfmt = (char*)"%09" PRId64; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIX64; - } - else - { - prfmt = (char*)"%" PRId64; - } + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + *(int8_t*)rawval); + return m_getpropertystr_storage.data(); + case PT_INT16: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo16; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRId16; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIX16; + } else { + ASSERT(false); + return NULL; + } - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, rawval_cast(rawval)); - return m_getpropertystr_storage.data(); - case PT_L4PROTO: // This can be resolved in the future - case PT_UINT8: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo8; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRIu8; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIu8; - } - else - { - ASSERT(false); - return NULL; - } + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + rawval_cast(rawval)); + return m_getpropertystr_storage.data(); + case PT_INT32: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo32; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRId32; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIX32; + } else { + ASSERT(false); + return NULL; + } - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, *(uint8_t *)rawval); - return m_getpropertystr_storage.data(); - case PT_PORT: // This can be resolved in the future - case PT_UINT16: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo16; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRIu16; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIu16; - } - else - { - ASSERT(false); - return NULL; - } + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + rawval_cast(rawval)); + return m_getpropertystr_storage.data(); + case PT_INT64: + case PT_PID: + case PT_ERRNO: + case PT_FD: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo64; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRId64; + } else if(print_format == PF_10_PADDED_DEC) { + prfmt = (char*)"%09" PRId64; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIX64; + } else { + prfmt = (char*)"%" PRId64; + } - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, rawval_cast(rawval)); - return m_getpropertystr_storage.data(); - case PT_UINT32: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo32; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRIu32; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIu32; - } - else - { - ASSERT(false); - return NULL; - } + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + rawval_cast(rawval)); + return m_getpropertystr_storage.data(); + case PT_L4PROTO: // This can be resolved in the future + case PT_UINT8: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo8; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRIu8; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIu8; + } else { + ASSERT(false); + return NULL; + } - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, rawval_cast(rawval)); - return m_getpropertystr_storage.data(); - case PT_UINT64: - case PT_RELTIME: - case PT_ABSTIME: - if(print_format == PF_OCT) - { - prfmt = (char*)"%" PRIo64; - } - else if(print_format == PF_DEC || - print_format == PF_ID) - { - prfmt = (char*)"%" PRIu64; - } - else if(print_format == PF_10_PADDED_DEC) - { - prfmt = (char*)"%09" PRIu64; - } - else if(print_format == PF_HEX) - { - prfmt = (char*)"%" PRIX64; - } - else - { - ASSERT(false); - return NULL; - } + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + *(uint8_t*)rawval); + return m_getpropertystr_storage.data(); + case PT_PORT: // This can be resolved in the future + case PT_UINT16: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo16; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRIu16; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIu16; + } else { + ASSERT(false); + return NULL; + } - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - prfmt, rawval_cast(rawval)); - return m_getpropertystr_storage.data(); - case PT_CHARBUF: - case PT_FSPATH: - case PT_FSRELPATH: - return (char*)rawval; - case PT_BYTEBUF: - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - binary_buffer_to_string(m_getpropertystr_storage.data(), - (const char*)rawval, - (uint32_t) STRPROPERTY_STORAGE_SIZE - 1, - len, - m_inspector->get_buffer_format()); - return m_getpropertystr_storage.data(); - case PT_SOCKADDR: + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + rawval_cast(rawval)); + return m_getpropertystr_storage.data(); + case PT_UINT32: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo32; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRIu32; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIu32; + } else { ASSERT(false); return NULL; - case PT_SOCKFAMILY: + } + + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + rawval_cast(rawval)); + return m_getpropertystr_storage.data(); + case PT_UINT64: + case PT_RELTIME: + case PT_ABSTIME: + if(print_format == PF_OCT) { + prfmt = (char*)"%" PRIo64; + } else if(print_format == PF_DEC || print_format == PF_ID) { + prfmt = (char*)"%" PRIu64; + } else if(print_format == PF_10_PADDED_DEC) { + prfmt = (char*)"%09" PRIu64; + } else if(print_format == PF_HEX) { + prfmt = (char*)"%" PRIX64; + } else { ASSERT(false); return NULL; - case PT_BOOL: - if(rawval_cast(rawval) != 0) - { - return (char*)"true"; - } - else - { - return (char*)"false"; - } - case PT_IPV4ADDR: - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8, - rawval[0], - rawval[1], - rawval[2], - rawval[3]); - return m_getpropertystr_storage.data(); - case PT_IPV6ADDR: - { - char address[INET6_ADDRSTRLEN]; - - if(NULL == inet_ntop(AF_INET6, rawval, address, INET6_ADDRSTRLEN)) - { - strlcpy(address, "", INET6_ADDRSTRLEN); - } + } - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - strlcpy(m_getpropertystr_storage.data(), address, STRPROPERTY_STORAGE_SIZE); + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + prfmt, + rawval_cast(rawval)); + return m_getpropertystr_storage.data(); + case PT_CHARBUF: + case PT_FSPATH: + case PT_FSRELPATH: + return (char*)rawval; + case PT_BYTEBUF: + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + binary_buffer_to_string(m_getpropertystr_storage.data(), + (const char*)rawval, + (uint32_t)STRPROPERTY_STORAGE_SIZE - 1, + len, + m_inspector->get_buffer_format()); + return m_getpropertystr_storage.data(); + case PT_SOCKADDR: + ASSERT(false); + return NULL; + case PT_SOCKFAMILY: + ASSERT(false); + return NULL; + case PT_BOOL: + if(rawval_cast(rawval) != 0) { + return (char*)"true"; + } else { + return (char*)"false"; + } + case PT_IPV4ADDR: + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8, + rawval[0], + rawval[1], + rawval[2], + rawval[3]); + return m_getpropertystr_storage.data(); + case PT_IPV6ADDR: { + char address[INET6_ADDRSTRLEN]; - return m_getpropertystr_storage.data(); + if(NULL == inet_ntop(AF_INET6, rawval, address, INET6_ADDRSTRLEN)) { + strlcpy(address, "", INET6_ADDRSTRLEN); } - case PT_IPADDR: - if(len == sizeof(struct in_addr)) - { - return rawval_to_string(rawval, PT_IPV4ADDR, print_format, len); - } - else if(len == sizeof(struct in6_addr)) - { - return rawval_to_string(rawval, PT_IPV6ADDR, print_format, len); - } - else - { - throw sinsp_exception("rawval_to_string called with IP address of incorrect size " + std::to_string(len)); - } - case PT_DOUBLE: - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%.1lf", rawval_cast(rawval)); - return m_getpropertystr_storage.data(); - case PT_IPNET: - m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - ""); - return m_getpropertystr_storage.data(); - default: - ASSERT(false); - throw sinsp_exception("wrong param type " + std::to_string((long long) ptype)); + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + strlcpy(m_getpropertystr_storage.data(), address, STRPROPERTY_STORAGE_SIZE); + + return m_getpropertystr_storage.data(); + } + case PT_IPADDR: + if(len == sizeof(struct in_addr)) { + return rawval_to_string(rawval, PT_IPV4ADDR, print_format, len); + } else if(len == sizeof(struct in6_addr)) { + return rawval_to_string(rawval, PT_IPV6ADDR, print_format, len); + } else { + throw sinsp_exception("rawval_to_string called with IP address of incorrect size " + + std::to_string(len)); + } + + case PT_DOUBLE: + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), + STRPROPERTY_STORAGE_SIZE, + "%.1lf", + rawval_cast(rawval)); + return m_getpropertystr_storage.data(); + case PT_IPNET: + m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); + snprintf(m_getpropertystr_storage.data(), STRPROPERTY_STORAGE_SIZE, ""); + return m_getpropertystr_storage.data(); + default: + ASSERT(false); + throw sinsp_exception("wrong param type " + std::to_string((long long)ptype)); } } -char* sinsp_filter_check::tostring(sinsp_evt* evt) -{ +char* sinsp_filter_check::tostring(sinsp_evt* evt) { m_extracted_values.clear(); - if(!extract(evt, m_extracted_values)) - { + if(!extract(evt, m_extracted_values)) { return NULL; } auto ftype = get_transformed_field_info()->m_type; - if (m_field->m_flags & EPF_IS_LIST) - { + if(m_field->m_flags & EPF_IS_LIST) { std::string res = "("; - for (auto &val : m_extracted_values) - { - if (res.size() > 1) - { + for(auto& val : m_extracted_values) { + if(res.size() > 1) { res += ","; } res += rawval_to_string(val.ptr, ftype, m_field->m_print_format, val.len); @@ -607,39 +461,41 @@ char* sinsp_filter_check::tostring(sinsp_evt* evt) strlcpy(m_getpropertystr_storage.data(), res.c_str(), STRPROPERTY_STORAGE_SIZE); return m_getpropertystr_storage.data(); } - return rawval_to_string(m_extracted_values[0].ptr, ftype, m_field->m_print_format, m_extracted_values[0].len); + return rawval_to_string(m_extracted_values[0].ptr, + ftype, + m_field->m_print_format, + m_extracted_values[0].len); } -Json::Value sinsp_filter_check::tojson(sinsp_evt* evt) -{ +Json::Value sinsp_filter_check::tojson(sinsp_evt* evt) { uint32_t len; Json::Value jsonval = extract_as_js(evt, &len); - if(jsonval == Json::nullValue) - { + if(jsonval == Json::nullValue) { m_extracted_values.clear(); - if(!extract(evt, m_extracted_values)) - { + if(!extract(evt, m_extracted_values)) { return Json::nullValue; } auto ftype = get_transformed_field_info()->m_type; - if (m_field->m_flags & EPF_IS_LIST) - { - for (auto &val : m_extracted_values) - { + if(m_field->m_flags & EPF_IS_LIST) { + for(auto& val : m_extracted_values) { jsonval.append(rawval_to_json(val.ptr, ftype, m_field->m_print_format, val.len)); } return jsonval; } - return rawval_to_json(m_extracted_values[0].ptr, ftype, m_field->m_print_format, m_extracted_values[0].len); + return rawval_to_json(m_extracted_values[0].ptr, + ftype, + m_field->m_print_format, + m_extracted_values[0].len); } return jsonval; } -int32_t sinsp_filter_check::parse_field_name(std::string_view str, bool alloc_state, bool needed_for_filtering) -{ +int32_t sinsp_filter_check::parse_field_name(std::string_view str, + bool alloc_state, + bool needed_for_filtering) { int32_t max_fldlen = -1; uint32_t max_flags = 0; @@ -649,18 +505,15 @@ int32_t sinsp_filter_check::parse_field_name(std::string_view str, bool alloc_st m_field_id = 0xffffffff; - for(int32_t j = 0; j != m_info->m_nfields; ++j) - { + for(int32_t j = 0; j != m_info->m_nfields; ++j) { auto& fld = m_info->m_fields[j]; int32_t fldlen = (int32_t)fld.m_name.size(); - if(fldlen <= max_fldlen) - { + if(fldlen <= max_fldlen) { continue; } /* Here we are searching for the longest match */ - if(str.compare(0, fldlen, fld.m_name) == 0) - { + if(str.compare(0, fldlen, fld.m_name) == 0) { /* we found some info about the required field, we save it in this way * we don't have to loop again through the fields. */ @@ -671,31 +524,27 @@ int32_t sinsp_filter_check::parse_field_name(std::string_view str, bool alloc_st } } - if(!needed_for_filtering) - { - if(max_flags & EPF_FILTER_ONLY) - { - throw sinsp_exception(std::string(str) + " is filter only and cannot be used as a display field"); + if(!needed_for_filtering) { + if(max_flags & EPF_FILTER_ONLY) { + throw sinsp_exception(std::string(str) + + " is filter only and cannot be used as a display field"); } } return max_fldlen; } -void sinsp_filter_check::add_filter_value(const char* str, uint32_t len, uint32_t i) -{ - if(has_filtercheck_value()) - { - throw sinsp_exception("can't add const field value: field '" - + std::string(get_transformed_field_info()->m_name) - + "' already has another field '" - + m_rhs_filter_check->get_transformed_field_info()->m_name - + "' as right-hand side value"); +void sinsp_filter_check::add_filter_value(const char* str, uint32_t len, uint32_t i) { + if(has_filtercheck_value()) { + throw sinsp_exception("can't add const field value: field '" + + std::string(get_transformed_field_info()->m_name) + + "' already has another field '" + + m_rhs_filter_check->get_transformed_field_info()->m_name + + "' as right-hand side value"); } // create storage for the value at the given index, if not present - while (i >= m_val_storages.size()) - { + while(i >= m_val_storages.size()) { m_val_storages.push_back(std::vector(s_min_filter_value_buf_size)); } @@ -704,16 +553,12 @@ void sinsp_filter_check::add_filter_value(const char* str, uint32_t len, uint32_ // too short in size, so we retry by resizing it up until a certain max // size beyond which we just give up and propagate the errors thrown size_t parsed_len = 0; - while (true) - { - try - { - parsed_len = parse_filter_value(str, len, &(m_val_storages[i][0]), m_val_storages[i].size()); - } - catch (sinsp_exception& e) - { - if (m_val_storages[i].size() >= s_max_filter_value_buf_size) - { + while(true) { + try { + parsed_len = + parse_filter_value(str, len, &(m_val_storages[i][0]), m_val_storages[i].size()); + } catch(sinsp_exception& e) { + if(m_val_storages[i].size() >= s_max_filter_value_buf_size) { throw e; } m_val_storages[i].resize(m_val_storages[i].size() * 2); @@ -726,66 +571,55 @@ void sinsp_filter_check::add_filter_value(const char* str, uint32_t len, uint32_ filter_value_t item(&(m_val_storages[i][0]), parsed_len); m_vals.resize(i + 1); m_vals[i] = item; - + // populate operator-specific optimizations - if (m_cmpop == CO_IN || m_cmpop == CO_INTERSECTS) - { + if(m_cmpop == CO_IN || m_cmpop == CO_INTERSECTS) { // If the operator is IN or INTERSECTS, populate the map search ensure_unique_ptr_allocated(m_val_storages_members); m_val_storages_members->insert(item); - if(parsed_len < m_val_storages_min_size) - { + if(parsed_len < m_val_storages_min_size) { m_val_storages_min_size = parsed_len; } - if(parsed_len > m_val_storages_max_size) - { + if(parsed_len > m_val_storages_max_size) { m_val_storages_max_size = parsed_len; } - } - else if (m_cmpop == CO_PMATCH) - { + } else if(m_cmpop == CO_PMATCH) { // If the operator is CO_PMATCH, also add the value to the paths set. ensure_unique_ptr_allocated(m_val_storages_paths); m_val_storages_paths->add_search_path(item); - } - else if (m_cmpop == CO_REGEX) - { - ensure_unique_ptr_allocated_deleter(m_val_regex, re2::StringPiece((const char*) item.first), re2::RE2::POSIX); + } else if(m_cmpop == CO_REGEX) { + ensure_unique_ptr_allocated_deleter(m_val_regex, + re2::StringPiece((const char*)item.first), + re2::RE2::POSIX); } } -void sinsp_filter_check::add_filter_value(std::unique_ptr rhs_chk) -{ - if(!get_filter_values().empty()) - { - throw sinsp_exception("can't add '" - + std::string(rhs_chk->get_transformed_field_info()->m_name) - + "' as field value: field '" - + std::string(get_transformed_field_info()->m_name) - + "' is already compared with other const values"); +void sinsp_filter_check::add_filter_value(std::unique_ptr rhs_chk) { + if(!get_filter_values().empty()) { + throw sinsp_exception( + "can't add '" + std::string(rhs_chk->get_transformed_field_info()->m_name) + + "' as field value: field '" + std::string(get_transformed_field_info()->m_name) + + "' is already compared with other const values"); } - if(has_filtercheck_value()) - { - throw sinsp_exception("can't add '" - + std::string(rhs_chk->get_transformed_field_info()->m_name) - + "' as field value: field '" - + std::string(get_transformed_field_info()->m_name) - + "' is already compared with right-hand side field '" - + std::string(m_rhs_filter_check->get_transformed_field_info()->m_name) + "'"); + if(has_filtercheck_value()) { + throw sinsp_exception( + "can't add '" + std::string(rhs_chk->get_transformed_field_info()->m_name) + + "' as field value: field '" + std::string(get_transformed_field_info()->m_name) + + "' is already compared with right-hand side field '" + + std::string(m_rhs_filter_check->get_transformed_field_info()->m_name) + "'"); } - if(m_cmpop == CO_PMATCH || m_cmpop == CO_REGEX) - { - throw sinsp_exception("operator '" + std::to_string(m_cmpop) + "' doesn't support right-hand side fields"); + if(m_cmpop == CO_PMATCH || m_cmpop == CO_REGEX) { + throw sinsp_exception("operator '" + std::to_string(m_cmpop) + + "' doesn't support right-hand side fields"); } - if (get_transformed_field_info()->m_type == PT_IPNET - || get_transformed_field_info()->m_type == PT_IPV4NET - || get_transformed_field_info()->m_type == PT_IPV6NET) - { + if(get_transformed_field_info()->m_type == PT_IPNET || + get_transformed_field_info()->m_type == PT_IPV4NET || + get_transformed_field_info()->m_type == PT_IPV6NET) { throw sinsp_exception("field type 'IPNET' doesn't support right-hand side fields"); } @@ -795,38 +629,43 @@ void sinsp_filter_check::add_filter_value(std::unique_ptr rh // // There are the involved filter checks: // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. It cannot be used as a rhs filter check because doesn't provide the extraction phase. // "fd.ip" // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. It cannot be used as a rhs filter check because doesn't provide the extraction phase. // "fd.net" // - // 1. It requires a netmask as a rhs value, we don't have filter checks that return a netmask in the extraction phase - // 2. It cannot be used as a rhs value filter check for other `PT_IPNET` filter checks, becuase they expect a netmask while it returns an address - // "fd.cnet" - // "fd.snet" - // "fd.lnet" - // "fd.rnet" + // 1. It requires a netmask as a rhs value, we don't have filter checks that return a netmask in + // the extraction phase + // 2. It cannot be used as a rhs value filter check for other `PT_IPNET` filter checks, becuase + // they expect a netmask while it returns an address "fd.cnet" "fd.snet" "fd.lnet" "fd.rnet" // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. It is a PT_DYN we don't know which is the effective type value. // "evt.rawarg" // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. It has no real sense to be used as a rhs (we can do if want, let's see) // "evt.around" // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. It cannot be used as a rhs filter check because doesn't provide the extraction phase. // "fd.port" // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. It cannot be used as a rhs filter check because doesn't provide the extraction phase. // "fd.proto" // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. OK! (but not supported for simplicity) // "proc.apid" // "proc.aname" @@ -835,25 +674,22 @@ void sinsp_filter_check::add_filter_value(std::unique_ptr rh // "proc.acmdline" // "proc.aenv" // - // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter check with this. + // 1. It has a custom comparison logic (no base `compare_nocache`) so we cannot use a rhs filter + // check with this. // 2. OK! (but not supported for simplicity) // "fd.cip.name" // "fd.sip.name" // "fd.lip.name" // "fd.rip.name" - if(!get_transformed_field_info()->is_rhs_field_supported()) - { - throw sinsp_exception("field '" - + std::string(get_transformed_field_info()->m_name) - + "' doesn't support right-hand side fields"); + if(!get_transformed_field_info()->is_rhs_field_supported()) { + throw sinsp_exception("field '" + std::string(get_transformed_field_info()->m_name) + + "' doesn't support right-hand side fields"); } - if(!rhs_chk->get_transformed_field_info()->is_rhs_field_supported()) - { - throw sinsp_exception("field '" - + std::string(get_transformed_field_info()->m_name) - + "' can't be used as a right-hand side field"); + if(!rhs_chk->get_transformed_field_info()->is_rhs_field_supported()) { + throw sinsp_exception("field '" + std::string(get_transformed_field_info()->m_name) + + "' can't be used as a right-hand side field"); } m_rhs_filter_check = std::move(rhs_chk); @@ -861,37 +697,39 @@ void sinsp_filter_check::add_filter_value(std::unique_ptr rh check_rhs_field_type_consistency(); } -size_t sinsp_filter_check::parse_filter_value(const char* str, uint32_t len, uint8_t *storage, uint32_t storage_len) -{ +size_t sinsp_filter_check::parse_filter_value(const char* str, + uint32_t len, + uint8_t* storage, + uint32_t storage_len) { size_t parsed_len; // byte buffer, no parsing needed - if (get_transformed_field_info()->m_type == PT_BYTEBUF) - { - if(len >= storage_len) - { + if(get_transformed_field_info()->m_type == PT_BYTEBUF) { + if(len >= storage_len) { throw sinsp_exception("filter parameter too long (byte buf)"); } memcpy(storage, str, len); return len; - } - else - { - parsed_len = sinsp_filter_value_parser::string_to_rawval(str, len, storage, storage_len, get_transformed_field_info()->m_type); + } else { + parsed_len = + sinsp_filter_value_parser::string_to_rawval(str, + len, + storage, + storage_len, + get_transformed_field_info()->m_type); } return parsed_len; } -bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, std::vector& values) -{ - if(op == CO_EXISTS) - { +bool sinsp_filter_check::compare_rhs(cmpop op, + ppm_param_type type, + std::vector& values) { + if(op == CO_EXISTS) { return true; } - if(get_transformed_field_info()->is_list()) - { + if(get_transformed_field_info()->is_list()) { // NOTE: using m_val_storages_members.find(item) relies on memcmp to // compare filter_value_t values, and not the base-level flt_compare. // This has two main consequences. First, this only works for equality @@ -901,152 +739,131 @@ bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, std::vector< // flt_compare uses some additional logic for certain data types (e.g. ipv6). // None of the libsinsp internal filterchecks use list type fields for now. // - // todo(jasondellaluce): refactor filter_value_t to actually use flt_compare instead of memcmp. - switch (type) - { - case PT_CHARBUF: - case PT_UINT64: - case PT_RELTIME: - case PT_ABSTIME: - case PT_BOOL: - case PT_IPADDR: - case PT_IPNET: - break; - default: - throw sinsp_exception("list filters are not supported for type " + std::string(param_type_to_string(type))); + // todo(jasondellaluce): refactor filter_value_t to actually use flt_compare instead of + // memcmp. + switch(type) { + case PT_CHARBUF: + case PT_UINT64: + case PT_RELTIME: + case PT_ABSTIME: + case PT_BOOL: + case PT_IPADDR: + case PT_IPNET: + break; + default: + throw sinsp_exception("list filters are not supported for type " + + std::string(param_type_to_string(type))); } filter_value_t item(NULL, 0); - switch (op) - { - case CO_EXISTS: - // note: sinsp_filter_check_*::compare already discard NULL values - return true; - case CO_IN: - for (const auto& it : values) - { - item.first = it.ptr; - item.second = it.len; - - // note: PT_IPNET would not work with simple memcmp comparison - // todo(jasondellaluce): refactor filter_value_t to actually use flt_compare instead of memcmp. - if (type == PT_IPNET) - { - bool found = false; - for (const auto& m : m_vals) - { - if (::flt_compare(CO_EQ, type, item.first, m.first, item.second, m.second)) - { - found = true; - break; - } - } - if (!found) - { - return false; + switch(op) { + case CO_EXISTS: + // note: sinsp_filter_check_*::compare already discard NULL values + return true; + case CO_IN: + for(const auto& it : values) { + item.first = it.ptr; + item.second = it.len; + + // note: PT_IPNET would not work with simple memcmp comparison + // todo(jasondellaluce): refactor filter_value_t to actually use flt_compare instead + // of memcmp. + if(type == PT_IPNET) { + bool found = false; + for(const auto& m : m_vals) { + if(::flt_compare(CO_EQ, type, item.first, m.first, item.second, m.second)) { + found = true; + break; } } - else - { - ensure_unique_ptr_allocated(m_val_storages_members); - if(it.len < m_val_storages_min_size || it.len > m_val_storages_max_size - || m_val_storages_members->find(item) == m_val_storages_members->end()) - { - return false; - } + if(!found) { + return false; } - } - return true; - case CO_INTERSECTS: - for (const auto& it : values) - { - item.first = it.ptr; - item.second = it.len; - - // note: PT_IPNET would not work with simple memcmp comparison - // todo(jasondellaluce): refactor filter_value_t to actually use flt_compare instead of memcmp. - if (type == PT_IPNET) - { - for (const auto& m : m_vals) - { - if (::flt_compare(CO_EQ, type, item.first, m.first, item.second, m.second)) - { - return true; - } - } + } else { + ensure_unique_ptr_allocated(m_val_storages_members); + if(it.len < m_val_storages_min_size || it.len > m_val_storages_max_size || + m_val_storages_members->find(item) == m_val_storages_members->end()) { + return false; } - else - { - ensure_unique_ptr_allocated(m_val_storages_members); - if(it.len >= m_val_storages_min_size && it.len <= m_val_storages_max_size - && m_val_storages_members->find(item) != m_val_storages_members->end()) - { + } + } + return true; + case CO_INTERSECTS: + for(const auto& it : values) { + item.first = it.ptr; + item.second = it.len; + + // note: PT_IPNET would not work with simple memcmp comparison + // todo(jasondellaluce): refactor filter_value_t to actually use flt_compare instead + // of memcmp. + if(type == PT_IPNET) { + for(const auto& m : m_vals) { + if(::flt_compare(CO_EQ, type, item.first, m.first, item.second, m.second)) { return true; } } + } else { + ensure_unique_ptr_allocated(m_val_storages_members); + if(it.len >= m_val_storages_min_size && it.len <= m_val_storages_max_size && + m_val_storages_members->find(item) != m_val_storages_members->end()) { + return true; + } } - return false; - default: - throw sinsp_exception("list filter '" - + std::string(m_info->m_fields[m_field_id].m_name) - + "' only supports operators 'exists', 'in' and 'intersects'"); + } + return false; + default: + throw sinsp_exception("list filter '" + + std::string(m_info->m_fields[m_field_id].m_name) + + "' only supports operators 'exists', 'in' and 'intersects'"); } - } - else if (values.size() > 1) - { + } else if(values.size() > 1) { ASSERT(false); - throw sinsp_exception("non-list filter '" - + std::string(m_info->m_fields[m_field_id].m_name) - + "' expected to extract a single value, but " - + std::to_string(values.size()) + " were found"); + throw sinsp_exception("non-list filter '" + + std::string(m_info->m_fields[m_field_id].m_name) + + "' expected to extract a single value, but " + + std::to_string(values.size()) + " were found"); } - return compare_rhs(m_cmpop, - type, - values[0].ptr, - values[0].len); + return compare_rhs(m_cmpop, type, values[0].ptr, values[0].len); } -static inline filter_value_t craft_filter_value(ppm_param_type type, const void* value, uint32_t len) -{ +static inline filter_value_t craft_filter_value(ppm_param_type type, + const void* value, + uint32_t len) { // For raw strings, the length may not be set. So we do a strlen to find it. - switch (type) - { - case PT_CHARBUF: - case PT_FSPATH: - case PT_FSRELPATH: - // set len if missing - if (len == 0) - { - len = strlen((const char *) value); - } - - // don't count terminator chars - while (len > 0 && ((const char*) value)[len - 1] == '\0') - { - len--; - } - break; - default: - break; + switch(type) { + case PT_CHARBUF: + case PT_FSPATH: + case PT_FSRELPATH: + // set len if missing + if(len == 0) { + len = strlen((const char*)value); + } + + // don't count terminator chars + while(len > 0 && ((const char*)value)[len - 1] == '\0') { + len--; + } + break; + default: + break; } - return filter_value_t{(uint8_t *) value, len}; + return filter_value_t{(uint8_t*)value, len}; } -bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, const void* operand1, uint32_t op1_len) -{ - switch (op) - { +bool sinsp_filter_check::compare_rhs(cmpop op, + ppm_param_type type, + const void* operand1, + uint32_t op1_len) { + switch(op) { case CO_EXISTS: return true; case CO_IN: case CO_PMATCH: - case CO_INTERSECTS: - { + case CO_INTERSECTS: { // Certain filterchecks can't be done as a set // membership test/group match. For these, just loop over the // values and see if any value is equal. - switch(type) - { + switch(type) { case PT_IPV4NET: case PT_IPV6NET: case PT_IPNET: @@ -1054,15 +871,13 @@ bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, const void* case PT_SOCKTUPLE: case PT_FDLIST: case PT_SIGSET: - for (uint16_t i=0; i < m_vals.size(); i++) - { - if (::flt_compare(CO_EQ, - type, - operand1, - filter_value_p(i), - op1_len, - filter_value_len(i))) - { + for(uint16_t i = 0; i < m_vals.size(); i++) { + if(::flt_compare(CO_EQ, + type, + operand1, + filter_value_p(i), + op1_len, + filter_value_len(i))) { return true; } } @@ -1070,8 +885,7 @@ bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, const void* default: auto item = craft_filter_value(type, operand1, op1_len); - if (op == CO_IN || op == CO_INTERSECTS) - { + if(op == CO_IN || op == CO_INTERSECTS) { // CO_INTERSECTS is really more interesting when a filtercheck can extract // multiple values, and you're comparing the set of extracted values // against the set of rhs values. sinsp_filter_checks only extract a @@ -1079,16 +893,12 @@ bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, const void* ensure_unique_ptr_allocated(m_val_storages_members); if(item.second >= m_val_storages_min_size && item.second <= m_val_storages_max_size && - m_val_storages_members->find(item) != m_val_storages_members->end()) - { + m_val_storages_members->find(item) != m_val_storages_members->end()) { return true; } - } - else - { + } else { ensure_unique_ptr_allocated(m_val_storages_paths); - if (m_val_storages_paths->match(item)) - { + if(m_val_storages_paths->match(item)) { return true; } } @@ -1098,16 +908,15 @@ bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, const void* return false; } case CO_REGEX: - switch(type) - { + switch(type) { case PT_CHARBUF: case PT_FSPATH: case PT_FSRELPATH: - if (m_val_regex) - { + if(m_val_regex) { auto item = craft_filter_value(type, operand1, op1_len); - re2::StringPiece s((const char*) item.first, item.second); - return m_val_regex->Match(s, 0, item.second, re2::RE2::Anchor::ANCHOR_BOTH, nullptr, 0); + re2::StringPiece s((const char*)item.first, item.second); + return m_val_regex + ->Match(s, 0, item.second, re2::RE2::Anchor::ANCHOR_BOTH, nullptr, 0); } // fallthrough default: @@ -1115,52 +924,43 @@ bool sinsp_filter_check::compare_rhs(cmpop op, ppm_param_type type, const void* return false; }; default: - return (::flt_compare(op, - type, - operand1, - filter_value_p(), - op1_len, - filter_value_len()) - ); + return (::flt_compare(op, type, operand1, filter_value_p(), op1_len, filter_value_len())); } } -bool sinsp_filter_check::extract_nocache(sinsp_evt *evt, std::vector& values, bool sanitize_strings) -{ +bool sinsp_filter_check::extract_nocache(sinsp_evt* evt, + std::vector& values, + bool sanitize_strings) { values.clear(); extract_value_t val; val.ptr = extract_single(evt, &val.len, sanitize_strings); - if (val.ptr != NULL) - { + if(val.ptr != NULL) { values.push_back(val); return true; } return false; } -uint8_t* sinsp_filter_check::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check::extract_single(sinsp_evt* evt, uint32_t* len, bool sanitize_strings) { return NULL; } -bool sinsp_filter_check::extract(sinsp_evt *evt, std::vector& values, bool sanitize_strings) -{ - if(m_cache_metrics != NULL) - { +bool sinsp_filter_check::extract(sinsp_evt* evt, + std::vector& values, + bool sanitize_strings) { + if(m_cache_metrics != NULL) { m_cache_metrics->m_num_extract++; } // no cache is installed, so just default to non-cached extraction - if (!m_extract_cache) - { + if(!m_extract_cache) { // extract values and apply transformers on top of them return extract_nocache(evt, values, sanitize_strings) && apply_transformers(values); } // cache is not valid for this event, so we perform a non-cached extraction // and update it for the next time. We cache both failed and succeeded extractions - if (!m_extract_cache->is_valid(evt)) - { + if(!m_extract_cache->is_valid(evt)) { // for now, we support only shallow copies of cached values for performance // gains -- we rely on each filtercheck to keep owning the result values // across different extractions @@ -1169,62 +969,52 @@ bool sinsp_filter_check::extract(sinsp_evt *evt, std::vector& v m_extract_cache->update(evt, res, values, deepcopy); return res; } - + // cache hit, so copy the values, update the metrics, and return values = m_extract_cache->values(); - if(m_cache_metrics != NULL) - { + if(m_cache_metrics != NULL) { m_cache_metrics->m_num_extract_cache++; } return m_extract_cache->result(); } -bool sinsp_filter_check::compare(sinsp_evt* evt) -{ - if (m_cache_metrics != NULL) - { +bool sinsp_filter_check::compare(sinsp_evt* evt) { + if(m_cache_metrics != NULL) { m_cache_metrics->m_num_compare++; } // no cache is installed, so just default to non-cached comparison - if (!m_compare_cache) - { + if(!m_compare_cache) { return compare_nocache(evt); } // cache is not valid for this event, so we perform a non-cached comparison // and update it for the next time. We cache both failed and succeeded comparison - if (!m_compare_cache->is_valid(evt)) - { + if(!m_compare_cache->is_valid(evt)) { auto res = compare_nocache(evt); m_compare_cache->update(evt, res); return res; } // cache hit, so copy the values, update the metrics, and return - if (m_cache_metrics != NULL) - { + if(m_cache_metrics != NULL) { m_cache_metrics->m_num_compare_cache++; } return m_compare_cache->result(); } -bool sinsp_filter_check::compare_nocache(sinsp_evt* evt) -{ +bool sinsp_filter_check::compare_nocache(sinsp_evt* evt) { m_extracted_values.clear(); - if(!extract(evt, m_extracted_values, false)) - { + if(!extract(evt, m_extracted_values, false)) { return false; } auto lhs_type = get_transformed_field_info()->m_type; - if(has_filtercheck_value()) - { + if(has_filtercheck_value()) { check_rhs_field_type_consistency(); m_rhs_filter_check->m_extracted_values.clear(); - if(!m_rhs_filter_check->extract(evt, m_rhs_filter_check->m_extracted_values, false)) - { + if(!m_rhs_filter_check->extract(evt, m_rhs_filter_check->m_extracted_values, false)) { return false; } @@ -1234,19 +1024,15 @@ bool sinsp_filter_check::compare_nocache(sinsp_evt* evt) return compare_rhs(m_cmpop, lhs_type, m_extracted_values); } -void sinsp_filter_check::add_transformer(filter_transformer_type trtype) -{ +void sinsp_filter_check::add_transformer(filter_transformer_type trtype) { auto original_type = get_field_info(); - if (!original_type) - { + if(!original_type) { throw sinsp_exception("transformer added to non-initialized field info"); } - if(!original_type->is_transformer_supported()) - { - throw sinsp_exception("field '" - + std::string(get_field_info()->m_name) - + "' does not support transformers"); + if(!original_type->is_transformer_supported()) { + throw sinsp_exception("field '" + std::string(get_field_info()->m_name) + + "' does not support transformers"); } // lazily allocate copy of the field's info to add transformations on top of @@ -1258,14 +1044,12 @@ void sinsp_filter_check::add_transformer(filter_transformer_type trtype) // apply type transformation, both as a feasibility check and // as an information to be returned later on sinsp_filter_transformer tr(trtype); - if (!tr.transform_type(m_transformed_field->m_type)) - { - throw sinsp_exception("can't add field transformer: type '" - + std::string(param_type_to_string(m_transformed_field->m_type)) - + "' is not supported by '" - + filter_transformer_type_str(trtype) - + "' transformer applied on field '" - + std::string(get_field_info()->m_name) + "'"); + if(!tr.transform_type(m_transformed_field->m_type)) { + throw sinsp_exception("can't add field transformer: type '" + + std::string(param_type_to_string(m_transformed_field->m_type)) + + "' is not supported by '" + filter_transformer_type_str(trtype) + + "' transformer applied on field '" + + std::string(get_field_info()->m_name) + "'"); } // add transformer to the back of the list, they will be applied at @@ -1276,61 +1060,51 @@ void sinsp_filter_check::add_transformer(filter_transformer_type trtype) check_rhs_field_type_consistency(); } -bool sinsp_filter_check::apply_transformers(std::vector& values) -{ +bool sinsp_filter_check::apply_transformers(std::vector& values) { auto type = get_field_info()->m_type; - for(auto& tr : m_transformers) - { - if (!tr.transform_values(values, type)) - { + for(auto& tr : m_transformers) { + if(!tr.transform_values(values, type)) { return false; } } return true; } -void sinsp_filter_check::populate_filter_values_with_rhs_extracted_values(const std::vector& values) -{ +void sinsp_filter_check::populate_filter_values_with_rhs_extracted_values( + const std::vector& values) { // The storage of the extracted values from the rhs filter check should // be handled by the filter check itself during the extraction. - + // Clean the previous comparison. m_vals.clear(); // These are needed for In/Intersects - if (m_cmpop == CO_IN || m_cmpop == CO_INTERSECTS) - { + if(m_cmpop == CO_IN || m_cmpop == CO_INTERSECTS) { ensure_unique_ptr_allocated(m_val_storages_members); m_val_storages_members->clear(); m_val_storages_min_size = (std::numeric_limits::max)(); m_val_storages_max_size = (std::numeric_limits::min)(); } - for(const auto& v : values) - { + for(const auto& v : values) { filter_value_t item(v.ptr, v.len); m_vals.push_back(item); - - if (m_cmpop == CO_IN || m_cmpop == CO_INTERSECTS) - { + + if(m_cmpop == CO_IN || m_cmpop == CO_INTERSECTS) { m_val_storages_members->insert(std::move(item)); - if(v.len < m_val_storages_min_size) - { + if(v.len < m_val_storages_min_size) { m_val_storages_min_size = v.len; } - if(v.len > m_val_storages_max_size) - { + if(v.len > m_val_storages_max_size) { m_val_storages_max_size = v.len; } } } } -void sinsp_filter_check::check_rhs_field_type_consistency() const -{ - if (!has_filtercheck_value()) - { +void sinsp_filter_check::check_rhs_field_type_consistency() const { + if(!has_filtercheck_value()) { return; } @@ -1340,18 +1114,13 @@ void sinsp_filter_check::check_rhs_field_type_consistency() const auto rhs_list = m_rhs_filter_check->get_transformed_field_info()->is_list(); auto rhs_type = m_rhs_filter_check->get_transformed_field_info()->m_type; - if(!(lhs_type == rhs_type && lhs_list == rhs_list)) - { - throw sinsp_exception("field '" - + std::string(get_transformed_field_info()->m_name) - + "' has type '" - + std::string(param_type_to_string(lhs_type)) - + (lhs_list ? " (list)" : "") - + "' while the right-hand side field '" - + std::string(m_rhs_filter_check->get_transformed_field_info()->m_name) - + "' has incompatible type '" - + std::string(param_type_to_string(rhs_type)) - + (rhs_list ? " (list)" : "") - + "'"); + if(!(lhs_type == rhs_type && lhs_list == rhs_list)) { + throw sinsp_exception( + "field '" + std::string(get_transformed_field_info()->m_name) + "' has type '" + + std::string(param_type_to_string(lhs_type)) + (lhs_list ? " (list)" : "") + + "' while the right-hand side field '" + + std::string(m_rhs_filter_check->get_transformed_field_info()->m_name) + + "' has incompatible type '" + std::string(param_type_to_string(rhs_type)) + + (rhs_list ? " (list)" : "") + "'"); } } diff --git a/userspace/libsinsp/sinsp_filtercheck.h b/userspace/libsinsp/sinsp_filtercheck.h index b87b23b7e3..1c9d7de1a5 100644 --- a/userspace/libsinsp/sinsp_filtercheck.h +++ b/userspace/libsinsp/sinsp_filtercheck.h @@ -32,10 +32,11 @@ limitations under the License. #include #include -namespace re2 { class RE2; }; +namespace re2 { +class RE2; +}; -enum boolop: uint8_t -{ +enum boolop : uint8_t { BO_NONE = 0, BO_NOT = 1, BO_OR = 2, @@ -46,8 +47,7 @@ enum boolop: uint8_t BO_ANDNOT = 5, }; -namespace std -{ +namespace std { std::string to_string(boolop); } @@ -56,8 +56,7 @@ std::string to_string(boolop); // NOTE: in order to add a new type of filter check, you need to add a class for // it and then add it to new_filter_check_from_name. /////////////////////////////////////////////////////////////////////////////// -class sinsp_filter_check -{ +class sinsp_filter_check { public: sinsp_filter_check(); virtual ~sinsp_filter_check() = default; @@ -71,27 +70,20 @@ class sinsp_filter_check // Allocate a new check of the same type. // Every filtercheck plugin must implement this. // - virtual std::unique_ptr allocate_new() - { + virtual std::unique_ptr allocate_new() { throw sinsp_exception("can't clone abstract sinsp_filter_check"); } // // Get the list of fields that this check exports // - virtual const filter_check_info* get_fields() const - { - return m_info; - } + virtual const filter_check_info* get_fields() const { return m_info; } // // Return the info about the field that this instance contains // This must be used only after `parse_field_name` // - virtual const filtercheck_field_info* get_field_info() const - { - return m_field; - } + virtual const filtercheck_field_info* get_field_info() const { return m_field; } // // Parse the name of the field. @@ -114,18 +106,12 @@ class sinsp_filter_check // // Return the right-hand side constant values used for comparison // - virtual const std::vector& get_filter_values() const - { - return m_vals; - } + virtual const std::vector& get_filter_values() const { return m_vals; } // // Return true if the filter check is compared against another filter check // - virtual bool has_filtercheck_value() const - { - return m_rhs_filter_check.get() != nullptr; - } + virtual bool has_filtercheck_value() const { return m_rhs_filter_check.get() != nullptr; } // // Add extract transformers to the filter check @@ -135,19 +121,14 @@ class sinsp_filter_check // // Return true if the filter check contains field transformers // - virtual bool has_transformers() const - { - return !m_transformers.empty(); - } + virtual bool has_transformers() const { return !m_transformers.empty(); } // // Return the type of the current field after applying // all the configured transformers // - virtual const filtercheck_field_info* get_transformed_field_info() const - { - if (m_transformed_field != nullptr) - { + virtual const filtercheck_field_info* get_transformed_field_info() const { + if(m_transformed_field != nullptr) { return m_transformed_field.get(); } return get_field_info(); @@ -189,18 +170,14 @@ class sinsp_filter_check cmpop m_cmpop = CO_NONE; char* rawval_to_string(uint8_t* rawval, - ppm_param_type ptype, - ppm_print_format print_format, - uint32_t len); - + ppm_param_type ptype, + ppm_print_format print_format, + uint32_t len); protected: virtual bool compare_nocache(sinsp_evt*); - virtual Json::Value extract_as_js(sinsp_evt*, uint32_t* len) - { - return Json::nullValue; - } + virtual Json::Value extract_as_js(sinsp_evt*, uint32_t* len) { return Json::nullValue; } // // If present, apply all the transformers on the current filter check @@ -208,30 +185,36 @@ class sinsp_filter_check // bool apply_transformers(std::vector& values); - virtual size_t parse_filter_value(const char* str, uint32_t len, uint8_t *storage, uint32_t storage_len); + virtual size_t parse_filter_value(const char* str, + uint32_t len, + uint8_t* storage, + uint32_t storage_len); // This is a single-value version of extract for subclasses non supporting extracting // multiple values. By default, this returns NULL. // Subclasses are meant to either override this, or the multi-valued extract method. // // \param values [out] the values extracted from the filter check - virtual bool extract_nocache(sinsp_evt *evt, std::vector& values, bool sanitize_strings = true); + virtual bool extract_nocache(sinsp_evt* evt, + std::vector& values, + bool sanitize_strings = true); // \param len [out] length in bytes for the returned value virtual uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true); bool compare_rhs(cmpop op, ppm_param_type type, const void* operand1, uint32_t op1_len = 0); bool compare_rhs(cmpop op, ppm_param_type type, std::vector& values); - Json::Value rawval_to_json(uint8_t* rawval, ppm_param_type ptype, ppm_print_format print_format, uint32_t len); + Json::Value rawval_to_json(uint8_t* rawval, + ppm_param_type ptype, + ppm_print_format print_format, + uint32_t len); - inline uint8_t* filter_value_p(uint16_t i = 0) - { + inline uint8_t* filter_value_p(uint16_t i = 0) { ASSERT(i < m_vals.size()); return m_vals[i].first; } - inline uint32_t filter_value_len(uint16_t i = 0) - { + inline uint32_t filter_value_len(uint16_t i = 0) { ASSERT(i < m_vals.size()); return m_vals[i].second; } @@ -243,7 +226,7 @@ class sinsp_filter_check const filtercheck_field_info* m_field = nullptr; const filter_check_info* m_info = nullptr; - uint32_t m_field_id = (uint32_t) -1; + uint32_t m_field_id = (uint32_t)-1; private: // @@ -251,23 +234,24 @@ class sinsp_filter_check // filter compile time, it populates the filter check values with values extracted // from a right-hand side filter check at runtime. // - inline void populate_filter_values_with_rhs_extracted_values(const std::vector& values); + inline void populate_filter_values_with_rhs_extracted_values( + const std::vector& values); inline void check_rhs_field_type_consistency() const; - std::list m_transformers; + std::list m_transformers; std::unique_ptr m_rhs_filter_check = nullptr; std::unique_ptr m_transformed_field = nullptr; // used for comparing right-hand lists of values - std::unique_ptr< - std::unordered_set> m_val_storages_members; + std::unique_ptr> + m_val_storages_members; std::unique_ptr m_val_storages_paths; uint32_t m_val_storages_min_size; uint32_t m_val_storages_max_size; - struct default_re2_deleter { void operator()(re2::RE2* __ptr) const; }; + struct default_re2_deleter { + void operator()(re2::RE2* __ptr) const; + }; std::unique_ptr m_val_regex; static constexpr const size_t s_min_filter_value_buf_size = 16; diff --git a/userspace/libsinsp/sinsp_filtercheck_container.cpp b/userspace/libsinsp/sinsp_filtercheck_container.cpp index 5be96f593c..3ea445c7a0 100644 --- a/userspace/libsinsp/sinsp_filtercheck_container.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_container.cpp @@ -22,86 +22,258 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) - -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -static const filtercheck_field_info sinsp_filter_check_container_fields[] = -{ - {PT_CHARBUF, EPF_NONE, PF_NA, "container.id", "Container ID", "The truncated container ID (first 12 characters), e.g. 3ad7b26ded6d is extracted from the Linux cgroups by Falco within the kernel. Consequently, this field is reliably available and serves as the lookup key for Falco's synchronous or asynchronous requests against the container runtime socket to retrieve all other 'container.*' information. One important aspect to be aware of is that if the process occurs on the host, meaning not in the container PID namespace, this field is set to a string called 'host'. In Kubernetes, pod sandbox container processes can exist where `container.id` matches `k8s.pod.sandbox_id`, lacking other 'container.*' details."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.full_id", "Container ID", "The full container ID, e.g. 3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e. In contrast to `container.id`, we enrich this field as part of the container engine enrichment. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.name", "Container Name", "The container name. In instances of userspace container engine lookup delays, this field may not be available yet. One important aspect to be aware of is that if the process occurs on the host, meaning not in the container PID namespace, this field is set to a string called 'host'."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.image", "Image Name", "The container image name (e.g. falcosecurity/falco:latest for docker). In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.image.id", "Image ID", "The container image id (e.g. 6f7e2741b66b). In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.type", "Type", "The container type, e.g. docker, cri-o, containerd etc."}, - {PT_BOOL, EPF_NONE, PF_NA, "container.privileged", "Privileged", "'true' for containers running as privileged, 'false' otherwise. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.mounts", "Mounts", "A space-separated list of mount information. Each item in the list has the format 'source:dest:mode:rdrw:propagation'. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "container.mount", "Mount", "Information about a single mount, specified by number (e.g. container.mount[0]) or mount source (container.mount[/usr/local]). The pathname can be a glob (container.mount[/usr/local/*]), in which case the first matching mount will be returned. The information has the format 'source:dest:mode:rdrw:propagation'. If there is no mount with the specified index or matching the provided source, returns the string \"none\" instead of a NULL value. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "container.mount.source", "Mount Source", "The mount source, specified by number (e.g. container.mount.source[0]) or mount destination (container.mount.source[/host/lib/modules]). The pathname can be a glob. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "container.mount.dest", "Mount Destination", "The mount destination, specified by number (e.g. container.mount.dest[0]) or mount source (container.mount.dest[/lib/modules]). The pathname can be a glob. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "container.mount.mode", "Mount Mode", "The mount mode, specified by number (e.g. container.mount.mode[0]) or mount source (container.mount.mode[/usr/local]). The pathname can be a glob. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "container.mount.rdwr", "Mount Read/Write", "The mount rdwr value, specified by number (e.g. container.mount.rdwr[0]) or mount source (container.mount.rdwr[/usr/local]). The pathname can be a glob. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "container.mount.propagation", "Mount Propagation", "The mount propagation value, specified by number (e.g. container.mount.propagation[0]) or mount source (container.mount.propagation[/usr/local]). The pathname can be a glob. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.image.repository", "Repository", "The container image repository (e.g. falcosecurity/falco). In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.image.tag", "Image Tag", "The container image tag (e.g. stable, latest). In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.image.digest", "Registry Digest", "The container image registry digest (e.g. sha256:d977378f890d445c15e51795296e4e5062f109ce6da83e0a355fc4ad8699d27). In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.healthcheck", "Health Check", "The container's health check. Will be the null value (\"N/A\") if no healthcheck configured, \"NONE\" if configured but explicitly not created, and the healthcheck command line otherwise. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.liveness_probe", "Liveness", "The container's liveness probe. Will be the null value (\"N/A\") if no liveness probe configured, the liveness probe command line otherwise. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.readiness_probe", "Readiness", "The container's readiness probe. Will be the null value (\"N/A\") if no readiness probe configured, the readiness probe command line otherwise. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_UINT64, EPF_NONE, PF_DEC, "container.start_ts", "Container start", "Container start as epoch timestamp in nanoseconds based on proc.pidns_init_start_ts and extracted in the kernel and not from the container runtime socket / container engine."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "container.duration", "Number of nanoseconds since container.start_ts", "Number of nanoseconds since container.start_ts."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.ip", "Container ip address", "The container's / pod's primary ip address as retrieved from the container engine. Only ipv4 addresses are tracked. Consider container.cni.json (CRI use case) for logging ip addresses for each network interface. In instances of userspace container engine lookup delays, this field may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "container.cni.json", "Container's / pod's CNI result json", "The container's / pod's CNI result field from the respective pod status info. It contains ip addresses for each network interface exposed as unparsed escaped JSON string. Supported for CRI container engine (containerd, cri-o runtimes), optimized for containerd (some non-critical JSON keys removed). Useful for tracking ips (ipv4 and ipv6, dual-stack support) for each network interface (multi-interface support). In instances of userspace container engine lookup delays, this field may not be available yet."}, +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t *)&(x); \ + } while(0) + +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t *)(x).c_str(); \ + } while(0) + +static const filtercheck_field_info sinsp_filter_check_container_fields[] = { + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.id", + "Container ID", + "The truncated container ID (first 12 characters), e.g. 3ad7b26ded6d is extracted from " + "the Linux cgroups by Falco within the kernel. Consequently, this field is reliably " + "available and serves as the lookup key for Falco's synchronous or asynchronous requests " + "against the container runtime socket to retrieve all other 'container.*' information. " + "One important aspect to be aware of is that if the process occurs on the host, meaning " + "not in the container PID namespace, this field is set to a string called 'host'. In " + "Kubernetes, pod sandbox container processes can exist where `container.id` matches " + "`k8s.pod.sandbox_id`, lacking other 'container.*' details."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.full_id", + "Container ID", + "The full container ID, e.g. " + "3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e. In contrast to " + "`container.id`, we enrich this field as part of the container engine enrichment. In " + "instances of userspace container engine lookup delays, this field may not be available " + "yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.name", + "Container Name", + "The container name. In instances of userspace container engine lookup delays, this field " + "may not be available yet. One important aspect to be aware of is that if the process " + "occurs on the host, meaning not in the container PID namespace, this field is set to a " + "string called 'host'."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.image", + "Image Name", + "The container image name (e.g. falcosecurity/falco:latest for docker). In instances of " + "userspace container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.image.id", + "Image ID", + "The container image id (e.g. 6f7e2741b66b). In instances of userspace container engine " + "lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.type", + "Type", + "The container type, e.g. docker, cri-o, containerd etc."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "container.privileged", + "Privileged", + "'true' for containers running as privileged, 'false' otherwise. In instances of " + "userspace container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.mounts", + "Mounts", + "A space-separated list of mount information. Each item in the list has the format " + "'source:dest:mode:rdrw:propagation'. In instances of userspace container engine lookup " + "delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "container.mount", + "Mount", + "Information about a single mount, specified by number (e.g. container.mount[0]) or mount " + "source (container.mount[/usr/local]). The pathname can be a glob " + "(container.mount[/usr/local/*]), in which case the first matching mount will be " + "returned. The information has the format 'source:dest:mode:rdrw:propagation'. If there " + "is no mount with the specified index or matching the provided source, returns the string " + "\"none\" instead of a NULL value. In instances of userspace container engine lookup " + "delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "container.mount.source", + "Mount Source", + "The mount source, specified by number (e.g. container.mount.source[0]) or mount " + "destination (container.mount.source[/host/lib/modules]). The pathname can be a glob. In " + "instances of userspace container engine lookup delays, this field may not be available " + "yet."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "container.mount.dest", + "Mount Destination", + "The mount destination, specified by number (e.g. container.mount.dest[0]) or mount " + "source (container.mount.dest[/lib/modules]). The pathname can be a glob. In instances of " + "userspace container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "container.mount.mode", + "Mount Mode", + "The mount mode, specified by number (e.g. container.mount.mode[0]) or mount source " + "(container.mount.mode[/usr/local]). The pathname can be a glob. In instances of " + "userspace container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "container.mount.rdwr", + "Mount Read/Write", + "The mount rdwr value, specified by number (e.g. container.mount.rdwr[0]) or mount source " + "(container.mount.rdwr[/usr/local]). The pathname can be a glob. In instances of " + "userspace container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "container.mount.propagation", + "Mount Propagation", + "The mount propagation value, specified by number (e.g. container.mount.propagation[0]) " + "or mount source (container.mount.propagation[/usr/local]). The pathname can be a glob. " + "In instances of userspace container engine lookup delays, this field may not be " + "available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.image.repository", + "Repository", + "The container image repository (e.g. falcosecurity/falco). In instances of userspace " + "container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.image.tag", + "Image Tag", + "The container image tag (e.g. stable, latest). In instances of userspace container " + "engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.image.digest", + "Registry Digest", + "The container image registry digest (e.g. " + "sha256:d977378f890d445c15e51795296e4e5062f109ce6da83e0a355fc4ad8699d27). In instances of " + "userspace container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.healthcheck", + "Health Check", + "The container's health check. Will be the null value (\"N/A\") if no healthcheck " + "configured, \"NONE\" if configured but explicitly not created, and the healthcheck " + "command line otherwise. In instances of userspace container engine lookup delays, this " + "field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.liveness_probe", + "Liveness", + "The container's liveness probe. Will be the null value (\"N/A\") if no liveness probe " + "configured, the liveness probe command line otherwise. In instances of userspace " + "container engine lookup delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.readiness_probe", + "Readiness", + "The container's readiness probe. Will be the null value (\"N/A\") if no readiness probe " + "configured, the readiness probe command line otherwise. In instances of userspace " + "container engine lookup delays, this field may not be available yet."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "container.start_ts", + "Container start", + "Container start as epoch timestamp in nanoseconds based on proc.pidns_init_start_ts and " + "extracted in the kernel and not from the container runtime socket / container engine."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "container.duration", + "Number of nanoseconds since container.start_ts", + "Number of nanoseconds since container.start_ts."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.ip", + "Container ip address", + "The container's / pod's primary ip address as retrieved from the container engine. Only " + "ipv4 addresses are tracked. Consider container.cni.json (CRI use case) for logging ip " + "addresses for each network interface. In instances of userspace container engine lookup " + "delays, this field may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "container.cni.json", + "Container's / pod's CNI result json", + "The container's / pod's CNI result field from the respective pod status info. It " + "contains ip addresses for each network interface exposed as unparsed escaped JSON " + "string. Supported for CRI container engine (containerd, cri-o runtimes), optimized for " + "containerd (some non-critical JSON keys removed). Useful for tracking ips (ipv4 and " + "ipv6, dual-stack support) for each network interface (multi-interface support). In " + "instances of userspace container engine lookup delays, this field may not be available " + "yet."}, }; -sinsp_filter_check_container::sinsp_filter_check_container() -{ +sinsp_filter_check_container::sinsp_filter_check_container() { static const filter_check_info s_field_infos = { - "container", - "", - "Container information. If the event is not happening inside a container, both id and name will be set to 'host'.", - sizeof(sinsp_filter_check_container_fields) / sizeof(sinsp_filter_check_container_fields[0]), - sinsp_filter_check_container_fields, - filter_check_info::FL_NONE, + "container", + "", + "Container information. If the event is not happening inside a container, both id and " + "name will be set to 'host'.", + sizeof(sinsp_filter_check_container_fields) / + sizeof(sinsp_filter_check_container_fields[0]), + sinsp_filter_check_container_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; memset(&m_val, 0, sizeof(m_val)); } -std::unique_ptr sinsp_filter_check_container::allocate_new() -{ +std::unique_ptr sinsp_filter_check_container::allocate_new() { return std::make_unique(); } -int32_t sinsp_filter_check_container::extract_arg(string_view val, size_t basepos) -{ +int32_t sinsp_filter_check_container::extract_arg(string_view val, size_t basepos) { size_t start = val.find_first_of('[', basepos); - if(start == string::npos) - { + if(start == string::npos) { throw sinsp_exception("filter syntax error: " + string(val)); } size_t end = val.find_first_of(']', start); - if(end == string::npos) - { + if(end == string::npos) { throw sinsp_exception("filter syntax error: " + string(val)); } - string numstr(val.substr(start + 1, end-start - 1)); - try - { + string numstr(val.substr(start + 1, end - start - 1)); + try { m_argid = sinsp_numparser::parsed32(numstr); - } - catch (const sinsp_exception& e) - { - if(strstr(e.what(), "is not a valid number") == NULL) - { + } catch(const sinsp_exception &e) { + if(strstr(e.what(), "is not a valid number") == NULL) { throw; } @@ -109,114 +281,87 @@ int32_t sinsp_filter_check_container::extract_arg(string_view val, size_t basepo m_argstr = numstr; } - return end+1; + return end + 1; } -const std::string &sinsp_filter_check_container::get_argstr() const -{ +const std::string &sinsp_filter_check_container::get_argstr() const { return m_argstr; } -int32_t sinsp_filter_check_container::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ +int32_t sinsp_filter_check_container::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { int32_t res = 0; size_t basepos = sizeof("container.mount"); // container.mount. fields allow for indexing by number or source/dest mount path. - if(val.find("container.mount.") == 0) - { + if(val.find("container.mount.") == 0) { // Note--basepos includes the trailing null, which is // equivalent to the trailing '.' here. - if(val.find("source", basepos) == basepos) - { + if(val.find("source", basepos) == basepos) { m_field_id = TYPE_CONTAINER_MOUNT_SOURCE; - } - else if(val.find("dest", basepos) == basepos) - { + } else if(val.find("dest", basepos) == basepos) { m_field_id = TYPE_CONTAINER_MOUNT_DEST; - } - else if(val.find("mode", basepos) == basepos) - { + } else if(val.find("mode", basepos) == basepos) { m_field_id = TYPE_CONTAINER_MOUNT_MODE; - } - else if(val.find("rdwr", basepos) == basepos) - { + } else if(val.find("rdwr", basepos) == basepos) { m_field_id = TYPE_CONTAINER_MOUNT_RDWR; - } - else if(val.find("propagation", basepos) == basepos) - { + } else if(val.find("propagation", basepos) == basepos) { m_field_id = TYPE_CONTAINER_MOUNT_PROPAGATION; - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } m_field = &m_info->m_fields[m_field_id]; res = extract_arg(val, basepos); - } - else if (val.find("container.mount") == 0 && - val.size() > basepos-1 && val.at(basepos-1) != 's') - { + } else if(val.find("container.mount") == 0 && val.size() > basepos - 1 && + val.at(basepos - 1) != 's') { m_field_id = TYPE_CONTAINER_MOUNT; m_field = &m_info->m_fields[m_field_id]; - res = extract_arg(val, basepos-1); - } - else - { + res = extract_arg(val, basepos - 1); + } else { res = sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } return res; } - -uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t *sinsp_filter_check_container::extract_single(sinsp_evt *evt, + uint32_t *len, + bool sanitize_strings) { *len = 0; - sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + sinsp_threadinfo *tinfo = evt->get_thread_info(); + if(tinfo == NULL) { return NULL; } sinsp_container_info::ptr_t container_info = NULL; bool is_host = tinfo->m_container_id.empty() && !tinfo->is_in_pid_namespace(); - if(!tinfo->m_container_id.empty()) - { + if(!tinfo->m_container_id.empty()) { container_info = m_inspector->m_container_manager.get_container(tinfo->m_container_id); } - switch(m_field_id) - { + switch(m_field_id) { case TYPE_CONTAINER_ID: - if(is_host) - { + if(is_host) { m_tstr = "host"; - } - else - { + } else { m_tstr = tinfo->m_container_id; } RETURN_EXTRACT_STRING(m_tstr); case TYPE_CONTAINER_FULL_CONTAINER_ID: - if(is_host) - { + if(is_host) { m_tstr = "host"; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } - if(container_info->m_full_id.empty()) - { + if(container_info->m_full_id.empty()) { return NULL; } @@ -224,19 +369,14 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* } RETURN_EXTRACT_STRING(m_tstr); case TYPE_CONTAINER_NAME: - if(is_host) - { + if(is_host) { m_tstr = "host"; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } - if(container_info->m_name.empty()) - { + if(container_info->m_name.empty()) { return NULL; } @@ -245,19 +385,14 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* RETURN_EXTRACT_STRING(m_tstr); case TYPE_CONTAINER_IMAGE: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } - if(container_info->m_image.empty()) - { + if(container_info->m_image.empty()) { return NULL; } @@ -269,20 +404,15 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* case TYPE_CONTAINER_IMAGE_REPOSITORY: case TYPE_CONTAINER_IMAGE_TAG: case TYPE_CONTAINER_IMAGE_DIGEST: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } const string *field; - switch(m_field_id) - { + switch(m_field_id) { case TYPE_CONTAINER_IMAGE_ID: field = &container_info->m_imageid; break; @@ -299,8 +429,7 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* return nullptr; } - if(field->empty()) - { + if(field->empty()) { return NULL; } @@ -309,18 +438,13 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* RETURN_EXTRACT_STRING(m_tstr); case TYPE_CONTAINER_TYPE: - if(is_host) - { + if(is_host) { m_tstr = "host"; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } - switch(container_info->m_type) - { + switch(container_info->m_type) { case sinsp_container_type::CT_DOCKER: m_tstr = "docker"; break; @@ -358,22 +482,17 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* } RETURN_EXTRACT_STRING(m_tstr); case TYPE_CONTAINER_PRIVILEGED: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } // Only return a true/false value for // container types where we really know the // privileged status. - if (!is_docker_compatible(container_info->m_type)) - { + if(!is_docker_compatible(container_info->m_type)) { return NULL; } @@ -383,27 +502,19 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* RETURN_EXTRACT_VAR(m_val.u32); break; case TYPE_CONTAINER_MOUNTS: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } m_tstr = ""; bool first = true; - for(auto &mntinfo : container_info->m_mounts) - { - if(first) - { + for(auto &mntinfo : container_info->m_mounts) { + if(first) { first = false; - } - else - { + } else { m_tstr += ","; } @@ -415,34 +526,24 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* break; case TYPE_CONTAINER_MOUNT: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } const sinsp_container_info::container_mount_info *mntinfo; - if(m_argid != -1) - { + if(m_argid != -1) { mntinfo = container_info->mount_by_idx(m_argid); - } - else - { + } else { mntinfo = container_info->mount_by_source(m_argstr); } - if(!mntinfo) - { + if(!mntinfo) { return NULL; - } - else - { + } else { m_tstr = mntinfo->to_string(); } @@ -455,42 +556,30 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* case TYPE_CONTAINER_MOUNT_MODE: case TYPE_CONTAINER_MOUNT_RDWR: case TYPE_CONTAINER_MOUNT_PROPAGATION: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } const sinsp_container_info::container_mount_info *mntinfo; - if(m_argid != -1) - { + if(m_argid != -1) { mntinfo = container_info->mount_by_idx(m_argid); - } - else - { - if (m_field_id == TYPE_CONTAINER_MOUNT_SOURCE) - { + } else { + if(m_field_id == TYPE_CONTAINER_MOUNT_SOURCE) { mntinfo = container_info->mount_by_dest(m_argstr); - } - else - { + } else { mntinfo = container_info->mount_by_source(m_argstr); } } - if(!mntinfo) - { + if(!mntinfo) { return NULL; } - switch (m_field_id) - { + switch(m_field_id) { case TYPE_CONTAINER_MOUNT_SOURCE: m_tstr = mntinfo->m_source; break; @@ -514,30 +603,26 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* case TYPE_CONTAINER_HEALTHCHECK: case TYPE_CONTAINER_LIVENESS_PROBE: case TYPE_CONTAINER_READINESS_PROBE: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } - for(auto &probe : container_info->m_health_probes) - { + for(auto &probe : container_info->m_health_probes) { if((m_field_id == TYPE_CONTAINER_HEALTHCHECK && - probe.m_probe_type == sinsp_container_info::container_health_probe::PT_HEALTHCHECK) || + probe.m_probe_type == + sinsp_container_info::container_health_probe::PT_HEALTHCHECK) || (m_field_id == TYPE_CONTAINER_LIVENESS_PROBE && - probe.m_probe_type == sinsp_container_info::container_health_probe::PT_LIVENESS_PROBE) || + probe.m_probe_type == + sinsp_container_info::container_health_probe::PT_LIVENESS_PROBE) || (m_field_id == TYPE_CONTAINER_READINESS_PROBE && - probe.m_probe_type == sinsp_container_info::container_health_probe::PT_READINESS_PROBE)) - { + probe.m_probe_type == + sinsp_container_info::container_health_probe::PT_READINESS_PROBE)) { m_tstr = probe.m_health_probe_exe; - for(auto &arg : probe.m_health_probe_args) - { + for(auto &arg : probe.m_health_probe_args) { m_tstr += " "; m_tstr += arg; } @@ -554,15 +639,13 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* } break; case TYPE_CONTAINER_START_TS: - if(is_host || tinfo->m_pidns_init_start_ts == 0) - { + if(is_host || tinfo->m_pidns_init_start_ts == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_pidns_init_start_ts); break; case TYPE_CONTAINER_DURATION: - if(is_host || tinfo->m_clone_ts == 0) - { + if(is_host || tinfo->m_clone_ts == 0) { return NULL; } m_val.s64 = evt->get_ts() - tinfo->m_pidns_init_start_ts; @@ -570,14 +653,10 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* RETURN_EXTRACT_VAR(m_val.s64); break; case TYPE_CONTAINER_IP_ADDR: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } m_val.u32 = htonl(container_info->m_container_ip); @@ -588,14 +667,10 @@ uint8_t* sinsp_filter_check_container::extract_single(sinsp_evt *evt, uint32_t* } break; case TYPE_CONTAINER_CNIRESULT: - if(is_host) - { + if(is_host) { return NULL; - } - else - { - if(!container_info) - { + } else { + if(!container_info) { return NULL; } RETURN_EXTRACT_STRING(container_info->m_pod_sandbox_cniresult); diff --git a/userspace/libsinsp/sinsp_filtercheck_container.h b/userspace/libsinsp/sinsp_filtercheck_container.h index 35263b549b..ee62a95b4c 100644 --- a/userspace/libsinsp/sinsp_filtercheck_container.h +++ b/userspace/libsinsp/sinsp_filtercheck_container.h @@ -21,11 +21,9 @@ limitations under the License. #include #include -class sinsp_filter_check_container : public sinsp_filter_check -{ +class sinsp_filter_check_container : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_CONTAINER_ID = 0, TYPE_CONTAINER_FULL_CONTAINER_ID, TYPE_CONTAINER_NAME, @@ -56,7 +54,9 @@ class sinsp_filter_check_container : public sinsp_filter_check virtual ~sinsp_filter_check_container() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; const std::string& get_argstr() const; diff --git a/userspace/libsinsp/sinsp_filtercheck_event.cpp b/userspace/libsinsp/sinsp_filtercheck_event.cpp index 351b30d553..5c4f0cd0a5 100644 --- a/userspace/libsinsp/sinsp_filtercheck_event.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_event.cpp @@ -31,107 +31,418 @@ extern sinsp_evttables g_infotables; #define UESTORAGE_INITIAL_BUFSIZE 256 -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) - -#define RETURN_EXTRACT_PTR(x) do { \ - *len = sizeof(*(x)); \ - return (uint8_t*) (x); \ -} while(0) - -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -#define RETURN_EXTRACT_CSTR(x) do { \ - if((x)) \ - { \ - *len = strlen((char *) ((x))); \ - } \ - return (uint8_t*) ((x)); \ -} while(0) - -static inline bool str_match_start(std::string_view val, size_t len, const char* m) -{ +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ + } while(0) + +#define RETURN_EXTRACT_PTR(x) \ + do { \ + *len = sizeof(*(x)); \ + return (uint8_t*)(x); \ + } while(0) + +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) + +#define RETURN_EXTRACT_CSTR(x) \ + do { \ + if((x)) { \ + *len = strlen((char*)((x))); \ + } \ + return (uint8_t*)((x)); \ + } while(0) + +static inline bool str_match_start(std::string_view val, size_t len, const char* m) { return val.compare(0, len, m) == 0; } -#define STR_MATCH(s) str_match_start(val, sizeof (s) -1, s) - -const filtercheck_field_info sinsp_filter_check_event_fields[] = -{ - {PT_RELTIME, EPF_NONE, PF_DEC, "evt.latency", "Latency", "delta between an exit event and the correspondent enter event, in nanoseconds."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "evt.latency.s", "Latency (s)", "integer part of the event latency delta."}, - {PT_RELTIME, EPF_NONE, PF_10_PADDED_DEC, "evt.latency.ns", "Latency (ns)", "fractional part of the event latency delta."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.latency.quantized", "Quantized Latency", "10-base log of the delta between an exit event and the correspondent enter event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.latency.human", "Human-Readable Latency", "delta between an exit event and the correspondent enter event, as a human readable string (e.g. 10.3ms)."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "evt.deltatime", "Delta", "delta between this event and the previous event, in nanoseconds."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "evt.deltatime.s", "Delta (s)", "integer part of the delta between this event and the previous event."}, - {PT_RELTIME, EPF_NONE, PF_10_PADDED_DEC, "evt.deltatime.ns", "Delta (ns)", "fractional part of the delta between this event and the previous event."}, - {PT_CHARBUF, EPF_PRINT_ONLY, PF_NA, "evt.outputtime", "Output Time", "this depends on -t param, default is %evt.time ('h')."}, - {PT_CHARBUF, EPF_NONE, PF_DIR, "evt.dir", "Direction", "event direction can be either '>' for enter events or '<' for exit events."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.type", "Type", "The name of the event (e.g. 'open')."}, - {PT_UINT32, EPF_ARG_REQUIRED, PF_NA, "evt.type.is", "Type Is", "allows one to specify an event type, and returns 1 for events that are of that type. For example, evt.type.is.open returns 1 for open events, 0 for any other event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "syscall.type", "Syscall Type", "For system call events, the name of the system call (e.g. 'open'). Unset for other events (e.g. switch or internal events). Use this field instead of evt.type if you need to make sure that the filtered/printed value is actually a system call."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.category", "Category", "The event category. Example values are 'file' (for file operations like open and close), 'net' (for network operations like socket and bind), memory (for things like brk or mmap), and so on."}, - {PT_INT16, EPF_NONE, PF_ID, "evt.cpu", "CPU Number", "number of the CPU where this event happened."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.args", "Arguments", "all the event arguments, aggregated into a single string."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "evt.arg", "Argument", "one of the event arguments specified by name or by number. Some events (e.g. return codes or FDs) will be converted into a text representation when possible. E.g. 'evt.arg.fd' or 'evt.arg[0]'."}, - {PT_DYN, EPF_ARG_REQUIRED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "evt.rawarg", "Raw Argument", "one of the event arguments specified by name. E.g. 'evt.rawarg.fd'."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.info", "Information", "for most events, this field returns the same value as evt.args. However, for some events (like writes to /dev/log) it provides higher level information coming from decoding the arguments."}, - {PT_BYTEBUF, EPF_NONE, PF_NA, "evt.buffer", "Buffer", "the binary data buffer for events that have one, like read(), recvfrom(), etc. Use this field in filters with 'contains' to search into I/O data buffers."}, - {PT_UINT64, EPF_NONE, PF_DEC, "evt.buflen", "Buffer Length", "the length of the binary data buffer for events that have one, like read(), recvfrom(), etc."}, - {PT_CHARBUF, EPF_NONE, PF_DEC, "evt.res", "Return Value", "event return value, as a string. If the event failed, the result is an error code string (e.g. 'ENOENT'), otherwise the result is the string 'SUCCESS'."}, - {PT_INT64, EPF_NONE, PF_DEC, "evt.rawres", "Raw Return Value", "event return value, as a number (e.g. -2). Useful for range comparisons."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.failed", "Failed", "'true' for events that returned an error status."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_io", "Is I/O", "'true' for events that read or write to FDs, like read(), send, recvfrom(), etc."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_io_read", "Is Read", "'true' for events that read from FDs, like read(), recv(), recvfrom(), etc."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_io_write", "Is Write", "'true' for events that write to FDs, like write(), send(), etc."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.io_dir", "I/O Direction", "'r' for events that read from FDs, like read(); 'w' for events that write to FDs, like write()."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_wait", "Is Wait", "'true' for events that make the thread wait, e.g. sleep(), select(), poll()."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "evt.wait_latency", "Wait Latency", "for events that make the thread wait (e.g. sleep(), select(), poll()), this is the time spent waiting for the event to return, in nanoseconds."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_syslog", "Is Syslog", "'true' for events that are writes to /dev/log."}, - {PT_UINT32, EPF_NONE, PF_DEC, "evt.count", "Count", "This filter field always returns 1."}, - {PT_UINT32, EPF_NONE, PF_DEC, "evt.count.error", "Error Count", "This filter field returns 1 for events that returned with an error."}, - {PT_UINT32, EPF_NONE, PF_DEC, "evt.count.error.file", "File Error Count", "This filter field returns 1 for events that returned with an error and are related to file I/O."}, - {PT_UINT32, EPF_NONE, PF_DEC, "evt.count.error.net", "Network Error Count", "This filter field returns 1 for events that returned with an error and are related to network I/O."}, - {PT_UINT32, EPF_NONE, PF_DEC, "evt.count.error.memory", "Memory Error Count", "This filter field returns 1 for events that returned with an error and are related to memory allocation."}, - {PT_UINT32, EPF_NONE, PF_DEC, "evt.count.error.other", "Other Error Count", "This filter field returns 1 for events that returned with an error and are related to none of the previous categories."}, - {PT_UINT32, EPF_NONE, PF_DEC, "evt.count.exit", "Exit Count", "This filter field returns 1 for exit events."}, - {PT_UINT32, EPF_TABLE_ONLY, PF_DEC, "evt.count.procinfo", "Procinfo Count", "This filter field returns 1 for procinfo events generated by process main threads."}, - {PT_UINT32, EPF_TABLE_ONLY, PF_DEC, "evt.count.threadinfo", "Thread Info Count", "This filter field returns 1 for procinfo events."}, - {PT_UINT64, (filtercheck_field_flags) (EPF_FILTER_ONLY | EPF_ARG_REQUIRED | EPF_NO_RHS | EPF_NO_TRANSFORMER), PF_DEC, "evt.around", "Around Interval", "Accepts the event if it's around the specified time interval. The syntax is evt.around[T]=D, where T is the value returned by %evt.rawtime for the event and D is a delta in milliseconds. For example, evt.around[1404996934793590564]=1000 will return the events with timestamp with one second before the timestamp and one second after it, for a total of two seconds of capture."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "evt.abspath", "Absolute Path", "Absolute path calculated from dirfd and name during syscalls like renameat and symlinkat. Use 'evt.abspath.src' or 'evt.abspath.dst' for syscalls that support multiple paths."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.in", "Input Buffer Length", "the length of the binary data buffer, but only for input I/O events."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.out", "Output Buffer Length", "the length of the binary data buffer, but only for output I/O events."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.file", "File Buffer Length", "the length of the binary data buffer, but only for file I/O events."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.file.in", "File Input Buffer Length", "the length of the binary data buffer, but only for input file I/O events."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.file.out", "File Output Buffer Length", "the length of the binary data buffer, but only for output file I/O events."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.net", "Network Buffer Length", "the length of the binary data buffer, but only for network I/O events."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.net.in", "Network Input Buffer Length", "the length of the binary data buffer, but only for input network I/O events."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "evt.buflen.net.out", "Network Output Buffer Length", "the length of the binary data buffer, but only for output network I/O events."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_open_read", "Is Opened For Reading", "'true' for open/openat/openat2/open_by_handle_at events where the path was opened for reading"}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_open_write", "Is Opened For Writing", "'true' for open/openat/openat2/open_by_handle_at events where the path was opened for writing"}, - {PT_CHARBUF, EPF_TABLE_ONLY, PF_NA, "evt.infra.docker.name", "Docker Name", "for docker infrastructure events, the name of the event."}, - {PT_CHARBUF, EPF_TABLE_ONLY, PF_NA, "evt.infra.docker.container.id", "Docker ID", "for docker infrastructure events, the id of the impacted container."}, - {PT_CHARBUF, EPF_TABLE_ONLY, PF_NA, "evt.infra.docker.container.name", "Container Name", "for docker infrastructure events, the name of the impacted container."}, - {PT_CHARBUF, EPF_TABLE_ONLY, PF_NA, "evt.infra.docker.container.image", "Container Image", "for docker infrastructure events, the image name of the impacted container."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_open_exec", "Is Created With Execute Permissions", "'true' for open/openat/openat2/open_by_handle_at or creat events where a file is created with execute permissions"}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_open_create", "Is Created", "'true' for for open/openat/openat2/open_by_handle_at events where a file is created."}, +#define STR_MATCH(s) str_match_start(val, sizeof(s) - 1, s) + +const filtercheck_field_info sinsp_filter_check_event_fields[] = { + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "evt.latency", + "Latency", + "delta between an exit event and the correspondent enter event, in nanoseconds."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "evt.latency.s", + "Latency (s)", + "integer part of the event latency delta."}, + {PT_RELTIME, + EPF_NONE, + PF_10_PADDED_DEC, + "evt.latency.ns", + "Latency (ns)", + "fractional part of the event latency delta."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.latency.quantized", + "Quantized Latency", + "10-base log of the delta between an exit event and the correspondent enter event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.latency.human", + "Human-Readable Latency", + "delta between an exit event and the correspondent enter event, as a human readable " + "string (e.g. 10.3ms)."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "evt.deltatime", + "Delta", + "delta between this event and the previous event, in nanoseconds."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "evt.deltatime.s", + "Delta (s)", + "integer part of the delta between this event and the previous event."}, + {PT_RELTIME, + EPF_NONE, + PF_10_PADDED_DEC, + "evt.deltatime.ns", + "Delta (ns)", + "fractional part of the delta between this event and the previous event."}, + {PT_CHARBUF, + EPF_PRINT_ONLY, + PF_NA, + "evt.outputtime", + "Output Time", + "this depends on -t param, default is %evt.time ('h')."}, + {PT_CHARBUF, + EPF_NONE, + PF_DIR, + "evt.dir", + "Direction", + "event direction can be either '>' for enter events or '<' for exit events."}, + {PT_CHARBUF, EPF_NONE, PF_NA, "evt.type", "Type", "The name of the event (e.g. 'open')."}, + {PT_UINT32, + EPF_ARG_REQUIRED, + PF_NA, + "evt.type.is", + "Type Is", + "allows one to specify an event type, and returns 1 for events that are of that type. For " + "example, evt.type.is.open returns 1 for open events, 0 for any other event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "syscall.type", + "Syscall Type", + "For system call events, the name of the system call (e.g. 'open'). Unset for other " + "events (e.g. switch or internal events). Use this field instead of evt.type if you need " + "to make sure that the filtered/printed value is actually a system call."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.category", + "Category", + "The event category. Example values are 'file' (for file operations like open and close), " + "'net' (for network operations like socket and bind), memory (for things like brk or " + "mmap), and so on."}, + {PT_INT16, + EPF_NONE, + PF_ID, + "evt.cpu", + "CPU Number", + "number of the CPU where this event happened."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.args", + "Arguments", + "all the event arguments, aggregated into a single string."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "evt.arg", + "Argument", + "one of the event arguments specified by name or by number. Some events (e.g. return " + "codes or FDs) will be converted into a text representation when possible. E.g. " + "'evt.arg.fd' or 'evt.arg[0]'."}, + {PT_DYN, + EPF_ARG_REQUIRED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "evt.rawarg", + "Raw Argument", + "one of the event arguments specified by name. E.g. 'evt.rawarg.fd'."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.info", + "Information", + "for most events, this field returns the same value as evt.args. However, for some events " + "(like writes to /dev/log) it provides higher level information coming from decoding the " + "arguments."}, + {PT_BYTEBUF, + EPF_NONE, + PF_NA, + "evt.buffer", + "Buffer", + "the binary data buffer for events that have one, like read(), recvfrom(), etc. Use this " + "field in filters with 'contains' to search into I/O data buffers."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "evt.buflen", + "Buffer Length", + "the length of the binary data buffer for events that have one, like read(), recvfrom(), " + "etc."}, + {PT_CHARBUF, + EPF_NONE, + PF_DEC, + "evt.res", + "Return Value", + "event return value, as a string. If the event failed, the result is an error code string " + "(e.g. 'ENOENT'), otherwise the result is the string 'SUCCESS'."}, + {PT_INT64, + EPF_NONE, + PF_DEC, + "evt.rawres", + "Raw Return Value", + "event return value, as a number (e.g. -2). Useful for range comparisons."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.failed", + "Failed", + "'true' for events that returned an error status."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_io", + "Is I/O", + "'true' for events that read or write to FDs, like read(), send, recvfrom(), etc."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_io_read", + "Is Read", + "'true' for events that read from FDs, like read(), recv(), recvfrom(), etc."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_io_write", + "Is Write", + "'true' for events that write to FDs, like write(), send(), etc."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.io_dir", + "I/O Direction", + "'r' for events that read from FDs, like read(); 'w' for events that write to FDs, like " + "write()."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_wait", + "Is Wait", + "'true' for events that make the thread wait, e.g. sleep(), select(), poll()."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "evt.wait_latency", + "Wait Latency", + "for events that make the thread wait (e.g. sleep(), select(), poll()), this is the time " + "spent waiting for the event to return, in nanoseconds."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_syslog", + "Is Syslog", + "'true' for events that are writes to /dev/log."}, + {PT_UINT32, EPF_NONE, PF_DEC, "evt.count", "Count", "This filter field always returns 1."}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "evt.count.error", + "Error Count", + "This filter field returns 1 for events that returned with an error."}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "evt.count.error.file", + "File Error Count", + "This filter field returns 1 for events that returned with an error and are related to " + "file I/O."}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "evt.count.error.net", + "Network Error Count", + "This filter field returns 1 for events that returned with an error and are related to " + "network I/O."}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "evt.count.error.memory", + "Memory Error Count", + "This filter field returns 1 for events that returned with an error and are related to " + "memory allocation."}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "evt.count.error.other", + "Other Error Count", + "This filter field returns 1 for events that returned with an error and are related to " + "none of the previous categories."}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "evt.count.exit", + "Exit Count", + "This filter field returns 1 for exit events."}, + {PT_UINT32, + EPF_TABLE_ONLY, + PF_DEC, + "evt.count.procinfo", + "Procinfo Count", + "This filter field returns 1 for procinfo events generated by process main threads."}, + {PT_UINT32, + EPF_TABLE_ONLY, + PF_DEC, + "evt.count.threadinfo", + "Thread Info Count", + "This filter field returns 1 for procinfo events."}, + {PT_UINT64, + (filtercheck_field_flags)(EPF_FILTER_ONLY | EPF_ARG_REQUIRED | EPF_NO_RHS | + EPF_NO_TRANSFORMER), + PF_DEC, + "evt.around", + "Around Interval", + "Accepts the event if it's around the specified time interval. The syntax is " + "evt.around[T]=D, where T is the value returned by %evt.rawtime for the event and D is a " + "delta in milliseconds. For example, evt.around[1404996934793590564]=1000 will return the " + "events with timestamp with one second before the timestamp and one second after it, for " + "a total of two seconds of capture."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "evt.abspath", + "Absolute Path", + "Absolute path calculated from dirfd and name during syscalls like renameat and " + "symlinkat. Use 'evt.abspath.src' or 'evt.abspath.dst' for syscalls that support multiple " + "paths."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.in", + "Input Buffer Length", + "the length of the binary data buffer, but only for input I/O events."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.out", + "Output Buffer Length", + "the length of the binary data buffer, but only for output I/O events."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.file", + "File Buffer Length", + "the length of the binary data buffer, but only for file I/O events."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.file.in", + "File Input Buffer Length", + "the length of the binary data buffer, but only for input file I/O events."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.file.out", + "File Output Buffer Length", + "the length of the binary data buffer, but only for output file I/O events."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.net", + "Network Buffer Length", + "the length of the binary data buffer, but only for network I/O events."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.net.in", + "Network Input Buffer Length", + "the length of the binary data buffer, but only for input network I/O events."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "evt.buflen.net.out", + "Network Output Buffer Length", + "the length of the binary data buffer, but only for output network I/O events."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_open_read", + "Is Opened For Reading", + "'true' for open/openat/openat2/open_by_handle_at events where the path was opened for " + "reading"}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_open_write", + "Is Opened For Writing", + "'true' for open/openat/openat2/open_by_handle_at events where the path was opened for " + "writing"}, + {PT_CHARBUF, + EPF_TABLE_ONLY, + PF_NA, + "evt.infra.docker.name", + "Docker Name", + "for docker infrastructure events, the name of the event."}, + {PT_CHARBUF, + EPF_TABLE_ONLY, + PF_NA, + "evt.infra.docker.container.id", + "Docker ID", + "for docker infrastructure events, the id of the impacted container."}, + {PT_CHARBUF, + EPF_TABLE_ONLY, + PF_NA, + "evt.infra.docker.container.name", + "Container Name", + "for docker infrastructure events, the name of the impacted container."}, + {PT_CHARBUF, + EPF_TABLE_ONLY, + PF_NA, + "evt.infra.docker.container.image", + "Container Image", + "for docker infrastructure events, the image name of the impacted container."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_open_exec", + "Is Created With Execute Permissions", + "'true' for open/openat/openat2/open_by_handle_at or creat events where a file is created " + "with execute permissions"}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_open_create", + "Is Created", + "'true' for for open/openat/openat2/open_by_handle_at events where a file is created."}, }; -sinsp_filter_check_event::sinsp_filter_check_event() -{ +sinsp_filter_check_event::sinsp_filter_check_event() { static const filter_check_info s_field_infos = { - "evt", - "Syscall events only", - "Event fields applicable to syscall events. Note that for most events you can access the individual arguments/parameters of each syscall via evt.arg, e.g. evt.arg.filename.", - sizeof(sinsp_filter_check_event_fields) / sizeof(sinsp_filter_check_event_fields[0]), - sinsp_filter_check_event_fields, - filter_check_info::FL_NONE, + "evt", + "Syscall events only", + "Event fields applicable to syscall events. Note that for most events you can access " + "the individual arguments/parameters of each syscall via evt.arg, e.g. " + "evt.arg.filename.", + sizeof(sinsp_filter_check_event_fields) / sizeof(sinsp_filter_check_event_fields[0]), + sinsp_filter_check_event_fields, + filter_check_info::FL_NONE, }; m_is_compare = false; m_info = &s_field_infos; @@ -139,123 +450,105 @@ sinsp_filter_check_event::sinsp_filter_check_event() m_converter = std::make_unique(); } -std::unique_ptr sinsp_filter_check_event::allocate_new() -{ +std::unique_ptr sinsp_filter_check_event::allocate_new() { return std::make_unique(); } -int32_t sinsp_filter_check_event::extract_arg(string_view fldname, string_view val, const ppm_param_info** parinfo) -{ +int32_t sinsp_filter_check_event::extract_arg(string_view fldname, + string_view val, + const ppm_param_info** parinfo) { uint32_t parsed_len = 0; // // 'arg' and 'resarg' are handled in a custom way // - if(val.size() > fldname.size() && val.at(fldname.size()) == '[') - { - if(parinfo != NULL) - { + if(val.size() > fldname.size() && val.at(fldname.size()) == '[') { + if(parinfo != NULL) { throw sinsp_exception("evt.arg fields must be expressed explicitly"); } parsed_len = (uint32_t)val.find(']'); string numstr(val.substr(fldname.size() + 1, parsed_len - fldname.size() - 1)); - if(m_field_id == TYPE_AROUND) - { + if(m_field_id == TYPE_AROUND) { m_val.u64 = sinsp_numparser::parseu64(numstr); - } - else - { + } else { m_argid = sinsp_numparser::parsed32(numstr); } parsed_len++; - } - else if(val.size() > fldname.size() && val.at(fldname.size()) == '.') - { - if(m_field_id == TYPE_AROUND) - { + } else if(val.size() > fldname.size() && val.at(fldname.size()) == '.') { + if(m_field_id == TYPE_AROUND) { throw sinsp_exception("wrong syntax for evt.around"); } const ppm_param_info* pi = - sinsp_utils::find_longest_matching_evt_param(val.substr(fldname.size() + 1)); + sinsp_utils::find_longest_matching_evt_param(val.substr(fldname.size() + 1)); - if(pi == NULL) - { - throw sinsp_exception("unknown event argument " + string(val.substr(fldname.size() + 1))); + if(pi == NULL) { + throw sinsp_exception("unknown event argument " + + string(val.substr(fldname.size() + 1))); } m_argname = pi->name; parsed_len = (uint32_t)(fldname.size() + strlen(pi->name) + 1); m_argid = -1; - if(parinfo != NULL) - { + if(parinfo != NULL) { *parinfo = pi; } - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } return parsed_len; } -int32_t sinsp_filter_check_event::extract_type(string_view fldname, string_view val, const ppm_param_info** parinfo) -{ +int32_t sinsp_filter_check_event::extract_type(string_view fldname, + string_view val, + const ppm_param_info** parinfo) { uint32_t parsed_len = 0; - if(val.size() > fldname.size() && val.at(fldname.size()) == '.') - { + if(val.size() > fldname.size() && val.at(fldname.size()) == '.') { string itype(val.substr(fldname.size() + 1)); - if(sinsp_numparser::tryparseu32(itype, &m_evtid)) - { + if(sinsp_numparser::tryparseu32(itype, &m_evtid)) { m_evtid1 = PPM_EVENT_MAX; parsed_len = (uint32_t)(fldname.size() + itype.size() + 1); return parsed_len; } - for(uint32_t j = 0; j < PPM_EVENT_MAX; j++) - { + for(uint32_t j = 0; j < PPM_EVENT_MAX; j++) { const ppm_event_info* ei = &g_infotables.m_event_info[j]; - if(itype == ei->name) - { + if(itype == ei->name) { m_evtid = j; m_evtid1 = j + 1; parsed_len = (uint32_t)(fldname.size() + strlen(ei->name) + 1); break; } } - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } return parsed_len; } -int32_t sinsp_filter_check_event::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ +int32_t sinsp_filter_check_event::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { int32_t res = 0; // // A couple of fields are handled in a custom way // - if(STR_MATCH("evt.arg") && !STR_MATCH("evt.args")) - { + if(STR_MATCH("evt.arg") && !STR_MATCH("evt.args")) { m_field_id = TYPE_ARGSTR; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evt.arg", val, NULL); - } - else if(STR_MATCH("evt.rawarg")) - { + } else if(STR_MATCH("evt.rawarg")) { m_field_id = TYPE_ARGRAW; m_customfield = m_info->m_fields[m_field_id]; m_field = &m_customfield; @@ -264,68 +557,54 @@ int32_t sinsp_filter_check_event::parse_field_name(std::string_view val, bool al m_customfield.m_type = m_arginfo->type; m_customfield.m_print_format = m_arginfo->fmt; - } - else if(STR_MATCH("evt.around")) - { + } else if(STR_MATCH("evt.around")) { m_field_id = TYPE_AROUND; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evt.around", val, NULL); - } - else if(STR_MATCH("evt.latency") || - STR_MATCH("evt.latency.s") || - STR_MATCH("evt.latency.ns") || - STR_MATCH("evt.latency.quantized") || - STR_MATCH("evt.latency.human")) - { + } else if(STR_MATCH("evt.latency") || STR_MATCH("evt.latency.s") || + STR_MATCH("evt.latency.ns") || STR_MATCH("evt.latency.quantized") || + STR_MATCH("evt.latency.human")) { res = sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); - } - else if(STR_MATCH("evt.abspath")) - { + } else if(STR_MATCH("evt.abspath")) { m_field_id = TYPE_ABSPATH; m_field = &m_info->m_fields[m_field_id]; - if(STR_MATCH("evt.abspath.src")) - { + if(STR_MATCH("evt.abspath.src")) { m_argid = 1; res = sizeof("evt.abspath.src") - 1; - } - else if(STR_MATCH("evt.abspath.dst")) - { + } else if(STR_MATCH("evt.abspath.dst")) { m_argid = 2; res = sizeof("evt.abspath.dst") - 1; - } - else - { + } else { m_argid = 0; res = sizeof("evt.abspath") - 1; } - } - else if(STR_MATCH("evt.type.is")) - { + } else if(STR_MATCH("evt.type.is")) { m_field_id = TYPE_TYPE_IS; m_field = &m_info->m_fields[m_field_id]; res = extract_type("evt.type.is", val, NULL); - } - else - { + } else { res = sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } return res; } -size_t sinsp_filter_check_event::parse_filter_value(const char* str, uint32_t len, uint8_t *storage, uint32_t storage_len) -{ +size_t sinsp_filter_check_event::parse_filter_value(const char* str, + uint32_t len, + uint8_t* storage, + uint32_t storage_len) { size_t parsed_len; - if(m_field_id == sinsp_filter_check_event::TYPE_ARGRAW) - { + if(m_field_id == sinsp_filter_check_event::TYPE_ARGRAW) { ASSERT(m_arginfo != NULL); - parsed_len = sinsp_filter_value_parser::string_to_rawval(str, len, storage, storage_len, m_arginfo->type); - } - else - { + parsed_len = sinsp_filter_value_parser::string_to_rawval(str, + len, + storage, + storage_len, + m_arginfo->type); + } else { parsed_len = sinsp_filter_check::parse_filter_value(str, len, storage, storage_len); } @@ -334,28 +613,20 @@ size_t sinsp_filter_check_event::parse_filter_value(const char* str, uint32_t le return parsed_len; } - - -void sinsp_filter_check_event::validate_filter_value(const char* str, uint32_t len) -{ - if(m_field_id == TYPE_TYPE) - { +void sinsp_filter_check_event::validate_filter_value(const char* str, uint32_t len) { + if(m_field_id == TYPE_TYPE) { sinsp_evttables* einfo = m_inspector->get_event_info_tables(); const ppm_event_info* etable = einfo->m_event_info; string stype(str, len); - for(uint32_t j = 0; j < PPM_EVENT_MAX; j++) - { - if(stype == etable[j].name) - { + for(uint32_t j = 0; j < PPM_EVENT_MAX; j++) { + if(stype == etable[j].name) { return; } } - for(uint16_t j = 0; j < PPM_SC_MAX; j++) - { - if(stype == scap_get_ppm_sc_name((ppm_sc_code)j)) - { + for(uint16_t j = 0; j < PPM_SC_MAX; j++) { + if(stype == scap_get_ppm_sc_name((ppm_sc_code)j)) { return; } } @@ -364,24 +635,18 @@ void sinsp_filter_check_event::validate_filter_value(const char* str, uint32_t l // name, which will be extracted as valid values for evt.type // we loop over all plugins and check if at least one defines a // meta-event with the given name - for (auto& p : m_inspector->get_plugin_manager()->plugins()) - { - if (p->caps() & CAP_ASYNC) - { + for(auto& p : m_inspector->get_plugin_manager()->plugins()) { + if(p->caps() & CAP_ASYNC) { const auto& names = p->async_event_names(); - if (names.find(stype) != names.end()) - { + if(names.find(stype) != names.end()) { return; } } } throw sinsp_exception("unknown event type " + stype); - } - else if(m_field_id == TYPE_AROUND) - { - if(m_cmpop != CO_EQ) - { + } else if(m_field_id == TYPE_AROUND) { + if(m_cmpop != CO_EQ) { throw sinsp_exception("evt.around supports only '=' comparison operator"); } @@ -391,58 +656,43 @@ void sinsp_filter_check_event::validate_filter_value(const char* str, uint32_t l } } -uint8_t* extract_argraw(sinsp_evt *evt, uint32_t* len, const char *argname) -{ +uint8_t* extract_argraw(sinsp_evt* evt, uint32_t* len, const char* argname) { const sinsp_evt_param* pi = evt->get_param_by_name(argname); - if(pi != NULL) - { + if(pi != NULL) { *len = pi->m_len; return (uint8_t*)pi->m_val; - } - else - { + } else { return NULL; } } -uint8_t *sinsp_filter_check_event::extract_abspath(sinsp_evt *evt, uint32_t *len) -{ +uint8_t* sinsp_filter_check_event::extract_abspath(sinsp_evt* evt, uint32_t* len) { std::string spath; - if(evt->get_tinfo() == NULL) - { + if(evt->get_tinfo() == NULL) { return NULL; } uint16_t etype = evt->get_type(); const char *dirfdarg = NULL, *patharg = NULL; - if(etype == PPME_SYSCALL_RENAMEAT_X || etype == PPME_SYSCALL_RENAMEAT2_X) - { - if(m_argid == 0 || m_argid == 1) - { + if(etype == PPME_SYSCALL_RENAMEAT_X || etype == PPME_SYSCALL_RENAMEAT2_X) { + if(m_argid == 0 || m_argid == 1) { dirfdarg = "olddirfd"; patharg = "oldpath"; - } - else if(m_argid == 2) - { + } else if(m_argid == 2) { dirfdarg = "newdirfd"; patharg = "newpath"; } - } - else if(etype == PPME_SYSCALL_SYMLINKAT_X) - { + } else if(etype == PPME_SYSCALL_SYMLINKAT_X) { dirfdarg = "linkdirfd"; patharg = "linkpath"; - } - else if(etype == PPME_SYSCALL_OPENAT_E || etype == PPME_SYSCALL_OPENAT_2_X || etype == PPME_SYSCALL_OPENAT2_X) - { + } else if(etype == PPME_SYSCALL_OPENAT_E || etype == PPME_SYSCALL_OPENAT_2_X || + etype == PPME_SYSCALL_OPENAT2_X) { dirfdarg = "dirfd"; patharg = "name"; - } - else if(etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) - { + } else if(etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) { int fd = 0; std::string fullname; @@ -451,8 +701,7 @@ uint8_t *sinsp_filter_check_event::extract_abspath(sinsp_evt *evt, uint32_t *len // fd = evt->get_param(0)->as(); - if(fd>0) - { + if(fd > 0) { // // Get the file path directly from the ring buffer. // concatenate_paths takes care of resolving the path @@ -461,63 +710,45 @@ uint8_t *sinsp_filter_check_event::extract_abspath(sinsp_evt *evt, uint32_t *len RETURN_EXTRACT_STRING(m_strstorage); } - } - else if(etype == PPME_SYSCALL_LINKAT_E || etype == PPME_SYSCALL_LINKAT_2_X) - { - if(m_argid == 0 || m_argid == 1) - { + } else if(etype == PPME_SYSCALL_LINKAT_E || etype == PPME_SYSCALL_LINKAT_2_X) { + if(m_argid == 0 || m_argid == 1) { dirfdarg = "olddir"; patharg = "oldpath"; - } - else if(m_argid == 2) - { + } else if(m_argid == 2) { dirfdarg = "newdir"; patharg = "newpath"; } - } - else if(etype == PPME_SYSCALL_UNLINKAT_E || etype == PPME_SYSCALL_UNLINKAT_2_X) - { + } else if(etype == PPME_SYSCALL_UNLINKAT_E || etype == PPME_SYSCALL_UNLINKAT_2_X) { dirfdarg = "dirfd"; patharg = "name"; - } - else if(etype == PPME_SYSCALL_MKDIRAT_X) - { + } else if(etype == PPME_SYSCALL_MKDIRAT_X) { dirfdarg = "dirfd"; patharg = "path"; - } - else if(etype == PPME_SYSCALL_FCHMODAT_X) - { + } else if(etype == PPME_SYSCALL_FCHMODAT_X) { dirfdarg = "dirfd"; patharg = "filename"; - } - else if(etype == PPME_SYSCALL_FCHOWNAT_X) - { + } else if(etype == PPME_SYSCALL_FCHOWNAT_X) { dirfdarg = "dirfd"; patharg = "pathname"; } - if(!dirfdarg || !patharg) - { + if(!dirfdarg || !patharg) { return 0; } int dirfdargidx = -1, pathargidx = -1, idx = 0; - while (((dirfdargidx < 0) || (pathargidx < 0)) && (idx < (int) evt->get_num_params())) - { - const char *name = evt->get_param_name(idx); - if((dirfdargidx < 0) && (strcmp(name, dirfdarg) == 0)) - { + while(((dirfdargidx < 0) || (pathargidx < 0)) && (idx < (int)evt->get_num_params())) { + const char* name = evt->get_param_name(idx); + if((dirfdargidx < 0) && (strcmp(name, dirfdarg) == 0)) { dirfdargidx = idx; } - if((pathargidx < 0) && (strcmp(name, patharg) == 0)) - { + if((pathargidx < 0) && (strcmp(name, patharg) == 0)) { pathargidx = idx; } idx++; } - if((dirfdargidx < 0) || (pathargidx < 0)) - { + if((dirfdargidx < 0) || (pathargidx < 0)) { return 0; } @@ -528,36 +759,25 @@ uint8_t *sinsp_filter_check_event::extract_abspath(sinsp_evt *evt, uint32_t *len string sdir; bool is_absolute = (path[0] == '/'); - if(is_absolute) - { + if(is_absolute) { // // The path is absolute. // Some processes (e.g. irqbalance) actually do this: they pass an invalid fd and // and absolute path, and openat succeeds. // sdir = "."; - } - else if(dirfd == PPM_AT_FDCWD) - { + } else if(dirfd == PPM_AT_FDCWD) { sdir = evt->get_tinfo()->get_cwd(); - } - else - { + } else { evt->set_fd_info(evt->get_tinfo()->get_fd(dirfd)); - if(evt->get_fd_info() == NULL) - { + if(evt->get_fd_info() == NULL) { ASSERT(false); sdir = "/"; - } - else - { - if(evt->get_fd_info()->m_name[evt->get_fd_info()->m_name.length()] == '/') - { + } else { + if(evt->get_fd_info()->m_name[evt->get_fd_info()->m_name.length()] == '/') { sdir = evt->get_fd_info()->m_name; - } - else - { + } else { sdir = evt->get_fd_info()->m_name + '/'; } } @@ -568,17 +788,14 @@ uint8_t *sinsp_filter_check_event::extract_abspath(sinsp_evt *evt, uint32_t *len RETURN_EXTRACT_STRING(m_strstorage); } -inline uint8_t* sinsp_filter_check_event::extract_buflen(sinsp_evt *evt, uint32_t* len) -{ - if(evt->get_direction() == SCAP_ED_OUT) - { +inline uint8_t* sinsp_filter_check_event::extract_buflen(sinsp_evt* evt, uint32_t* len) { + if(evt->get_direction() == SCAP_ED_OUT) { // // Extract the return value // m_val.s64 = evt->get_param(0)->as(); - if(m_val.s64 >= 0) - { + if(m_val.s64 >= 0) { RETURN_EXTRACT_VAR(m_val.s64); } } @@ -586,10 +803,8 @@ inline uint8_t* sinsp_filter_check_event::extract_buflen(sinsp_evt *evt, uint32_ return NULL; } -Json::Value sinsp_filter_check_event::extract_as_js(sinsp_evt *evt, uint32_t* len) -{ - switch(m_field_id) - { +Json::Value sinsp_filter_check_event::extract_as_js(sinsp_evt* evt, uint32_t* len) { + switch(m_field_id) { case TYPE_RUNTIME_TIME_OUTPUT_FORMAT: return (Json::Value::Int64)evt->get_ts(); @@ -599,7 +814,7 @@ Json::Value sinsp_filter_check_event::extract_as_js(sinsp_evt *evt, uint32_t* le case TYPE_DELTA: case TYPE_DELTA_S: case TYPE_DELTA_NS: - return (Json::Value::Int64)*(uint64_t*)extract_single(evt, len); + return (Json::Value::Int64) * (uint64_t*)extract_single(evt, len); case TYPE_COUNT: m_val.u32 = 1; return m_val.u32; @@ -611,33 +826,25 @@ Json::Value sinsp_filter_check_event::extract_as_js(sinsp_evt *evt, uint32_t* le return Json::nullValue; } -uint8_t* sinsp_filter_check_event::extract_error_count(sinsp_evt *evt, uint32_t* len) -{ +uint8_t* sinsp_filter_check_event::extract_error_count(sinsp_evt* evt, uint32_t* len) { const sinsp_evt_param* pi = evt->get_param_by_name("res"); - if(pi != NULL) - { + if(pi != NULL) { int64_t res = pi->as(); - if(res < 0) - { + if(res < 0) { m_val.u32 = 1; RETURN_EXTRACT_VAR(m_val.u32); - } - else - { + } else { return NULL; } } - if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) - { + if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) { pi = evt->get_param_by_name("fd"); - if(pi != NULL) - { + if(pi != NULL) { int64_t res = pi->as(); - if(res < 0) - { + if(res < 0) { m_val.u32 = 1; RETURN_EXTRACT_VAR(m_val.u32); } @@ -647,304 +854,256 @@ uint8_t* sinsp_filter_check_event::extract_error_count(sinsp_evt *evt, uint32_t* return NULL; } -uint8_t* sinsp_filter_check_event::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_event::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; - switch(m_field_id) - { - case TYPE_LATENCY: - { - m_val.u64 = 0; - - if(evt->get_tinfo() != NULL) - { - ppm_event_category ecat = evt->get_category(); - if(ecat & EC_INTERNAL) - { - return NULL; - } + switch(m_field_id) { + case TYPE_LATENCY: { + m_val.u64 = 0; - m_val.u64 = evt->get_tinfo()->m_latency; + if(evt->get_tinfo() != NULL) { + ppm_event_category ecat = evt->get_category(); + if(ecat & EC_INTERNAL) { + return NULL; } - RETURN_EXTRACT_VAR(m_val.u64); + m_val.u64 = evt->get_tinfo()->m_latency; } - case TYPE_LATENCY_HUMAN: - { - m_val.u64 = 0; - if(evt->get_tinfo() != NULL) - { - ppm_event_category ecat = evt->get_category(); - if(ecat & EC_INTERNAL) - { - return NULL; - } - - m_converter->set_val(PT_RELTIME, - EPF_NONE, - (uint8_t*)&evt->get_tinfo()->m_latency, - 8, - 0, - ppm_print_format::PF_DEC); + RETURN_EXTRACT_VAR(m_val.u64); + } + case TYPE_LATENCY_HUMAN: { + m_val.u64 = 0; - m_strstorage = m_converter->tostring_nice(NULL, 0, 1000000000); + if(evt->get_tinfo() != NULL) { + ppm_event_category ecat = evt->get_category(); + if(ecat & EC_INTERNAL) { + return NULL; } - RETURN_EXTRACT_STRING(m_strstorage); + m_converter->set_val(PT_RELTIME, + EPF_NONE, + (uint8_t*)&evt->get_tinfo()->m_latency, + 8, + 0, + ppm_print_format::PF_DEC); + + m_strstorage = m_converter->tostring_nice(NULL, 0, 1000000000); } - case TYPE_LATENCY_S: - case TYPE_LATENCY_NS: - { - m_val.u64 = 0; - - if(evt->get_tinfo() != NULL) - { - ppm_event_category ecat = evt->get_category(); - if(ecat & EC_INTERNAL) - { - return NULL; - } - uint64_t lat = evt->get_tinfo()->m_latency; + RETURN_EXTRACT_STRING(m_strstorage); + } + case TYPE_LATENCY_S: + case TYPE_LATENCY_NS: { + m_val.u64 = 0; - if(m_field_id == TYPE_LATENCY_S) - { - m_val.u64 = lat / 1000000000; - } - else - { - m_val.u64 = lat % 1000000000; - } + if(evt->get_tinfo() != NULL) { + ppm_event_category ecat = evt->get_category(); + if(ecat & EC_INTERNAL) { + return NULL; } - RETURN_EXTRACT_VAR(m_val.u64); - } - case TYPE_LATENCY_QUANTIZED: - { - if(evt->get_tinfo() != NULL) - { - ppm_event_category ecat = evt->get_category(); - if(ecat & EC_INTERNAL) - { - return NULL; - } + uint64_t lat = evt->get_tinfo()->m_latency; - uint64_t lat = evt->get_tinfo()->m_latency; - if(lat != 0) - { - double llatency = log10((double)lat); + if(m_field_id == TYPE_LATENCY_S) { + m_val.u64 = lat / 1000000000; + } else { + m_val.u64 = lat % 1000000000; + } + } - if(llatency > 11) - { - llatency = 11; - } + RETURN_EXTRACT_VAR(m_val.u64); + } + case TYPE_LATENCY_QUANTIZED: { + if(evt->get_tinfo() != NULL) { + ppm_event_category ecat = evt->get_category(); + if(ecat & EC_INTERNAL) { + return NULL; + } - m_val.u64 = (uint64_t)(llatency * m_inspector->get_quantization_interval() / 11) + 1; + uint64_t lat = evt->get_tinfo()->m_latency; + if(lat != 0) { + double llatency = log10((double)lat); - RETURN_EXTRACT_VAR(m_val.u64); + if(llatency > 11) { + llatency = 11; } - } - return NULL; + m_val.u64 = + (uint64_t)(llatency * m_inspector->get_quantization_interval() / 11) + 1; + + RETURN_EXTRACT_VAR(m_val.u64); + } } + + return NULL; + } case TYPE_DELTA: case TYPE_DELTA_S: - case TYPE_DELTA_NS: - { - if(m_val.u64 == 0) - { - m_val.u64 = evt->get_ts(); - m_tsdelta = 0; - } - else - { - uint64_t tts = evt->get_ts(); + case TYPE_DELTA_NS: { + if(m_val.u64 == 0) { + m_val.u64 = evt->get_ts(); + m_tsdelta = 0; + } else { + uint64_t tts = evt->get_ts(); - if(m_field_id == TYPE_DELTA) - { - m_tsdelta = tts - m_val.u64; - } - else if(m_field_id == TYPE_DELTA_S) - { - m_tsdelta = (tts - m_val.u64) / ONE_SECOND_IN_NS; - } - else if(m_field_id == TYPE_DELTA_NS) - { - m_tsdelta = (tts - m_val.u64) % ONE_SECOND_IN_NS; - } - - m_val.u64 = tts; + if(m_field_id == TYPE_DELTA) { + m_tsdelta = tts - m_val.u64; + } else if(m_field_id == TYPE_DELTA_S) { + m_tsdelta = (tts - m_val.u64) / ONE_SECOND_IN_NS; + } else if(m_field_id == TYPE_DELTA_NS) { + m_tsdelta = (tts - m_val.u64) % ONE_SECOND_IN_NS; } - RETURN_EXTRACT_VAR(m_tsdelta); + m_val.u64 = tts; } - case TYPE_RUNTIME_TIME_OUTPUT_FORMAT: - { - char timebuffer[100]; - m_strstorage = ""; - switch(m_inspector->get_time_output_mode()) - { - case 'h': - sinsp_utils::ts_to_string(evt->get_ts(), &m_strstorage, false, true); - RETURN_EXTRACT_STRING(m_strstorage); - - case 'a': - m_strstorage += to_string(evt->get_ts() / ONE_SECOND_IN_NS); - m_strstorage += "."; - m_strstorage += to_string(evt->get_ts() % ONE_SECOND_IN_NS); - RETURN_EXTRACT_STRING(m_strstorage); - - case 'r': - m_strstorage += to_string((evt->get_ts() - m_inspector->m_firstevent_ts) / ONE_SECOND_IN_NS); - m_strstorage += "."; - snprintf(timebuffer, sizeof(timebuffer), "%09llu", (evt->get_ts() - m_inspector->m_firstevent_ts) % ONE_SECOND_IN_NS); - m_strstorage += string(timebuffer); - RETURN_EXTRACT_STRING(m_strstorage); - - case 'd': - { - if(evt->get_tinfo() != NULL) - { - long long unsigned lat = evt->get_tinfo()->m_latency; - - m_strstorage += to_string(lat / 1000000000); - m_strstorage += "."; - snprintf(timebuffer, sizeof(timebuffer), "%09llu", lat % 1000000000); - m_strstorage += string(timebuffer); - } - else - { - m_strstorage = "0.000000000"; - } - RETURN_EXTRACT_STRING(m_strstorage); - } + RETURN_EXTRACT_VAR(m_tsdelta); + } + case TYPE_RUNTIME_TIME_OUTPUT_FORMAT: { + char timebuffer[100]; + m_strstorage = ""; + switch(m_inspector->get_time_output_mode()) { + case 'h': + sinsp_utils::ts_to_string(evt->get_ts(), &m_strstorage, false, true); + RETURN_EXTRACT_STRING(m_strstorage); - case 'D': - if(m_val.u64 == 0) - { - m_val.u64 = evt->get_ts(); - m_tsdelta = 0; - } - uint64_t tts = evt->get_ts(); + case 'a': + m_strstorage += to_string(evt->get_ts() / ONE_SECOND_IN_NS); + m_strstorage += "."; + m_strstorage += to_string(evt->get_ts() % ONE_SECOND_IN_NS); + RETURN_EXTRACT_STRING(m_strstorage); + + case 'r': + m_strstorage += + to_string((evt->get_ts() - m_inspector->m_firstevent_ts) / ONE_SECOND_IN_NS); + m_strstorage += "."; + snprintf(timebuffer, + sizeof(timebuffer), + "%09llu", + (evt->get_ts() - m_inspector->m_firstevent_ts) % ONE_SECOND_IN_NS); + m_strstorage += string(timebuffer); + RETURN_EXTRACT_STRING(m_strstorage); - m_strstorage += to_string((tts - m_val.u64) / ONE_SECOND_IN_NS); - m_tsdelta = (tts - m_val.u64) / ONE_SECOND_IN_NS; - m_strstorage += "."; - snprintf(timebuffer, sizeof(timebuffer), "%09llu", (tts - m_val.u64) % ONE_SECOND_IN_NS); - m_strstorage += string(timebuffer); - m_tsdelta = (tts - m_val.u64) % ONE_SECOND_IN_NS; + case 'd': { + if(evt->get_tinfo() != NULL) { + long long unsigned lat = evt->get_tinfo()->m_latency; - m_val.u64 = tts; - RETURN_EXTRACT_STRING(m_strstorage); + m_strstorage += to_string(lat / 1000000000); + m_strstorage += "."; + snprintf(timebuffer, sizeof(timebuffer), "%09llu", lat % 1000000000); + m_strstorage += string(timebuffer); + } else { + m_strstorage = "0.000000000"; } + + RETURN_EXTRACT_STRING(m_strstorage); } + + case 'D': + if(m_val.u64 == 0) { + m_val.u64 = evt->get_ts(); + m_tsdelta = 0; + } + uint64_t tts = evt->get_ts(); + + m_strstorage += to_string((tts - m_val.u64) / ONE_SECOND_IN_NS); + m_tsdelta = (tts - m_val.u64) / ONE_SECOND_IN_NS; + m_strstorage += "."; + snprintf(timebuffer, + sizeof(timebuffer), + "%09llu", + (tts - m_val.u64) % ONE_SECOND_IN_NS); + m_strstorage += string(timebuffer); + m_tsdelta = (tts - m_val.u64) % ONE_SECOND_IN_NS; + + m_val.u64 = tts; + RETURN_EXTRACT_STRING(m_strstorage); + } + } case TYPE_DIR: - if(PPME_IS_ENTER(evt->get_type())) - { + if(PPME_IS_ENTER(evt->get_type())) { RETURN_EXTRACT_CSTR(">"); - } - else - { + } else { RETURN_EXTRACT_CSTR("<"); } - case TYPE_TYPE: - { - uint8_t* evname; - uint16_t etype = evt->get_scap_evt()->type; - - if(etype == PPME_GENERIC_E || etype == PPME_GENERIC_X) - { - uint16_t ppm_sc = evt->get_param(0)->as(); - - // Only generic enter event has the nativeID as second param - if(m_inspector && m_inspector->is_capture() && ppm_sc == PPM_SC_UNKNOWN && etype == PPME_GENERIC_E) - { - // try to enforce a forward compatibility for syscalls added - // after a scap file was generated, - // by looking up using nativeID. - // Of course, this will only reliably work for - // same architecture scap capture->replay. - uint16_t nativeid = evt->get_param(1)->as(); - ppm_sc = scap_native_id_to_ppm_sc(nativeid); - } - evname = (uint8_t*)scap_get_ppm_sc_name((ppm_sc_code)ppm_sc); - } - else - { - // note: for async events, the event name is encoded - // inside the event itself. In this case libsinsp's evt.type - // field acts as an alias of evt.asynctype. - if (etype == PPME_ASYNCEVENT_E) - { - evname = (uint8_t*) evt->get_param(1)->m_val; - } - else - { - evname = (uint8_t*)evt->get_name(); - } + case TYPE_TYPE: { + uint8_t* evname; + uint16_t etype = evt->get_scap_evt()->type; + + if(etype == PPME_GENERIC_E || etype == PPME_GENERIC_X) { + uint16_t ppm_sc = evt->get_param(0)->as(); + + // Only generic enter event has the nativeID as second param + if(m_inspector && m_inspector->is_capture() && ppm_sc == PPM_SC_UNKNOWN && + etype == PPME_GENERIC_E) { + // try to enforce a forward compatibility for syscalls added + // after a scap file was generated, + // by looking up using nativeID. + // Of course, this will only reliably work for + // same architecture scap capture->replay. + uint16_t nativeid = evt->get_param(1)->as(); + ppm_sc = scap_native_id_to_ppm_sc(nativeid); + } + evname = (uint8_t*)scap_get_ppm_sc_name((ppm_sc_code)ppm_sc); + } else { + // note: for async events, the event name is encoded + // inside the event itself. In this case libsinsp's evt.type + // field acts as an alias of evt.asynctype. + if(etype == PPME_ASYNCEVENT_E) { + evname = (uint8_t*)evt->get_param(1)->m_val; + } else { + evname = (uint8_t*)evt->get_name(); } - - RETURN_EXTRACT_CSTR(evname); } - break; - case TYPE_TYPE_IS: - { - uint16_t etype = evt->get_scap_evt()->type; - if(etype == m_evtid || etype == m_evtid1) - { - m_val.u32 = 1; - } - else - { - m_val.u32 = 0; - } + RETURN_EXTRACT_CSTR(evname); + } break; + case TYPE_TYPE_IS: { + uint16_t etype = evt->get_scap_evt()->type; - RETURN_EXTRACT_VAR(m_val.u32); + if(etype == m_evtid || etype == m_evtid1) { + m_val.u32 = 1; + } else { + m_val.u32 = 0; } - break; - case TYPE_SYSCALL_TYPE: - { - uint8_t* evname; - ppm_event_code etype = (ppm_event_code)evt->get_scap_evt()->type; - if(!libsinsp::events::is_syscall_event(etype)) - { - return NULL; - } - if(etype == PPME_GENERIC_E || etype == PPME_GENERIC_X) - { - uint16_t ppm_sc = evt->get_param(0)->as(); - - // Only generic enter event has the nativeID as second param - if (m_inspector && m_inspector->is_capture() && ppm_sc == PPM_SC_UNKNOWN && etype == PPME_GENERIC_E) - { - // try to enforce a forward compatibility for syscalls added - // after a scap file was generated, - // by looking up using nativeID. - // Of course, this will only reliably work for - // same architecture scap capture->replay. - uint16_t nativeid = evt->get_param(1)->as(); - ppm_sc = scap_native_id_to_ppm_sc(nativeid); - } - evname = (uint8_t*)scap_get_ppm_sc_name((ppm_sc_code)ppm_sc); - } - else - { - evname = (uint8_t*)evt->get_name(); - } + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_SYSCALL_TYPE: { + uint8_t* evname; + ppm_event_code etype = (ppm_event_code)evt->get_scap_evt()->type; + if(!libsinsp::events::is_syscall_event(etype)) { + return NULL; + } + + if(etype == PPME_GENERIC_E || etype == PPME_GENERIC_X) { + uint16_t ppm_sc = evt->get_param(0)->as(); - RETURN_EXTRACT_CSTR(evname); + // Only generic enter event has the nativeID as second param + if(m_inspector && m_inspector->is_capture() && ppm_sc == PPM_SC_UNKNOWN && + etype == PPME_GENERIC_E) { + // try to enforce a forward compatibility for syscalls added + // after a scap file was generated, + // by looking up using nativeID. + // Of course, this will only reliably work for + // same architecture scap capture->replay. + uint16_t nativeid = evt->get_param(1)->as(); + ppm_sc = scap_native_id_to_ppm_sc(nativeid); + } + evname = (uint8_t*)scap_get_ppm_sc_name((ppm_sc_code)ppm_sc); + } else { + evname = (uint8_t*)evt->get_name(); } - break; + + RETURN_EXTRACT_CSTR(evname); + } break; case TYPE_CATEGORY: sinsp_evt::category cat; evt->get_category(&cat); - switch(cat.m_category) - { + switch(cat.m_category) { case EC_UNKNOWN: m_strstorage = "unknown"; break; @@ -986,10 +1145,8 @@ uint8_t* sinsp_filter_check_event::extract_single(sinsp_evt *evt, uint32_t* len, break; case EC_IO_READ: case EC_IO_WRITE: - case EC_IO_OTHER: - { - switch(cat.m_subcategory) - { + case EC_IO_OTHER: { + switch(cat.m_subcategory) { case sinsp_evt::SC_FILE: m_strstorage = "file"; break; @@ -1009,8 +1166,7 @@ uint8_t* sinsp_filter_check_event::extract_single(sinsp_evt *evt, uint32_t* len, m_strstorage = "unknown"; break; } - } - break; + } break; case EC_WAIT: m_strstorage = "wait"; break; @@ -1044,580 +1200,440 @@ uint8_t* sinsp_filter_check_event::extract_single(sinsp_evt *evt, uint32_t* len, case TYPE_ARGRAW: return extract_argraw(evt, len, m_arginfo->name); break; - case TYPE_ARGSTR: - { - const char* resolved_argstr; - const char* argstr; + case TYPE_ARGSTR: { + const char* resolved_argstr; + const char* argstr; - ASSERT(m_inspector != NULL); - - if(m_argid != -1) - { - if(m_argid >= (int32_t)evt->get_num_params()) - { - return NULL; - } + ASSERT(m_inspector != NULL); - argstr = evt->get_param_as_str(m_argid, &resolved_argstr, m_inspector->get_buffer_format()); - } - else - { - argstr = evt->get_param_value_str(m_argname, &resolved_argstr, m_inspector->get_buffer_format()); + if(m_argid != -1) { + if(m_argid >= (int32_t)evt->get_num_params()) { + return NULL; } - if(resolved_argstr != NULL && resolved_argstr[0] != 0) - { - RETURN_EXTRACT_CSTR(resolved_argstr); - } - else - { - RETURN_EXTRACT_CSTR(argstr); - } + argstr = evt->get_param_as_str(m_argid, + &resolved_argstr, + m_inspector->get_buffer_format()); + } else { + argstr = evt->get_param_value_str(m_argname, + &resolved_argstr, + m_inspector->get_buffer_format()); } - break; - case TYPE_INFO: - { - if(m_inspector->get_parser()->get_syslog_decoder().is_data_valid()) - { - // syslog is actually the only info line we support up until now - m_strstorage = m_inspector->get_parser()->get_syslog_decoder().get_info_line(); - RETURN_EXTRACT_STRING(m_strstorage); - } + + if(resolved_argstr != NULL && resolved_argstr[0] != 0) { + RETURN_EXTRACT_CSTR(resolved_argstr); + } else { + RETURN_EXTRACT_CSTR(argstr); } + } break; + case TYPE_INFO: { + if(m_inspector->get_parser()->get_syslog_decoder().is_data_valid()) { + // syslog is actually the only info line we support up until now + m_strstorage = m_inspector->get_parser()->get_syslog_decoder().get_info_line(); + RETURN_EXTRACT_STRING(m_strstorage); + } + } // // NOTE: this falls through to TYPE_ARGSTR, and that's what we want! // Please don't add anything here! // - case TYPE_ARGS: - { - if(evt->get_type() == PPME_GENERIC_E || evt->get_type() == PPME_GENERIC_X) - { - // - // Don't print the arguments for generic events: they have only internal use - // - RETURN_EXTRACT_CSTR(""); - } + case TYPE_ARGS: { + if(evt->get_type() == PPME_GENERIC_E || evt->get_type() == PPME_GENERIC_X) { + // + // Don't print the arguments for generic events: they have only internal use + // + RETURN_EXTRACT_CSTR(""); + } - const char* resolved_argstr = NULL; - const char* argstr = NULL; - uint32_t nargs = evt->get_num_params(); - m_strstorage.clear(); + const char* resolved_argstr = NULL; + const char* argstr = NULL; + uint32_t nargs = evt->get_num_params(); + m_strstorage.clear(); - for(uint32_t j = 0; j < nargs; j++) - { - ASSERT(m_inspector != NULL); + for(uint32_t j = 0; j < nargs; j++) { + ASSERT(m_inspector != NULL); - argstr = evt->get_param_as_str(j, &resolved_argstr, m_inspector->get_buffer_format()); + argstr = evt->get_param_as_str(j, &resolved_argstr, m_inspector->get_buffer_format()); - if(resolved_argstr[0] == 0) - { - m_strstorage += evt->get_param_name(j); - m_strstorage += '='; - m_strstorage += argstr; - m_strstorage += " "; - } - else - { - m_strstorage += evt->get_param_name(j); - m_strstorage += '='; - m_strstorage += argstr; - m_strstorage += string("(") + resolved_argstr + ") "; - } + if(resolved_argstr[0] == 0) { + m_strstorage += evt->get_param_name(j); + m_strstorage += '='; + m_strstorage += argstr; + m_strstorage += " "; + } else { + m_strstorage += evt->get_param_name(j); + m_strstorage += '='; + m_strstorage += argstr; + m_strstorage += string("(") + resolved_argstr + ") "; } + } - if(!m_strstorage.empty()) - { - m_strstorage.pop_back(); - } - RETURN_EXTRACT_STRING(m_strstorage); + if(!m_strstorage.empty()) { + m_strstorage.pop_back(); + } + RETURN_EXTRACT_STRING(m_strstorage); + } break; + case TYPE_BUFFER: { + if(m_is_compare) { + return extract_argraw(evt, len, "data"); } - break; - case TYPE_BUFFER: - { - if(m_is_compare) - { - return extract_argraw(evt, len, "data"); - } - const char* resolved_argstr; - const char* argstr; - argstr = evt->get_param_value_str("data", &resolved_argstr, m_inspector->get_buffer_format()); - *len = evt->get_rawbuf_str_len(); + const char* resolved_argstr; + const char* argstr; + argstr = evt->get_param_value_str("data", + &resolved_argstr, + m_inspector->get_buffer_format()); + *len = evt->get_rawbuf_str_len(); - return (uint8_t*)argstr; - } + return (uint8_t*)argstr; + } case TYPE_BUFLEN: - if(evt->get_fd_info() && evt->get_category() & EC_IO_BASE) - { + if(evt->get_fd_info() && evt->get_category() & EC_IO_BASE) { return extract_buflen(evt, len); } break; - case TYPE_RESRAW: - { - const sinsp_evt_param* pi = evt->get_param_by_name("res"); + case TYPE_RESRAW: { + const sinsp_evt_param* pi = evt->get_param_by_name("res"); + + if(pi != NULL) { + *len = pi->m_len; + return (uint8_t*)pi->m_val; + } - if(pi != NULL) - { + if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) { + pi = evt->get_param_by_name("fd"); + + if(pi != NULL) { *len = pi->m_len; return (uint8_t*)pi->m_val; } + } - if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) - { - pi = evt->get_param_by_name("fd"); + return NULL; + } break; + case TYPE_RESSTR: { + const char* resolved_argstr; + const char* argstr; - if(pi != NULL) - { - *len = pi->m_len; - return (uint8_t*)pi->m_val; - } - } + const sinsp_evt_param* pi = evt->get_param_by_name("res"); - return NULL; - } - break; - case TYPE_RESSTR: - { - const char* resolved_argstr; - const char* argstr; - - const sinsp_evt_param* pi = evt->get_param_by_name("res"); + if(pi != NULL) { + int64_t res = pi->as(); - if(pi != NULL) - { - int64_t res = pi->as(); + if(res >= 0) { + RETURN_EXTRACT_CSTR("SUCCESS"); + } else { + argstr = evt->get_param_value_str("res", &resolved_argstr); + ASSERT(resolved_argstr != NULL && resolved_argstr[0] != 0); - if(res >= 0) - { - RETURN_EXTRACT_CSTR("SUCCESS"); - } - else - { - argstr = evt->get_param_value_str("res", &resolved_argstr); - ASSERT(resolved_argstr != NULL && resolved_argstr[0] != 0); - - if(resolved_argstr != NULL && resolved_argstr[0] != 0) - { - RETURN_EXTRACT_CSTR(resolved_argstr); - } - else if(argstr != NULL) - { - RETURN_EXTRACT_CSTR(argstr); - } + if(resolved_argstr != NULL && resolved_argstr[0] != 0) { + RETURN_EXTRACT_CSTR(resolved_argstr); + } else if(argstr != NULL) { + RETURN_EXTRACT_CSTR(argstr); } } - else - { - if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) - { - pi = evt->get_param_by_name("fd"); - if (pi) - { - int64_t res = pi->as(); - - if(res >= 0) - { - RETURN_EXTRACT_CSTR("SUCCESS"); - } - else - { - argstr = evt->get_param_value_str("fd", &resolved_argstr); - ASSERT(resolved_argstr != NULL && resolved_argstr[0] != 0); - - if(resolved_argstr != NULL && resolved_argstr[0] != 0) - { - RETURN_EXTRACT_CSTR(resolved_argstr); - } - else if(argstr != NULL) - { - RETURN_EXTRACT_CSTR(argstr); - } + } else { + if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) { + pi = evt->get_param_by_name("fd"); + if(pi) { + int64_t res = pi->as(); + + if(res >= 0) { + RETURN_EXTRACT_CSTR("SUCCESS"); + } else { + argstr = evt->get_param_value_str("fd", &resolved_argstr); + ASSERT(resolved_argstr != NULL && resolved_argstr[0] != 0); + + if(resolved_argstr != NULL && resolved_argstr[0] != 0) { + RETURN_EXTRACT_CSTR(resolved_argstr); + } else if(argstr != NULL) { + RETURN_EXTRACT_CSTR(argstr); } } } } - - return NULL; } - break; - case TYPE_FAILED: - { - m_val.u32 = 0; - const sinsp_evt_param* pi = evt->get_param_by_name("res"); - - if(pi != NULL) - { - if(pi->as() < 0) - { - m_val.u32 = 1; - } - } - else if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) - { - pi = evt->get_param_by_name("fd"); - if(pi != NULL) - { - if(pi->as() < 0) - { - m_val.u32 = 1; - } - } - } + return NULL; + } break; + case TYPE_FAILED: { + m_val.u32 = 0; + const sinsp_evt_param* pi = evt->get_param_by_name("res"); - RETURN_EXTRACT_VAR(m_val.u32); - } - break; - case TYPE_ISIO: - { - ppm_event_flags eflags = evt->get_info_flags(); - if(eflags & (EF_READS_FROM_FD | EF_WRITES_TO_FD)) - { + if(pi != NULL) { + if(pi->as() < 0) { m_val.u32 = 1; } - else - { - m_val.u32 = 0; + } else if((evt->get_info_flags() & EF_CREATES_FD) && PPME_IS_EXIT(evt->get_type())) { + pi = evt->get_param_by_name("fd"); + + if(pi != NULL) { + if(pi->as() < 0) { + m_val.u32 = 1; + } } } RETURN_EXTRACT_VAR(m_val.u32); - case TYPE_ISIO_READ: - { - ppm_event_flags eflags = evt->get_info_flags(); - if(eflags & EF_READS_FROM_FD) - { - m_val.u32 = 1; - } - else - { - m_val.u32 = 0; - } + } break; + case TYPE_ISIO: { + ppm_event_flags eflags = evt->get_info_flags(); + if(eflags & (EF_READS_FROM_FD | EF_WRITES_TO_FD)) { + m_val.u32 = 1; + } else { + m_val.u32 = 0; + } + } - RETURN_EXTRACT_VAR(m_val.u32); + RETURN_EXTRACT_VAR(m_val.u32); + case TYPE_ISIO_READ: { + ppm_event_flags eflags = evt->get_info_flags(); + if(eflags & EF_READS_FROM_FD) { + m_val.u32 = 1; + } else { + m_val.u32 = 0; } - case TYPE_ISIO_WRITE: - { - ppm_event_flags eflags = evt->get_info_flags(); - if(eflags & EF_WRITES_TO_FD) - { - m_val.u32 = 1; - } - else - { - m_val.u32 = 0; - } - RETURN_EXTRACT_VAR(m_val.u32); + RETURN_EXTRACT_VAR(m_val.u32); + } + case TYPE_ISIO_WRITE: { + ppm_event_flags eflags = evt->get_info_flags(); + if(eflags & EF_WRITES_TO_FD) { + m_val.u32 = 1; + } else { + m_val.u32 = 0; } - case TYPE_IODIR: - { - ppm_event_flags eflags = evt->get_info_flags(); - if(eflags & EF_WRITES_TO_FD) - { - m_strstorage = "write"; - } - else if(eflags & EF_READS_FROM_FD) - { - m_strstorage = "read"; - } - else - { - return NULL; - } - RETURN_EXTRACT_STRING(m_strstorage); + RETURN_EXTRACT_VAR(m_val.u32); + } + case TYPE_IODIR: { + ppm_event_flags eflags = evt->get_info_flags(); + if(eflags & EF_WRITES_TO_FD) { + m_strstorage = "write"; + } else if(eflags & EF_READS_FROM_FD) { + m_strstorage = "read"; + } else { + return NULL; } - case TYPE_ISWAIT: - { - ppm_event_flags eflags = evt->get_info_flags(); - if(eflags & (EF_WAITS)) - { - m_val.u32 = 1; - } - else - { - m_val.u32 = 0; - } + + RETURN_EXTRACT_STRING(m_strstorage); + } + case TYPE_ISWAIT: { + ppm_event_flags eflags = evt->get_info_flags(); + if(eflags & (EF_WAITS)) { + m_val.u32 = 1; + } else { + m_val.u32 = 0; } + } RETURN_EXTRACT_VAR(m_val.u32); - case TYPE_WAIT_LATENCY: - { - ppm_event_flags eflags = evt->get_info_flags(); - uint16_t etype = evt->get_scap_evt()->type; - - if(eflags & (EF_WAITS) && PPME_IS_EXIT(etype)) - { - if(evt->get_tinfo() != NULL) - { - m_val.u64 = evt->get_tinfo()->m_latency; - } - else - { - m_val.u64 = 0; - } + case TYPE_WAIT_LATENCY: { + ppm_event_flags eflags = evt->get_info_flags(); + uint16_t etype = evt->get_scap_evt()->type; - RETURN_EXTRACT_VAR(m_val.u64); - } - else - { - return NULL; + if(eflags & (EF_WAITS) && PPME_IS_EXIT(etype)) { + if(evt->get_tinfo() != NULL) { + m_val.u64 = evt->get_tinfo()->m_latency; + } else { + m_val.u64 = 0; } + + RETURN_EXTRACT_VAR(m_val.u64); + } else { + return NULL; } - case TYPE_ISSYSLOG: - { - m_val.u32 = 0; + } + case TYPE_ISSYSLOG: { + m_val.u32 = 0; - ppm_event_flags eflags = evt->get_info_flags(); - if(eflags & EF_WRITES_TO_FD) - { - sinsp_fdinfo* fdinfo = evt->get_fd_info(); + ppm_event_flags eflags = evt->get_info_flags(); + if(eflags & EF_WRITES_TO_FD) { + sinsp_fdinfo* fdinfo = evt->get_fd_info(); - if(fdinfo != NULL && fdinfo->is_syslog()) - { - m_val.u32 = 1; - } + if(fdinfo != NULL && fdinfo->is_syslog()) { + m_val.u32 = 1; } - - RETURN_EXTRACT_VAR(m_val.u32); } + + RETURN_EXTRACT_VAR(m_val.u32); + } case TYPE_COUNT: m_val.u32 = 1; RETURN_EXTRACT_VAR(m_val.u32); case TYPE_COUNT_ERROR: return extract_error_count(evt, len); - case TYPE_COUNT_ERROR_FILE: - { - sinsp_fdinfo* fdinfo = evt->get_fd_info(); + case TYPE_COUNT_ERROR_FILE: { + sinsp_fdinfo* fdinfo = evt->get_fd_info(); - if(fdinfo != NULL) - { - if(fdinfo->m_type == SCAP_FD_FILE || - fdinfo->m_type == SCAP_FD_FILE_V2 || - fdinfo->m_type == SCAP_FD_DIRECTORY) - { - return extract_error_count(evt, len); - } - } - else - { - uint16_t etype = evt->get_type(); - - if(etype == PPME_SYSCALL_OPEN_X || - etype == PPME_SYSCALL_CREAT_X || - etype == PPME_SYSCALL_OPENAT_X || - etype == PPME_SYSCALL_OPENAT_2_X || - etype == PPME_SYSCALL_OPENAT2_X || - etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) - { - return extract_error_count(evt, len); - } + if(fdinfo != NULL) { + if(fdinfo->m_type == SCAP_FD_FILE || fdinfo->m_type == SCAP_FD_FILE_V2 || + fdinfo->m_type == SCAP_FD_DIRECTORY) { + return extract_error_count(evt, len); } + } else { + uint16_t etype = evt->get_type(); - return NULL; + if(etype == PPME_SYSCALL_OPEN_X || etype == PPME_SYSCALL_CREAT_X || + etype == PPME_SYSCALL_OPENAT_X || etype == PPME_SYSCALL_OPENAT_2_X || + etype == PPME_SYSCALL_OPENAT2_X || etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) { + return extract_error_count(evt, len); + } } - case TYPE_COUNT_ERROR_NET: - { - sinsp_fdinfo* fdinfo = evt->get_fd_info(); - if(fdinfo != NULL) - { - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK || - fdinfo->m_type == SCAP_FD_IPV6_SOCK || - fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || - fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK || - fdinfo->m_type == SCAP_FD_UNIX_SOCK) - { - return extract_error_count(evt, len); - } + return NULL; + } + case TYPE_COUNT_ERROR_NET: { + sinsp_fdinfo* fdinfo = evt->get_fd_info(); + + if(fdinfo != NULL) { + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK || fdinfo->m_type == SCAP_FD_IPV6_SOCK || + fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK || + fdinfo->m_type == SCAP_FD_UNIX_SOCK) { + return extract_error_count(evt, len); } - else - { - uint16_t etype = evt->get_type(); - - if(etype == PPME_SOCKET_ACCEPT_X || - etype == PPME_SOCKET_ACCEPT_5_X || - etype == PPME_SOCKET_ACCEPT4_X || - etype == PPME_SOCKET_ACCEPT4_5_X || - etype == PPME_SOCKET_ACCEPT4_6_X || - etype == PPME_SOCKET_CONNECT_X) - { - return extract_error_count(evt, len); - } + } else { + uint16_t etype = evt->get_type(); + + if(etype == PPME_SOCKET_ACCEPT_X || etype == PPME_SOCKET_ACCEPT_5_X || + etype == PPME_SOCKET_ACCEPT4_X || etype == PPME_SOCKET_ACCEPT4_5_X || + etype == PPME_SOCKET_ACCEPT4_6_X || etype == PPME_SOCKET_CONNECT_X) { + return extract_error_count(evt, len); } + } + return NULL; + } + case TYPE_COUNT_ERROR_MEMORY: { + if(evt->get_category() == EC_MEMORY) { + return extract_error_count(evt, len); + } else { return NULL; } - case TYPE_COUNT_ERROR_MEMORY: - { - if(evt->get_category() == EC_MEMORY) - { + } + case TYPE_COUNT_ERROR_OTHER: { + sinsp_fdinfo* fdinfo = evt->get_fd_info(); + + if(fdinfo != NULL) { + if(!(fdinfo->m_type == SCAP_FD_FILE || fdinfo->m_type == SCAP_FD_FILE_V2 || + fdinfo->m_type == SCAP_FD_DIRECTORY || fdinfo->m_type == SCAP_FD_IPV4_SOCK || + fdinfo->m_type == SCAP_FD_IPV6_SOCK || fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || + fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK || fdinfo->m_type == SCAP_FD_UNIX_SOCK)) { return extract_error_count(evt, len); } - else - { - return NULL; - } - } - case TYPE_COUNT_ERROR_OTHER: - { - sinsp_fdinfo* fdinfo = evt->get_fd_info(); + } else { + uint16_t etype = evt->get_type(); - if(fdinfo != NULL) - { - if(!(fdinfo->m_type == SCAP_FD_FILE || - fdinfo->m_type == SCAP_FD_FILE_V2 || - fdinfo->m_type == SCAP_FD_DIRECTORY || - fdinfo->m_type == SCAP_FD_IPV4_SOCK || - fdinfo->m_type == SCAP_FD_IPV6_SOCK || - fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || - fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK || - fdinfo->m_type == SCAP_FD_UNIX_SOCK)) - { - return extract_error_count(evt, len); - } - } - else - { - uint16_t etype = evt->get_type(); - - if(!(etype == PPME_SYSCALL_OPEN_X || - etype == PPME_SYSCALL_CREAT_X || - etype == PPME_SYSCALL_OPENAT_X || - etype == PPME_SYSCALL_OPENAT_2_X || - etype == PPME_SYSCALL_OPENAT2_X || - etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X || - etype == PPME_SOCKET_ACCEPT_X || - etype == PPME_SOCKET_ACCEPT_5_X || - etype == PPME_SOCKET_ACCEPT4_X || - etype == PPME_SOCKET_ACCEPT4_5_X || - etype == PPME_SOCKET_ACCEPT4_6_X || - etype == PPME_SOCKET_CONNECT_X || - evt->get_category() == EC_MEMORY)) - { - return extract_error_count(evt, len); - } + if(!(etype == PPME_SYSCALL_OPEN_X || etype == PPME_SYSCALL_CREAT_X || + etype == PPME_SYSCALL_OPENAT_X || etype == PPME_SYSCALL_OPENAT_2_X || + etype == PPME_SYSCALL_OPENAT2_X || etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X || + etype == PPME_SOCKET_ACCEPT_X || etype == PPME_SOCKET_ACCEPT_5_X || + etype == PPME_SOCKET_ACCEPT4_X || etype == PPME_SOCKET_ACCEPT4_5_X || + etype == PPME_SOCKET_ACCEPT4_6_X || etype == PPME_SOCKET_CONNECT_X || + evt->get_category() == EC_MEMORY)) { + return extract_error_count(evt, len); } - - return NULL; } + + return NULL; + } case TYPE_COUNT_EXIT: - if(PPME_IS_EXIT(evt->get_type())) - { + if(PPME_IS_EXIT(evt->get_type())) { m_val.u32 = 1; RETURN_EXTRACT_VAR(m_val.u32); - } - else - { + } else { return NULL; } - case TYPE_COUNT_PROCINFO: - { - uint16_t etype = evt->get_type(); + case TYPE_COUNT_PROCINFO: { + uint16_t etype = evt->get_type(); - if(etype == PPME_PROCINFO_E) - { - sinsp_threadinfo* tinfo = evt->get_thread_info(); + if(etype == PPME_PROCINFO_E) { + sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo != NULL && tinfo->is_main_thread()) - { - m_val.u32 = 1; - RETURN_EXTRACT_VAR(m_val.u32); - } + if(tinfo != NULL && tinfo->is_main_thread()) { + m_val.u32 = 1; + RETURN_EXTRACT_VAR(m_val.u32); } } + } - break; - case TYPE_COUNT_THREADINFO: - { - uint16_t etype = evt->get_type(); + break; + case TYPE_COUNT_THREADINFO: { + uint16_t etype = evt->get_type(); - if(etype == PPME_PROCINFO_E) - { - m_val.u32 = 1; - RETURN_EXTRACT_VAR(m_val.u32); - } + if(etype == PPME_PROCINFO_E) { + m_val.u32 = 1; + RETURN_EXTRACT_VAR(m_val.u32); } + } - break; + break; case TYPE_ABSPATH: return extract_abspath(evt, len); case TYPE_BUFLEN_IN: - if(evt->get_fd_info() && evt->get_category() == EC_IO_READ) - { + if(evt->get_fd_info() && evt->get_category() == EC_IO_READ) { return extract_buflen(evt, len); } break; case TYPE_BUFLEN_OUT: - if(evt->get_fd_info() && evt->get_category() == EC_IO_WRITE) - { + if(evt->get_fd_info() && evt->get_category() == EC_IO_WRITE) { return extract_buflen(evt, len); } break; case TYPE_BUFLEN_FILE: - if(evt->get_fd_info() && evt->get_category() & EC_IO_BASE) - { - if(evt->get_fd_info()->m_type == SCAP_FD_FILE || evt->get_fd_info()->m_type == SCAP_FD_FILE_V2) - { + if(evt->get_fd_info() && evt->get_category() & EC_IO_BASE) { + if(evt->get_fd_info()->m_type == SCAP_FD_FILE || + evt->get_fd_info()->m_type == SCAP_FD_FILE_V2) { return extract_buflen(evt, len); } } break; case TYPE_BUFLEN_FILE_IN: - if(evt->get_fd_info() && evt->get_category() == EC_IO_READ) - { - if(evt->get_fd_info()->m_type == SCAP_FD_FILE || evt->get_fd_info()->m_type == SCAP_FD_FILE_V2) - { + if(evt->get_fd_info() && evt->get_category() == EC_IO_READ) { + if(evt->get_fd_info()->m_type == SCAP_FD_FILE || + evt->get_fd_info()->m_type == SCAP_FD_FILE_V2) { return extract_buflen(evt, len); } } break; case TYPE_BUFLEN_FILE_OUT: - if(evt->get_fd_info() && evt->get_category() == EC_IO_WRITE) - { - if(evt->get_fd_info()->m_type == SCAP_FD_FILE || evt->get_fd_info()->m_type == SCAP_FD_FILE_V2) - { + if(evt->get_fd_info() && evt->get_category() == EC_IO_WRITE) { + if(evt->get_fd_info()->m_type == SCAP_FD_FILE || + evt->get_fd_info()->m_type == SCAP_FD_FILE_V2) { return extract_buflen(evt, len); } } break; case TYPE_BUFLEN_NET: - if(evt->get_fd_info() && evt->get_category() & EC_IO_BASE) - { + if(evt->get_fd_info() && evt->get_category() & EC_IO_BASE) { scap_fd_type etype = evt->get_fd_info()->m_type; - if(etype >= SCAP_FD_IPV4_SOCK && etype <= SCAP_FD_IPV6_SERVSOCK) - { + if(etype >= SCAP_FD_IPV4_SOCK && etype <= SCAP_FD_IPV6_SERVSOCK) { return extract_buflen(evt, len); } } break; case TYPE_BUFLEN_NET_IN: - if(evt->get_fd_info() && evt->get_category() == EC_IO_READ) - { + if(evt->get_fd_info() && evt->get_category() == EC_IO_READ) { scap_fd_type etype = evt->get_fd_info()->m_type; - if(etype >= SCAP_FD_IPV4_SOCK && etype <= SCAP_FD_IPV6_SERVSOCK) - { + if(etype >= SCAP_FD_IPV4_SOCK && etype <= SCAP_FD_IPV6_SERVSOCK) { return extract_buflen(evt, len); } } break; case TYPE_BUFLEN_NET_OUT: - if(evt->get_fd_info() && evt->get_category() == EC_IO_WRITE) - { + if(evt->get_fd_info() && evt->get_category() == EC_IO_WRITE) { scap_fd_type etype = evt->get_fd_info()->m_type; - if(etype >= SCAP_FD_IPV4_SOCK && etype <= SCAP_FD_IPV6_SERVSOCK) - { + if(etype >= SCAP_FD_IPV4_SOCK && etype <= SCAP_FD_IPV6_SERVSOCK) { return extract_buflen(evt, len); } } @@ -1626,150 +1642,118 @@ uint8_t* sinsp_filter_check_event::extract_single(sinsp_evt *evt, uint32_t* len, case TYPE_ISOPEN_READ: case TYPE_ISOPEN_WRITE: case TYPE_ISOPEN_EXEC: - case TYPE_ISOPEN_CREATE: - { - uint16_t etype = evt->get_type(); + case TYPE_ISOPEN_CREATE: { + uint16_t etype = evt->get_type(); + + m_val.u32 = 0; + // If any of the exec bits is on, we consider this an open+exec + uint32_t is_exec_mask = (PPM_S_IXUSR | PPM_S_IXGRP | PPM_S_IXOTH); + + if(etype == PPME_SYSCALL_OPEN_X || etype == PPME_SYSCALL_OPENAT_E || + etype == PPME_SYSCALL_OPENAT_2_X || etype == PPME_SYSCALL_OPENAT2_X || + etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) { + bool is_new_version = + etype == PPME_SYSCALL_OPENAT_2_X || etype == PPME_SYSCALL_OPENAT2_X; + // For both OPEN_X and OPENAT_E, + // flags is the 3rd argument. + uint32_t flags = evt->get_param(is_new_version ? 3 : 2)->as(); + + // PPM open flags use 0x11 for + // PPM_O_RDWR, so there's no need to + // check that value explicitly. + if(m_field_id == TYPE_ISOPEN_READ && flags & PPM_O_RDONLY) { + m_val.u32 = 1; + } - m_val.u32 = 0; - // If any of the exec bits is on, we consider this an open+exec - uint32_t is_exec_mask = (PPM_S_IXUSR | PPM_S_IXGRP | PPM_S_IXOTH); - - if(etype == PPME_SYSCALL_OPEN_X || - etype == PPME_SYSCALL_OPENAT_E || - etype == PPME_SYSCALL_OPENAT_2_X || - etype == PPME_SYSCALL_OPENAT2_X || - etype == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X) - { - bool is_new_version = etype == PPME_SYSCALL_OPENAT_2_X || etype == PPME_SYSCALL_OPENAT2_X; - // For both OPEN_X and OPENAT_E, - // flags is the 3rd argument. - uint32_t flags = evt->get_param(is_new_version ? 3 : 2)->as(); - - // PPM open flags use 0x11 for - // PPM_O_RDWR, so there's no need to - // check that value explicitly. - if(m_field_id == TYPE_ISOPEN_READ && - flags & PPM_O_RDONLY) - { - m_val.u32 = 1; - } + if(m_field_id == TYPE_ISOPEN_WRITE && flags & PPM_O_WRONLY) { + m_val.u32 = 1; + } - if(m_field_id == TYPE_ISOPEN_WRITE && - flags & PPM_O_WRONLY) - { + if(m_field_id == TYPE_ISOPEN_CREATE) { + // If PPM_O_F_CREATED is set the file is created + if(flags & PPM_O_F_CREATED) { m_val.u32 = 1; } - if(m_field_id == TYPE_ISOPEN_CREATE) - { - // If PPM_O_F_CREATED is set the file is created - if(flags & PPM_O_F_CREATED) - { - m_val.u32 = 1; - } + // If PPM_O_TMPFILE is set and syscall is successful the file is created + if(flags & PPM_O_TMPFILE) { + int64_t retval = evt->get_param(0)->as(); - // If PPM_O_TMPFILE is set and syscall is successful the file is created - if(flags & PPM_O_TMPFILE) - { - int64_t retval = evt->get_param(0)->as(); - - if(retval >= 0) - { - m_val.u32 = 1; - } + if(retval >= 0) { + m_val.u32 = 1; } } - - /* `open_by_handle_at` exit event has no `mode` parameter. */ - if(m_field_id == TYPE_ISOPEN_EXEC && (flags & (PPM_O_TMPFILE | PPM_O_CREAT) && etype != PPME_SYSCALL_OPEN_BY_HANDLE_AT_X)) - { - uint32_t mode_bits = evt->get_param(is_new_version ? 4 : 3)->as(); - m_val.u32 = (mode_bits & is_exec_mask)? 1 : 0; - } - } - else if ((m_field_id == TYPE_ISOPEN_EXEC) && (etype == PPME_SYSCALL_CREAT_X)) - { - uint32_t mode_bits = evt->get_param(2)->as(); - m_val.u32 = (mode_bits & is_exec_mask)? 1 : 0; } - RETURN_EXTRACT_VAR(m_val.u32); + /* `open_by_handle_at` exit event has no `mode` parameter. */ + if(m_field_id == TYPE_ISOPEN_EXEC && (flags & (PPM_O_TMPFILE | PPM_O_CREAT) && + etype != PPME_SYSCALL_OPEN_BY_HANDLE_AT_X)) { + uint32_t mode_bits = evt->get_param(is_new_version ? 4 : 3)->as(); + m_val.u32 = (mode_bits & is_exec_mask) ? 1 : 0; + } + } else if((m_field_id == TYPE_ISOPEN_EXEC) && (etype == PPME_SYSCALL_CREAT_X)) { + uint32_t mode_bits = evt->get_param(2)->as(); + m_val.u32 = (mode_bits & is_exec_mask) ? 1 : 0; } - break; + RETURN_EXTRACT_VAR(m_val.u32); + } + + break; case TYPE_INFRA_DOCKER_NAME: case TYPE_INFRA_DOCKER_CONTAINER_ID: case TYPE_INFRA_DOCKER_CONTAINER_NAME: - case TYPE_INFRA_DOCKER_CONTAINER_IMAGE: - { - uint16_t etype = evt->get_scap_evt()->type; - - if(etype == PPME_INFRASTRUCTURE_EVENT_E) - { - std::string descstr{evt->get_param(2)->as()}; - vector elements = sinsp_split(descstr, ';'); - for(string ute : elements) - { - string e = trim(ute); - - if(m_field_id == TYPE_INFRA_DOCKER_NAME) - { - if(e.substr(0, sizeof("Event") - 1) == "Event") - { - vector subelements = sinsp_split(e, ':'); - ASSERT(subelements.size() == 2); - m_strstorage = trim(subelements[1]); - RETURN_EXTRACT_STRING(m_strstorage); - } + case TYPE_INFRA_DOCKER_CONTAINER_IMAGE: { + uint16_t etype = evt->get_scap_evt()->type; + + if(etype == PPME_INFRASTRUCTURE_EVENT_E) { + std::string descstr{evt->get_param(2)->as()}; + vector elements = sinsp_split(descstr, ';'); + for(string ute : elements) { + string e = trim(ute); + + if(m_field_id == TYPE_INFRA_DOCKER_NAME) { + if(e.substr(0, sizeof("Event") - 1) == "Event") { + vector subelements = sinsp_split(e, ':'); + ASSERT(subelements.size() == 2); + m_strstorage = trim(subelements[1]); + RETURN_EXTRACT_STRING(m_strstorage); } - else if(m_field_id == TYPE_INFRA_DOCKER_CONTAINER_ID) - { - if(e.substr(0, sizeof("ID") - 1) == "ID") - { - vector subelements = sinsp_split(e, ':'); - ASSERT(subelements.size() == 2); - m_strstorage = trim(subelements[1]); - if(m_strstorage.length() > 12) - { - m_strstorage = m_strstorage.substr(0, 12); - } - RETURN_EXTRACT_STRING(m_strstorage); + } else if(m_field_id == TYPE_INFRA_DOCKER_CONTAINER_ID) { + if(e.substr(0, sizeof("ID") - 1) == "ID") { + vector subelements = sinsp_split(e, ':'); + ASSERT(subelements.size() == 2); + m_strstorage = trim(subelements[1]); + if(m_strstorage.length() > 12) { + m_strstorage = m_strstorage.substr(0, 12); } + RETURN_EXTRACT_STRING(m_strstorage); } - else if(m_field_id == TYPE_INFRA_DOCKER_CONTAINER_NAME) - { - if(e.substr(0, sizeof("name") - 1) == "name") - { - vector subelements = sinsp_split(e, ':'); - ASSERT(subelements.size() == 2); - m_strstorage = trim(subelements[1]); - RETURN_EXTRACT_STRING(m_strstorage); - } + } else if(m_field_id == TYPE_INFRA_DOCKER_CONTAINER_NAME) { + if(e.substr(0, sizeof("name") - 1) == "name") { + vector subelements = sinsp_split(e, ':'); + ASSERT(subelements.size() == 2); + m_strstorage = trim(subelements[1]); + RETURN_EXTRACT_STRING(m_strstorage); } - else if(m_field_id == TYPE_INFRA_DOCKER_CONTAINER_IMAGE) - { - if(e.substr(0, sizeof("Image") - 1) == "Image") - { - vector subelements = sinsp_split(e, ':'); - ASSERT(subelements.size() == 2); - m_strstorage = subelements[1]; - - if(m_strstorage.find("@") != string::npos) - { - m_strstorage = m_strstorage.substr(0, m_strstorage.find("@")); - } - else if(m_strstorage.find("sha256") != string::npos) - { - m_strstorage = e.substr(e.find(":") + 1); - } - m_strstorage = trim(m_strstorage); - RETURN_EXTRACT_STRING(m_strstorage); + } else if(m_field_id == TYPE_INFRA_DOCKER_CONTAINER_IMAGE) { + if(e.substr(0, sizeof("Image") - 1) == "Image") { + vector subelements = sinsp_split(e, ':'); + ASSERT(subelements.size() == 2); + m_strstorage = subelements[1]; + + if(m_strstorage.find("@") != string::npos) { + m_strstorage = m_strstorage.substr(0, m_strstorage.find("@")); + } else if(m_strstorage.find("sha256") != string::npos) { + m_strstorage = e.substr(e.find(":") + 1); } + m_strstorage = trim(m_strstorage); + RETURN_EXTRACT_STRING(m_strstorage); } } } } - break; + } break; default: ASSERT(false); return NULL; @@ -1778,51 +1762,36 @@ uint8_t* sinsp_filter_check_event::extract_single(sinsp_evt *evt, uint32_t* len, return NULL; } -bool sinsp_filter_check_event::compare_nocache(sinsp_evt *evt) -{ +bool sinsp_filter_check_event::compare_nocache(sinsp_evt* evt) { bool res; m_is_compare = true; - if(m_field_id == TYPE_ARGRAW) - { + if(m_field_id == TYPE_ARGRAW) { uint32_t len; bool sanitize_strings = false; // note: this uses the single-value extract because this filtercheck // class does not support multi-valued extraction uint8_t* extracted_val = extract_single(evt, &len, sanitize_strings); - if(extracted_val == NULL) - { + if(extracted_val == NULL) { return false; } ASSERT(m_arginfo != NULL); - res = compare_rhs(m_cmpop, - m_arginfo->type, - extracted_val); - } - else if(m_field_id == TYPE_AROUND) - { + res = compare_rhs(m_cmpop, m_arginfo->type, extracted_val); + } else if(m_field_id == TYPE_AROUND) { uint64_t ts = evt->get_ts(); uint64_t t1 = ts - m_tsdelta; uint64_t t2 = ts + m_tsdelta; - bool res1 = ::flt_compare(CO_GE, - PT_UINT64, - &m_val.u64, - &t1); + bool res1 = ::flt_compare(CO_GE, PT_UINT64, &m_val.u64, &t1); - bool res2 = ::flt_compare(CO_LE, - PT_UINT64, - &m_val.u64, - &t2); + bool res2 = ::flt_compare(CO_LE, PT_UINT64, &m_val.u64, &t2); return res1 && res2; - } - else - { + } else { res = sinsp_filter_check::compare_nocache(evt); } diff --git a/userspace/libsinsp/sinsp_filtercheck_event.h b/userspace/libsinsp/sinsp_filtercheck_event.h index 65afa2034c..8dbea21d23 100644 --- a/userspace/libsinsp/sinsp_filtercheck_event.h +++ b/userspace/libsinsp/sinsp_filtercheck_event.h @@ -21,11 +21,9 @@ limitations under the License. #include #include -class sinsp_filter_check_event : public sinsp_filter_check -{ +class sinsp_filter_check_event : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_LATENCY = 0, TYPE_LATENCY_S = 1, TYPE_LATENCY_NS = 2, @@ -90,21 +88,28 @@ class sinsp_filter_check_event : public sinsp_filter_check virtual ~sinsp_filter_check_event() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; - size_t parse_filter_value(const char* str, uint32_t len, uint8_t* storage, uint32_t storage_len) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; + size_t parse_filter_value(const char* str, + uint32_t len, + uint8_t* storage, + uint32_t storage_len) override; protected: Json::Value extract_as_js(sinsp_evt*, uint32_t* len) override; - virtual uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; + virtual uint8_t* extract_single(sinsp_evt*, + uint32_t* len, + bool sanitize_strings = true) override; virtual bool compare_nocache(sinsp_evt*) override; private: void validate_filter_value(const char* str, uint32_t len); int32_t extract_arg(std::string_view fldname, std::string_view val, const ppm_param_info**); int32_t extract_type(std::string_view fldname, std::string_view val, const ppm_param_info**); - uint8_t* extract_error_count(sinsp_evt *evt, uint32_t* len); - uint8_t *extract_abspath(sinsp_evt *evt, uint32_t *len); - inline uint8_t* extract_buflen(sinsp_evt *evt, uint32_t* len); + uint8_t* extract_error_count(sinsp_evt* evt, uint32_t* len); + uint8_t* extract_abspath(sinsp_evt* evt, uint32_t* len); + inline uint8_t* extract_buflen(sinsp_evt* evt, uint32_t* len); union { uint16_t u16; diff --git a/userspace/libsinsp/sinsp_filtercheck_evtin.cpp b/userspace/libsinsp/sinsp_filtercheck_evtin.cpp index 81ed2c80f5..9635a15aa8 100644 --- a/userspace/libsinsp/sinsp_filtercheck_evtin.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_evtin.cpp @@ -24,182 +24,327 @@ limitations under the License. using namespace std; -static inline bool str_match_start(std::string_view val, size_t len, const char* m) -{ +static inline bool str_match_start(std::string_view val, size_t len, const char* m) { return val.compare(0, len, m) == 0; } -#define STR_MATCH(s) str_match_start(val, sizeof (s) -1, s) - -static const filtercheck_field_info sinsp_filter_check_evtin_fields[] = -{ - { PT_INT64, EPF_NONE|EPF_DEPRECATED, PF_ID, "evtin.span.id", "In Span ID", "accepts all the events that are between the enter and exit tracers of the spans with the given ID and are generated by the same thread that generated the tracers." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.ntags", "In Span Tag Count", "accepts all the events that are between the enter and exit tracers of the spans with the given number of tags and are generated by the same thread that generated the tracers." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.nargs", "In Span Argument Count", "accepts all the events that are between the enter and exit tracers of the spans with the given number of arguments and are generated by the same thread that generated the tracers." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.tags", "In Span Tags", "accepts all the events that are between the enter and exit tracers of the spans with the given tags and are generated by the same thread that generated the tracers." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.tag", "In Span Tag", "accepts all the events that are between the enter and exit tracers of the spans with the given tag and are generated by the same thread that generated the tracers. See the description of span.tag for information about the syntax accepted by this field." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.args", "In Span Arguments", "accepts all the events that are between the enter and exit tracers of the spans with the given arguments and are generated by the same thread that generated the tracers." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.arg", "In Span Argument", "accepts all the events that are between the enter and exit tracers of the spans with the given argument and are generated by the same thread that generated the tracers. See the description of span.arg for information about the syntax accepted by this field." }, - { PT_INT64, EPF_NONE|EPF_DEPRECATED, PF_ID, "evtin.span.p.id", "In Parent ID", "same as evtin.span.id, but also accepts events generated by other threads in the same process that produced the span." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.p.ntags", "In Parent Tag Count", "same as evtin.span.ntags, but also accepts events generated by other threads in the same process that produced the span." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.p.nargs", "In Parent Argument Count", "same as evtin.span.nargs, but also accepts events generated by other threads in the same process that produced the span." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.p.tags", "In Parent Tags", "same as evtin.span.tags, but also accepts events generated by other threads in the same process that produced the span." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.p.tag", "In Parent Tag", "same as evtin.span.tag, but also accepts events generated by other threads in the same process that produced the span." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.p.args", "In Parent Arguments", "same as evtin.span.args, but also accepts events generated by other threads in the same process that produced the span." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.p.arg", "In Parent Argument", "same as evtin.span.arg, but also accepts events generated by other threads in the same process that produced the span." }, - { PT_INT64, EPF_NONE|EPF_DEPRECATED, PF_ID, "evtin.span.s.id", "In Script ID", "same as evtin.span.id, but also accepts events generated by the script that produced the span, i.e. by the processes whose parent PID is the same as the one of the process generating the span." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.s.ntags", "In Script Tag Count", "same as evtin.span.id, but also accepts events generated by the script that produced the span, i.e. by the processes whose parent PID is the same as the one of the process generating the span." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.s.nargs", "In Script Argument Count", "same as evtin.span.id, but also accepts events generated by the script that produced the span, i.e. by the processes whose parent PID is the same as the one of the process generating the span." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.s.tags", "In Script Tags", "same as evtin.span.id, but also accepts events generated by the script that produced the span, i.e. by the processes whose parent PID is the same as the one of the process generating the span." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.s.tag", "In Script Tag", "same as evtin.span.id, but also accepts events generated by the script that produced the span, i.e. by the processes whose parent PID is the same as the one of the process generating the span." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.s.args", "In Script Arguments", "same as evtin.span.id, but also accepts events generated by the script that produced the span, i.e. by the processes whose parent PID is the same as the one of the process generating the span." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.s.arg", "In Script Argument", "same as evtin.span.id, but also accepts events generated by the script that produced the span, i.e. by the processes whose parent PID is the same as the one of the process generating the span." }, - { PT_INT64, EPF_NONE|EPF_DEPRECATED, PF_ID, "evtin.span.m.id", "In Machine ID", "same as evtin.span.id, but accepts all the events generated on the machine during the span, including other threads and other processes." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.m.ntags", "In Machine Tag Count", "same as evtin.span.id, but accepts all the events generated on the machine during the span, including other threads and other processes." }, - { PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "evtin.span.m.nargs", "In Machine Argument Count", "same as evtin.span.id, but accepts all the events generated on the machine during the span, including other threads and other processes." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.m.tags", "In Machine Tags", "same as evtin.span.id, but accepts all the events generated on the machine during the span, including other threads and other processes." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.m.tag", "In Machine Tag", "same as evtin.span.id, but accepts all the events generated on the machine during the span, including other threads and other processes." }, - { PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "evtin.span.m.args", "In Machine Arguments", "same as evtin.span.id, but accepts all the events generated on the machine during the span, including other threads and other processes." }, - { PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "evtin.span.m.arg", "In Machine Argument", "same as evtin.span.id, but accepts all the events generated on the machine during the span, including other threads and other processes." }, +#define STR_MATCH(s) str_match_start(val, sizeof(s) - 1, s) + +static const filtercheck_field_info sinsp_filter_check_evtin_fields[] = { + {PT_INT64, + EPF_NONE | EPF_DEPRECATED, + PF_ID, + "evtin.span.id", + "In Span ID", + "accepts all the events that are between the enter and exit tracers of the spans with the " + "given ID and are generated by the same thread that generated the tracers."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.ntags", + "In Span Tag Count", + "accepts all the events that are between the enter and exit tracers of the spans with the " + "given number of tags and are generated by the same thread that generated the tracers."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.nargs", + "In Span Argument Count", + "accepts all the events that are between the enter and exit tracers of the spans with the " + "given number of arguments and are generated by the same thread that generated the " + "tracers."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.tags", + "In Span Tags", + "accepts all the events that are between the enter and exit tracers of the spans with the " + "given tags and are generated by the same thread that generated the tracers."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.tag", + "In Span Tag", + "accepts all the events that are between the enter and exit tracers of the spans with the " + "given tag and are generated by the same thread that generated the tracers. See the " + "description of span.tag for information about the syntax accepted by this field."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.args", + "In Span Arguments", + "accepts all the events that are between the enter and exit tracers of the spans with the " + "given arguments and are generated by the same thread that generated the tracers."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.arg", + "In Span Argument", + "accepts all the events that are between the enter and exit tracers of the spans with the " + "given argument and are generated by the same thread that generated the tracers. See the " + "description of span.arg for information about the syntax accepted by this field."}, + {PT_INT64, + EPF_NONE | EPF_DEPRECATED, + PF_ID, + "evtin.span.p.id", + "In Parent ID", + "same as evtin.span.id, but also accepts events generated by other threads in the same " + "process that produced the span."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.p.ntags", + "In Parent Tag Count", + "same as evtin.span.ntags, but also accepts events generated by other threads in the same " + "process that produced the span."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.p.nargs", + "In Parent Argument Count", + "same as evtin.span.nargs, but also accepts events generated by other threads in the same " + "process that produced the span."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.p.tags", + "In Parent Tags", + "same as evtin.span.tags, but also accepts events generated by other threads in the same " + "process that produced the span."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.p.tag", + "In Parent Tag", + "same as evtin.span.tag, but also accepts events generated by other threads in the same " + "process that produced the span."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.p.args", + "In Parent Arguments", + "same as evtin.span.args, but also accepts events generated by other threads in the same " + "process that produced the span."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.p.arg", + "In Parent Argument", + "same as evtin.span.arg, but also accepts events generated by other threads in the same " + "process that produced the span."}, + {PT_INT64, + EPF_NONE | EPF_DEPRECATED, + PF_ID, + "evtin.span.s.id", + "In Script ID", + "same as evtin.span.id, but also accepts events generated by the script that produced the " + "span, i.e. by the processes whose parent PID is the same as the one of the process " + "generating the span."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.s.ntags", + "In Script Tag Count", + "same as evtin.span.id, but also accepts events generated by the script that produced the " + "span, i.e. by the processes whose parent PID is the same as the one of the process " + "generating the span."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.s.nargs", + "In Script Argument Count", + "same as evtin.span.id, but also accepts events generated by the script that produced the " + "span, i.e. by the processes whose parent PID is the same as the one of the process " + "generating the span."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.s.tags", + "In Script Tags", + "same as evtin.span.id, but also accepts events generated by the script that produced the " + "span, i.e. by the processes whose parent PID is the same as the one of the process " + "generating the span."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.s.tag", + "In Script Tag", + "same as evtin.span.id, but also accepts events generated by the script that produced the " + "span, i.e. by the processes whose parent PID is the same as the one of the process " + "generating the span."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.s.args", + "In Script Arguments", + "same as evtin.span.id, but also accepts events generated by the script that produced the " + "span, i.e. by the processes whose parent PID is the same as the one of the process " + "generating the span."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.s.arg", + "In Script Argument", + "same as evtin.span.id, but also accepts events generated by the script that produced the " + "span, i.e. by the processes whose parent PID is the same as the one of the process " + "generating the span."}, + {PT_INT64, + EPF_NONE | EPF_DEPRECATED, + PF_ID, + "evtin.span.m.id", + "In Machine ID", + "same as evtin.span.id, but accepts all the events generated on the machine during the " + "span, including other threads and other processes."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.m.ntags", + "In Machine Tag Count", + "same as evtin.span.id, but accepts all the events generated on the machine during the " + "span, including other threads and other processes."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "evtin.span.m.nargs", + "In Machine Argument Count", + "same as evtin.span.id, but accepts all the events generated on the machine during the " + "span, including other threads and other processes."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.m.tags", + "In Machine Tags", + "same as evtin.span.id, but accepts all the events generated on the machine during the " + "span, including other threads and other processes."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.m.tag", + "In Machine Tag", + "same as evtin.span.id, but accepts all the events generated on the machine during the " + "span, including other threads and other processes."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "evtin.span.m.args", + "In Machine Arguments", + "same as evtin.span.id, but accepts all the events generated on the machine during the " + "span, including other threads and other processes."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "evtin.span.m.arg", + "In Machine Argument", + "same as evtin.span.id, but accepts all the events generated on the machine during the " + "span, including other threads and other processes."}, }; -sinsp_filter_check_evtin::sinsp_filter_check_evtin() -{ +sinsp_filter_check_evtin::sinsp_filter_check_evtin() { static const filter_check_info s_field_infos = { - "evtin", - "", - "Fields used if information about distributed tracing is available.", - sizeof(sinsp_filter_check_evtin_fields) / sizeof(sinsp_filter_check_evtin_fields[0]), - sinsp_filter_check_evtin_fields, - filter_check_info::FL_HIDDEN, + "evtin", + "", + "Fields used if information about distributed tracing is available.", + sizeof(sinsp_filter_check_evtin_fields) / sizeof(sinsp_filter_check_evtin_fields[0]), + sinsp_filter_check_evtin_fields, + filter_check_info::FL_HIDDEN, }; m_info = &s_field_infos; } -int32_t sinsp_filter_check_evtin::extract_arg(string_view fldname, string_view val) -{ +int32_t sinsp_filter_check_evtin::extract_arg(string_view fldname, string_view val) { uint32_t parsed_len = 0; // // 'arg' and 'resarg' are handled in a custom way // - if(val.size() > fldname.size() && val.at(fldname.size()) == '[') - { + if(val.size() > fldname.size() && val.at(fldname.size()) == '[') { parsed_len = (uint32_t)val.find(']'); string numstr(val.substr(fldname.size() + 1, parsed_len - fldname.size() - 1)); m_argid = sinsp_numparser::parsed32(numstr); parsed_len++; - } - else if(val.size() > fldname.size() && val.at(fldname.size()) == '.') - { + } else if(val.size() > fldname.size() && val.at(fldname.size()) == '.') { const ppm_param_info* pi = - sinsp_utils::find_longest_matching_evt_param(val.substr(fldname.size() + 1)); + sinsp_utils::find_longest_matching_evt_param(val.substr(fldname.size() + 1)); - if(pi == NULL) - { - throw sinsp_exception("unknown event argument " + string(val.substr(fldname.size() + 1))); + if(pi == NULL) { + throw sinsp_exception("unknown event argument " + + string(val.substr(fldname.size() + 1))); } m_argname = pi->name; parsed_len = (uint32_t)(fldname.size() + strlen(pi->name) + 1); m_argid = -1; - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } return parsed_len; } -int32_t sinsp_filter_check_evtin::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ +int32_t sinsp_filter_check_evtin::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { int32_t res; // // A couple of fields are handled in a custom way // - if(STR_MATCH("evtin.span.tag") && - !STR_MATCH("evtin.span.tags")) - { + if(STR_MATCH("evtin.span.tag") && !STR_MATCH("evtin.span.tags")) { m_field_id = TYPE_TAG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.tag", val); - } - else if(STR_MATCH("evtin.span.arg") && - !STR_MATCH("evtin.span.args")) - { + } else if(STR_MATCH("evtin.span.arg") && !STR_MATCH("evtin.span.args")) { m_field_id = TYPE_ARG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.arg", val); - } - else if(STR_MATCH("evtin.span.p.tag") && - !STR_MATCH("evtin.span.p.tags")) - { + } else if(STR_MATCH("evtin.span.p.tag") && !STR_MATCH("evtin.span.p.tags")) { m_field_id = TYPE_P_TAG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.p.tag", val); - } - else if(STR_MATCH("evtin.span.p.arg") && - !STR_MATCH("evtin.span.p.args")) - { + } else if(STR_MATCH("evtin.span.p.arg") && !STR_MATCH("evtin.span.p.args")) { m_field_id = TYPE_P_ARG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.p.arg", val); - } - else if(STR_MATCH("evtin.span.s.tag") && - !STR_MATCH("evtin.span.s.tags")) - { + } else if(STR_MATCH("evtin.span.s.tag") && !STR_MATCH("evtin.span.s.tags")) { m_field_id = TYPE_S_TAG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.s.tag", val); - } - else if(STR_MATCH("evtin.span.s.arg") && - !STR_MATCH("evtin.span.s.args")) - { + } else if(STR_MATCH("evtin.span.s.arg") && !STR_MATCH("evtin.span.s.args")) { m_field_id = TYPE_S_ARG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.s.arg", val); - } - else if(STR_MATCH("evtin.span.m.tag") && - !STR_MATCH("evtin.span.m.tags")) - { + } else if(STR_MATCH("evtin.span.m.tag") && !STR_MATCH("evtin.span.m.tags")) { m_field_id = TYPE_M_TAG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.m.tag", val); - } - else if(STR_MATCH("evtin.span.m.arg") && - !STR_MATCH("evtin.span.m.args")) - { + } else if(STR_MATCH("evtin.span.m.arg") && !STR_MATCH("evtin.span.m.args")) { m_field_id = TYPE_M_ARG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("evtin.span.m.arg", val); - } - else - { + } else { res = sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } return res; } -std::unique_ptr sinsp_filter_check_evtin::allocate_new() -{ +std::unique_ptr sinsp_filter_check_evtin::allocate_new() { return std::make_unique(); } -uint8_t* sinsp_filter_check_evtin::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_evtin::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { // do nothing: support to tracers has been dropped *len = 0; return NULL; diff --git a/userspace/libsinsp/sinsp_filtercheck_evtin.h b/userspace/libsinsp/sinsp_filtercheck_evtin.h index 6754e0c765..5c5dd5ac71 100644 --- a/userspace/libsinsp/sinsp_filtercheck_evtin.h +++ b/userspace/libsinsp/sinsp_filtercheck_evtin.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_evtin : public sinsp_filter_check -{ +class sinsp_filter_check_evtin : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_ID = 0, TYPE_NTAGS, TYPE_NARGS, @@ -59,7 +57,9 @@ class sinsp_filter_check_evtin : public sinsp_filter_check virtual ~sinsp_filter_check_evtin() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; protected: uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; diff --git a/userspace/libsinsp/sinsp_filtercheck_fd.cpp b/userspace/libsinsp/sinsp_filtercheck_fd.cpp index a6b48242cb..496f17164c 100644 --- a/userspace/libsinsp/sinsp_filtercheck_fd.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_fd.cpp @@ -23,90 +23,305 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) - -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -#define RETURN_EXTRACT_CSTR(x) do { \ - if((x)) \ - { \ - *len = strlen((char *) ((x))); \ - } \ - return (uint8_t*) ((x)); \ -} while(0) - -static inline bool str_match_start(std::string_view val, size_t len, const char* m) -{ +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t *)&(x); \ + } while(0) + +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t *)(x).c_str(); \ + } while(0) + +#define RETURN_EXTRACT_CSTR(x) \ + do { \ + if((x)) { \ + *len = strlen((char *)((x))); \ + } \ + return (uint8_t *)((x)); \ + } while(0) + +static inline bool str_match_start(std::string_view val, size_t len, const char *m) { return val.compare(0, len, m) == 0; } -#define STR_MATCH(s) str_match_start(val, sizeof (s) -1, s) - -static const filtercheck_field_info sinsp_filter_check_fd_fields[] = -{ - {PT_INT64, EPF_NONE, PF_ID, "fd.num", "FD Number", "the unique number identifying the file descriptor."}, - {PT_CHARBUF, EPF_NONE, PF_DEC, "fd.type", "FD Type", "type of FD. Can be 'file', 'directory', 'ipv4', 'ipv6', 'unix', 'pipe', 'event', 'signalfd', 'eventpoll', 'inotify' 'signalfd' or 'memfd'."}, - {PT_CHARBUF, EPF_NONE, PF_DEC, "fd.typechar", "FD Type Char", "type of FD as a single character. Can be 'f' for file, 4 for IPv4 socket, 6 for IPv6 socket, 'u' for unix socket, p for pipe, 'e' for eventfd, 's' for signalfd, 'l' for eventpoll, 'i' for inotify, 'b' for bpf, 'u' for userfaultd, 'r' for io_uring, 'm' for memfd ,'o' for unknown."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.name", "FD Name", "FD full name. If the fd is a file, this field contains the full path. If the FD is a socket, this field contain the connection tuple."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.directory", "FD Directory", "If the fd is a file, the directory that contains it."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.filename", "FD Filename", "If the fd is a file, the filename without the path."}, - {PT_IPADDR, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.ip", "FD IP Address", "matches the ip address (client or server) of the fd."}, - {PT_IPADDR, EPF_NONE, PF_NA, "fd.cip", "FD Client Address", "client IP address."}, - {PT_IPADDR, EPF_NONE, PF_NA, "fd.sip", "FD Server Address", "server IP address."}, - {PT_IPADDR, EPF_NONE, PF_NA, "fd.lip", "FD Local Address", "local IP address."}, - {PT_IPADDR, EPF_NONE, PF_NA, "fd.rip", "FD Remote Address", "remote IP address."}, - {PT_PORT, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_DEC, "fd.port", "FD Port", "matches the port (either client or server) of the fd."}, - {PT_PORT, EPF_NONE, PF_DEC, "fd.cport", "FD Client Port", "for TCP/UDP FDs, the client port."}, - {PT_PORT, EPF_NONE, PF_DEC, "fd.sport", "FD Server Port", "for TCP/UDP FDs, server port."}, - {PT_PORT, EPF_NONE, PF_DEC, "fd.lport", "FD Local Port", "for TCP/UDP FDs, the local port."}, - {PT_PORT, EPF_NONE, PF_DEC, "fd.rport", "FD Remote Port", "for TCP/UDP FDs, the remote port."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.l4proto", "FD IP Protocol", "the IP protocol of a socket. Can be 'tcp', 'udp', 'icmp' or 'raw'."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.sockfamily", "FD Socket Family", "the socket family for socket events. Can be 'ip' or 'unix'."}, - {PT_BOOL, EPF_NONE, PF_NA, "fd.is_server", "FD Server", "'true' if the process owning this FD is the server endpoint in the connection."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.uid", "FD ID", "a unique identifier for the FD, created by chaining the FD number and the thread ID."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.containername", "FD Container Name", "chaining of the container ID and the FD name. Useful when trying to identify which container an FD belongs to."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.containerdirectory", "FD Container Directory", "chaining of the container ID and the directory name. Useful when trying to identify which container a directory belongs to."}, - {PT_PORT, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.proto", "FD Protocol", "matches the protocol (either client or server) of the fd."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.cproto", "FD Client Protocol", "for TCP/UDP FDs, the client protocol."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.sproto", "FD Server Protocol", "for TCP/UDP FDs, server protocol."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.lproto", "FD Local Protocol", "for TCP/UDP FDs, the local protocol."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.rproto", "FD Remote Protocol", "for TCP/UDP FDs, the remote protocol."}, - {PT_IPNET, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.net", "FD IP Network", "matches the IP network (client or server) of the fd."}, - {PT_IPNET, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.cnet", "FD Client Network", "matches the client IP network of the fd."}, - {PT_IPNET, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.snet", "FD Server Network", "matches the server IP network of the fd."}, - {PT_IPNET, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.lnet", "FD Local Network", "matches the local IP network of the fd."}, - {PT_IPNET, EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.rnet", "FD Remote Network", "matches the remote IP network of the fd."}, - {PT_BOOL, EPF_NONE, PF_NA, "fd.connected", "FD Connected", "for TCP/UDP FDs, 'true' if the socket is connected."}, - {PT_BOOL, EPF_NONE, PF_NA, "fd.name_changed", "FD Name Changed", "True when an event changes the name of an fd used by this event. This can occur in some cases such as udp connections where the connection tuple changes."}, - {PT_CHARBUF, EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.cip.name", "FD Client Domain Name", "Domain name associated with the client IP address."}, - {PT_CHARBUF, EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.sip.name", "FD Server Domain Name", "Domain name associated with the server IP address."}, - {PT_CHARBUF, EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.lip.name", "FD Local Domain Name", "Domain name associated with the local IP address."}, - {PT_CHARBUF, EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "fd.rip.name", "FD Remote Domain Name", "Domain name associated with the remote IP address."}, - {PT_INT32, EPF_NONE, PF_HEX, "fd.dev", "FD Device", "device number (major/minor) containing the referenced file"}, - {PT_INT32, EPF_NONE, PF_DEC, "fd.dev.major", "FD Major Device", "major device number containing the referenced file"}, - {PT_INT32, EPF_NONE, PF_DEC, "fd.dev.minor", "FD Minor Device", "minor device number containing the referenced file"}, - {PT_INT64, EPF_NONE, PF_DEC, "fd.ino", "FD Inode Number", "inode number of the referenced file"}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fd.nameraw", "FD Name Raw", "FD full name raw. Just like fd.name, but only used if fd is a file path. File path is kept raw with limited sanitization and without deriving the absolute path."}, - {PT_CHARBUF, EPF_IS_LIST | EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_DEC, "fd.types", "FD Type", "List of FD types in used. Can be passed an fd number e.g. fd.types[0] to get the type of stdout as a single item list."}, - {PT_BOOL, EPF_NONE, PF_NA, "fd.is_upper_layer", "FD Upper Layer", "'true' if the fd is of a file in the upper layer of an overlayfs."}, - {PT_BOOL, EPF_NONE, PF_NA, "fd.is_lower_layer", "FD Lower Layer", "'true' if the fd is of a file in the lower layer of an overlayfs."}, +#define STR_MATCH(s) str_match_start(val, sizeof(s) - 1, s) + +static const filtercheck_field_info sinsp_filter_check_fd_fields[] = { + {PT_INT64, + EPF_NONE, + PF_ID, + "fd.num", + "FD Number", + "the unique number identifying the file descriptor."}, + {PT_CHARBUF, + EPF_NONE, + PF_DEC, + "fd.type", + "FD Type", + "type of FD. Can be 'file', 'directory', 'ipv4', 'ipv6', 'unix', 'pipe', 'event', " + "'signalfd', 'eventpoll', 'inotify' 'signalfd' or 'memfd'."}, + {PT_CHARBUF, + EPF_NONE, + PF_DEC, + "fd.typechar", + "FD Type Char", + "type of FD as a single character. Can be 'f' for file, 4 for IPv4 socket, 6 for IPv6 " + "socket, 'u' for unix socket, p for pipe, 'e' for eventfd, 's' for signalfd, 'l' for " + "eventpoll, 'i' for inotify, 'b' for bpf, 'u' for userfaultd, 'r' for io_uring, 'm' for " + "memfd ,'o' for unknown."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.name", + "FD Name", + "FD full name. If the fd is a file, this field contains the full path. If the FD is a " + "socket, this field contain the connection tuple."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.directory", + "FD Directory", + "If the fd is a file, the directory that contains it."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.filename", + "FD Filename", + "If the fd is a file, the filename without the path."}, + {PT_IPADDR, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.ip", + "FD IP Address", + "matches the ip address (client or server) of the fd."}, + {PT_IPADDR, EPF_NONE, PF_NA, "fd.cip", "FD Client Address", "client IP address."}, + {PT_IPADDR, EPF_NONE, PF_NA, "fd.sip", "FD Server Address", "server IP address."}, + {PT_IPADDR, EPF_NONE, PF_NA, "fd.lip", "FD Local Address", "local IP address."}, + {PT_IPADDR, EPF_NONE, PF_NA, "fd.rip", "FD Remote Address", "remote IP address."}, + {PT_PORT, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_DEC, + "fd.port", + "FD Port", + "matches the port (either client or server) of the fd."}, + {PT_PORT, + EPF_NONE, + PF_DEC, + "fd.cport", + "FD Client Port", + "for TCP/UDP FDs, the client port."}, + {PT_PORT, EPF_NONE, PF_DEC, "fd.sport", "FD Server Port", "for TCP/UDP FDs, server port."}, + {PT_PORT, + EPF_NONE, + PF_DEC, + "fd.lport", + "FD Local Port", + "for TCP/UDP FDs, the local port."}, + {PT_PORT, + EPF_NONE, + PF_DEC, + "fd.rport", + "FD Remote Port", + "for TCP/UDP FDs, the remote port."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.l4proto", + "FD IP Protocol", + "the IP protocol of a socket. Can be 'tcp', 'udp', 'icmp' or 'raw'."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.sockfamily", + "FD Socket Family", + "the socket family for socket events. Can be 'ip' or 'unix'."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "fd.is_server", + "FD Server", + "'true' if the process owning this FD is the server endpoint in the connection."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.uid", + "FD ID", + "a unique identifier for the FD, created by chaining the FD number and the thread ID."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.containername", + "FD Container Name", + "chaining of the container ID and the FD name. Useful when trying to identify which " + "container an FD belongs to."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.containerdirectory", + "FD Container Directory", + "chaining of the container ID and the directory name. Useful when trying to identify " + "which container a directory belongs to."}, + {PT_PORT, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.proto", + "FD Protocol", + "matches the protocol (either client or server) of the fd."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.cproto", + "FD Client Protocol", + "for TCP/UDP FDs, the client protocol."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.sproto", + "FD Server Protocol", + "for TCP/UDP FDs, server protocol."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.lproto", + "FD Local Protocol", + "for TCP/UDP FDs, the local protocol."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.rproto", + "FD Remote Protocol", + "for TCP/UDP FDs, the remote protocol."}, + {PT_IPNET, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.net", + "FD IP Network", + "matches the IP network (client or server) of the fd."}, + {PT_IPNET, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.cnet", + "FD Client Network", + "matches the client IP network of the fd."}, + {PT_IPNET, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.snet", + "FD Server Network", + "matches the server IP network of the fd."}, + {PT_IPNET, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.lnet", + "FD Local Network", + "matches the local IP network of the fd."}, + {PT_IPNET, + EPF_FILTER_ONLY | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.rnet", + "FD Remote Network", + "matches the remote IP network of the fd."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "fd.connected", + "FD Connected", + "for TCP/UDP FDs, 'true' if the socket is connected."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "fd.name_changed", + "FD Name Changed", + "True when an event changes the name of an fd used by this event. This can occur in some " + "cases such as udp connections where the connection tuple changes."}, + {PT_CHARBUF, + EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.cip.name", + "FD Client Domain Name", + "Domain name associated with the client IP address."}, + {PT_CHARBUF, + EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.sip.name", + "FD Server Domain Name", + "Domain name associated with the server IP address."}, + {PT_CHARBUF, + EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.lip.name", + "FD Local Domain Name", + "Domain name associated with the local IP address."}, + {PT_CHARBUF, + EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "fd.rip.name", + "FD Remote Domain Name", + "Domain name associated with the remote IP address."}, + {PT_INT32, + EPF_NONE, + PF_HEX, + "fd.dev", + "FD Device", + "device number (major/minor) containing the referenced file"}, + {PT_INT32, + EPF_NONE, + PF_DEC, + "fd.dev.major", + "FD Major Device", + "major device number containing the referenced file"}, + {PT_INT32, + EPF_NONE, + PF_DEC, + "fd.dev.minor", + "FD Minor Device", + "minor device number containing the referenced file"}, + {PT_INT64, + EPF_NONE, + PF_DEC, + "fd.ino", + "FD Inode Number", + "inode number of the referenced file"}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fd.nameraw", + "FD Name Raw", + "FD full name raw. Just like fd.name, but only used if fd is a file path. File path is " + "kept raw with limited sanitization and without deriving the absolute path."}, + {PT_CHARBUF, + EPF_IS_LIST | EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_DEC, + "fd.types", + "FD Type", + "List of FD types in used. Can be passed an fd number e.g. fd.types[0] to get the type of " + "stdout as a single item list."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "fd.is_upper_layer", + "FD Upper Layer", + "'true' if the fd is of a file in the upper layer of an overlayfs."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "fd.is_lower_layer", + "FD Lower Layer", + "'true' if the fd is of a file in the lower layer of an overlayfs."}, }; -sinsp_filter_check_fd::sinsp_filter_check_fd() -{ +sinsp_filter_check_fd::sinsp_filter_check_fd() { static const filter_check_info s_field_infos = { - "fd", - "", - "Every syscall that has a file descriptor in its arguments has these fields set with information related to the file.", - sizeof(sinsp_filter_check_fd_fields) / sizeof(sinsp_filter_check_fd_fields[0]), - sinsp_filter_check_fd_fields, - filter_check_info::FL_NONE, + "fd", + "", + "Every syscall that has a file descriptor in its arguments has these fields set with " + "information related to the file.", + sizeof(sinsp_filter_check_fd_fields) / sizeof(sinsp_filter_check_fd_fields[0]), + sinsp_filter_check_fd_fields, + filter_check_info::FL_NONE, }; m_tinfo = NULL; @@ -116,20 +331,17 @@ sinsp_filter_check_fd::sinsp_filter_check_fd() memset(&m_val, 0, sizeof(m_val)); } -std::unique_ptr sinsp_filter_check_fd::allocate_new() -{ +std::unique_ptr sinsp_filter_check_fd::allocate_new() { return std::make_unique(); } -int32_t sinsp_filter_check_fd::extract_arg(string_view fldname, string_view val) -{ +int32_t sinsp_filter_check_fd::extract_arg(string_view fldname, string_view val) { uint32_t parsed_len = 0; // // 'arg' and 'resarg' are handled in a custom way // - if(val.size() > fldname.size() && val.at(fldname.size()) == '[') - { + if(val.size() > fldname.size() && val.at(fldname.size()) == '[') { parsed_len = (uint32_t)val.find(']'); string numstr(val.substr(fldname.size() + 1, parsed_len - fldname.size() - 1)); @@ -141,18 +353,17 @@ int32_t sinsp_filter_check_fd::extract_arg(string_view fldname, string_view val) return parsed_len; } -int32_t sinsp_filter_check_fd::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ - if(STR_MATCH("fd.types")) - { +int32_t sinsp_filter_check_fd::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { + if(STR_MATCH("fd.types")) { m_field_id = TYPE_FDTYPES; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; res = extract_arg("fd.types", val); - if(res == 0) - { + if(res == 0) { m_argid = -1; res = (int32_t)(sizeof("fd.types") - 1); } @@ -163,194 +374,157 @@ int32_t sinsp_filter_check_fd::parse_field_name(std::string_view val, bool alloc return sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } -bool sinsp_filter_check_fd::extract_fdname_from_creator(sinsp_evt *evt, uint32_t* len, bool sanitize_strings, bool fd_nameraw) -{ - const char* resolved_argstr; +bool sinsp_filter_check_fd::extract_fdname_from_creator(sinsp_evt *evt, + uint32_t *len, + bool sanitize_strings, + bool fd_nameraw) { + const char *resolved_argstr; uint16_t etype = evt->get_type(); - if(PPME_IS_ENTER(etype)) - { + if(PPME_IS_ENTER(etype)) { return false; } - switch(etype) - { + switch(etype) { case PPME_SYSCALL_OPEN_X: case PPME_SOCKET_ACCEPT_X: case PPME_SOCKET_ACCEPT_5_X: case PPME_SOCKET_ACCEPT4_X: case PPME_SOCKET_ACCEPT4_5_X: case PPME_SOCKET_ACCEPT4_6_X: - case PPME_SYSCALL_CREAT_X: - { - const char* argstr = evt->get_param_as_str(1, &resolved_argstr, - m_inspector->get_buffer_format()); - - if(resolved_argstr[0] != 0) - { - m_tstr = resolved_argstr; - } - else - { - m_tstr = argstr; - } + case PPME_SYSCALL_CREAT_X: { + const char *argstr = + evt->get_param_as_str(1, &resolved_argstr, m_inspector->get_buffer_format()); - return true; + if(resolved_argstr[0] != 0) { + m_tstr = resolved_argstr; + } else { + m_tstr = argstr; } - case PPME_SOCKET_CONNECT_X: - { - const char* argstr = evt->get_param_as_str(1, &resolved_argstr, - m_inspector->get_buffer_format()); - if(resolved_argstr[0] != 0) - { - m_tstr = resolved_argstr; - } - else - { - m_tstr = argstr; - } + return true; + } + case PPME_SOCKET_CONNECT_X: { + const char *argstr = + evt->get_param_as_str(1, &resolved_argstr, m_inspector->get_buffer_format()); - return true; + if(resolved_argstr[0] != 0) { + m_tstr = resolved_argstr; + } else { + m_tstr = argstr; } + + return true; + } case PPME_SYSCALL_OPENAT_X: case PPME_SYSCALL_OPENAT_2_X: - case PPME_SYSCALL_OPENAT2_X: - { - sinsp_evt enter_evt; - const sinsp_evt_param *parinfo; - - if(etype == PPME_SYSCALL_OPENAT_X) - { - // - // XXX This is highly inefficient, as it re-requests the enter event and then - // does unnecessary allocations and copies. We assume that failed openat() happen - // rarely enough that we don't care. - // - if(!m_inspector->get_parser()->retrieve_enter_event(&enter_evt, evt)) - { - return false; - } - } + case PPME_SYSCALL_OPENAT2_X: { + sinsp_evt enter_evt; + const sinsp_evt_param *parinfo; - parinfo = etype == PPME_SYSCALL_OPENAT_X ? enter_evt.get_param(1) : evt->get_param(2); - std::string_view name = parinfo->as(); + if(etype == PPME_SYSCALL_OPENAT_X) { + // + // XXX This is highly inefficient, as it re-requests the enter event and then + // does unnecessary allocations and copies. We assume that failed openat() happen + // rarely enough that we don't care. + // + if(!m_inspector->get_parser()->retrieve_enter_event(&enter_evt, evt)) { + return false; + } + } - parinfo = etype == PPME_SYSCALL_OPENAT_X ? enter_evt.get_param(0) : evt->get_param(1); - int64_t dirfd = parinfo->as(); + parinfo = etype == PPME_SYSCALL_OPENAT_X ? enter_evt.get_param(1) : evt->get_param(2); + std::string_view name = parinfo->as(); - std::string sdir = m_inspector->get_parser()->parse_dirfd(evt, name, dirfd); + parinfo = etype == PPME_SYSCALL_OPENAT_X ? enter_evt.get_param(0) : evt->get_param(1); + int64_t dirfd = parinfo->as(); - if(fd_nameraw) - { - m_tstr = name; - } - else - { - // fullpath - m_tstr = sinsp_utils::concatenate_paths(sdir, name); // here we'd like a string - } + std::string sdir = m_inspector->get_parser()->parse_dirfd(evt, name, dirfd); - if(sanitize_strings) - { - sanitize_string(m_tstr); - } + if(fd_nameraw) { + m_tstr = name; + } else { + // fullpath + m_tstr = sinsp_utils::concatenate_paths(sdir, name); // here we'd like a string + } - return true; + if(sanitize_strings) { + sanitize_string(m_tstr); } - case PPME_SYSCALL_OPEN_BY_HANDLE_AT_X: - { - m_tstr = evt->get_param(3)->as(); - if(sanitize_strings) - { - sanitize_string(m_tstr); - } + return true; + } + case PPME_SYSCALL_OPEN_BY_HANDLE_AT_X: { + m_tstr = evt->get_param(3)->as(); - return true; + if(sanitize_strings) { + sanitize_string(m_tstr); } + + return true; + } default: m_tstr = ""; return true; } } -uint8_t* sinsp_filter_check_fd::extract_from_null_fd(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t *sinsp_filter_check_fd::extract_from_null_fd(sinsp_evt *evt, + uint32_t *len, + bool sanitize_strings) { *len = 0; // // Even is there's no fd, we still try to extract a name from exit events that create // one. With these events, the fact that there's no FD means that the call failed, // but even if that happened we still want to collect the name. // - switch(m_field_id) - { - case TYPE_FDNAME: - { - if(extract_fdname_from_creator(evt, len, sanitize_strings) == true) - { + switch(m_field_id) { + case TYPE_FDNAME: { + if(extract_fdname_from_creator(evt, len, sanitize_strings) == true) { RETURN_EXTRACT_STRING(m_tstr); - } - else - { + } else { return NULL; } } - case TYPE_CONTAINERNAME: - { - if(extract_fdname_from_creator(evt, len, sanitize_strings) == true) - { + case TYPE_CONTAINERNAME: { + if(extract_fdname_from_creator(evt, len, sanitize_strings) == true) { m_tstr = m_tinfo->m_container_id + ':' + m_tstr; RETURN_EXTRACT_STRING(m_tstr); - } - else - { + } else { return NULL; } } case TYPE_DIRECTORY: - case TYPE_CONTAINERDIRECTORY: - { - if(extract_fdname_from_creator(evt, len, sanitize_strings) == true) - { - if(sanitize_strings) - { + case TYPE_CONTAINERDIRECTORY: { + if(extract_fdname_from_creator(evt, len, sanitize_strings) == true) { + if(sanitize_strings) { sanitize_string(m_tstr); } size_t pos = m_tstr.rfind('/'); - if(pos != string::npos && pos != 0) - { - if(pos < m_tstr.size() - 1) - { + if(pos != string::npos && pos != 0) { + if(pos < m_tstr.size() - 1) { m_tstr.resize(pos); } - } - else - { + } else { m_tstr = "/"; } - if(m_field_id == TYPE_CONTAINERDIRECTORY) - { + if(m_field_id == TYPE_CONTAINERDIRECTORY) { m_tstr = m_tinfo->m_container_id + ':' + m_tstr; } RETURN_EXTRACT_STRING(m_tstr); - } - else - { + } else { return NULL; } } - case TYPE_FILENAME: - { + case TYPE_FILENAME: { return NULL; } case TYPE_FDTYPECHAR: *len = 1; - switch(PPME_MAKE_ENTER(evt->get_type())) - { + switch(PPME_MAKE_ENTER(evt->get_type())) { case PPME_SYSCALL_OPEN_E: case PPME_SYSCALL_OPENAT_E: case PPME_SYSCALL_OPENAT_2_E: @@ -365,15 +539,15 @@ uint8_t* sinsp_filter_check_fd::extract_from_null_fd(sinsp_evt *evt, uint32_t* l case PPME_SOCKET_ACCEPT4_E: case PPME_SOCKET_ACCEPT4_5_E: case PPME_SOCKET_ACCEPT4_6_E: - // - // Note, this is not accurate, because it always - // returns IPv4 even if this could be IPv6 or unix. - // For the moment, I assume it's better than nothing, and doing - // real event parsing here would be a pain. - // - m_tcstr[0] = CHAR_FD_IPV4_SOCK; - m_tcstr[1] = 0; - return m_tcstr; + // + // Note, this is not accurate, because it always + // returns IPv4 even if this could be IPv6 or unix. + // For the moment, I assume it's better than nothing, and doing + // real event parsing here would be a pain. + // + m_tcstr[0] = CHAR_FD_IPV4_SOCK; + m_tcstr[1] = 0; + return m_tcstr; case PPME_SYSCALL_PIPE_E: case PPME_SYSCALL_PIPE2_E: m_tcstr[0] = CHAR_FD_FIFO; @@ -403,34 +577,29 @@ uint8_t* sinsp_filter_check_fd::extract_from_null_fd(sinsp_evt *evt, uint32_t* l m_tcstr[1] = 0; return m_tcstr; } - case TYPE_FDNAMERAW: - { - if(extract_fdname_from_creator(evt, len, sanitize_strings, true) == true) - { - remove_duplicate_path_separators(m_tstr); - RETURN_EXTRACT_STRING(m_tstr); - } - else - { - return NULL; - } + case TYPE_FDNAMERAW: { + if(extract_fdname_from_creator(evt, len, sanitize_strings, true) == true) { + remove_duplicate_path_separators(m_tstr); + RETURN_EXTRACT_STRING(m_tstr); + } else { + return NULL; } + } default: return NULL; } } -bool sinsp_filter_check_fd::extract_nocache(sinsp_evt *evt, std::vector& values, bool sanitize_strings) -{ +bool sinsp_filter_check_fd::extract_nocache(sinsp_evt *evt, + std::vector &values, + bool sanitize_strings) { values.clear(); - if(!extract_fd(evt)) - { + if(!extract_fd(evt)) { return false; } - if(m_field_id == TYPE_FDTYPES && m_argid == -1) - { + if(m_field_id == TYPE_FDTYPES && m_argid == -1) { // We are of the form fd.types so gather all open file // descriptor types into a (de-duplicated) list // @@ -440,18 +609,16 @@ bool sinsp_filter_check_fd::extract_nocache(sinsp_evt *evt, std::vector fd_types; + std::unordered_set fd_types; // Iterate over the list of open file descriptors and add all // unique file descriptor types to the vector for comparison - auto fd_type_gather = [&fd_types, &values](uint64_t, const sinsp_fdinfo& fdinfo) - { - const char* type = fdinfo.get_typestring(); + auto fd_type_gather = [&fd_types, &values](uint64_t, const sinsp_fdinfo &fdinfo) { + const char *type = fdinfo.get_typestring(); - if (fd_types.emplace(type).second) - { + if(fd_types.emplace(type).second) { extract_value_t val; - val.ptr = (uint8_t*)type; + val.ptr = (uint8_t *)type; val.len = strlen(type); values.push_back(val); @@ -468,151 +635,118 @@ bool sinsp_filter_check_fd::extract_nocache(sinsp_evt *evt, std::vectorm_lastevent_fd); } - switch(m_field_id) - { + switch(m_field_id) { case TYPE_FDNAME: case TYPE_CONTAINERNAME: - if(m_fdinfo == NULL) - { + if(m_fdinfo == NULL) { return extract_from_null_fd(evt, len, sanitize_strings); } - if(evt->get_type() == PPME_SOCKET_CONNECT_X) - { + if(evt->get_type() == PPME_SOCKET_CONNECT_X) { int64_t retval = evt->get_param(0)->as(); - if(retval < 0) - { + if(retval < 0) { return extract_from_null_fd(evt, len, sanitize_strings); } } - if(m_field_id == TYPE_CONTAINERNAME) - { + if(m_field_id == TYPE_CONTAINERNAME) { ASSERT(m_tinfo != NULL); m_tstr = m_tinfo->m_container_id + ':' + m_fdinfo->m_name; - } - else - { + } else { m_tstr = m_fdinfo->m_name; } - if(sanitize_strings) - { + if(sanitize_strings) { sanitize_string(m_tstr); } RETURN_EXTRACT_STRING(m_tstr); break; case TYPE_FDTYPES: case TYPE_FDTYPE: - if(m_fdinfo == NULL) - { + if(m_fdinfo == NULL) { return NULL; - } - else - { - uint8_t *typestr = (uint8_t*)m_fdinfo->get_typestring(); + } else { + uint8_t *typestr = (uint8_t *)m_fdinfo->get_typestring(); RETURN_EXTRACT_CSTR(typestr); } break; case TYPE_DIRECTORY: - case TYPE_CONTAINERDIRECTORY: - { - if(m_fdinfo == NULL) - { - return extract_from_null_fd(evt, len, sanitize_strings); - } + case TYPE_CONTAINERDIRECTORY: { + if(m_fdinfo == NULL) { + return extract_from_null_fd(evt, len, sanitize_strings); + } - if(!(m_fdinfo->is_file() || m_fdinfo->is_directory())) - { - return NULL; - } + if(!(m_fdinfo->is_file() || m_fdinfo->is_directory())) { + return NULL; + } - m_tstr = m_fdinfo->m_name; - if(sanitize_strings) - { - sanitize_string(m_tstr); - } + m_tstr = m_fdinfo->m_name; + if(sanitize_strings) { + sanitize_string(m_tstr); + } - if(m_fdinfo->is_file()) - { - size_t pos = m_tstr.rfind('/'); - if(pos != string::npos && pos != 0) - { - if(pos < m_tstr.size() - 1) - { - m_tstr.resize(pos); - } - } - else - { - m_tstr = "/"; + if(m_fdinfo->is_file()) { + size_t pos = m_tstr.rfind('/'); + if(pos != string::npos && pos != 0) { + if(pos < m_tstr.size() - 1) { + m_tstr.resize(pos); } + } else { + m_tstr = "/"; } + } - if(m_field_id == TYPE_CONTAINERDIRECTORY) - { - m_tstr = m_tinfo->m_container_id + ':' + m_tstr; - } + if(m_field_id == TYPE_CONTAINERDIRECTORY) { + m_tstr = m_tinfo->m_container_id + ':' + m_tstr; + } - RETURN_EXTRACT_STRING(m_tstr); + RETURN_EXTRACT_STRING(m_tstr); + } break; + case TYPE_FILENAME: { + if(m_fdinfo == NULL) { + return extract_from_null_fd(evt, len, sanitize_strings); } - break; - case TYPE_FILENAME: - { - if(m_fdinfo == NULL) - { - return extract_from_null_fd(evt, len, sanitize_strings); - } - if(!m_fdinfo->is_file()) - { - return NULL; - } + if(!m_fdinfo->is_file()) { + return NULL; + } - m_tstr = m_fdinfo->m_name; - if(sanitize_strings) - { - sanitize_string(m_tstr); - } + m_tstr = m_fdinfo->m_name; + if(sanitize_strings) { + sanitize_string(m_tstr); + } - size_t pos = m_tstr.rfind('/'); - if(pos != string::npos) - { - if(pos < m_tstr.size() - 1) - { - m_tstr = m_tstr.substr(pos + 1, string::npos); - } + size_t pos = m_tstr.rfind('/'); + if(pos != string::npos) { + if(pos < m_tstr.size() - 1) { + m_tstr = m_tstr.substr(pos + 1, string::npos); } - else - { - m_tstr = "/"; - } - - RETURN_EXTRACT_STRING(m_tstr); + } else { + m_tstr = "/"; } - break; + + RETURN_EXTRACT_STRING(m_tstr); + } break; case TYPE_FDTYPECHAR: - if(m_fdinfo == NULL) - { + if(m_fdinfo == NULL) { return extract_from_null_fd(evt, len, sanitize_strings); } @@ -621,797 +755,612 @@ uint8_t* sinsp_filter_check_fd::extract_single(sinsp_evt *evt, uint32_t* len, bo m_tcstr[1] = 0; return m_tcstr; case TYPE_CNET: - case TYPE_CLIENTIP: - { - if(m_fdinfo == NULL) - { - return NULL; - } - - if(m_fdinfo->is_role_none()) - { - return NULL; - } + case TYPE_CLIENTIP: { + if(m_fdinfo == NULL) { + return NULL; + } - scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); - } - else if (evt_type == SCAP_FD_IPV6_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip); - } + if(m_fdinfo->is_role_none()) { + return NULL; } - break; - case TYPE_CLIENTIP_NAME: - { - if(m_fdinfo == NULL) - { - return NULL; - } - if(m_fdinfo->is_role_none()) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip); + } + } break; + case TYPE_CLIENTIP_NAME: { + if(m_fdinfo == NULL) { + return NULL; + } - m_tstr.clear(); - scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, evt->get_ts()); - } - else if (evt_type == SCAP_FD_IPV6_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET6, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0], evt->get_ts()); - } + if(m_fdinfo->is_role_none()) { + return NULL; + } - if(!m_tstr.empty()) - { - RETURN_EXTRACT_STRING(m_tstr); - } + m_tstr.clear(); + scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + evt->get_ts()); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET6, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0], + evt->get_ts()); + } + + if(!m_tstr.empty()) { + RETURN_EXTRACT_STRING(m_tstr); } - break; + } break; case TYPE_SNET: - case TYPE_SERVERIP: - { - if(m_fdinfo == NULL) - { - return NULL; - } - - if(m_fdinfo->is_role_none()) - { - return NULL; - } + case TYPE_SERVERIP: { + if(m_fdinfo == NULL) { + return NULL; + } - scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip); - } - else if(evt_type == SCAP_FD_IPV4_SERVSOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip); - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip); - } - else if(evt_type == SCAP_FD_IPV6_SERVSOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip); - } + if(m_fdinfo->is_role_none()) { + return NULL; } - break; - case TYPE_SERVERIP_NAME: - { - if(m_fdinfo == NULL) - { - return NULL; - } - if(m_fdinfo->is_role_none()) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip); + } else if(evt_type == SCAP_FD_IPV4_SERVSOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip); + } else if(evt_type == SCAP_FD_IPV6_SERVSOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip); + } + } break; + case TYPE_SERVERIP_NAME: { + if(m_fdinfo == NULL) { + return NULL; + } - m_tstr.clear(); - scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, evt->get_ts()); - } - else if(evt_type == SCAP_FD_IPV4_SERVSOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET, &m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip, evt->get_ts()); - } - else if (evt_type == SCAP_FD_IPV6_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET6, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0], evt->get_ts()); - } - else if(evt_type == SCAP_FD_IPV6_SERVSOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET6, &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip.m_b[0], evt->get_ts()); - } + if(m_fdinfo->is_role_none()) { + return NULL; + } - if(!m_tstr.empty()) - { - RETURN_EXTRACT_STRING(m_tstr); - } + m_tstr.clear(); + scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, + evt->get_ts()); + } else if(evt_type == SCAP_FD_IPV4_SERVSOCK) { + m_tstr = sinsp_dns_manager::get().name_of(AF_INET, + &m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip, + evt->get_ts()); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET6, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0], + evt->get_ts()); + } else if(evt_type == SCAP_FD_IPV6_SERVSOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET6, + &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip.m_b[0], + evt->get_ts()); + } + + if(!m_tstr.empty()) { + RETURN_EXTRACT_STRING(m_tstr); } - break; + } break; case TYPE_LNET: case TYPE_RNET: case TYPE_LIP: case TYPE_RIP: case TYPE_LIP_NAME: - case TYPE_RIP_NAME: - { - if(m_fdinfo == NULL) - { - return NULL; - } + case TYPE_RIP_NAME: { + if(m_fdinfo == NULL) { + return NULL; + } - scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type != SCAP_FD_IPV4_SOCK && - evt_type != SCAP_FD_IPV6_SOCK) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type != SCAP_FD_IPV4_SOCK && evt_type != SCAP_FD_IPV6_SOCK) { + return NULL; + } - if(m_fdinfo->is_role_none()) - { - return NULL; - } + if(m_fdinfo->is_role_none()) { + return NULL; + } - /* With local we mean that the client address corresponds to one of our local interfaces */ - bool is_local; + /* With local we mean that the client address corresponds to one of our local interfaces */ + bool is_local; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, m_tinfo); - } - else - { - is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, m_tinfo); - } + if(evt_type == SCAP_FD_IPV4_SOCK) { + is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + m_tinfo); + } else { + is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, + m_tinfo); + } - if(m_field_id != TYPE_LIP_NAME && m_field_id != TYPE_RIP_NAME) - { - if(is_local) - { - if(m_field_id == TYPE_LIP || m_field_id == TYPE_LNET) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip); - } + if(m_field_id != TYPE_LIP_NAME && m_field_id != TYPE_RIP_NAME) { + if(is_local) { + if(m_field_id == TYPE_LIP || m_field_id == TYPE_LNET) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip); } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip); - } + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip); } } - else - { - if(m_field_id == TYPE_LIP || m_field_id == TYPE_LNET) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip); - } + } else { + if(m_field_id == TYPE_LIP || m_field_id == TYPE_LNET) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip); } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip); - } + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip); } } } - else - { - m_tstr.clear(); - if(is_local) - { - if(m_field_id == TYPE_LIP_NAME) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, evt->get_ts()); - } - else - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET6, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0], evt->get_ts()); - } + } else { + m_tstr.clear(); + if(is_local) { + if(m_field_id == TYPE_LIP_NAME) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + evt->get_ts()); + } else { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET6, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0], + evt->get_ts()); } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, evt->get_ts()); - } - else - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET6, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0], evt->get_ts()); - } + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, + evt->get_ts()); + } else { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET6, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0], + evt->get_ts()); } } - else - { - if(m_field_id == TYPE_LIP_NAME) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, evt->get_ts()); - } - else - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET6, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0], evt->get_ts()); - } + } else { + if(m_field_id == TYPE_LIP_NAME) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, + evt->get_ts()); + } else { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET6, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0], + evt->get_ts()); } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, evt->get_ts()); - } - else - { - m_tstr = sinsp_dns_manager::get().name_of(AF_INET6, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0], evt->get_ts()); - } + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + evt->get_ts()); + } else { + m_tstr = sinsp_dns_manager::get().name_of( + AF_INET6, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0], + evt->get_ts()); } } - - if(!m_tstr.empty()) - { - RETURN_EXTRACT_STRING(m_tstr); - } } - } - break; - case TYPE_CLIENTPORT: - { - if(m_fdinfo == NULL) - { - return NULL; + if(!m_tstr.empty()) { + RETURN_EXTRACT_STRING(m_tstr); } + } + } - scap_fd_type evt_type = m_fdinfo->m_type; + break; + case TYPE_CLIENTPORT: { + if(m_fdinfo == NULL) { + return NULL; + } - if(m_fdinfo->is_role_none()) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport); - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport); - } + if(m_fdinfo->is_role_none()) { + return NULL; } - break; - case TYPE_CLIENTPROTO: - { - if(m_fdinfo == NULL) - { - return NULL; - } - scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport); + } + } break; + case TYPE_CLIENTPROTO: { + if(m_fdinfo == NULL) { + return NULL; + } - if(m_fdinfo->is_role_none()) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; - m_tstr = ""; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = port_to_string(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport, this->m_fdinfo->get_l4proto(), m_inspector->is_hostname_and_port_resolution_enabled()); - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - m_tstr = port_to_string(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport, this->m_fdinfo->get_l4proto(), m_inspector->is_hostname_and_port_resolution_enabled()); - } + if(m_fdinfo->is_role_none()) { + return NULL; + } - RETURN_EXTRACT_STRING(m_tstr); + m_tstr = ""; + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = port_to_string(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport, + this->m_fdinfo->get_l4proto(), + m_inspector->is_hostname_and_port_resolution_enabled()); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + m_tstr = port_to_string(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport, + this->m_fdinfo->get_l4proto(), + m_inspector->is_hostname_and_port_resolution_enabled()); } - break; - case TYPE_SERVERPORT: - { - if(m_fdinfo == NULL) - { - return NULL; - } - scap_fd_type evt_type = m_fdinfo->m_type; + RETURN_EXTRACT_STRING(m_tstr); + } break; + case TYPE_SERVERPORT: { + if(m_fdinfo == NULL) { + return NULL; + } - if(evt_type == SCAP_FD_IPV4_SOCK) - { - if(m_fdinfo->is_role_none()) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport); - } - else if(evt_type == SCAP_FD_IPV4_SERVSOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_port); + if(evt_type == SCAP_FD_IPV4_SOCK) { + if(m_fdinfo->is_role_none()) { + return NULL; } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - if(m_fdinfo->is_role_none()) - { - return NULL; - } - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport); - } - else if(evt_type == SCAP_FD_IPV6_SERVSOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_port); - } - else - { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport); + } else if(evt_type == SCAP_FD_IPV4_SERVSOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_port); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + if(m_fdinfo->is_role_none()) { return NULL; } + + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport); + } else if(evt_type == SCAP_FD_IPV6_SERVSOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_port); + } else { + return NULL; + } + } break; + case TYPE_SERVERPROTO: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_SERVERPROTO: - { - if(m_fdinfo == NULL) - { - return NULL; - } - uint16_t nport = 0; + uint16_t nport = 0; - scap_fd_type evt_type = m_fdinfo->m_type; + scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - if(m_fdinfo->is_role_none()) - { - return NULL; - } - nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; - } - else if(evt_type == SCAP_FD_IPV4_SERVSOCK) - { - nport = m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_port; - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - if(m_fdinfo->is_role_none()) - { - return NULL; - } - nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; - } - else if(evt_type == SCAP_FD_IPV6_SERVSOCK) - { - nport = m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_port; - } - else - { + if(evt_type == SCAP_FD_IPV4_SOCK) { + if(m_fdinfo->is_role_none()) { return NULL; } - - m_tstr = ""; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - m_tstr = port_to_string(nport, this->m_fdinfo->get_l4proto(), m_inspector->is_hostname_and_port_resolution_enabled()); - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - m_tstr = port_to_string(nport, this->m_fdinfo->get_l4proto(), m_inspector->is_hostname_and_port_resolution_enabled()); + nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; + } else if(evt_type == SCAP_FD_IPV4_SERVSOCK) { + nport = m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_port; + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + if(m_fdinfo->is_role_none()) { + return NULL; } + nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; + } else if(evt_type == SCAP_FD_IPV6_SERVSOCK) { + nport = m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_port; + } else { + return NULL; + } - RETURN_EXTRACT_STRING(m_tstr); + m_tstr = ""; + if(evt_type == SCAP_FD_IPV4_SOCK) { + m_tstr = port_to_string(nport, + this->m_fdinfo->get_l4proto(), + m_inspector->is_hostname_and_port_resolution_enabled()); + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + m_tstr = port_to_string(nport, + this->m_fdinfo->get_l4proto(), + m_inspector->is_hostname_and_port_resolution_enabled()); } - break; + + RETURN_EXTRACT_STRING(m_tstr); + } break; case TYPE_LPORT: - case TYPE_RPORT: - { - if(m_fdinfo == NULL) - { - return NULL; - } + case TYPE_RPORT: { + if(m_fdinfo == NULL) { + return NULL; + } - scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type != SCAP_FD_IPV4_SOCK && - evt_type != SCAP_FD_IPV6_SOCK) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type != SCAP_FD_IPV4_SOCK && evt_type != SCAP_FD_IPV6_SOCK) { + return NULL; + } - if(m_fdinfo->is_role_none()) - { - return NULL; - } + if(m_fdinfo->is_role_none()) { + return NULL; + } - bool is_local; + bool is_local; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, m_tinfo); - } - else - { - is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, m_tinfo); - } + if(evt_type == SCAP_FD_IPV4_SOCK) { + is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + m_tinfo); + } else { + is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, + m_tinfo); + } - if(is_local) - { - if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport); - } + if(is_local) { + if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport); } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport); - } + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport); } } - else - { - if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport); - } + } else { + if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport); } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport); - } - else - { - RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport); - } + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport); + } else { + RETURN_EXTRACT_VAR(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport); } } } - break; + } break; case TYPE_LPROTO: - case TYPE_RPROTO: - { - if(m_fdinfo == NULL) - { - return NULL; - } + case TYPE_RPROTO: { + if(m_fdinfo == NULL) { + return NULL; + } - scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type != SCAP_FD_IPV4_SOCK && - evt_type != SCAP_FD_IPV6_SOCK) - { - return NULL; - } + scap_fd_type evt_type = m_fdinfo->m_type; + if(evt_type != SCAP_FD_IPV4_SOCK && evt_type != SCAP_FD_IPV6_SOCK) { + return NULL; + } - if(m_fdinfo->is_role_none()) - { - return NULL; - } + if(m_fdinfo->is_role_none()) { + return NULL; + } - int16_t nport = 0; + int16_t nport = 0; - bool is_local; + bool is_local; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, m_tinfo); - } - else - { - is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, m_tinfo); - } + if(evt_type == SCAP_FD_IPV4_SOCK) { + is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + m_tinfo); + } else { + is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, + m_tinfo); + } - if(is_local) - { - if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport; - } - else - { - nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport; - } + if(is_local) { + if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport; + } else { + nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport; } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; - } - else - { - nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; - } + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; + } else { + nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; } } - else - { - if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; - } - else - { - nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; - } + } else { + if(m_field_id == TYPE_LPORT || m_field_id == TYPE_LPROTO) { + if(evt_type == SCAP_FD_IPV4_SOCK) { + nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; + } else { + nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { - nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport; - } - else - { - nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport; - } - + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { + nport = m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport; + } else { + nport = m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport; } } - - m_tstr = port_to_string(nport, this->m_fdinfo->get_l4proto(), m_inspector->is_hostname_and_port_resolution_enabled()); - RETURN_EXTRACT_STRING(m_tstr); } - break; - - case TYPE_L4PROTO: - { - if(m_fdinfo == NULL) - { - return NULL; - } - scap_l4_proto l4p = m_fdinfo->get_l4proto(); - - switch(l4p) - { - case SCAP_L4_TCP: - m_tstr = "tcp"; - break; - case SCAP_L4_UDP: - m_tstr = "udp"; - break; - case SCAP_L4_ICMP: - m_tstr = "icmp"; - break; - case SCAP_L4_RAW: - m_tstr = "raw"; - break; - default: - m_tstr = ""; - break; - } + m_tstr = port_to_string(nport, + this->m_fdinfo->get_l4proto(), + m_inspector->is_hostname_and_port_resolution_enabled()); + RETURN_EXTRACT_STRING(m_tstr); + } break; - RETURN_EXTRACT_STRING(m_tstr); + case TYPE_L4PROTO: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_IS_SERVER: - { - if(m_fdinfo == NULL) - { - return NULL; - } - if(m_fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || m_fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) - { - m_val.u32 = true; - } - else if(m_fdinfo->m_type == SCAP_FD_IPV4_SOCK) - { - m_val.u32 = - m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, m_tinfo); - } - else if(m_fdinfo->m_type == SCAP_FD_IPV6_SOCK) - { - m_val.u32 = - m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip, m_tinfo); - } - else - { - m_val.u32 = false; - } + scap_l4_proto l4p = m_fdinfo->get_l4proto(); - RETURN_EXTRACT_VAR(m_val.u32); + switch(l4p) { + case SCAP_L4_TCP: + m_tstr = "tcp"; + break; + case SCAP_L4_UDP: + m_tstr = "udp"; + break; + case SCAP_L4_ICMP: + m_tstr = "icmp"; + break; + case SCAP_L4_RAW: + m_tstr = "raw"; + break; + default: + m_tstr = ""; + break; } - break; - case TYPE_SOCKFAMILY: - { - if(m_fdinfo == NULL) - { - return NULL; - } - if(m_fdinfo->m_type == SCAP_FD_IPV4_SOCK || m_fdinfo->m_type == SCAP_FD_IPV6_SOCK || - m_fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || m_fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) - { - m_tstr = "ip"; - RETURN_EXTRACT_STRING(m_tstr); - } - else if(m_fdinfo->m_type == SCAP_FD_UNIX_SOCK) - { - m_tstr = "unix"; - RETURN_EXTRACT_STRING(m_tstr); - } - else - { - return NULL; - } + RETURN_EXTRACT_STRING(m_tstr); + } break; + case TYPE_IS_SERVER: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_UID: - { - if(m_tinfo == nullptr) - { - return NULL; - } - m_tstr = to_string(m_tinfo->m_tid) + to_string(m_tinfo->m_lastevent_fd); - RETURN_EXTRACT_STRING(m_tstr); + if(m_fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || m_fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) { + m_val.u32 = true; + } else if(m_fdinfo->m_type == SCAP_FD_IPV4_SOCK) { + m_val.u32 = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, + m_tinfo); + } else if(m_fdinfo->m_type == SCAP_FD_IPV6_SOCK) { + m_val.u32 = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip, + m_tinfo); + } else { + m_val.u32 = false; + } + + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_SOCKFAMILY: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_IS_CONNECTED: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u32 = m_fdinfo->is_socket_connected(); + if(m_fdinfo->m_type == SCAP_FD_IPV4_SOCK || m_fdinfo->m_type == SCAP_FD_IPV6_SOCK || + m_fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK || m_fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) { + m_tstr = "ip"; + RETURN_EXTRACT_STRING(m_tstr); + } else if(m_fdinfo->m_type == SCAP_FD_UNIX_SOCK) { + m_tstr = "unix"; + RETURN_EXTRACT_STRING(m_tstr); + } else { + return NULL; + } + } break; + case TYPE_UID: { + if(m_tinfo == nullptr) { + return NULL; + } - RETURN_EXTRACT_VAR(m_val.u32); + m_tstr = to_string(m_tinfo->m_tid) + to_string(m_tinfo->m_lastevent_fd); + RETURN_EXTRACT_STRING(m_tstr); + } break; + case TYPE_IS_CONNECTED: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_NAME_CHANGED: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u32 = evt->fdinfo_name_changed(); + m_val.u32 = m_fdinfo->is_socket_connected(); - RETURN_EXTRACT_VAR(m_val.u32); + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_NAME_CHANGED: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_DEV: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u32 = m_fdinfo->get_device(); + m_val.u32 = evt->fdinfo_name_changed(); - RETURN_EXTRACT_VAR(m_val.u32); + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_DEV: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_DEV_MAJOR: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u32 = m_fdinfo->get_device_major(); + m_val.u32 = m_fdinfo->get_device(); - RETURN_EXTRACT_VAR(m_val.u32); + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_DEV_MAJOR: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_DEV_MINOR: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u32 = m_fdinfo->get_device_minor(); + m_val.u32 = m_fdinfo->get_device_major(); - RETURN_EXTRACT_VAR(m_val.u32); + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_DEV_MINOR: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_INO: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u64 = m_fdinfo->get_ino(); - RETURN_EXTRACT_VAR(m_val.u64); + m_val.u32 = m_fdinfo->get_device_minor(); + + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_INO: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_FDNAMERAW: - { - if(m_fdinfo == NULL) - { + + m_val.u64 = m_fdinfo->get_ino(); + RETURN_EXTRACT_VAR(m_val.u64); + } break; + case TYPE_FDNAMERAW: { + if(m_fdinfo == NULL) { return extract_from_null_fd(evt, len, sanitize_strings); } m_tstr = m_fdinfo->m_name_raw; remove_duplicate_path_separators(m_tstr); RETURN_EXTRACT_STRING(m_tstr); + } break; + case TYPE_FDUPPER: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_FDUPPER: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u32 = m_fdinfo->is_overlay_upper(); - RETURN_EXTRACT_VAR(m_val.u32); + m_val.u32 = m_fdinfo->is_overlay_upper(); + RETURN_EXTRACT_VAR(m_val.u32); + } break; + case TYPE_FDLOWER: { + if(m_fdinfo == NULL) { + return NULL; } - break; - case TYPE_FDLOWER: - { - if(m_fdinfo == NULL) - { - return NULL; - } - m_val.u32 = m_fdinfo->is_overlay_lower(); - RETURN_EXTRACT_VAR(m_val.u32); - } - break; + m_val.u32 = m_fdinfo->is_overlay_lower(); + RETURN_EXTRACT_VAR(m_val.u32); + } break; default: ASSERT(false); } @@ -1419,87 +1368,80 @@ uint8_t* sinsp_filter_check_fd::extract_single(sinsp_evt *evt, uint32_t* len, bo return NULL; } -bool sinsp_filter_check_fd::compare_ip(sinsp_evt *evt) -{ - if(!extract_fd(evt)) - { +bool sinsp_filter_check_fd::compare_ip(sinsp_evt *evt) { + if(!extract_fd(evt)) { return false; } - if(m_fdinfo != NULL) - { - if(m_cmpop == CO_EXISTS) - { + if(m_fdinfo != NULL) { + if(m_cmpop == CO_EXISTS) { return true; } scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - if(m_cmpop == CO_EQ || m_cmpop == CO_IN) - { - if(compare_rhs(m_cmpop, PT_IPV4ADDR, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip) || - compare_rhs(m_cmpop, PT_IPV4ADDR, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip)) - { + if(evt_type == SCAP_FD_IPV4_SOCK) { + if(m_cmpop == CO_EQ || m_cmpop == CO_IN) { + if(compare_rhs(m_cmpop, + PT_IPV4ADDR, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip) || + compare_rhs(m_cmpop, + PT_IPV4ADDR, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip)) { return true; } - } - else if(m_cmpop == CO_NE) - { - if(compare_rhs(m_cmpop, PT_IPV4ADDR, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip) && - compare_rhs(m_cmpop, PT_IPV4ADDR, &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip)) - { + } else if(m_cmpop == CO_NE) { + if(compare_rhs(m_cmpop, + PT_IPV4ADDR, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip) && + compare_rhs(m_cmpop, + PT_IPV4ADDR, + &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip)) { return true; } - } - else - { - throw sinsp_exception("filter error: IP filter only supports '=' and '!=' operators"); - } - } - else if(evt_type == SCAP_FD_IPV4_SERVSOCK) - { - if(m_cmpop == CO_EQ || m_cmpop == CO_NE || m_cmpop == CO_IN) - { - return compare_rhs(m_cmpop, PT_IPV4ADDR, &m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip); - } - else - { - throw sinsp_exception("filter error: IP filter only supports '=' and '!=' operators"); - } - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { - if(m_cmpop == CO_EQ || m_cmpop == CO_IN) - { - if(compare_rhs(m_cmpop, PT_IPV6ADDR, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip) || - compare_rhs(m_cmpop, PT_IPV6ADDR, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip)) - { + } else { + throw sinsp_exception( + "filter error: IP filter only supports '=' and '!=' operators"); + } + } else if(evt_type == SCAP_FD_IPV4_SERVSOCK) { + if(m_cmpop == CO_EQ || m_cmpop == CO_NE || m_cmpop == CO_IN) { + return compare_rhs(m_cmpop, + PT_IPV4ADDR, + &m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip); + } else { + throw sinsp_exception( + "filter error: IP filter only supports '=' and '!=' operators"); + } + } else if(evt_type == SCAP_FD_IPV6_SOCK) { + if(m_cmpop == CO_EQ || m_cmpop == CO_IN) { + if(compare_rhs(m_cmpop, + PT_IPV6ADDR, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip) || + compare_rhs(m_cmpop, + PT_IPV6ADDR, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip)) { return true; } - } - else if(m_cmpop == CO_NE) - { - if(compare_rhs(m_cmpop, PT_IPV6ADDR, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip) && - compare_rhs(m_cmpop, PT_IPV6ADDR, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip)) - { + } else if(m_cmpop == CO_NE) { + if(compare_rhs(m_cmpop, + PT_IPV6ADDR, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip) && + compare_rhs(m_cmpop, + PT_IPV6ADDR, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip)) { return true; } + } else { + throw sinsp_exception( + "filter error: IP filter only supports '=' and '!=' operators"); } - else - { - throw sinsp_exception("filter error: IP filter only supports '=' and '!=' operators"); - } - } - else if(evt_type == SCAP_FD_IPV6_SERVSOCK) - { - if(m_cmpop == CO_EQ || m_cmpop == CO_NE || m_cmpop == CO_IN) - { - return compare_rhs(m_cmpop, PT_IPV6ADDR, &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip); - } - else - { - throw sinsp_exception("filter error: IP filter only supports '=' and '!=' operators"); + } else if(evt_type == SCAP_FD_IPV6_SERVSOCK) { + if(m_cmpop == CO_EQ || m_cmpop == CO_NE || m_cmpop == CO_IN) { + return compare_rhs(m_cmpop, + PT_IPV6ADDR, + &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip); + } else { + throw sinsp_exception( + "filter error: IP filter only supports '=' and '!=' operators"); } } } @@ -1507,170 +1449,139 @@ bool sinsp_filter_check_fd::compare_ip(sinsp_evt *evt) return false; } -bool sinsp_filter_check_fd::compare_net(sinsp_evt *evt) -{ - if(!extract_fd(evt) || m_fdinfo == nullptr) - { +bool sinsp_filter_check_fd::compare_net(sinsp_evt *evt) { + if(!extract_fd(evt) || m_fdinfo == nullptr) { return false; } - if(m_cmpop == CO_EXISTS) - { + if(m_cmpop == CO_EXISTS) { return true; } bool sip_cmp = false; bool dip_cmp = false; - switch (m_fdinfo->m_type) - { + switch(m_fdinfo->m_type) { case SCAP_FD_IPV4_SERVSOCK: - if (filter_value_len() != sizeof(ipv4net)) - { + if(filter_value_len() != sizeof(ipv4net)) { return m_cmpop == CO_NE; } - return flt_compare_ipv4net(m_cmpop, m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip, (ipv4net*)filter_value_p()); + return flt_compare_ipv4net(m_cmpop, + m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip, + (ipv4net *)filter_value_p()); case SCAP_FD_IPV6_SERVSOCK: - if (filter_value_len() != sizeof(ipv6net)) - { + if(filter_value_len() != sizeof(ipv6net)) { return m_cmpop == CO_NE; } - return flt_compare_ipv6net(m_cmpop, &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip, (ipv6net*)filter_value_p()); + return flt_compare_ipv6net(m_cmpop, + &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip, + (ipv6net *)filter_value_p()); case SCAP_FD_IPV4_SOCK: - if (filter_value_len() != sizeof(ipv4net)) - { + if(filter_value_len() != sizeof(ipv4net)) { return m_cmpop == CO_NE; } - sip_cmp = flt_compare_ipv4net(m_cmpop, m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, (ipv4net*)filter_value_p()); - dip_cmp = flt_compare_ipv4net(m_cmpop, m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, (ipv4net*)filter_value_p()); + sip_cmp = flt_compare_ipv4net(m_cmpop, + m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + (ipv4net *)filter_value_p()); + dip_cmp = flt_compare_ipv4net(m_cmpop, + m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, + (ipv4net *)filter_value_p()); break; case SCAP_FD_IPV6_SOCK: - if (filter_value_len() != sizeof(ipv6net)) - { + if(filter_value_len() != sizeof(ipv6net)) { return m_cmpop == CO_NE; } - sip_cmp = flt_compare_ipv6net(m_cmpop, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, (ipv6net*)filter_value_p()); - dip_cmp = flt_compare_ipv6net(m_cmpop, &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip, (ipv6net*)filter_value_p()); + sip_cmp = flt_compare_ipv6net(m_cmpop, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, + (ipv6net *)filter_value_p()); + dip_cmp = flt_compare_ipv6net(m_cmpop, + &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip, + (ipv6net *)filter_value_p()); break; default: return false; } - if(m_cmpop == CO_EQ || m_cmpop == CO_IN) - { + if(m_cmpop == CO_EQ || m_cmpop == CO_IN) { return sip_cmp || dip_cmp; } - if(m_cmpop == CO_NE) - { + if(m_cmpop == CO_NE) { return sip_cmp && dip_cmp; } return false; } -bool sinsp_filter_check_fd::compare_port(sinsp_evt *evt) -{ - if(!extract_fd(evt)) - { +bool sinsp_filter_check_fd::compare_port(sinsp_evt *evt) { + if(!extract_fd(evt)) { return false; } - if(m_fdinfo != NULL) - { - if(m_cmpop == CO_EXISTS) - { + if(m_fdinfo != NULL) { + if(m_cmpop == CO_EXISTS) { return true; } - - uint16_t* sport; - uint16_t* dport; + + uint16_t *sport; + uint16_t *dport; scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type == SCAP_FD_IPV4_SOCK) - { + if(evt_type == SCAP_FD_IPV4_SOCK) { sport = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport; dport = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport; - } - else if(evt_type == SCAP_FD_IPV4_SERVSOCK) - { + } else if(evt_type == SCAP_FD_IPV4_SERVSOCK) { sport = &m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_port; dport = &m_fdinfo->m_sockinfo.m_ipv4serverinfo.m_port; - } - else if(evt_type == SCAP_FD_IPV6_SOCK) - { + } else if(evt_type == SCAP_FD_IPV6_SOCK) { sport = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport; dport = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport; - } - else if(evt_type == SCAP_FD_IPV6_SERVSOCK) - { + } else if(evt_type == SCAP_FD_IPV6_SERVSOCK) { sport = &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_port; dport = &m_fdinfo->m_sockinfo.m_ipv6serverinfo.m_port; - } - else - { + } else { return false; } - switch(m_cmpop) - { + switch(m_cmpop) { case CO_EQ: - if(*sport == *(uint16_t*)filter_value_p() || - *dport == *(uint16_t*)filter_value_p()) - { + if(*sport == *(uint16_t *)filter_value_p() || *dport == *(uint16_t *)filter_value_p()) { return true; } break; case CO_NE: - if(*sport != *(uint16_t*)filter_value_p() && - *dport != *(uint16_t*)filter_value_p()) - { + if(*sport != *(uint16_t *)filter_value_p() && *dport != *(uint16_t *)filter_value_p()) { return true; } break; case CO_LT: - if(*sport < *(uint16_t*)filter_value_p() || - *dport < *(uint16_t*)filter_value_p()) - { + if(*sport < *(uint16_t *)filter_value_p() || *dport < *(uint16_t *)filter_value_p()) { return true; } break; case CO_LE: - if(*sport <= *(uint16_t*)filter_value_p() || - *dport <= *(uint16_t*)filter_value_p()) - { + if(*sport <= *(uint16_t *)filter_value_p() || *dport <= *(uint16_t *)filter_value_p()) { return true; } break; case CO_GT: - if(*sport > *(uint16_t*)filter_value_p() || - *dport > *(uint16_t*)filter_value_p()) - { + if(*sport > *(uint16_t *)filter_value_p() || *dport > *(uint16_t *)filter_value_p()) { return true; } break; case CO_GE: - if(*sport >= *(uint16_t*)filter_value_p() || - *dport >= *(uint16_t*)filter_value_p()) - { + if(*sport >= *(uint16_t *)filter_value_p() || *dport >= *(uint16_t *)filter_value_p()) { return true; } break; case CO_IN: - if(compare_rhs(m_cmpop, - PT_PORT, - sport, - sizeof(*sport)) || - compare_rhs(m_cmpop, - PT_PORT, - dport, - sizeof(*dport))) - { + if(compare_rhs(m_cmpop, PT_PORT, sport, sizeof(*sport)) || + compare_rhs(m_cmpop, PT_PORT, dport, sizeof(*dport))) { return true; } break; @@ -1682,113 +1593,75 @@ bool sinsp_filter_check_fd::compare_port(sinsp_evt *evt) return false; } -bool sinsp_filter_check_fd::compare_domain(sinsp_evt *evt) -{ - if(!extract_fd(evt)) - { +bool sinsp_filter_check_fd::compare_domain(sinsp_evt *evt) { + if(!extract_fd(evt)) { return false; } - if(m_fdinfo != NULL) - { - if(m_cmpop == CO_EXISTS) - { + if(m_fdinfo != NULL) { + if(m_cmpop == CO_EXISTS) { return true; } - + scap_fd_type evt_type = m_fdinfo->m_type; - if(evt_type != SCAP_FD_IPV4_SOCK && - evt_type != SCAP_FD_IPV6_SOCK) - { + if(evt_type != SCAP_FD_IPV4_SOCK && evt_type != SCAP_FD_IPV6_SOCK) { return false; } - if(m_fdinfo->is_role_none()) - { + if(m_fdinfo->is_role_none()) { return false; } uint32_t *addr; - if(m_field_id == TYPE_CLIENTIP_NAME) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { + if(m_field_id == TYPE_CLIENTIP_NAME) { + if(evt_type == SCAP_FD_IPV4_SOCK) { addr = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip; - } - else - { + } else { addr = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0]; } - } - else if(m_field_id == TYPE_SERVERIP_NAME) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { + } else if(m_field_id == TYPE_SERVERIP_NAME) { + if(evt_type == SCAP_FD_IPV4_SOCK) { addr = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip; - } - else - { + } else { addr = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0]; } - } - else - { + } else { bool is_local; - if(evt_type == SCAP_FD_IPV4_SOCK) - { - is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, m_tinfo); - } - else - { - is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine(m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, m_tinfo); - } - - if(is_local) - { - if(m_field_id == TYPE_LIP_NAME) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { + if(evt_type == SCAP_FD_IPV4_SOCK) { + is_local = m_inspector->get_ifaddr_list().is_ipv4addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + m_tinfo); + } else { + is_local = m_inspector->get_ifaddr_list().is_ipv6addr_in_local_machine( + m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip, + m_tinfo); + } + + if(is_local) { + if(m_field_id == TYPE_LIP_NAME) { + if(evt_type == SCAP_FD_IPV4_SOCK) { addr = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip; - } - else - { + } else { addr = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0]; } - } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { addr = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip; - } - else - { + } else { addr = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0]; } } - } - else - { - if(m_field_id == TYPE_LIP_NAME) - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { + } else { + if(m_field_id == TYPE_LIP_NAME) { + if(evt_type == SCAP_FD_IPV4_SOCK) { addr = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip; - } - else - { + } else { addr = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b[0]; } - } - else - { - if(evt_type == SCAP_FD_IPV4_SOCK) - { + } else { + if(evt_type == SCAP_FD_IPV4_SOCK) { addr = &m_fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip; - } - else - { + } else { addr = &m_fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b[0]; } } @@ -1797,106 +1670,90 @@ bool sinsp_filter_check_fd::compare_domain(sinsp_evt *evt) uint64_t ts = evt->get_ts(); - if(m_cmpop == CO_IN) - { - for (uint16_t i=0; i < m_vals.size(); i++) - { - if(sinsp_dns_manager::get().match((const char *)filter_value_p(i), (evt_type == SCAP_FD_IPV6_SOCK)? AF_INET6 : AF_INET, addr, ts)) - { + if(m_cmpop == CO_IN) { + for(uint16_t i = 0; i < m_vals.size(); i++) { + if(sinsp_dns_manager::get().match( + (const char *)filter_value_p(i), + (evt_type == SCAP_FD_IPV6_SOCK) ? AF_INET6 : AF_INET, + addr, + ts)) { return true; } } return false; - } - else if(m_cmpop == CO_EQ) - { - return sinsp_dns_manager::get().match((const char *)filter_value_p(), (evt_type == SCAP_FD_IPV6_SOCK)? AF_INET6 : AF_INET, addr, ts); - } - else if(m_cmpop == CO_NE) - { - return !sinsp_dns_manager::get().match((const char *)filter_value_p(), (evt_type == SCAP_FD_IPV6_SOCK)? AF_INET6 : AF_INET, addr, ts); - } - else - { - throw sinsp_exception("filter error: fd.*ip.name filter only supports '=' and '!=' operators"); + } else if(m_cmpop == CO_EQ) { + return sinsp_dns_manager::get().match( + (const char *)filter_value_p(), + (evt_type == SCAP_FD_IPV6_SOCK) ? AF_INET6 : AF_INET, + addr, + ts); + } else if(m_cmpop == CO_NE) { + return !sinsp_dns_manager::get().match( + (const char *)filter_value_p(), + (evt_type == SCAP_FD_IPV6_SOCK) ? AF_INET6 : AF_INET, + addr, + ts); + } else { + throw sinsp_exception( + "filter error: fd.*ip.name filter only supports '=' and '!=' operators"); } } return false; } -bool sinsp_filter_check_fd::extract_fd(sinsp_evt *evt) -{ +bool sinsp_filter_check_fd::extract_fd(sinsp_evt *evt) { ppm_event_flags eflags = evt->get_info_flags(); // // Make sure this is an event that creates or consumes an fd // - if(eflags & (EF_CREATES_FD | EF_USES_FD | EF_DESTROYS_FD)) - { + if(eflags & (EF_CREATES_FD | EF_USES_FD | EF_DESTROYS_FD)) { // // This is an fd-related event, get the thread info and the fd info // m_tinfo = evt->get_thread_info(); - if(m_tinfo == NULL) - { + if(m_tinfo == NULL) { return false; } - if (m_argid != -1) - { + if(m_argid != -1) { m_fdinfo = m_tinfo->get_fd(m_argid); - } - else - { + } else { m_fdinfo = evt->get_fd_info(); - if (m_fdinfo == NULL && m_tinfo->m_lastevent_fd != -1) - { + if(m_fdinfo == NULL && m_tinfo->m_lastevent_fd != -1) { m_fdinfo = m_tinfo->get_fd(m_tinfo->m_lastevent_fd); } } // We'll check if fd is null below - } - else - { + } else { return false; } return true; } -bool sinsp_filter_check_fd::compare_nocache(sinsp_evt *evt) -{ +bool sinsp_filter_check_fd::compare_nocache(sinsp_evt *evt) { // // Some fields are filter only and therefore get a special treatment // - if(m_field_id == TYPE_IP) - { + if(m_field_id == TYPE_IP) { return compare_ip(evt); - } - else if(m_field_id == TYPE_PORT || m_field_id == TYPE_PROTO) - { + } else if(m_field_id == TYPE_PORT || m_field_id == TYPE_PROTO) { return compare_port(evt); - } - else if(m_field_id == TYPE_NET) - { + } else if(m_field_id == TYPE_NET) { return compare_net(evt); - } - else if(m_field_id == TYPE_CLIENTIP_NAME || - m_field_id == TYPE_SERVERIP_NAME || - m_field_id == TYPE_LIP_NAME || - m_field_id == TYPE_RIP_NAME) - { + } else if(m_field_id == TYPE_CLIENTIP_NAME || m_field_id == TYPE_SERVERIP_NAME || + m_field_id == TYPE_LIP_NAME || m_field_id == TYPE_RIP_NAME) { m_extracted_values.clear(); - if(!extract(evt, m_extracted_values, false)) - { + if(!extract(evt, m_extracted_values, false)) { return compare_domain(evt); } auto ftype = sinsp_filter_check::get_transformed_field_info()->m_type; return compare_rhs(m_cmpop, ftype, m_extracted_values); } - return sinsp_filter_check::compare_nocache(evt); + return sinsp_filter_check::compare_nocache(evt); } diff --git a/userspace/libsinsp/sinsp_filtercheck_fd.h b/userspace/libsinsp/sinsp_filtercheck_fd.h index 1cc6ee22da..ce83fc1266 100644 --- a/userspace/libsinsp/sinsp_filtercheck_fd.h +++ b/userspace/libsinsp/sinsp_filtercheck_fd.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_fd : public sinsp_filter_check -{ +class sinsp_filter_check_fd : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_FDNUM = 0, TYPE_FDTYPE = 1, TYPE_FDTYPECHAR = 2, @@ -77,23 +75,30 @@ class sinsp_filter_check_fd : public sinsp_filter_check virtual ~sinsp_filter_check_fd() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; protected: - bool extract_nocache(sinsp_evt*, std::vector& values, bool sanitize_strings = true) override; + bool extract_nocache(sinsp_evt*, + std::vector& values, + bool sanitize_strings = true) override; uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; bool compare_nocache(sinsp_evt*) override; private: int32_t extract_arg(std::string_view fldname, std::string_view val); - uint8_t* extract_from_null_fd(sinsp_evt *evt, uint32_t* len, bool sanitize_strings); - bool extract_fdname_from_creator(sinsp_evt *evt, uint32_t* len, bool sanitize_strings, bool fd_nameraw = false); - bool extract_fd(sinsp_evt *evt); + uint8_t* extract_from_null_fd(sinsp_evt* evt, uint32_t* len, bool sanitize_strings); + bool extract_fdname_from_creator(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings, + bool fd_nameraw = false); + bool extract_fd(sinsp_evt* evt); - bool compare_ip(sinsp_evt *evt); - bool compare_net(sinsp_evt *evt); - bool compare_port(sinsp_evt *evt); - bool compare_domain(sinsp_evt *evt); + bool compare_ip(sinsp_evt* evt); + bool compare_net(sinsp_evt* evt); + bool compare_port(sinsp_evt* evt); + bool compare_domain(sinsp_evt* evt); sinsp_threadinfo* m_tinfo; sinsp_fdinfo* m_fdinfo; diff --git a/userspace/libsinsp/sinsp_filtercheck_fdlist.cpp b/userspace/libsinsp/sinsp_filtercheck_fdlist.cpp index 9c48d2294d..785fab234a 100644 --- a/userspace/libsinsp/sinsp_filtercheck_fdlist.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_fdlist.cpp @@ -22,172 +22,186 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -static const filtercheck_field_info sinsp_filter_check_fdlist_fields[] = -{ - {PT_CHARBUF, EPF_NONE, PF_ID, "fdlist.nums", "FD Numbers", "for poll events, this is a comma-separated list of the FD numbers in the 'fds' argument, returned as a string."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fdlist.names", "FD Names", "for poll events, this is a comma-separated list of the FD names in the 'fds' argument, returned as a string."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fdlist.cips", "FD Client Addresses", "for poll events, this is a comma-separated list of the client IP addresses in the 'fds' argument, returned as a string."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fdlist.sips", "FD Source Addresses", "for poll events, this is a comma-separated list of the server IP addresses in the 'fds' argument, returned as a string."}, - {PT_CHARBUF, EPF_NONE, PF_DEC, "fdlist.cports", "FD Client Ports", "for TCP/UDP FDs, for poll events, this is a comma-separated list of the client TCP/UDP ports in the 'fds' argument, returned as a string."}, - {PT_CHARBUF, EPF_NONE, PF_DEC, "fdlist.sports", "FD Source Ports", "for poll events, this is a comma-separated list of the server TCP/UDP ports in the 'fds' argument, returned as a string."}, +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t *)(x).c_str(); \ + } while(0) + +static const filtercheck_field_info sinsp_filter_check_fdlist_fields[] = { + {PT_CHARBUF, + EPF_NONE, + PF_ID, + "fdlist.nums", + "FD Numbers", + "for poll events, this is a comma-separated list of the FD numbers in the 'fds' argument, " + "returned as a string."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fdlist.names", + "FD Names", + "for poll events, this is a comma-separated list of the FD names in the 'fds' argument, " + "returned as a string."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fdlist.cips", + "FD Client Addresses", + "for poll events, this is a comma-separated list of the client IP addresses in the 'fds' " + "argument, returned as a string."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fdlist.sips", + "FD Source Addresses", + "for poll events, this is a comma-separated list of the server IP addresses in the 'fds' " + "argument, returned as a string."}, + {PT_CHARBUF, + EPF_NONE, + PF_DEC, + "fdlist.cports", + "FD Client Ports", + "for TCP/UDP FDs, for poll events, this is a comma-separated list of the client TCP/UDP " + "ports in the 'fds' argument, returned as a string."}, + {PT_CHARBUF, + EPF_NONE, + PF_DEC, + "fdlist.sports", + "FD Source Ports", + "for poll events, this is a comma-separated list of the server TCP/UDP ports in the 'fds' " + "argument, returned as a string."}, }; -sinsp_filter_check_fdlist::sinsp_filter_check_fdlist() -{ +sinsp_filter_check_fdlist::sinsp_filter_check_fdlist() { static const filter_check_info s_field_infos = { - "fdlist", - "", - "Poll event related fields.", - sizeof(sinsp_filter_check_fdlist_fields) / sizeof(sinsp_filter_check_fdlist_fields[0]), - sinsp_filter_check_fdlist_fields, - filter_check_info::FL_NONE, + "fdlist", + "", + "Poll event related fields.", + sizeof(sinsp_filter_check_fdlist_fields) / sizeof(sinsp_filter_check_fdlist_fields[0]), + sinsp_filter_check_fdlist_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; } -std::unique_ptr sinsp_filter_check_fdlist::allocate_new() -{ +std::unique_ptr sinsp_filter_check_fdlist::allocate_new() { return std::make_unique(); } -uint8_t* sinsp_filter_check_fdlist::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t *sinsp_filter_check_fdlist::extract_single(sinsp_evt *evt, + uint32_t *len, + bool sanitize_strings) { *len = 0; ASSERT(evt); const sinsp_evt_param *parinfo; uint16_t etype = evt->get_type(); - if(etype == PPME_SYSCALL_POLL_E || etype == PPME_SYSCALL_PPOLL_E) - { + if(etype == PPME_SYSCALL_POLL_E || etype == PPME_SYSCALL_PPOLL_E) { parinfo = evt->get_param(0); - } - else if(etype == PPME_SYSCALL_POLL_X || etype == PPME_SYSCALL_PPOLL_X) - { + } else if(etype == PPME_SYSCALL_POLL_X || etype == PPME_SYSCALL_PPOLL_X) { parinfo = evt->get_param(1); - } - else - { + } else { return NULL; } uint32_t j = 0; - const char* payload = parinfo->m_val; + const char *payload = parinfo->m_val; uint16_t nfds = *(uint16_t *)payload; uint32_t pos = 2; - sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(!tinfo) - { + sinsp_threadinfo *tinfo = evt->get_thread_info(); + if(!tinfo) { return NULL; } m_strval.clear(); - for(j = 0; j < nfds; j++) - { + for(j = 0; j < nfds; j++) { bool add_comma = true; int64_t fd = *(int64_t *)(payload + pos); sinsp_fdinfo *fdinfo = tinfo ? tinfo->get_fd(fd) : NULL; - switch(m_field_id) - { - case TYPE_FDNUMS: - { + switch(m_field_id) { + case TYPE_FDNUMS: { m_strval += to_string(fd); - } - break; - case TYPE_FDNAMES: - { - if(fdinfo != NULL) - { - if(fdinfo->m_name != "") - { + } break; + case TYPE_FDNAMES: { + if(fdinfo != NULL) { + if(fdinfo->m_name != "") { m_strval += fdinfo->m_name; - } - else - { + } else { m_strval += ""; } - } - else - { + } else { m_strval += ""; } - } - break; - case TYPE_CLIENTIPS: - { - if(fdinfo != NULL) - { + } break; + case TYPE_CLIENTIPS: { + if(fdinfo != NULL) { char m_addrbuff[100]; - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) - { - inet_ntop(AF_INET, &fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, m_addrbuff, sizeof(m_addrbuff)); + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) { + inet_ntop(AF_INET, + &fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip, + m_addrbuff, + sizeof(m_addrbuff)); m_strval += m_addrbuff; break; - } - else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) - { - inet_ntop(AF_INET6, fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b, m_addrbuff, sizeof(m_addrbuff)); + } else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) { + inet_ntop(AF_INET6, + fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b, + m_addrbuff, + sizeof(m_addrbuff)); m_strval += m_addrbuff; break; } } add_comma = false; - } - break; - case TYPE_SERVERIPS: - { - if(fdinfo != NULL) - { + } break; + case TYPE_SERVERIPS: { + if(fdinfo != NULL) { char m_addrbuff[100]; - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) - { - inet_ntop(AF_INET, &fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, m_addrbuff, sizeof(m_addrbuff)); + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) { + inet_ntop(AF_INET, + &fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dip, + m_addrbuff, + sizeof(m_addrbuff)); m_strval += m_addrbuff; break; - } - else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) - { - inet_ntop(AF_INET6, fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b, m_addrbuff, sizeof(m_addrbuff)); + } else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) { + inet_ntop(AF_INET6, + fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b, + m_addrbuff, + sizeof(m_addrbuff)); m_strval += m_addrbuff; break; - } - else if(fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK) - { - inet_ntop(AF_INET, &fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip, m_addrbuff, sizeof(m_addrbuff)); + } else if(fdinfo->m_type == SCAP_FD_IPV4_SERVSOCK) { + inet_ntop(AF_INET, + &fdinfo->m_sockinfo.m_ipv4serverinfo.m_ip, + m_addrbuff, + sizeof(m_addrbuff)); m_strval += m_addrbuff; break; - } - else if(fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) - { - inet_ntop(AF_INET, &fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip.m_b, m_addrbuff, sizeof(m_addrbuff)); + } else if(fdinfo->m_type == SCAP_FD_IPV6_SERVSOCK) { + inet_ntop(AF_INET, + &fdinfo->m_sockinfo.m_ipv6serverinfo.m_ip.m_b, + m_addrbuff, + sizeof(m_addrbuff)); m_strval += m_addrbuff; break; } } add_comma = false; - } - break; - case TYPE_CLIENTPORTS: - { - if(fdinfo != NULL) - { - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) - { + } break; + case TYPE_CLIENTPORTS: { + if(fdinfo != NULL) { + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) { m_strval += to_string(fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport); break; - } - else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) - { + } else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) { m_strval += to_string(fdinfo->m_sockinfo.m_ipv6info.m_fields.m_sport); break; } @@ -195,48 +209,37 @@ uint8_t* sinsp_filter_check_fdlist::extract_single(sinsp_evt *evt, uint32_t* len add_comma = false; } - case TYPE_SERVERPORTS: - { - if(fdinfo != NULL) - { - if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) - { + case TYPE_SERVERPORTS: { + if(fdinfo != NULL) { + if(fdinfo->m_type == SCAP_FD_IPV4_SOCK) { m_strval += to_string(fdinfo->m_sockinfo.m_ipv4info.m_fields.m_dport); break; - } - else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) - { + } else if(fdinfo->m_type == SCAP_FD_IPV6_SOCK) { m_strval += to_string(fdinfo->m_sockinfo.m_ipv6info.m_fields.m_dport); break; } } add_comma = false; - } - break; + } break; default: ASSERT(false); } - if(j < nfds && add_comma) - { + if(j < nfds && add_comma) { m_strval += ","; } pos += 10; } - if(m_strval.size() != 0) - { - if(m_strval.back() == ',') - { + if(m_strval.size() != 0) { + if(m_strval.back() == ',') { m_strval = m_strval.substr(0, m_strval.size() - 1); } RETURN_EXTRACT_STRING(m_strval); - } - else - { + } else { return NULL; } } diff --git a/userspace/libsinsp/sinsp_filtercheck_fdlist.h b/userspace/libsinsp/sinsp_filtercheck_fdlist.h index 3c9c5deee0..144030baac 100644 --- a/userspace/libsinsp/sinsp_filtercheck_fdlist.h +++ b/userspace/libsinsp/sinsp_filtercheck_fdlist.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_fdlist : public sinsp_filter_check -{ +class sinsp_filter_check_fdlist : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_FDNUMS = 0, TYPE_FDNAMES = 1, TYPE_CLIENTIPS = 2, diff --git a/userspace/libsinsp/sinsp_filtercheck_fspath.cpp b/userspace/libsinsp/sinsp_filtercheck_fspath.cpp index 909b643679..b28d7b7d13 100644 --- a/userspace/libsinsp/sinsp_filtercheck_fspath.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_fspath.cpp @@ -25,45 +25,88 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -static const filtercheck_field_info sinsp_filter_check_fspath_fields[] = - { - {PT_CHARBUF, EPF_NONE, PF_NA, "fs.path.name", "Path for Filesystem-related operation", "For any event type that deals with a filesystem path, the path the file syscall is operating on. This path is always fully resolved, prepending the thread cwd when needed."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fs.path.nameraw", "Raw path for Filesystem-related operation", "For any event type that deals with a filesystem path, the path the file syscall is operating on. This path is always the path provided to the syscall and may not be fully resolved."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fs.path.source", "Source path for Filesystem-related operation", "For any event type that deals with a filesystem path, and specifically for a source and target like mv, cp, etc, the source path the file syscall is operating on. This path is always fully resolved, prepending the thread cwd when needed."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fs.path.sourceraw", "Source path for Filesystem-related operation", "For any event type that deals with a filesystem path, and specifically for a source and target like mv, cp, etc, the source path the file syscall is operating on. This path is always the path provided to the syscall and may not be fully resolved."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fs.path.target", "Target path for Filesystem-related operation", "For any event type that deals with a filesystem path, and specifically for a target and target like mv, cp, etc, the target path the file syscall is operating on. This path is always fully resolved, prepending the thread cwd when needed."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "fs.path.targetraw", "Target path for Filesystem-related operation", "For any event type that deals with a filesystem path, and specifically for a target and target like mv, cp, etc, the target path the file syscall is operating on. This path is always the path provided to the syscall and may not be fully resolved."}, +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) + +static const filtercheck_field_info sinsp_filter_check_fspath_fields[] = { + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fs.path.name", + "Path for Filesystem-related operation", + "For any event type that deals with a filesystem path, the path the file syscall is " + "operating on. This path is always fully resolved, prepending the thread cwd when " + "needed."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fs.path.nameraw", + "Raw path for Filesystem-related operation", + "For any event type that deals with a filesystem path, the path the file syscall is " + "operating on. This path is always the path provided to the syscall and may not be fully " + "resolved."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fs.path.source", + "Source path for Filesystem-related operation", + "For any event type that deals with a filesystem path, and specifically for a source and " + "target like mv, cp, etc, the source path the file syscall is operating on. This path is " + "always fully resolved, prepending the thread cwd when needed."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fs.path.sourceraw", + "Source path for Filesystem-related operation", + "For any event type that deals with a filesystem path, and specifically for a source and " + "target like mv, cp, etc, the source path the file syscall is operating on. This path is " + "always the path provided to the syscall and may not be fully resolved."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fs.path.target", + "Target path for Filesystem-related operation", + "For any event type that deals with a filesystem path, and specifically for a target and " + "target like mv, cp, etc, the target path the file syscall is operating on. This path is " + "always fully resolved, prepending the thread cwd when needed."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "fs.path.targetraw", + "Target path for Filesystem-related operation", + "For any event type that deals with a filesystem path, and specifically for a target and " + "target like mv, cp, etc, the target path the file syscall is operating on. This path is " + "always the path provided to the syscall and may not be fully resolved."}, }; sinsp_filter_check_fspath::sinsp_filter_check_fspath() - // These will either be populated when calling - // create_fspath_checks or copied from another filtercheck - // when calling set_fspath_checks(). - : m_success_checks(std::make_shared()), - m_path_checks(std::make_shared()), - m_source_checks(std::make_shared()), - m_target_checks(std::make_shared()) -{ + // These will either be populated when calling + // create_fspath_checks or copied from another filtercheck + // when calling set_fspath_checks(). + : + m_success_checks(std::make_shared()), + m_path_checks(std::make_shared()), + m_source_checks(std::make_shared()), + m_target_checks(std::make_shared()) { static const filter_check_info s_field_infos = { - "fs.path", - "", - "Every syscall that has a filesystem path in its arguments has these fields set with information related to the path arguments. This differs from the fd.* fields as it includes syscalls like unlink, rename, etc. that act directly on filesystem paths as compared to opened file descriptors.", - sizeof(sinsp_filter_check_fspath_fields) / sizeof(sinsp_filter_check_fspath_fields[0]), - sinsp_filter_check_fspath_fields, - filter_check_info::FL_NONE, + "fs.path", + "", + "Every syscall that has a filesystem path in its arguments has these fields set with " + "information related to the path arguments. This differs from the fd.* fields as it " + "includes syscalls like unlink, rename, etc. that act directly on filesystem paths as " + "compared to opened file descriptors.", + sizeof(sinsp_filter_check_fspath_fields) / sizeof(sinsp_filter_check_fspath_fields[0]), + sinsp_filter_check_fspath_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; }; -std::shared_ptr sinsp_filter_check_fspath::create_event_check(const char *name, - cmpop cop, - const char *value) -{ +std::shared_ptr +sinsp_filter_check_fspath::create_event_check(const char* name, cmpop cop, const char* value) { auto chk = std::make_shared(); chk->m_inspector = m_inspector; @@ -71,16 +114,14 @@ std::shared_ptr sinsp_filter_check_fspath::create_event_chec chk->m_boolop = BO_NONE; chk->parse_field_name(name, true, true); - if(value) - { + if(value) { chk->add_filter_value(value, strlen(value), 0); } return chk; } -std::shared_ptr sinsp_filter_check_fspath::create_fd_check(const char *name) -{ +std::shared_ptr sinsp_filter_check_fspath::create_fd_check(const char* name) { auto chk = std::make_shared(); chk->m_inspector = m_inspector; @@ -91,19 +132,23 @@ std::shared_ptr sinsp_filter_check_fspath::create_fd_check(c return chk; } -void sinsp_filter_check_fspath::create_fspath_checks() -{ +void sinsp_filter_check_fspath::create_fspath_checks() { std::shared_ptr evt_arg_path = create_event_check("evt.rawarg.path"); - std::shared_ptr evt_arg_pathname = create_event_check("evt.rawarg.pathname"); - std::shared_ptr evt_arg_res_eq_0 = create_event_check("evt.rawarg.res", CO_EQ, "0"); + std::shared_ptr evt_arg_pathname = + create_event_check("evt.rawarg.pathname"); + std::shared_ptr evt_arg_res_eq_0 = + create_event_check("evt.rawarg.res", CO_EQ, "0"); std::shared_ptr evt_arg_name = create_event_check("evt.rawarg.name"); std::shared_ptr evt_fd_name = create_fd_check("fd.name"); - std::shared_ptr evt_arg_fd_ne_neg1 = create_event_check("evt.rawarg.fd", CO_NE, "-1"); + std::shared_ptr evt_arg_fd_ne_neg1 = + create_event_check("evt.rawarg.fd", CO_NE, "-1"); std::shared_ptr evt_arg_oldpath = create_event_check("evt.rawarg.oldpath"); std::shared_ptr evt_arg_newpath = create_event_check("evt.rawarg.newpath"); - std::shared_ptr evt_arg_linkpath = create_event_check("evt.rawarg.linkpath"); + std::shared_ptr evt_arg_linkpath = + create_event_check("evt.rawarg.linkpath"); std::shared_ptr evt_arg_target = create_event_check("evt.rawarg.target"); - std::shared_ptr evt_arg_filename = create_event_check("evt.rawarg.filename"); + std::shared_ptr evt_arg_filename = + create_event_check("evt.rawarg.filename"); std::shared_ptr evt_arg_special = create_event_check("evt.rawarg.special"); std::shared_ptr evt_arg_dev = create_event_check("evt.rawarg.dev"); std::shared_ptr evt_arg_dir = create_event_check("evt.rawarg.dir"); @@ -212,24 +257,22 @@ void sinsp_filter_check_fspath::create_fspath_checks() m_success_checks->emplace(PPME_SYSCALL_UMOUNT2_X, evt_arg_res_eq_0); } -void sinsp_filter_check_fspath::set_fspath_checks(const std::shared_ptr& success_checks, - const std::shared_ptr& path_checks, - const std::shared_ptr& source_checks, - const std::shared_ptr& target_checks) -{ +void sinsp_filter_check_fspath::set_fspath_checks( + const std::shared_ptr& success_checks, + const std::shared_ptr& path_checks, + const std::shared_ptr& source_checks, + const std::shared_ptr& target_checks) { m_success_checks = success_checks; m_path_checks = path_checks; m_source_checks = source_checks; m_target_checks = target_checks; } -std::unique_ptr sinsp_filter_check_fspath::allocate_new() -{ +std::unique_ptr sinsp_filter_check_fspath::allocate_new() { // If not yet populated, do so now. The maps will be empty // *only* for the initial filtercheck created in // filter_check_list. - if(m_path_checks->empty()) - { + if(m_path_checks->empty()) { create_fspath_checks(); } @@ -240,54 +283,47 @@ std::unique_ptr sinsp_filter_check_fspath::allocate_new() return ret; } - // Similar to sinsp_parser::parse_dirfd(). // Makes only sense when called against a directory fdinfo. -static inline std::string format_dirfd(sinsp_evt* evt) -{ +static inline std::string format_dirfd(sinsp_evt* evt) { auto fd_info_dirfd = evt->get_fd_info(); - if(!fd_info_dirfd || !fd_info_dirfd->is_directory()) - { + if(!fd_info_dirfd || !fd_info_dirfd->is_directory()) { return ""; } - if(fd_info_dirfd->m_name.back() == '/') - { + if(fd_info_dirfd->m_name.back() == '/') { return fd_info_dirfd->m_name; } return fd_info_dirfd->m_name + '/'; } -uint8_t* sinsp_filter_check_fspath::extract_single(sinsp_evt* evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_fspath::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; ASSERT(evt); // First check the success conditions. auto it = m_success_checks->find(evt->get_type()); - if(it == m_success_checks->end() || !it->second->compare(evt)) - { + if(it == m_success_checks->end() || !it->second->compare(evt)) { return NULL; } std::optional> enter_param; std::vector extract_values; - switch(m_field_id) - { + switch(m_field_id) { case TYPE_NAME: case TYPE_NAMERAW: // For some event types we need to get the values from the enter event instead. - switch(evt->get_type()) - { + switch(evt->get_type()) { case PPME_SYSCALL_MKDIR_X: case PPME_SYSCALL_RMDIR_X: case PPME_SYSCALL_UNLINK_X: enter_param = evt->get_enter_evt_param("path"); - if(!enter_param.has_value()) - { + if(!enter_param.has_value()) { return NULL; } m_tstr = enter_param.value(); @@ -295,64 +331,59 @@ uint8_t* sinsp_filter_check_fspath::extract_single(sinsp_evt* evt, uint32_t* len case PPME_SYSCALL_UNLINKAT_X: case PPME_SYSCALL_OPENAT_X: enter_param = evt->get_enter_evt_param("name"); - if(!enter_param.has_value()) - { + if(!enter_param.has_value()) { return NULL; } m_tstr = enter_param.value(); break; default: - if (!extract_fspath(evt, extract_values, m_path_checks)) - { + if(!extract_fspath(evt, extract_values, m_path_checks)) { return NULL; } - m_tstr.assign((const char*) extract_values[0].ptr, strnlen((const char*) extract_values[0].ptr, extract_values[0].len)); + m_tstr.assign((const char*)extract_values[0].ptr, + strnlen((const char*)extract_values[0].ptr, extract_values[0].len)); }; break; case TYPE_SOURCE: case TYPE_SOURCERAW: // For some event types we need to get the values from the enter event instead. - switch(evt->get_type()) - { + switch(evt->get_type()) { case PPME_SYSCALL_LINK_X: case PPME_SYSCALL_LINKAT_X: enter_param = evt->get_enter_evt_param("newpath"); - if(!enter_param.has_value()) - { + if(!enter_param.has_value()) { return NULL; } m_tstr = enter_param.value(); break; default: - if(!extract_fspath(evt, extract_values, m_source_checks)) - { + if(!extract_fspath(evt, extract_values, m_source_checks)) { return NULL; } - m_tstr.assign((const char*) extract_values[0].ptr, strnlen((const char*) extract_values[0].ptr, extract_values[0].len)); + m_tstr.assign((const char*)extract_values[0].ptr, + strnlen((const char*)extract_values[0].ptr, extract_values[0].len)); }; break; case TYPE_TARGET: case TYPE_TARGETRAW: // For some event types we need to get the values from the enter event instead. - switch(evt->get_type()) - { + switch(evt->get_type()) { case PPME_SYSCALL_LINK_X: case PPME_SYSCALL_LINKAT_X: enter_param = evt->get_enter_evt_param("oldpath"); - if(!enter_param.has_value()) - { + if(!enter_param.has_value()) { return NULL; } m_tstr = enter_param.value(); break; default: - if (!extract_fspath(evt, extract_values, m_target_checks)) - { + if(!extract_fspath(evt, extract_values, m_target_checks)) { return NULL; } - m_tstr.assign((const char*) extract_values[0].ptr, strnlen((const char*) extract_values[0].ptr, extract_values[0].len)); + m_tstr.assign((const char*)extract_values[0].ptr, + strnlen((const char*)extract_values[0].ptr, extract_values[0].len)); }; break; default: @@ -361,110 +392,91 @@ uint8_t* sinsp_filter_check_fspath::extract_single(sinsp_evt* evt, uint32_t* len // For the non-raw fields, if the path is not absolute, // prepend the cwd of the threadinfo or the dirfd to the path. - if((m_field_id == TYPE_NAME || - m_field_id == TYPE_SOURCE || - m_field_id == TYPE_TARGET)) - { + if((m_field_id == TYPE_NAME || m_field_id == TYPE_SOURCE || m_field_id == TYPE_TARGET)) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return NULL; } - if(!std::filesystem::path(m_tstr).is_absolute()) - { - std::string sdir; // init + if(!std::filesystem::path(m_tstr).is_absolute()) { + std::string sdir; // init // Compare to `sinsp_filter_check_fd::extract_fdname_from_creator` logic // note: no implementation for old / legacy event definitions - switch(evt->get_type()) - { - // For openat, event fdinfo is already correctly expanded by parsers; - // See sinsp_parser::parse_open_openat_creat_exit(). - case PPME_SYSCALL_OPENAT_2_X: - case PPME_SYSCALL_OPENAT2_X: - { - sdir = ""; - auto fdinfo = evt->get_fd_info(); - if (fdinfo != nullptr) - { - m_tstr = evt->get_fd_info()->m_name; - } - else - { - m_tstr = ""; - } - break; + switch(evt->get_type()) { + // For openat, event fdinfo is already correctly expanded by parsers; + // See sinsp_parser::parse_open_openat_creat_exit(). + case PPME_SYSCALL_OPENAT_2_X: + case PPME_SYSCALL_OPENAT2_X: { + sdir = ""; + auto fdinfo = evt->get_fd_info(); + if(fdinfo != nullptr) { + m_tstr = evt->get_fd_info()->m_name; + } else { + m_tstr = ""; } - // For the following syscalls, the event fdinfo is set to their dirfd. - // Set `sdir` to the dirfd info path. - case PPME_SYSCALL_NEWFSTATAT_X: - case PPME_SYSCALL_FCHOWNAT_X: - case PPME_SYSCALL_FCHMODAT_X: - case PPME_SYSCALL_MKDIRAT_X: - case PPME_SYSCALL_UNLINKAT_2_X: - case PPME_SYSCALL_MKNODAT_X: + break; + } + // For the following syscalls, the event fdinfo is set to their dirfd. + // Set `sdir` to the dirfd info path. + case PPME_SYSCALL_NEWFSTATAT_X: + case PPME_SYSCALL_FCHOWNAT_X: + case PPME_SYSCALL_FCHMODAT_X: + case PPME_SYSCALL_MKDIRAT_X: + case PPME_SYSCALL_UNLINKAT_2_X: + case PPME_SYSCALL_MKNODAT_X: + sdir = format_dirfd(evt); + break; + case PPME_SYSCALL_SYMLINKAT_X: // linkdirfd + { + if(m_field_id == TYPE_SOURCE) { sdir = format_dirfd(evt); - break; - case PPME_SYSCALL_SYMLINKAT_X: // linkdirfd - { - if (m_field_id == TYPE_SOURCE) - { - sdir = format_dirfd(evt); - } - else - { - sdir = ""; - } - break; + } else { + sdir = ""; } - case PPME_SYSCALL_RENAMEAT2_X: - { - // newdirfd or olddirfd, we need to extract the dirfd on the fly here - int64_t dirfd; - if (m_field_id == TYPE_TARGET) - { - // newdirfd - dirfd = evt->get_param(3)->as(); - sdir = m_inspector->get_parser()->parse_dirfd(evt, m_tstr, dirfd); - } - else if (m_field_id == TYPE_SOURCE) - { - // olddirfd - dirfd = evt->get_param(1)->as(); - sdir = m_inspector->get_parser()->parse_dirfd(evt, m_tstr, dirfd); - } - else - { - sdir = ""; - } - break; + break; + } + case PPME_SYSCALL_RENAMEAT2_X: { + // newdirfd or olddirfd, we need to extract the dirfd on the fly here + int64_t dirfd; + if(m_field_id == TYPE_TARGET) { + // newdirfd + dirfd = evt->get_param(3)->as(); + sdir = m_inspector->get_parser()->parse_dirfd(evt, m_tstr, dirfd); + } else if(m_field_id == TYPE_SOURCE) { + // olddirfd + dirfd = evt->get_param(1)->as(); + sdir = m_inspector->get_parser()->parse_dirfd(evt, m_tstr, dirfd); + } else { + sdir = ""; } - default: // assign cwd as sdir - sdir = tinfo->get_cwd(); - break; + break; + } + default: // assign cwd as sdir + sdir = tinfo->get_cwd(); + break; } /* Note on what `sdir` is: - * - the pathname is absolute: - * sdir = "." after running `parse_dirfd_stateless` - * or sdir = "" - * - the pathname is relative: - * - if `dirfd` is `PPM_AT_FDCWD` -> sdir = cwd. - * - if no `dirfd` is applicable for the syscall at hand -> sdir = cwd - * - if `dirfd` is applicable, but we have no information about `dirfd` -> sdir = "". - * - if `dirfd` is applicable and if `dirfd` has a valid value for us -> sdir = path + "/" at the end. - */ - + * - the pathname is absolute: + * sdir = "." after running `parse_dirfd_stateless` + * or sdir = "" + * - the pathname is relative: + * - if `dirfd` is `PPM_AT_FDCWD` -> sdir = cwd. + * - if no `dirfd` is applicable for the syscall at hand -> sdir = cwd + * - if `dirfd` is applicable, but we have no information about `dirfd` -> sdir = + *"". + * - if `dirfd` is applicable and if `dirfd` has a valid value for us -> sdir = path + + *"/" at the end. + */ + m_tstr = sinsp_utils::concatenate_paths(sdir, m_tstr); - } - else - { + } else { /* Note about `concatenate_paths` - * It takes care of resolving the path and as such needed even if sdir is empty - * or if the path is absolute in order to for example resolve paths similar to - * /tmp/dir1/dir2/dir3/../../../..///file.txt - */ + * It takes care of resolving the path and as such needed even if sdir is empty + * or if the path is absolute in order to for example resolve paths similar to + * /tmp/dir1/dir2/dir3/../../../..///file.txt + */ m_tstr = sinsp_utils::concatenate_paths("", m_tstr); } } @@ -473,20 +485,16 @@ uint8_t* sinsp_filter_check_fspath::extract_single(sinsp_evt* evt, uint32_t* len } bool sinsp_filter_check_fspath::extract_fspath(sinsp_evt* evt, - std::vector& values, - const std::shared_ptr& checks) -{ + std::vector& values, + const std::shared_ptr& checks) { sinsp_evt* extract_evt = evt; auto it = checks->find(extract_evt->get_type()); - if(it == checks->end()) - { + if(it == checks->end()) { return false; } - if(!it->second->extract(extract_evt, values, true) || - values.size() != 1) - { + if(!it->second->extract(extract_evt, values, true) || values.size() != 1) { return false; } diff --git a/userspace/libsinsp/sinsp_filtercheck_fspath.h b/userspace/libsinsp/sinsp_filtercheck_fspath.h index a38584e6fc..8a32b25835 100644 --- a/userspace/libsinsp/sinsp_filtercheck_fspath.h +++ b/userspace/libsinsp/sinsp_filtercheck_fspath.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_fspath : public sinsp_filter_check -{ +class sinsp_filter_check_fspath : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_NAME = 0, TYPE_NAMERAW = 1, TYPE_SOURCE = 2, @@ -44,20 +42,20 @@ class sinsp_filter_check_fspath : public sinsp_filter_check private: typedef std::map> filtercheck_map_t; - std::shared_ptr create_event_check(const char *name, - cmpop cop = CO_NONE, - const char *value = NULL); + std::shared_ptr create_event_check(const char* name, + cmpop cop = CO_NONE, + const char* value = NULL); - std::shared_ptr create_fd_check(const char *name); + std::shared_ptr create_fd_check(const char* name); void create_fspath_checks(); void set_fspath_checks(const std::shared_ptr& success_checks, - const std::shared_ptr& path_checks, - const std::shared_ptr& source_checks, - const std::shared_ptr& target_checks); + const std::shared_ptr& path_checks, + const std::shared_ptr& source_checks, + const std::shared_ptr& target_checks); bool extract_fspath(sinsp_evt* evt, - std::vector& values, - const std::shared_ptr& map); + std::vector& values, + const std::shared_ptr& map); std::string m_tstr; diff --git a/userspace/libsinsp/sinsp_filtercheck_gen_event.cpp b/userspace/libsinsp/sinsp_filtercheck_gen_event.cpp index ed2fa4b25a..82a6bed352 100644 --- a/userspace/libsinsp/sinsp_filtercheck_gen_event.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_gen_event.cpp @@ -24,70 +24,162 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) - -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -#define RETURN_EXTRACT_CSTR(x) do { \ - if((x)) \ - { \ - *len = strlen((char *) ((x))); \ - } \ - return (uint8_t*) ((x)); \ -} while(0) - -static const filtercheck_field_info sinsp_filter_check_gen_event_fields[] = -{ - {PT_UINT64, EPF_NONE, PF_ID, "evt.num", "Event Number", "event number."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.time", "Time", "event timestamp as a time string that includes the nanosecond part."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.time.s", "Time (s)", "event timestamp as a time string with no nanoseconds."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.time.iso8601", "ISO 8601 Time", "event timestamp in ISO 8601 format, including nanoseconds and time zone offset (in UTC)."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.datetime", "Datetime", "event timestamp as a time string that includes the date."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.datetime.s", "Datetime (s)", "event timestamp as a datetime string with no nanoseconds."}, - {PT_ABSTIME, EPF_NONE, PF_DEC, "evt.rawtime", "Absolute Time", "absolute event timestamp, i.e. nanoseconds from epoch."}, - {PT_ABSTIME, EPF_NONE, PF_DEC, "evt.rawtime.s", "Absolute Time (s)", "integer part of the event timestamp (e.g. seconds since epoch)."}, - {PT_ABSTIME, EPF_NONE, PF_10_PADDED_DEC, "evt.rawtime.ns", "Absolute Time (ns)", "fractional part of the absolute event timestamp."}, - {PT_RELTIME, EPF_NONE, PF_10_PADDED_DEC, "evt.reltime", "Relative Time", "number of nanoseconds from the beginning of the capture."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "evt.reltime.s", "Relative Time (s)", "number of seconds from the beginning of the capture."}, - {PT_RELTIME, EPF_NONE, PF_10_PADDED_DEC, "evt.reltime.ns", "Relative Time (ns)", "fractional part (in ns) of the time from the beginning of the capture."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.pluginname", "Plugin Name", "if the event comes from a plugin-defined event source, the name of the plugin that generated it. The plugin must be currently loaded."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.plugininfo", "Plugin Info", "if the event comes from a plugin-defined event source, a summary of the event as formatted by the plugin. The plugin must be currently loaded."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.source", "Event Source", "the name of the source that produced the event."}, - {PT_BOOL, EPF_NONE, PF_NA, "evt.is_async", "Async Event", "'true' for asynchronous events, 'false' otherwise."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.asynctype", "Async-Event Type", "If the event is asynchronous, the type of the event (e.g. 'container')."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "evt.hostname", "Hostname", "The hostname of the underlying host can be customized by setting an environment variable (e.g. FALCO_HOSTNAME for the Falco agent). This is valuable in Kubernetes setups, where the hostname can match the pod name particularly in DaemonSet deployments. To achieve this, assign Kubernetes' spec.nodeName to the environment variable. Notably, spec.nodeName generally includes the cluster name."}, - /* Note for libs adopters: libs exposes a customizable env variable for hostname which defaults to `set(SCAP_HOSTNAME_ENV_VAR "SCAP_HOSTNAME")`, and Falco client adopts "FALCO_HOSTNAME". */ +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ + } while(0) + +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) + +#define RETURN_EXTRACT_CSTR(x) \ + do { \ + if((x)) { \ + *len = strlen((char*)((x))); \ + } \ + return (uint8_t*)((x)); \ + } while(0) + +static const filtercheck_field_info sinsp_filter_check_gen_event_fields[] = { + {PT_UINT64, EPF_NONE, PF_ID, "evt.num", "Event Number", "event number."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.time", + "Time", + "event timestamp as a time string that includes the nanosecond part."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.time.s", + "Time (s)", + "event timestamp as a time string with no nanoseconds."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.time.iso8601", + "ISO 8601 Time", + "event timestamp in ISO 8601 format, including nanoseconds and time zone offset (in " + "UTC)."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.datetime", + "Datetime", + "event timestamp as a time string that includes the date."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.datetime.s", + "Datetime (s)", + "event timestamp as a datetime string with no nanoseconds."}, + {PT_ABSTIME, + EPF_NONE, + PF_DEC, + "evt.rawtime", + "Absolute Time", + "absolute event timestamp, i.e. nanoseconds from epoch."}, + {PT_ABSTIME, + EPF_NONE, + PF_DEC, + "evt.rawtime.s", + "Absolute Time (s)", + "integer part of the event timestamp (e.g. seconds since epoch)."}, + {PT_ABSTIME, + EPF_NONE, + PF_10_PADDED_DEC, + "evt.rawtime.ns", + "Absolute Time (ns)", + "fractional part of the absolute event timestamp."}, + {PT_RELTIME, + EPF_NONE, + PF_10_PADDED_DEC, + "evt.reltime", + "Relative Time", + "number of nanoseconds from the beginning of the capture."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "evt.reltime.s", + "Relative Time (s)", + "number of seconds from the beginning of the capture."}, + {PT_RELTIME, + EPF_NONE, + PF_10_PADDED_DEC, + "evt.reltime.ns", + "Relative Time (ns)", + "fractional part (in ns) of the time from the beginning of the capture."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.pluginname", + "Plugin Name", + "if the event comes from a plugin-defined event source, the name of the plugin that " + "generated it. The plugin must be currently loaded."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.plugininfo", + "Plugin Info", + "if the event comes from a plugin-defined event source, a summary of the event as " + "formatted by the plugin. The plugin must be currently loaded."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.source", + "Event Source", + "the name of the source that produced the event."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "evt.is_async", + "Async Event", + "'true' for asynchronous events, 'false' otherwise."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.asynctype", + "Async-Event Type", + "If the event is asynchronous, the type of the event (e.g. 'container')."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "evt.hostname", + "Hostname", + "The hostname of the underlying host can be customized by setting an environment variable " + "(e.g. FALCO_HOSTNAME for the Falco agent). This is valuable in Kubernetes setups, where " + "the hostname can match the pod name particularly in DaemonSet deployments. To achieve " + "this, assign Kubernetes' spec.nodeName to the environment variable. Notably, " + "spec.nodeName generally includes the cluster name."}, + /* Note for libs adopters: libs exposes a customizable env variable for hostname which + defaults to `set(SCAP_HOSTNAME_ENV_VAR "SCAP_HOSTNAME")`, and Falco client adopts + "FALCO_HOSTNAME". */ }; -sinsp_filter_check_gen_event::sinsp_filter_check_gen_event() -{ +sinsp_filter_check_gen_event::sinsp_filter_check_gen_event() { static const filter_check_info s_field_infos = { - "evt", - "All event types", - "These fields can be used for all event types", - sizeof(sinsp_filter_check_gen_event_fields) / sizeof(sinsp_filter_check_gen_event_fields[0]), - sinsp_filter_check_gen_event_fields, - filter_check_info::FL_NONE, + "evt", + "All event types", + "These fields can be used for all event types", + sizeof(sinsp_filter_check_gen_event_fields) / + sizeof(sinsp_filter_check_gen_event_fields[0]), + sinsp_filter_check_gen_event_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; memset(&m_val, 0, sizeof(m_val)); } -std::unique_ptr sinsp_filter_check_gen_event::allocate_new() -{ +std::unique_ptr sinsp_filter_check_gen_event::allocate_new() { return std::make_unique(); } -Json::Value sinsp_filter_check_gen_event::extract_as_js(sinsp_evt *evt, uint32_t* len) -{ - switch(m_field_id) - { +Json::Value sinsp_filter_check_gen_event::extract_as_js(sinsp_evt* evt, uint32_t* len) { + switch(m_field_id) { case TYPE_TIME: case TYPE_TIME_S: case TYPE_TIME_ISO8601: @@ -101,7 +193,7 @@ Json::Value sinsp_filter_check_gen_event::extract_as_js(sinsp_evt *evt, uint32_t case TYPE_RELTS: case TYPE_RELTS_S: case TYPE_RELTS_NS: - return (Json::Value::Int64)*(uint64_t*)extract_single(evt, len); + return (Json::Value::Int64) * (uint64_t*)extract_single(evt, len); default: return Json::nullValue; } @@ -109,20 +201,17 @@ Json::Value sinsp_filter_check_gen_event::extract_as_js(sinsp_evt *evt, uint32_t return Json::nullValue; } -uint8_t* sinsp_filter_check_gen_event::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_gen_event::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { const scap_machine_info* minfo; *len = 0; - switch(m_field_id) - { + switch(m_field_id) { case TYPE_TIME: - if(false) - { + if(false) { m_strstorage = to_string(evt->get_ts()); - } - else - { + } else { sinsp_utils::ts_to_string(evt->get_ts(), &m_strstorage, false, true); } RETURN_EXTRACT_STRING(m_strstorage); @@ -160,56 +249,44 @@ uint8_t* sinsp_filter_check_gen_event::extract_single(sinsp_evt *evt, uint32_t* m_val.u64 = evt->get_num(); RETURN_EXTRACT_VAR(m_val.u64); case TYPE_PLUGINNAME: - case TYPE_PLUGININFO: - { + case TYPE_PLUGININFO: { const auto& plugin = m_inspector->get_plugin_manager()->plugin_by_evt(evt); - if (plugin == nullptr) - { + if(plugin == nullptr) { return NULL; } - if(m_field_id == TYPE_PLUGINNAME) - { + if(m_field_id == TYPE_PLUGINNAME) { m_strstorage = plugin->name(); - } - else - { + } else { m_strstorage = plugin->event_to_string(evt); } RETURN_EXTRACT_STRING(m_strstorage); } case TYPE_SOURCE: - if (evt->get_source_idx() == sinsp_no_event_source_idx - || evt->get_source_name() == sinsp_no_event_source_name) - { + if(evt->get_source_idx() == sinsp_no_event_source_idx || + evt->get_source_name() == sinsp_no_event_source_name) { return NULL; } RETURN_EXTRACT_CSTR(evt->get_source_name()); case TYPE_ISASYNC: - if (libsinsp::events::is_metaevent((ppm_event_code) evt->get_type())) - { + if(libsinsp::events::is_metaevent((ppm_event_code)evt->get_type())) { m_val.u32 = 1; - } - else - { + } else { m_val.u32 = 0; } RETURN_EXTRACT_VAR(m_val.u32); case TYPE_ASYNCTYPE: - if (!libsinsp::events::is_metaevent((ppm_event_code) evt->get_type())) - { + if(!libsinsp::events::is_metaevent((ppm_event_code)evt->get_type())) { return NULL; } - if (evt->get_type() == PPME_ASYNCEVENT_E) - { + if(evt->get_type() == PPME_ASYNCEVENT_E) { RETURN_EXTRACT_CSTR(evt->get_param(1)->m_val); } RETURN_EXTRACT_CSTR(evt->get_name()); case TYPE_HOSTNAME: minfo = m_inspector->get_machine_info(); - if (!minfo) - { + if(!minfo) { return NULL; } RETURN_EXTRACT_CSTR(minfo->hostname); diff --git a/userspace/libsinsp/sinsp_filtercheck_gen_event.h b/userspace/libsinsp/sinsp_filtercheck_gen_event.h index f21127abe6..bd2a33e2e6 100644 --- a/userspace/libsinsp/sinsp_filtercheck_gen_event.h +++ b/userspace/libsinsp/sinsp_filtercheck_gen_event.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_gen_event : public sinsp_filter_check -{ +class sinsp_filter_check_gen_event : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_NUMBER = 0, TYPE_TIME = 1, TYPE_TIME_S = 2, diff --git a/userspace/libsinsp/sinsp_filtercheck_group.cpp b/userspace/libsinsp/sinsp_filtercheck_group.cpp index 47291870d7..da25214643 100644 --- a/userspace/libsinsp/sinsp_filtercheck_group.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_group.cpp @@ -22,52 +22,50 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ + } while(0) -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) -static const filtercheck_field_info sinsp_filter_check_group_fields[] = -{ - {PT_UINT32, EPF_NONE, PF_ID, "group.gid", "Group ID", "group ID."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "group.name", "Group Name", "group name."}, +static const filtercheck_field_info sinsp_filter_check_group_fields[] = { + {PT_UINT32, EPF_NONE, PF_ID, "group.gid", "Group ID", "group ID."}, + {PT_CHARBUF, EPF_NONE, PF_NA, "group.name", "Group Name", "group name."}, }; -sinsp_filter_check_group::sinsp_filter_check_group() -{ +sinsp_filter_check_group::sinsp_filter_check_group() { static const filter_check_info s_field_infos = { - "group", - "", - "Information about the user group.", - sizeof(sinsp_filter_check_group_fields) / sizeof(sinsp_filter_check_group_fields[0]), - sinsp_filter_check_group_fields, - filter_check_info::FL_NONE, + "group", + "", + "Information about the user group.", + sizeof(sinsp_filter_check_group_fields) / sizeof(sinsp_filter_check_group_fields[0]), + sinsp_filter_check_group_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; } -std::unique_ptr sinsp_filter_check_group::allocate_new() -{ +std::unique_ptr sinsp_filter_check_group::allocate_new() { return std::make_unique(); } -uint8_t* sinsp_filter_check_group::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_group::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return NULL; } - switch(m_field_id) - { + switch(m_field_id) { case TYPE_GID: m_gid = tinfo->m_group.gid(); RETURN_EXTRACT_VAR(m_gid); diff --git a/userspace/libsinsp/sinsp_filtercheck_group.h b/userspace/libsinsp/sinsp_filtercheck_group.h index 8dee9c32fe..aea3d7d443 100644 --- a/userspace/libsinsp/sinsp_filtercheck_group.h +++ b/userspace/libsinsp/sinsp_filtercheck_group.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_group : public sinsp_filter_check -{ +class sinsp_filter_check_group : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_GID, TYPE_NAME, }; @@ -40,5 +38,4 @@ class sinsp_filter_check_group : public sinsp_filter_check private: uint32_t m_gid; std::string m_name; - }; diff --git a/userspace/libsinsp/sinsp_filtercheck_k8s.cpp b/userspace/libsinsp/sinsp_filtercheck_k8s.cpp index 1f9176c557..a06b1c21e1 100644 --- a/userspace/libsinsp/sinsp_filtercheck_k8s.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_k8s.cpp @@ -22,239 +22,392 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) -static inline bool str_match_start(std::string_view val, size_t len, const char* m) -{ +static inline bool str_match_start(std::string_view val, size_t len, const char* m) { return val.compare(0, len, m) == 0; } -#define STR_MATCH(s) str_match_start(val, sizeof (s) -1, s) - -static const filtercheck_field_info sinsp_filter_check_k8s_fields[] = -{ - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.ns.name", "Namespace Name", "The Kubernetes namespace name. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.name", "Pod Name", "The Kubernetes pod name. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.id", "Legacy Pod UID", "[LEGACY] The Kubernetes pod UID, e.g. 3e41dc6b-08a8-44db-bc2a-3724b18ab19a. This legacy field points to `k8s.pod.uid`; however, the pod ID typically refers to the pod sandbox ID. We recommend using the semantically more accurate `k8s.pod.uid` field. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.uid", "Pod UID", "The Kubernetes pod UID, e.g. 3e41dc6b-08a8-44db-bc2a-3724b18ab19a. Note that the pod UID is a unique identifier assigned upon pod creation within Kubernetes, allowing the Kubernetes control plane to manage and track pods reliably. As such, it is fundamentally a different concept compared to the pod sandbox ID. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.sandbox_id", "Pod / Sandbox ID", "The truncated Kubernetes pod sandbox ID (first 12 characters), e.g 63060edc2d3a. The sandbox ID is specific to the container runtime environment. It is the equivalent of the container ID for the pod / sandbox and extracted from the Linux cgroups. As such, it differs from the pod UID. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet. In Kubernetes, pod sandbox container processes can exist where `container.id` matches `k8s.pod.sandbox_id`, lacking other 'container.*' details."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.full_sandbox_id", "Pod / Sandbox ID", "The full Kubernetes pod / sandbox ID, e.g 63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "k8s.pod.label", "Pod Label", "The Kubernetes pod label. The label can be accessed either with the familiar brackets notation, e.g. 'k8s.pod.label[foo]' or by appending a dot followed by the name, e.g. 'k8s.pod.label.foo'. The label name itself can include the original special characters such as '.', '-', '_' or '/' characters. For instance, 'k8s.pod.label[app.kubernetes.io/name]', 'k8s.pod.label.app.kubernetes.io/name' or 'k8s.pod.label[custom-label_one]' are all valid. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.labels", "Pod Labels", "The Kubernetes pod comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.ip", "Pod Ip", "The Kubernetes pod ip, same as container.ip field as each container in a pod shares the network stack of the sandbox / pod. Only ipv4 addresses are tracked. Consider k8s.pod.cni.json for logging ip addresses for each network interface. This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "k8s.pod.cni.json", "Pod CNI result json", "The Kubernetes pod CNI result field from the respective pod status info, same as container.cni.json field. It contains ip addresses for each network interface exposed as unparsed escaped JSON string. Supported for CRI container engine (containerd, cri-o runtimes), optimized for containerd (some non-critical JSON keys removed). Useful for tracking ips (ipv4 and ipv6, dual-stack support) for each network interface (multi-interface support). This field is extracted from the container runtime socket simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may not be available yet."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.rc.name", "Replication Controller Name", "Kubernetes replication controller name."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.rc.id", "Replication Controller ID", "Kubernetes replication controller id."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "k8s.rc.label", "Replication Controller Label", "Kubernetes replication controller label. E.g. 'k8s.rc.label.foo'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.rc.labels", "Replication Controller Labels", "Kubernetes replication controller comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.svc.name", "Service Name", "Kubernetes service name (can return more than one value, concatenated)."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.svc.id", "Service ID", "Kubernetes service id (can return more than one value, concatenated)."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "k8s.svc.label", "Service Label", "Kubernetes service label. E.g. 'k8s.svc.label.foo' (can return more than one value, concatenated)."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.svc.labels", "Service Labels", "Kubernetes service comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.ns.id", "Namespace ID", "Kubernetes namespace id."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "k8s.ns.label", "Namespace Label", "Kubernetes namespace label. E.g. 'k8s.ns.label.foo'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.ns.labels", "Namespace Labels", "Kubernetes namespace comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.rs.name", "Replica Set Name", "Kubernetes replica set name."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.rs.id", "Replica Set ID", "Kubernetes replica set id."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "k8s.rs.label", "Replica Set Label", "Kubernetes replica set label. E.g. 'k8s.rs.label.foo'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.rs.labels", "Replica Set Labels", "Kubernetes replica set comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.deployment.name", "Deployment Name", "Kubernetes deployment name."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.deployment.id", "Deployment ID", "Kubernetes deployment id."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "k8s.deployment.label", "Deployment Label", "Kubernetes deployment label. E.g. 'k8s.rs.label.foo'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "k8s.deployment.labels", "Deployment Labels", "Kubernetes deployment comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, +#define STR_MATCH(s) str_match_start(val, sizeof(s) - 1, s) + +static const filtercheck_field_info sinsp_filter_check_k8s_fields[] = { + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.ns.name", + "Namespace Name", + "The Kubernetes namespace name. This field is extracted from the container runtime socket " + "simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may " + "not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.name", + "Pod Name", + "The Kubernetes pod name. This field is extracted from the container runtime socket " + "simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may " + "not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.id", + "Legacy Pod UID", + "[LEGACY] The Kubernetes pod UID, e.g. 3e41dc6b-08a8-44db-bc2a-3724b18ab19a. This legacy " + "field points to `k8s.pod.uid`; however, the pod ID typically refers to the pod sandbox " + "ID. We recommend using the semantically more accurate `k8s.pod.uid` field. This field is " + "extracted from the container runtime socket simultaneously as we look up the " + "'container.*' fields. In cases of lookup delays, it may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.uid", + "Pod UID", + "The Kubernetes pod UID, e.g. 3e41dc6b-08a8-44db-bc2a-3724b18ab19a. Note that the pod UID " + "is a unique identifier assigned upon pod creation within Kubernetes, allowing the " + "Kubernetes control plane to manage and track pods reliably. As such, it is fundamentally " + "a different concept compared to the pod sandbox ID. This field is extracted from the " + "container runtime socket simultaneously as we look up the 'container.*' fields. In cases " + "of lookup delays, it may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.sandbox_id", + "Pod / Sandbox ID", + "The truncated Kubernetes pod sandbox ID (first 12 characters), e.g 63060edc2d3a. The " + "sandbox ID is specific to the container runtime environment. It is the equivalent of the " + "container ID for the pod / sandbox and extracted from the Linux cgroups. As such, it " + "differs from the pod UID. This field is extracted from the container runtime socket " + "simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may " + "not be available yet. In Kubernetes, pod sandbox container processes can exist where " + "`container.id` matches `k8s.pod.sandbox_id`, lacking other 'container.*' details."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.full_sandbox_id", + "Pod / Sandbox ID", + "The full Kubernetes pod / sandbox ID, e.g " + "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a. This field is " + "extracted from the container runtime socket simultaneously as we look up the " + "'container.*' fields. In cases of lookup delays, it may not be available yet."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "k8s.pod.label", + "Pod Label", + "The Kubernetes pod label. The label can be accessed either with the familiar brackets " + "notation, e.g. 'k8s.pod.label[foo]' or by appending a dot followed by the name, e.g. " + "'k8s.pod.label.foo'. The label name itself can include the original special characters " + "such as '.', '-', '_' or '/' characters. For instance, " + "'k8s.pod.label[app.kubernetes.io/name]', 'k8s.pod.label.app.kubernetes.io/name' or " + "'k8s.pod.label[custom-label_one]' are all valid. This field is extracted from the " + "container runtime socket simultaneously as we look up the 'container.*' fields. In cases " + "of lookup delays, it may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.labels", + "Pod Labels", + "The Kubernetes pod comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'. This " + "field is extracted from the container runtime socket simultaneously as we look up the " + "'container.*' fields. In cases of lookup delays, it may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.ip", + "Pod Ip", + "The Kubernetes pod ip, same as container.ip field as each container in a pod shares the " + "network stack of the sandbox / pod. Only ipv4 addresses are tracked. Consider " + "k8s.pod.cni.json for logging ip addresses for each network interface. This field is " + "extracted from the container runtime socket simultaneously as we look up the " + "'container.*' fields. In cases of lookup delays, it may not be available yet."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "k8s.pod.cni.json", + "Pod CNI result json", + "The Kubernetes pod CNI result field from the respective pod status info, same as " + "container.cni.json field. It contains ip addresses for each network interface exposed as " + "unparsed escaped JSON string. Supported for CRI container engine (containerd, cri-o " + "runtimes), optimized for containerd (some non-critical JSON keys removed). Useful for " + "tracking ips (ipv4 and ipv6, dual-stack support) for each network interface " + "(multi-interface support). This field is extracted from the container runtime socket " + "simultaneously as we look up the 'container.*' fields. In cases of lookup delays, it may " + "not be available yet."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.rc.name", + "Replication Controller Name", + "Kubernetes replication controller name."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.rc.id", + "Replication Controller ID", + "Kubernetes replication controller id."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "k8s.rc.label", + "Replication Controller Label", + "Kubernetes replication controller label. E.g. 'k8s.rc.label.foo'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.rc.labels", + "Replication Controller Labels", + "Kubernetes replication controller comma-separated key/value labels. E.g. " + "'foo1:bar1,foo2:bar2'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.svc.name", + "Service Name", + "Kubernetes service name (can return more than one value, concatenated)."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.svc.id", + "Service ID", + "Kubernetes service id (can return more than one value, concatenated)."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "k8s.svc.label", + "Service Label", + "Kubernetes service label. E.g. 'k8s.svc.label.foo' (can return more than one value, " + "concatenated)."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.svc.labels", + "Service Labels", + "Kubernetes service comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.ns.id", + "Namespace ID", + "Kubernetes namespace id."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "k8s.ns.label", + "Namespace Label", + "Kubernetes namespace label. E.g. 'k8s.ns.label.foo'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.ns.labels", + "Namespace Labels", + "Kubernetes namespace comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.rs.name", + "Replica Set Name", + "Kubernetes replica set name."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.rs.id", + "Replica Set ID", + "Kubernetes replica set id."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "k8s.rs.label", + "Replica Set Label", + "Kubernetes replica set label. E.g. 'k8s.rs.label.foo'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.rs.labels", + "Replica Set Labels", + "Kubernetes replica set comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.deployment.name", + "Deployment Name", + "Kubernetes deployment name."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.deployment.id", + "Deployment ID", + "Kubernetes deployment id."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "k8s.deployment.label", + "Deployment Label", + "Kubernetes deployment label. E.g. 'k8s.rs.label.foo'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "k8s.deployment.labels", + "Deployment Labels", + "Kubernetes deployment comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, }; -sinsp_filter_check_k8s::sinsp_filter_check_k8s() -{ +sinsp_filter_check_k8s::sinsp_filter_check_k8s() { static const filter_check_info s_field_infos = { - "k8s", - "", - "Kubernetes context about pods and namespace name. These fields are populated with data gathered from the container runtime.", - sizeof(sinsp_filter_check_k8s_fields) / sizeof(sinsp_filter_check_k8s_fields[0]), - sinsp_filter_check_k8s_fields, - filter_check_info::FL_NONE, + "k8s", + "", + "Kubernetes context about pods and namespace name. These fields are populated with " + "data gathered from the container runtime.", + sizeof(sinsp_filter_check_k8s_fields) / sizeof(sinsp_filter_check_k8s_fields[0]), + sinsp_filter_check_k8s_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; } -std::unique_ptr sinsp_filter_check_k8s::allocate_new() -{ +std::unique_ptr sinsp_filter_check_k8s::allocate_new() { return std::make_unique(); } -int32_t sinsp_filter_check_k8s::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ - if(STR_MATCH("k8s.pod.label") && - !STR_MATCH("k8s.pod.labels")) - { +int32_t sinsp_filter_check_k8s::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { + if(STR_MATCH("k8s.pod.label") && !STR_MATCH("k8s.pod.labels")) { m_field_id = TYPE_K8S_POD_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("k8s.pod.label", val); - } - else if(STR_MATCH("k8s.rc.label") && - !STR_MATCH("k8s.rc.labels")) - { + } else if(STR_MATCH("k8s.rc.label") && !STR_MATCH("k8s.rc.labels")) { m_field_id = TYPE_K8S_RC_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("k8s.rc.label", val); - } - else if(STR_MATCH("k8s.rs.label") && - !STR_MATCH("k8s.rs.labels")) - { + } else if(STR_MATCH("k8s.rs.label") && !STR_MATCH("k8s.rs.labels")) { m_field_id = TYPE_K8S_RS_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("k8s.rs.label", val); - } - else if(STR_MATCH("k8s.svc.label") && - !STR_MATCH("k8s.svc.labels")) - { + } else if(STR_MATCH("k8s.svc.label") && !STR_MATCH("k8s.svc.labels")) { m_field_id = TYPE_K8S_SVC_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("k8s.svc.label", val); - } - else if(STR_MATCH("k8s.ns.label") && - !STR_MATCH("k8s.ns.labels")) - { + } else if(STR_MATCH("k8s.ns.label") && !STR_MATCH("k8s.ns.labels")) { m_field_id = TYPE_K8S_NS_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("k8s.ns.label", val); - } - else if(STR_MATCH("k8s.deployment.label") && - !STR_MATCH("k8s.deployment.labels")) - { + } else if(STR_MATCH("k8s.deployment.label") && !STR_MATCH("k8s.deployment.labels")) { m_field_id = TYPE_K8S_DEPLOYMENT_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("k8s.deployment.label", val); - } - else - { + } else { return sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } } -int32_t sinsp_filter_check_k8s::extract_arg(string_view fldname, string_view val) -{ +int32_t sinsp_filter_check_k8s::extract_arg(string_view fldname, string_view val) { int32_t parsed_len = 0; - if(val.size() > fldname.size() && val.at(fldname.size()) == '.') - { + if(val.size() > fldname.size() && val.at(fldname.size()) == '.') { size_t endpos; - for(endpos = fldname.size() + 1; endpos < val.length(); ++endpos) - { - if(!isalnum(val.at(endpos)) - && val.at(endpos) != '/' - && val.at(endpos) != '_' - && val.at(endpos) != '-' - && val.at(endpos) != '.') - { + for(endpos = fldname.size() + 1; endpos < val.length(); ++endpos) { + if(!isalnum(val.at(endpos)) && val.at(endpos) != '/' && val.at(endpos) != '_' && + val.at(endpos) != '-' && val.at(endpos) != '.') { break; } } parsed_len = (uint32_t)endpos; m_argname = val.substr(fldname.size() + 1, endpos - fldname.size() - 1); - } - else if(val.size() > fldname.size() && val.at(fldname.size()) == '[') - { + } else if(val.size() > fldname.size() && val.at(fldname.size()) == '[') { size_t startpos = fldname.size(); parsed_len = (uint32_t)val.find(']', startpos); - if ((uint32_t) parsed_len == (uint32_t) std::string::npos) - { - throw sinsp_exception("the field '" + string(fldname) + "' requires an argument but ']' is not found"); + if((uint32_t)parsed_len == (uint32_t)std::string::npos) { + throw sinsp_exception("the field '" + string(fldname) + + "' requires an argument but ']' is not found"); } m_argname = val.substr(startpos + 1, parsed_len - startpos - 1); parsed_len++; - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } return parsed_len; } -void sinsp_filter_check_k8s::concatenate_container_labels(const map& labels, string* s) -{ - for (auto const& label_pair : labels) - { +void sinsp_filter_check_k8s::concatenate_container_labels( + const map& labels, + string* s) { + for(auto const& label_pair : labels) { // exclude annotations and internal labels - if (label_pair.first.find("annotation.") == 0 || label_pair.first.find("io.kubernetes.") == 0) { + if(label_pair.first.find("annotation.") == 0 || + label_pair.first.find("io.kubernetes.") == 0) { continue; } - if(!s->empty()) - { + if(!s->empty()) { s->append(", "); } s->append(label_pair.first); - if(!label_pair.second.empty()) - { + if(!label_pair.second.empty()) { s->append(":" + label_pair.second); } } } -uint8_t* sinsp_filter_check_k8s::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_k8s::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; ASSERT(evt); - if(evt == NULL) - { + if(evt == NULL) { ASSERT(false); return NULL; } sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return NULL; } // Here we extract info only if we have the container - if(tinfo->m_container_id.empty()) - { + if(tinfo->m_container_id.empty()) { return NULL; } - const auto container_info = m_inspector->m_container_manager.get_container(tinfo->m_container_id); + const auto container_info = + m_inspector->m_container_manager.get_container(tinfo->m_container_id); // No m_pod_sandbox_id means no k8s. // m_pod_sandbox_id retrieved from the ContainerStatusResponse CRI API call. - if(container_info == nullptr || container_info->m_pod_sandbox_id.empty()) - { + if(container_info == nullptr || container_info->m_pod_sandbox_id.empty()) { return NULL; } m_tstr.clear(); - // Note: All fields are retrieved from the CRI API calls aka as part of the container engine lookups. - // There is no interaction w/ the Kubernetes Server in any way to retrieve these fields. As alternative explore the new `k8smeta` plugin. - // Comments explain the origin of each field (either ContainerStatusResponse or PodSandboxStatusResponse CRI API call). + // Note: All fields are retrieved from the CRI API calls aka as part of the container engine + // lookups. There is no interaction w/ the Kubernetes Server in any way to retrieve these + // fields. As alternative explore the new `k8smeta` plugin. Comments explain the origin of each + // field (either ContainerStatusResponse or PodSandboxStatusResponse CRI API call). - switch(m_field_id) - { + switch(m_field_id) { case TYPE_K8S_POD_NAME: // Retrieved from the ContainerStatusResponse CRI API call. - if(container_info->m_labels.count("io.kubernetes.pod.name") > 0) - { + if(container_info->m_labels.count("io.kubernetes.pod.name") > 0) { m_tstr = container_info->m_labels.at("io.kubernetes.pod.name"); RETURN_EXTRACT_STRING(m_tstr); } break; case TYPE_K8S_NS_NAME: // Retrieved from the ContainerStatusResponse CRI API call. - if(container_info->m_labels.count("io.kubernetes.pod.namespace") > 0) - { + if(container_info->m_labels.count("io.kubernetes.pod.namespace") > 0) { m_tstr = container_info->m_labels.at("io.kubernetes.pod.namespace"); RETURN_EXTRACT_STRING(m_tstr); } @@ -262,8 +415,7 @@ uint8_t* sinsp_filter_check_k8s::extract_single(sinsp_evt *evt, uint32_t* len, b case TYPE_K8S_POD_ID: case TYPE_K8S_POD_UID: // Retrieved from the ContainerStatusResponse CRI API call. - if(container_info->m_labels.count("io.kubernetes.pod.uid") > 0) - { + if(container_info->m_labels.count("io.kubernetes.pod.uid") > 0) { m_tstr = container_info->m_labels.at("io.kubernetes.pod.uid"); RETURN_EXTRACT_STRING(m_tstr); } @@ -272,10 +424,8 @@ uint8_t* sinsp_filter_check_k8s::extract_single(sinsp_evt *evt, uint32_t* len, b case TYPE_K8S_POD_FULL_SANDBOX_ID: // Retrieved from the ContainerStatusResponse CRI API call. m_tstr = container_info->m_pod_sandbox_id; - if(m_field_id == TYPE_K8S_POD_SANDBOX_ID) - { - if(m_tstr.size() > 12) - { + if(m_field_id == TYPE_K8S_POD_SANDBOX_ID) { + if(m_tstr.size() > 12) { m_tstr.resize(12); } } @@ -284,33 +434,33 @@ uint8_t* sinsp_filter_check_k8s::extract_single(sinsp_evt *evt, uint32_t* len, b case TYPE_K8S_POD_LABEL: case TYPE_K8S_POD_LABELS: // Requires s_cri_extra_queries enabled, which is the default for Falco. - // Note that m_pod_sandbox_labels, while part of the container struct, is retrieved from an extra PodSandboxStatusResponse call, not the ContainerStatusResponse CRI API call. + // Note that m_pod_sandbox_labels, while part of the container struct, is retrieved from an + // extra PodSandboxStatusResponse call, not the ContainerStatusResponse CRI API call. { sinsp_container_info::ptr_t sandbox_container_info; - if(container_info->m_pod_sandbox_cniresult.empty()) // more robust check than checking for empty labels + if(container_info->m_pod_sandbox_cniresult + .empty()) // more robust check than checking for empty labels { - // Fallback: Retrieve PodSandboxStatusResponse fields stored in explicit pod sandbox container - sandbox_container_info = m_inspector->m_container_manager.get_container(container_info->m_pod_sandbox_id.substr(0, 12)); + // Fallback: Retrieve PodSandboxStatusResponse fields stored in explicit pod sandbox + // container + sandbox_container_info = m_inspector->m_container_manager.get_container( + container_info->m_pod_sandbox_id.substr(0, 12)); } - if (m_field_id == TYPE_K8S_POD_LABEL) - { - if(sandbox_container_info && sandbox_container_info->m_pod_sandbox_labels.count(m_argname) > 0) // fallback + if(m_field_id == TYPE_K8S_POD_LABEL) { + if(sandbox_container_info && + sandbox_container_info->m_pod_sandbox_labels.count(m_argname) > 0) // fallback { m_tstr = sandbox_container_info->m_pod_sandbox_labels.at(m_argname); - } - else if (container_info->m_pod_sandbox_labels.count(m_argname) > 0) - { + } else if(container_info->m_pod_sandbox_labels.count(m_argname) > 0) { m_tstr = container_info->m_pod_sandbox_labels.at(m_argname); } RETURN_EXTRACT_STRING(m_tstr); - } - else if (m_field_id == TYPE_K8S_POD_LABELS) - { - if(sandbox_container_info) // fallback - { - concatenate_container_labels(sandbox_container_info->m_pod_sandbox_labels, &m_tstr); - } else + } else if(m_field_id == TYPE_K8S_POD_LABELS) { + if(sandbox_container_info) // fallback { + concatenate_container_labels(sandbox_container_info->m_pod_sandbox_labels, + &m_tstr); + } else { concatenate_container_labels(container_info->m_pod_sandbox_labels, &m_tstr); } RETURN_EXTRACT_STRING(m_tstr); @@ -319,17 +469,19 @@ uint8_t* sinsp_filter_check_k8s::extract_single(sinsp_evt *evt, uint32_t* len, b break; case TYPE_K8S_POD_IP: // Requires s_cri_extra_queries enabled, which is the default for Falco. - // Note that m_pod_sandbox_labels, while part of the container struct, is retrieved from an extra PodSandboxStatusResponse call, not the ContainerStatusResponse CRI API call. - if(container_info->m_pod_sandbox_cniresult.empty()) // more robust check than checking for 0 in m_container_ip + // Note that m_pod_sandbox_labels, while part of the container struct, is retrieved from an + // extra PodSandboxStatusResponse call, not the ContainerStatusResponse CRI API call. + if(container_info->m_pod_sandbox_cniresult + .empty()) // more robust check than checking for 0 in m_container_ip { // Fallback: Retrieve PodSandboxStatusResponse fields stored in pod sandbox container - const sinsp_container_info::ptr_t sandbox_container_info = m_inspector->m_container_manager.get_container(container_info->m_pod_sandbox_id.substr(0, 12)); - if(sandbox_container_info) - { + const sinsp_container_info::ptr_t sandbox_container_info = + m_inspector->m_container_manager.get_container( + container_info->m_pod_sandbox_id.substr(0, 12)); + if(sandbox_container_info) { m_u32val = htonl(sandbox_container_info->m_container_ip); } - } else - { + } else { m_u32val = htonl(container_info->m_container_ip); } char addrbuff[100]; @@ -339,13 +491,14 @@ uint8_t* sinsp_filter_check_k8s::extract_single(sinsp_evt *evt, uint32_t* len, b break; case TYPE_K8S_POD_CNIRESULT: // Requires s_cri_extra_queries enabled, which is the default for Falco. - // Note that m_pod_sandbox_labels, while part of the container struct, is retrieved from an extra PodSandboxStatusResponse call, not the ContainerStatusResponse CRI API call. - if(container_info->m_pod_sandbox_cniresult.empty()) - { + // Note that m_pod_sandbox_labels, while part of the container struct, is retrieved from an + // extra PodSandboxStatusResponse call, not the ContainerStatusResponse CRI API call. + if(container_info->m_pod_sandbox_cniresult.empty()) { // Fallback: Retrieve PodSandboxStatusResponse fields stored in pod sandbox container - const sinsp_container_info::ptr_t sandbox_container_info = m_inspector->m_container_manager.get_container(container_info->m_pod_sandbox_id.substr(0, 12)); - if(sandbox_container_info) - { + const sinsp_container_info::ptr_t sandbox_container_info = + m_inspector->m_container_manager.get_container( + container_info->m_pod_sandbox_id.substr(0, 12)); + if(sandbox_container_info) { RETURN_EXTRACT_STRING(sandbox_container_info->m_pod_sandbox_cniresult); } } diff --git a/userspace/libsinsp/sinsp_filtercheck_k8s.h b/userspace/libsinsp/sinsp_filtercheck_k8s.h index dc5868375e..a36cdd8ed6 100644 --- a/userspace/libsinsp/sinsp_filtercheck_k8s.h +++ b/userspace/libsinsp/sinsp_filtercheck_k8s.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_k8s : public sinsp_filter_check -{ +class sinsp_filter_check_k8s : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_K8S_NS_NAME = 0, TYPE_K8S_POD_NAME, TYPE_K8S_POD_ID, @@ -61,14 +59,17 @@ class sinsp_filter_check_k8s : public sinsp_filter_check virtual ~sinsp_filter_check_k8s() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; protected: uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; private: int32_t extract_arg(std::string_view fldname, std::string_view val); - void concatenate_container_labels(const std::map& labels, std::string* s); + void concatenate_container_labels(const std::map& labels, + std::string* s); std::string m_argname; std::string m_tstr; uint32_t m_u32val; diff --git a/userspace/libsinsp/sinsp_filtercheck_mesos.cpp b/userspace/libsinsp/sinsp_filtercheck_mesos.cpp index 94db4e771b..01906d2a6d 100644 --- a/userspace/libsinsp/sinsp_filtercheck_mesos.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_mesos.cpp @@ -22,103 +22,145 @@ limitations under the License. using namespace std; -static inline bool str_match_start(std::string_view val, size_t len, const char* m) -{ +static inline bool str_match_start(std::string_view val, size_t len, const char* m) { return val.compare(0, len, m) == 0; } -#define STR_MATCH(s) str_match_start(val, sizeof (s) -1, s) - -static const filtercheck_field_info sinsp_filter_check_mesos_fields[] = -{ - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "mesos.task.name", "Task Name", "Mesos task name."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "mesos.task.id", "Task ID", "Mesos task id."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "mesos.task.label", "Task Label", "Mesos task label. E.g. 'mesos.task.label.foo'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "mesos.task.labels", "Task Labels", "Mesos task comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "mesos.framework.name", "Framework Name", "Mesos framework name."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "mesos.framework.id", "Framework ID", "Mesos framework id."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "marathon.app.name", "App Name", "Marathon app name."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "marathon.app.id", "App ID", "Marathon app id."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "marathon.app.label", "App Label", "Marathon app label. E.g. 'marathon.app.label.foo'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "marathon.app.labels", "App Labels", "Marathon app comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "marathon.group.name", "Group Name", "Marathon group name."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "marathon.group.id", "Group ID", "Marathon group id."}, +#define STR_MATCH(s) str_match_start(val, sizeof(s) - 1, s) + +static const filtercheck_field_info sinsp_filter_check_mesos_fields[] = { + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "mesos.task.name", + "Task Name", + "Mesos task name."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "mesos.task.id", + "Task ID", + "Mesos task id."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "mesos.task.label", + "Task Label", + "Mesos task label. E.g. 'mesos.task.label.foo'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "mesos.task.labels", + "Task Labels", + "Mesos task comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "mesos.framework.name", + "Framework Name", + "Mesos framework name."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "mesos.framework.id", + "Framework ID", + "Mesos framework id."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "marathon.app.name", + "App Name", + "Marathon app name."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "marathon.app.id", + "App ID", + "Marathon app id."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "marathon.app.label", + "App Label", + "Marathon app label. E.g. 'marathon.app.label.foo'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "marathon.app.labels", + "App Labels", + "Marathon app comma-separated key/value labels. E.g. 'foo1:bar1,foo2:bar2'."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "marathon.group.name", + "Group Name", + "Marathon group name."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "marathon.group.id", + "Group ID", + "Marathon group id."}, }; -sinsp_filter_check_mesos::sinsp_filter_check_mesos() -{ +sinsp_filter_check_mesos::sinsp_filter_check_mesos() { static const filter_check_info s_field_infos = { - "mesos", - "", - "Mesos related context.", - sizeof(sinsp_filter_check_mesos_fields) / sizeof(sinsp_filter_check_mesos_fields[0]), - sinsp_filter_check_mesos_fields, - filter_check_info::FL_NONE, + "mesos", + "", + "Mesos related context.", + sizeof(sinsp_filter_check_mesos_fields) / sizeof(sinsp_filter_check_mesos_fields[0]), + sinsp_filter_check_mesos_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; } -std::unique_ptr sinsp_filter_check_mesos::allocate_new() -{ +std::unique_ptr sinsp_filter_check_mesos::allocate_new() { return std::make_unique(); } -int32_t sinsp_filter_check_mesos::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ - if(STR_MATCH("mesos.task.label") && - !STR_MATCH("mesos.task.labels")) - { +int32_t sinsp_filter_check_mesos::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { + if(STR_MATCH("mesos.task.label") && !STR_MATCH("mesos.task.labels")) { m_field_id = TYPE_MESOS_TASK_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("mesos.task.label", val); - } - else if(STR_MATCH("marathon.app.label") && - !STR_MATCH("marathon.app.labels")) - { + } else if(STR_MATCH("marathon.app.label") && !STR_MATCH("marathon.app.labels")) { m_field_id = TYPE_MARATHON_APP_LABEL; m_field = &m_info->m_fields[m_field_id]; return extract_arg("marathon.app.label", val); - } - else - { + } else { return sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } } -int32_t sinsp_filter_check_mesos::extract_arg(string_view fldname, string_view val) -{ +int32_t sinsp_filter_check_mesos::extract_arg(string_view fldname, string_view val) { int32_t parsed_len = 0; - if(val.size() > fldname.size() && val.at(fldname.size()) == '.') - { + if(val.size() > fldname.size() && val.at(fldname.size()) == '.') { size_t endpos; - for(endpos = fldname.size() + 1; endpos < val.length(); ++endpos) - { - if(!isalnum(val.at(endpos)) - && val.at(endpos) != '/' - && val.at(endpos) != '_' - && val.at(endpos) != '-' - && val.at(endpos) != '.') - { + for(endpos = fldname.size() + 1; endpos < val.length(); ++endpos) { + if(!isalnum(val.at(endpos)) && val.at(endpos) != '/' && val.at(endpos) != '_' && + val.at(endpos) != '-' && val.at(endpos) != '.') { break; } } parsed_len = (uint32_t)endpos; m_argname = val.substr(fldname.size() + 1, endpos - fldname.size() - 1); - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } return parsed_len; } -uint8_t* sinsp_filter_check_mesos::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_mesos::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { // note: all mesos fields are deprecated since removing them from the codebase *len = 0; return NULL; diff --git a/userspace/libsinsp/sinsp_filtercheck_mesos.h b/userspace/libsinsp/sinsp_filtercheck_mesos.h index c94b878607..8ba3f922ab 100644 --- a/userspace/libsinsp/sinsp_filtercheck_mesos.h +++ b/userspace/libsinsp/sinsp_filtercheck_mesos.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_mesos : public sinsp_filter_check -{ +class sinsp_filter_check_mesos : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_MESOS_TASK_NAME = 0, TYPE_MESOS_TASK_ID, TYPE_MESOS_TASK_LABEL, @@ -43,7 +41,9 @@ class sinsp_filter_check_mesos : public sinsp_filter_check virtual ~sinsp_filter_check_mesos() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; protected: uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; diff --git a/userspace/libsinsp/sinsp_filtercheck_rawstring.cpp b/userspace/libsinsp/sinsp_filtercheck_rawstring.cpp index ccaca3f490..d75fc4efb3 100644 --- a/userspace/libsinsp/sinsp_filtercheck_rawstring.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_rawstring.cpp @@ -22,20 +22,18 @@ limitations under the License. using namespace std; -static const filtercheck_field_info rawstring_check_fields[] = -{ - {PT_CHARBUF, EPF_NONE, PF_NA, "NA", "NA", "INTERNAL."}, +static const filtercheck_field_info rawstring_check_fields[] = { + {PT_CHARBUF, EPF_NONE, PF_NA, "NA", "NA", "INTERNAL."}, }; -rawstring_check::rawstring_check(const string& text) -{ +rawstring_check::rawstring_check(const string& text) { static const filter_check_info s_field_infos = { - "", - "", - "", - sizeof(rawstring_check_fields) / sizeof(rawstring_check_fields[0]), - rawstring_check_fields, - filter_check_info::FL_HIDDEN, + "", + "", + "", + sizeof(rawstring_check_fields) / sizeof(rawstring_check_fields[0]), + rawstring_check_fields, + filter_check_info::FL_HIDDEN, }; m_field = rawstring_check_fields; m_info = &s_field_infos; @@ -43,20 +41,19 @@ rawstring_check::rawstring_check(const string& text) m_text = text; } -std::unique_ptr rawstring_check::allocate_new() -{ +std::unique_ptr rawstring_check::allocate_new() { ASSERT(false); return nullptr; } -int32_t rawstring_check::parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) -{ +int32_t rawstring_check::parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) { ASSERT(false); return -1; } -uint8_t* rawstring_check::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* rawstring_check::extract_single(sinsp_evt* evt, uint32_t* len, bool sanitize_strings) { *len = m_text.size(); return (uint8_t*)m_text.c_str(); } diff --git a/userspace/libsinsp/sinsp_filtercheck_rawstring.h b/userspace/libsinsp/sinsp_filtercheck_rawstring.h index 8b27583487..55e24b90f2 100644 --- a/userspace/libsinsp/sinsp_filtercheck_rawstring.h +++ b/userspace/libsinsp/sinsp_filtercheck_rawstring.h @@ -20,14 +20,15 @@ limitations under the License. #include -class rawstring_check : public sinsp_filter_check -{ +class rawstring_check : public sinsp_filter_check { public: rawstring_check(const std::string& text); virtual ~rawstring_check() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; private: diff --git a/userspace/libsinsp/sinsp_filtercheck_reference.cpp b/userspace/libsinsp/sinsp_filtercheck_reference.cpp index 8a7a44fa8c..7dd2529b11 100644 --- a/userspace/libsinsp/sinsp_filtercheck_reference.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_reference.cpp @@ -20,12 +20,11 @@ limitations under the License. #include #include -#define STRPROPERTY_STORAGE_SIZE 1024 +#define STRPROPERTY_STORAGE_SIZE 1024 using namespace std; -sinsp_filter_check_reference::sinsp_filter_check_reference() -{ +sinsp_filter_check_reference::sinsp_filter_check_reference() { m_cinfo.m_name = ""; m_cinfo.m_desc = ""; m_cinfo.m_fields = &m_finfo; @@ -36,20 +35,21 @@ sinsp_filter_check_reference::sinsp_filter_check_reference() m_info = &m_cinfo; } -std::unique_ptr sinsp_filter_check_reference::allocate_new() -{ +std::unique_ptr sinsp_filter_check_reference::allocate_new() { ASSERT(false); return nullptr; } -int32_t sinsp_filter_check_reference::parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) -{ +int32_t sinsp_filter_check_reference::parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) { ASSERT(false); return -1; } -uint8_t* sinsp_filter_check_reference::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_reference::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = m_len; return m_val; } @@ -58,70 +58,72 @@ uint8_t* sinsp_filter_check_reference::extract_single(sinsp_evt *evt, uint32_t* // convert a number into a byte representation. // E.g. 1230 becomes 1.23K // -char* sinsp_filter_check_reference::format_bytes(double val, uint32_t str_len, bool is_int) -{ +char* sinsp_filter_check_reference::format_bytes(double val, uint32_t str_len, bool is_int) { char* pr_fmt; - if(is_int) - { + if(is_int) { pr_fmt = (char*)"%*.0lf%c"; - } - else - { + } else { pr_fmt = (char*)"%*.2lf%c"; } - if(val > (1024LL * 1024 * 1024 * 1024 * 1024)) - { + if(val > (1024LL * 1024 * 1024 * 1024 * 1024)) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - pr_fmt, str_len - 1, (val) / (1024LL * 1024 * 1024 * 1024 * 1024), 'P'); - } - else if(val > (1024LL * 1024 * 1024 * 1024)) - { + STRPROPERTY_STORAGE_SIZE, + pr_fmt, + str_len - 1, + (val) / (1024LL * 1024 * 1024 * 1024 * 1024), + 'P'); + } else if(val > (1024LL * 1024 * 1024 * 1024)) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - pr_fmt, str_len - 1, (val) / (1024LL * 1024 * 1024 * 1024), 'T'); - } - else if(val > (1024LL * 1024 * 1024)) - { + STRPROPERTY_STORAGE_SIZE, + pr_fmt, + str_len - 1, + (val) / (1024LL * 1024 * 1024 * 1024), + 'T'); + } else if(val > (1024LL * 1024 * 1024)) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - pr_fmt, str_len - 1, (val) / (1024LL * 1024 * 1024), 'G'); - } - else if(val > (1024 * 1024)) - { + STRPROPERTY_STORAGE_SIZE, + pr_fmt, + str_len - 1, + (val) / (1024LL * 1024 * 1024), + 'G'); + } else if(val > (1024 * 1024)) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - pr_fmt, str_len - 1, (val) / (1024 * 1024), 'M'); - } - else if(val > 1024) - { + STRPROPERTY_STORAGE_SIZE, + pr_fmt, + str_len - 1, + (val) / (1024 * 1024), + 'M'); + } else if(val > 1024) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - pr_fmt, str_len - 1, (val) / (1024), 'K'); - } - else - { + STRPROPERTY_STORAGE_SIZE, + pr_fmt, + str_len - 1, + (val) / (1024), + 'K'); + } else { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - pr_fmt, str_len, val, 0); + STRPROPERTY_STORAGE_SIZE, + pr_fmt, + str_len, + val, + 0); } uint32_t len = (uint32_t)strlen(m_getpropertystr_storage.data()); - if(len > str_len) - { + if(len > str_len) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); memmove(m_getpropertystr_storage.data(), - m_getpropertystr_storage.data() + len - str_len, - str_len + 1); // include trailing \0 + m_getpropertystr_storage.data() + len - str_len, + str_len + 1); // include trailing \0 } return m_getpropertystr_storage.data(); @@ -134,79 +136,73 @@ char* sinsp_filter_check_reference::format_bytes(double val, uint32_t str_len, b #define ONE_MILLISECOND_IN_NS 1000000 #define ONE_MICROSECOND_IN_NS 1000 -char* sinsp_filter_check_reference::format_time(uint64_t val, uint32_t str_len) -{ - if(val >= 3600 * ONE_SECOND_IN_NS) - { +char* sinsp_filter_check_reference::format_time(uint64_t val, uint32_t str_len) { + if(val >= 3600 * ONE_SECOND_IN_NS) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%.2u:%.2u:%.2u", (unsigned int)(val / (3600 * ONE_SECOND_IN_NS)), - (unsigned int)((val / (60 * ONE_SECOND_IN_NS)) % 60 ), - (unsigned int)((val / ONE_SECOND_IN_NS) % 60)); - } - else if(val >= 60 * ONE_SECOND_IN_NS) - { + STRPROPERTY_STORAGE_SIZE, + "%.2u:%.2u:%.2u", + (unsigned int)(val / (3600 * ONE_SECOND_IN_NS)), + (unsigned int)((val / (60 * ONE_SECOND_IN_NS)) % 60), + (unsigned int)((val / ONE_SECOND_IN_NS) % 60)); + } else if(val >= 60 * ONE_SECOND_IN_NS) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%u:%u", (unsigned int)(val / (60 * ONE_SECOND_IN_NS)), (unsigned int)((val / ONE_SECOND_IN_NS) % 60)); - } - else if(val >= ONE_SECOND_IN_NS) - { + STRPROPERTY_STORAGE_SIZE, + "%u:%u", + (unsigned int)(val / (60 * ONE_SECOND_IN_NS)), + (unsigned int)((val / ONE_SECOND_IN_NS) % 60)); + } else if(val >= ONE_SECOND_IN_NS) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%u.%02us", (unsigned int)(val / ONE_SECOND_IN_NS), (unsigned int)((val % ONE_SECOND_IN_NS) / 10000000)); - } - else if(val >= ONE_SECOND_IN_NS / 100) - { + STRPROPERTY_STORAGE_SIZE, + "%u.%02us", + (unsigned int)(val / ONE_SECOND_IN_NS), + (unsigned int)((val % ONE_SECOND_IN_NS) / 10000000)); + } else if(val >= ONE_SECOND_IN_NS / 100) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%ums", (unsigned int)(val / (ONE_SECOND_IN_NS / 1000))); - } - else if(val >= ONE_SECOND_IN_NS / 1000) - { + STRPROPERTY_STORAGE_SIZE, + "%ums", + (unsigned int)(val / (ONE_SECOND_IN_NS / 1000))); + } else if(val >= ONE_SECOND_IN_NS / 1000) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%u.%02ums", (unsigned int)(val / (ONE_SECOND_IN_NS / 1000)), (unsigned int)((val % ONE_MILLISECOND_IN_NS) / 10000)); - } - else if(val >= ONE_SECOND_IN_NS / 100000) - { + STRPROPERTY_STORAGE_SIZE, + "%u.%02ums", + (unsigned int)(val / (ONE_SECOND_IN_NS / 1000)), + (unsigned int)((val % ONE_MILLISECOND_IN_NS) / 10000)); + } else if(val >= ONE_SECOND_IN_NS / 100000) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%uus", (unsigned int)(val / (ONE_SECOND_IN_NS / 1000000))); - } - else if(val >= ONE_SECOND_IN_NS / 1000000) - { + STRPROPERTY_STORAGE_SIZE, + "%uus", + (unsigned int)(val / (ONE_SECOND_IN_NS / 1000000))); + } else if(val >= ONE_SECOND_IN_NS / 1000000) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%u.%02uus", (unsigned int)(val / (ONE_SECOND_IN_NS / 1000000)), (unsigned int)((val % ONE_MICROSECOND_IN_NS) / 10)); - } - else - { + STRPROPERTY_STORAGE_SIZE, + "%u.%02uus", + (unsigned int)(val / (ONE_SECOND_IN_NS / 1000000)), + (unsigned int)((val % ONE_MICROSECOND_IN_NS) / 10)); + } else { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%uns", (unsigned int)val); + STRPROPERTY_STORAGE_SIZE, + "%uns", + (unsigned int)val); } uint32_t reslen = (uint32_t)strlen(m_getpropertystr_storage.data()); - if(reslen < str_len) - { + if(reslen < str_len) { uint32_t padding_size = str_len - reslen; m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); memmove(m_getpropertystr_storage.data() + padding_size, - m_getpropertystr_storage.data(), - str_len + 1); + m_getpropertystr_storage.data(), + str_len + 1); - for(uint32_t j = 0; j < padding_size; j++) - { + for(uint32_t j = 0; j < padding_size; j++) { m_getpropertystr_storage[j] = ' '; } } @@ -214,12 +210,10 @@ char* sinsp_filter_check_reference::format_time(uint64_t val, uint32_t str_len) return m_getpropertystr_storage.data(); } -char* sinsp_filter_check_reference::print_double(uint8_t* rawval, uint32_t str_len) -{ +char* sinsp_filter_check_reference::print_double(uint8_t* rawval, uint32_t str_len) { double val; - switch(get_field_info()->m_type) - { + switch(get_field_info()->m_type) { case PT_INT8: val = (double)*(int8_t*)rawval; break; @@ -250,55 +244,46 @@ char* sinsp_filter_check_reference::print_double(uint8_t* rawval, uint32_t str_l break; } - if(m_cnt > 1) - { + if(m_cnt > 1) { val /= m_cnt; } - if(m_print_format == PF_ID) - { + if(m_print_format == PF_ID) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); - snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%*lf", str_len, val); + snprintf(m_getpropertystr_storage.data(), STRPROPERTY_STORAGE_SIZE, "%*lf", str_len, val); return m_getpropertystr_storage.data(); - } - else - { + } else { return format_bytes(val, str_len, false); } - } -char* sinsp_filter_check_reference::print_int(uint8_t* rawval, uint32_t str_len) -{ +char* sinsp_filter_check_reference::print_int(uint8_t* rawval, uint32_t str_len) { int64_t val; - switch(get_field_info()->m_type) - { + switch(get_field_info()->m_type) { case PT_INT8: - val = (int64_t)*(int8_t*)rawval; + val = (int64_t) * (int8_t*)rawval; break; case PT_INT16: - val = (int64_t)*(int16_t*)rawval; + val = (int64_t) * (int16_t*)rawval; break; case PT_INT32: - val = (int64_t)*(int32_t*)rawval; + val = (int64_t) * (int32_t*)rawval; break; case PT_INT64: - val = (int64_t)*(int64_t*)rawval; + val = (int64_t) * (int64_t*)rawval; break; case PT_UINT8: - val = (int64_t)*(uint8_t*)rawval; + val = (int64_t) * (uint8_t*)rawval; break; case PT_UINT16: - val = (int64_t)*(uint16_t*)rawval; + val = (int64_t) * (uint16_t*)rawval; break; case PT_UINT32: - val = (int64_t)*(uint32_t*)rawval; + val = (int64_t) * (uint32_t*)rawval; break; case PT_UINT64: - val = (int64_t)*(uint64_t*)rawval; + val = (int64_t) * (uint64_t*)rawval; break; default: ASSERT(false); @@ -306,133 +291,107 @@ char* sinsp_filter_check_reference::print_int(uint8_t* rawval, uint32_t str_len) break; } - if(m_cnt > 1) - { + if(m_cnt > 1) { val /= (int64_t)m_cnt; } - if(m_print_format == PF_ID) - { + if(m_print_format == PF_ID) { m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%*" PRId64, str_len, val); + STRPROPERTY_STORAGE_SIZE, + "%*" PRId64, + str_len, + val); return m_getpropertystr_storage.data(); - } - else - { + } else { return format_bytes((double)val, str_len, true); } - } char* sinsp_filter_check_reference::tostring_nice(sinsp_evt* evt, - uint32_t str_len, - uint64_t time_delta) -{ + uint32_t str_len, + uint64_t time_delta) { uint32_t len; // note: this uses the single-value extract because this filtercheck // class does not support multi-valued extraction uint8_t* rawval = extract_single(evt, &len); - if(rawval == NULL) - { + if(rawval == NULL) { return NULL; } - if(time_delta != 0) - { + if(time_delta != 0) { m_cnt = (double)time_delta / ONE_SECOND_IN_NS; } auto type = get_field_info()->m_type; - if(type >= PT_INT8 && type <= PT_UINT64) - { - if(m_print_format == PF_ID || m_cnt == 1 || m_cnt == 0) - { + if(type >= PT_INT8 && type <= PT_UINT64) { + if(m_print_format == PF_ID || m_cnt == 1 || m_cnt == 0) { return print_int(rawval, str_len); - } - else - { + } else { return print_double(rawval, str_len); } - } - else if(type == PT_RELTIME) - { + } else if(type == PT_RELTIME) { double val = (double)*(uint64_t*)rawval; - if(m_cnt > 1) - { + if(m_cnt > 1) { val /= m_cnt; } return format_time((int64_t)val, str_len); - } - else if(type == PT_DOUBLE) - { + } else if(type == PT_DOUBLE) { double dval = (double)*(double*)rawval; - if(m_cnt > 1) - { + if(m_cnt > 1) { dval /= m_cnt; } m_getpropertystr_storage.resize(STRPROPERTY_STORAGE_SIZE); snprintf(m_getpropertystr_storage.data(), - STRPROPERTY_STORAGE_SIZE, - "%*.2lf", str_len, dval); + STRPROPERTY_STORAGE_SIZE, + "%*.2lf", + str_len, + dval); return m_getpropertystr_storage.data(); - } - else - { + } else { return rawval_to_string(rawval, type, m_field->m_print_format, len); } } Json::Value sinsp_filter_check_reference::tojson(sinsp_evt* evt, - uint32_t str_len, - uint64_t time_delta) -{ + uint32_t str_len, + uint64_t time_delta) { uint32_t len; // note: this uses the single-value extract because this filtercheck // class does not support multi-valued extraction uint8_t* rawval = extract_single(evt, &len); - if(rawval == NULL) - { + if(rawval == NULL) { return ""; } - if(time_delta != 0) - { + if(time_delta != 0) { m_cnt = (double)time_delta / ONE_SECOND_IN_NS; } auto type = get_field_info()->m_type; - if(type == PT_RELTIME) - { + if(type == PT_RELTIME) { double val = (double)*(uint64_t*)rawval; - if(m_cnt > 1) - { + if(m_cnt > 1) { val /= m_cnt; } return format_time((int64_t)val, str_len); - } - else if(type == PT_DOUBLE) - { + } else if(type == PT_DOUBLE) { double dval = (double)*(double*)rawval; - if(m_cnt > 1) - { + if(m_cnt > 1) { dval /= m_cnt; } return dval; - } - else - { + } else { return rawval_to_json(rawval, type, m_field->m_print_format, len); } } diff --git a/userspace/libsinsp/sinsp_filtercheck_reference.h b/userspace/libsinsp/sinsp_filtercheck_reference.h index 8e800b2084..1f5ba7a430 100644 --- a/userspace/libsinsp/sinsp_filtercheck_reference.h +++ b/userspace/libsinsp/sinsp_filtercheck_reference.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_reference : public sinsp_filter_check -{ +class sinsp_filter_check_reference : public sinsp_filter_check { public: - enum alignment - { + enum alignment { ALIGN_LEFT, ALIGN_RIGHT, }; @@ -33,13 +31,17 @@ class sinsp_filter_check_reference : public sinsp_filter_check virtual ~sinsp_filter_check_reference() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; - inline void set_val(ppm_param_type type, filtercheck_field_flags flags, - uint8_t* val, int32_t len, - uint32_t cnt, ppm_print_format print_format) - { + inline void set_val(ppm_param_type type, + filtercheck_field_flags flags, + uint8_t* val, + int32_t len, + uint32_t cnt, + ppm_print_format print_format) { m_finfo.m_type = type; m_finfo.m_flags = flags; m_val = val; @@ -49,7 +51,7 @@ class sinsp_filter_check_reference : public sinsp_filter_check } char* tostring_nice(sinsp_evt* evt, uint32_t str_len, uint64_t time_delta); - using sinsp_filter_check::tojson; // to avoid warning: "... hides overloaded virtual function" + using sinsp_filter_check::tojson; // to avoid warning: "... hides overloaded virtual function" Json::Value tojson(sinsp_evt* evt, uint32_t str_len, uint64_t time_delta); private: @@ -62,6 +64,6 @@ class sinsp_filter_check_reference : public sinsp_filter_check filter_check_info m_cinfo; uint8_t* m_val; uint32_t m_len; - double m_cnt; // For averages, this stores the entry count + double m_cnt; // For averages, this stores the entry count ppm_print_format m_print_format; }; diff --git a/userspace/libsinsp/sinsp_filtercheck_syslog.cpp b/userspace/libsinsp/sinsp_filtercheck_syslog.cpp index da53485b45..7fea5a3467 100644 --- a/userspace/libsinsp/sinsp_filtercheck_syslog.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_syslog.cpp @@ -22,62 +22,76 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ + } while(0) -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) -#define RETURN_EXTRACT_CSTR(x) do { \ - if((x)) \ - { \ - *len = strlen((char *) ((x))); \ - } \ - return (uint8_t*) ((x)); \ -} while(0) +#define RETURN_EXTRACT_CSTR(x) \ + do { \ + if((x)) { \ + *len = strlen((char*)((x))); \ + } \ + return (uint8_t*)((x)); \ + } while(0) -static const filtercheck_field_info sinsp_filter_check_syslog_fields[] = -{ - {PT_CHARBUF, EPF_NONE, PF_NA, "syslog.facility.str", "Facility", "facility as a string."}, - {PT_UINT32, EPF_NONE, PF_DEC, "syslog.facility", "Numeric Facility", "facility as a number (0-23)."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "syslog.severity.str", "Severity", "severity as a string. Can have one of these values: emerg, alert, crit, err, warn, notice, info, debug"}, - {PT_UINT32, EPF_NONE, PF_DEC, "syslog.severity", "Numeric Severity", "severity as a number (0-7)."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "syslog.message", "Message", "message sent to syslog."}, +static const filtercheck_field_info sinsp_filter_check_syslog_fields[] = { + {PT_CHARBUF, EPF_NONE, PF_NA, "syslog.facility.str", "Facility", "facility as a string."}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "syslog.facility", + "Numeric Facility", + "facility as a number (0-23)."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "syslog.severity.str", + "Severity", + "severity as a string. Can have one of these values: emerg, alert, crit, err, warn, " + "notice, info, debug"}, + {PT_UINT32, + EPF_NONE, + PF_DEC, + "syslog.severity", + "Numeric Severity", + "severity as a number (0-7)."}, + {PT_CHARBUF, EPF_NONE, PF_NA, "syslog.message", "Message", "message sent to syslog."}, }; -sinsp_filter_check_syslog::sinsp_filter_check_syslog() -{ +sinsp_filter_check_syslog::sinsp_filter_check_syslog() { static const filter_check_info s_field_infos = { - "syslog", - "", - "Content of Syslog messages.", - sizeof(sinsp_filter_check_syslog_fields) / sizeof(sinsp_filter_check_syslog_fields[0]), - sinsp_filter_check_syslog_fields, - filter_check_info::FL_NONE, + "syslog", + "", + "Content of Syslog messages.", + sizeof(sinsp_filter_check_syslog_fields) / sizeof(sinsp_filter_check_syslog_fields[0]), + sinsp_filter_check_syslog_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; } -std::unique_ptr sinsp_filter_check_syslog::allocate_new() -{ +std::unique_ptr sinsp_filter_check_syslog::allocate_new() { return std::make_unique(); } -uint8_t* sinsp_filter_check_syslog::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_syslog::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; auto& decoder = m_inspector->get_parser()->get_syslog_decoder(); - if (!decoder.is_data_valid()) - { + if(!decoder.is_data_valid()) { return NULL; } - switch(m_field_id) - { + switch(m_field_id) { case TYPE_FACILITY: m_storageu32 = decoder.get_facility(); RETURN_EXTRACT_VAR(m_storageu32); diff --git a/userspace/libsinsp/sinsp_filtercheck_syslog.h b/userspace/libsinsp/sinsp_filtercheck_syslog.h index fd7983e6d1..5ae0885d2e 100644 --- a/userspace/libsinsp/sinsp_filtercheck_syslog.h +++ b/userspace/libsinsp/sinsp_filtercheck_syslog.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_syslog : public sinsp_filter_check -{ +class sinsp_filter_check_syslog : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_FACILITY_STR = 0, TYPE_FACILITY, TYPE_SEVERITY_STR, diff --git a/userspace/libsinsp/sinsp_filtercheck_thread.cpp b/userspace/libsinsp/sinsp_filtercheck_thread.cpp index d137396ea2..7e4e5e7233 100644 --- a/userspace/libsinsp/sinsp_filtercheck_thread.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_thread.cpp @@ -22,211 +22,739 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) - -#define RETURN_EXTRACT_PTR(x) do { \ - *len = sizeof(*(x)); \ - return (uint8_t*) (x); \ -} while(0) - -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -static inline bool str_match_start(std::string_view val, size_t len, const char* m) -{ +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ + } while(0) + +#define RETURN_EXTRACT_PTR(x) \ + do { \ + *len = sizeof(*(x)); \ + return (uint8_t*)(x); \ + } while(0) + +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) + +static inline bool str_match_start(std::string_view val, size_t len, const char* m) { return val.compare(0, len, m) == 0; } -#define STR_MATCH(s) str_match_start(val, sizeof (s) -1, s) - -static const filtercheck_field_info sinsp_filter_check_thread_fields[] = -{ - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.exe", "First Argument", "The first command-line argument (i.e., argv[0]), typically the executable name or a custom string as specified by the user. It is primarily obtained from syscall arguments, truncated after 4096 bytes, or, as a fallback, by reading /proc/PID/cmdline, in which case it may be truncated after 1024 bytes. This field may differ from the last component of proc.exepath, reflecting how command invocation and execution paths can vary."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.pexe", "Parent First Argument", "The proc.exe (first command line argument argv[0]) of the parent process."}, - {PT_CHARBUF, EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "proc.aexe", "Ancestor First Argument", "The proc.exe (first command line argument argv[0]) for a specific process ancestor. You can access different levels of ancestors by using indices. For example, proc.aexe[1] retrieves the proc.exe of the parent process, proc.aexe[2] retrieves the proc.exe of the grandparent process, and so on. The current process's proc.exe line can be obtained using proc.aexe[0]. When used without any arguments, proc.aexe is applicable only in filters and matches any of the process ancestors. For instance, you can use `proc.aexe endswith java` to match any process ancestor whose proc.exe ends with the term `java`."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.exepath", "Process Executable Path", "The full executable path of a process, resolving to the canonical path for symlinks. This is primarily obtained from the kernel, or as a fallback, by reading /proc/PID/exe (in the latter case, the path is truncated after 1024 bytes). For eBPF drivers, due to verifier limits, path components may be truncated to 24 for legacy eBPF on kernel <5.2, 48 for legacy eBPF on kernel >=5.2, or 96 for modern eBPF."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.pexepath", "Parent Process Executable Path", "The proc.exepath (full executable path) of the parent process."}, - {PT_CHARBUF, EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "proc.aexepath", "Ancestor Executable Path", "The proc.exepath (full executable path) for a specific process ancestor. You can access different levels of ancestors by using indices. For example, proc.aexepath[1] retrieves the proc.exepath of the parent process, proc.aexepath[2] retrieves the proc.exepath of the grandparent process, and so on. The current process's proc.exepath line can be obtained using proc.aexepath[0]. When used without any arguments, proc.aexepath is applicable only in filters and matches any of the process ancestors. For instance, you can use `proc.aexepath endswith java` to match any process ancestor whose path ends with the term `java`."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.name", "Name", "The process name (truncated after 16 characters) generating the event (task->comm). Truncation is determined by kernel settings and not by Falco. This field is collected from the syscalls args or, as a fallback, extracted from /proc/PID/status. The name of the process and the name of the executable file on disk (if applicable) can be different if a process is given a custom name which is often the case for example for java applications."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.pname", "Parent Name", "The proc.name truncated after 16 characters) of the process generating the event."}, - {PT_CHARBUF, EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "proc.aname", "Ancestor Name", "The proc.name (truncated after 16 characters) for a specific process ancestor. You can access different levels of ancestors by using indices. For example, proc.aname[1] retrieves the proc.name of the parent process, proc.aname[2] retrieves the proc.name of the grandparent process, and so on. The current process's proc.name line can be obtained using proc.aname[0]. When used without any arguments, proc.aname is applicable only in filters and matches any of the process ancestors. For instance, you can use `proc.aname=bash` to match any process ancestor whose name is `bash`."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.args", "Arguments", "The arguments passed on the command line when starting the process generating the event excluding argv[0] (truncated after 4096 bytes). This field is collected from the syscalls args or, as a fallback, extracted from /proc/PID/cmdline."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.cmdline", "Command Line", "The concatenation of `proc.name + proc.args` (truncated after 4096 bytes) when starting the process generating the event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.pcmdline", "Parent Command Line", "The proc.cmdline (full command line (proc.name + proc.args)) of the parent of the process generating the event."}, - {PT_CHARBUF, EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "proc.acmdline", "Ancestor Command Line", "The full command line (proc.name + proc.args) for a specific process ancestor. You can access different levels of ancestors by using indices. For example, proc.acmdline[1] retrieves the full command line of the parent process, proc.acmdline[2] retrieves the proc.cmdline of the grandparent process, and so on. The current process's full command line can be obtained using proc.acmdline[0]. When used without any arguments, proc.acmdline is applicable only in filters and matches any of the process ancestors. For instance, you can use `proc.acmdline contains base64` to match any process ancestor whose command line contains the term base64."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.cmdnargs", "Number of Command Line args", "The number of command line args (proc.args)."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.cmdlenargs", "Total Count of Characters in Command Line args", "The total count of characters / length of the command line args (proc.args) combined excluding whitespaces between args."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.exeline", "Executable Command Line", "The full command line, with exe as first argument (proc.exe + proc.args) when starting the process generating the event."}, - {PT_CHARBUF, EPF_ARG_ALLOWED, PF_NA, "proc.env", "Environment", "The environment variables of the process generating the event as concatenated string 'ENV_NAME=value ENV_NAME1=value1'. Can also be used to extract the value of a known env variable, e.g. proc.env[ENV_NAME]."}, - {PT_CHARBUF, EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_NA, "proc.aenv", "Ancestor Environment", "[EXPERIMENTAL] This field can be used in three flavors: (1) as a filter checking all parents, e.g. 'proc.aenv contains xyz', which is similar to the familiar 'proc.aname contains xyz' approach, (2) checking the `proc.env` of a specified level of the parent, e.g. 'proc.aenv[2]', which is similar to the familiar 'proc.aname[2]' approach, or (3) checking the first matched value of a known ENV_NAME in the parent lineage, such as 'proc.aenv[ENV_NAME]' (across a max of 20 ancestor levels). This field may be deprecated or undergo breaking changes in future releases. Please use it with caution."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.cwd", "Current Working Directory", "The current working directory of the event."}, - {PT_INT64, EPF_NONE, PF_ID, "proc.loginshellid", "Login Shell ID", "The pid of the oldest shell among the ancestors of the current process, if there is one. This field can be used to separate different user sessions."}, - {PT_UINT32, EPF_NONE, PF_ID, "proc.tty", "Process TTY", "The controlling terminal of the process. 0 for processes without a terminal."}, - {PT_INT64, EPF_NONE, PF_ID, "proc.pid", "Process ID", "The id of the process generating the event."}, - {PT_INT64, EPF_NONE, PF_ID, "proc.ppid", "Parent Process ID", "The pid of the parent of the process generating the event."}, - {PT_INT64, EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, PF_ID, "proc.apid", "Ancestor Process ID", "The pid for a specific process ancestor. You can access different levels of ancestors by using indices. For example, proc.apid[1] retrieves the pid of the parent process, proc.apid[2] retrieves the pid of the grandparent process, and so on. The current process's pid can be obtained using proc.apid[0]. When used without any arguments, proc.apid is applicable only in filters and matches any of the process ancestors. For instance, you can use `proc.apid=1337` to match any process ancestor whose pid is equal to 1337."}, - {PT_INT64, EPF_NONE, PF_ID, "proc.vpid", "Virtual Process ID", "The id of the process generating the event as seen from its current PID namespace."}, - {PT_INT64, EPF_NONE, PF_ID, "proc.pvpid", "Parent Virtual Process ID", "The id of the parent process generating the event as seen from its current PID namespace."}, - {PT_INT64, EPF_NONE, PF_ID, "proc.sid", "Process Session ID", "The session id of the process generating the event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.sname", "Process Session Name", "The name of the current process's session leader. This is either the process with pid=proc.sid or the eldest ancestor that has the same sid as the current process."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.sid.exe", "Process Session First Argument", "The first command line argument argv[0] (usually the executable name or a custom one) of the current process's session leader. This is either the process with pid=proc.sid or the eldest ancestor that has the same sid as the current process."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.sid.exepath", "Process Session Executable Path", "The full executable path of the current process's session leader. This is either the process with pid=proc.sid or the eldest ancestor that has the same sid as the current process."}, - {PT_INT64, EPF_NONE, PF_ID, "proc.vpgid", "Process Virtual Group ID", "The process group id of the process generating the event, as seen from its current PID namespace."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.vpgid.name", "Process Group Name", "The name of the current process's process group leader. This is either the process with proc.vpgid == proc.vpid or the eldest ancestor that has the same vpgid as the current process. The description of `proc.is_vpgid_leader` offers additional insights."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.vpgid.exe", "Process Group First Argument", "The first command line argument argv[0] (usually the executable name or a custom one) of the current process's process group leader. This is either the process with proc.vpgid == proc.vpid or the eldest ancestor that has the same vpgid as the current process. The description of `proc.is_vpgid_leader` offers additional insights."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.vpgid.exepath", "Process Group Executable Path", "The full executable path of the current process's process group leader. This is either the process with proc.vpgid == proc.vpid or the eldest ancestor that has the same vpgid as the current process. The description of `proc.is_vpgid_leader` offers additional insights."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "proc.duration", "Process Duration", "Number of nanoseconds since the process started."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "proc.ppid.duration", "Parent Process Duration", "Number of nanoseconds since the parent process started."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "proc.pid.ts", "Process start ts", "Start of process as epoch timestamp in nanoseconds."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "proc.ppid.ts", "Parent Process start ts", "Start of parent process as epoch timestamp in nanoseconds."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_exe_writable", "Process Executable Is Writable", "'true' if this process' executable file is writable by the same user that spawned the process."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_exe_upper_layer", "Process Executable Is In Upper Layer", "'true' if this process' executable file is in upper layer in overlayfs. This field value can only be trusted if the underlying kernel version is greater or equal than 3.18.0, since overlayfs was introduced at that time."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_exe_lower_layer", "Process Executable Is In Lower Layer", "'true' if this process' executable file is in lower layer in overlayfs. This field value can only be trusted if the underlying kernel version is greater or equal than 3.18.0, since overlayfs was introduced at that time."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_exe_from_memfd", "Process Executable Is Stored In Memfd", "'true' if the executable file of the current process is an anonymous file created using memfd_create() and is being executed by referencing its file descriptor (fd). This type of file exists only in memory and not on disk. Relevant to detect malicious in-memory code injection. Requires kernel version greater or equal to 3.17.0."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_sid_leader", "Process Is Process Session Leader", "'true' if this process is the leader of the process session, proc.sid == proc.vpid. For host processes vpid reflects pid."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_vpgid_leader", "Process Is Virtual Process Group Leader", "'true' if this process is the leader of the virtual process group, proc.vpgid == proc.vpid. For host processes vpgid and vpid reflect pgid and pid. Can help to distinguish if the process was 'directly' executed for instance in a tty (similar to bash history logging, `is_vpgid_leader` would be 'true') or executed as descendent process in the same process group which for example is the case when subprocesses are spawned from a script (`is_vpgid_leader` would be 'false')."}, - {PT_INT64, EPF_NONE, PF_DEC, "proc.exe_ino", "Inode number of executable file on disk", "The inode number of the executable file on disk. Can be correlated with fd.ino."}, - {PT_ABSTIME, EPF_NONE, PF_DEC, "proc.exe_ino.ctime", "Last status change time (ctime) of executable file", "Last status change time of executable file (inode->ctime) as epoch timestamp in nanoseconds. Time is changed by writing or by setting inode information e.g. owner, group, link count, mode etc."}, - {PT_ABSTIME, EPF_NONE, PF_DEC, "proc.exe_ino.mtime", "Last modification time (mtime) of executable file", "Last modification time of executable file (inode->mtime) as epoch timestamp in nanoseconds. Time is changed by file modifications, e.g. by mknod, truncate, utime, write of more than zero bytes etc. For tracking changes in owner, group, link count or mode, use proc.exe_ino.ctime instead."}, - {PT_ABSTIME, EPF_NONE, PF_DEC, "proc.exe_ino.ctime_duration_proc_start", "Number of nanoseconds between ctime exe file and proc clone ts", "Number of nanoseconds between modifying status of executable image and spawning a new process using the changed executable image."}, - {PT_ABSTIME, EPF_NONE, PF_DEC, "proc.exe_ino.ctime_duration_pidns_start", "Number of nanoseconds between pidns start ts and ctime exe file", "Number of nanoseconds between PID namespace start ts and ctime exe file if PID namespace start predates ctime."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.pidns_init_start_ts", "Start ts of pid namespace", "Start of PID namespace (container or non container pid namespace) as epoch timestamp in nanoseconds."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "thread.cap_permitted", "Permitted capabilities", "The permitted capabilities set"}, - {PT_CHARBUF, EPF_NONE, PF_NA, "thread.cap_inheritable", "Inheritable capabilities", "The inheritable capabilities set"}, - {PT_CHARBUF, EPF_NONE, PF_NA, "thread.cap_effective", "Effective capabilities", "The effective capabilities set"}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_container_healthcheck", "Process Is Container Healthcheck", "'true' if this process is running as a part of the container's health check."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_container_liveness_probe", "Process Is Container Liveness", "'true' if this process is running as a part of the container's liveness probe."}, - {PT_BOOL, EPF_NONE, PF_NA, "proc.is_container_readiness_probe", "Process Is Container Readiness", "'true' if this process is running as a part of the container's readiness probe."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.fdopencount", "FD Count", "Number of open FDs for the process"}, - {PT_INT64, EPF_NONE, PF_DEC, "proc.fdlimit", "FD Limit", "Maximum number of FDs the process can open."}, - {PT_DOUBLE, EPF_NONE, PF_NA, "proc.fdusage", "FD Usage", "The ratio between open FDs and maximum available FDs for the process."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.vmsize", "VM Size", "Total virtual memory for the process (as kb)."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.vmrss", "VM RSS", "Resident non-swapped memory for the process (as kb)."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.vmswap", "VM Swap", "Swapped memory for the process (as kb)."}, - {PT_UINT64, EPF_NONE, PF_DEC, "thread.pfmajor", "Major Page Faults", "Number of major page faults since thread start."}, - {PT_UINT64, EPF_NONE, PF_DEC, "thread.pfminor", "Minor Page Faults", "Number of minor page faults since thread start."}, - {PT_INT64, EPF_NONE, PF_ID, "thread.tid", "Thread ID", "The id of the thread generating the event."}, - {PT_BOOL, EPF_NONE, PF_NA, "thread.ismain", "Main Thread", "'true' if the thread generating the event is the main one in the process."}, - {PT_INT64, EPF_NONE, PF_ID, "thread.vtid", "Virtual Thread ID", "The id of the thread generating the event as seen from its current PID namespace."}, - {PT_CHARBUF, EPF_TABLE_ONLY, PF_NA, "thread.nametid", "Thread Name + ID", "This field chains the process name and tid of a thread and can be used as a specific identifier of a thread for a specific execve."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "thread.exectime", "Scheduled Thread CPU Time", "CPU time spent by the last scheduled thread, in nanoseconds. Exported by switch events only."}, - {PT_RELTIME, EPF_NONE, PF_DEC, "thread.totexectime", "Current Thread CPU Time", "Total CPU time, in nanoseconds since the beginning of the capture, for the current thread. Exported by switch events only."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "thread.cgroups", "Thread Cgroups", "All cgroups the thread belongs to, aggregated into a single string."}, - {PT_CHARBUF, EPF_ARG_REQUIRED, PF_NA, "thread.cgroup", "Thread Cgroup", "The cgroup the thread belongs to, for a specific subsystem. e.g. thread.cgroup.cpuacct."}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.nthreads", "Threads", "The number of alive threads that the process generating the event currently has, including the leader thread. Please note that the leader thread may not be here, in that case 'proc.nthreads' and 'proc.nchilds' are equal"}, - {PT_UINT64, EPF_NONE, PF_DEC, "proc.nchilds", "Children", "The number of alive not leader threads that the process generating the event currently has. This excludes the leader thread."}, - {PT_DOUBLE, EPF_NONE, PF_NA, "thread.cpu", "Thread CPU", "The CPU consumed by the thread in the last second."}, - {PT_DOUBLE, EPF_NONE, PF_NA, "thread.cpu.user", "Thread User CPU", "The user CPU consumed by the thread in the last second."}, - {PT_DOUBLE, EPF_NONE, PF_NA, "thread.cpu.system", "Thread System CPU", "The system CPU consumed by the thread in the last second."}, - {PT_UINT64, EPF_NONE, PF_DEC, "thread.vmsize", "Thread VM Size (kb)", "For the process main thread, this is the total virtual memory for the process (as kb). For the other threads, this field is zero."}, - {PT_UINT64, EPF_NONE, PF_DEC, "thread.vmrss", "Thread VM RSS (kb)", "For the process main thread, this is the resident non-swapped memory for the process (as kb). For the other threads, this field is zero."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "thread.vmsize.b", "Thread VM Size (b)", "For the process main thread, this is the total virtual memory for the process (in bytes). For the other threads, this field is zero."}, - {PT_UINT64, EPF_TABLE_ONLY, PF_DEC, "thread.vmrss.b", "Thread VM RSS (b)", "For the process main thread, this is the resident non-swapped memory for the process (in bytes). For the other threads, this field is zero."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.stdin.type", "Standard Input fd type", "The type of file descriptor 0, corresponding to stdin, of the process generating the event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.stdout.type", "Standard Output fd type", "The type of file descriptor 1, corresponding to stdout, of the process generating the event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.stderr.type", "Standard Error fd type", "The type of file descriptor 2, corresponding to stderr, of the process generating the event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.stdin.name", "Standard Input fd name", "The name of the file descriptor 0, corresponding to stdin, of the process generating the event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.stdout.name", "Standard Output fd name", "The name of the file descriptor 1, corresponding to stdout, of the process generating the event."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "proc.stderr.name", "Standard Error fd name", "The name of the file descriptor 2, corresponding to stderr, of the process generating the event."}, +#define STR_MATCH(s) str_match_start(val, sizeof(s) - 1, s) + +static const filtercheck_field_info sinsp_filter_check_thread_fields[] = { + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.exe", + "First Argument", + "The first command-line argument (i.e., argv[0]), typically the executable name or a " + "custom string as specified by the user. It is primarily obtained from syscall arguments, " + "truncated after 4096 bytes, or, as a fallback, by reading /proc/PID/cmdline, in which " + "case it may be truncated after 1024 bytes. This field may differ from the last component " + "of proc.exepath, reflecting how command invocation and execution paths can vary."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.pexe", + "Parent First Argument", + "The proc.exe (first command line argument argv[0]) of the parent process."}, + {PT_CHARBUF, + EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "proc.aexe", + "Ancestor First Argument", + "The proc.exe (first command line argument argv[0]) for a specific process ancestor. You " + "can access different levels of ancestors by using indices. For example, proc.aexe[1] " + "retrieves the proc.exe of the parent process, proc.aexe[2] retrieves the proc.exe of the " + "grandparent process, and so on. The current process's proc.exe line can be obtained " + "using proc.aexe[0]. When used without any arguments, proc.aexe is applicable only in " + "filters and matches any of the process ancestors. For instance, you can use `proc.aexe " + "endswith java` to match any process ancestor whose proc.exe ends with the term `java`."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.exepath", + "Process Executable Path", + "The full executable path of a process, resolving to the canonical path for symlinks. " + "This is primarily obtained from the kernel, or as a fallback, by reading /proc/PID/exe " + "(in the latter case, the path is truncated after 1024 bytes). For eBPF drivers, due to " + "verifier limits, path components may be truncated to 24 for legacy eBPF on kernel <5.2, " + "48 for legacy eBPF on kernel >=5.2, or 96 for modern eBPF."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.pexepath", + "Parent Process Executable Path", + "The proc.exepath (full executable path) of the parent process."}, + {PT_CHARBUF, + EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "proc.aexepath", + "Ancestor Executable Path", + "The proc.exepath (full executable path) for a specific process ancestor. You can access " + "different levels of ancestors by using indices. For example, proc.aexepath[1] retrieves " + "the proc.exepath of the parent process, proc.aexepath[2] retrieves the proc.exepath of " + "the grandparent process, and so on. The current process's proc.exepath line can be " + "obtained using proc.aexepath[0]. When used without any arguments, proc.aexepath is " + "applicable only in filters and matches any of the process ancestors. For instance, you " + "can use `proc.aexepath endswith java` to match any process ancestor whose path ends with " + "the term `java`."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.name", + "Name", + "The process name (truncated after 16 characters) generating the event (task->comm). " + "Truncation is determined by kernel settings and not by Falco. This field is collected " + "from the syscalls args or, as a fallback, extracted from /proc/PID/status. The name of " + "the process and the name of the executable file on disk (if applicable) can be different " + "if a process is given a custom name which is often the case for example for java " + "applications."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.pname", + "Parent Name", + "The proc.name truncated after 16 characters) of the process generating the event."}, + {PT_CHARBUF, + EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "proc.aname", + "Ancestor Name", + "The proc.name (truncated after 16 characters) for a specific process ancestor. You can " + "access different levels of ancestors by using indices. For example, proc.aname[1] " + "retrieves the proc.name of the parent process, proc.aname[2] retrieves the proc.name of " + "the grandparent process, and so on. The current process's proc.name line can be obtained " + "using proc.aname[0]. When used without any arguments, proc.aname is applicable only in " + "filters and matches any of the process ancestors. For instance, you can use " + "`proc.aname=bash` to match any process ancestor whose name is `bash`."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.args", + "Arguments", + "The arguments passed on the command line when starting the process generating the event " + "excluding argv[0] (truncated after 4096 bytes). This field is collected from the " + "syscalls args or, as a fallback, extracted from /proc/PID/cmdline."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.cmdline", + "Command Line", + "The concatenation of `proc.name + proc.args` (truncated after 4096 bytes) when starting " + "the process generating the event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.pcmdline", + "Parent Command Line", + "The proc.cmdline (full command line (proc.name + proc.args)) of the parent of the " + "process generating the event."}, + {PT_CHARBUF, + EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "proc.acmdline", + "Ancestor Command Line", + "The full command line (proc.name + proc.args) for a specific process ancestor. You can " + "access different levels of ancestors by using indices. For example, proc.acmdline[1] " + "retrieves the full command line of the parent process, proc.acmdline[2] retrieves the " + "proc.cmdline of the grandparent process, and so on. The current process's full command " + "line can be obtained using proc.acmdline[0]. When used without any arguments, " + "proc.acmdline is applicable only in filters and matches any of the process ancestors. " + "For instance, you can use `proc.acmdline contains base64` to match any process ancestor " + "whose command line contains the term base64."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.cmdnargs", + "Number of Command Line args", + "The number of command line args (proc.args)."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.cmdlenargs", + "Total Count of Characters in Command Line args", + "The total count of characters / length of the command line args (proc.args) combined " + "excluding whitespaces between args."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.exeline", + "Executable Command Line", + "The full command line, with exe as first argument (proc.exe + proc.args) when starting " + "the process generating the event."}, + {PT_CHARBUF, + EPF_ARG_ALLOWED, + PF_NA, + "proc.env", + "Environment", + "The environment variables of the process generating the event as concatenated string " + "'ENV_NAME=value ENV_NAME1=value1'. Can also be used to extract the value of a known env " + "variable, e.g. proc.env[ENV_NAME]."}, + {PT_CHARBUF, + EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_NA, + "proc.aenv", + "Ancestor Environment", + "[EXPERIMENTAL] This field can be used in three flavors: (1) as a filter checking all " + "parents, e.g. 'proc.aenv contains xyz', which is similar to the familiar 'proc.aname " + "contains xyz' approach, (2) checking the `proc.env` of a specified level of the parent, " + "e.g. 'proc.aenv[2]', which is similar to the familiar 'proc.aname[2]' approach, or (3) " + "checking the first matched value of a known ENV_NAME in the parent lineage, such as " + "'proc.aenv[ENV_NAME]' (across a max of 20 ancestor levels). This field may be deprecated " + "or undergo breaking changes in future releases. Please use it with caution."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.cwd", + "Current Working Directory", + "The current working directory of the event."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "proc.loginshellid", + "Login Shell ID", + "The pid of the oldest shell among the ancestors of the current process, if there is one. " + "This field can be used to separate different user sessions."}, + {PT_UINT32, + EPF_NONE, + PF_ID, + "proc.tty", + "Process TTY", + "The controlling terminal of the process. 0 for processes without a terminal."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "proc.pid", + "Process ID", + "The id of the process generating the event."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "proc.ppid", + "Parent Process ID", + "The pid of the parent of the process generating the event."}, + {PT_INT64, + EPF_ARG_ALLOWED | EPF_NO_RHS | EPF_NO_TRANSFORMER, + PF_ID, + "proc.apid", + "Ancestor Process ID", + "The pid for a specific process ancestor. You can access different levels of ancestors by " + "using indices. For example, proc.apid[1] retrieves the pid of the parent process, " + "proc.apid[2] retrieves the pid of the grandparent process, and so on. The current " + "process's pid can be obtained using proc.apid[0]. When used without any arguments, " + "proc.apid is applicable only in filters and matches any of the process ancestors. For " + "instance, you can use `proc.apid=1337` to match any process ancestor whose pid is equal " + "to 1337."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "proc.vpid", + "Virtual Process ID", + "The id of the process generating the event as seen from its current PID namespace."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "proc.pvpid", + "Parent Virtual Process ID", + "The id of the parent process generating the event as seen from its current PID " + "namespace."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "proc.sid", + "Process Session ID", + "The session id of the process generating the event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.sname", + "Process Session Name", + "The name of the current process's session leader. This is either the process with " + "pid=proc.sid or the eldest ancestor that has the same sid as the current process."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.sid.exe", + "Process Session First Argument", + "The first command line argument argv[0] (usually the executable name or a custom one) of " + "the current process's session leader. This is either the process with pid=proc.sid or " + "the eldest ancestor that has the same sid as the current process."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.sid.exepath", + "Process Session Executable Path", + "The full executable path of the current process's session leader. This is either the " + "process with pid=proc.sid or the eldest ancestor that has the same sid as the current " + "process."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "proc.vpgid", + "Process Virtual Group ID", + "The process group id of the process generating the event, as seen from its current PID " + "namespace."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.vpgid.name", + "Process Group Name", + "The name of the current process's process group leader. This is either the process with " + "proc.vpgid == proc.vpid or the eldest ancestor that has the same vpgid as the current " + "process. The description of `proc.is_vpgid_leader` offers additional insights."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.vpgid.exe", + "Process Group First Argument", + "The first command line argument argv[0] (usually the executable name or a custom one) of " + "the current process's process group leader. This is either the process with proc.vpgid " + "== proc.vpid or the eldest ancestor that has the same vpgid as the current process. The " + "description of `proc.is_vpgid_leader` offers additional insights."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.vpgid.exepath", + "Process Group Executable Path", + "The full executable path of the current process's process group leader. This is either " + "the process with proc.vpgid == proc.vpid or the eldest ancestor that has the same vpgid " + "as the current process. The description of `proc.is_vpgid_leader` offers additional " + "insights."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "proc.duration", + "Process Duration", + "Number of nanoseconds since the process started."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "proc.ppid.duration", + "Parent Process Duration", + "Number of nanoseconds since the parent process started."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "proc.pid.ts", + "Process start ts", + "Start of process as epoch timestamp in nanoseconds."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "proc.ppid.ts", + "Parent Process start ts", + "Start of parent process as epoch timestamp in nanoseconds."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_exe_writable", + "Process Executable Is Writable", + "'true' if this process' executable file is writable by the same user that spawned the " + "process."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_exe_upper_layer", + "Process Executable Is In Upper Layer", + "'true' if this process' executable file is in upper layer in overlayfs. This field value " + "can only be trusted if the underlying kernel version is greater or equal than 3.18.0, " + "since overlayfs was introduced at that time."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_exe_lower_layer", + "Process Executable Is In Lower Layer", + "'true' if this process' executable file is in lower layer in overlayfs. This field value " + "can only be trusted if the underlying kernel version is greater or equal than 3.18.0, " + "since overlayfs was introduced at that time."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_exe_from_memfd", + "Process Executable Is Stored In Memfd", + "'true' if the executable file of the current process is an anonymous file created using " + "memfd_create() and is being executed by referencing its file descriptor (fd). This type " + "of file exists only in memory and not on disk. Relevant to detect malicious in-memory " + "code injection. Requires kernel version greater or equal to 3.17.0."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_sid_leader", + "Process Is Process Session Leader", + "'true' if this process is the leader of the process session, proc.sid == proc.vpid. For " + "host processes vpid reflects pid."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_vpgid_leader", + "Process Is Virtual Process Group Leader", + "'true' if this process is the leader of the virtual process group, proc.vpgid == " + "proc.vpid. For host processes vpgid and vpid reflect pgid and pid. Can help to " + "distinguish if the process was 'directly' executed for instance in a tty (similar to " + "bash history logging, `is_vpgid_leader` would be 'true') or executed as descendent " + "process in the same process group which for example is the case when subprocesses are " + "spawned from a script (`is_vpgid_leader` would be 'false')."}, + {PT_INT64, + EPF_NONE, + PF_DEC, + "proc.exe_ino", + "Inode number of executable file on disk", + "The inode number of the executable file on disk. Can be correlated with fd.ino."}, + {PT_ABSTIME, + EPF_NONE, + PF_DEC, + "proc.exe_ino.ctime", + "Last status change time (ctime) of executable file", + "Last status change time of executable file (inode->ctime) as epoch timestamp in " + "nanoseconds. Time is changed by writing or by setting inode information e.g. owner, " + "group, link count, mode etc."}, + {PT_ABSTIME, + EPF_NONE, + PF_DEC, + "proc.exe_ino.mtime", + "Last modification time (mtime) of executable file", + "Last modification time of executable file (inode->mtime) as epoch timestamp in " + "nanoseconds. Time is changed by file modifications, e.g. by mknod, truncate, utime, " + "write of more than zero bytes etc. For tracking changes in owner, group, link count or " + "mode, use proc.exe_ino.ctime instead."}, + {PT_ABSTIME, + EPF_NONE, + PF_DEC, + "proc.exe_ino.ctime_duration_proc_start", + "Number of nanoseconds between ctime exe file and proc clone ts", + "Number of nanoseconds between modifying status of executable image and spawning a new " + "process using the changed executable image."}, + {PT_ABSTIME, + EPF_NONE, + PF_DEC, + "proc.exe_ino.ctime_duration_pidns_start", + "Number of nanoseconds between pidns start ts and ctime exe file", + "Number of nanoseconds between PID namespace start ts and ctime exe file if PID namespace " + "start predates ctime."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.pidns_init_start_ts", + "Start ts of pid namespace", + "Start of PID namespace (container or non container pid namespace) as epoch timestamp in " + "nanoseconds."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "thread.cap_permitted", + "Permitted capabilities", + "The permitted capabilities set"}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "thread.cap_inheritable", + "Inheritable capabilities", + "The inheritable capabilities set"}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "thread.cap_effective", + "Effective capabilities", + "The effective capabilities set"}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_container_healthcheck", + "Process Is Container Healthcheck", + "'true' if this process is running as a part of the container's health check."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_container_liveness_probe", + "Process Is Container Liveness", + "'true' if this process is running as a part of the container's liveness probe."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "proc.is_container_readiness_probe", + "Process Is Container Readiness", + "'true' if this process is running as a part of the container's readiness probe."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.fdopencount", + "FD Count", + "Number of open FDs for the process"}, + {PT_INT64, + EPF_NONE, + PF_DEC, + "proc.fdlimit", + "FD Limit", + "Maximum number of FDs the process can open."}, + {PT_DOUBLE, + EPF_NONE, + PF_NA, + "proc.fdusage", + "FD Usage", + "The ratio between open FDs and maximum available FDs for the process."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.vmsize", + "VM Size", + "Total virtual memory for the process (as kb)."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.vmrss", + "VM RSS", + "Resident non-swapped memory for the process (as kb)."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.vmswap", + "VM Swap", + "Swapped memory for the process (as kb)."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "thread.pfmajor", + "Major Page Faults", + "Number of major page faults since thread start."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "thread.pfminor", + "Minor Page Faults", + "Number of minor page faults since thread start."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "thread.tid", + "Thread ID", + "The id of the thread generating the event."}, + {PT_BOOL, + EPF_NONE, + PF_NA, + "thread.ismain", + "Main Thread", + "'true' if the thread generating the event is the main one in the process."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "thread.vtid", + "Virtual Thread ID", + "The id of the thread generating the event as seen from its current PID namespace."}, + {PT_CHARBUF, + EPF_TABLE_ONLY, + PF_NA, + "thread.nametid", + "Thread Name + ID", + "This field chains the process name and tid of a thread and can be used as a specific " + "identifier of a thread for a specific execve."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "thread.exectime", + "Scheduled Thread CPU Time", + "CPU time spent by the last scheduled thread, in nanoseconds. Exported by switch events " + "only."}, + {PT_RELTIME, + EPF_NONE, + PF_DEC, + "thread.totexectime", + "Current Thread CPU Time", + "Total CPU time, in nanoseconds since the beginning of the capture, for the current " + "thread. Exported by switch events only."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "thread.cgroups", + "Thread Cgroups", + "All cgroups the thread belongs to, aggregated into a single string."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED, + PF_NA, + "thread.cgroup", + "Thread Cgroup", + "The cgroup the thread belongs to, for a specific subsystem. e.g. thread.cgroup.cpuacct."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.nthreads", + "Threads", + "The number of alive threads that the process generating the event currently has, " + "including the leader thread. Please note that the leader thread may not be here, in that " + "case 'proc.nthreads' and 'proc.nchilds' are equal"}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "proc.nchilds", + "Children", + "The number of alive not leader threads that the process generating the event currently " + "has. This excludes the leader thread."}, + {PT_DOUBLE, + EPF_NONE, + PF_NA, + "thread.cpu", + "Thread CPU", + "The CPU consumed by the thread in the last second."}, + {PT_DOUBLE, + EPF_NONE, + PF_NA, + "thread.cpu.user", + "Thread User CPU", + "The user CPU consumed by the thread in the last second."}, + {PT_DOUBLE, + EPF_NONE, + PF_NA, + "thread.cpu.system", + "Thread System CPU", + "The system CPU consumed by the thread in the last second."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "thread.vmsize", + "Thread VM Size (kb)", + "For the process main thread, this is the total virtual memory for the process (as kb). " + "For the other threads, this field is zero."}, + {PT_UINT64, + EPF_NONE, + PF_DEC, + "thread.vmrss", + "Thread VM RSS (kb)", + "For the process main thread, this is the resident non-swapped memory for the process (as " + "kb). For the other threads, this field is zero."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "thread.vmsize.b", + "Thread VM Size (b)", + "For the process main thread, this is the total virtual memory for the process (in " + "bytes). For the other threads, this field is zero."}, + {PT_UINT64, + EPF_TABLE_ONLY, + PF_DEC, + "thread.vmrss.b", + "Thread VM RSS (b)", + "For the process main thread, this is the resident non-swapped memory for the process (in " + "bytes). For the other threads, this field is zero."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.stdin.type", + "Standard Input fd type", + "The type of file descriptor 0, corresponding to stdin, of the process generating the " + "event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.stdout.type", + "Standard Output fd type", + "The type of file descriptor 1, corresponding to stdout, of the process generating the " + "event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.stderr.type", + "Standard Error fd type", + "The type of file descriptor 2, corresponding to stderr, of the process generating the " + "event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.stdin.name", + "Standard Input fd name", + "The name of the file descriptor 0, corresponding to stdin, of the process generating the " + "event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.stdout.name", + "Standard Output fd name", + "The name of the file descriptor 1, corresponding to stdout, of the process generating " + "the event."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "proc.stderr.name", + "Standard Error fd name", + "The name of the file descriptor 2, corresponding to stderr, of the process generating " + "the event."}, }; -sinsp_filter_check_thread::sinsp_filter_check_thread() -{ +sinsp_filter_check_thread::sinsp_filter_check_thread() { static const filter_check_info s_field_infos = { - "process", - "", - "Additional information about the process and thread executing the syscall event.", - sizeof(sinsp_filter_check_thread_fields) / sizeof(sinsp_filter_check_thread_fields[0]), - sinsp_filter_check_thread_fields, - filter_check_info::FL_NONE, + "process", + "", + "Additional information about the process and thread executing the syscall event.", + sizeof(sinsp_filter_check_thread_fields) / sizeof(sinsp_filter_check_thread_fields[0]), + sinsp_filter_check_thread_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; memset(&m_val, 0, sizeof(m_val)); } -std::unique_ptr sinsp_filter_check_thread::allocate_new() -{ +std::unique_ptr sinsp_filter_check_thread::allocate_new() { return std::make_unique(); } -int32_t sinsp_filter_check_thread::extract_arg(std::string_view fldname, std::string_view val, const ppm_param_info** parinfo) -{ +int32_t sinsp_filter_check_thread::extract_arg(std::string_view fldname, + std::string_view val, + const ppm_param_info** parinfo) { std::string::size_type parsed_len = 0; // // 'arg' and 'resarg' are handled in a custom way // - if(m_field_id == TYPE_APID || - m_field_id == TYPE_ANAME || - m_field_id == TYPE_AEXE || - m_field_id == TYPE_AEXEPATH || - m_field_id == TYPE_ACMDLINE) - { - if(val.size() > fldname.size() && val.at(fldname.size()) == '[') - { + if(m_field_id == TYPE_APID || m_field_id == TYPE_ANAME || m_field_id == TYPE_AEXE || + m_field_id == TYPE_AEXEPATH || m_field_id == TYPE_ACMDLINE) { + if(val.size() > fldname.size() && val.at(fldname.size()) == '[') { parsed_len = val.find(']'); - if(parsed_len == std::string::npos) - { - throw sinsp_exception("the field '" + string(fldname) + "' requires an argument but ']' is not found"); + if(parsed_len == std::string::npos) { + throw sinsp_exception("the field '" + string(fldname) + + "' requires an argument but ']' is not found"); } string numstr(val.substr(fldname.size() + 1, parsed_len - fldname.size() - 1)); m_argid = sinsp_numparser::parsed32(numstr); parsed_len++; - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } - } - else if(m_field_id == TYPE_ENV || - m_field_id == TYPE_AENV ) - { - if(val.size() > fldname.size() && val.at(fldname.size()) == '[') - { + } else if(m_field_id == TYPE_ENV || m_field_id == TYPE_AENV) { + if(val.size() > fldname.size() && val.at(fldname.size()) == '[') { std::string::size_type startpos = fldname.size(); parsed_len = val.find(']', startpos); - if(parsed_len == std::string::npos) - { - throw sinsp_exception("the field '" + string(fldname) + "' requires an argument but ']' is not found"); + if(parsed_len == std::string::npos) { + throw sinsp_exception("the field '" + string(fldname) + + "' requires an argument but ']' is not found"); } m_argname = val.substr(startpos + 1, parsed_len - startpos - 1); - if(!m_argname.empty() && std::all_of(m_argname.begin(), m_argname.end(), [](unsigned char c) { return std::isdigit(c); })) - { + if(!m_argname.empty() && std::all_of(m_argname.begin(), + m_argname.end(), + [](unsigned char c) { return std::isdigit(c); })) { m_argid = sinsp_numparser::parsed32(m_argname); m_argname.clear(); } parsed_len++; - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } - } - else if(m_field_id == TYPE_CGROUP) - { - if(val.size() > fldname.size() && val.at(fldname.size()) == '.') - { + } else if(m_field_id == TYPE_CGROUP) { + if(val.size() > fldname.size() && val.at(fldname.size()) == '.') { std::string::size_type endpos; - for(endpos = fldname.size() + 1; endpos < val.length(); ++endpos) - { - if(!isalpha(val.at(endpos)) - && val.at(endpos) != '_') - { + for(endpos = fldname.size() + 1; endpos < val.length(); ++endpos) { + if(!isalpha(val.at(endpos)) && val.at(endpos) != '_') { break; } } parsed_len = endpos; m_argname = val.substr(fldname.size() + 1, endpos - fldname.size() - 1); - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } } @@ -234,74 +762,56 @@ int32_t sinsp_filter_check_thread::extract_arg(std::string_view fldname, std::st return (int32_t)parsed_len; } -int32_t sinsp_filter_check_thread::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ - if(STR_MATCH("arg")) - { +int32_t sinsp_filter_check_thread::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { + if(STR_MATCH("arg")) { // // 'arg' is handled in a custom way // throw sinsp_exception("filter error: proc.arg filter not implemented yet"); - } - else if(STR_MATCH("proc.apid")) - { + } else if(STR_MATCH("proc.apid")) { m_field_id = TYPE_APID; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; - try - { + try { res = extract_arg("proc.apid", val, NULL); - } - catch(...) - { - if(val == "proc.apid") - { + } catch(...) { + if(val == "proc.apid") { m_argid = -1; res = (int32_t)val.size(); } } return res; - } - else if(STR_MATCH("proc.aname")) - { + } else if(STR_MATCH("proc.aname")) { m_field_id = TYPE_ANAME; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; - try - { + try { res = extract_arg("proc.aname", val, NULL); - } - catch(...) - { - if(val == "proc.aname") - { + } catch(...) { + if(val == "proc.aname") { m_argid = -1; res = (int32_t)val.size(); } } return res; - } - else if(STR_MATCH("proc.aexepath")) - { + } else if(STR_MATCH("proc.aexepath")) { m_field_id = TYPE_AEXEPATH; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; - try - { + try { res = extract_arg("proc.aexepath", val, NULL); - } - catch(...) - { - if(val == "proc.aexepath") - { + } catch(...) { + if(val == "proc.aexepath") { m_argid = -1; res = (int32_t)val.size(); } @@ -309,88 +819,66 @@ int32_t sinsp_filter_check_thread::parse_field_name(std::string_view val, bool a return res; } - /* note: because of str similarity of proc.aexe to proc.aexepath, this needs to be placed after proc.aexepath */ - else if(STR_MATCH("proc.aexe")) - { + /* note: because of str similarity of proc.aexe to proc.aexepath, this needs to be placed after + proc.aexepath */ + else if(STR_MATCH("proc.aexe")) { m_field_id = TYPE_AEXE; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; - try - { + try { res = extract_arg("proc.aexe", val, NULL); - } - catch(...) - { - if(val == "proc.aexe") - { + } catch(...) { + if(val == "proc.aexe") { m_argid = -1; res = (int32_t)val.size(); } } return res; - } - else if(STR_MATCH("proc.acmdline")) - { + } else if(STR_MATCH("proc.acmdline")) { m_field_id = TYPE_ACMDLINE; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; - try - { + try { res = extract_arg("proc.acmdline", val, NULL); - } - catch(...) - { - if(val == "proc.acmdline") - { + } catch(...) { + if(val == "proc.acmdline") { m_argid = -1; res = (int32_t)val.size(); } } return res; - } - else if(STR_MATCH("proc.env")) - { + } else if(STR_MATCH("proc.env")) { m_field_id = TYPE_ENV; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; - try - { + try { res = extract_arg("proc.env", val, NULL); - } - catch(...) - { - if(val == "proc.env") - { + } catch(...) { + if(val == "proc.env") { m_argname.clear(); res = (int32_t)val.size(); } } return res; - } - else if(STR_MATCH("proc.aenv")) - { + } else if(STR_MATCH("proc.aenv")) { m_field_id = TYPE_AENV; m_field = &m_info->m_fields[m_field_id]; int32_t res = 0; - try - { + try { res = extract_arg("proc.aenv", val, NULL); - } - catch(...) - { - if(val == "proc.aenv") - { + } catch(...) { + if(val == "proc.aenv") { m_argname.clear(); m_argid = -1; res = (int32_t)val.size(); @@ -398,64 +886,54 @@ int32_t sinsp_filter_check_thread::parse_field_name(std::string_view val, bool a } return res; - } - else if(STR_MATCH("thread.totexectime")) - { + } else if(STR_MATCH("thread.totexectime")) { // // Allocate thread storage for the value // - if(alloc_state) - { - auto acc = m_inspector->m_thread_manager->dynamic_fields()->add_field("_tmp_sinsp_filter_thread_totexectime"); + if(alloc_state) { + auto acc = m_inspector->m_thread_manager->dynamic_fields()->add_field( + "_tmp_sinsp_filter_thread_totexectime"); m_thread_dyn_field_accessor = - std::make_unique>(acc.new_accessor()); + std::make_unique>( + acc.new_accessor()); } return sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); - } - else if(STR_MATCH("thread.cgroup") && - !STR_MATCH("thread.cgroups")) - { + } else if(STR_MATCH("thread.cgroup") && !STR_MATCH("thread.cgroups")) { m_field_id = TYPE_CGROUP; m_field = &m_info->m_fields[m_field_id]; return extract_arg("thread.cgroup", val, NULL); - } - else if(STR_MATCH("thread.cpu")) - { - if(alloc_state) - { - auto acc = m_inspector->m_thread_manager->dynamic_fields()->add_field("_tmp_sinsp_filter_thread_cpu"); + } else if(STR_MATCH("thread.cpu")) { + if(alloc_state) { + auto acc = m_inspector->m_thread_manager->dynamic_fields()->add_field( + "_tmp_sinsp_filter_thread_cpu"); m_thread_dyn_field_accessor = - std::make_unique>(acc.new_accessor()); + std::make_unique>( + acc.new_accessor()); } return sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); - } - else - { + } else { return sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } } -uint64_t sinsp_filter_check_thread::extract_exectime(sinsp_evt *evt) -{ +uint64_t sinsp_filter_check_thread::extract_exectime(sinsp_evt* evt) { uint64_t res = 0; - if(m_last_proc_switch_times.size() == 0) - { + if(m_last_proc_switch_times.size() == 0) { // // Initialize the vector of CPU times // const scap_machine_info* minfo = m_inspector->get_machine_info(); ASSERT(minfo->num_cpus != 0); - if (minfo == NULL || minfo->num_cpus == 0) { + if(minfo == NULL || minfo->num_cpus == 0) { return res; } - for(uint32_t j = 0; j < minfo->num_cpus; j++) - { + for(uint32_t j = 0; j < minfo->num_cpus; j++) { m_last_proc_switch_times.push_back(0); } } @@ -464,8 +942,7 @@ uint64_t sinsp_filter_check_thread::extract_exectime(sinsp_evt *evt) uint64_t ts = evt->get_ts(); uint64_t lasttime = m_last_proc_switch_times[cpuid]; - if(lasttime != 0) - { + if(lasttime != 0) { res = ts - lasttime; } @@ -476,23 +953,23 @@ uint64_t sinsp_filter_check_thread::extract_exectime(sinsp_evt *evt) return res; } -uint8_t* sinsp_filter_check_thread::extract_thread_cpu(sinsp_evt *evt, uint32_t* len, sinsp_threadinfo* tinfo, bool extract_user, bool extract_system) -{ +uint8_t* sinsp_filter_check_thread::extract_thread_cpu(sinsp_evt* evt, + uint32_t* len, + sinsp_threadinfo* tinfo, + bool extract_user, + bool extract_system) { uint16_t etype = evt->get_type(); - if(etype == PPME_PROCINFO_E) - { + if(etype == PPME_PROCINFO_E) { uint64_t user = 0; uint64_t system = 0; uint64_t tcpu; - if(extract_user) - { + if(extract_user) { user = evt->get_param(0)->as(); } - if(extract_system) - { + if(extract_system) { system = evt->get_param(1)->as(); } @@ -500,17 +977,13 @@ uint8_t* sinsp_filter_check_thread::extract_thread_cpu(sinsp_evt *evt, uint32_t* uint64_t last_t_tot_cpu = 0; tinfo->get_dynamic_field(*m_thread_dyn_field_accessor, last_t_tot_cpu); - if(last_t_tot_cpu != 0) - { + if(last_t_tot_cpu != 0) { uint64_t deltaval = tcpu - last_t_tot_cpu; - m_val.d = (double)deltaval;// / (ONE_SECOND_IN_NS / 100); - if(m_val.d > 100) - { + m_val.d = (double)deltaval; // / (ONE_SECOND_IN_NS / 100); + if(m_val.d > 100) { m_val.d = 100; } - } - else - { + } else { m_val.d = 0; } @@ -523,38 +996,32 @@ uint8_t* sinsp_filter_check_thread::extract_thread_cpu(sinsp_evt *evt, uint32_t* } // Some syscall sources, such as the gVisor integration, cannot match events to host PIDs and TIDs. -// The event will retain the PID field which is consistent with the rest of sinsp logic, but it won't represent -// a real PID and so it should not be displayed to the user. -inline bool should_extract_xid(int64_t xid) -{ +// The event will retain the PID field which is consistent with the rest of sinsp logic, but it +// won't represent a real PID and so it should not be displayed to the user. +inline bool should_extract_xid(int64_t xid) { return xid >= -1 && xid <= UINT32_MAX; } -uint8_t* sinsp_filter_check_thread::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_thread::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL && - m_field_id != TYPE_TID && - m_field_id != TYPE_EXECTIME && - m_field_id != TYPE_TOTEXECTIME) - { + if(tinfo == NULL && m_field_id != TYPE_TID && m_field_id != TYPE_EXECTIME && + m_field_id != TYPE_TOTEXECTIME) { return NULL; } - switch(m_field_id) - { + switch(m_field_id) { case TYPE_TID: m_val.s64 = evt->get_tid(); - if (!should_extract_xid(m_val.s64)) - { + if(!should_extract_xid(m_val.s64)) { return NULL; } RETURN_EXTRACT_VAR(m_val.s64); case TYPE_PID: - if (!should_extract_xid(tinfo->m_pid)) - { + if(!should_extract_xid(tinfo->m_pid)) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_pid); @@ -562,257 +1029,226 @@ uint8_t* sinsp_filter_check_thread::extract_single(sinsp_evt *evt, uint32_t* len RETURN_EXTRACT_VAR(tinfo->m_sid); case TYPE_VPGID: RETURN_EXTRACT_VAR(tinfo->m_vpgid); - case TYPE_SNAME: - { - int64_t sid = tinfo->m_sid; - - if(!tinfo->is_in_pid_namespace()) - { - // Relying on the convention that a session id is the process id of the session leader. - // `threadinfo` lookup only applies when the process is running on the host and not in a pid - // namespace. However, if the process is running in a pid namespace, we instead traverse the process - // lineage until we find a match. - sinsp_threadinfo* sinfo = m_inspector->get_thread_ref(sid, false, true).get(); - if(sinfo != NULL) - { - m_tstr = sinfo->get_comm(); - RETURN_EXTRACT_STRING(m_tstr); - } + case TYPE_SNAME: { + int64_t sid = tinfo->m_sid; + + if(!tinfo->is_in_pid_namespace()) { + // Relying on the convention that a session id is the process id of the session leader. + // `threadinfo` lookup only applies when the process is running on the host and not in a + // pid namespace. However, if the process is running in a pid namespace, we instead + // traverse the process lineage until we find a match. + sinsp_threadinfo* sinfo = m_inspector->get_thread_ref(sid, false, true).get(); + if(sinfo != NULL) { + m_tstr = sinfo->get_comm(); + RETURN_EXTRACT_STRING(m_tstr); } + } - // This can occur when the session leader process has exited or if the process - // is running in a pid namespace and we only have the virtual session id, as - // seen from its pid namespace. - // Find the highest ancestor process that has the same session id and - // declare it to be the session leader. - sinsp_threadinfo* session_leader = tinfo; - - sinsp_threadinfo::visitor_func_t visitor = [sid, &session_leader](sinsp_threadinfo* pt) - { - if(pt->m_sid != sid) - { - return false; - } - session_leader = pt; - return true; - }; + // This can occur when the session leader process has exited or if the process + // is running in a pid namespace and we only have the virtual session id, as + // seen from its pid namespace. + // Find the highest ancestor process that has the same session id and + // declare it to be the session leader. + sinsp_threadinfo* session_leader = tinfo; - tinfo->traverse_parent_state(visitor); + sinsp_threadinfo::visitor_func_t visitor = [sid, &session_leader](sinsp_threadinfo* pt) { + if(pt->m_sid != sid) { + return false; + } + session_leader = pt; + return true; + }; - // session_leader has been updated to the highest process that has the same session id. - // session_leader's comm is considered the session leader. - m_tstr = session_leader->get_comm(); - RETURN_EXTRACT_STRING(m_tstr); - } - case TYPE_SID_EXE: - { - int64_t sid = tinfo->m_sid; + tinfo->traverse_parent_state(visitor); - if(!tinfo->is_in_pid_namespace()) - { - // Relying on the convention that a session id is the process id of the session leader. - // `threadinfo` lookup only applies when the process is running on the host and not in a pid - // namespace. However, if the process is running in a pid namespace, we instead traverse the process - // lineage until we find a match. - sinsp_threadinfo* sinfo = m_inspector->get_thread_ref(sid, false, true).get(); - if(sinfo != NULL) - { - m_tstr = sinfo->get_exe(); - RETURN_EXTRACT_STRING(m_tstr); - } + // session_leader has been updated to the highest process that has the same session id. + // session_leader's comm is considered the session leader. + m_tstr = session_leader->get_comm(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_SID_EXE: { + int64_t sid = tinfo->m_sid; + + if(!tinfo->is_in_pid_namespace()) { + // Relying on the convention that a session id is the process id of the session leader. + // `threadinfo` lookup only applies when the process is running on the host and not in a + // pid namespace. However, if the process is running in a pid namespace, we instead + // traverse the process lineage until we find a match. + sinsp_threadinfo* sinfo = m_inspector->get_thread_ref(sid, false, true).get(); + if(sinfo != NULL) { + m_tstr = sinfo->get_exe(); + RETURN_EXTRACT_STRING(m_tstr); } + } - // This can occur when the session leader process has exited or if the process - // is running in a pid namespace and we only have the virtual session id, as - // seen from its pid namespace. - // Find the highest ancestor process that has the same session id and - // declare it to be the session leader. - sinsp_threadinfo* session_leader = tinfo; + // This can occur when the session leader process has exited or if the process + // is running in a pid namespace and we only have the virtual session id, as + // seen from its pid namespace. + // Find the highest ancestor process that has the same session id and + // declare it to be the session leader. + sinsp_threadinfo* session_leader = tinfo; - sinsp_threadinfo::visitor_func_t visitor = [sid, &session_leader](sinsp_threadinfo* pt) - { - if(pt->m_sid != sid) - { - return false; - } - session_leader = pt; - return true; - }; + sinsp_threadinfo::visitor_func_t visitor = [sid, &session_leader](sinsp_threadinfo* pt) { + if(pt->m_sid != sid) { + return false; + } + session_leader = pt; + return true; + }; - tinfo->traverse_parent_state(visitor); + tinfo->traverse_parent_state(visitor); - // session_leader has been updated to the highest process that has the same session id. - // session_leader's exe is considered the session leader. - m_tstr = session_leader->get_exe(); - RETURN_EXTRACT_STRING(m_tstr); - } - case TYPE_SID_EXEPATH: - { - int64_t sid = tinfo->m_sid; - - if(!tinfo->is_in_pid_namespace()) - { - // Relying on the convention that a session id is the process id of the session leader. - // `threadinfo` lookup only applies when the process is running on the host and not in a pid - // namespace. However, if the process is running in a pid namespace, we instead traverse the process - // lineage until we find a match. - sinsp_threadinfo* sinfo = m_inspector->get_thread_ref(sid, false, true).get(); - if(sinfo != NULL) - { - m_tstr = sinfo->get_exepath(); - RETURN_EXTRACT_STRING(m_tstr); - } + // session_leader has been updated to the highest process that has the same session id. + // session_leader's exe is considered the session leader. + m_tstr = session_leader->get_exe(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_SID_EXEPATH: { + int64_t sid = tinfo->m_sid; + + if(!tinfo->is_in_pid_namespace()) { + // Relying on the convention that a session id is the process id of the session leader. + // `threadinfo` lookup only applies when the process is running on the host and not in a + // pid namespace. However, if the process is running in a pid namespace, we instead + // traverse the process lineage until we find a match. + sinsp_threadinfo* sinfo = m_inspector->get_thread_ref(sid, false, true).get(); + if(sinfo != NULL) { + m_tstr = sinfo->get_exepath(); + RETURN_EXTRACT_STRING(m_tstr); } + } - // This can occur when the session leader process has exited or if the process - // is running in a pid namespace and we only have the virtual session id, as - // seen from its pid namespace. - // Find the highest ancestor process that has the same session id and - // declare it to be the session leader. - sinsp_threadinfo* session_leader = tinfo; + // This can occur when the session leader process has exited or if the process + // is running in a pid namespace and we only have the virtual session id, as + // seen from its pid namespace. + // Find the highest ancestor process that has the same session id and + // declare it to be the session leader. + sinsp_threadinfo* session_leader = tinfo; - sinsp_threadinfo::visitor_func_t visitor = [sid, &session_leader](sinsp_threadinfo* pt) - { - if(pt->m_sid != sid) - { - return false; - } - session_leader = pt; - return true; - }; + sinsp_threadinfo::visitor_func_t visitor = [sid, &session_leader](sinsp_threadinfo* pt) { + if(pt->m_sid != sid) { + return false; + } + session_leader = pt; + return true; + }; - tinfo->traverse_parent_state(visitor); + tinfo->traverse_parent_state(visitor); - // session_leader has been updated to the highest process that has the same session id. - // session_leader's exepath is considered the session leader. - m_tstr = session_leader->get_exepath(); - RETURN_EXTRACT_STRING(m_tstr); + // session_leader has been updated to the highest process that has the same session id. + // session_leader's exepath is considered the session leader. + m_tstr = session_leader->get_exepath(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_VPGID_NAME: { + int64_t vpgid = tinfo->m_vpgid; + + if(!tinfo->is_in_pid_namespace()) { + // Relying on the convention that a process group id is the process id of the process + // group leader. `threadinfo` lookup only applies when the process is running on the + // host and not in a pid namespace. However, if the process is running in a pid + // namespace, we instead traverse the process lineage until we find a match. + sinsp_threadinfo* vpgidinfo = m_inspector->get_thread_ref(vpgid, false, true).get(); + if(vpgidinfo != NULL) { + m_tstr = vpgidinfo->get_comm(); + RETURN_EXTRACT_STRING(m_tstr); + } } - case TYPE_VPGID_NAME: - { - int64_t vpgid = tinfo->m_vpgid; + // This can occur when the process group leader process has exited or if the process + // is running in a pid namespace and we only have the virtual process group id, as + // seen from its pid namespace. + // Find the highest ancestor process that has the same process group id and + // declare it to be the process group leader. + sinsp_threadinfo* group_leader = tinfo; - if(!tinfo->is_in_pid_namespace()) - { - // Relying on the convention that a process group id is the process id of the process group leader. - // `threadinfo` lookup only applies when the process is running on the host and not in a pid - // namespace. However, if the process is running in a pid namespace, we instead traverse the process - // lineage until we find a match. - sinsp_threadinfo* vpgidinfo = m_inspector->get_thread_ref(vpgid, false, true).get(); - if(vpgidinfo != NULL) - { - m_tstr = vpgidinfo->get_comm(); - RETURN_EXTRACT_STRING(m_tstr); - } + sinsp_threadinfo::visitor_func_t visitor = [vpgid, &group_leader](sinsp_threadinfo* pt) { + if(pt->m_vpgid != vpgid) { + return false; } - // This can occur when the process group leader process has exited or if the process - // is running in a pid namespace and we only have the virtual process group id, as - // seen from its pid namespace. - // Find the highest ancestor process that has the same process group id and - // declare it to be the process group leader. - sinsp_threadinfo* group_leader = tinfo; - - sinsp_threadinfo::visitor_func_t visitor = [vpgid, &group_leader](sinsp_threadinfo* pt) - { - if(pt->m_vpgid != vpgid) - { - return false; - } - group_leader = pt; - return true; - }; + group_leader = pt; + return true; + }; - tinfo->traverse_parent_state(visitor); + tinfo->traverse_parent_state(visitor); - // group_leader has been updated to the highest process that has the same process group id. - // group_leader's comm is considered the process group leader. - m_tstr = group_leader->get_comm(); - RETURN_EXTRACT_STRING(m_tstr); + // group_leader has been updated to the highest process that has the same process group id. + // group_leader's comm is considered the process group leader. + m_tstr = group_leader->get_comm(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_VPGID_EXE: { + int64_t vpgid = tinfo->m_vpgid; + + if(!tinfo->is_in_pid_namespace()) { + // Relying on the convention that a process group id is the process id of the process + // group leader. `threadinfo` lookup only applies when the process is running on the + // host and not in a pid namespace. However, if the process is running in a pid + // namespace, we instead traverse the process lineage until we find a match. + sinsp_threadinfo* vpgidinfo = m_inspector->get_thread_ref(vpgid, false, true).get(); + if(vpgidinfo != NULL) { + m_tstr = vpgidinfo->get_exe(); + RETURN_EXTRACT_STRING(m_tstr); + } } - case TYPE_VPGID_EXE: - { - int64_t vpgid = tinfo->m_vpgid; + // This can occur when the process group leader process has exited or if the process + // is running in a pid namespace and we only have the virtual process group id, as + // seen from its pid namespace. + // Find the highest ancestor process that has the same process group id and + // declare it to be the process group leader. + sinsp_threadinfo* group_leader = tinfo; - if(!tinfo->is_in_pid_namespace()) - { - // Relying on the convention that a process group id is the process id of the process group leader. - // `threadinfo` lookup only applies when the process is running on the host and not in a pid - // namespace. However, if the process is running in a pid namespace, we instead traverse the process - // lineage until we find a match. - sinsp_threadinfo* vpgidinfo = m_inspector->get_thread_ref(vpgid, false, true).get(); - if(vpgidinfo != NULL) - { - m_tstr = vpgidinfo->get_exe(); - RETURN_EXTRACT_STRING(m_tstr); - } + sinsp_threadinfo::visitor_func_t visitor = [vpgid, &group_leader](sinsp_threadinfo* pt) { + if(pt->m_vpgid != vpgid) { + return false; } - // This can occur when the process group leader process has exited or if the process - // is running in a pid namespace and we only have the virtual process group id, as - // seen from its pid namespace. - // Find the highest ancestor process that has the same process group id and - // declare it to be the process group leader. - sinsp_threadinfo* group_leader = tinfo; - - sinsp_threadinfo::visitor_func_t visitor = [vpgid, &group_leader](sinsp_threadinfo* pt) - { - if(pt->m_vpgid != vpgid) - { - return false; - } - group_leader = pt; - return true; - }; - - tinfo->traverse_parent_state(visitor); - - // group_leader has been updated to the highest process that has the same process group id. - // group_leader's exe is considered the process group leader. - m_tstr = group_leader->get_exe(); - RETURN_EXTRACT_STRING(m_tstr); + group_leader = pt; + return true; + }; - } - case TYPE_VPGID_EXEPATH: - { - int64_t vpgid = tinfo->m_vpgid; + tinfo->traverse_parent_state(visitor); - if(!tinfo->is_in_pid_namespace()) - { - // Relying on the convention that a process group id is the process id of the process group leader. - // `threadinfo` lookup only applies when the process is running on the host and not in a pid - // namespace. However, if the process is running in a pid namespace, we instead traverse the process - // lineage until we find a match. - sinsp_threadinfo* vpgidinfo = m_inspector->get_thread_ref(vpgid, false, true).get(); - if(vpgidinfo != NULL) - { - m_tstr = vpgidinfo->get_exepath(); - RETURN_EXTRACT_STRING(m_tstr); - } + // group_leader has been updated to the highest process that has the same process group id. + // group_leader's exe is considered the process group leader. + m_tstr = group_leader->get_exe(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_VPGID_EXEPATH: { + int64_t vpgid = tinfo->m_vpgid; + + if(!tinfo->is_in_pid_namespace()) { + // Relying on the convention that a process group id is the process id of the process + // group leader. `threadinfo` lookup only applies when the process is running on the + // host and not in a pid namespace. However, if the process is running in a pid + // namespace, we instead traverse the process lineage until we find a match. + sinsp_threadinfo* vpgidinfo = m_inspector->get_thread_ref(vpgid, false, true).get(); + if(vpgidinfo != NULL) { + m_tstr = vpgidinfo->get_exepath(); + RETURN_EXTRACT_STRING(m_tstr); } + } - // This can occur when the process group leader process has exited or if the process - // is running in a pid namespace and we only have the virtual process group id, as - // seen from its pid namespace. - // Find the highest ancestor process that has the same process group id and - // declare it to be the process group leader. - sinsp_threadinfo* group_leader = tinfo; + // This can occur when the process group leader process has exited or if the process + // is running in a pid namespace and we only have the virtual process group id, as + // seen from its pid namespace. + // Find the highest ancestor process that has the same process group id and + // declare it to be the process group leader. + sinsp_threadinfo* group_leader = tinfo; - sinsp_threadinfo::visitor_func_t visitor = [vpgid, &group_leader](sinsp_threadinfo* pt) - { - if(pt->m_vpgid != vpgid) - { - return false; - } - group_leader = pt; - return true; - }; + sinsp_threadinfo::visitor_func_t visitor = [vpgid, &group_leader](sinsp_threadinfo* pt) { + if(pt->m_vpgid != vpgid) { + return false; + } + group_leader = pt; + return true; + }; - tinfo->traverse_parent_state(visitor); + tinfo->traverse_parent_state(visitor); - // group_leader has been updated to the highest process that has the same process group id. - // group_leader's exepath is considered the process group leader. - m_tstr = group_leader->get_exepath(); - RETURN_EXTRACT_STRING(m_tstr); - } + // group_leader has been updated to the highest process that has the same process group id. + // group_leader's exepath is considered the process group leader. + m_tstr = group_leader->get_exepath(); + RETURN_EXTRACT_STRING(m_tstr); + } case TYPE_TTY: RETURN_EXTRACT_VAR(tinfo->m_tty); case TYPE_NAME: @@ -824,498 +1260,385 @@ uint8_t* sinsp_filter_check_thread::extract_single(sinsp_evt *evt, uint32_t* len case TYPE_EXEPATH: m_tstr = tinfo->get_exepath(); RETURN_EXTRACT_STRING(m_tstr); - case TYPE_ARGS: - { - m_tstr.clear(); + case TYPE_ARGS: { + m_tstr.clear(); - uint32_t j; - uint32_t nargs = (uint32_t)tinfo->m_args.size(); + uint32_t j; + uint32_t nargs = (uint32_t)tinfo->m_args.size(); - for(j = 0; j < nargs; j++) - { - m_tstr += tinfo->m_args[j]; - if(j < nargs -1) - { - m_tstr += ' '; - } + for(j = 0; j < nargs; j++) { + m_tstr += tinfo->m_args[j]; + if(j < nargs - 1) { + m_tstr += ' '; } + } + + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_ENV: { + m_tstr.clear(); + // proc.env[ENV_NAME] use case: returns matched env variable value + if(!m_argname.empty()) { + m_tstr = tinfo->get_env(m_argname); + RETURN_EXTRACT_STRING(m_tstr); + } else { + m_tstr = tinfo->concatenate_all_env(); RETURN_EXTRACT_STRING(m_tstr); } - case TYPE_ENV: - { - m_tstr.clear(); + } + case TYPE_AENV: { + m_tstr.clear(); - // proc.env[ENV_NAME] use case: returns matched env variable value - if(!m_argname.empty()) - { - m_tstr = tinfo->get_env(m_argname); - RETURN_EXTRACT_STRING(m_tstr); - } - else - { - m_tstr = tinfo->concatenate_all_env(); - RETURN_EXTRACT_STRING(m_tstr); - } + // in case of proc.aenv without [ENV_NAME] return proc.env; same applies for proc.aenv[0] + if(m_argname.empty() && m_argid < 1) { + m_tstr = tinfo->concatenate_all_env(); + RETURN_EXTRACT_STRING(m_tstr); } - case TYPE_AENV: - { - m_tstr.clear(); - // in case of proc.aenv without [ENV_NAME] return proc.env; same applies for proc.aenv[0] - if(m_argname.empty() && m_argid < 1) - { - m_tstr = tinfo->concatenate_all_env(); + // get current tinfo / init for subsequent parent lineage traversal + sinsp_threadinfo* mt = NULL; + if(tinfo->is_main_thread()) { + mt = tinfo; + } else { + mt = tinfo->get_main_thread(); + if(mt == NULL) { RETURN_EXTRACT_STRING(m_tstr); } + } - // get current tinfo / init for subsequent parent lineage traversal - sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { - mt = tinfo; - } - else + if(!m_argname.empty()) // extract a specific ENV_NAME value + { + // start parent lineage traversal + for(int32_t j = 0; j < 20; j++) // up to 20 levels, but realistically we will exit way + // before given the mt nullptr check { - mt = tinfo->get_main_thread(); - if(mt == NULL) - { - RETURN_EXTRACT_STRING(m_tstr); + mt = mt->get_parent_thread(); + + if(mt == NULL) { + break; } - } - if(!m_argname.empty()) // extract a specific ENV_NAME value - { - // start parent lineage traversal - for(int32_t j = 0; j < 20; j++) // up to 20 levels, but realistically we will exit way before given the mt nullptr check - { - mt = mt->get_parent_thread(); - - if(mt == NULL) - { - break; - } - - m_tstr = mt->get_env(m_argname); - if(!m_tstr.empty()) - { - break; - } + m_tstr = mt->get_env(m_argname); + if(!m_tstr.empty()) { + break; } - RETURN_EXTRACT_STRING(m_tstr); } - else if(m_argid > 0) - { - // start parent lineage traversal - for(int32_t j = 0; j < m_argid; j++) - { - mt = mt->get_parent_thread(); - - if(mt == NULL) - { - return NULL; - } - } + RETURN_EXTRACT_STRING(m_tstr); + } else if(m_argid > 0) { + // start parent lineage traversal + for(int32_t j = 0; j < m_argid; j++) { + mt = mt->get_parent_thread(); - // parent tinfo specified found; extract env - m_tstr = mt->concatenate_all_env(); - RETURN_EXTRACT_STRING(m_tstr); + if(mt == NULL) { + return NULL; + } } + + // parent tinfo specified found; extract env + m_tstr = mt->concatenate_all_env(); RETURN_EXTRACT_STRING(m_tstr); } - case TYPE_CMDLINE: - { - sinsp_threadinfo::populate_cmdline(m_tstr, tinfo); - RETURN_EXTRACT_STRING(m_tstr); - } - case TYPE_EXELINE: - { - m_tstr = tinfo->get_exe() + " "; + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_CMDLINE: { + sinsp_threadinfo::populate_cmdline(m_tstr, tinfo); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_EXELINE: { + m_tstr = tinfo->get_exe() + " "; - uint32_t j; - uint32_t nargs = (uint32_t)tinfo->m_args.size(); + uint32_t j; + uint32_t nargs = (uint32_t)tinfo->m_args.size(); - for(j = 0; j < nargs; j++) - { - m_tstr += tinfo->m_args[j]; - if(j < nargs -1) - { - m_tstr += ' '; - } + for(j = 0; j < nargs; j++) { + m_tstr += tinfo->m_args[j]; + if(j < nargs - 1) { + m_tstr += ' '; } - - RETURN_EXTRACT_STRING(m_tstr); } + + RETURN_EXTRACT_STRING(m_tstr); + } case TYPE_CWD: m_tstr = tinfo->get_cwd(); RETURN_EXTRACT_STRING(m_tstr); - case TYPE_NTHREADS: - { - m_val.u64 = tinfo->get_num_threads(); - RETURN_EXTRACT_VAR(m_val.u64); - } - break; - case TYPE_NCHILDS: - { - m_val.u64 = tinfo->get_num_not_leader_threads(); - RETURN_EXTRACT_VAR(m_val.u64); - } - break; + case TYPE_NTHREADS: { + m_val.u64 = tinfo->get_num_threads(); + RETURN_EXTRACT_VAR(m_val.u64); + } break; + case TYPE_NCHILDS: { + m_val.u64 = tinfo->get_num_not_leader_threads(); + RETURN_EXTRACT_VAR(m_val.u64); + } break; case TYPE_ISMAINTHREAD: m_val.u32 = (uint32_t)tinfo->is_main_thread(); RETURN_EXTRACT_VAR(m_val.u32); - case TYPE_EXECTIME: - { - m_val.u64 = 0; - uint16_t etype = evt->get_type(); + case TYPE_EXECTIME: { + m_val.u64 = 0; + uint16_t etype = evt->get_type(); - if(etype == PPME_SCHEDSWITCH_1_E || etype == PPME_SCHEDSWITCH_6_E) - { - m_val.u64 = extract_exectime(evt); - } - - RETURN_EXTRACT_VAR(m_val.u64); + if(etype == PPME_SCHEDSWITCH_1_E || etype == PPME_SCHEDSWITCH_6_E) { + m_val.u64 = extract_exectime(evt); } - case TYPE_TOTEXECTIME: - { - m_val.u64 = 0; - uint16_t etype = evt->get_type(); - if(etype == PPME_SCHEDSWITCH_1_E || etype == PPME_SCHEDSWITCH_6_E) - { - m_val.u64 = extract_exectime(evt); - } + RETURN_EXTRACT_VAR(m_val.u64); + } + case TYPE_TOTEXECTIME: { + m_val.u64 = 0; + uint16_t etype = evt->get_type(); - sinsp_threadinfo* tinfo = evt->get_thread_info(false); + if(etype == PPME_SCHEDSWITCH_1_E || etype == PPME_SCHEDSWITCH_6_E) { + m_val.u64 = extract_exectime(evt); + } - if(tinfo != NULL) - { - uint64_t ptot = 0; - tinfo->get_dynamic_field(*m_thread_dyn_field_accessor, ptot); - m_val.u64 += ptot; - tinfo->set_dynamic_field(*m_thread_dyn_field_accessor, m_val.u64); - RETURN_EXTRACT_VAR(m_val.u64); - } - else - { - return NULL; - } + sinsp_threadinfo* tinfo = evt->get_thread_info(false); + + if(tinfo != NULL) { + uint64_t ptot = 0; + tinfo->get_dynamic_field(*m_thread_dyn_field_accessor, ptot); + m_val.u64 += ptot; + tinfo->set_dynamic_field(*m_thread_dyn_field_accessor, m_val.u64); + RETURN_EXTRACT_VAR(m_val.u64); + } else { + return NULL; } + } case TYPE_PPID: - if(tinfo->is_main_thread()) - { - if (!should_extract_xid(tinfo->m_ptid)) - { + if(tinfo->is_main_thread()) { + if(!should_extract_xid(tinfo->m_ptid)) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_ptid); - } - else - { + } else { sinsp_threadinfo* mt = tinfo->get_main_thread(); - if(mt != NULL) - { - if (!should_extract_xid(mt->m_ptid)) - { + if(mt != NULL) { + if(!should_extract_xid(mt->m_ptid)) { return NULL; } RETURN_EXTRACT_VAR(mt->m_ptid); - } - else - { + } else { return NULL; } } - case TYPE_PNAME: - { - sinsp_threadinfo* ptinfo = - m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); + case TYPE_PNAME: { + sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); - if(ptinfo != NULL) - { - m_tstr = ptinfo->get_comm(); - RETURN_EXTRACT_STRING(m_tstr); - } - else - { - return NULL; - } + if(ptinfo != NULL) { + m_tstr = ptinfo->get_comm(); + RETURN_EXTRACT_STRING(m_tstr); + } else { + return NULL; } - case TYPE_PCMDLINE: - { - sinsp_threadinfo* ptinfo = - m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); + } + case TYPE_PCMDLINE: { + sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); - if(ptinfo != NULL) - { - sinsp_threadinfo::populate_cmdline(m_tstr, ptinfo); - RETURN_EXTRACT_STRING(m_tstr); - } - else - { - return NULL; - } + if(ptinfo != NULL) { + sinsp_threadinfo::populate_cmdline(m_tstr, ptinfo); + RETURN_EXTRACT_STRING(m_tstr); + } else { + return NULL; } - case TYPE_ACMDLINE: - { - sinsp_threadinfo* mt = NULL; - - if(tinfo->is_main_thread()) - { - mt = tinfo; - } - else - { - mt = tinfo->get_main_thread(); - - if(mt == NULL) - { - return NULL; - } - } + } + case TYPE_ACMDLINE: { + sinsp_threadinfo* mt = NULL; - for(int32_t j = 0; j < m_argid; j++) - { - mt = mt->get_parent_thread(); + if(tinfo->is_main_thread()) { + mt = tinfo; + } else { + mt = tinfo->get_main_thread(); - if(mt == NULL) - { - return NULL; - } + if(mt == NULL) { + return NULL; } - sinsp_threadinfo::populate_cmdline(m_tstr, mt); - RETURN_EXTRACT_STRING(m_tstr); } - case TYPE_APID: - { - sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { - mt = tinfo; - } - else - { - mt = tinfo->get_main_thread(); + for(int32_t j = 0; j < m_argid; j++) { + mt = mt->get_parent_thread(); - if(mt == NULL) - { - return NULL; - } + if(mt == NULL) { + return NULL; } + } + sinsp_threadinfo::populate_cmdline(m_tstr, mt); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_APID: { + sinsp_threadinfo* mt = NULL; - // - // Search for a specific ancestors - // - for(int32_t j = 0; j < m_argid; j++) - { - mt = mt->get_parent_thread(); + if(tinfo->is_main_thread()) { + mt = tinfo; + } else { + mt = tinfo->get_main_thread(); - if(mt == NULL) - { - return NULL; - } + if(mt == NULL) { + return NULL; } + } - if (!should_extract_xid(mt->m_pid)) - { + // + // Search for a specific ancestors + // + for(int32_t j = 0; j < m_argid; j++) { + mt = mt->get_parent_thread(); + + if(mt == NULL) { return NULL; } - RETURN_EXTRACT_VAR(mt->m_pid); } - case TYPE_ANAME: - { - sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { - mt = tinfo; - } - else - { - mt = tinfo->get_main_thread(); + if(!should_extract_xid(mt->m_pid)) { + return NULL; + } + RETURN_EXTRACT_VAR(mt->m_pid); + } + case TYPE_ANAME: { + sinsp_threadinfo* mt = NULL; - if(mt == NULL) - { - return NULL; - } + if(tinfo->is_main_thread()) { + mt = tinfo; + } else { + mt = tinfo->get_main_thread(); + + if(mt == NULL) { + return NULL; } + } - for(int32_t j = 0; j < m_argid; j++) - { - mt = mt->get_parent_thread(); + for(int32_t j = 0; j < m_argid; j++) { + mt = mt->get_parent_thread(); - if(mt == NULL) - { - return NULL; - } + if(mt == NULL) { + return NULL; } + } + + m_tstr = mt->get_comm(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_PEXE: { + sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); - m_tstr = mt->get_comm(); + if(ptinfo != NULL) { + m_tstr = ptinfo->get_exe(); RETURN_EXTRACT_STRING(m_tstr); + } else { + return NULL; } - case TYPE_PEXE: - { - sinsp_threadinfo* ptinfo = - m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); + } + case TYPE_AEXE: { + sinsp_threadinfo* mt = NULL; - if(ptinfo != NULL) - { - m_tstr = ptinfo->get_exe(); - RETURN_EXTRACT_STRING(m_tstr); - } - else - { + if(tinfo->is_main_thread()) { + mt = tinfo; + } else { + mt = tinfo->get_main_thread(); + + if(mt == NULL) { return NULL; } } - case TYPE_AEXE: - { - sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { - mt = tinfo; - } - else - { - mt = tinfo->get_main_thread(); + for(int32_t j = 0; j < m_argid; j++) { + mt = mt->get_parent_thread(); - if(mt == NULL) - { - return NULL; - } + if(mt == NULL) { + return NULL; } + } - for(int32_t j = 0; j < m_argid; j++) - { - mt = mt->get_parent_thread(); - - if(mt == NULL) - { - return NULL; - } - } + m_tstr = mt->get_exe(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_PEXEPATH: { + sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); - m_tstr = mt->get_exe(); + if(ptinfo != NULL) { + m_tstr = ptinfo->get_exepath(); RETURN_EXTRACT_STRING(m_tstr); + } else { + return NULL; } - case TYPE_PEXEPATH: - { - sinsp_threadinfo* ptinfo = - m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); + } + case TYPE_AEXEPATH: { + sinsp_threadinfo* mt = NULL; - if(ptinfo != NULL) - { - m_tstr = ptinfo->get_exepath(); - RETURN_EXTRACT_STRING(m_tstr); - } - else - { + if(tinfo->is_main_thread()) { + mt = tinfo; + } else { + mt = tinfo->get_main_thread(); + + if(mt == NULL) { return NULL; } } - case TYPE_AEXEPATH: - { - sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { - mt = tinfo; - } - else - { - mt = tinfo->get_main_thread(); + for(int32_t j = 0; j < m_argid; j++) { + mt = mt->get_parent_thread(); - if(mt == NULL) - { - return NULL; - } + if(mt == NULL) { + return NULL; } + } - for(int32_t j = 0; j < m_argid; j++) - { - mt = mt->get_parent_thread(); + m_tstr = mt->get_exepath(); + RETURN_EXTRACT_STRING(m_tstr); + } + case TYPE_LOGINSHELLID: { + sinsp_threadinfo* mt = NULL; + int64_t* res = NULL; - if(mt == NULL) - { - return NULL; - } - } + if(tinfo->is_main_thread()) { + mt = tinfo; + } else { + mt = tinfo->get_main_thread(); - m_tstr = mt->get_exepath(); - RETURN_EXTRACT_STRING(m_tstr); + if(mt == NULL) { + return NULL; + } } - case TYPE_LOGINSHELLID: - { - sinsp_threadinfo* mt = NULL; - int64_t* res = NULL; - if(tinfo->is_main_thread()) - { - mt = tinfo; - } - else - { - mt = tinfo->get_main_thread(); + sinsp_threadinfo::visitor_func_t check_thread_for_shell = [&res](sinsp_threadinfo* pt) { + size_t len = pt->m_comm.size(); - if(mt == NULL) - { - return NULL; - } + if(len >= 2 && pt->m_comm[len - 2] == 's' && pt->m_comm[len - 1] == 'h') { + res = &pt->m_pid; } - sinsp_threadinfo::visitor_func_t check_thread_for_shell = [&res] (sinsp_threadinfo *pt) - { - size_t len = pt->m_comm.size(); - - if(len >= 2 && pt->m_comm[len - 2] == 's' && pt->m_comm[len - 1] == 'h') - { - res = &pt->m_pid; - } - - return true; - }; + return true; + }; - // First call the visitor on the main thread. - check_thread_for_shell(mt); + // First call the visitor on the main thread. + check_thread_for_shell(mt); - // Then check all its parents to see if they are shells - mt->traverse_parent_state(check_thread_for_shell); + // Then check all its parents to see if they are shells + mt->traverse_parent_state(check_thread_for_shell); - RETURN_EXTRACT_PTR(res); - } + RETURN_EXTRACT_PTR(res); + } case TYPE_DURATION: - if(tinfo->m_clone_ts != 0) - { + if(tinfo->m_clone_ts != 0) { m_val.s64 = evt->get_ts() - tinfo->m_clone_ts; ASSERT(m_val.s64 > 0); RETURN_EXTRACT_VAR(m_val.s64); - } - else - { + } else { return NULL; } - case TYPE_PPID_DURATION: - { - sinsp_threadinfo* ptinfo = - m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); + case TYPE_PPID_DURATION: { + sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); - if(ptinfo != NULL) - { - if(ptinfo->m_clone_ts != 0) - { - m_val.s64 = evt->get_ts() - ptinfo->m_clone_ts; - ASSERT(m_val.s64 > 0); - RETURN_EXTRACT_VAR(m_val.s64); - } - } - else - { - return NULL; + if(ptinfo != NULL) { + if(ptinfo->m_clone_ts != 0) { + m_val.s64 = evt->get_ts() - ptinfo->m_clone_ts; + ASSERT(m_val.s64 > 0); + RETURN_EXTRACT_VAR(m_val.s64); } + } else { + return NULL; } + } case TYPE_FDOPENCOUNT: m_val.u64 = tinfo->get_fd_opencount(); RETURN_EXTRACT_VAR(m_val.u64); @@ -1335,45 +1658,33 @@ uint8_t* sinsp_filter_check_thread::extract_single(sinsp_evt *evt, uint32_t* len m_val.u64 = tinfo->m_vmswap_kb; RETURN_EXTRACT_VAR(m_val.u64); case TYPE_THREAD_VMSIZE: - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { m_val.u64 = tinfo->m_vmsize_kb; - } - else - { + } else { m_val.u64 = 0; } RETURN_EXTRACT_VAR(m_val.u64); case TYPE_THREAD_VMRSS: - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { m_val.u64 = tinfo->m_vmrss_kb; - } - else - { + } else { m_val.u64 = 0; } RETURN_EXTRACT_VAR(m_val.u64); case TYPE_THREAD_VMSIZE_B: - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { m_val.u64 = tinfo->m_vmsize_kb * 1024; - } - else - { + } else { m_val.u64 = 0; } RETURN_EXTRACT_VAR(m_val.u64); case TYPE_THREAD_VMRSS_B: - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { m_val.u64 = tinfo->m_vmrss_kb * 1024; - } - else - { + } else { m_val.u64 = 0; } @@ -1384,116 +1695,106 @@ uint8_t* sinsp_filter_check_thread::extract_single(sinsp_evt *evt, uint32_t* len case TYPE_PFMINOR: m_val.u64 = tinfo->m_pfminor; RETURN_EXTRACT_VAR(m_val.u64); - case TYPE_CGROUPS: - { - m_tstr.clear(); - auto cgroups = tinfo->cgroups(); + case TYPE_CGROUPS: { + m_tstr.clear(); + auto cgroups = tinfo->cgroups(); - uint32_t j; - uint32_t nargs = (uint32_t)cgroups.size(); + uint32_t j; + uint32_t nargs = (uint32_t)cgroups.size(); - if(nargs == 0) - { - return NULL; - } + if(nargs == 0) { + return NULL; + } - for(j = 0; j < nargs; j++) - { - m_tstr += cgroups[j].first; - m_tstr += "="; - m_tstr += cgroups[j].second; - if(j < nargs - 1) - { - m_tstr += ' '; - } + for(j = 0; j < nargs; j++) { + m_tstr += cgroups[j].first; + m_tstr += "="; + m_tstr += cgroups[j].second; + if(j < nargs - 1) { + m_tstr += ' '; } - - RETURN_EXTRACT_STRING(m_tstr); } + + RETURN_EXTRACT_STRING(m_tstr); + } case TYPE_CGROUP: - if(tinfo->get_cgroup(m_argname, m_tstr)) - { + if(tinfo->get_cgroup(m_argname, m_tstr)) { RETURN_EXTRACT_STRING(m_tstr); } return NULL; case TYPE_VTID: - if(tinfo->m_vtid == -1) - { + if(tinfo->m_vtid == -1) { return NULL; } m_val.u64 = tinfo->m_vtid; RETURN_EXTRACT_VAR(m_val.u64); case TYPE_VPID: - if(tinfo->m_vpid == -1) - { + if(tinfo->m_vpid == -1) { return NULL; } m_val.u64 = tinfo->m_vpid; RETURN_EXTRACT_VAR(m_val.u64); -/* - case TYPE_PROC_CPU: - { - uint16_t etype = evt->get_type(); - - if(etype == PPME_PROCINFO_E) - { - double thval; - uint64_t tcpu; - - sinsp_evt_param* parinfo = evt->get_param(0); - tcpu = *(uint64_t*)parinfo->m_val; - - parinfo = evt->get_param(1); - tcpu += *(uint64_t*)parinfo->m_val; - - if(tinfo->m_last_t_tot_cpu != 0) - { - uint64_t deltaval = tcpu - tinfo->m_last_t_tot_cpu; - thval = (double)deltaval;// / (ONE_SECOND_IN_NS / 100); - if(thval > 100) - { - thval = 100; - } - } - else - { - thval = 0; - } - - tinfo->m_last_t_tot_cpu = tcpu; - - uint64_t ets = evt->get_ts(); - sinsp_threadinfo* mt = tinfo->get_main_thread(); - - if(ets != mt->m_last_mt_cpu_ts) - { - mt->m_last_mt_tot_cpu = 0; - mt->m_last_mt_cpu_ts = ets; - } - - mt->m_last_mt_tot_cpu += thval; - m_val.d = mt->m_last_mt_tot_cpu; - - RETURN_EXTRACT_VAR(m_val.d); - } - - return NULL; - } -*/ - case TYPE_THREAD_CPU: - { - return extract_thread_cpu(evt, len, tinfo, true, true); - } - case TYPE_THREAD_CPU_USER: - { - return extract_thread_cpu(evt, len, tinfo, true, false); - } - case TYPE_THREAD_CPU_SYSTEM: - { - return extract_thread_cpu(evt, len, tinfo, false, true); - } + /* + case TYPE_PROC_CPU: + { + uint16_t etype = evt->get_type(); + + if(etype == PPME_PROCINFO_E) + { + double thval; + uint64_t tcpu; + + sinsp_evt_param* parinfo = evt->get_param(0); + tcpu = *(uint64_t*)parinfo->m_val; + + parinfo = evt->get_param(1); + tcpu += *(uint64_t*)parinfo->m_val; + + if(tinfo->m_last_t_tot_cpu != 0) + { + uint64_t deltaval = tcpu - tinfo->m_last_t_tot_cpu; + thval = (double)deltaval;// / (ONE_SECOND_IN_NS / 100); + if(thval > 100) + { + thval = 100; + } + } + else + { + thval = 0; + } + + tinfo->m_last_t_tot_cpu = tcpu; + + uint64_t ets = evt->get_ts(); + sinsp_threadinfo* mt = tinfo->get_main_thread(); + + if(ets != mt->m_last_mt_cpu_ts) + { + mt->m_last_mt_tot_cpu = 0; + mt->m_last_mt_cpu_ts = ets; + } + + mt->m_last_mt_tot_cpu += thval; + m_val.d = mt->m_last_mt_tot_cpu; + + RETURN_EXTRACT_VAR(m_val.d); + } + + return NULL; + } + */ + case TYPE_THREAD_CPU: { + return extract_thread_cpu(evt, len, tinfo, true, true); + } + case TYPE_THREAD_CPU_USER: { + return extract_thread_cpu(evt, len, tinfo, true, false); + } + case TYPE_THREAD_CPU_SYSTEM: { + return extract_thread_cpu(evt, len, tinfo, false, true); + } case TYPE_NAMETID: m_tstr = tinfo->get_comm() + to_string(evt->get_tid()); RETURN_EXTRACT_STRING(m_tstr); @@ -1533,182 +1834,139 @@ uint8_t* sinsp_filter_check_thread::extract_single(sinsp_evt *evt, uint32_t* len case TYPE_CAP_EFFECTIVE: m_tstr = sinsp_utils::caps_to_string(tinfo->m_cap_effective); RETURN_EXTRACT_STRING(m_tstr); - case TYPE_CMDNARGS: - { - m_val.u64 = (uint32_t)tinfo->m_args.size(); - RETURN_EXTRACT_VAR(m_val.u64); - } - case TYPE_CMDLENARGS: - { - m_val.u64 = 0; - uint32_t j; - uint32_t nargs = (uint32_t)tinfo->m_args.size(); - - for(j = 0; j < nargs; j++) - { - m_val.u64 += tinfo->m_args[j].length(); + case TYPE_CMDNARGS: { + m_val.u64 = (uint32_t)tinfo->m_args.size(); + RETURN_EXTRACT_VAR(m_val.u64); + } + case TYPE_CMDLENARGS: { + m_val.u64 = 0; + uint32_t j; + uint32_t nargs = (uint32_t)tinfo->m_args.size(); - } - RETURN_EXTRACT_VAR(m_val.u64); + for(j = 0; j < nargs; j++) { + m_val.u64 += tinfo->m_args[j].length(); } - case TYPE_PVPID: - { - sinsp_threadinfo* ptinfo = - m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); + RETURN_EXTRACT_VAR(m_val.u64); + } + case TYPE_PVPID: { + sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); - if(ptinfo != NULL) - { - RETURN_EXTRACT_VAR(ptinfo->m_vpid); - } - else - { - return NULL; - } + if(ptinfo != NULL) { + RETURN_EXTRACT_VAR(ptinfo->m_vpid); + } else { + return NULL; } + } case TYPE_EXE_INO: // Inode 0 is used as a NULL value to indicate that there is no inode. - if(tinfo->m_exe_ino == 0) - { + if(tinfo->m_exe_ino == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_exe_ino); case TYPE_EXE_INO_CTIME: - if(tinfo->m_exe_ino_ctime == 0) - { + if(tinfo->m_exe_ino_ctime == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_exe_ino_ctime); case TYPE_EXE_INO_MTIME: - if(tinfo->m_exe_ino_mtime == 0) - { + if(tinfo->m_exe_ino_mtime == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_exe_ino_mtime); case TYPE_EXE_INO_CTIME_DURATION_CLONE_TS: - if(tinfo->m_exe_ino_ctime_duration_clone_ts == 0) - { + if(tinfo->m_exe_ino_ctime_duration_clone_ts == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_exe_ino_ctime_duration_clone_ts); case TYPE_EXE_INO_CTIME_DURATION_PIDNS_START: - if(tinfo->m_exe_ino_ctime_duration_pidns_start == 0) - { + if(tinfo->m_exe_ino_ctime_duration_pidns_start == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_exe_ino_ctime_duration_pidns_start); case TYPE_PIDNS_INIT_START_TS: - if(tinfo->m_pidns_init_start_ts == 0) - { + if(tinfo->m_pidns_init_start_ts == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_pidns_init_start_ts); case TYPE_PID_CLONE_TS: - if(tinfo->m_clone_ts == 0) - { + if(tinfo->m_clone_ts == 0) { return NULL; } RETURN_EXTRACT_VAR(tinfo->m_clone_ts); - case TYPE_PPID_CLONE_TS: - { - sinsp_threadinfo* ptinfo = - m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); + case TYPE_PPID_CLONE_TS: { + sinsp_threadinfo* ptinfo = m_inspector->get_thread_ref(tinfo->m_ptid, false, true).get(); - if(ptinfo != NULL) - { - RETURN_EXTRACT_VAR(ptinfo->m_clone_ts); - } - else - { - return NULL; - } + if(ptinfo != NULL) { + RETURN_EXTRACT_VAR(ptinfo->m_clone_ts); + } else { + return NULL; } + } case TYPE_FD_STDIN_TYPE: case TYPE_FD_STDOUT_TYPE: - case TYPE_FD_STDERR_TYPE: - { - int64_t fd = -1; - if (m_field_id == TYPE_FD_STDIN_TYPE) - { - fd = 0; - } - else if (m_field_id == TYPE_FD_STDOUT_TYPE) - { - fd = 1; - } - else if (m_field_id == TYPE_FD_STDERR_TYPE) - { - fd = 2; - } - auto fdtable_ptr = tinfo->get_fd_table(); - if (fdtable_ptr == nullptr) - { - return NULL; - } - auto fdinfo = fdtable_ptr->find(fd); - if (fdinfo == nullptr) - { - return NULL; - } - m_tstr = fdinfo->get_typestring(); - RETURN_EXTRACT_STRING(m_tstr); + case TYPE_FD_STDERR_TYPE: { + int64_t fd = -1; + if(m_field_id == TYPE_FD_STDIN_TYPE) { + fd = 0; + } else if(m_field_id == TYPE_FD_STDOUT_TYPE) { + fd = 1; + } else if(m_field_id == TYPE_FD_STDERR_TYPE) { + fd = 2; + } + auto fdtable_ptr = tinfo->get_fd_table(); + if(fdtable_ptr == nullptr) { + return NULL; + } + auto fdinfo = fdtable_ptr->find(fd); + if(fdinfo == nullptr) { + return NULL; } + m_tstr = fdinfo->get_typestring(); + RETURN_EXTRACT_STRING(m_tstr); + } case TYPE_FD_STDIN_NAME: case TYPE_FD_STDOUT_NAME: - case TYPE_FD_STDERR_NAME: - { - int64_t fd = -1; - if (m_field_id == TYPE_FD_STDIN_NAME) - { - fd = 0; - } - else if (m_field_id == TYPE_FD_STDOUT_NAME) - { - fd = 1; - } - else if (m_field_id == TYPE_FD_STDERR_NAME) - { - fd = 2; - } - auto fdtable_ptr = tinfo->get_fd_table(); - if (fdtable_ptr == nullptr) - { - return NULL; - } - auto fdinfo = fdtable_ptr->find(fd); - if (fdinfo == nullptr) - { - return NULL; - } - m_tstr = fdinfo->m_name.c_str(); - RETURN_EXTRACT_STRING(m_tstr); - } + case TYPE_FD_STDERR_NAME: { + int64_t fd = -1; + if(m_field_id == TYPE_FD_STDIN_NAME) { + fd = 0; + } else if(m_field_id == TYPE_FD_STDOUT_NAME) { + fd = 1; + } else if(m_field_id == TYPE_FD_STDERR_NAME) { + fd = 2; + } + auto fdtable_ptr = tinfo->get_fd_table(); + if(fdtable_ptr == nullptr) { + return NULL; + } + auto fdinfo = fdtable_ptr->find(fd); + if(fdinfo == nullptr) { + return NULL; + } + m_tstr = fdinfo->m_name.c_str(); + RETURN_EXTRACT_STRING(m_tstr); + } default: ASSERT(false); return NULL; } } -bool sinsp_filter_check_thread::compare_full_apid(sinsp_evt *evt) -{ +bool sinsp_filter_check_thread::compare_full_apid(sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return false; } sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { mt = tinfo; - } - else - { + } else { mt = tinfo->get_main_thread(); - if(mt == NULL) - { + if(mt == NULL) { return false; } } @@ -1717,16 +1975,12 @@ bool sinsp_filter_check_thread::compare_full_apid(sinsp_evt *evt) // No id specified, search in all of the ancestors // bool found = false; - sinsp_threadinfo::visitor_func_t visitor = [this, &found] (sinsp_threadinfo *pt) - { + sinsp_threadinfo::visitor_func_t visitor = [this, &found](sinsp_threadinfo* pt) { bool res; - res = compare_rhs(m_cmpop, - PT_PID, - &pt->m_pid); + res = compare_rhs(m_cmpop, PT_PID, &pt->m_pid); - if(res == true) - { + if(res == true) { found = true; // Can stop traversing parent state @@ -1741,27 +1995,21 @@ bool sinsp_filter_check_thread::compare_full_apid(sinsp_evt *evt) return found; } -bool sinsp_filter_check_thread::compare_full_aname(sinsp_evt *evt) -{ +bool sinsp_filter_check_thread::compare_full_aname(sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return false; } sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { mt = tinfo; - } - else - { + } else { mt = tinfo->get_main_thread(); - if(mt == NULL) - { + if(mt == NULL) { return false; } } @@ -1770,16 +2018,12 @@ bool sinsp_filter_check_thread::compare_full_aname(sinsp_evt *evt) // No id specified, search in all of the ancestors // bool found = false; - sinsp_threadinfo::visitor_func_t visitor = [this, &found] (sinsp_threadinfo *pt) - { + sinsp_threadinfo::visitor_func_t visitor = [this, &found](sinsp_threadinfo* pt) { bool res; - res = compare_rhs(m_cmpop, - PT_CHARBUF, - (void*)pt->m_comm.c_str()); + res = compare_rhs(m_cmpop, PT_CHARBUF, (void*)pt->m_comm.c_str()); - if(res == true) - { + if(res == true) { found = true; // Can stop traversing parent state @@ -1794,27 +2038,21 @@ bool sinsp_filter_check_thread::compare_full_aname(sinsp_evt *evt) return found; } -bool sinsp_filter_check_thread::compare_full_aexe(sinsp_evt *evt) -{ +bool sinsp_filter_check_thread::compare_full_aexe(sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return false; } sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { mt = tinfo; - } - else - { + } else { mt = tinfo->get_main_thread(); - if(mt == NULL) - { + if(mt == NULL) { return false; } } @@ -1823,16 +2061,12 @@ bool sinsp_filter_check_thread::compare_full_aexe(sinsp_evt *evt) // No id specified, search in all of the ancestors // bool found = false; - sinsp_threadinfo::visitor_func_t visitor = [this, &found] (sinsp_threadinfo *pt) - { + sinsp_threadinfo::visitor_func_t visitor = [this, &found](sinsp_threadinfo* pt) { bool res; - res = compare_rhs(m_cmpop, - PT_CHARBUF, - (void*)pt->m_exe.c_str()); + res = compare_rhs(m_cmpop, PT_CHARBUF, (void*)pt->m_exe.c_str()); - if(res == true) - { + if(res == true) { found = true; // Can stop traversing parent state @@ -1847,27 +2081,21 @@ bool sinsp_filter_check_thread::compare_full_aexe(sinsp_evt *evt) return found; } -bool sinsp_filter_check_thread::compare_full_aexepath(sinsp_evt *evt) -{ +bool sinsp_filter_check_thread::compare_full_aexepath(sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return false; } sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { mt = tinfo; - } - else - { + } else { mt = tinfo->get_main_thread(); - if(mt == NULL) - { + if(mt == NULL) { return false; } } @@ -1876,16 +2104,12 @@ bool sinsp_filter_check_thread::compare_full_aexepath(sinsp_evt *evt) // No id specified, search in all of the ancestors // bool found = false; - sinsp_threadinfo::visitor_func_t visitor = [this, &found] (sinsp_threadinfo *pt) - { + sinsp_threadinfo::visitor_func_t visitor = [this, &found](sinsp_threadinfo* pt) { bool res; - res = compare_rhs(m_cmpop, - PT_CHARBUF, - (void*)pt->m_exepath.c_str()); + res = compare_rhs(m_cmpop, PT_CHARBUF, (void*)pt->m_exepath.c_str()); - if(res == true) - { + if(res == true) { found = true; // Can stop traversing parent state @@ -1900,27 +2124,21 @@ bool sinsp_filter_check_thread::compare_full_aexepath(sinsp_evt *evt) return found; } -bool sinsp_filter_check_thread::compare_full_acmdline(sinsp_evt *evt) -{ +bool sinsp_filter_check_thread::compare_full_acmdline(sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return false; } sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { mt = tinfo; - } - else - { + } else { mt = tinfo->get_main_thread(); - if(mt == NULL) - { + if(mt == NULL) { return false; } } @@ -1929,18 +2147,14 @@ bool sinsp_filter_check_thread::compare_full_acmdline(sinsp_evt *evt) // No id specified, search in all of the ancestors // bool found = false; - sinsp_threadinfo::visitor_func_t visitor = [this, &found] (sinsp_threadinfo *pt) - { + sinsp_threadinfo::visitor_func_t visitor = [this, &found](sinsp_threadinfo* pt) { bool res; std::string cmdline; sinsp_threadinfo::populate_cmdline(cmdline, pt); - res = compare_rhs(m_cmpop, - PT_CHARBUF, - (void*)cmdline.c_str()); + res = compare_rhs(m_cmpop, PT_CHARBUF, (void*)cmdline.c_str()); - if(res == true) - { + if(res == true) { found = true; // Can stop traversing parent state @@ -1955,27 +2169,21 @@ bool sinsp_filter_check_thread::compare_full_acmdline(sinsp_evt *evt) return found; } -bool sinsp_filter_check_thread::compare_full_aenv(sinsp_evt *evt) -{ +bool sinsp_filter_check_thread::compare_full_aenv(sinsp_evt* evt) { sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return false; } sinsp_threadinfo* mt = NULL; - if(tinfo->is_main_thread()) - { + if(tinfo->is_main_thread()) { mt = tinfo; - } - else - { + } else { mt = tinfo->get_main_thread(); - if(mt == NULL) - { + if(mt == NULL) { return false; } } @@ -1984,15 +2192,11 @@ bool sinsp_filter_check_thread::compare_full_aenv(sinsp_evt *evt) // No id specified, search in all of the ancestors // bool found = false; - sinsp_threadinfo::visitor_func_t visitor = [this, &found] (sinsp_threadinfo *pt) - { + sinsp_threadinfo::visitor_func_t visitor = [this, &found](sinsp_threadinfo* pt) { std::string full_env = pt->concatenate_all_env(); - bool res = compare_rhs(m_cmpop, - PT_CHARBUF, - (void*)full_env.c_str()); + bool res = compare_rhs(m_cmpop, PT_CHARBUF, (void*)full_env.c_str()); - if(res == true) - { + if(res == true) { found = true; // Can stop traversing parent state @@ -2007,47 +2211,29 @@ bool sinsp_filter_check_thread::compare_full_aenv(sinsp_evt *evt) return found; } -bool sinsp_filter_check_thread::compare_nocache(sinsp_evt *evt) -{ - if(m_field_id == TYPE_APID) - { - if(m_argid == -1) - { +bool sinsp_filter_check_thread::compare_nocache(sinsp_evt* evt) { + if(m_field_id == TYPE_APID) { + if(m_argid == -1) { return compare_full_apid(evt); } - } - else if(m_field_id == TYPE_ANAME) - { - if(m_argid == -1) - { + } else if(m_field_id == TYPE_ANAME) { + if(m_argid == -1) { return compare_full_aname(evt); } - } - else if(m_field_id == TYPE_AEXE) - { - if(m_argid == -1) - { + } else if(m_field_id == TYPE_AEXE) { + if(m_argid == -1) { return compare_full_aexe(evt); } - } - else if(m_field_id == TYPE_AEXEPATH) - { - if(m_argid == -1) - { + } else if(m_field_id == TYPE_AEXEPATH) { + if(m_argid == -1) { return compare_full_aexepath(evt); } - } - else if(m_field_id == TYPE_ACMDLINE) - { - if(m_argid == -1) - { + } else if(m_field_id == TYPE_ACMDLINE) { + if(m_argid == -1) { return compare_full_acmdline(evt); } - } - else if(m_field_id == TYPE_AENV) - { - if(m_argname.empty()) - { + } else if(m_field_id == TYPE_AENV) { + if(m_argname.empty()) { return compare_full_aenv(evt); } } @@ -2055,7 +2241,6 @@ bool sinsp_filter_check_thread::compare_nocache(sinsp_evt *evt) return sinsp_filter_check::compare_nocache(evt); } -int32_t sinsp_filter_check_thread::get_argid() const -{ +int32_t sinsp_filter_check_thread::get_argid() const { return m_argid; } diff --git a/userspace/libsinsp/sinsp_filtercheck_thread.h b/userspace/libsinsp/sinsp_filtercheck_thread.h index 5822bd2c41..871b6d780c 100644 --- a/userspace/libsinsp/sinsp_filtercheck_thread.h +++ b/userspace/libsinsp/sinsp_filtercheck_thread.h @@ -21,11 +21,9 @@ limitations under the License. #include #include -class sinsp_filter_check_thread : public sinsp_filter_check -{ +class sinsp_filter_check_thread : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_EXE = 0, TYPE_PEXE, TYPE_AEXE, @@ -119,18 +117,24 @@ class sinsp_filter_check_thread : public sinsp_filter_check virtual ~sinsp_filter_check_thread() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; int32_t get_argid() const; protected: - uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; - bool compare_nocache(sinsp_evt*) override; + uint8_t *extract_single(sinsp_evt *, uint32_t *len, bool sanitize_strings = true) override; + bool compare_nocache(sinsp_evt *) override; private: uint64_t extract_exectime(sinsp_evt *evt); - int32_t extract_arg(std::string_view fldname, std::string_view val, const ppm_param_info**); - uint8_t* extract_thread_cpu(sinsp_evt *evt, uint32_t* len, sinsp_threadinfo* tinfo, bool extract_user, bool extract_system); + int32_t extract_arg(std::string_view fldname, std::string_view val, const ppm_param_info **); + uint8_t *extract_thread_cpu(sinsp_evt *evt, + uint32_t *len, + sinsp_threadinfo *tinfo, + bool extract_user, + bool extract_system); inline bool compare_full_apid(sinsp_evt *evt); bool compare_full_aname(sinsp_evt *evt); bool compare_full_aexe(sinsp_evt *evt); @@ -148,5 +152,6 @@ class sinsp_filter_check_thread : public sinsp_filter_check double d; } m_val; std::vector m_last_proc_switch_times; - std::unique_ptr> m_thread_dyn_field_accessor; + std::unique_ptr> + m_thread_dyn_field_accessor; }; diff --git a/userspace/libsinsp/sinsp_filtercheck_tracer.cpp b/userspace/libsinsp/sinsp_filtercheck_tracer.cpp index 336c8946a2..6399b82544 100644 --- a/userspace/libsinsp/sinsp_filtercheck_tracer.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_tracer.cpp @@ -27,66 +27,178 @@ using namespace std; #define TEXT_ARG_ID -1000000 -static inline bool str_match_start(std::string_view val, size_t len, const char* m) -{ +static inline bool str_match_start(std::string_view val, size_t len, const char* m) { return val.compare(0, len, m) == 0; } -#define STR_MATCH(s) str_match_start(val, sizeof (s) -1, s) - -static const filtercheck_field_info sinsp_filter_check_tracer_fields[] = -{ - {PT_INT64, EPF_NONE|EPF_DEPRECATED, PF_ID, "span.id", "Span ID", "ID of the span. This is a unique identifier that is used to match the enter and exit tracer events for this span. It can also be used to match different spans belonging to a trace."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "span.time", "Time", "time of the span's enter tracer as a human readable string that includes the nanosecond part."}, - {PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "span.ntags", "Tag Count", "number of tags that this span has."}, - {PT_UINT32, EPF_NONE|EPF_DEPRECATED, PF_DEC, "span.nargs", "Argument Count", "number of arguments that this span has."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "span.tags", "Tags", "dot-separated list of all of the span's tags."}, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "span.tag", "Tag", "one of the span's tags, specified by 0-based offset, e.g. 'span.tag[1]'. You can use a negative offset to pick elements from the end of the tag list. For example, 'span.tag[-1]' returns the last tag."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "span.args", "Arguments", "comma-separated list of the span's arguments." }, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "span.arg", "Argument", "one of the span arguments, specified by name or by 0-based offset. E.g. 'span.arg.xxx' or 'span.arg[1]'. You can use a negative offset to pick elements from the end of the tag list. For example, 'span.arg[-1]' returns the last argument." }, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "span.enterargs", "Enter Arguments", "comma-separated list of the span's enter tracer event arguments. For enter tracers, this is the same as evt.args. For exit tracers, this is the evt.args of the corresponding enter tracer." }, - {PT_CHARBUF, EPF_ARG_REQUIRED|EPF_DEPRECATED, PF_NA, "span.enterarg", "Enter Argument", "one of the span's enter arguments, specified by name or by 0-based offset. For enter tracer events, this is the same as evt.arg. For exit tracer events, this is the evt.arg of the corresponding enter event." }, - {PT_RELTIME, EPF_NONE|EPF_DEPRECATED, PF_DEC, "span.duration", "Duration", "delta between this span's exit tracer event and the enter tracer event."}, - {PT_UINT64, EPF_TABLE_ONLY|EPF_DEPRECATED, PF_DEC, "span.duration.quantized", "Quantized Duration", "10-base log of the delta between an exit tracer event and the correspondent enter event."}, - {PT_CHARBUF, EPF_NONE|EPF_DEPRECATED, PF_NA, "span.duration.human", "Human-Readable Duration", "delta between this span's exit tracer event and the enter event, as a human readable string (e.g. 10.3ms)."}, - {PT_RELTIME, (filtercheck_field_flags) (EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), PF_DEC, "span.duration.fortag", "Duration For Tag", "duration of the span if the number of tags matches the field argument, otherwise 0. For example, span.duration.fortag[1] returns the duration of all the spans with 1 tag, and zero for all the other ones."}, - {PT_UINT64, EPF_TABLE_ONLY|EPF_DEPRECATED, PF_DEC, "span.count", "Span Count", "1 for span exit events."}, - {PT_UINT64, (filtercheck_field_flags) (EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), PF_DEC, "span.count.fortag", "Count For Tag", "1 if the span's number of tags matches the field argument, and zero for all the other ones."}, - {PT_UINT64, (filtercheck_field_flags) (EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), PF_DEC, "span.childcount.fortag", "Child Count For Tag", "1 if the span's number of tags is greater than the field argument, and zero for all the other ones."}, - {PT_CHARBUF, (filtercheck_field_flags) (EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), PF_NA, "span.idtag", "List View ID", "id used by the span list view."}, - {PT_CHARBUF, EPF_TABLE_ONLY|EPF_DEPRECATED, PF_NA, "span.rawtime", "List View Time", "id used by the span list view."}, - {PT_CHARBUF, EPF_TABLE_ONLY|EPF_DEPRECATED, PF_NA, "span.rawparenttime", "List View Parent Time", "id used by the span list view."}, +#define STR_MATCH(s) str_match_start(val, sizeof(s) - 1, s) + +static const filtercheck_field_info sinsp_filter_check_tracer_fields[] = { + {PT_INT64, + EPF_NONE | EPF_DEPRECATED, + PF_ID, + "span.id", + "Span ID", + "ID of the span. This is a unique identifier that is used to match the enter and exit " + "tracer events for this span. It can also be used to match different spans belonging to a " + "trace."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "span.time", + "Time", + "time of the span's enter tracer as a human readable string that includes the nanosecond " + "part."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "span.ntags", + "Tag Count", + "number of tags that this span has."}, + {PT_UINT32, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "span.nargs", + "Argument Count", + "number of arguments that this span has."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "span.tags", + "Tags", + "dot-separated list of all of the span's tags."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "span.tag", + "Tag", + "one of the span's tags, specified by 0-based offset, e.g. 'span.tag[1]'. You can use a " + "negative offset to pick elements from the end of the tag list. For example, " + "'span.tag[-1]' returns the last tag."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "span.args", + "Arguments", + "comma-separated list of the span's arguments."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "span.arg", + "Argument", + "one of the span arguments, specified by name or by 0-based offset. E.g. 'span.arg.xxx' " + "or 'span.arg[1]'. You can use a negative offset to pick elements from the end of the tag " + "list. For example, 'span.arg[-1]' returns the last argument."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "span.enterargs", + "Enter Arguments", + "comma-separated list of the span's enter tracer event arguments. For enter tracers, this " + "is the same as evt.args. For exit tracers, this is the evt.args of the corresponding " + "enter tracer."}, + {PT_CHARBUF, + EPF_ARG_REQUIRED | EPF_DEPRECATED, + PF_NA, + "span.enterarg", + "Enter Argument", + "one of the span's enter arguments, specified by name or by 0-based offset. For enter " + "tracer events, this is the same as evt.arg. For exit tracer events, this is the evt.arg " + "of the corresponding enter event."}, + {PT_RELTIME, + EPF_NONE | EPF_DEPRECATED, + PF_DEC, + "span.duration", + "Duration", + "delta between this span's exit tracer event and the enter tracer event."}, + {PT_UINT64, + EPF_TABLE_ONLY | EPF_DEPRECATED, + PF_DEC, + "span.duration.quantized", + "Quantized Duration", + "10-base log of the delta between an exit tracer event and the correspondent enter " + "event."}, + {PT_CHARBUF, + EPF_NONE | EPF_DEPRECATED, + PF_NA, + "span.duration.human", + "Human-Readable Duration", + "delta between this span's exit tracer event and the enter event, as a human readable " + "string (e.g. 10.3ms)."}, + {PT_RELTIME, + (filtercheck_field_flags)(EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), + PF_DEC, + "span.duration.fortag", + "Duration For Tag", + "duration of the span if the number of tags matches the field argument, otherwise 0. For " + "example, span.duration.fortag[1] returns the duration of all the spans with 1 tag, and " + "zero for all the other ones."}, + {PT_UINT64, + EPF_TABLE_ONLY | EPF_DEPRECATED, + PF_DEC, + "span.count", + "Span Count", + "1 for span exit events."}, + {PT_UINT64, + (filtercheck_field_flags)(EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), + PF_DEC, + "span.count.fortag", + "Count For Tag", + "1 if the span's number of tags matches the field argument, and zero for all the other " + "ones."}, + {PT_UINT64, + (filtercheck_field_flags)(EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), + PF_DEC, + "span.childcount.fortag", + "Child Count For Tag", + "1 if the span's number of tags is greater than the field argument, and zero for all the " + "other ones."}, + {PT_CHARBUF, + (filtercheck_field_flags)(EPF_TABLE_ONLY | EPF_ARG_REQUIRED | EPF_DEPRECATED), + PF_NA, + "span.idtag", + "List View ID", + "id used by the span list view."}, + {PT_CHARBUF, + EPF_TABLE_ONLY | EPF_DEPRECATED, + PF_NA, + "span.rawtime", + "List View Time", + "id used by the span list view."}, + {PT_CHARBUF, + EPF_TABLE_ONLY | EPF_DEPRECATED, + PF_NA, + "span.rawparenttime", + "List View Parent Time", + "id used by the span list view."}, }; -sinsp_filter_check_tracer::sinsp_filter_check_tracer() -{ +sinsp_filter_check_tracer::sinsp_filter_check_tracer() { static const filter_check_info s_field_infos = { - "span", - "", - "Fields used if information about distributed tracing is available.", - sizeof(sinsp_filter_check_tracer_fields) / sizeof(sinsp_filter_check_tracer_fields[0]), - sinsp_filter_check_tracer_fields, - filter_check_info::FL_HIDDEN, + "span", + "", + "Fields used if information about distributed tracing is available.", + sizeof(sinsp_filter_check_tracer_fields) / sizeof(sinsp_filter_check_tracer_fields[0]), + sinsp_filter_check_tracer_fields, + filter_check_info::FL_HIDDEN, }; m_info = &s_field_infos; } -std::unique_ptr sinsp_filter_check_tracer::allocate_new() -{ +std::unique_ptr sinsp_filter_check_tracer::allocate_new() { return std::make_unique(); } -int32_t sinsp_filter_check_tracer::extract_arg(string_view fldname, string_view val, const ppm_param_info** parinfo) -{ +int32_t sinsp_filter_check_tracer::extract_arg(string_view fldname, + string_view val, + const ppm_param_info** parinfo) { uint32_t parsed_len = 0; // // 'arg' and 'resarg' are handled in a custom way // - if(val.size() > fldname.size() && val.at(fldname.size()) == '[') - { - if(parinfo != NULL) - { + if(val.size() > fldname.size() && val.at(fldname.size()) == '[') { + if(parinfo != NULL) { throw sinsp_exception("tracer field must be expressed explicitly"); } @@ -94,99 +206,76 @@ int32_t sinsp_filter_check_tracer::extract_arg(string_view fldname, string_view string numstr(val.substr(fldname.size() + 1, parsed_len - fldname.size() - 1)); m_argid = sinsp_numparser::parsed32(numstr); parsed_len++; - } - else if(val.size() > fldname.size() && val.at(fldname.size()) == '.') - { - if(fldname == "span.tag") - { + } else if(val.size() > fldname.size() && val.at(fldname.size()) == '.') { + if(fldname == "span.tag") { throw sinsp_exception("invalid syntax for span.tag"); - } - else if(fldname == "span.idtag") - { + } else if(fldname == "span.idtag") { throw sinsp_exception("invalid syntax for span.idtag"); } m_argname = val.substr(fldname.size() + 1); parsed_len = (uint32_t)(fldname.size() + m_argname.size() + 1); m_argid = TEXT_ARG_ID; - } - else - { + } else { throw sinsp_exception("filter syntax error: " + string(val)); } return parsed_len; } -int32_t sinsp_filter_check_tracer::parse_field_name(std::string_view val, bool alloc_state, bool needed_for_filtering) -{ +int32_t sinsp_filter_check_tracer::parse_field_name(std::string_view val, + bool alloc_state, + bool needed_for_filtering) { int32_t res; // // A couple of fields are handled in a custom way // - if(STR_MATCH("span.tag") && - !STR_MATCH("span.tags")) - { + if(STR_MATCH("span.tag") && !STR_MATCH("span.tags")) { m_field_id = TYPE_TAG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("span.tag", val, NULL); - } - else if(STR_MATCH("span.arg") && - !STR_MATCH("span.args")) - { + } else if(STR_MATCH("span.arg") && !STR_MATCH("span.args")) { m_field_id = TYPE_ARG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("span.arg", val, NULL); - } - else if(STR_MATCH("span.enterarg") && - !STR_MATCH("span.enterargs")) - { + } else if(STR_MATCH("span.enterarg") && !STR_MATCH("span.enterargs")) { m_field_id = TYPE_ENTERARG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("span.enterarg", val, NULL); - } - else if(STR_MATCH("span.duration.fortag")) - { + } else if(STR_MATCH("span.duration.fortag")) { m_field_id = TYPE_TAGDURATION; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("span.duration.fortag", val, NULL); - } - else if(STR_MATCH("span.count.fortag")) - { + } else if(STR_MATCH("span.count.fortag")) { m_field_id = TYPE_TAGCOUNT; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("span.count.fortag", val, NULL); - } - else if(STR_MATCH("span.childcount.fortag")) - { + } else if(STR_MATCH("span.childcount.fortag")) { m_field_id = TYPE_TAGCHILDSCOUNT; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("span.childcount.fortag", val, NULL); - } - else if(STR_MATCH("span.idtag")) - { + } else if(STR_MATCH("span.idtag")) { m_field_id = TYPE_IDTAG; m_field = &m_info->m_fields[m_field_id]; res = extract_arg("span.idtag", val, NULL); - } - else - { + } else { res = sinsp_filter_check::parse_field_name(val, alloc_state, needed_for_filtering); } return res; } -uint8_t* sinsp_filter_check_tracer::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_tracer::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { // do nothing: support to tracers has been dropped *len = 0; return NULL; diff --git a/userspace/libsinsp/sinsp_filtercheck_tracer.h b/userspace/libsinsp/sinsp_filtercheck_tracer.h index 250be09eb6..a7cfb7cfa8 100644 --- a/userspace/libsinsp/sinsp_filtercheck_tracer.h +++ b/userspace/libsinsp/sinsp_filtercheck_tracer.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_tracer : public sinsp_filter_check -{ +class sinsp_filter_check_tracer : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_ID = 0, TYPE_TIME, TYPE_NTAGS, @@ -51,13 +49,17 @@ class sinsp_filter_check_tracer : public sinsp_filter_check virtual ~sinsp_filter_check_tracer() = default; std::unique_ptr allocate_new() override; - int32_t parse_field_name(std::string_view, bool alloc_state, bool needed_for_filtering) override; + int32_t parse_field_name(std::string_view, + bool alloc_state, + bool needed_for_filtering) override; protected: uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override; private: - int32_t extract_arg(std::string_view fldname, std::string_view val, const struct ppm_param_info** parinfo); + int32_t extract_arg(std::string_view fldname, + std::string_view val, + const struct ppm_param_info** parinfo); int32_t m_argid; std::string m_argname; diff --git a/userspace/libsinsp/sinsp_filtercheck_user.cpp b/userspace/libsinsp/sinsp_filtercheck_user.cpp index 352d754171..a64f1091a3 100644 --- a/userspace/libsinsp/sinsp_filtercheck_user.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_user.cpp @@ -22,72 +22,85 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) - -#define RETURN_EXTRACT_STRING(x) do { \ - *len = (x).size(); \ - return (uint8_t*) (x).c_str(); \ -} while(0) - -static const filtercheck_field_info sinsp_filter_check_user_fields[] = -{ - {PT_UINT32, EPF_NONE, PF_ID, "user.uid", "User ID", "user ID."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "user.name", "User Name", "user name."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "user.homedir", "Home Directory", "home directory of the user."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "user.shell", "Shell", "user's shell."}, - {PT_INT64, EPF_NONE, PF_ID, "user.loginuid", "Login User ID", "audit user id (auid), internally the loginuid is of type `uint32_t`. However, if an invalid uid corresponding to UINT32_MAX is encountered, it is returned as -1 to support familiar filtering conditions."}, - {PT_CHARBUF, EPF_NONE, PF_NA, "user.loginname", "Login User Name", "audit user name (auid)."}, +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ + } while(0) + +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ + } while(0) + +static const filtercheck_field_info sinsp_filter_check_user_fields[] = { + {PT_UINT32, EPF_NONE, PF_ID, "user.uid", "User ID", "user ID."}, + {PT_CHARBUF, EPF_NONE, PF_NA, "user.name", "User Name", "user name."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "user.homedir", + "Home Directory", + "home directory of the user."}, + {PT_CHARBUF, EPF_NONE, PF_NA, "user.shell", "Shell", "user's shell."}, + {PT_INT64, + EPF_NONE, + PF_ID, + "user.loginuid", + "Login User ID", + "audit user id (auid), internally the loginuid is of type `uint32_t`. However, if an " + "invalid uid corresponding to UINT32_MAX is encountered, it is returned as -1 to support " + "familiar filtering conditions."}, + {PT_CHARBUF, + EPF_NONE, + PF_NA, + "user.loginname", + "Login User Name", + "audit user name (auid)."}, }; -sinsp_filter_check_user::sinsp_filter_check_user() -{ +sinsp_filter_check_user::sinsp_filter_check_user() { static const filter_check_info s_field_infos = { - "user", - "", - "Information about the user executing the specific event.", - sizeof(sinsp_filter_check_user_fields) / sizeof(sinsp_filter_check_user_fields[0]), - sinsp_filter_check_user_fields, - filter_check_info::FL_NONE, + "user", + "", + "Information about the user executing the specific event.", + sizeof(sinsp_filter_check_user_fields) / sizeof(sinsp_filter_check_user_fields[0]), + sinsp_filter_check_user_fields, + filter_check_info::FL_NONE, }; m_info = &s_field_infos; memset(&m_val, 0, sizeof(m_val)); } -std::unique_ptr sinsp_filter_check_user::allocate_new() -{ +std::unique_ptr sinsp_filter_check_user::allocate_new() { return std::make_unique(); } -uint8_t* sinsp_filter_check_user::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_user::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; sinsp_threadinfo* tinfo = evt->get_thread_info(); - if(tinfo == NULL) - { + if(tinfo == NULL) { return NULL; } // For container events, use the user from the container metadata instead. if(m_field_id == TYPE_NAME && - (evt->get_type() == PPME_CONTAINER_JSON_E || evt->get_type() == PPME_CONTAINER_JSON_2_E)) - { + (evt->get_type() == PPME_CONTAINER_JSON_E || evt->get_type() == PPME_CONTAINER_JSON_2_E)) { const sinsp_container_info::ptr_t container_info = - m_inspector->m_container_manager.get_container(tinfo->m_container_id); + m_inspector->m_container_manager.get_container(tinfo->m_container_id); - if(!container_info) - { + if(!container_info) { return NULL; } RETURN_EXTRACT_STRING(container_info->m_container_user); } - switch(m_field_id) - { + switch(m_field_id) { case TYPE_UID: m_val.u32 = tinfo->m_user.uid(); RETURN_EXTRACT_VAR(m_val.u32); @@ -102,8 +115,7 @@ uint8_t* sinsp_filter_check_user::extract_single(sinsp_evt *evt, uint32_t* len, RETURN_EXTRACT_STRING(m_strval); case TYPE_LOGINUID: m_val.s64 = (int64_t)-1; - if(tinfo->m_loginuser.uid() < UINT32_MAX) - { + if(tinfo->m_loginuser.uid() < UINT32_MAX) { m_val.s64 = (int64_t)tinfo->m_loginuser.uid(); } RETURN_EXTRACT_VAR(m_val.s64); diff --git a/userspace/libsinsp/sinsp_filtercheck_user.h b/userspace/libsinsp/sinsp_filtercheck_user.h index a2bdf16000..3382eaf608 100644 --- a/userspace/libsinsp/sinsp_filtercheck_user.h +++ b/userspace/libsinsp/sinsp_filtercheck_user.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_user : public sinsp_filter_check -{ +class sinsp_filter_check_user : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_UID = 0, TYPE_NAME = 1, TYPE_HOMEDIR = 2, diff --git a/userspace/libsinsp/sinsp_filtercheck_utils.cpp b/userspace/libsinsp/sinsp_filtercheck_utils.cpp index dba10b01df..6c9b5f37c5 100644 --- a/userspace/libsinsp/sinsp_filtercheck_utils.cpp +++ b/userspace/libsinsp/sinsp_filtercheck_utils.cpp @@ -22,40 +22,38 @@ limitations under the License. using namespace std; -#define RETURN_EXTRACT_VAR(x) do { \ - *len = sizeof((x)); \ - return (uint8_t*) &(x); \ -} while(0) +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ + } while(0) -static const filtercheck_field_info sinsp_filter_check_utils_fields[] = -{ - {PT_UINT64, EPF_NONE, PF_ID, "util.cnt", "Counter", "incremental counter."}, +static const filtercheck_field_info sinsp_filter_check_utils_fields[] = { + {PT_UINT64, EPF_NONE, PF_ID, "util.cnt", "Counter", "incremental counter."}, }; -sinsp_filter_check_utils::sinsp_filter_check_utils() -{ +sinsp_filter_check_utils::sinsp_filter_check_utils() { static const filter_check_info s_field_infos = { - "util", - "", - "", - sizeof(sinsp_filter_check_utils_fields) / sizeof(sinsp_filter_check_utils_fields[0]), - sinsp_filter_check_utils_fields, - filter_check_info::FL_HIDDEN, + "util", + "", + "", + sizeof(sinsp_filter_check_utils_fields) / sizeof(sinsp_filter_check_utils_fields[0]), + sinsp_filter_check_utils_fields, + filter_check_info::FL_HIDDEN, }; m_info = &s_field_infos; m_cnt = 0; } -std::unique_ptr sinsp_filter_check_utils::allocate_new() -{ +std::unique_ptr sinsp_filter_check_utils::allocate_new() { return std::make_unique(); } -uint8_t* sinsp_filter_check_utils::extract_single(sinsp_evt *evt, uint32_t* len, bool sanitize_strings) -{ +uint8_t* sinsp_filter_check_utils::extract_single(sinsp_evt* evt, + uint32_t* len, + bool sanitize_strings) { *len = 0; - switch(m_field_id) - { + switch(m_field_id) { case TYPE_CNT: m_cnt++; RETURN_EXTRACT_VAR(m_cnt); diff --git a/userspace/libsinsp/sinsp_filtercheck_utils.h b/userspace/libsinsp/sinsp_filtercheck_utils.h index 7b9146b464..f448cd83bc 100644 --- a/userspace/libsinsp/sinsp_filtercheck_utils.h +++ b/userspace/libsinsp/sinsp_filtercheck_utils.h @@ -20,11 +20,9 @@ limitations under the License. #include -class sinsp_filter_check_utils : public sinsp_filter_check -{ +class sinsp_filter_check_utils : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_CNT, }; diff --git a/userspace/libsinsp/sinsp_inet.h b/userspace/libsinsp/sinsp_inet.h index 4162c92e3b..a410fc0774 100644 --- a/userspace/libsinsp/sinsp_inet.h +++ b/userspace/libsinsp/sinsp_inet.h @@ -22,7 +22,7 @@ limitations under the License. #ifndef NOMINMAX #define NOMINMAX #endif -# include +#include #else -# include +#include #endif diff --git a/userspace/libsinsp/sinsp_observer.h b/userspace/libsinsp/sinsp_observer.h index 3c0a28c08f..42641521c6 100644 --- a/userspace/libsinsp/sinsp_observer.h +++ b/userspace/libsinsp/sinsp_observer.h @@ -20,24 +20,39 @@ limitations under the License. #include -class sinsp_observer -{ +class sinsp_observer { public: virtual ~sinsp_observer() {} - virtual void on_read(sinsp_evt* evt, int64_t tid, int64_t fd, sinsp_fdinfo* fdinfo, const char *data, uint32_t original_len, uint32_t len) = 0; - virtual void on_write(sinsp_evt* evt, int64_t tid, int64_t fd, sinsp_fdinfo* fdinfo, const char *data, uint32_t original_len, uint32_t len) = 0; + virtual void on_read(sinsp_evt* evt, + int64_t tid, + int64_t fd, + sinsp_fdinfo* fdinfo, + const char* data, + uint32_t original_len, + uint32_t len) = 0; + virtual void on_write(sinsp_evt* evt, + int64_t tid, + int64_t fd, + sinsp_fdinfo* fdinfo, + const char* data, + uint32_t original_len, + uint32_t len) = 0; virtual void on_sendfile(sinsp_evt* evt, int64_t fdin, uint32_t len) = 0; virtual void on_connect(sinsp_evt* evt, uint8_t* packed_data) = 0; - virtual void on_accept(sinsp_evt* evt, int64_t newfd, uint8_t* packed_data, sinsp_fdinfo* new_fdinfo) = 0; + virtual void on_accept(sinsp_evt* evt, + int64_t newfd, + uint8_t* packed_data, + sinsp_fdinfo* new_fdinfo) = 0; virtual void on_file_open(sinsp_evt* evt, const std::string& fullpath, uint32_t flags) = 0; virtual void on_error(sinsp_evt* evt) = 0; virtual void on_erase_fd(erase_fd_params* params) = 0; - virtual void on_socket_shutdown(sinsp_evt *evt) = 0; + virtual void on_socket_shutdown(sinsp_evt* evt) = 0; virtual void on_execve(sinsp_evt* evt) = 0; virtual void on_clone(sinsp_evt* evt, sinsp_threadinfo* newtinfo, int64_t tid_collision) = 0; virtual void on_bind(sinsp_evt* evt) = 0; - virtual bool on_resolve_container(sinsp_container_manager* manager, sinsp_threadinfo* tinfo, bool query_os_for_missing_info) = 0; - virtual void on_socket_status_changed(sinsp_evt *evt) = 0; + virtual bool on_resolve_container(sinsp_container_manager* manager, + sinsp_threadinfo* tinfo, + bool query_os_for_missing_info) = 0; + virtual void on_socket_status_changed(sinsp_evt* evt) = 0; }; - diff --git a/userspace/libsinsp/sinsp_public.h b/userspace/libsinsp/sinsp_public.h index d4a1cc60ed..7ff1dc5304 100644 --- a/userspace/libsinsp/sinsp_public.h +++ b/userspace/libsinsp/sinsp_public.h @@ -30,7 +30,7 @@ limitations under the License. #define ASSERT(X) assert(X); -#else // _DEBUG +#else // _DEBUG #define ASSERT(X) -#endif // _DEBUG -#endif // ASSERT +#endif // _DEBUG +#endif // ASSERT diff --git a/userspace/libsinsp/sinsp_signal.h b/userspace/libsinsp/sinsp_signal.h index eaf36e463e..e127afda89 100644 --- a/userspace/libsinsp/sinsp_signal.h +++ b/userspace/libsinsp/sinsp_signal.h @@ -16,38 +16,38 @@ limitations under the License. */ -#define SE_NSIG 64 -#define SE_SIGHUP 1 -#define SE_SIGINT 2 -#define SE_SIGQUIT 3 -#define SE_SIGILL 4 -#define SE_SIGTRAP 5 -#define SE_SIGABRT 6 -#define SE_SIGIOT 6 -#define SE_SIGBUS 7 -#define SE_SIGFPE 8 -#define SE_SIGKILL 9 -#define SE_SIGUSR1 10 -#define SE_SIGSEGV 11 -#define SE_SIGUSR2 12 -#define SE_SIGPIPE 13 -#define SE_SIGALRM 14 -#define SE_SIGTERM 15 -#define SE_SIGSTKFLT 16 -#define SE_SIGCHLD 17 -#define SE_SIGCONT 18 -#define SE_SIGSTOP 19 -#define SE_SIGTSTP 20 -#define SE_SIGTTIN 21 -#define SE_SIGTTOU 22 -#define SE_SIGURG 23 -#define SE_SIGXCPU 24 -#define SE_SIGXFSZ 25 -#define SE_SIGVTALRM 26 -#define SE_SIGPROF 27 -#define SE_SIGWINCH 28 -#define SE_SIGIO 29 -#define SE_SIGPOLL SE_SIGIO -#define SE_SIGPWR 30 -#define SE_SIGSYS 31 -#define SE_SIGUNUSED 31 +#define SE_NSIG 64 +#define SE_SIGHUP 1 +#define SE_SIGINT 2 +#define SE_SIGQUIT 3 +#define SE_SIGILL 4 +#define SE_SIGTRAP 5 +#define SE_SIGABRT 6 +#define SE_SIGIOT 6 +#define SE_SIGBUS 7 +#define SE_SIGFPE 8 +#define SE_SIGKILL 9 +#define SE_SIGUSR1 10 +#define SE_SIGSEGV 11 +#define SE_SIGUSR2 12 +#define SE_SIGPIPE 13 +#define SE_SIGALRM 14 +#define SE_SIGTERM 15 +#define SE_SIGSTKFLT 16 +#define SE_SIGCHLD 17 +#define SE_SIGCONT 18 +#define SE_SIGSTOP 19 +#define SE_SIGTSTP 20 +#define SE_SIGTTIN 21 +#define SE_SIGTTOU 22 +#define SE_SIGURG 23 +#define SE_SIGXCPU 24 +#define SE_SIGXFSZ 25 +#define SE_SIGVTALRM 26 +#define SE_SIGPROF 27 +#define SE_SIGWINCH 28 +#define SE_SIGIO 29 +#define SE_SIGPOLL SE_SIGIO +#define SE_SIGPWR 30 +#define SE_SIGSYS 31 +#define SE_SIGUNUSED 31 diff --git a/userspace/libsinsp/sinsp_suppress.cpp b/userspace/libsinsp/sinsp_suppress.cpp index 763c41ff05..01ed82271f 100644 --- a/userspace/libsinsp/sinsp_suppress.cpp +++ b/userspace/libsinsp/sinsp_suppress.cpp @@ -24,30 +24,24 @@ limitations under the License. #include #include -void libsinsp::sinsp_suppress::suppress_comm(const std::string &comm) -{ +void libsinsp::sinsp_suppress::suppress_comm(const std::string &comm) { m_suppressed_comms.emplace(comm); } -void libsinsp::sinsp_suppress::suppress_tid(uint64_t tid) -{ +void libsinsp::sinsp_suppress::suppress_tid(uint64_t tid) { m_suppressed_tids.emplace(tid); } -void libsinsp::sinsp_suppress::clear_suppress_comm() -{ +void libsinsp::sinsp_suppress::clear_suppress_comm() { m_suppressed_comms.clear(); } -void libsinsp::sinsp_suppress::clear_suppress_tid() -{ +void libsinsp::sinsp_suppress::clear_suppress_tid() { m_suppressed_tids.clear(); } -bool libsinsp::sinsp_suppress::check_suppressed_comm(uint64_t tid, const std::string &comm) -{ - if(m_suppressed_comms.find(comm) != m_suppressed_comms.end()) - { +bool libsinsp::sinsp_suppress::check_suppressed_comm(uint64_t tid, const std::string &comm) { + if(m_suppressed_comms.find(comm) != m_suppressed_comms.end()) { m_suppressed_tids.insert(tid); m_num_suppressed_events++; return true; @@ -55,10 +49,8 @@ bool libsinsp::sinsp_suppress::check_suppressed_comm(uint64_t tid, const std::st return false; } -int32_t libsinsp::sinsp_suppress::process_event(scap_evt *e) -{ - if(m_suppressed_tids.empty() && m_suppressed_comms.empty()) - { +int32_t libsinsp::sinsp_suppress::process_event(scap_evt *e) { + if(m_suppressed_tids.empty() && m_suppressed_comms.empty()) { // nothing to suppress return SCAP_SUCCESS; } @@ -70,15 +62,13 @@ int32_t libsinsp::sinsp_suppress::process_event(scap_evt *e) uint64_t tid; memcpy(&tid, &e->tid, sizeof(uint64_t)); - switch(e->type) - { + switch(e->type) { case PPME_SYSCALL_CLONE_20_X: case PPME_SYSCALL_FORK_20_X: case PPME_SYSCALL_VFORK_20_X: case PPME_SYSCALL_EXECVE_19_X: case PPME_SYSCALL_EXECVEAT_X: - case PPME_SYSCALL_CLONE3_X: - { + case PPME_SYSCALL_CLONE3_X: { uint32_t j; const char *comm = nullptr; uint64_t *ptid_ptr = nullptr; @@ -88,8 +78,7 @@ int32_t libsinsp::sinsp_suppress::process_event(scap_evt *e) uint16_t scratch = 0; ASSERT(e->nparams >= 14); - if(e->nparams < 14) - { + if(e->nparams < 14) { // SCAP_SUCCESS means "do not suppress this event" return SCAP_SUCCESS; } @@ -97,10 +86,8 @@ int32_t libsinsp::sinsp_suppress::process_event(scap_evt *e) // For all of these events, the comm is argument 14, // so we need to walk the list of params that far to // find the comm. - for(j = 0; j < 13; j++) - { - if(j == 5) - { + for(j = 0; j < 13; j++) { + if(j == 5) { ptid_ptr = (uint64_t *)valptr; } @@ -109,8 +96,7 @@ int32_t libsinsp::sinsp_suppress::process_event(scap_evt *e) } ASSERT(ptid_ptr != nullptr); - if(ptid_ptr == nullptr) - { + if(ptid_ptr == nullptr) { // SCAP_SUCCESS means "do not suppress this event" return SCAP_SUCCESS; } @@ -119,52 +105,41 @@ int32_t libsinsp::sinsp_suppress::process_event(scap_evt *e) uint64_t ptid; memcpy(&ptid, ptid_ptr, sizeof(uint64_t)); - if(is_suppressed_tid(ptid)) - { + if(is_suppressed_tid(ptid)) { m_suppressed_tids.insert(tid); m_num_suppressed_events++; return SCAP_FILTERED_EVENT; } - if(check_suppressed_comm(tid, comm)) - { + if(check_suppressed_comm(tid, comm)) { return SCAP_FILTERED_EVENT; } return SCAP_SUCCESS; } - case PPME_PROCEXIT_1_E: - { + case PPME_PROCEXIT_1_E: { auto it = m_suppressed_tids.find(tid); - if (it != m_suppressed_tids.end()) - { + if(it != m_suppressed_tids.end()) { m_suppressed_tids.erase(it); m_num_suppressed_events++; return SCAP_FILTERED_EVENT; - } - else - { + } else { return SCAP_SUCCESS; } } default: - if (is_suppressed_tid(tid)) - { + if(is_suppressed_tid(tid)) { m_num_suppressed_events++; return SCAP_FILTERED_EVENT; - } - else - { + } else { return SCAP_SUCCESS; } } } -bool libsinsp::sinsp_suppress::is_suppressed_tid(uint64_t tid) const -{ - if (tid == 0) - { +bool libsinsp::sinsp_suppress::is_suppressed_tid(uint64_t tid) const { + if(tid == 0) { return false; } return m_suppressed_tids.find(tid) != m_suppressed_tids.end(); diff --git a/userspace/libsinsp/sinsp_suppress.h b/userspace/libsinsp/sinsp_suppress.h index f5df45cff3..39fbb73589 100644 --- a/userspace/libsinsp/sinsp_suppress.h +++ b/userspace/libsinsp/sinsp_suppress.h @@ -24,11 +24,9 @@ limitations under the License. typedef struct ppm_evt_hdr scap_evt; -namespace libsinsp -{ +namespace libsinsp { -class sinsp_suppress -{ +class sinsp_suppress { public: sinsp_suppress() = default; @@ -57,4 +55,4 @@ class sinsp_suppress uint64_t m_num_suppressed_events = 0; }; -} +} // namespace libsinsp diff --git a/userspace/libsinsp/sinsp_syslog.cpp b/userspace/libsinsp/sinsp_syslog.cpp index 181a457ef0..233440ead8 100644 --- a/userspace/libsinsp/sinsp_syslog.cpp +++ b/userspace/libsinsp/sinsp_syslog.cpp @@ -22,47 +22,20 @@ limitations under the License. #define PRI_BUF_SIZE 16 static const std::string s_syslog_severity_strings[] = -{ - "emerg", "alert", "crit", "err", "warn", "notice", "info", "debug" -}; - -static const std::string s_syslog_facility_strings[] = -{ - "kern", - "user", - "mail", - "daemon", - "auth", - "syslog", - "lpr", - "news", - "uucp", - "clock", - "authpriv", - "ftp", - "ntp", - "logaudit", - "logalert", - "cron", - "local0", - "local1", - "local2", - "local3", - "local4", - "local5", - "local6", - "local7" -}; - -void sinsp_syslog_decoder::parse_data(const char *data, uint32_t len) -{ + {"emerg", "alert", "crit", "err", "warn", "notice", "info", "debug"}; + +static const std::string s_syslog_facility_strings[] = { + "kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", + "uucp", "clock", "authpriv", "ftp", "ntp", "logaudit", "logalert", "cron", + "local0", "local1", "local2", "local3", "local4", "local5", "local6", "local7"}; + +void sinsp_syslog_decoder::parse_data(const char* data, uint32_t len) { char pri[PRI_BUF_SIZE]; const char* tc = data + 1; const char* te = data + len; uint32_t j = 0; - while(tc < te && *tc != '>' && *tc != '\0' && j < PRI_BUF_SIZE - 1) - { + while(tc < te && *tc != '>' && *tc != '\0' && j < PRI_BUF_SIZE - 1) { pri[j++] = *tc; tc++; } @@ -72,42 +45,36 @@ void sinsp_syslog_decoder::parse_data(const char *data, uint32_t len) decode_message(data, len, pri, j); } -std::string sinsp_syslog_decoder::get_severity_str() const -{ - if(!is_data_valid() || m_severity >= sizeof(s_syslog_severity_strings) / sizeof(s_syslog_severity_strings[0])) - { +std::string sinsp_syslog_decoder::get_severity_str() const { + if(!is_data_valid() || + m_severity >= sizeof(s_syslog_severity_strings) / sizeof(s_syslog_severity_strings[0])) { return ""; - } - else - { + } else { return s_syslog_severity_strings[m_severity]; } } -std::string sinsp_syslog_decoder::get_facility_str() const -{ - if(!is_data_valid() || m_facility >= sizeof(s_syslog_facility_strings) / sizeof(s_syslog_facility_strings[0])) - { +std::string sinsp_syslog_decoder::get_facility_str() const { + if(!is_data_valid() || + m_facility >= sizeof(s_syslog_facility_strings) / sizeof(s_syslog_facility_strings[0])) { return ""; - } - else - { + } else { return s_syslog_facility_strings[m_facility]; } } -void sinsp_syslog_decoder::decode_message(const char *data, uint32_t len, char* pristr, uint32_t pristrlen) -{ - if(len < pristrlen + 2 || pristrlen == 0) - { +void sinsp_syslog_decoder::decode_message(const char* data, + uint32_t len, + char* pristr, + uint32_t pristrlen) { + if(len < pristrlen + 2 || pristrlen == 0) { m_priority = s_invalid_priority; return; } bool res = sinsp_numparser::tryparsed32_fast(pristr, pristrlen, &m_priority); - if(!res) - { + if(!res) { m_priority = s_invalid_priority; return; } @@ -118,10 +85,8 @@ void sinsp_syslog_decoder::decode_message(const char *data, uint32_t len, char* m_msg.assign(data + pristrlen + 2, len - pristrlen - 2); } -std::string sinsp_syslog_decoder::get_info_line() const -{ - if (!is_data_valid()) - { +std::string sinsp_syslog_decoder::get_info_line() const { + if(!is_data_valid()) { return ""; } diff --git a/userspace/libsinsp/sinsp_syslog.h b/userspace/libsinsp/sinsp_syslog.h index 6e6cd1de33..0e62400904 100644 --- a/userspace/libsinsp/sinsp_syslog.h +++ b/userspace/libsinsp/sinsp_syslog.h @@ -24,47 +24,28 @@ limitations under the License. #include #include -class sinsp_syslog_decoder -{ +class sinsp_syslog_decoder { public: - void parse_data(const char *data, uint32_t len); + void parse_data(const char* data, uint32_t len); std::string get_info_line() const; std::string get_severity_str() const; std::string get_facility_str() const; - inline void reset() - { - m_priority = s_invalid_priority; - } + inline void reset() { m_priority = s_invalid_priority; } - bool is_data_valid() const - { - return m_priority != s_invalid_priority; - } + bool is_data_valid() const { return m_priority != s_invalid_priority; } - inline int32_t get_priority() const - { - return m_priority; - } + inline int32_t get_priority() const { return m_priority; } - inline uint32_t get_facility() const - { - return m_facility; - } + inline uint32_t get_facility() const { return m_facility; } - inline uint32_t get_severity() const - { - return m_severity; - } + inline uint32_t get_severity() const { return m_severity; } - inline const std::string& get_msg() const - { - return m_msg; - } + inline const std::string& get_msg() const { return m_msg; } private: - void decode_message(const char *data, uint32_t len, char* pristr, uint32_t pristrlen); + void decode_message(const char* data, uint32_t len, char* pristr, uint32_t pristrlen); int32_t m_priority{s_invalid_priority}; uint32_t m_facility{0}; diff --git a/userspace/libsinsp/state/dynamic_struct.h b/userspace/libsinsp/state/dynamic_struct.h index 6705f7d094..63b1500dc5 100644 --- a/userspace/libsinsp/state/dynamic_struct.h +++ b/userspace/libsinsp/state/dynamic_struct.h @@ -29,476 +29,413 @@ namespace state { /** * @brief A base class for classes and structs that allow dynamic programming - * by being extensible and allowing adding and accessing new data fields at runtime. + * by being extensible and allowing adding and accessing new data fields at runtime. */ -class dynamic_struct -{ +class dynamic_struct { public: - template class field_accessor; - - /** - * @brief Info about a given field in a dynamic struct. - */ - class field_info - { - public: - template - static inline field_info build(const std::string& name, size_t index, uintptr_t defsptr, bool readonly=false) - { - return field_info(name, index, libsinsp::state::typeinfo::of(), defsptr, readonly); - } - - inline field_info(const std::string& n, size_t in, const typeinfo& i, uintptr_t defsptr, bool r) - : m_readonly(r), - m_index(in), - m_name(n), - m_info(i), - m_defs_id(defsptr) {} - inline field_info(): - m_readonly(true), - m_index((size_t) -1), - m_name(""), - m_info(typeinfo::of()), - m_defs_id((uintptr_t) NULL) {} - inline ~field_info() = default; - inline field_info(field_info&&) = default; - inline field_info& operator = (field_info&&) = default; - inline field_info(const field_info& s) = default; - inline field_info& operator = (const field_info& s) = default; - - friend inline bool operator==(const field_info& a, const field_info& b) - { - return a.info() == b.info() - && a.name() == b.name() - && a.m_index == b.m_index - && a.m_defs_id == b.m_defs_id; - }; - - friend inline bool operator!=(const field_info& a, const field_info& b) - { - return !(a == b); - }; - - /** - * @brief Returns the id of the shared definitions this info belongs to. - */ - inline uintptr_t defs_id() const - { - return m_defs_id; - } - - /** - * @brief Returns true if the field is read only. - */ - inline bool readonly() const - { - return m_readonly; - } - - /** - * @brief Returns true if the field info is valid. - */ - inline bool valid() const - { - // note(jasondellaluce): for now dynamic fields of type table are - // not supported, so we consider them to be invalid - return m_index != (size_t) -1 && m_index != typeinfo::index_t::TI_TABLE; - } - - /** - * @brief Returns the name of the field. - */ - inline const std::string& name() const - { - return m_name; - } - - /** - * @brief Returns the index of the field. - */ - inline size_t index() const - { - return m_index; - } - - /** - * @brief Returns the type info of the field. - */ - inline const libsinsp::state::typeinfo& info() const - { - return m_info; - } - - /** - * @brief Returns a strongly-typed accessor for the given field, - * that can be used to reading and writing the field's value in - * all instances of structs where it is defined. - */ - template - inline field_accessor new_accessor() const - { - if (!valid()) - { - throw sinsp_exception("can't create dynamic struct field accessor for invalid field"); - } - auto t = libsinsp::state::typeinfo::of(); - if (m_info != t) - { - throw sinsp_exception( - "incompatible type for dynamic struct field accessor: field=" + m_name - + ", expected_type=" + t.name() + ", actual_type=" + m_info.name()); - } - return field_accessor(*this); - } - - private: - bool m_readonly; - size_t m_index; - std::string m_name; - libsinsp::state::typeinfo m_info; - uintptr_t m_defs_id; - - friend class dynamic_struct; - }; - - /** - * @brief An strongly-typed accessor for accessing a field of a dynamic struct. - * @tparam T Type of the field. - */ - template - class field_accessor - { - public: - inline field_accessor() = default; - inline ~field_accessor() = default; - inline field_accessor(field_accessor&&) = default; - inline field_accessor& operator = (field_accessor&&) = default; - inline field_accessor(const field_accessor& s) = default; - inline field_accessor& operator = (const field_accessor& s) = default; - - /** - * @brief Returns the info about the field to which this accessor is tied. - */ - inline const field_info& info() const - { - return m_info; - } - - private: - inline explicit field_accessor(const field_info& info): m_info(info) { }; - - field_info m_info; - - friend class dynamic_struct; - friend class dynamic_struct::field_info; - }; - - /** - * @brief Dynamic fields metadata of a given struct or class - * that are discoverable and accessible dynamically at runtime. - * All instances of the same struct or class must share the same - * instance of field_infos. - */ - class field_infos - { - public: - inline field_infos(): m_defs_id((uintptr_t) this) { }; - inline explicit field_infos(uintptr_t defs_id): m_defs_id(defs_id) { }; - virtual ~field_infos() = default; - inline field_infos(field_infos&&) = default; - inline field_infos& operator = (field_infos&&) = default; - inline field_infos(const field_infos& s) = delete; - inline field_infos& operator = (const field_infos& s) = delete; - - inline uintptr_t id() const - { - return m_defs_id; - } - - /** - * @brief Adds metadata for a new field to the list. An exception is - * thrown if two fields are defined with the same name and with - * incompatible types, otherwise the previous definition is returned. - * - * @tparam T Type of the field. - * @param name Display name of the field. - */ - template - inline const field_info& add_field(const std::string& name) - { - auto field = field_info::build(name, m_definitions.size(), id()); - return add_field_info(field); - } - - virtual const std::unordered_map& fields() - { - return m_definitions; - } + template + class field_accessor; + + /** + * @brief Info about a given field in a dynamic struct. + */ + class field_info { + public: + template + static inline field_info build(const std::string& name, + size_t index, + uintptr_t defsptr, + bool readonly = false) { + return field_info(name, index, libsinsp::state::typeinfo::of(), defsptr, readonly); + } + + inline field_info(const std::string& n, + size_t in, + const typeinfo& i, + uintptr_t defsptr, + bool r): + m_readonly(r), + m_index(in), + m_name(n), + m_info(i), + m_defs_id(defsptr) {} + inline field_info(): + m_readonly(true), + m_index((size_t)-1), + m_name(""), + m_info(typeinfo::of()), + m_defs_id((uintptr_t)NULL) {} + inline ~field_info() = default; + inline field_info(field_info&&) = default; + inline field_info& operator=(field_info&&) = default; + inline field_info(const field_info& s) = default; + inline field_info& operator=(const field_info& s) = default; + + friend inline bool operator==(const field_info& a, const field_info& b) { + return a.info() == b.info() && a.name() == b.name() && a.m_index == b.m_index && + a.m_defs_id == b.m_defs_id; + }; + + friend inline bool operator!=(const field_info& a, const field_info& b) { + return !(a == b); + }; + + /** + * @brief Returns the id of the shared definitions this info belongs to. + */ + inline uintptr_t defs_id() const { return m_defs_id; } + + /** + * @brief Returns true if the field is read only. + */ + inline bool readonly() const { return m_readonly; } + + /** + * @brief Returns true if the field info is valid. + */ + inline bool valid() const { + // note(jasondellaluce): for now dynamic fields of type table are + // not supported, so we consider them to be invalid + return m_index != (size_t)-1 && m_index != typeinfo::index_t::TI_TABLE; + } + + /** + * @brief Returns the name of the field. + */ + inline const std::string& name() const { return m_name; } + + /** + * @brief Returns the index of the field. + */ + inline size_t index() const { return m_index; } + + /** + * @brief Returns the type info of the field. + */ + inline const libsinsp::state::typeinfo& info() const { return m_info; } + + /** + * @brief Returns a strongly-typed accessor for the given field, + * that can be used to reading and writing the field's value in + * all instances of structs where it is defined. + */ + template + inline field_accessor new_accessor() const { + if(!valid()) { + throw sinsp_exception( + "can't create dynamic struct field accessor for invalid field"); + } + auto t = libsinsp::state::typeinfo::of(); + if(m_info != t) { + throw sinsp_exception( + "incompatible type for dynamic struct field accessor: field=" + m_name + + ", expected_type=" + t.name() + ", actual_type=" + m_info.name()); + } + return field_accessor(*this); + } + + private: + bool m_readonly; + size_t m_index; + std::string m_name; + libsinsp::state::typeinfo m_info; + uintptr_t m_defs_id; + + friend class dynamic_struct; + }; + + /** + * @brief An strongly-typed accessor for accessing a field of a dynamic struct. + * @tparam T Type of the field. + */ + template + class field_accessor { + public: + inline field_accessor() = default; + inline ~field_accessor() = default; + inline field_accessor(field_accessor&&) = default; + inline field_accessor& operator=(field_accessor&&) = default; + inline field_accessor(const field_accessor& s) = default; + inline field_accessor& operator=(const field_accessor& s) = default; + + /** + * @brief Returns the info about the field to which this accessor is tied. + */ + inline const field_info& info() const { return m_info; } + + private: + inline explicit field_accessor(const field_info& info): m_info(info) {}; + + field_info m_info; + + friend class dynamic_struct; + friend class dynamic_struct::field_info; + }; + + /** + * @brief Dynamic fields metadata of a given struct or class + * that are discoverable and accessible dynamically at runtime. + * All instances of the same struct or class must share the same + * instance of field_infos. + */ + class field_infos { + public: + inline field_infos(): m_defs_id((uintptr_t)this) {}; + inline explicit field_infos(uintptr_t defs_id): m_defs_id(defs_id) {}; + virtual ~field_infos() = default; + inline field_infos(field_infos&&) = default; + inline field_infos& operator=(field_infos&&) = default; + inline field_infos(const field_infos& s) = delete; + inline field_infos& operator=(const field_infos& s) = delete; + + inline uintptr_t id() const { return m_defs_id; } + + /** + * @brief Adds metadata for a new field to the list. An exception is + * thrown if two fields are defined with the same name and with + * incompatible types, otherwise the previous definition is returned. + * + * @tparam T Type of the field. + * @param name Display name of the field. + */ + template + inline const field_info& add_field(const std::string& name) { + auto field = field_info::build(name, m_definitions.size(), id()); + return add_field_info(field); + } + + virtual const std::unordered_map& fields() { + return m_definitions; + } + + protected: + virtual const field_info& add_field_info(const field_info& field) { + if(field.info().index() == typeinfo::index_t::TI_TABLE) { + throw sinsp_exception("dynamic fields of type table are not supported"); + } + + const auto& it = m_definitions.find(field.name()); + if(it != m_definitions.end()) { + const auto& t = field.info(); + if(it->second.info() != t) { + throw sinsp_exception( + "multiple definitions of dynamic field with different types in " + "struct: " + + field.name() + ", prevtype=" + it->second.info().name() + + ", newtype=" + t.name()); + } + return it->second; + } + m_definitions.insert({field.name(), field}); + const auto& def = m_definitions.at(field.name()); + m_definitions_ordered.push_back(&def); + return def; + } + + uintptr_t m_defs_id; + std::unordered_map m_definitions; + std::vector m_definitions_ordered; + friend class dynamic_struct; + }; + + inline explicit dynamic_struct(const std::shared_ptr& dynamic_fields): + m_fields(), + m_dynamic_fields(dynamic_fields) {} + + inline dynamic_struct(dynamic_struct&&) = default; + + inline dynamic_struct& operator=(dynamic_struct&&) = default; + + inline dynamic_struct(const dynamic_struct& s) { deep_fields_copy(s); } + + inline dynamic_struct& operator=(const dynamic_struct& s) { + deep_fields_copy(s); + return *this; + } + + virtual ~dynamic_struct() { destroy_dynamic_fields(); } + + /** + * @brief Accesses a field with the given accessor and reads its value. + */ + template + inline void get_dynamic_field(const field_accessor& a, Val& out) { + _check_defsptr(a.info(), false); + get_dynamic_field(a.info(), reinterpret_cast(&out)); + } + + /** + * @brief Accesses a field with the given accessor and writes its value. + */ + template + inline void set_dynamic_field(const field_accessor& a, const Val& in) { + _check_defsptr(a.info(), true); + if(a.info().readonly()) { + throw sinsp_exception("can't set a read-only dynamic struct field: " + a.info().name()); + } + set_dynamic_field(a.info(), reinterpret_cast(&in)); + } + + /** + * @brief Returns information about all the dynamic fields accessible in a struct. + */ + inline const std::shared_ptr& dynamic_fields() const { return m_dynamic_fields; } + + /** + * @brief Sets the shared definitions for the dynamic fields accessible in a struct. + * The definitions can be set to a non-null value only once, either at + * construction time by invoking this method. + */ + virtual void set_dynamic_fields(const std::shared_ptr& defs) { + if(m_dynamic_fields.get() == defs.get()) { + return; + } + if(m_dynamic_fields && m_dynamic_fields.use_count() > 1) { + throw sinsp_exception("dynamic struct defintions set twice"); + } + if(!defs) { + throw sinsp_exception("dynamic struct constructed with null field definitions"); + } + m_dynamic_fields = defs; + } protected: - virtual const field_info& add_field_info(const field_info& field) - { - if (field.info().index() == typeinfo::index_t::TI_TABLE) - { - throw sinsp_exception("dynamic fields of type table are not supported"); - } - - const auto &it = m_definitions.find(field.name()); - if (it != m_definitions.end()) - { - const auto& t = field.info(); - if (it->second.info() != t) - { - throw sinsp_exception("multiple definitions of dynamic field with different types in struct: " - + field.name() + ", prevtype=" + it->second.info().name() + ", newtype=" + t.name()); - } - return it->second; - } - m_definitions.insert({ field.name(), field }); - const auto& def = m_definitions.at(field.name()); - m_definitions_ordered.push_back(&def); - return def; - } - - uintptr_t m_defs_id; - std::unordered_map m_definitions; - std::vector m_definitions_ordered; - friend class dynamic_struct; - }; - - inline explicit dynamic_struct(const std::shared_ptr& dynamic_fields) - : m_fields(), m_dynamic_fields(dynamic_fields) { } - - inline dynamic_struct(dynamic_struct&&) = default; - - inline dynamic_struct& operator=(dynamic_struct&&) = default; - - inline dynamic_struct(const dynamic_struct& s) - { - deep_fields_copy(s); - } - - inline dynamic_struct& operator=(const dynamic_struct& s) - { - deep_fields_copy(s); - return *this; - } - - virtual ~dynamic_struct() - { - destroy_dynamic_fields(); - } - - /** - * @brief Accesses a field with the given accessor and reads its value. - */ - template - inline void get_dynamic_field(const field_accessor& a, Val& out) - { - _check_defsptr(a.info(), false); - get_dynamic_field(a.info(), reinterpret_cast(&out)); - } - - /** - * @brief Accesses a field with the given accessor and writes its value. - */ - template - inline void set_dynamic_field(const field_accessor& a, const Val& in) - { - _check_defsptr(a.info(), true); - if (a.info().readonly()) - { - throw sinsp_exception("can't set a read-only dynamic struct field: " + a.info().name()); - } - set_dynamic_field(a.info(), reinterpret_cast(&in)); - } - - /** - * @brief Returns information about all the dynamic fields accessible in a struct. - */ - inline const std::shared_ptr& dynamic_fields() const - { - return m_dynamic_fields; - } - - /** - * @brief Sets the shared definitions for the dynamic fields accessible in a struct. - * The definitions can be set to a non-null value only once, either at - * construction time by invoking this method. - */ - virtual void set_dynamic_fields(const std::shared_ptr& defs) - { - if (m_dynamic_fields.get() == defs.get()) - { - return; - } - if (m_dynamic_fields && m_dynamic_fields.use_count() > 1) - { - throw sinsp_exception("dynamic struct defintions set twice"); - } - if (!defs) - { - throw sinsp_exception("dynamic struct constructed with null field definitions"); - } - m_dynamic_fields = defs; - } - -protected: - /** - * @brief Gets the value of a dynamic field and writes it into "out". - * "out" points to a variable having the type of the field_info argument, - * according to the type definitions supported in libsinsp::state::typeinfo. - * For strings, "out" is considered of type const char**. - */ - virtual void get_dynamic_field(const field_info& i, void* out) - { - const auto* buf = _access_dynamic_field(i.m_index); - if (i.info().index() == typeinfo::index_t::TI_STRING) - { - *((const char**) out) = ((const std::string*) buf)->c_str(); - } - else - { - memcpy(out, buf, i.info().size()); - } - } - - /** - * @brief Sets the value of a dynamic field by reading it from "in". - * "in" points to a variable having the type of the field_info argument, - * according to the type definitions supported in libsinsp::state::typeinfo. - * For strings, "in" is considered of type const char**. - */ - virtual void set_dynamic_field(const field_info& i, const void* in) - { - auto* buf = _access_dynamic_field(i.m_index); - if (i.info().index() == typeinfo::index_t::TI_STRING) - { - *((std::string*) buf) = *((const char**) in); - } - else - { - memcpy(buf, in, i.info().size()); - } - } - - /** - * @brief Destroys all the dynamic field values currently allocated - */ - virtual void destroy_dynamic_fields() - { - if (!m_dynamic_fields) - { - return; - } - for (size_t i = 0; i < m_fields.size(); i++) - { - m_dynamic_fields->m_definitions_ordered[i]->info().destroy(m_fields[i]); - free(m_fields[i]); - } - m_fields.clear(); - } + /** + * @brief Gets the value of a dynamic field and writes it into "out". + * "out" points to a variable having the type of the field_info argument, + * according to the type definitions supported in libsinsp::state::typeinfo. + * For strings, "out" is considered of type const char**. + */ + virtual void get_dynamic_field(const field_info& i, void* out) { + const auto* buf = _access_dynamic_field(i.m_index); + if(i.info().index() == typeinfo::index_t::TI_STRING) { + *((const char**)out) = ((const std::string*)buf)->c_str(); + } else { + memcpy(out, buf, i.info().size()); + } + } + + /** + * @brief Sets the value of a dynamic field by reading it from "in". + * "in" points to a variable having the type of the field_info argument, + * according to the type definitions supported in libsinsp::state::typeinfo. + * For strings, "in" is considered of type const char**. + */ + virtual void set_dynamic_field(const field_info& i, const void* in) { + auto* buf = _access_dynamic_field(i.m_index); + if(i.info().index() == typeinfo::index_t::TI_STRING) { + *((std::string*)buf) = *((const char**)in); + } else { + memcpy(buf, in, i.info().size()); + } + } + + /** + * @brief Destroys all the dynamic field values currently allocated + */ + virtual void destroy_dynamic_fields() { + if(!m_dynamic_fields) { + return; + } + for(size_t i = 0; i < m_fields.size(); i++) { + m_dynamic_fields->m_definitions_ordered[i]->info().destroy(m_fields[i]); + free(m_fields[i]); + } + m_fields.clear(); + } private: - inline void _check_defsptr(const field_info& i, bool write) const - { - if (!i.valid()) - { - throw sinsp_exception("can't set invalid field in dynamic struct"); - } - if (m_dynamic_fields->id() != i.m_defs_id) - { - throw sinsp_exception("using dynamic field accessor on struct it was not created from: " + i.name()); - } - if (write && i.readonly()) - { - throw sinsp_exception("can't set a read-only dynamic struct field: " + i.name()); - } - } - - inline void* _access_dynamic_field(size_t index) - { - if (!m_dynamic_fields) - { - throw sinsp_exception("dynamic struct has no field definitions"); - } - if (index >= m_dynamic_fields->m_definitions_ordered.size()) - { - throw sinsp_exception("dynamic struct access overflow: " + std::to_string(index)); - } - while (m_fields.size() <= index) - { - auto def = m_dynamic_fields->m_definitions_ordered[m_fields.size()]; - void* fieldbuf = malloc(def->info().size()); - def->info().construct(fieldbuf); - m_fields.push_back(fieldbuf); - } - return m_fields[index]; - } - - inline void deep_fields_copy(const dynamic_struct& other_const) - { - // note: const cast should be safe here as we're not going to resize - // nor edit the dynamic fields allocated in "other" - auto& other = const_cast(other_const); - - // copy the definitions - set_dynamic_fields(other.dynamic_fields()); - - // deep copy of all the fields - destroy_dynamic_fields(); - for (size_t i = 0; i < other.m_fields.size(); i++) - { - const auto info = m_dynamic_fields->m_definitions_ordered[i]; - // note: we use uintptr_t as it fits all the data types supported for - // reading and writing dynamic fields (e.g. uint32_t, uint64_t, const char*, base_table*, ...) - uintptr_t val = 0; - other.get_dynamic_field(*info, reinterpret_cast(&val)); - set_dynamic_field(*info, &val); - } - } - - std::vector m_fields; - std::shared_ptr m_dynamic_fields; + inline void _check_defsptr(const field_info& i, bool write) const { + if(!i.valid()) { + throw sinsp_exception("can't set invalid field in dynamic struct"); + } + if(m_dynamic_fields->id() != i.m_defs_id) { + throw sinsp_exception( + "using dynamic field accessor on struct it was not created from: " + i.name()); + } + if(write && i.readonly()) { + throw sinsp_exception("can't set a read-only dynamic struct field: " + i.name()); + } + } + + inline void* _access_dynamic_field(size_t index) { + if(!m_dynamic_fields) { + throw sinsp_exception("dynamic struct has no field definitions"); + } + if(index >= m_dynamic_fields->m_definitions_ordered.size()) { + throw sinsp_exception("dynamic struct access overflow: " + std::to_string(index)); + } + while(m_fields.size() <= index) { + auto def = m_dynamic_fields->m_definitions_ordered[m_fields.size()]; + void* fieldbuf = malloc(def->info().size()); + def->info().construct(fieldbuf); + m_fields.push_back(fieldbuf); + } + return m_fields[index]; + } + + inline void deep_fields_copy(const dynamic_struct& other_const) { + // note: const cast should be safe here as we're not going to resize + // nor edit the dynamic fields allocated in "other" + auto& other = const_cast(other_const); + + // copy the definitions + set_dynamic_fields(other.dynamic_fields()); + + // deep copy of all the fields + destroy_dynamic_fields(); + for(size_t i = 0; i < other.m_fields.size(); i++) { + const auto info = m_dynamic_fields->m_definitions_ordered[i]; + // note: we use uintptr_t as it fits all the data types supported for + // reading and writing dynamic fields (e.g. uint32_t, uint64_t, const char*, + // base_table*, ...) + uintptr_t val = 0; + other.get_dynamic_field(*info, reinterpret_cast(&val)); + set_dynamic_field(*info, &val); + } + } + + std::vector m_fields; + std::shared_ptr m_dynamic_fields; }; - -}; // state -}; // libsinsp +}; // namespace state +}; // namespace libsinsp // specializations for string types -template<> inline void libsinsp::state::dynamic_struct::get_dynamic_field( - const field_accessor& a, const char*& out) -{ - _check_defsptr(a.info(), false); - get_dynamic_field(a.info(), reinterpret_cast(&out)); +template<> +inline void libsinsp::state::dynamic_struct::get_dynamic_field( + const field_accessor& a, + const char*& out) { + _check_defsptr(a.info(), false); + get_dynamic_field(a.info(), reinterpret_cast(&out)); } -template<> inline void libsinsp::state::dynamic_struct::get_dynamic_field( - const field_accessor& a, std::string& out) -{ - const char* s = NULL; - get_dynamic_field(a, s); - if (!s) - { - out.clear(); - } - else - { - out = s; - } +template<> +inline void libsinsp::state::dynamic_struct::get_dynamic_field( + const field_accessor& a, + std::string& out) { + const char* s = NULL; + get_dynamic_field(a, s); + if(!s) { + out.clear(); + } else { + out = s; + } } -template <> inline void libsinsp::state::dynamic_struct::set_dynamic_field( - const field_accessor& a, const char* const& in) -{ - _check_defsptr(a.info(), true); - set_dynamic_field(a.info(), reinterpret_cast(&in)); +template<> +inline void libsinsp::state::dynamic_struct::set_dynamic_field( + const field_accessor& a, + const char* const& in) { + _check_defsptr(a.info(), true); + set_dynamic_field(a.info(), reinterpret_cast(&in)); } -template <> inline void libsinsp::state::dynamic_struct::set_dynamic_field( - const field_accessor& a, const std::string& in) -{ - set_dynamic_field(a, in.c_str()); +template<> +inline void libsinsp::state::dynamic_struct::set_dynamic_field( + const field_accessor& a, + const std::string& in) { + set_dynamic_field(a, in.c_str()); } diff --git a/userspace/libsinsp/state/static_struct.h b/userspace/libsinsp/state/static_struct.h index 0b62563b19..90947c6ba1 100644 --- a/userspace/libsinsp/state/static_struct.h +++ b/userspace/libsinsp/state/static_struct.h @@ -32,244 +32,215 @@ namespace state { * The structure of the class is predetermined at compile-time and its fields * are placed at a given offset within the class memory area. */ -class static_struct -{ +class static_struct { public: - template class field_accessor; - - /** - * @brief Info about a given field in a static struct. - */ - class field_info - { - public: - inline field_info(): - m_readonly(true), - m_offset((size_t) -1), - m_name(""), - m_info(typeinfo::of()) {} - inline ~field_info() = default; - inline field_info(field_info&&) = default; - inline field_info& operator = (field_info&&) = default; - inline field_info(const field_info& s) = default; - inline field_info& operator = (const field_info& s) = default; - - friend inline bool operator==(const field_info& a, const field_info& b) - { - return a.info() == b.info() - && a.name() == b.name() - && a.readonly() == b.readonly() - && a.m_offset == b.m_offset; - }; - - friend inline bool operator!=(const field_info& a, const field_info& b) - { - return !(a == b); - }; - - /** - * @brief Returns true if the field info is valid. - */ - inline bool valid() const - { - return m_offset != (size_t) -1; - } - - /** - * @brief Returns true if the field is read only. - */ - inline bool readonly() const - { - return m_readonly; - } - - /** - * @brief Returns the name of the field. - */ - inline const std::string& name() const - { - return m_name; - } - - /** - * @brief Returns the type info of the field. - */ - inline const libsinsp::state::typeinfo& info() const - { - return m_info; - } - - /** - * @brief Returns a strongly-typed accessor for the given field, - * that can be used to reading and writing the field's value in - * all instances of structs where it is defined. - */ - template - inline field_accessor new_accessor() const - { - if (!valid()) - { - throw sinsp_exception("can't create static struct field accessor for invalid field"); - } - auto t = libsinsp::state::typeinfo::of(); - if (m_info != t) - { - throw sinsp_exception( - "incompatible type for static struct field accessor: field=" + m_name - + ", expected_type=" + t.name() + ", actual_type=" + m_info.name()); - } - return field_accessor(*this); - } - - private: - inline field_info(const std::string& n, size_t o, const typeinfo& i, bool r) - : m_readonly(r), - m_offset(o), - m_name(n), - m_info(i) { } - - template - static inline field_info _build(const std::string& name, size_t offset, bool readonly=false) - { - return field_info(name, offset, libsinsp::state::typeinfo::of(), readonly); - } - - bool m_readonly; - size_t m_offset; - std::string m_name; - libsinsp::state::typeinfo m_info; - - friend class static_struct; - }; - - /** - * @brief An strongly-typed accessor for accessing a field of a static struct. - * @tparam T Type of the field. - */ - template - class field_accessor - { - public: - inline field_accessor() = default; - inline ~field_accessor() = default; - inline field_accessor(field_accessor&&) = default; - inline field_accessor& operator = (field_accessor&&) = default; - inline field_accessor(const field_accessor& s) = default; - inline field_accessor& operator = (const field_accessor& s) = default; - - /** - * @brief Returns the info about the field to which this accessor is tied. - */ - inline const field_info& info() const - { - return m_info; - } - - private: - field_accessor(const field_info& info): m_info(info) { }; - - field_info m_info; - - friend class static_struct; - friend class static_struct::field_info; - }; - - /** - * @brief A group of field infos, describing all the ones available - * in a static struct. - */ - using field_infos = std::unordered_map; - - inline static_struct() = default; - inline virtual ~static_struct() = default; - inline static_struct(static_struct&&) = default; - inline static_struct& operator = (static_struct&&) = default; - inline static_struct(const static_struct& s) = default; - inline static_struct& operator = (const static_struct& s) = default; - - /** - * @brief Accesses a field with the given accessor and reads its value. - */ - template - inline const T& get_static_field(const field_accessor& a) const - { - if (!a.info().valid()) - { - throw sinsp_exception("can't get invalid field in static struct"); - } - return *(reinterpret_cast((void*) (((uintptr_t) this) + a.info().m_offset))); - } - - /** - * @brief Accesses a field with the given accessor and reads its value. - */ - template - inline void get_static_field(const field_accessor& a, Val& out) const - { - out = get_static_field(a); - } - - /** - * @brief Accesses a field with the given accessor and writes its value. - * An exception is thrown if the field is read-only. - */ - template - inline void set_static_field(const field_accessor& a, const Val& in) - { - if (!a.info().valid()) - { - throw sinsp_exception("can't set invalid field in static struct"); - } - if (a.info().readonly()) - { - throw sinsp_exception("can't set a read-only static struct field: " + a.info().name()); - } - *(reinterpret_cast((void*) (((uintptr_t) this) + a.info().m_offset))) = in; - } - - /** - * @brief Returns information about all the static fields accessible in a struct. - */ - virtual field_infos static_fields() const - { - return {}; - } + template + class field_accessor; + + /** + * @brief Info about a given field in a static struct. + */ + class field_info { + public: + inline field_info(): + m_readonly(true), + m_offset((size_t)-1), + m_name(""), + m_info(typeinfo::of()) {} + inline ~field_info() = default; + inline field_info(field_info&&) = default; + inline field_info& operator=(field_info&&) = default; + inline field_info(const field_info& s) = default; + inline field_info& operator=(const field_info& s) = default; + + friend inline bool operator==(const field_info& a, const field_info& b) { + return a.info() == b.info() && a.name() == b.name() && a.readonly() == b.readonly() && + a.m_offset == b.m_offset; + }; + + friend inline bool operator!=(const field_info& a, const field_info& b) { + return !(a == b); + }; + + /** + * @brief Returns true if the field info is valid. + */ + inline bool valid() const { return m_offset != (size_t)-1; } + + /** + * @brief Returns true if the field is read only. + */ + inline bool readonly() const { return m_readonly; } + + /** + * @brief Returns the name of the field. + */ + inline const std::string& name() const { return m_name; } + + /** + * @brief Returns the type info of the field. + */ + inline const libsinsp::state::typeinfo& info() const { return m_info; } + + /** + * @brief Returns a strongly-typed accessor for the given field, + * that can be used to reading and writing the field's value in + * all instances of structs where it is defined. + */ + template + inline field_accessor new_accessor() const { + if(!valid()) { + throw sinsp_exception( + "can't create static struct field accessor for invalid field"); + } + auto t = libsinsp::state::typeinfo::of(); + if(m_info != t) { + throw sinsp_exception( + "incompatible type for static struct field accessor: field=" + m_name + + ", expected_type=" + t.name() + ", actual_type=" + m_info.name()); + } + return field_accessor(*this); + } + + private: + inline field_info(const std::string& n, size_t o, const typeinfo& i, bool r): + m_readonly(r), + m_offset(o), + m_name(n), + m_info(i) {} + + template + static inline field_info _build(const std::string& name, + size_t offset, + bool readonly = false) { + return field_info(name, offset, libsinsp::state::typeinfo::of(), readonly); + } + + bool m_readonly; + size_t m_offset; + std::string m_name; + libsinsp::state::typeinfo m_info; + + friend class static_struct; + }; + + /** + * @brief An strongly-typed accessor for accessing a field of a static struct. + * @tparam T Type of the field. + */ + template + class field_accessor { + public: + inline field_accessor() = default; + inline ~field_accessor() = default; + inline field_accessor(field_accessor&&) = default; + inline field_accessor& operator=(field_accessor&&) = default; + inline field_accessor(const field_accessor& s) = default; + inline field_accessor& operator=(const field_accessor& s) = default; + + /** + * @brief Returns the info about the field to which this accessor is tied. + */ + inline const field_info& info() const { return m_info; } + + private: + field_accessor(const field_info& info): m_info(info) {}; + + field_info m_info; + + friend class static_struct; + friend class static_struct::field_info; + }; + + /** + * @brief A group of field infos, describing all the ones available + * in a static struct. + */ + using field_infos = std::unordered_map; + + inline static_struct() = default; + inline virtual ~static_struct() = default; + inline static_struct(static_struct&&) = default; + inline static_struct& operator=(static_struct&&) = default; + inline static_struct(const static_struct& s) = default; + inline static_struct& operator=(const static_struct& s) = default; + + /** + * @brief Accesses a field with the given accessor and reads its value. + */ + template + inline const T& get_static_field(const field_accessor& a) const { + if(!a.info().valid()) { + throw sinsp_exception("can't get invalid field in static struct"); + } + return *(reinterpret_cast((void*)(((uintptr_t)this) + a.info().m_offset))); + } + + /** + * @brief Accesses a field with the given accessor and reads its value. + */ + template + inline void get_static_field(const field_accessor& a, Val& out) const { + out = get_static_field(a); + } + + /** + * @brief Accesses a field with the given accessor and writes its value. + * An exception is thrown if the field is read-only. + */ + template + inline void set_static_field(const field_accessor& a, const Val& in) { + if(!a.info().valid()) { + throw sinsp_exception("can't set invalid field in static struct"); + } + if(a.info().readonly()) { + throw sinsp_exception("can't set a read-only static struct field: " + a.info().name()); + } + *(reinterpret_cast((void*)(((uintptr_t)this) + a.info().m_offset))) = in; + } + + /** + * @brief Returns information about all the static fields accessible in a struct. + */ + virtual field_infos static_fields() const { return {}; } protected: - /** - * @brief Defines the information about a field defined in the class or struct. - * An exception is thrown if two fields are defined with the same name. - * - * @tparam T Type of the field. - * @param thisptr "this" pointer of the struct containing the field, - * which is used to compute the field's memory offset in other instances - * of the same struct. - * @param v Reference to the field of which info is defined. - * @param name Display name of the field. - */ - template - inline const field_info& define_static_field(field_infos& fields, const void* thisptr, const T& v, const std::string& name, bool readonly=false) const - { - const auto &it = fields.find(name); - if (it != fields.end()) - { - throw sinsp_exception("multiple definitions of static field in struct: " + name); - } - - // todo(jasondellaluce): add extra safety boundary checks here - size_t offset = (size_t) (((uintptr_t) &v) - (uintptr_t) thisptr); - fields.insert({ name, field_info::_build(name, offset, readonly) }); - return fields.at(name); - } + /** + * @brief Defines the information about a field defined in the class or struct. + * An exception is thrown if two fields are defined with the same name. + * + * @tparam T Type of the field. + * @param thisptr "this" pointer of the struct containing the field, + * which is used to compute the field's memory offset in other instances + * of the same struct. + * @param v Reference to the field of which info is defined. + * @param name Display name of the field. + */ + template + inline const field_info& define_static_field(field_infos& fields, + const void* thisptr, + const T& v, + const std::string& name, + bool readonly = false) const { + const auto& it = fields.find(name); + if(it != fields.end()) { + throw sinsp_exception("multiple definitions of static field in struct: " + name); + } + + // todo(jasondellaluce): add extra safety boundary checks here + size_t offset = (size_t)(((uintptr_t)&v) - (uintptr_t)thisptr); + fields.insert({name, field_info::_build(name, offset, readonly)}); + return fields.at(name); + } }; - -}; // state -}; // libsinsp +}; // namespace state +}; // namespace libsinsp // specializations for strings -template <> inline void libsinsp::state::static_struct::get_static_field( - const field_accessor& a, const char*& out) const -{ - out = get_static_field(a).c_str(); +template<> +inline void libsinsp::state::static_struct::get_static_field( + const field_accessor& a, + const char*& out) const { + out = get_static_field(a).c_str(); } diff --git a/userspace/libsinsp/state/table.h b/userspace/libsinsp/state/table.h index 8c13f78c0d..dd7a3bc1ac 100644 --- a/userspace/libsinsp/state/table.h +++ b/userspace/libsinsp/state/table.h @@ -28,203 +28,183 @@ namespace state { /** * @brief Base class for entries of a state table. */ -struct table_entry: public static_struct, dynamic_struct -{ - table_entry(const std::shared_ptr& dyn_fields) - : static_struct(), dynamic_struct(dyn_fields) { } - virtual ~table_entry() = default; - table_entry(table_entry&&) = default; - table_entry& operator = (table_entry&&) = default; - table_entry(const table_entry& s) = default; - table_entry& operator = (const table_entry& s) = default; +struct table_entry : public static_struct, dynamic_struct { + table_entry(const std::shared_ptr& dyn_fields): + static_struct(), + dynamic_struct(dyn_fields) {} + virtual ~table_entry() = default; + table_entry(table_entry&&) = default; + table_entry& operator=(table_entry&&) = default; + table_entry(const table_entry& s) = default; + table_entry& operator=(const table_entry& s) = default; }; /** * @brief Base non-templated interface for state tables, defining * type-independent properties common to all tables. */ -class base_table -{ +class base_table { public: - inline base_table( - const std::string& name, - const typeinfo& key_info, - const static_struct::field_infos* static_fields) - : m_this_ptr(this), - m_name(name), - m_key_info(key_info), - m_static_fields(static_fields), - m_dynamic_fields(std::make_shared()) { } - - virtual ~base_table() = default; - inline base_table(base_table&&) = default; - inline base_table& operator = (base_table&&) = default; - inline base_table(const base_table& s) = delete; - inline base_table& operator = (const base_table& s) = delete; - - /** - * @brief Returns a pointer to the area of memory in which this table - * object is allocated. Here for convenience as required in other code parts. - */ - inline const base_table* const& table_ptr() const - { - return m_this_ptr; - } - - /** - * @brief Returns the name of the table. - */ - inline const std::string& name() const - { - return m_name; - } - - /** - * @brief Returns the non-null type info about the table's key. - */ - inline const typeinfo& key_info() const - { - return m_key_info; - } - - /** - * @brief Returns the fields metadata list for the static fields defined - * for the value data type of this table. This fields will be accessible - * for all the entries of this table. - */ - virtual const static_struct::field_infos* static_fields() const - { - return m_static_fields; - } - - /** - * @brief Returns the fields metadata list for the dynamic fields defined - * for the value data type of this table. This fields will be accessible - * for all the entries of this table. The returned metadata list can - * be expended at runtime by adding new dynamic fields, which will then - * be allocated and accessible for all the present and future entries - * present in the table. - */ - virtual const std::shared_ptr& dynamic_fields() const - { - return m_dynamic_fields; - } - - virtual void set_dynamic_fields(const std::shared_ptr& dynf) - { - if (m_dynamic_fields.get() == dynf.get()) - { - return; - } - if (!dynf) - { - throw sinsp_exception("null definitions passed to set_dynamic_fields"); - } - if (m_dynamic_fields && m_dynamic_fields.use_count() > 1) - { - throw sinsp_exception("can't replace already in-use dynamic fields table definitions"); - } - m_dynamic_fields = dynf; - } - - /** - * @brief Returns the number of entries present in the table. - */ - virtual size_t entries_count() const = 0; - - /** - * @brief Erase all the entries present in the table. - * After invoking this function, entries_count() will return true. - */ - virtual void clear_entries() = 0; - - /** - * @brief Allocates and returns a new entry for the table. This is just - * a factory method, the entry will not automatically added to the table. - * Once a new entry is allocated with this method, users must invoke - * add_entry() in order to actually insert it in the table. - */ - virtual std::unique_ptr new_entry() const = 0; - - /** - * @brief Iterates over all the entries contained in the table and invokes - * the given predicate for each of them. - * - * @param pred The predicate to invoke for all the table's entries. The - * predicate returns true if the iteration can proceed to the next entry, - * and false if the iteration needs to break out. - * @return true If the iteration proceeded successfully for all the entries. - * @return false If the iteration broke out. - */ - virtual bool foreach_entry(std::function pred) = 0; + inline base_table(const std::string& name, + const typeinfo& key_info, + const static_struct::field_infos* static_fields): + m_this_ptr(this), + m_name(name), + m_key_info(key_info), + m_static_fields(static_fields), + m_dynamic_fields(std::make_shared()) {} + + virtual ~base_table() = default; + inline base_table(base_table&&) = default; + inline base_table& operator=(base_table&&) = default; + inline base_table(const base_table& s) = delete; + inline base_table& operator=(const base_table& s) = delete; + + /** + * @brief Returns a pointer to the area of memory in which this table + * object is allocated. Here for convenience as required in other code parts. + */ + inline const base_table* const& table_ptr() const { return m_this_ptr; } + + /** + * @brief Returns the name of the table. + */ + inline const std::string& name() const { return m_name; } + + /** + * @brief Returns the non-null type info about the table's key. + */ + inline const typeinfo& key_info() const { return m_key_info; } + + /** + * @brief Returns the fields metadata list for the static fields defined + * for the value data type of this table. This fields will be accessible + * for all the entries of this table. + */ + virtual const static_struct::field_infos* static_fields() const { return m_static_fields; } + + /** + * @brief Returns the fields metadata list for the dynamic fields defined + * for the value data type of this table. This fields will be accessible + * for all the entries of this table. The returned metadata list can + * be expended at runtime by adding new dynamic fields, which will then + * be allocated and accessible for all the present and future entries + * present in the table. + */ + virtual const std::shared_ptr& dynamic_fields() const { + return m_dynamic_fields; + } + + virtual void set_dynamic_fields(const std::shared_ptr& dynf) { + if(m_dynamic_fields.get() == dynf.get()) { + return; + } + if(!dynf) { + throw sinsp_exception("null definitions passed to set_dynamic_fields"); + } + if(m_dynamic_fields && m_dynamic_fields.use_count() > 1) { + throw sinsp_exception("can't replace already in-use dynamic fields table definitions"); + } + m_dynamic_fields = dynf; + } + + /** + * @brief Returns the number of entries present in the table. + */ + virtual size_t entries_count() const = 0; + + /** + * @brief Erase all the entries present in the table. + * After invoking this function, entries_count() will return true. + */ + virtual void clear_entries() = 0; + + /** + * @brief Allocates and returns a new entry for the table. This is just + * a factory method, the entry will not automatically added to the table. + * Once a new entry is allocated with this method, users must invoke + * add_entry() in order to actually insert it in the table. + */ + virtual std::unique_ptr new_entry() const = 0; + + /** + * @brief Iterates over all the entries contained in the table and invokes + * the given predicate for each of them. + * + * @param pred The predicate to invoke for all the table's entries. The + * predicate returns true if the iteration can proceed to the next entry, + * and false if the iteration needs to break out. + * @return true If the iteration proceeded successfully for all the entries. + * @return false If the iteration broke out. + */ + virtual bool foreach_entry(std::function pred) = 0; private: - const base_table* m_this_ptr; - std::string m_name; - typeinfo m_key_info; - const static_struct::field_infos* m_static_fields; - std::shared_ptr m_dynamic_fields; + const base_table* m_this_ptr; + std::string m_name; + typeinfo m_key_info; + const static_struct::field_infos* m_static_fields; + std::shared_ptr m_dynamic_fields; }; /** * @brief Base interfaces for state tables, with strong typing for tables' key. */ -template -class table: public base_table -{ - static_assert(std::is_default_constructible(), - "table key types must have a default constructor"); +template +class table : public base_table { + static_assert(std::is_default_constructible(), + "table key types must have a default constructor"); public: - inline table(const std::string& name, const static_struct::field_infos* static_fields) - : base_table(name, typeinfo::of(), static_fields) {} - inline table(const std::string& name): table(name, _static_fields()) {} - virtual ~table() = default; - inline table(table&&) = default; - inline table& operator = (table&&) = default; - inline table(const table& s) = delete; - inline table& operator = (const table& s) = delete; - - /** - * @brief Returns a pointer to an entry present in the table at the given - * key. The pointer is owned by the table, and will remain valid up until - * the table is destroyed or the entry is removed from the table. - * - * @param key Key of the entry to be retrieved. - * @return std::shared_ptr Pointer to the entry if - * present in the table at the given key, and nullptr otherwise. - */ - virtual std::shared_ptr get_entry(const KeyType& key) = 0; - - /** - * @brief Inserts a new entry in the table with the given key. If another - * entry is already present with the same key, it gets replaced. After - * insertion, table will be come the owner of the entry's pointer. - * - * @param key Key of the entry to be added. - * @param entry Entry to be added with the given key. - * @return std::shared_ptr Non-null pointer to the - * newly-added entry, which will remain valid up until the table is - * destroyed or the entry is removed from the table. - */ - virtual std::shared_ptr add_entry(const KeyType& key, std::unique_ptr entry) = 0; - - /** - * @brief Removes an entry from the table with the given key. - * - * @param key Key of the entry to be removed. - * @return true If an entry was present at the given key. - * @return false If an entry was not present at the given key. - */ - virtual bool erase_entry(const KeyType& key) = 0; + inline table(const std::string& name, const static_struct::field_infos* static_fields): + base_table(name, typeinfo::of(), static_fields) {} + inline table(const std::string& name): table(name, _static_fields()) {} + virtual ~table() = default; + inline table(table&&) = default; + inline table& operator=(table&&) = default; + inline table(const table& s) = delete; + inline table& operator=(const table& s) = delete; + + /** + * @brief Returns a pointer to an entry present in the table at the given + * key. The pointer is owned by the table, and will remain valid up until + * the table is destroyed or the entry is removed from the table. + * + * @param key Key of the entry to be retrieved. + * @return std::shared_ptr Pointer to the entry if + * present in the table at the given key, and nullptr otherwise. + */ + virtual std::shared_ptr get_entry(const KeyType& key) = 0; + + /** + * @brief Inserts a new entry in the table with the given key. If another + * entry is already present with the same key, it gets replaced. After + * insertion, table will be come the owner of the entry's pointer. + * + * @param key Key of the entry to be added. + * @param entry Entry to be added with the given key. + * @return std::shared_ptr Non-null pointer to the + * newly-added entry, which will remain valid up until the table is + * destroyed or the entry is removed from the table. + */ + virtual std::shared_ptr add_entry(const KeyType& key, + std::unique_ptr entry) = 0; + + /** + * @brief Removes an entry from the table with the given key. + * + * @param key Key of the entry to be removed. + * @return true If an entry was present at the given key. + * @return false If an entry was not present at the given key. + */ + virtual bool erase_entry(const KeyType& key) = 0; private: - static inline const static_struct::field_infos* _static_fields() - { + static inline const static_struct::field_infos* _static_fields() { static const static_struct::field_infos s_fields{}; return &s_fields; } }; -}; // state -}; // libsinsp +}; // namespace state +}; // namespace libsinsp diff --git a/userspace/libsinsp/state/table_adapters.h b/userspace/libsinsp/state/table_adapters.h index 0580166370..2b07ebf996 100644 --- a/userspace/libsinsp/state/table_adapters.h +++ b/userspace/libsinsp/state/table_adapters.h @@ -16,39 +16,33 @@ limitations under the License. #include -namespace libsinsp -{ -namespace state -{ +namespace libsinsp { +namespace state { /** * @brief A subclass of dynamic_struct::field_infos that have a fixed, * and immutable, list of dynamic field definitions all declared at * construction-time */ -class fixed_dynamic_fields_infos : public dynamic_struct::field_infos -{ +class fixed_dynamic_fields_infos : public dynamic_struct::field_infos { public: virtual ~fixed_dynamic_fields_infos() = default; inline fixed_dynamic_fields_infos(std::initializer_list infos): - field_infos(infos.begin()->defs_id()) - { + field_infos(infos.begin()->defs_id()) { auto defs_id = infos.begin()->defs_id(); - for(const auto& f : infos) - { - if(f.defs_id() != defs_id) - { + for(const auto& f : infos) { + if(f.defs_id() != defs_id) { throw sinsp_exception( - "inconsistent definition ID passed to fixed_dynamic_fields_infos"); + "inconsistent definition ID passed to fixed_dynamic_fields_infos"); } field_infos::add_field_info(f); } } protected: - const dynamic_struct::field_info& add_field_info(const dynamic_struct::field_info& field) override final - { + const dynamic_struct::field_info& add_field_info( + const dynamic_struct::field_info& field) override final { throw sinsp_exception("can't add field to fixed_dynamic_fields_infos: " + field.name()); } }; @@ -61,21 +55,19 @@ class fixed_dynamic_fields_infos : public dynamic_struct::field_infos * and make the wrapped value available as a single dynamic field. The dynamic * fields definitions of this wrapper are fixed and immutable. */ -template class value_table_entry_adapter : public libsinsp::state::table_entry -{ +template +class value_table_entry_adapter : public libsinsp::state::table_entry { public: // note: this dynamic definitions are fixed in size and structure, // so there's no need of worrying about specific identifier checks // as they should be safely interchangeable static const constexpr uintptr_t s_dynamic_fields_id = 1234; - struct dynamic_fields_t : public fixed_dynamic_fields_infos - { + struct dynamic_fields_t : public fixed_dynamic_fields_infos { using _dfi = dynamic_struct::field_info; - inline dynamic_fields_t(): fixed_dynamic_fields_infos({_dfi::build("value", 0, s_dynamic_fields_id)}) - { - } + inline dynamic_fields_t(): + fixed_dynamic_fields_infos({_dfi::build("value", 0, s_dynamic_fields_id)}) {} virtual ~dynamic_fields_t() = default; }; @@ -91,44 +83,34 @@ template class value_table_entry_adapter : public libsinsp::state::t inline void set_value(T* v) { m_value = v; } protected: - virtual void get_dynamic_field(const dynamic_struct::field_info& i, void* out) override final - { - if(i.index() != 0 || i.defs_id() != s_dynamic_fields_id) - { + virtual void get_dynamic_field(const dynamic_struct::field_info& i, void* out) override final { + if(i.index() != 0 || i.defs_id() != s_dynamic_fields_id) { throw sinsp_exception( - "invalid field info passed to value_table_entry_adapter::get_dynamic_field"); + "invalid field info passed to value_table_entry_adapter::get_dynamic_field"); } - if(i.info().index() == typeinfo::index_t::TI_STRING) - { + if(i.info().index() == typeinfo::index_t::TI_STRING) { *((const char**)out) = ((const std::string*)m_value)->c_str(); - } - else - { + } else { memcpy(out, (const void*)m_value, i.info().size()); } } - virtual void set_dynamic_field(const dynamic_struct::field_info& i, const void* in) override final - { - if(i.index() != 0 || i.defs_id() != s_dynamic_fields_id) - { + virtual void set_dynamic_field(const dynamic_struct::field_info& i, + const void* in) override final { + if(i.index() != 0 || i.defs_id() != s_dynamic_fields_id) { throw sinsp_exception( - "invalid field info passed to value_table_entry_adapter::set_dynamic_field"); + "invalid field info passed to value_table_entry_adapter::set_dynamic_field"); } - if(i.info().index() == typeinfo::index_t::TI_STRING) - { + if(i.info().index() == typeinfo::index_t::TI_STRING) { *((std::string*)m_value) = *((const char**)in); - } - else - { + } else { memcpy((void*)m_value, in, i.info().size()); } } - virtual void destroy_dynamic_fields() override final - { + virtual void destroy_dynamic_fields() override final { // nothing to do } @@ -146,14 +128,14 @@ template class value_table_entry_adapter : public libsinsp::state::t * be extra careful when performing addition or deletion operations, as that * can lead to expensive sparse array operations or results. */ -template, - typename DynFields = typename TWrap::dynamic_fields_t> -class stl_container_table_adapter : public libsinsp::state::table -{ +template, + typename DynFields = typename TWrap::dynamic_fields_t> +class stl_container_table_adapter : public libsinsp::state::table { public: stl_container_table_adapter(const std::string& name, T& container): - table(name, _static_fields()), m_container(container) - { + table(name, _static_fields()), + m_container(container) { set_dynamic_fields(std::make_shared()); } @@ -163,67 +145,57 @@ class stl_container_table_adapter : public libsinsp::state::table void clear_entries() override { m_container.clear(); } - std::unique_ptr new_entry() const override - { + std::unique_ptr new_entry() const override { auto ret = std::make_unique(); ret->set_dynamic_fields(this->dynamic_fields()); return ret; } - bool foreach_entry(std::function pred) override - { + bool foreach_entry(std::function pred) override { TWrap w; w.set_dynamic_fields(this->dynamic_fields()); - for(auto& v : m_container) - { + for(auto& v : m_container) { w.set_value(&v); - if(!pred(w)) - { + if(!pred(w)) { return false; } } return true; } - std::shared_ptr get_entry(const uint64_t& key) override - { - if(key >= m_container.size()) - { + std::shared_ptr get_entry(const uint64_t& key) override { + if(key >= m_container.size()) { return nullptr; } return wrap_value(&m_container[key]); } - std::shared_ptr - add_entry(const uint64_t& key, std::unique_ptr entry) override - { - if(!entry) - { + std::shared_ptr add_entry( + const uint64_t& key, + std::unique_ptr entry) override { + if(!entry) { throw sinsp_exception("null entry added to table: " + this->name()); } - if(entry->dynamic_fields() != this->dynamic_fields()) - { - throw sinsp_exception("entry with mismatching dynamic fields added to table: " + this->name()); + if(entry->dynamic_fields() != this->dynamic_fields()) { + throw sinsp_exception("entry with mismatching dynamic fields added to table: " + + this->name()); } auto value = dynamic_cast(entry.get()); - if(!value) - { + if(!value) { throw sinsp_exception("entry with mismatching type added to table: " + this->name()); } - if(value->value() != nullptr) - { - throw sinsp_exception("entry with unexpected owned value added to table: " + this->name()); + if(value->value() != nullptr) { + throw sinsp_exception("entry with unexpected owned value added to table: " + + this->name()); } m_container.resize(key + 1); return wrap_value(&m_container[key]); } - bool erase_entry(const uint64_t& key) override - { - if(key >= m_container.size()) - { + bool erase_entry(const uint64_t& key) override { + if(key >= m_container.size()) { return false; } m_container.erase(m_container.begin() + key); @@ -231,8 +203,7 @@ class stl_container_table_adapter : public libsinsp::state::table } private: - static inline const static_struct::field_infos* _static_fields() - { + static inline const static_struct::field_infos* _static_fields() { static const auto s_fields = TWrap{}.static_fields(); return &s_fields; } @@ -242,12 +213,9 @@ class stl_container_table_adapter : public libsinsp::state::table // helps us dynamically allocate a batch of wrappers, creating new ones // only if we need them. Wrappers are reused for multiple entries, and // we leverage shared_ptrs to automatically release them once not anymore used - inline std::shared_ptr wrap_value(typename T::value_type* v) - { - for(auto& w : m_wrappers) - { - if(w.value() == nullptr) - { + inline std::shared_ptr wrap_value(typename T::value_type* v) { + for(auto& w : m_wrappers) { + if(w.value() == nullptr) { w.set_value(v); return std::shared_ptr(&w, wrap_deleter); } @@ -261,8 +229,8 @@ class stl_container_table_adapter : public libsinsp::state::table } T& m_container; - std::list m_wrappers; // using lists for ptr stability + std::list m_wrappers; // using lists for ptr stability }; -}; // namespace state -}; // namespace libsinsp +}; // namespace state +}; // namespace libsinsp diff --git a/userspace/libsinsp/state/table_registry.h b/userspace/libsinsp/state/table_registry.h index 89d1d56825..0a9b6f5664 100644 --- a/userspace/libsinsp/state/table_registry.h +++ b/userspace/libsinsp/state/table_registry.h @@ -22,98 +22,86 @@ limitations under the License. namespace libsinsp { namespace state { - /** * @brief A registry for the available state tables. Table owners can register * their tables and make them available for discovery and retrieval by other * components. - * + * * @note The lifeto,e of the tables registered in the registry is regulated * by the owner of each tables. This means that a table pointer obtained * through get_table() will remain valid and available up until the owner * destroys the table. For example, in the case of an inspector's own tables - * the lifetime of the tables will be the same as the one of the inspector. - * + * the lifetime of the tables will be the same as the one of the inspector. + * * todo(jasondellaluce): switch from raw ptrs to shared ptrs, but the * current libsinsp implementation does not allow us to */ -class table_registry -{ +class table_registry { public: - table_registry() = default; - ~table_registry() = default; - table_registry(table_registry&&) = default; - table_registry& operator = (table_registry&&) = default; - table_registry(const table_registry& s) = delete; - table_registry& operator = (const table_registry& s) = delete; + table_registry() = default; + ~table_registry() = default; + table_registry(table_registry&&) = default; + table_registry& operator=(table_registry&&) = default; + table_registry(const table_registry& s) = delete; + table_registry& operator=(const table_registry& s) = delete; - /** - * @brief Obtain a pointer to a table registered in the registry with - * the given name. Throws an exception if a table with the given name - * is defined with types incompatible with the ones provided in the - * template. - * - * @tparam KeyType Type of the table's key. - * @param name Name of the table. - * @return table* Pointer to the registered table, - * or nullptr if no table is registered by the given name. - */ - template - table* get_table(const std::string& name) const - { - const auto &it = m_tables.find(name); - if (it != m_tables.end()) - { - auto t = libsinsp::state::typeinfo::of(); - if (it->second->key_info() != t) - { - throw sinsp_exception( - "table in registry accessed with wrong key type: table='" + name - + "', requested='" + t.name() + "', actual='" - + it->second->key_info().name() + "'"); - } - return static_cast*>(it->second); - } - return nullptr; - } + /** + * @brief Obtain a pointer to a table registered in the registry with + * the given name. Throws an exception if a table with the given name + * is defined with types incompatible with the ones provided in the + * template. + * + * @tparam KeyType Type of the table's key. + * @param name Name of the table. + * @return table* Pointer to the registered table, + * or nullptr if no table is registered by the given name. + */ + template + table* get_table(const std::string& name) const { + const auto& it = m_tables.find(name); + if(it != m_tables.end()) { + auto t = libsinsp::state::typeinfo::of(); + if(it->second->key_info() != t) { + throw sinsp_exception("table in registry accessed with wrong key type: table='" + + name + "', requested='" + t.name() + "', actual='" + + it->second->key_info().name() + "'"); + } + return static_cast*>(it->second); + } + return nullptr; + } - /** - * @brief Registers a table in the registry with a given name and - * returns a pointer to the table. Throws an exception if a table is - * already present with the given name. - * - * @tparam KeyType Type of the table's key. - * @param name Name of the table. - * @param t Pointer to the table. - * @return table* Pointer to the newly-registered table. - */ - template - table* add_table(table* t) - { - if (!t) - { - throw sinsp_exception("null table added to registry"); - } - const auto &it = m_tables.find(t->name()); - if (it != m_tables.end()) - { - throw sinsp_exception("table added to registry multiple times: " + t->name()); - } - m_tables.insert({ t->name(), t }); - return t; - } + /** + * @brief Registers a table in the registry with a given name and + * returns a pointer to the table. Throws an exception if a table is + * already present with the given name. + * + * @tparam KeyType Type of the table's key. + * @param name Name of the table. + * @param t Pointer to the table. + * @return table* Pointer to the newly-registered table. + */ + template + table* add_table(table* t) { + if(!t) { + throw sinsp_exception("null table added to registry"); + } + const auto& it = m_tables.find(t->name()); + if(it != m_tables.end()) { + throw sinsp_exception("table added to registry multiple times: " + t->name()); + } + m_tables.insert({t->name(), t}); + return t; + } - /** - * @brief Returns all the tables known in the registry. - */ - const std::unordered_map& tables() const - { - return m_tables; - } + /** + * @brief Returns all the tables known in the registry. + */ + const std::unordered_map& tables() const { return m_tables; } private: - std::unordered_map m_tables; + std::unordered_map m_tables; }; -}; // state -}; // libsinsp +}; // namespace state +}; // namespace libsinsp diff --git a/userspace/libsinsp/state/type_info.h b/userspace/libsinsp/state/type_info.h index 8bc999c054..80c87945ad 100644 --- a/userspace/libsinsp/state/type_info.h +++ b/userspace/libsinsp/state/type_info.h @@ -34,138 +34,166 @@ namespace state { * also provides construction and destruction utilities for each supported * types for convenience. */ -class typeinfo -{ +class typeinfo { public: - /** - * @brief Numeric identifier of a supported type. - */ - enum index_t: uint8_t - { - TI_INT8 = 1, - TI_INT16 = 2, - TI_INT32 = 3, - TI_INT64 = 4, - TI_UINT8 = 5, - TI_UINT16 = 6, - TI_UINT32 = 7, - TI_UINT64 = 8, - TI_STRING = 9, - TI_TABLE = 10, - // note(jasondellaluce): weird value due to plugin API backward compatibility - TI_BOOL = 25, - }; - - /** - * @brief Returns a type info for the type T. - */ - template static inline typeinfo of() - { - throw sinsp_exception("state::typeinfo::of invoked for unsupported type: " + std::string(typeid(T).name())); - } - - inline typeinfo() = delete; - inline ~typeinfo() = default; - inline typeinfo(typeinfo&&) = default; - inline typeinfo& operator = (typeinfo&&) = default; - inline typeinfo(const typeinfo& s) = default; - inline typeinfo& operator = (const typeinfo& s) = default; - - friend inline bool operator==(const typeinfo& a, const typeinfo& b) - { - return a.index() == b.index(); - }; - - friend inline bool operator!=(const typeinfo& a, const typeinfo& b) - { - return a.index() != b.index(); - }; - - /** - * @brief Returns the name of the type. - */ - inline const char* name() const - { - return m_name; - } - - /** - * @brief Returns the numeric representation of the type. - */ - inline index_t index() const - { - return m_index; - } - - /** - * @brief Returns the byte size of variables of the given type. - */ - inline size_t size() const - { - return m_size; - } - - /** - * @brief Constructs and initializes the given type in the passed-in - * memory location, which is expected to be larger or equal than size(). - */ - inline void construct(void* p) const noexcept - { - if (p && m_construct) m_construct(p); - } - - /** - * @brief Destructs and deinitializes the given type in the passed-in - * memory location, which is expected to be larger or equal than size(). - */ - inline void destroy(void* p) const noexcept - { - if (p && m_destroy) m_destroy(p); - } + /** + * @brief Numeric identifier of a supported type. + */ + enum index_t : uint8_t { + TI_INT8 = 1, + TI_INT16 = 2, + TI_INT32 = 3, + TI_INT64 = 4, + TI_UINT8 = 5, + TI_UINT16 = 6, + TI_UINT32 = 7, + TI_UINT64 = 8, + TI_STRING = 9, + TI_TABLE = 10, + // note(jasondellaluce): weird value due to plugin API backward compatibility + TI_BOOL = 25, + }; + + /** + * @brief Returns a type info for the type T. + */ + template + static inline typeinfo of() { + throw sinsp_exception("state::typeinfo::of invoked for unsupported type: " + + std::string(typeid(T).name())); + } + + inline typeinfo() = delete; + inline ~typeinfo() = default; + inline typeinfo(typeinfo&&) = default; + inline typeinfo& operator=(typeinfo&&) = default; + inline typeinfo(const typeinfo& s) = default; + inline typeinfo& operator=(const typeinfo& s) = default; + + friend inline bool operator==(const typeinfo& a, const typeinfo& b) { + return a.index() == b.index(); + }; + + friend inline bool operator!=(const typeinfo& a, const typeinfo& b) { + return a.index() != b.index(); + }; + + /** + * @brief Returns the name of the type. + */ + inline const char* name() const { return m_name; } + + /** + * @brief Returns the numeric representation of the type. + */ + inline index_t index() const { return m_index; } + + /** + * @brief Returns the byte size of variables of the given type. + */ + inline size_t size() const { return m_size; } + + /** + * @brief Constructs and initializes the given type in the passed-in + * memory location, which is expected to be larger or equal than size(). + */ + inline void construct(void* p) const noexcept { + if(p && m_construct) + m_construct(p); + } + + /** + * @brief Destructs and deinitializes the given type in the passed-in + * memory location, which is expected to be larger or equal than size(). + */ + inline void destroy(void* p) const noexcept { + if(p && m_destroy) + m_destroy(p); + } private: - inline typeinfo(const char* n, index_t k, size_t s, void (*c)(void*), void (*d)(void*)) - : m_name(n), m_index(k), m_size(s), m_construct(c), m_destroy(d) { } - - template > static inline void _construct(void* p) - { - _Alloc a; - std::allocator_traits<_Alloc>::construct(a, reinterpret_cast(p)); - } - - template > static inline void _destroy(void* p) - { - _Alloc a; - std::allocator_traits<_Alloc>::destroy(a, reinterpret_cast(p)); - } - - template static inline typeinfo _build(const char* n, index_t k) - { - return typeinfo(n, k, sizeof(T), _construct, _destroy); - } - - const char* m_name; - index_t m_index; - size_t m_size; - void (*m_construct)(void*); - void (*m_destroy)(void*); + inline typeinfo(const char* n, index_t k, size_t s, void (*c)(void*), void (*d)(void*)): + m_name(n), + m_index(k), + m_size(s), + m_construct(c), + m_destroy(d) {} + + template> + static inline void _construct(void* p) { + _Alloc a; + std::allocator_traits<_Alloc>::construct(a, reinterpret_cast(p)); + } + + template> + static inline void _destroy(void* p) { + _Alloc a; + std::allocator_traits<_Alloc>::destroy(a, reinterpret_cast(p)); + } + + template + static inline typeinfo _build(const char* n, index_t k) { + return typeinfo(n, k, sizeof(T), _construct, _destroy); + } + + const char* m_name; + index_t m_index; + size_t m_size; + void (*m_construct)(void*); + void (*m_destroy)(void*); }; class base_table; // below is the manually-controlled list of all the supported types -template<> inline typeinfo typeinfo::of() { return _build("bool", TI_BOOL); } -template<> inline typeinfo typeinfo::of() { return _build("int8", TI_INT8); } -template<> inline typeinfo typeinfo::of() { return _build("int16", TI_INT16); } -template<> inline typeinfo typeinfo::of() { return _build("int32", TI_INT32); } -template<> inline typeinfo typeinfo::of() { return _build("int64", TI_INT64); } -template<> inline typeinfo typeinfo::of() { return _build("uint8", TI_UINT8); } -template<> inline typeinfo typeinfo::of() { return _build("uint16", TI_UINT16); } -template<> inline typeinfo typeinfo::of() { return _build("uint32", TI_UINT32); } -template<> inline typeinfo typeinfo::of() { return _build("uint64", TI_UINT64); } -template<> inline typeinfo typeinfo::of() { return _build("string", TI_STRING); } -template<> inline typeinfo typeinfo::of() { return _build("table", TI_TABLE); } -template<> inline typeinfo typeinfo::of() { return _build("table", TI_TABLE); } - -}; // state -}; // libsinsp +template<> +inline typeinfo typeinfo::of() { + return _build("bool", TI_BOOL); +} +template<> +inline typeinfo typeinfo::of() { + return _build("int8", TI_INT8); +} +template<> +inline typeinfo typeinfo::of() { + return _build("int16", TI_INT16); +} +template<> +inline typeinfo typeinfo::of() { + return _build("int32", TI_INT32); +} +template<> +inline typeinfo typeinfo::of() { + return _build("int64", TI_INT64); +} +template<> +inline typeinfo typeinfo::of() { + return _build("uint8", TI_UINT8); +} +template<> +inline typeinfo typeinfo::of() { + return _build("uint16", TI_UINT16); +} +template<> +inline typeinfo typeinfo::of() { + return _build("uint32", TI_UINT32); +} +template<> +inline typeinfo typeinfo::of() { + return _build("uint64", TI_UINT64); +} +template<> +inline typeinfo typeinfo::of() { + return _build("string", TI_STRING); +} +template<> +inline typeinfo typeinfo::of() { + return _build("table", TI_TABLE); +} +template<> +inline typeinfo typeinfo::of() { + return _build("table", TI_TABLE); +} + +}; // namespace state +}; // namespace libsinsp diff --git a/userspace/libsinsp/test/CMakeLists.txt b/userspace/libsinsp/test/CMakeLists.txt index 132165c938..44e50efa2f 100644 --- a/userspace/libsinsp/test/CMakeLists.txt +++ b/userspace/libsinsp/test/CMakeLists.txt @@ -2,21 +2,19 @@ # # Copyright (C) 2023 The Falco Authors. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. # include(jsoncpp) -if (NOT EMSCRIPTEN) +if(NOT EMSCRIPTEN) include(tbb) endif() if(NOT MINIMAL_BUILD AND NOT EMSCRIPTEN) @@ -26,15 +24,17 @@ endif() # MINIMAL_BUILD include(zlib) if(WIN32) - set(CMAKE_CXX_FLAGS "-D_CRT_SECURE_NO_WARNINGS -DWIN32 -DMINIMAL_BUILD /EHsc /W3 /Zi /std:c++17") + set(CMAKE_CXX_FLAGS + "-D_CRT_SECURE_NO_WARNINGS -DWIN32 -DMINIMAL_BUILD /EHsc /W3 /Zi /std:c++17" + ) set(CMAKE_CXX_FLAGS_DEBUG ${FALCOSECURITY_LIBS_DEBUG_FLAGS}) set(CMAKE_CXX_STANDARD 17) endif() # Create a libsinsp_test_var.h file with some variables used by our tests -configure_file ( - "${CMAKE_CURRENT_SOURCE_DIR}/libsinsp_test_var.h.in" - "${CMAKE_CURRENT_BINARY_DIR}/libsinsp_test_var.h" +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/libsinsp_test_var.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/libsinsp_test_var.h" ) file(GLOB_RECURSE TEST_PLUGINS ${CMAKE_CURRENT_SOURCE_DIR}/plugins/*.cpp) @@ -46,7 +46,9 @@ if(NOT WIN32) file(GLOB_RECURSE SINSP_FILTERCHECKS_SUITE ${CMAKE_CURRENT_SOURCE_DIR}/filterchecks/*.cpp) - file(GLOB_RECURSE SINSP_CONTAINER_ENGINE_SUITE ${CMAKE_CURRENT_SOURCE_DIR}/container_engine/*.cpp) + file(GLOB_RECURSE SINSP_CONTAINER_ENGINE_SUITE + ${CMAKE_CURRENT_SOURCE_DIR}/container_engine/*.cpp + ) endif() option(SCAP_FILES_SUITE_ENABLE "Enable scap-file tests in sinsp" "ON") @@ -55,22 +57,15 @@ if((NOT ${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "s390x") AND ${SCAP_FILES_SUITE_ # Binary dir in which we will save all our Cmake files file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/scap_files") # Add here the name for new scap-files - set(SCAP_FILE_NAMES - "kexec_arm64.scap" - "kexec_x86.scap" - "sample.scap" - ) - set(SCAP_FILE_DOWNLOAD_PREFIX - "https://download.falco.org/fixtures/libs/scap_files" - ) + set(SCAP_FILE_NAMES "kexec_arm64.scap" "kexec_x86.scap" "sample.scap") + set(SCAP_FILE_DOWNLOAD_PREFIX "https://download.falco.org/fixtures/libs/scap_files") message(STATUS "Download all scap-files from: ${SCAP_FILE_DOWNLOAD_PREFIX}") foreach(FILE_NAME ${SCAP_FILE_NAMES}) message(STATUS "Downloading scap-file: ${SCAP_FILE_DOWNLOAD_PREFIX}/${FILE_NAME}") if(NOT EXISTS "${CMAKE_BINARY_DIR}/scap_files/${FILE_NAME}") - file(DOWNLOAD - "${SCAP_FILE_DOWNLOAD_PREFIX}/${FILE_NAME}" - "${CMAKE_BINARY_DIR}/scap_files/${FILE_NAME}" - SHOW_PROGRESS) + file(DOWNLOAD "${SCAP_FILE_DOWNLOAD_PREFIX}/${FILE_NAME}" + "${CMAKE_BINARY_DIR}/scap_files/${FILE_NAME}" SHOW_PROGRESS + ) else() message(STATUS "Skipping download, file already present") endif() @@ -134,7 +129,9 @@ set(LIBSINSP_UNIT_TESTS_SOURCES ) if(WIN32) - list(REMOVE_ITEM LIBSINSP_UNIT_TESTS_SOURCES + list( + REMOVE_ITEM + LIBSINSP_UNIT_TESTS_SOURCES events_file.ut.cpp events_fspath.ut.cpp events_net.ut.cpp @@ -146,10 +143,8 @@ if(WIN32) public_sinsp_API/sinsp_logger.cpp ) elseif(APPLE OR EMSCRIPTEN) - list(REMOVE_ITEM LIBSINSP_UNIT_TESTS_SOURCES - events_net.ut.cpp - filter_op_net_compare.ut.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/parsers/parse_connect.cpp + list(REMOVE_ITEM LIBSINSP_UNIT_TESTS_SOURCES events_net.ut.cpp filter_op_net_compare.ut.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/parsers/parse_connect.cpp ) endif() @@ -157,17 +152,20 @@ if(NOT MINIMAL_BUILD) list(APPEND LIBSINSP_UNIT_TESTS_SOURCES procfs_utils.ut.cpp) endif() -if (CMAKE_SYSTEM_NAME MATCHES "Linux") - list(APPEND LIBSINSP_UNIT_TESTS_SOURCES +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + list( + APPEND + LIBSINSP_UNIT_TESTS_SOURCES async_key_value_source.ut.cpp filter_ppm_codes.ut.cpp public_sinsp_API/events_set.cpp public_sinsp_API/interesting_syscalls.cpp - public_sinsp_API/ppm_sc_codes.cpp) + public_sinsp_API/ppm_sc_codes.cpp + ) endif() -# Link against additional files could be useful when testing plugins -# `ADDITIONAL_SINSP_TESTS_SUITE` is a list of source files `;` separated +# Link against additional files could be useful when testing plugins `ADDITIONAL_SINSP_TESTS_SUITE` +# is a list of source files `;` separated if(ADDITIONAL_SINSP_TESTS_SUITE) message(STATUS "- Additional sinsp source files: ${ADDITIONAL_SINSP_TESTS_SUITE}") list(APPEND LIBSINSP_UNIT_TESTS_SOURCES "${ADDITIONAL_SINSP_TESTS_SUITE}") @@ -175,29 +173,27 @@ endif() add_executable(unit-test-libsinsp ${LIBSINSP_UNIT_TESTS_SOURCES}) -if (EMSCRIPTEN) +if(EMSCRIPTEN) target_compile_options(unit-test-libsinsp PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0") target_link_options(unit-test-libsinsp PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0") target_link_options(unit-test-libsinsp PRIVATE "-sALLOW_MEMORY_GROWTH=1") - target_link_options(unit-test-libsinsp PRIVATE "-sEXPORTED_FUNCTIONS=['_main','_htons','_ntohs']") - # note(jasondellaluce): since we run tests with node, we need to add this - # for reading from local capture files. + target_link_options( + unit-test-libsinsp PRIVATE "-sEXPORTED_FUNCTIONS=['_main','_htons','_ntohs']" + ) + # note(jasondellaluce): since we run tests with node, we need to add this for reading from local + # capture files. target_link_options(unit-test-libsinsp PRIVATE "-sNODERAWFS=1") endif() -target_include_directories(unit-test-libsinsp - PRIVATE - ${LIBS_DIR} # needed for driver/event_stats.h - ${CMAKE_CURRENT_BINARY_DIR} # needed for libsinsp_test_var.h.in - ${CMAKE_CURRENT_SOURCE_DIR} +target_include_directories( + unit-test-libsinsp + PRIVATE ${LIBS_DIR} # needed for driver/event_stats.h + ${CMAKE_CURRENT_BINARY_DIR} # needed for libsinsp_test_var.h.in + ${CMAKE_CURRENT_SOURCE_DIR} ) -target_link_libraries(unit-test-libsinsp - sinsp - "${GTEST_LIB}" - "${GTEST_MAIN_LIB}" - "${TBB_LIB}" - "${JSONCPP_LIB}" +target_link_libraries( + unit-test-libsinsp sinsp "${GTEST_LIB}" "${GTEST_MAIN_LIB}" "${TBB_LIB}" "${JSONCPP_LIB}" ) # Add some additional include directories associated with `ADDITIONAL_SINSP_TESTS_SUITE` @@ -207,7 +203,8 @@ if(ADDITIONAL_SINSP_TESTS_INCLUDE_FOLDERS) target_include_directories(unit-test-libsinsp PRIVATE ${ADDITIONAL_SINSP_TESTS_INCLUDE_FOLDERS}) endif() -add_custom_target(run-unit-test-libsinsp +add_custom_target( + run-unit-test-libsinsp DEPENDS unit-test-libsinsp COMMAND unit-test-libsinsp ) diff --git a/userspace/libsinsp/test/ast_exprs.ut.cpp b/userspace/libsinsp/test/ast_exprs.ut.cpp index 64b56377ee..0728f58e60 100644 --- a/userspace/libsinsp/test/ast_exprs.ut.cpp +++ b/userspace/libsinsp/test/ast_exprs.ut.cpp @@ -21,8 +21,7 @@ limitations under the License. using namespace libsinsp::filter::ast; -static std::unique_ptr make_expr(const std::string& cond) -{ +static std::unique_ptr make_expr(const std::string& cond) { libsinsp::filter::parser p(cond); std::unique_ptr e = p.parse(); @@ -30,8 +29,7 @@ static std::unique_ptr make_expr(const std::string& cond) return e; } -TEST(ast, compare_binary_check_exprs) -{ +TEST(ast, compare_binary_check_exprs) { std::unique_ptr e1 = make_expr("evt.num >= 0"); std::unique_ptr e2 = make_expr("evt.num = 0"); ASSERT_FALSE(e1->is_equal(e2.get())); diff --git a/userspace/libsinsp/test/async_key_value_source.ut.cpp b/userspace/libsinsp/test/async_key_value_source.ut.cpp index 5b64af2874..650c126827 100644 --- a/userspace/libsinsp/test/async_key_value_source.ut.cpp +++ b/userspace/libsinsp/test/async_key_value_source.ut.cpp @@ -30,26 +30,21 @@ limitations under the License. using namespace libsinsp; -namespace -{ +namespace { /** * Intermediate realization of async_key_value_source that can return pre-canned * results. */ -class precanned_metadata_source : public async_key_value_source -{ +class precanned_metadata_source : public async_key_value_source { public: const static uint64_t FOREVER_MS; - precanned_metadata_source(const uint64_t max_wait_ms, const uint64_t ttl_ms = FOREVER_MS) - : async_key_value_source(max_wait_ms, ttl_ms), - m_responses() - { - } + precanned_metadata_source(const uint64_t max_wait_ms, const uint64_t ttl_ms = FOREVER_MS): + async_key_value_source(max_wait_ms, ttl_ms), + m_responses() {} - void set_response(const std::string& key, const std::string& response) - { + void set_response(const std::string& key, const std::string& response) { m_responses[key] = response; } @@ -63,23 +58,18 @@ const uint64_t precanned_metadata_source::FOREVER_MS = static_cast(~0L /** * Realization of async_key_value_source that returns results without delay. */ -class immediate_metadata_source : public precanned_metadata_source -{ +class immediate_metadata_source : public precanned_metadata_source { public: const static uint64_t MAX_WAIT_TIME_MS; - immediate_metadata_source(const uint64_t max_wait_ms = MAX_WAIT_TIME_MS) - : precanned_metadata_source(max_wait_ms) - { - } + immediate_metadata_source(const uint64_t max_wait_ms = MAX_WAIT_TIME_MS): + precanned_metadata_source(max_wait_ms) {} protected: - virtual void run_impl() override - { + virtual void run_impl() override { std::string key; - while (dequeue_next_key(key)) - { + while(dequeue_next_key(key)) { store_value(key, get_response(key)); } } @@ -90,29 +80,24 @@ const uint64_t immediate_metadata_source::MAX_WAIT_TIME_MS = 5000; * Realization of async_key_value_source that returns results with some * specified delay. */ -class delayed_metadata_source : public precanned_metadata_source -{ +class delayed_metadata_source : public precanned_metadata_source { public: const static uint64_t MAX_WAIT_TIME_MS; - delayed_metadata_source(const uint64_t delay_ms, const uint64_t ttl_ms = FOREVER_MS) - : precanned_metadata_source(MAX_WAIT_TIME_MS, ttl_ms), - m_delay_ms(delay_ms), - m_response_available(false) - { - } + delayed_metadata_source(const uint64_t delay_ms, const uint64_t ttl_ms = FOREVER_MS): + precanned_metadata_source(MAX_WAIT_TIME_MS, ttl_ms), + m_delay_ms(delay_ms), + m_response_available(false) {} bool is_response_available() const { return m_response_available; } protected: - virtual void run_impl() override - { + virtual void run_impl() override { std::string key; m_response_available = false; - while (dequeue_next_key(key)) - { + while(dequeue_next_key(key)) { std::this_thread::sleep_for(std::chrono::milliseconds(m_delay_ms)); store_value(key, get_response(key)); m_response_available = true; @@ -129,8 +114,7 @@ const uint64_t delayed_metadata_source::MAX_WAIT_TIME_MS = 0; * Ensure that a concrete async_key_value_source is in the expected initial * state after construction. */ -TEST(async_key_value_source_test, construction) -{ +TEST(async_key_value_source_test, construction) { immediate_metadata_source source; ASSERT_EQ(immediate_metadata_source::MAX_WAIT_TIME_MS, source.get_max_wait()); @@ -143,8 +127,7 @@ TEST(async_key_value_source_test, construction) * the timeout, that the lookup() method returns true, and that it returns * the metadata in the output parameter. */ -TEST(async_key_value_source_test, lookup_key_immediate_return) -{ +TEST(async_key_value_source_test, lookup_key_immediate_return) { const std::string key = "foo"; const std::string metadata = "bar"; std::string response = "response-not-set"; @@ -162,8 +145,7 @@ TEST(async_key_value_source_test, lookup_key_immediate_return) /** * Ensure that get_complete_results returns all complete results */ -TEST(async_key_value_source_test, get_complete_results) -{ +TEST(async_key_value_source_test, get_complete_results) { const std::string key1 = "foo1"; const std::string key2 = "foo2"; const std::string metadata = "bar"; @@ -194,8 +176,7 @@ TEST(async_key_value_source_test, get_complete_results) * Ensure that get_complete_results returns all complete results * but does *not* return results that have not yet been computed */ -TEST(async_key_value_source_test, get_complete_results_incomplete) -{ +TEST(async_key_value_source_test, get_complete_results_incomplete) { const std::string key1 = "foo1"; const std::string key2 = "foo2"; const std::string metadata = "bar"; @@ -227,8 +208,7 @@ TEST(async_key_value_source_test, get_complete_results_incomplete) * Ensure that lookup_delayed() does not return the value immediately * but only after the specified time */ -TEST(async_key_value_source_test, lookup_delayed) -{ +TEST(async_key_value_source_test, lookup_delayed) { const std::string key = "foo_delayed"; const std::string metadata = "bar"; std::string response = "response-not-set"; @@ -259,8 +239,7 @@ TEST(async_key_value_source_test, lookup_delayed) * before the timeout, and if the client did not provide a callback, that * calling lookup() after the result it available returns the value. */ -TEST(async_key_value_source_test, lookup_key_delayed_return_second_call) -{ +TEST(async_key_value_source_test, lookup_key_delayed_return_second_call) { const uint64_t DELAY_MS = 50; const std::string key = "mykey"; const std::string metadata = "myvalue"; @@ -284,8 +263,7 @@ TEST(async_key_value_source_test, lookup_key_delayed_return_second_call) // than 5 seconds, something went wrong. std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_MS)); const int FIVE_SECS_IN_MS = 5 * 1000; - for (int i = 0; !source.is_response_available() && i < FIVE_SECS_IN_MS; ++i) - { + for(int i = 0; !source.is_response_available() && i < FIVE_SECS_IN_MS; ++i) { // Avoid tight busy loop std::this_thread::sleep_for(std::chrono::milliseconds(1)); } @@ -302,8 +280,7 @@ TEST(async_key_value_source_test, lookup_key_delayed_return_second_call) * before the timeout, and if the client did provide a callback, that the * callback is invoked with the metadata once they're avaialble. */ -TEST(async_key_value_source_test, look_key_delayed_async_callback) -{ +TEST(async_key_value_source_test, look_key_delayed_async_callback) { const uint64_t DELAY_MS = 50; const std::string key = "mykey"; const std::string metadata = "myvalue"; @@ -322,15 +299,14 @@ TEST(async_key_value_source_test, look_key_delayed_async_callback) source.set_response(key, metadata); response_found = - source.lookup(key, - sync_response, - [&m, &async_response, &lookup_complete](const std::string& key, - const std::string& value) - { - std::lock_guard lk(m); - async_response = value; - lookup_complete = true; - }); + source.lookup(key, + sync_response, + [&m, &async_response, &lookup_complete](const std::string& key, + const std::string& value) { + std::lock_guard lk(m); + async_response = value; + lookup_complete = true; + }); ASSERT_FALSE(response_found); @@ -342,11 +318,10 @@ TEST(async_key_value_source_test, look_key_delayed_async_callback) std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_MS)); std::string response; const int FIVE_SECS_IN_MS = 5 * 1000; - for (int i = 0; !async_response_received && i < FIVE_SECS_IN_MS; ++i) - { + for(int i = 0; !async_response_received && i < FIVE_SECS_IN_MS; ++i) { { std::lock_guard lk(m); - if (lookup_complete) { + if(lookup_complete) { response = async_response; async_response_received = true; } @@ -361,8 +336,7 @@ TEST(async_key_value_source_test, look_key_delayed_async_callback) /** * Ensure that "old" results are pruned */ -TEST(async_key_value_source_test, prune_old_metadata) -{ +TEST(async_key_value_source_test, prune_old_metadata) { const uint64_t DELAY_MS = 0; const uint64_t TTL_MS = 20; @@ -399,56 +373,43 @@ TEST(async_key_value_source_test, prune_old_metadata) ASSERT_FALSE(source.lookup(key1, response)); } -struct result -{ +struct result { uint64_t val = 0; int retries = 0; }; -class test_key_value_source : public libsinsp::async_key_value_source -{ +class test_key_value_source : public libsinsp::async_key_value_source { public: - test_key_value_source(uint64_t delay_ms, uint64_t wait_response_ms, uint64_t ttl_ms = std::numeric_limits::max(), short num_failures = 0, short backoff_ms = 10): - async_key_value_source(wait_response_ms, ttl_ms), - m_delay_ms(delay_ms), - m_num_failures(num_failures), - m_backoff_ms(backoff_ms) - { + test_key_value_source(uint64_t delay_ms, + uint64_t wait_response_ms, + uint64_t ttl_ms = std::numeric_limits::max(), + short num_failures = 0, + short backoff_ms = 10): + async_key_value_source(wait_response_ms, ttl_ms), + m_delay_ms(delay_ms), + m_num_failures(num_failures), + m_backoff_ms(backoff_ms) { assert(m_num_failures >= 0); assert(backoff_ms >= 0); } - virtual ~test_key_value_source() - { - stop(); - } + virtual ~test_key_value_source() { stop(); } - bool next_key(std::string& key) - { - return dequeue_next_key(key); - } + bool next_key(std::string& key) { return dequeue_next_key(key); } - void run_impl() - { + void run_impl() { std::string key; result res; - while(dequeue_next_key(key, &res)) - { - if(m_delay_ms > 0) - { + while(dequeue_next_key(key, &res)) { + if(m_delay_ms > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(m_delay_ms)); } - if(res.retries < m_num_failures) - { + if(res.retries < m_num_failures) { res.retries++; // Simulate failures, re-enqueue the key after m_backoff_ms milliseconds - defer_lookup(key, - &res, - std::chrono::milliseconds(m_backoff_ms)); - } - else - { + defer_lookup(key, &res, std::chrono::milliseconds(m_backoff_ms)); + } else { res.val = (uint64_t)atoi(key.c_str()); store_value(key, res); } @@ -461,61 +422,51 @@ class test_key_value_source : public libsinsp::async_key_value_source t(new test_key_value_source(0, UINT64_MAX)); } -TEST(async_key_value_source_test, basic) -{ +TEST(async_key_value_source_test, basic) { std::unique_ptr t(new test_key_value_source(0, UINT64_MAX)); result res; - while(!t->lookup("1", res)) - { + while(!t->lookup("1", res)) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } ASSERT_EQ(1, res.val); } -TEST(async_key_value_source_test, long_delay_lookups) -{ +TEST(async_key_value_source_test, long_delay_lookups) { std::unique_ptr t(new test_key_value_source(500, UINT64_MAX)); result res; - while(!t->lookup("1", res)) - { + while(!t->lookup("1", res)) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } ASSERT_EQ(1, res.val); } -TEST(async_key_value_source_test, basic_nowait) -{ +TEST(async_key_value_source_test, basic_nowait) { std::unique_ptr t(new test_key_value_source(0, 0)); result res; - while(!t->lookup("1", res)) - { + while(!t->lookup("1", res)) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } ASSERT_EQ(1, res.val); } -TEST(async_key_value_source_test, long_delay_lookups_nowait) -{ +TEST(async_key_value_source_test, long_delay_lookups_nowait) { std::unique_ptr t(new test_key_value_source(500, 0)); result res; - while(!t->lookup("1", res)) - { + while(!t->lookup("1", res)) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } ASSERT_EQ(1, res.val); } -TEST(async_key_value_source_test, async) -{ +TEST(async_key_value_source_test, async) { uint64_t ttl_ms = std::numeric_limits::max(); short num_failures = 3; result res; @@ -535,13 +486,12 @@ TEST(async_key_value_source_test, async) }); std::unique_lock lk(cv_m); - if(!cv.wait_for(lk, std::chrono::milliseconds(100), [&done](){ return done; })) { + if(!cv.wait_for(lk, std::chrono::milliseconds(100), [&done]() { return done; })) { FAIL() << "Timeout expired while waiting for result"; } } -TEST(async_key_value_source_test, async_ttl_expired) -{ +TEST(async_key_value_source_test, async_ttl_expired) { uint64_t ttl_ms = 10; short num_failures = 3; short backoff_ms = 6; @@ -552,31 +502,28 @@ TEST(async_key_value_source_test, async_ttl_expired) bool done = false; t.lookup( - "1", res, - [&cv_m, &cv, &done](const std::string& key, const result& res) - { + "1", + res, + [&cv_m, &cv, &done](const std::string& key, const result& res) { + FAIL() << "unexpected callback for key: " << key; + { + std::lock_guard lk(cv_m); + done = true; + } + cv.notify_all(); + }, + [&cv_m, &cv, &done](const std::string& key) { + ASSERT_EQ("1", key); + { + std::lock_guard lk(cv_m); + done = true; + } + cv.notify_all(); + }); - FAIL() << "unexpected callback for key: " << key; - { - std::lock_guard lk(cv_m); - done = true; - } - cv.notify_all(); - }, - [&cv_m, &cv, &done](const std::string& key) - { - ASSERT_EQ("1", key); - { - std::lock_guard lk(cv_m); - done = true; - } - cv.notify_all(); - }); - { std::unique_lock lk(cv_m); - if(!cv.wait_for(lk, std::chrono::milliseconds(100), [&done]() - { return done; })) { + if(!cv.wait_for(lk, std::chrono::milliseconds(100), [&done]() { return done; })) { FAIL() << "Timeout expired while waiting for result"; } } @@ -586,4 +533,4 @@ TEST(async_key_value_source_test, async_ttl_expired) ASSERT_FALSE(t.next_key(key)); } -} // namespace +} // namespace diff --git a/userspace/libsinsp/test/cgroup_list_counter.ut.cpp b/userspace/libsinsp/test/cgroup_list_counter.ut.cpp index 3476242b06..1920143f99 100644 --- a/userspace/libsinsp/test/cgroup_list_counter.ut.cpp +++ b/userspace/libsinsp/test/cgroup_list_counter.ut.cpp @@ -19,23 +19,20 @@ limitations under the License. #include #include -TEST(cgroup_list_counter_test, basic) -{ +TEST(cgroup_list_counter_test, basic) { libsinsp::cgroup_list_counter counter; ASSERT_EQ(8, counter("0-5,8,14")); ASSERT_EQ(1, counter("5")); ASSERT_EQ(6, counter("9-14")); } -TEST(cgroup_list_counter_test, invalid_value) -{ +TEST(cgroup_list_counter_test, invalid_value) { libsinsp::cgroup_list_counter counter; ASSERT_EQ(-1, counter("")); ASSERT_EQ(-1, counter(",1")); } -TEST(cgroup_list_counter_test, invalid_range_missing_number) -{ +TEST(cgroup_list_counter_test, invalid_range_missing_number) { libsinsp::cgroup_list_counter counter; ASSERT_EQ(-1, counter("-5,8,14")); ASSERT_EQ(-1, counter("1,-5,8,14")); @@ -43,22 +40,17 @@ TEST(cgroup_list_counter_test, invalid_range_missing_number) ASSERT_EQ(-1, counter("1,4-")); } -TEST(cgroup_list_counter_test, invalid_range_double_dash) -{ +TEST(cgroup_list_counter_test, invalid_range_double_dash) { libsinsp::cgroup_list_counter counter; ASSERT_EQ(-1, counter("1,4-5-6,14")); } -TEST(cgroup_list_counter_test, invalid_range_wrong_order) -{ +TEST(cgroup_list_counter_test, invalid_range_wrong_order) { libsinsp::cgroup_list_counter counter; ASSERT_EQ(-1, counter("1,6-5,14")); } -TEST(cgroup_list_counter_test, not_a_number) -{ +TEST(cgroup_list_counter_test, not_a_number) { libsinsp::cgroup_list_counter counter; ASSERT_EQ(-1, counter("1,5-a,14")); } - - diff --git a/userspace/libsinsp/test/classes/sinsp.cpp b/userspace/libsinsp/test/classes/sinsp.cpp index 99eabecf5e..c82836f30b 100644 --- a/userspace/libsinsp/test/classes/sinsp.cpp +++ b/userspace/libsinsp/test/classes/sinsp.cpp @@ -25,8 +25,7 @@ limitations under the License. #define HOST_ROOT_ENV "HOST_ROOT" #ifdef HAS_ENGINE_KMOD -TEST(sinsp, wrong_host_root) -{ +TEST(sinsp, wrong_host_root) { ASSERT_EQ(0, setenv(HOST_ROOT_ENV, "fake_hostroot", 1)); sinsp inspector = {}; diff --git a/userspace/libsinsp/test/classes/sinsp_thread_manager.cpp b/userspace/libsinsp/test/classes/sinsp_thread_manager.cpp index 4103d970ec..6eeda6582b 100644 --- a/userspace/libsinsp/test/classes/sinsp_thread_manager.cpp +++ b/userspace/libsinsp/test/classes/sinsp_thread_manager.cpp @@ -18,8 +18,7 @@ limitations under the License. #include -TEST(sinsp_thread_manager, remove_non_existing_thread) -{ +TEST(sinsp_thread_manager, remove_non_existing_thread) { sinsp_thread_manager manager(nullptr); int64_t unknown_tid = 100; @@ -28,8 +27,7 @@ TEST(sinsp_thread_manager, remove_non_existing_thread) manager.remove_thread(unknown_tid); } -TEST(sinsp_thread_manager, thread_group_manager) -{ +TEST(sinsp_thread_manager, thread_group_manager) { sinsp_thread_manager manager(nullptr); /* We don't have thread group info here */ @@ -50,8 +48,7 @@ TEST(sinsp_thread_manager, thread_group_manager) ASSERT_EQ(manager.get_thread_group_info(tinfo->m_pid).get(), new_tginfo.get()); } -TEST(sinsp_thread_manager, create_thread_dependencies_null_pointer) -{ +TEST(sinsp_thread_manager, create_thread_dependencies_null_pointer) { sinsp m_inspector; scap_test_input_data data; data.event_count = 0; @@ -65,8 +62,7 @@ TEST(sinsp_thread_manager, create_thread_dependencies_null_pointer) EXPECT_THROW(m_inspector.m_thread_manager->create_thread_dependencies(tinfo), sinsp_exception); } -TEST(sinsp_thread_manager, create_thread_dependencies_invalid_tinfo) -{ +TEST(sinsp_thread_manager, create_thread_dependencies_invalid_tinfo) { sinsp m_inspector; scap_test_input_data data; data.event_count = 0; @@ -83,8 +79,7 @@ TEST(sinsp_thread_manager, create_thread_dependencies_invalid_tinfo) ASSERT_FALSE(tinfo->m_tginfo); } -TEST(sinsp_thread_manager, create_thread_dependencies_tginfo_already_there) -{ +TEST(sinsp_thread_manager, create_thread_dependencies_tginfo_already_there) { sinsp m_inspector; scap_test_input_data data; data.event_count = 0; @@ -104,8 +99,7 @@ TEST(sinsp_thread_manager, create_thread_dependencies_tginfo_already_there) ASSERT_EQ(tinfo->m_tginfo->get_thread_count(), 1); } -TEST(sinsp_thread_manager, create_thread_dependencies_new_tginfo) -{ +TEST(sinsp_thread_manager, create_thread_dependencies_new_tginfo) { sinsp m_inspector; scap_test_input_data data; data.event_count = 0; @@ -125,8 +119,7 @@ TEST(sinsp_thread_manager, create_thread_dependencies_new_tginfo) ASSERT_EQ(tinfo->m_ptid, 0); } -TEST(sinsp_thread_manager, create_thread_dependencies_use_existing_tginfo) -{ +TEST(sinsp_thread_manager, create_thread_dependencies_use_existing_tginfo) { sinsp m_inspector; scap_test_input_data data; data.event_count = 0; @@ -152,8 +145,7 @@ TEST(sinsp_thread_manager, create_thread_dependencies_use_existing_tginfo) ASSERT_THREAD_GROUP_INFO(tinfo->m_pid, 2, false, 2, 2); } -TEST_F(sinsp_with_test_input, THRD_MANAGER_create_thread_dependencies_valid_parent) -{ +TEST_F(sinsp_with_test_input, THRD_MANAGER_create_thread_dependencies_valid_parent) { DEFAULT_TREE /* new thread will be a child of p6_t1 */ @@ -168,8 +160,7 @@ TEST_F(sinsp_with_test_input, THRD_MANAGER_create_thread_dependencies_valid_pare ASSERT_THREAD_CHILDREN(p6_t1_tid, 1, 1); } -TEST_F(sinsp_with_test_input, THRD_MANAGER_create_thread_dependencies_invalid_parent) -{ +TEST_F(sinsp_with_test_input, THRD_MANAGER_create_thread_dependencies_invalid_parent) { DEFAULT_TREE /* new thread will be a child of p6_t1 */ @@ -184,14 +175,12 @@ TEST_F(sinsp_with_test_input, THRD_MANAGER_create_thread_dependencies_invalid_pa ASSERT_EQ(tinfo->m_ptid, 0); } -TEST(sinsp_thread_manager, THRD_MANAGER_find_new_reaper_nullptr) -{ +TEST(sinsp_thread_manager, THRD_MANAGER_find_new_reaper_nullptr) { sinsp_thread_manager manager(nullptr); EXPECT_THROW(manager.find_new_reaper(nullptr), sinsp_exception); } -TEST_F(sinsp_with_test_input, THRD_MANAGER_find_reaper_in_the_same_thread_group) -{ +TEST_F(sinsp_with_test_input, THRD_MANAGER_find_reaper_in_the_same_thread_group) { DEFAULT_TREE /* We mark it as dead otherwise it will be chosen as a new reaper */ @@ -199,13 +188,13 @@ TEST_F(sinsp_with_test_input, THRD_MANAGER_find_reaper_in_the_same_thread_group) ASSERT_TRUE(p5_t1_tinfo); p5_t1_tinfo->set_dead(); - /* Call the find reaper method, the reaper thread should be the unique thread alive in the group */ + /* Call the find reaper method, the reaper thread should be the unique thread alive in the group + */ auto reaper = m_inspector.m_thread_manager->find_new_reaper(p5_t1_tinfo); ASSERT_EQ(reaper->m_tid, p5_t2_tid); } -TEST_F(sinsp_with_test_input, THRD_MANAGER_find_reaper_in_the_tree) -{ +TEST_F(sinsp_with_test_input, THRD_MANAGER_find_reaper_in_the_tree) { DEFAULT_TREE auto p6_t1_tinfo = m_inspector.get_thread_ref(p6_t1_tid, false).get(); @@ -216,8 +205,7 @@ TEST_F(sinsp_with_test_input, THRD_MANAGER_find_reaper_in_the_tree) ASSERT_EQ(reaper->m_tid, p4_t1_tid); } -TEST_F(sinsp_with_test_input, THRD_MANAGER_find_new_reaper_detect_loop) -{ +TEST_F(sinsp_with_test_input, THRD_MANAGER_find_new_reaper_detect_loop) { DEFAULT_TREE /* If we detect a loop the new reaper will be nullptr. diff --git a/userspace/libsinsp/test/classes/sinsp_threadinfo.cpp b/userspace/libsinsp/test/classes/sinsp_threadinfo.cpp index 2604134936..f63c7a034e 100644 --- a/userspace/libsinsp/test/classes/sinsp_threadinfo.cpp +++ b/userspace/libsinsp/test/classes/sinsp_threadinfo.cpp @@ -18,8 +18,7 @@ limitations under the License. #include -TEST(sinsp_threadinfo, get_main_thread) -{ +TEST(sinsp_threadinfo, get_main_thread) { auto tinfo = std::make_shared(); tinfo->m_tid = 23; tinfo->m_pid = 23; @@ -35,7 +34,8 @@ TEST(sinsp_threadinfo, get_main_thread) tinfo->m_tid = 25; ASSERT_EQ(tinfo->get_main_thread(), nullptr); - /* We should still obtain a nullptr since the first tinfo in the thread group info is not a main thread. */ + /* We should still obtain a nullptr since the first tinfo in the thread group info is not a main + * thread. */ tinfo->m_tginfo = tginfo; ASSERT_EQ(tinfo->get_main_thread(), nullptr); @@ -43,7 +43,8 @@ TEST(sinsp_threadinfo, get_main_thread) main_tinfo->m_tid = 23; main_tinfo->m_pid = 23; - /* We should still obtain a nullptr since we put the main thread as the last element of the list. */ + /* We should still obtain a nullptr since we put the main thread as the last element of the + * list. */ tinfo->m_tginfo->add_thread_to_group(main_tinfo, false); ASSERT_EQ(tinfo->get_main_thread(), nullptr); @@ -51,8 +52,7 @@ TEST(sinsp_threadinfo, get_main_thread) ASSERT_EQ(tinfo->get_main_thread(), main_tinfo.get()); } -TEST(sinsp_threadinfo, get_num_threads) -{ +TEST(sinsp_threadinfo, get_num_threads) { auto tinfo = std::make_shared(); tinfo->m_tid = 25; tinfo->m_pid = 23; @@ -78,14 +78,13 @@ TEST(sinsp_threadinfo, get_num_threads) main_tinfo->set_dead(); - /* Please note that here we still have 2 because we have just marked the thread as Dead without decrementing the - * alive count */ + /* Please note that here we still have 2 because we have just marked the thread as Dead without + * decrementing the alive count */ ASSERT_EQ(tinfo->get_num_threads(), 2); ASSERT_EQ(tinfo->get_num_not_leader_threads(), 2); } -TEST_F(sinsp_with_test_input, THRD_INFO_assign_children_to_reaper) -{ +TEST_F(sinsp_with_test_input, THRD_INFO_assign_children_to_reaper) { DEFAULT_TREE auto p3_t1_tinfo = m_inspector.get_thread_ref(p3_t1_tid, false).get(); @@ -111,14 +110,14 @@ TEST_F(sinsp_with_test_input, THRD_INFO_assign_children_to_reaper) ASSERT_THREAD_CHILDREN(p1_t1_tid, 2, 2, p4_t1_tid, p4_t2_tid); - /* Another call to the reparenting function should do nothing since p3_t1 has no other children */ + /* Another call to the reparenting function should do nothing since p3_t1 has no other children + */ p3_t1_tinfo->assign_children_to_reaper(p1_t1_tinfo); ASSERT_THREAD_CHILDREN(p3_t1_tid, 0, 0); ASSERT_THREAD_CHILDREN(p1_t1_tid, 2, 2, p4_t1_tid, p4_t2_tid); } -TEST_F(sinsp_with_test_input, THRD_INFO_assign_children_to_a_nullptr) -{ +TEST_F(sinsp_with_test_input, THRD_INFO_assign_children_to_a_nullptr) { DEFAULT_TREE auto p2_t1_tinfo = m_inspector.get_thread_ref(p2_t1_tid, false).get(); diff --git a/userspace/libsinsp/test/classes/thread_group_info.cpp b/userspace/libsinsp/test/classes/thread_group_info.cpp index 3b00128328..4a5763caa9 100644 --- a/userspace/libsinsp/test/classes/thread_group_info.cpp +++ b/userspace/libsinsp/test/classes/thread_group_info.cpp @@ -20,8 +20,7 @@ limitations under the License. /*=============================== THREAD-GROUP-INFO ===========================*/ -TEST(thread_group_info, create_thread_group_info) -{ +TEST(thread_group_info, create_thread_group_info) { std::shared_ptr tinfo = std::make_shared(); tinfo.reset(); @@ -51,8 +50,7 @@ TEST(thread_group_info, create_thread_group_info) EXPECT_TRUE(tginfo.is_reaper()); } -TEST(thread_group_info, populate_thread_group_info) -{ +TEST(thread_group_info, populate_thread_group_info) { auto tinfo = std::make_shared(); tinfo->m_tid = 23; tinfo->m_pid = 23; diff --git a/userspace/libsinsp/test/classes/versions.cpp b/userspace/libsinsp/test/classes/versions.cpp index 22b8b8089a..db97e56b57 100644 --- a/userspace/libsinsp/test/classes/versions.cpp +++ b/userspace/libsinsp/test/classes/versions.cpp @@ -20,70 +20,64 @@ limitations under the License. #include -TEST(versions, valid) -{ - EXPECT_FALSE(sinsp_version("1").is_valid()); - EXPECT_FALSE(sinsp_version("1.1").is_valid()); - EXPECT_TRUE(sinsp_version("1.2.3").is_valid()); - EXPECT_EQ(sinsp_version("1.2.3").major(), 1); - EXPECT_EQ(sinsp_version("1.2.3").minor(), 2); - EXPECT_EQ(sinsp_version("1.2.3").patch(), 3); +TEST(versions, valid) { + EXPECT_FALSE(sinsp_version("1").is_valid()); + EXPECT_FALSE(sinsp_version("1.1").is_valid()); + EXPECT_TRUE(sinsp_version("1.2.3").is_valid()); + EXPECT_EQ(sinsp_version("1.2.3").major(), 1); + EXPECT_EQ(sinsp_version("1.2.3").minor(), 2); + EXPECT_EQ(sinsp_version("1.2.3").patch(), 3); } -TEST(versions, operator_eq) -{ - EXPECT_TRUE(sinsp_version("1.2.3") == sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("1.2.3") == sinsp_version("2.2.3")); - EXPECT_FALSE(sinsp_version("1.2.3") == sinsp_version("1.3.3")); - EXPECT_FALSE(sinsp_version("1.2.3") == sinsp_version("1.2.4")); +TEST(versions, operator_eq) { + EXPECT_TRUE(sinsp_version("1.2.3") == sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("1.2.3") == sinsp_version("2.2.3")); + EXPECT_FALSE(sinsp_version("1.2.3") == sinsp_version("1.3.3")); + EXPECT_FALSE(sinsp_version("1.2.3") == sinsp_version("1.2.4")); } -TEST(versions, operator_ne) -{ - EXPECT_FALSE(sinsp_version("1.2.3") != sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.2.3") != sinsp_version("2.2.3")); - EXPECT_TRUE(sinsp_version("1.2.3") != sinsp_version("1.3.3")); - EXPECT_TRUE(sinsp_version("1.2.3") != sinsp_version("1.2.4")); +TEST(versions, operator_ne) { + EXPECT_FALSE(sinsp_version("1.2.3") != sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.2.3") != sinsp_version("2.2.3")); + EXPECT_TRUE(sinsp_version("1.2.3") != sinsp_version("1.3.3")); + EXPECT_TRUE(sinsp_version("1.2.3") != sinsp_version("1.2.4")); } -TEST(versions, operator_gt) -{ - EXPECT_TRUE(sinsp_version("2.2.3") > sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.3.3") > sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.2.4") > sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("1.2.3") > sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("2.2.3") > sinsp_version("1.5.5")); +TEST(versions, operator_gt) { + EXPECT_TRUE(sinsp_version("2.2.3") > sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.3.3") > sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.2.4") > sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("1.2.3") > sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("2.2.3") > sinsp_version("1.5.5")); - EXPECT_TRUE(sinsp_version("2.2.3") >= sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.3.3") >= sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.2.4") >= sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.2.3") >= sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("2.2.3") >= sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.3.3") >= sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.2.4") >= sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.2.3") >= sinsp_version("1.2.3")); } -TEST(versions, operator_lt) -{ - EXPECT_FALSE(sinsp_version("2.2.3") < sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("1.3.3") < sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("1.2.4") < sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("1.2.3") < sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.1.150") < sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("0.18.150") < sinsp_version("1.2.3")); +TEST(versions, operator_lt) { + EXPECT_FALSE(sinsp_version("2.2.3") < sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("1.3.3") < sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("1.2.4") < sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("1.2.3") < sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.1.150") < sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("0.18.150") < sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("2.2.3") <= sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("1.3.3") <= sinsp_version("1.2.3")); - EXPECT_FALSE(sinsp_version("1.2.4") <= sinsp_version("1.2.3")); - EXPECT_TRUE(sinsp_version("1.2.3") <= sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("2.2.3") <= sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("1.3.3") <= sinsp_version("1.2.3")); + EXPECT_FALSE(sinsp_version("1.2.4") <= sinsp_version("1.2.3")); + EXPECT_TRUE(sinsp_version("1.2.3") <= sinsp_version("1.2.3")); } -TEST(versions, compatible_with) -{ - sinsp_version a("1.2.3"); - EXPECT_FALSE(a.compatible_with(sinsp_version("0.2.3"))); - EXPECT_FALSE(a.compatible_with(sinsp_version("2.2.3"))); - EXPECT_TRUE(a.compatible_with(sinsp_version("1.1.3"))); - EXPECT_FALSE(a.compatible_with(sinsp_version("1.3.3"))); - EXPECT_TRUE(a.compatible_with(sinsp_version("1.2.2"))); - EXPECT_FALSE(a.compatible_with(sinsp_version("1.2.4"))); - EXPECT_TRUE(a.compatible_with(sinsp_version("1.1.19"))); - EXPECT_TRUE(a.compatible_with(a)); +TEST(versions, compatible_with) { + sinsp_version a("1.2.3"); + EXPECT_FALSE(a.compatible_with(sinsp_version("0.2.3"))); + EXPECT_FALSE(a.compatible_with(sinsp_version("2.2.3"))); + EXPECT_TRUE(a.compatible_with(sinsp_version("1.1.3"))); + EXPECT_FALSE(a.compatible_with(sinsp_version("1.3.3"))); + EXPECT_TRUE(a.compatible_with(sinsp_version("1.2.2"))); + EXPECT_FALSE(a.compatible_with(sinsp_version("1.2.4"))); + EXPECT_TRUE(a.compatible_with(sinsp_version("1.1.19"))); + EXPECT_TRUE(a.compatible_with(a)); } diff --git a/userspace/libsinsp/test/container_engine/container_cache.ut.cpp b/userspace/libsinsp/test/container_engine/container_cache.ut.cpp index 465d30b90e..bbdd6f76d4 100644 --- a/userspace/libsinsp/test/container_engine/container_cache.ut.cpp +++ b/userspace/libsinsp/test/container_engine/container_cache.ut.cpp @@ -21,41 +21,43 @@ limitations under the License. #include "../sinsp_with_test_input.h" #include -TEST_F(sinsp_with_test_input, container_manager_cache_threadtable_lifecycle) -{ - std::string test_container_id = "3ad7b26ded6d"; - DEFAULT_TREE; - ASSERT_EQ(DEFAULT_TREE_NUM_PROCS, m_inspector.m_thread_manager->get_thread_count()); - // Assign the test container id to one thread in the threadtable - sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(p4_t1_tid, false, true).get(); - ASSERT_TRUE(tinfo); - tinfo->m_container_id = test_container_id; - ASSERT_EQ(test_container_id, tinfo->m_container_id); - - // Manually add a mock container to the container engine cache - std::shared_ptr container_info = std::make_shared(); - container_info->m_type = CT_CRI; +TEST_F(sinsp_with_test_input, container_manager_cache_threadtable_lifecycle) { + std::string test_container_id = "3ad7b26ded6d"; + DEFAULT_TREE; + ASSERT_EQ(DEFAULT_TREE_NUM_PROCS, m_inspector.m_thread_manager->get_thread_count()); + // Assign the test container id to one thread in the threadtable + sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(p4_t1_tid, false, true).get(); + ASSERT_TRUE(tinfo); + tinfo->m_container_id = test_container_id; + ASSERT_EQ(test_container_id, tinfo->m_container_id); + + // Manually add a mock container to the container engine cache + std::shared_ptr container_info = std::make_shared(); + container_info->m_type = CT_CRI; container_info->m_id = test_container_id; - m_inspector.m_container_manager.add_container(std::move(container_info), nullptr); - const sinsp_container_info::ptr_t container_info_check = m_inspector.m_container_manager.get_container(test_container_id); - ASSERT_TRUE(container_info_check); - ASSERT_EQ(test_container_id, container_info_check->m_id); - - // Arbitrary time travel to invoke removal / flush logic remove_inactive_containers - m_inspector.m_containers_purging_scan_time_ns = 0; - m_inspector.m_container_manager.m_last_flush_time_ns = 1; - m_inspector.m_container_manager.remove_inactive_containers(); - const sinsp_container_info::ptr_t container_info_check_not_removed = m_inspector.m_container_manager.get_container(test_container_id); - ASSERT_TRUE(container_info_check_not_removed); // container remains cached - ASSERT_EQ(test_container_id, container_info_check_not_removed->m_id); - - // Mock remove test_container1 container from threadtable - tinfo = m_inspector.get_thread_ref(p4_t1_tid, false, true).get(); - tinfo->m_container_id = ""; - m_inspector.m_containers_purging_scan_time_ns = 0; - m_inspector.m_container_manager.m_last_flush_time_ns = 1; - m_inspector.m_container_manager.remove_inactive_containers(); - - const sinsp_container_info::ptr_t container_info_check_removed = m_inspector.m_container_manager.get_container(test_container_id); - ASSERT_FALSE(container_info_check_removed); // now a nullptr since the container was removed + m_inspector.m_container_manager.add_container(std::move(container_info), nullptr); + const sinsp_container_info::ptr_t container_info_check = + m_inspector.m_container_manager.get_container(test_container_id); + ASSERT_TRUE(container_info_check); + ASSERT_EQ(test_container_id, container_info_check->m_id); + + // Arbitrary time travel to invoke removal / flush logic remove_inactive_containers + m_inspector.m_containers_purging_scan_time_ns = 0; + m_inspector.m_container_manager.m_last_flush_time_ns = 1; + m_inspector.m_container_manager.remove_inactive_containers(); + const sinsp_container_info::ptr_t container_info_check_not_removed = + m_inspector.m_container_manager.get_container(test_container_id); + ASSERT_TRUE(container_info_check_not_removed); // container remains cached + ASSERT_EQ(test_container_id, container_info_check_not_removed->m_id); + + // Mock remove test_container1 container from threadtable + tinfo = m_inspector.get_thread_ref(p4_t1_tid, false, true).get(); + tinfo->m_container_id = ""; + m_inspector.m_containers_purging_scan_time_ns = 0; + m_inspector.m_container_manager.m_last_flush_time_ns = 1; + m_inspector.m_container_manager.remove_inactive_containers(); + + const sinsp_container_info::ptr_t container_info_check_removed = + m_inspector.m_container_manager.get_container(test_container_id); + ASSERT_FALSE(container_info_check_removed); // now a nullptr since the container was removed } diff --git a/userspace/libsinsp/test/container_engine/container_image_splitting.ut.cpp b/userspace/libsinsp/test/container_engine/container_image_splitting.ut.cpp index 19b6d07656..c3ccd10012 100644 --- a/userspace/libsinsp/test/container_engine/container_image_splitting.ut.cpp +++ b/userspace/libsinsp/test/container_engine/container_image_splitting.ut.cpp @@ -26,65 +26,64 @@ limitations under the License. using namespace std; static list> with_splitting_testcases = { - // input host port name tag digest - {"busybox", "", "", "busybox", "", ""}, - {"busybox:latest", "", "", "busybox", "latest", ""}, - {"busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "", - "", - "busybox", - "1.27.2", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, - {"my.host.name/busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "my.host.name", - "", - "busybox", - "1.27.2", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, - {"my.host.name:12345/library/busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "my.host.name", - "12345", - "library/busybox", - "1.27.2", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, - {"localhost:12345/library/busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "localhost", - "12345", - "library/busybox", - "1.27.2", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}}; + // input host port name tag digest + {"busybox", "", "", "busybox", "", ""}, + {"busybox:latest", "", "", "busybox", "latest", ""}, + {"busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "", + "", + "busybox", + "1.27.2", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"my.host.name/busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "my.host.name", + "", + "busybox", + "1.27.2", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"my.host.name:12345/library/" + "busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "my.host.name", + "12345", + "library/busybox", + "1.27.2", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"localhost:12345/library/busybox:1.27.2@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "localhost", + "12345", + "library/busybox", + "1.27.2", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}}; static list> without_splitting_testcases = { - // input repo tag digest - {"busybox", "busybox", "", ""}, - {"local.host:5000/libs/test", "local.host:5000/libs/test", "", ""}, - {"libs/test:dev", "libs/test", "dev", ""}, - {"local.host:5000/libs:1.0", "local.host:5000/libs", "1.0", ""}, - {"libs@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "libs", - "", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, - {"local.host:5000/nginx@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "local.host:5000/nginx", - "", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, - {"libs:1.0@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "libs", - "1.0", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, - {"local.host:5000/nginx:alpine@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", - "local.host:5000/nginx", - "alpine", - "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}}; + // input repo tag digest + {"busybox", "busybox", "", ""}, + {"local.host:5000/libs/test", "local.host:5000/libs/test", "", ""}, + {"libs/test:dev", "libs/test", "dev", ""}, + {"local.host:5000/libs:1.0", "local.host:5000/libs", "1.0", ""}, + {"libs@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "libs", + "", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"local.host:5000/nginx@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "local.host:5000/nginx", + "", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"libs:1.0@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "libs", + "1.0", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"local.host:5000/nginx:alpine@sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "local.host:5000/nginx", + "alpine", + "sha256:da39a3ee5e6b4b0d3255bfef95601890afd80709"}}; #define CHECK_VALUE(name, actual, expected) \ - ASSERT_EQ(actual, expected) << "Expected " << name " '" << expected \ - << "' did not match actual value '" << actual << "'" + ASSERT_EQ(actual, expected) << "Expected " << name " '" << expected \ + << "' did not match actual value '" << actual << "'" -TEST(container_image_splitting_test, with_repo_splitting) -{ - for (auto& testcase : with_splitting_testcases) - { +TEST(container_image_splitting_test, with_repo_splitting) { + for(auto& testcase : with_splitting_testcases) { string hostname; string port; string name; @@ -101,10 +100,8 @@ TEST(container_image_splitting_test, with_repo_splitting) } } -TEST(container_image_splitting_test, without_repo_splitting) -{ - for (auto& testcase : without_splitting_testcases) - { +TEST(container_image_splitting_test, without_repo_splitting) { + for(auto& testcase : without_splitting_testcases) { string hostname, port; string repo; string tag; diff --git a/userspace/libsinsp/test/container_engine/container_info.ut.cpp b/userspace/libsinsp/test/container_engine/container_info.ut.cpp index bf601f40ad..11a1e8bae4 100644 --- a/userspace/libsinsp/test/container_engine/container_info.ut.cpp +++ b/userspace/libsinsp/test/container_engine/container_info.ut.cpp @@ -21,19 +21,16 @@ limitations under the License. #include #include -class sinsp_container_lookup_test : public ::testing::TestWithParam>> -{ -}; +class sinsp_container_lookup_test + : public ::testing::TestWithParam>> {}; -TEST(sinsp_container_lookup_test, default_values) -{ +TEST(sinsp_container_lookup_test, default_values) { sinsp_container_lookup lookup; lookup.set_status(sinsp_container_lookup::state::STARTED); EXPECT_TRUE(lookup.first_attempt()); // Loop until retry attempt are exausted. int actual_retries = 0; - while(lookup.should_retry() && actual_retries < 4) - { + while(lookup.should_retry() && actual_retries < 4) { lookup.attempt_increment(); actual_retries++; } @@ -42,16 +39,14 @@ TEST(sinsp_container_lookup_test, default_values) ASSERT_EQ(500, lookup.delay()); } -TEST_P(sinsp_container_lookup_test, delays_match) -{ +TEST_P(sinsp_container_lookup_test, delays_match) { short max_retry; short max_delay_ms; std::vector expected_delays; std::tie(max_retry, max_delay_ms, expected_delays) = GetParam(); auto lookup = sinsp_container_lookup(max_retry, max_delay_ms); lookup.set_status(sinsp_container_lookup::state::STARTED); - for(size_t i = 0; i < expected_delays.size(); i++) - { + for(size_t i = 0; i < expected_delays.size(); i++) { ASSERT_EQ(i == 0, lookup.first_attempt()); lookup.attempt_increment(); ASSERT_EQ(i < (expected_delays.size() - 1), lookup.should_retry()); @@ -61,10 +56,11 @@ TEST_P(sinsp_container_lookup_test, delays_match) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" -INSTANTIATE_TEST_CASE_P(sinsp_container_lookup, - sinsp_container_lookup_test, - ::testing::Values( - std::tuple>{3, 500, {125, 250, 500}}, - std::tuple>{5, 1000, {125, 250, 500, 1000, 1000}}, - std::tuple>{2, 1, {1, 1}})); +INSTANTIATE_TEST_CASE_P( + sinsp_container_lookup, + sinsp_container_lookup_test, + ::testing::Values( + std::tuple>{3, 500, {125, 250, 500}}, + std::tuple>{5, 1000, {125, 250, 500, 1000, 1000}}, + std::tuple>{2, 1, {1, 1}})); #pragma GCC diagnostic pop diff --git a/userspace/libsinsp/test/container_engine/container_parser_cri_containerd.ut.cpp b/userspace/libsinsp/test/container_engine/container_parser_cri_containerd.ut.cpp index 2c6023b89f..d3277e8574 100644 --- a/userspace/libsinsp/test/container_engine/container_parser_cri_containerd.ut.cpp +++ b/userspace/libsinsp/test/container_engine/container_parser_cri_containerd.ut.cpp @@ -16,7 +16,8 @@ limitations under the License. */ -#if !defined(MINIMAL_BUILD) and !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all +#if !defined(MINIMAL_BUILD) and \ + !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all #include #include #include @@ -24,14 +25,14 @@ limitations under the License. #include "../sinsp_with_test_input.h" /* - * Mock container runtime socket API responses for both container and pod in the containerd CRI scenario, - * thereby enabling us to test the parser logic. - * Since we're not querying the socket directly, calling higher-level parsing functions isn't feasible. - * Instead, we perform targeted step-by-step tests that closely resemble the actual code flow. + * Mock container runtime socket API responses for both container and pod in the containerd CRI + * scenario, thereby enabling us to test the parser logic. Since we're not querying the socket + * directly, calling higher-level parsing functions isn't feasible. Instead, we perform targeted + * step-by-step tests that closely resemble the actual code flow. * - * Note: The container and pod status responses below are mocked and don't come from a real server, so - * some information might need to be added later. You can use the crictl tool to obtain realistic JSONs - * by inspecting the container and pod with their truncated IDs: + * Note: The container and pod status responses below are mocked and don't come from a real server, + * so some information might need to be added later. You can use the crictl tool to obtain realistic + * JSONs by inspecting the container and pod with their truncated IDs: * * https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/crictl.md * @@ -408,9 +409,7 @@ std::string pod_info_json = R"({ } })"; -runtime::v1alpha2::ContainerStatusResponse get_default_cri_containerd_container_status_resp() -{ - +runtime::v1alpha2::ContainerStatusResponse get_default_cri_containerd_container_status_resp() { // "status": { // "id": "3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e", // "metadata": { @@ -465,10 +464,12 @@ runtime::v1alpha2::ContainerStatusResponse get_default_cri_containerd_container_ auto status = resp.mutable_status(); status->set_id("3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e"); - status->set_state(runtime::v1alpha2::ContainerState::CONTAINER_RUNNING); // "CONTAINER_RUNNING" - status->set_created_at((uint64_t)1676262698000004577); // dummy - status->set_started_at((uint64_t)1676262698000004577); // dummy - status->set_image_ref("docker.io/library/busybox@sha256:3fbc632167424a6d997e74f52b878d7cc478225cffac6bc977eedfe51c7f4e79"); + status->set_state(runtime::v1alpha2::ContainerState::CONTAINER_RUNNING); // "CONTAINER_RUNNING" + status->set_created_at((uint64_t)1676262698000004577); // dummy + status->set_started_at((uint64_t)1676262698000004577); // dummy + status->set_image_ref( + "docker.io/library/" + "busybox@sha256:3fbc632167424a6d997e74f52b878d7cc478225cffac6bc977eedfe51c7f4e79"); status->mutable_image()->set_image("docker.io/library/busybox:latest"); auto labels = status->mutable_labels(); (*labels)["io.kubernetes.container.name"] = "busybox"; @@ -493,9 +494,7 @@ runtime::v1alpha2::ContainerStatusResponse get_default_cri_containerd_container_ return resp; } -runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_containerd_pod_status_resp() -{ - +runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_containerd_pod_status_resp() { // "status": { // "id": "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a", // "metadata": { @@ -540,7 +539,7 @@ runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_containerd_pod_statu auto status = resp.mutable_status(); status->set_id("63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"); status->set_state(runtime::v1alpha2::PodSandboxState::SANDBOX_READY); - status->set_created_at((uint64_t)1676262698000004577); // dummy + status->set_created_at((uint64_t)1676262698000004577); // dummy status->mutable_metadata()->set_name("nginx-sandbox"); status->mutable_network()->set_ip("10.244.0.2"); auto labels = status->mutable_labels(); @@ -562,22 +561,26 @@ runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_containerd_pod_statu return resp; } -TEST_F(sinsp_with_test_input, container_parser_cri_containerd) -{ +TEST_F(sinsp_with_test_input, container_parser_cri_containerd) { std::string cri_path = "/run/containerd/containerd_mock.sock"; auto cri_api_v1alpha2 = std::make_unique(cri_path); - ASSERT_FALSE(cri_api_v1alpha2->is_ok()); // we are not querying a container runtime socket in this mock test + ASSERT_FALSE( + cri_api_v1alpha2 + ->is_ok()); // we are not querying a container runtime socket in this mock test // Get mock responses - runtime::v1alpha2::ContainerStatusResponse container_status_resp = get_default_cri_containerd_container_status_resp(); - runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = get_default_cri_containerd_pod_status_resp(); + runtime::v1alpha2::ContainerStatusResponse container_status_resp = + get_default_cri_containerd_container_status_resp(); + runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = + get_default_cri_containerd_pod_status_resp(); const auto &resp_container = container_status_resp.status(); const auto &resp_container_info = container_status_resp.info(); const auto root_container = cri_api_v1alpha2->get_info_jvalue(resp_container_info); const auto &resp_pod_sandbox_container = pod_sandbox_status_resp.status(); const auto &resp_pod_sandbox_container_info = pod_sandbox_status_resp.info(); - const auto root_pod_sandbox = cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); + const auto root_pod_sandbox = + cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); std::shared_ptr container_ptr = std::make_shared(); // explicit reference to mimic actual code flow and test sub parser functions sinsp_container_info &container = *container_ptr; @@ -587,7 +590,7 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd) // container.m_type = CT_CONTAINERD; - container.m_id = "3ad7b26ded6d"; // truncated id extracted from cgroups + container.m_id = "3ad7b26ded6d"; // truncated id extracted from cgroups auto res = cri_api_v1alpha2->parse_cri_base(resp_container, container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_pod_sandbox_id_for_container(root_container, container); @@ -602,10 +605,13 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd) // CRI image failure resilience test for cases where it may begin with sha256 auto status = container_status_resp.mutable_status(); - status->set_image_ref("sha256:3fbc632167424a6d997e74f52b878d7cc478225cffac6bc977eedfe51c7f4e79"); + status->set_image_ref( + "sha256:3fbc632167424a6d997e74f52b878d7cc478225cffac6bc977eedfe51c7f4e79"); status->mutable_image()->set_image(""); const auto &resp_container_simulate_image_recovery = container_status_resp.status(); - res = cri_api_v1alpha2->parse_cri_image(resp_container_simulate_image_recovery, root_container, container); + res = cri_api_v1alpha2->parse_cri_image(resp_container_simulate_image_recovery, + root_container, + container); ASSERT_TRUE(res); ASSERT_EQ("docker.io/library/busybox:latest", container.m_image); ASSERT_EQ("docker.io/library/busybox", container.m_imagerepo); @@ -625,14 +631,16 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd) ASSERT_EQ(50000, container.m_cpu_quota); // Below retrieved from PodSandboxStatusResponse - res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, root_pod_sandbox, container); + res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, + root_pod_sandbox, + container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_pod_sandbox_labels(resp_pod_sandbox_container, container); ASSERT_TRUE(res); - // + // // Test sinsp filterchecks, similar to spawn_process_container test - // + // add_default_init_thread(); open_inspector(); @@ -642,28 +650,111 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; std::vector cgroups = { - "cgroups=cpuset=/k8s.io/3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e", - "cpu=/k8s.io/3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e", "cpuacct=/", - "blkio=/k8s.io/3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e", - "memory=/k8s.io/3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e"}; + "cgroups=cpuset=/k8s.io/" + "3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e", + "cpu=/k8s.io/3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e", + "cpuacct=/", + "blkio=/k8s.io/3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e", + "memory=/k8s.io/3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); std::string container_json = m_inspector.m_container_manager.container_to_json(container); add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, (uint64_t)1, (uint64_t)1, (uint64_t)0, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)7208, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)parent_tid, (uint64_t)parent_pid); - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (uint64_t)0, "bash", empty_bytebuf, child_tid, child_pid, (uint64_t)1, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)3764, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)1, (uint64_t)1); + add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)0, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)parent_tid, + (uint64_t)parent_pid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (uint64_t)0, + "bash", + empty_bytebuf, + child_tid, + child_pid, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)1, + (uint64_t)1); add_event_advance_ts(increasing_ts(), -1, PPME_CONTAINER_JSON_2_E, 1, container_json.c_str()); add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 27, (int64_t)0, "/bin/test-exe", empty_bytebuf, child_tid, child_pid, parent_tid, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)29612, (uint32_t)4, (uint32_t)0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, empty_bytebuf, (int32_t)34818, parent_pid, (uint32_t)0, (int32_t)PPM_EXE_UPPER_LAYER, parent_pid, parent_pid, parent_pid, (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)0); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 27, + (int64_t)0, + "/bin/test-exe", + empty_bytebuf, + child_tid, + child_pid, + parent_tid, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + empty_bytebuf, + (int32_t)34818, + parent_pid, + (uint32_t)0, + (int32_t)PPM_EXE_UPPER_LAYER, + parent_pid, + parent_pid, + parent_pid, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)0); // Check containers were added to the container cache - const sinsp_container_info::ptr_t container_info_check = m_inspector.m_container_manager.get_container(container.m_id); + const sinsp_container_info::ptr_t container_info_check = + m_inspector.m_container_manager.get_container(container.m_id); ASSERT_TRUE(container_info_check); ASSERT_EQ("3ad7b26ded6d", container_info_check->m_id); - // Check container and k8s related filter fields that are retrieved from the container runtime socket + // Check container and k8s related filter fields that are retrieved from the container runtime + // socket ASSERT_EQ(get_field_as_string(evt, "container.id"), "3ad7b26ded6d"); - ASSERT_EQ(get_field_as_string(evt, "container.full_id"), "3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e"); + ASSERT_EQ(get_field_as_string(evt, "container.full_id"), + "3ad7b26ded6d8e7b23da7d48fe889434573036c27ae5a74837233de441c3601e"); ASSERT_EQ(get_field_as_string(evt, "container.name"), "busybox"); ASSERT_EQ(get_field_as_string(evt, "container.image"), "docker.io/library/busybox:latest"); ASSERT_EQ(get_field_as_string(evt, "container.image.id"), "busybox"); @@ -675,25 +766,34 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd) ASSERT_EQ(get_field_as_string(evt, "container.mount.propagation[/boot]"), "private"); ASSERT_EQ(get_field_as_string(evt, "container.image.repository"), "docker.io/library/busybox"); ASSERT_EQ(get_field_as_string(evt, "container.image.tag"), "latest"); - ASSERT_EQ(get_field_as_string(evt, "container.image.digest"), "sha256:3fbc632167424a6d997e74f52b878d7cc478225cffac6bc977eedfe51c7f4e79"); + ASSERT_EQ(get_field_as_string(evt, "container.image.digest"), + "sha256:3fbc632167424a6d997e74f52b878d7cc478225cffac6bc977eedfe51c7f4e79"); ASSERT_EQ(get_field_as_string(evt, "container.ip"), "10.244.0.2"); - ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0.1\",\"IP\":\"10.244.0.2\"}]}}"); + ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), + "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0." + "1\",\"IP\":\"10.244.0.2\"}]}}"); ASSERT_EQ(get_field_as_string(evt, "k8s.ns.name"), "default"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.name"), "nginx-sandbox"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), "hdishddjaidwnduw9a43535366368"); // legacy pod UID - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), + "hdishddjaidwnduw9a43535366368"); // legacy pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), + get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID ASSERT_EQ(get_field_as_string(evt, "k8s.pod.sandbox_id"), "63060edc2d3a"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), + "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label.example-label/custom_one"), "mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label[example-label/custom_one]"), "mylabel"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), "app:myapp, example-label/custom_one:mylabel"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), + "app:myapp, example-label/custom_one:mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.ip"), "10.244.0.2"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0.1\",\"IP\":\"10.244.0.2\"}]}}"); - + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), + "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0." + "1\",\"IP\":\"10.244.0.2\"}]}}"); // - // Simulate unsuccessful simultaneous PodSandboxStatusResponse lookup when processing a real container; check k8s filterchecks fallbacks + // Simulate unsuccessful simultaneous PodSandboxStatusResponse lookup when processing a real + // container; check k8s filterchecks fallbacks // container.m_pod_sandbox_cniresult.clear(); @@ -701,49 +801,64 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd) container.m_pod_sandbox_labels.clear(); m_inspector.m_container_manager.replace_container(std::move(container_ptr)); - std::shared_ptr sandbox_container_ptr = std::make_shared(); + std::shared_ptr sandbox_container_ptr = + std::make_shared(); sinsp_container_info &sandbox_container = *sandbox_container_ptr; - // Checking fallbacks means the k8s.pod.* fields in the filterchecks are retrieved from the cached sandbox container - // and not from the actual container, we deleted the fields in question from the container above + // Checking fallbacks means the k8s.pod.* fields in the filterchecks are retrieved from the + // cached sandbox container and not from the actual container, we deleted the fields in question + // from the container above sandbox_container.m_type = CT_CONTAINERD; - sandbox_container.m_id = "63060edc2d3a"; // truncated id extracted from cgroups for the sandbox container + sandbox_container.m_id = + "63060edc2d3a"; // truncated id extracted from cgroups for the sandbox container sandbox_container.m_is_pod_sandbox = true; res = cri_api_v1alpha2->parse_cri_base(resp_pod_sandbox_container, sandbox_container); ASSERT_TRUE(res); - res = cri_api_v1alpha2->parse_cri_pod_sandbox_id_for_podsandbox(sandbox_container); // not used in the assertions below, but keep for completeness + res = cri_api_v1alpha2->parse_cri_pod_sandbox_id_for_podsandbox( + sandbox_container); // not used in the assertions below, but keep for completeness ASSERT_TRUE(res); - res = cri_api_v1alpha2->parse_cri_labels(resp_pod_sandbox_container, sandbox_container); // not used in the assertions below, but keep for completeness + res = cri_api_v1alpha2->parse_cri_labels( + resp_pod_sandbox_container, + sandbox_container); // not used in the assertions below, but keep for completeness ASSERT_TRUE(res); - res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, root_pod_sandbox, sandbox_container); + res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, + root_pod_sandbox, + sandbox_container); ASSERT_TRUE(res); - res = cri_api_v1alpha2->parse_cri_pod_sandbox_labels(resp_pod_sandbox_container, sandbox_container); + res = cri_api_v1alpha2->parse_cri_pod_sandbox_labels(resp_pod_sandbox_container, + sandbox_container); ASSERT_TRUE(res); m_inspector.m_container_manager.add_container(std::move(sandbox_container_ptr), nullptr); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label.example-label/custom_one"), "mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label[example-label/custom_one]"), "mylabel"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), "app:myapp, example-label/custom_one:mylabel"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), + "app:myapp, example-label/custom_one:mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.ip"), "10.244.0.2"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0.1\",\"IP\":\"10.244.0.2\"}]}}"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), + "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0." + "1\",\"IP\":\"10.244.0.2\"}]}}"); } -TEST_F(sinsp_with_test_input, container_parser_cri_containerd_sandbox_container) -{ +TEST_F(sinsp_with_test_input, container_parser_cri_containerd_sandbox_container) { // // On ther other hand this test is solely for sandbox container processes // std::string cri_path = "/run/containerd/containerd_mock.sock"; auto cri_api_v1alpha2 = std::make_unique(cri_path); - ASSERT_FALSE(cri_api_v1alpha2->is_ok()); // we are not querying a container runtime socket in this mock test + ASSERT_FALSE( + cri_api_v1alpha2 + ->is_ok()); // we are not querying a container runtime socket in this mock test // Get mock responses - runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = get_default_cri_containerd_pod_status_resp(); + runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = + get_default_cri_containerd_pod_status_resp(); const auto &resp_pod_sandbox_container = pod_sandbox_status_resp.status(); const auto &resp_pod_sandbox_container_info = pod_sandbox_status_resp.info(); - const auto root_pod_sandbox = cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); + const auto root_pod_sandbox = + cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); std::shared_ptr container_ptr = std::make_shared(); sinsp_container_info &container = *container_ptr; @@ -752,7 +867,8 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd_sandbox_container) // container.m_type = CT_CONTAINERD; - container.m_id = "63060edc2d3a"; // truncated id extracted from cgroups for the sandbox container + container.m_id = + "63060edc2d3a"; // truncated id extracted from cgroups for the sandbox container container.m_is_pod_sandbox = true; auto res = cri_api_v1alpha2->parse_cri_base(resp_pod_sandbox_container, container); ASSERT_TRUE(res); @@ -760,15 +876,17 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd_sandbox_container) ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_labels(resp_pod_sandbox_container, container); ASSERT_TRUE(res); - res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, root_pod_sandbox, container); + res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, + root_pod_sandbox, + container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_pod_sandbox_labels(resp_pod_sandbox_container, container); ASSERT_TRUE(res); ASSERT_TRUE(container.m_is_pod_sandbox); - // + // // Test sinsp filterchecks, similar to spawn_process_container test - // + // add_default_init_thread(); open_inspector(); @@ -778,44 +896,137 @@ TEST_F(sinsp_with_test_input, container_parser_cri_containerd_sandbox_container) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; std::vector cgroups = { - "cgroups=cpuset=/k8s.io/63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a", - "cpu=/k8s.io/63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a", "cpuacct=/", - "blkio=/k8s.io/63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a", - "memory=/k8s.io/63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"}; + "cgroups=cpuset=/k8s.io/" + "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a", + "cpu=/k8s.io/63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a", + "cpuacct=/", + "blkio=/k8s.io/63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a", + "memory=/k8s.io/63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); std::string container_json = m_inspector.m_container_manager.container_to_json(container); add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, (uint64_t)1, (uint64_t)1, (uint64_t)0, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)7208, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)parent_tid, (uint64_t)parent_pid); - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (uint64_t)0, "bash", empty_bytebuf, child_tid, child_pid, (uint64_t)1, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)3764, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)1, (uint64_t)1); + add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)0, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)parent_tid, + (uint64_t)parent_pid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (uint64_t)0, + "bash", + empty_bytebuf, + child_tid, + child_pid, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)1, + (uint64_t)1); add_event_advance_ts(increasing_ts(), -1, PPME_CONTAINER_JSON_2_E, 1, container_json.c_str()); add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 27, (int64_t)0, "/bin/test-exe", empty_bytebuf, child_tid, child_pid, parent_tid, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)29612, (uint32_t)4, (uint32_t)0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, empty_bytebuf, (int32_t)34818, parent_pid, (uint32_t)0, (int32_t)PPM_EXE_UPPER_LAYER, parent_pid, parent_pid, parent_pid, (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)0); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 27, + (int64_t)0, + "/bin/test-exe", + empty_bytebuf, + child_tid, + child_pid, + parent_tid, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + empty_bytebuf, + (int32_t)34818, + parent_pid, + (uint32_t)0, + (int32_t)PPM_EXE_UPPER_LAYER, + parent_pid, + parent_pid, + parent_pid, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)0); // Check containers were added to the container cache - const sinsp_container_info::ptr_t container_info_check = m_inspector.m_container_manager.get_container(container.m_id); + const sinsp_container_info::ptr_t container_info_check = + m_inspector.m_container_manager.get_container(container.m_id); ASSERT_TRUE(container_info_check); ASSERT_EQ("63060edc2d3a", container_info_check->m_id); - // Check container and k8s related filter fields that are retrieved from the container runtime socket + // Check container and k8s related filter fields that are retrieved from the container runtime + // socket ASSERT_EQ(get_field_as_string(evt, "container.id"), "63060edc2d3a"); - ASSERT_EQ(get_field_as_string(evt, "container.full_id"), "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"); + ASSERT_EQ(get_field_as_string(evt, "container.full_id"), + "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"); ASSERT_EQ(get_field_as_string(evt, "container.ip"), "10.244.0.2"); - ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0.1\",\"IP\":\"10.244.0.2\"}]}}"); + ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), + "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0." + "1\",\"IP\":\"10.244.0.2\"}]}}"); ASSERT_EQ(get_field_as_string(evt, "k8s.ns.name"), "default"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.name"), "nginx-sandbox"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), "hdishddjaidwnduw9a43535366368"); // legacy pod UID - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), + "hdishddjaidwnduw9a43535366368"); // legacy pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), + get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID ASSERT_EQ(get_field_as_string(evt, "k8s.pod.sandbox_id"), "63060edc2d3a"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), + "63060edc2d3aa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6a"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label.example-label/custom_one"), "mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label[example-label/custom_one]"), "mylabel"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), "app:myapp, example-label/custom_one:mylabel"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), + "app:myapp, example-label/custom_one:mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.ip"), "10.244.0.2"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0.1\",\"IP\":\"10.244.0.2\"}]}}"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), + "{\"bridge\":{\"IPConfigs\":null},\"eth0\":{\"IPConfigs\":[{\"Gateway\":\"10.244.0." + "1\",\"IP\":\"10.244.0.2\"}]}}"); - // Since this is a pod sandbox container, making it clear that container ID and sandbox ID are the same - ASSERT_EQ(get_field_as_string(evt, "container.id"), get_field_as_string(evt, "k8s.pod.sandbox_id")); + // Since this is a pod sandbox container, making it clear that container ID and sandbox ID are + // the same + ASSERT_EQ(get_field_as_string(evt, "container.id"), + get_field_as_string(evt, "k8s.pod.sandbox_id")); } -#endif // MINIMAL_BUILD +#endif // MINIMAL_BUILD diff --git a/userspace/libsinsp/test/container_engine/container_parser_cri_crio.ut.cpp b/userspace/libsinsp/test/container_engine/container_parser_cri_crio.ut.cpp index f15ec4e303..ec3d62ec7e 100644 --- a/userspace/libsinsp/test/container_engine/container_parser_cri_crio.ut.cpp +++ b/userspace/libsinsp/test/container_engine/container_parser_cri_crio.ut.cpp @@ -16,7 +16,8 @@ limitations under the License. */ -#if !defined(MINIMAL_BUILD) and !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all +#if !defined(MINIMAL_BUILD) and \ + !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all #include #include #include @@ -26,12 +27,13 @@ limitations under the License. /* * Mock container runtime socket API responses for both container and pod in the crio CRI scenario, * thereby enabling us to test the parser logic. - * Since we're not querying the socket directly, calling higher-level parsing functions isn't feasible. - * Instead, we perform targeted step-by-step tests that closely resemble the actual code flow. + * Since we're not querying the socket directly, calling higher-level parsing functions isn't + * feasible. Instead, we perform targeted step-by-step tests that closely resemble the actual code + * flow. * - * Note: The container and pod status responses below are mocked and don't come from a real server, so - * some information might need to be added later. You can use the crictl tool to obtain realistic JSONs - * by inspecting the container and pod with their truncated IDs: + * Note: The container and pod status responses below are mocked and don't come from a real server, + * so some information might need to be added later. You can use the crictl tool to obtain realistic + * JSONs by inspecting the container and pod with their truncated IDs: * * https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/crictl.md * @@ -401,9 +403,7 @@ std::string pod_info_json_crio = R"({ } })"; -runtime::v1alpha2::ContainerStatusResponse get_default_cri_crio_container_status_resp() -{ - +runtime::v1alpha2::ContainerStatusResponse get_default_cri_crio_container_status_resp() { // "status": { // "id": "49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad", // "metadata": { @@ -419,7 +419,8 @@ runtime::v1alpha2::ContainerStatusResponse get_default_cri_crio_container_status // "annotations": {}, // "image": "quay.io/crio/redis:alpine" // }, - // "imageRef": "quay.io/crio/redis@sha256:1780b5a5496189974b94eb2595d86731d7a0820e4beb8ea770974298a943ed55", + // "imageRef": + // "quay.io/crio/redis@sha256:1780b5a5496189974b94eb2595d86731d7a0820e4beb8ea770974298a943ed55", // "reason": "", // "message": "", // "labels": { @@ -448,7 +449,8 @@ runtime::v1alpha2::ContainerStatusResponse get_default_cri_crio_container_status // "selinuxRelabel": false, // } // ], - // "logPath": "/var/log/crio/pods/1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca/49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.log" + // "logPath": + // "/var/log/crio/pods/1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca/49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.log" // }, // Mock container runtime socket API responses ContainerStatusResponse @@ -457,10 +459,12 @@ runtime::v1alpha2::ContainerStatusResponse get_default_cri_crio_container_status auto status = resp.mutable_status(); status->set_id("49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad"); - status->set_state(runtime::v1alpha2::ContainerState::CONTAINER_RUNNING); // "CONTAINER_RUNNING" - status->set_created_at((uint64_t)1676262698000004577); // dummy - status->set_started_at((uint64_t)1676262698000004577); // dummy - status->set_image_ref("quay.io/crio/redis@sha256:1780b5a5496189974b94eb2595d86731d7a0820e4beb8ea770974298a943ed55"); + status->set_state(runtime::v1alpha2::ContainerState::CONTAINER_RUNNING); // "CONTAINER_RUNNING" + status->set_created_at((uint64_t)1676262698000004577); // dummy + status->set_started_at((uint64_t)1676262698000004577); // dummy + status->set_image_ref( + "quay.io/crio/" + "redis@sha256:1780b5a5496189974b94eb2595d86731d7a0820e4beb8ea770974298a943ed55"); status->mutable_image()->set_image("quay.io/crio/redis:alpine"); auto labels = status->mutable_labels(); (*labels)["io.kubernetes.container.name"] = "redis"; @@ -485,9 +489,7 @@ runtime::v1alpha2::ContainerStatusResponse get_default_cri_crio_container_status return resp; } -runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_crio_pod_status_resp() -{ - +runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_crio_pod_status_resp() { // "status": { // "id": "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca", // "metadata": { @@ -532,7 +534,7 @@ runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_crio_pod_status_resp auto status = resp.mutable_status(); status->set_id("1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"); status->set_state(runtime::v1alpha2::PodSandboxState::SANDBOX_READY); - status->set_created_at((uint64_t)1676262698000004577); // dummy + status->set_created_at((uint64_t)1676262698000004577); // dummy status->mutable_metadata()->set_name("podsandbox1"); status->mutable_network()->set_ip("10.244.0.3"); auto labels = status->mutable_labels(); @@ -554,22 +556,26 @@ runtime::v1alpha2::PodSandboxStatusResponse get_default_cri_crio_pod_status_resp return resp; } -TEST_F(sinsp_with_test_input, container_parser_cri_crio) -{ +TEST_F(sinsp_with_test_input, container_parser_cri_crio) { std::string cri_path = "/run/crio/crio_mock.sock"; auto cri_api_v1alpha2 = std::make_unique(cri_path); - ASSERT_FALSE(cri_api_v1alpha2->is_ok()); // we are not querying a container runtime socket in this mock test + ASSERT_FALSE( + cri_api_v1alpha2 + ->is_ok()); // we are not querying a container runtime socket in this mock test // Get mock responses - runtime::v1alpha2::ContainerStatusResponse container_status_resp = get_default_cri_crio_container_status_resp(); - runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = get_default_cri_crio_pod_status_resp(); + runtime::v1alpha2::ContainerStatusResponse container_status_resp = + get_default_cri_crio_container_status_resp(); + runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = + get_default_cri_crio_pod_status_resp(); const auto &resp_container = container_status_resp.status(); const auto &resp_container_info = container_status_resp.info(); const auto root_container = cri_api_v1alpha2->get_info_jvalue(resp_container_info); const auto &resp_pod_sandbox_container = pod_sandbox_status_resp.status(); const auto &resp_pod_sandbox_container_info = pod_sandbox_status_resp.info(); - const auto root_pod_sandbox = cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); + const auto root_pod_sandbox = + cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); std::shared_ptr container_ptr = std::make_shared(); // explicit reference to mimic actual code flow and test sub parser functions sinsp_container_info &container = *container_ptr; @@ -579,7 +585,7 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio) // container.m_type = CT_CRIO; - container.m_id = "49ecc2820215"; // truncated id extracted from cgroups + container.m_id = "49ecc2820215"; // truncated id extracted from cgroups auto res = cri_api_v1alpha2->parse_cri_base(resp_container, container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_pod_sandbox_id_for_container(root_container, container); @@ -588,28 +594,32 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio) ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_image(resp_container, root_container, container); ASSERT_TRUE(res); - ASSERT_EQ("49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad", container.m_full_id); + ASSERT_EQ("49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad", + container.m_full_id); ASSERT_EQ("quay.io/crio/redis:alpine", container.m_image); ASSERT_EQ("quay.io/crio/redis", container.m_imagerepo); ASSERT_EQ("alpine", container.m_imagetag); // CRI image failure resilience test for cases where it may begin with sha256 auto status = container_status_resp.mutable_status(); - status->set_image_ref("sha256:49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad"); + status->set_image_ref( + "sha256:49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad"); status->mutable_image()->set_image(""); const auto &resp_container_simulate_image_recovery = container_status_resp.status(); - res = cri_api_v1alpha2->parse_cri_image(resp_container_simulate_image_recovery, root_container, container); + res = cri_api_v1alpha2->parse_cri_image(resp_container_simulate_image_recovery, + root_container, + container); ASSERT_TRUE(res); ASSERT_EQ("quay.io/crio/redis:alpine", container.m_image); ASSERT_EQ("quay.io/crio/redis", container.m_imagerepo); ASSERT_EQ("alpine", container.m_imagetag); res = cri_api_v1alpha2->parse_cri_json_imageid(root_container, container); - ASSERT_FALSE(res); // parse_cri_json_imageid only supported for containerd + ASSERT_FALSE(res); // parse_cri_json_imageid only supported for containerd res = cri_api_v1alpha2->parse_cri_mounts(resp_container, container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_env(root_container, container); - ASSERT_FALSE(res); // seems broken or not supported for cri-o + ASSERT_FALSE(res); // seems broken or not supported for cri-o res = cri_api_v1alpha2->parse_cri_user_info(root_container, container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_ext_container_info(root_container, container); @@ -618,14 +628,16 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio) ASSERT_EQ(20000, container.m_cpu_quota); // Below retrieved from PodSandboxStatusResponse - res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, root_pod_sandbox, container); + res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, + root_pod_sandbox, + container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_pod_sandbox_labels(resp_pod_sandbox_container, container); ASSERT_TRUE(res); - // + // // Test sinsp filterchecks, similar to spawn_process_container test - // + // add_default_init_thread(); open_inspector(); @@ -635,34 +647,123 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; std::vector cgroups = { - "cpuset=/pod_123.slice/pod_123-456.slice/crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", - "cpu=/pod_123.slice/pod_123-456.slice/crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", - "blkio=/pod_123.slice/pod_123-456.slice/crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", - "memory=/pod_123.slice/pod_123-456.slice/crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", - "hugetlb=/pod_123.slice/pod_123-456.slice/crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", - "pids=/pod_123.slice/pod_123-456.slice/crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", - "misc=/pod_123.slice/pod_123-456.slice/crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope"}; + "cpuset=/pod_123.slice/pod_123-456.slice/" + "crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", + "cpu=/pod_123.slice/pod_123-456.slice/" + "crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", + "blkio=/pod_123.slice/pod_123-456.slice/" + "crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", + "memory=/pod_123.slice/pod_123-456.slice/" + "crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", + "hugetlb=/pod_123.slice/pod_123-456.slice/" + "crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", + "pids=/pod_123.slice/pod_123-456.slice/" + "crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope", + "misc=/pod_123.slice/pod_123-456.slice/" + "crio-49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad.scope"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); std::string container_json = m_inspector.m_container_manager.container_to_json(container); add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, (uint64_t)1, (uint64_t)1, (uint64_t)0, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)7208, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)parent_tid, (uint64_t)parent_pid); - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (uint64_t)0, "bash", empty_bytebuf, child_tid, child_pid, (uint64_t)1, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)3764, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)1, (uint64_t)1); + add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)0, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)parent_tid, + (uint64_t)parent_pid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (uint64_t)0, + "bash", + empty_bytebuf, + child_tid, + child_pid, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)1, + (uint64_t)1); add_event_advance_ts(increasing_ts(), -1, PPME_CONTAINER_JSON_2_E, 1, container_json.c_str()); add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 27, (int64_t)0, "/bin/test-exe", empty_bytebuf, child_tid, child_pid, parent_tid, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)29612, (uint32_t)4, (uint32_t)0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, empty_bytebuf, (int32_t)34818, parent_pid, (uint32_t)0, (int32_t)PPM_EXE_UPPER_LAYER, parent_pid, parent_pid, parent_pid, (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)0); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 27, + (int64_t)0, + "/bin/test-exe", + empty_bytebuf, + child_tid, + child_pid, + parent_tid, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + empty_bytebuf, + (int32_t)34818, + parent_pid, + (uint32_t)0, + (int32_t)PPM_EXE_UPPER_LAYER, + parent_pid, + parent_pid, + parent_pid, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)0); // Check containers were added to the container cache - const sinsp_container_info::ptr_t container_info_check = m_inspector.m_container_manager.get_container(container.m_id); + const sinsp_container_info::ptr_t container_info_check = + m_inspector.m_container_manager.get_container(container.m_id); ASSERT_TRUE(container_info_check); ASSERT_EQ("49ecc2820215", container_info_check->m_id); - // Check container and k8s related filter fields that are retrieved from the container runtime socket + // Check container and k8s related filter fields that are retrieved from the container runtime + // socket ASSERT_EQ(get_field_as_string(evt, "container.id"), "49ecc2820215"); - ASSERT_EQ(get_field_as_string(evt, "container.full_id"), "49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad"); + ASSERT_EQ(get_field_as_string(evt, "container.full_id"), + "49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad"); ASSERT_EQ(get_field_as_string(evt, "container.name"), "redis"); ASSERT_EQ(get_field_as_string(evt, "container.image"), "quay.io/crio/redis:alpine"); - // ASSERT_EQ(get_field_as_string(evt, "container.image.id"), "redis"); // TBD unsure how it's parsed in cri.hpp for cri-o + // ASSERT_EQ(get_field_as_string(evt, "container.image.id"), "redis"); // TBD unsure how it's + // parsed in cri.hpp for cri-o ASSERT_EQ(get_field_as_string(evt, "container.type"), "cri-o"); ASSERT_EQ(get_field_as_string(evt, "container.privileged"), "true"); ASSERT_EQ(get_field_as_string(evt, "container.mounts"), "/boot:/host/boot::false:private"); @@ -671,39 +772,58 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio) ASSERT_EQ(get_field_as_string(evt, "container.mount.propagation[/boot]"), "private"); ASSERT_EQ(get_field_as_string(evt, "container.image.repository"), "quay.io/crio/redis"); ASSERT_EQ(get_field_as_string(evt, "container.image.tag"), "alpine"); - ASSERT_EQ(get_field_as_string(evt, "container.image.digest"), "sha256:49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad"); + ASSERT_EQ(get_field_as_string(evt, "container.image.digest"), + "sha256:49ecc282021562c567a8159ef424a06cdd8637efdca5953de9794eafe29adcad"); ASSERT_EQ(get_field_as_string(evt, "container.ip"), "10.244.0.3"); - ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10.244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); + ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), + "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:" + "76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":" + "\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/" + "dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10." + "244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/" + "0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); ASSERT_EQ(get_field_as_string(evt, "k8s.ns.name"), "redhat.test.crio"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.name"), "podsandbox1"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), "redhat-test-crio"); // legacy pod UID - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), "redhat-test-crio"); // legacy pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), + get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID ASSERT_EQ(get_field_as_string(evt, "k8s.pod.sandbox_id"), "1f04600dc694"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), + "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label.example-label/custom_one"), "mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label[example-label/custom_one]"), "mylabel"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), "app:myapp, example-label/custom_one:mylabel"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), + "app:myapp, example-label/custom_one:mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.ip"), "10.244.0.3"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10.244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), + "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:" + "76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":" + "\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/" + "dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10." + "244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/" + "0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); } -TEST_F(sinsp_with_test_input, container_parser_cri_crio_sandbox_container) -{ +TEST_F(sinsp_with_test_input, container_parser_cri_crio_sandbox_container) { // // On ther other hand this test is solely for sandbox container processes // std::string cri_path = "/run/crio/crio_mock.sock"; auto cri_api_v1alpha2 = std::make_unique(cri_path); - ASSERT_FALSE(cri_api_v1alpha2->is_ok()); // we are not querying a container runtime socket in this mock test + ASSERT_FALSE( + cri_api_v1alpha2 + ->is_ok()); // we are not querying a container runtime socket in this mock test // Get mock responses - runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = get_default_cri_crio_pod_status_resp(); + runtime::v1alpha2::PodSandboxStatusResponse pod_sandbox_status_resp = + get_default_cri_crio_pod_status_resp(); const auto &resp_pod_sandbox_container = pod_sandbox_status_resp.status(); const auto &resp_pod_sandbox_container_info = pod_sandbox_status_resp.info(); - const auto root_pod_sandbox = cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); + const auto root_pod_sandbox = + cri_api_v1alpha2->get_info_jvalue(resp_pod_sandbox_container_info); std::shared_ptr container_ptr = std::make_shared(); sinsp_container_info &container = *container_ptr; @@ -712,7 +832,8 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio_sandbox_container) // container.m_type = CT_CONTAINERD; - container.m_id = "1f04600dc694"; // truncated id extracted from cgroups for the sandbox container + container.m_id = + "1f04600dc694"; // truncated id extracted from cgroups for the sandbox container container.m_is_pod_sandbox = true; auto res = cri_api_v1alpha2->parse_cri_base(resp_pod_sandbox_container, container); ASSERT_TRUE(res); @@ -720,15 +841,17 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio_sandbox_container) ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_labels(resp_pod_sandbox_container, container); ASSERT_TRUE(res); - res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, root_pod_sandbox, container); + res = cri_api_v1alpha2->parse_cri_pod_sandbox_network(resp_pod_sandbox_container, + root_pod_sandbox, + container); ASSERT_TRUE(res); res = cri_api_v1alpha2->parse_cri_pod_sandbox_labels(resp_pod_sandbox_container, container); ASSERT_TRUE(res); ASSERT_TRUE(container.m_is_pod_sandbox); - // + // // Test sinsp filterchecks, similar to spawn_process_container test - // + // add_default_init_thread(); open_inspector(); @@ -738,47 +861,152 @@ TEST_F(sinsp_with_test_input, container_parser_cri_crio_sandbox_container) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; std::vector cgroups = { - "cpuset=/pod_123.slice/pod_123-456.slice/crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", - "cpu=/pod_123.slice/pod_123-456.slice/crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", - "blkio=/pod_123.slice/pod_123-456.slice/crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", - "memory=/pod_123.slice/pod_123-456.slice/crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", - "hugetlb=/pod_123.slice/pod_123-456.slice/crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", - "pids=/pod_123.slice/pod_123-456.slice/crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", - "misc=/pod_123.slice/pod_123-456.slice/crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope"}; + "cpuset=/pod_123.slice/pod_123-456.slice/" + "crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", + "cpu=/pod_123.slice/pod_123-456.slice/" + "crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", + "blkio=/pod_123.slice/pod_123-456.slice/" + "crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", + "memory=/pod_123.slice/pod_123-456.slice/" + "crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", + "hugetlb=/pod_123.slice/pod_123-456.slice/" + "crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", + "pids=/pod_123.slice/pod_123-456.slice/" + "crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope", + "misc=/pod_123.slice/pod_123-456.slice/" + "crio-1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca.scope"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); container.set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); std::string container_json = m_inspector.m_container_manager.container_to_json(container); add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, (uint64_t)1, (uint64_t)1, (uint64_t)0, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)7208, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)parent_tid, (uint64_t)parent_pid); - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (uint64_t)0, "bash", empty_bytebuf, child_tid, child_pid, (uint64_t)1, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)12088, (uint32_t)3764, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t)1000, (uint32_t)1000, (uint64_t)1, (uint64_t)1); + add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)0, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)parent_tid, + (uint64_t)parent_pid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (uint64_t)0, + "bash", + empty_bytebuf, + child_tid, + child_pid, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)1, + (uint64_t)1); add_event_advance_ts(increasing_ts(), -1, PPME_CONTAINER_JSON_2_E, 1, container_json.c_str()); add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 27, (int64_t)0, "/bin/test-exe", empty_bytebuf, child_tid, child_pid, parent_tid, "", (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)29612, (uint32_t)4, (uint32_t)0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, empty_bytebuf, (int32_t)34818, parent_pid, (uint32_t)0, (int32_t)PPM_EXE_UPPER_LAYER, parent_pid, parent_pid, parent_pid, (uint64_t)0, (uint64_t)0, (uint64_t)0, (uint32_t)0); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 27, + (int64_t)0, + "/bin/test-exe", + empty_bytebuf, + child_tid, + child_pid, + parent_tid, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + empty_bytebuf, + (int32_t)34818, + parent_pid, + (uint32_t)0, + (int32_t)PPM_EXE_UPPER_LAYER, + parent_pid, + parent_pid, + parent_pid, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + (uint32_t)0); // Check containers were added to the container cache - const sinsp_container_info::ptr_t container_info_check = m_inspector.m_container_manager.get_container(container.m_id); + const sinsp_container_info::ptr_t container_info_check = + m_inspector.m_container_manager.get_container(container.m_id); ASSERT_TRUE(container_info_check); ASSERT_EQ("1f04600dc694", container_info_check->m_id); - // Check container and k8s related filter fields that are retrieved from the container runtime socket + // Check container and k8s related filter fields that are retrieved from the container runtime + // socket ASSERT_EQ(get_field_as_string(evt, "container.id"), "1f04600dc694"); - ASSERT_EQ(get_field_as_string(evt, "container.full_id"), "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"); + ASSERT_EQ(get_field_as_string(evt, "container.full_id"), + "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"); ASSERT_EQ(get_field_as_string(evt, "container.ip"), "10.244.0.3"); - ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10.244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); + ASSERT_EQ(get_field_as_string(evt, "container.cni.json"), + "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:" + "76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":" + "\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/" + "dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10." + "244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/" + "0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); ASSERT_EQ(get_field_as_string(evt, "k8s.ns.name"), "redhat.test.crio"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.name"), "podsandbox1"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), "redhat-test-crio"); // legacy pod UID - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), "redhat-test-crio"); // legacy pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), + get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID ASSERT_EQ(get_field_as_string(evt, "k8s.pod.sandbox_id"), "1f04600dc694"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), + "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label.example-label/custom_one"), "mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label[example-label/custom_one]"), "mylabel"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), "app:myapp, example-label/custom_one:mylabel"); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), + "app:myapp, example-label/custom_one:mylabel"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.ip"), "10.244.0.3"); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10.244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); - - // Since this is a pod sandbox container, making it clear that container ID and sandbox ID are the same - ASSERT_EQ(get_field_as_string(evt, "container.id"), get_field_as_string(evt, "k8s.pod.sandbox_id")); + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), + "{\"cniVersion\":\"1.0.0\",\"interfaces\":[{\"name\":\"bridge\",\"mac\":\"ce:64:08:" + "76:88:6a\"},{\"name\":\"veth71b0e931\",\"mac\":\"72:b7:4f:bc:e4:a4\"},{\"name\":" + "\"eth0\",\"mac\":\"fe:06:00:f8:2f:4d\",\"sandbox\":\"/var/run/netns/" + "dec735d1-0e86-44c1-94e0-a102173334a4\"}],\"ips\":[{\"interface\":2,\"address\":\"10." + "244.0.3/16\",\"gateway\":\"10.244.0.1\"}],\"routes\":[{\"dst\":\"0.0.0.0/" + "0\",\"gw\":\"10.244.0.1\"}],\"dns\":{}}"); + + // Since this is a pod sandbox container, making it clear that container ID and sandbox ID are + // the same + ASSERT_EQ(get_field_as_string(evt, "container.id"), + get_field_as_string(evt, "k8s.pod.sandbox_id")); } -#endif // MINIMAL_BUILD +#endif // MINIMAL_BUILD diff --git a/userspace/libsinsp/test/container_engine/cri_settings.ut.cpp b/userspace/libsinsp/test/container_engine/cri_settings.ut.cpp index fd5fa5b46b..1480bd3013 100644 --- a/userspace/libsinsp/test/container_engine/cri_settings.ut.cpp +++ b/userspace/libsinsp/test/container_engine/cri_settings.ut.cpp @@ -16,19 +16,17 @@ limitations under the License. */ -#if !defined(MINIMAL_BUILD) and !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all +#if !defined(MINIMAL_BUILD) and \ + !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all #include #include #include #include "../sinsp_with_test_input.h" - -TEST_F(sinsp_with_test_input, default_cri_socket_paths) -{ +TEST_F(sinsp_with_test_input, default_cri_socket_paths) { libsinsp::cri::cri_settings& cri_settings = libsinsp::cri::cri_settings::get(); - if (!cri_settings.get_cri_unix_socket_paths().empty()) - { + if(!cri_settings.get_cri_unix_socket_paths().empty()) { cri_settings.clear_cri_unix_socket_paths(); } @@ -38,8 +36,8 @@ TEST_F(sinsp_with_test_input, default_cri_socket_paths) auto socket_paths = cri_settings.get_cri_unix_socket_paths(); ASSERT_EQ(socket_paths.size(), 3); - ASSERT_TRUE("/run/containerd/containerd.sock"==socket_paths[0]); - ASSERT_TRUE("/run/crio/crio.sock"==socket_paths[1]); - ASSERT_TRUE("/run/k3s/containerd/containerd.sock"==socket_paths[2]); + ASSERT_TRUE("/run/containerd/containerd.sock" == socket_paths[0]); + ASSERT_TRUE("/run/crio/crio.sock" == socket_paths[1]); + ASSERT_TRUE("/run/k3s/containerd/containerd.sock" == socket_paths[2]); } #endif diff --git a/userspace/libsinsp/test/dns_manager.ut.cpp b/userspace/libsinsp/test/dns_manager.ut.cpp index fcc02a10a6..0c1b66c0d9 100644 --- a/userspace/libsinsp/test/dns_manager.ut.cpp +++ b/userspace/libsinsp/test/dns_manager.ut.cpp @@ -20,14 +20,13 @@ limitations under the License. #include #include -TEST(sinsp_dns_manager, simple_dns_manager_invocation) -{ - // Simple dummy test to assert that sinsp_dns_manager is invocated correctly - // and not leaking memory - const char* name = "bogus"; - uint64_t ts = 11111111111111; - uint32_t addr = 111111; - bool result = sinsp_dns_manager::get().match(name, AF_INET, &addr, ts); - ASSERT_FALSE(result); +TEST(sinsp_dns_manager, simple_dns_manager_invocation) { + // Simple dummy test to assert that sinsp_dns_manager is invocated correctly + // and not leaking memory + const char* name = "bogus"; + uint64_t ts = 11111111111111; + uint32_t addr = 111111; + bool result = sinsp_dns_manager::get().match(name, AF_INET, &addr, ts); + ASSERT_FALSE(result); } #endif diff --git a/userspace/libsinsp/test/eventformatter.ut.cpp b/userspace/libsinsp/test/eventformatter.ut.cpp index b3e358ed24..7bcd2acc9e 100644 --- a/userspace/libsinsp/test/eventformatter.ut.cpp +++ b/userspace/libsinsp/test/eventformatter.ut.cpp @@ -28,31 +28,26 @@ limitations under the License. #include #include -static std::string pretty_print(const std::map& in) -{ +static std::string pretty_print(const std::map& in) { std::string ret = "("; - for (const auto& v : in) - { - ret.append(" {'").append(v.first) - .append("','").append(v.second).append("'}"); + for(const auto& v : in) { + ret.append(" {'").append(v.first).append("','").append(v.second).append("'}"); } return ret.append(" )"); } -class sinsp_formatter_test : public sinsp_with_test_input -{ +class sinsp_formatter_test : public sinsp_with_test_input { public: - void SetUp() override - { + void SetUp() override { sinsp_with_test_input::SetUp(); add_default_init_thread(); open_inspector(); } - void format(const std::string& fmt, - sinsp_evt_formatter::output_format of = sinsp_evt_formatter::output_format::OF_NORMAL, - bool resolve_transformers = true) - { + void format( + const std::string& fmt, + sinsp_evt_formatter::output_format of = sinsp_evt_formatter::output_format::OF_NORMAL, + bool resolve_transformers = true) { sinsp_evt_formatter f(&m_inspector, fmt, m_filter_list); f.set_resolve_transformed_fields(resolve_transformers); auto evt = generate_getcwd_failed_entry_event(); @@ -65,30 +60,30 @@ class sinsp_formatter_test : public sinsp_with_test_input bool m_last_res = false; std::string m_last_output; std::vector m_last_field_names; - std::map m_last_field_values; + std::map m_last_field_values; sinsp_filter_check_list m_filter_list; }; -TEST_F(sinsp_formatter_test, field_names) -{ +TEST_F(sinsp_formatter_test, field_names) { format("this is a sample output %proc.name %fd.type %proc.pid"); EXPECT_EQ(m_last_field_names.size(), 3); - EXPECT_NE(find(m_last_field_names.begin(), m_last_field_names.end(), "proc.name"), m_last_field_names.end()); - EXPECT_NE(find(m_last_field_names.begin(), m_last_field_names.end(), "fd.type"), m_last_field_names.end()); - EXPECT_NE(find(m_last_field_names.begin(), m_last_field_names.end(), "proc.pid"), m_last_field_names.end()); + EXPECT_NE(find(m_last_field_names.begin(), m_last_field_names.end(), "proc.name"), + m_last_field_names.end()); + EXPECT_NE(find(m_last_field_names.begin(), m_last_field_names.end(), "fd.type"), + m_last_field_names.end()); + EXPECT_NE(find(m_last_field_names.begin(), m_last_field_names.end(), "proc.pid"), + m_last_field_names.end()); } -TEST_F(sinsp_formatter_test, invalid_tokens) -{ +TEST_F(sinsp_formatter_test, invalid_tokens) { EXPECT_THROW(format("start %some.field end"), sinsp_exception); EXPECT_THROW(format("start %a end"), sinsp_exception); EXPECT_THROW(format("start % end"), sinsp_exception); EXPECT_THROW(format("start %proc.name %"), sinsp_exception); } -TEST_F(sinsp_formatter_test, field) -{ +TEST_F(sinsp_formatter_test, field) { format("start %proc.name end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start init end"); @@ -96,8 +91,7 @@ TEST_F(sinsp_formatter_test, field) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, field_json) -{ +TEST_F(sinsp_formatter_test, field_json) { format("start %proc.name end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "{\"proc.name\":\"init\"}"); @@ -105,8 +99,7 @@ TEST_F(sinsp_formatter_test, field_json) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, lenght_shorter) -{ +TEST_F(sinsp_formatter_test, lenght_shorter) { format("start %2proc.name end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start in end"); @@ -114,8 +107,7 @@ TEST_F(sinsp_formatter_test, lenght_shorter) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, lenght_shorter_json) -{ +TEST_F(sinsp_formatter_test, lenght_shorter_json) { format("start %2proc.name end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "{\"proc.name\":\"init\"}"); @@ -123,8 +115,7 @@ TEST_F(sinsp_formatter_test, lenght_shorter_json) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, lenght_larger) -{ +TEST_F(sinsp_formatter_test, lenght_larger) { format("start %10proc.name end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start init end"); @@ -132,8 +123,7 @@ TEST_F(sinsp_formatter_test, lenght_larger) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, lenght_larger_json) -{ +TEST_F(sinsp_formatter_test, lenght_larger_json) { format("start %10proc.name end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "{\"proc.name\":\"init\"}"); @@ -141,8 +131,7 @@ TEST_F(sinsp_formatter_test, lenght_larger_json) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, multiple_fields) -{ +TEST_F(sinsp_formatter_test, multiple_fields) { format("start %proc.name %thread.tid end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start init 1 end"); @@ -151,8 +140,7 @@ TEST_F(sinsp_formatter_test, multiple_fields) EXPECT_EQ(m_last_field_values["thread.tid"], "1"); } -TEST_F(sinsp_formatter_test, multiple_fields_json) -{ +TEST_F(sinsp_formatter_test, multiple_fields_json) { format("start %proc.name %thread.tid end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "{\"proc.name\":\"init\",\"thread.tid\":1}"); @@ -161,8 +149,7 @@ TEST_F(sinsp_formatter_test, multiple_fields_json) EXPECT_EQ(m_last_field_values["thread.tid"], "1"); } -TEST_F(sinsp_formatter_test, multiple_fields_with_no_blank) -{ +TEST_F(sinsp_formatter_test, multiple_fields_with_no_blank) { format("start%proc.nameand%thread.tidend"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "startinitand1end"); @@ -171,8 +158,7 @@ TEST_F(sinsp_formatter_test, multiple_fields_with_no_blank) EXPECT_EQ(m_last_field_values["thread.tid"], "1"); } -TEST_F(sinsp_formatter_test, stop_on_null) -{ +TEST_F(sinsp_formatter_test, stop_on_null) { format("start %proc.name %evt.asynctype end"); EXPECT_EQ(m_last_res, false); EXPECT_EQ(m_last_output, "start init "); @@ -180,8 +166,7 @@ TEST_F(sinsp_formatter_test, stop_on_null) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, stop_on_null_json) -{ +TEST_F(sinsp_formatter_test, stop_on_null_json) { format("start %proc.name %evt.asynctype end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, false); EXPECT_EQ(m_last_output, "{\"proc.name\":\"init\"}"); @@ -189,8 +174,7 @@ TEST_F(sinsp_formatter_test, stop_on_null_json) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, continue_on_null) -{ +TEST_F(sinsp_formatter_test, continue_on_null) { format("*start %proc.name %evt.asynctype end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start init end"); @@ -199,8 +183,7 @@ TEST_F(sinsp_formatter_test, continue_on_null) EXPECT_EQ(m_last_field_values["evt.asynctype"], ""); } -TEST_F(sinsp_formatter_test, continue_on_null_json) -{ +TEST_F(sinsp_formatter_test, continue_on_null_json) { format("*start %proc.name %evt.asynctype end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "{\"evt.asynctype\":null,\"proc.name\":\"init\"}"); @@ -209,24 +192,21 @@ TEST_F(sinsp_formatter_test, continue_on_null_json) EXPECT_EQ(m_last_field_values["evt.asynctype"], ""); } -TEST_F(sinsp_formatter_test, no_fields) -{ +TEST_F(sinsp_formatter_test, no_fields) { format("start end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start end"); EXPECT_EQ(m_last_field_values.size(), 0) << pretty_print(m_last_field_values); } -TEST_F(sinsp_formatter_test, no_fields_json) -{ +TEST_F(sinsp_formatter_test, no_fields_json) { format("start end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "null"); EXPECT_EQ(m_last_field_values.size(), 0) << pretty_print(m_last_field_values); } -TEST_F(sinsp_formatter_test, field_with_args) -{ +TEST_F(sinsp_formatter_test, field_with_args) { format("start %proc.aname[0] end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start init end"); @@ -234,8 +214,7 @@ TEST_F(sinsp_formatter_test, field_with_args) EXPECT_EQ(m_last_field_values["proc.aname[0]"], "init"); } -TEST_F(sinsp_formatter_test, field_with_args_json) -{ +TEST_F(sinsp_formatter_test, field_with_args_json) { format("start %proc.aname[0] end", sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "{\"proc.aname[0]\":\"init\"}"); @@ -243,8 +222,7 @@ TEST_F(sinsp_formatter_test, field_with_args_json) EXPECT_EQ(m_last_field_values["proc.aname[0]"], "init"); } -TEST_F(sinsp_formatter_test, multiple_fields_with_args_no_blank) -{ +TEST_F(sinsp_formatter_test, multiple_fields_with_args_no_blank) { format("start%proc.aname[0]and%proc.apid[0]end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "startinitand1end"); @@ -253,8 +231,7 @@ TEST_F(sinsp_formatter_test, multiple_fields_with_args_no_blank) EXPECT_EQ(m_last_field_values["proc.apid[0]"], "1"); } -TEST_F(sinsp_formatter_test, invalid_transformers) -{ +TEST_F(sinsp_formatter_test, invalid_transformers) { ASSERT_THROW(format("start %some_transformer(proc.aname) end"), sinsp_exception); ASSERT_THROW(format("start %val(proc.aname) end"), sinsp_exception); ASSERT_THROW(format("start %(proc.aname) end"), sinsp_exception); @@ -266,7 +243,7 @@ TEST_F(sinsp_formatter_test, invalid_transformers) ASSERT_THROW(format("start %toupper(val(proc.aname)"), sinsp_exception); ASSERT_THROW(format("start %touper("), sinsp_exception); ASSERT_THROW(format("start %("), sinsp_exception); - ASSERT_THROW(format("start %toupper(evt.num) end"), sinsp_exception); // wrong type + ASSERT_THROW(format("start %toupper(evt.num) end"), sinsp_exception); // wrong type // note: whitespaces are not allowed between transformers ASSERT_THROW(format("start %toupper (proc.name) end"), sinsp_exception); @@ -279,8 +256,7 @@ TEST_F(sinsp_formatter_test, invalid_transformers) ASSERT_THROW(format("start %toupper( tolower( proc.name ) ) end"), sinsp_exception); } -TEST_F(sinsp_formatter_test, field_with_transformer) -{ +TEST_F(sinsp_formatter_test, field_with_transformer) { format("start %toupper(proc.name) end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start INIT end"); @@ -289,8 +265,7 @@ TEST_F(sinsp_formatter_test, field_with_transformer) EXPECT_EQ(m_last_field_values["toupper(proc.name)"], "INIT"); } -TEST_F(sinsp_formatter_test, field_with_transformer_excluded) -{ +TEST_F(sinsp_formatter_test, field_with_transformer_excluded) { auto of = sinsp_evt_formatter::output_format::OF_NORMAL; format("start %toupper(proc.name) end", of, false); EXPECT_EQ(m_last_res, true); @@ -299,8 +274,7 @@ TEST_F(sinsp_formatter_test, field_with_transformer_excluded) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, field_with_transformer_excluded_json) -{ +TEST_F(sinsp_formatter_test, field_with_transformer_excluded_json) { auto of = sinsp_evt_formatter::output_format::OF_JSON; format("start %toupper(proc.name) end", of, false); EXPECT_EQ(m_last_res, true); @@ -309,8 +283,7 @@ TEST_F(sinsp_formatter_test, field_with_transformer_excluded_json) EXPECT_EQ(m_last_field_values["proc.name"], "init"); } -TEST_F(sinsp_formatter_test, field_with_transformer_and_arg) -{ +TEST_F(sinsp_formatter_test, field_with_transformer_and_arg) { format("start %toupper(evt.arg[1]) end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start /TEST/DIR end"); @@ -319,8 +292,7 @@ TEST_F(sinsp_formatter_test, field_with_transformer_and_arg) EXPECT_EQ(m_last_field_values["toupper(evt.arg[1])"], "/TEST/DIR"); } -TEST_F(sinsp_formatter_test, field_with_nested_transformer) -{ +TEST_F(sinsp_formatter_test, field_with_nested_transformer) { format("start %tolower(toupper(proc.name)) end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start init end"); @@ -329,8 +301,7 @@ TEST_F(sinsp_formatter_test, field_with_nested_transformer) EXPECT_EQ(m_last_field_values["tolower(toupper(proc.name))"], "init"); } -TEST_F(sinsp_formatter_test, field_with_nested_transformer_and_arg) -{ +TEST_F(sinsp_formatter_test, field_with_nested_transformer_and_arg) { format("start %tolower(toupper(evt.arg[1])) end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start /test/dir end"); @@ -339,8 +310,7 @@ TEST_F(sinsp_formatter_test, field_with_nested_transformer_and_arg) EXPECT_EQ(m_last_field_values["tolower(toupper(evt.arg[1]))"], "/test/dir"); } -TEST_F(sinsp_formatter_test, multiple_fields_with_transformer) -{ +TEST_F(sinsp_formatter_test, multiple_fields_with_transformer) { format("start %toupper(proc.name) %toupper(evt.arg.path) end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start INIT /TEST/DIR end"); @@ -351,11 +321,13 @@ TEST_F(sinsp_formatter_test, multiple_fields_with_transformer) EXPECT_EQ(m_last_field_values["toupper(evt.arg.path)"], "/TEST/DIR"); } -TEST_F(sinsp_formatter_test, multiple_fields_with_transformer_json) -{ - format("start %toupper(proc.name) %toupper(evt.arg.path) end", sinsp_evt_formatter::output_format::OF_JSON); +TEST_F(sinsp_formatter_test, multiple_fields_with_transformer_json) { + format("start %toupper(proc.name) %toupper(evt.arg.path) end", + sinsp_evt_formatter::output_format::OF_JSON); EXPECT_EQ(m_last_res, true); - EXPECT_EQ(m_last_output, "{\"evt.arg.path\":\"/test/dir\",\"proc.name\":\"init\",\"toupper(evt.arg.path)\":\"/TEST/DIR\",\"toupper(proc.name)\":\"INIT\"}"); + EXPECT_EQ(m_last_output, + "{\"evt.arg.path\":\"/test/dir\",\"proc.name\":\"init\",\"toupper(evt.arg.path)\":\"/" + "TEST/DIR\",\"toupper(proc.name)\":\"INIT\"}"); EXPECT_EQ(m_last_field_values.size(), 4) << pretty_print(m_last_field_values); EXPECT_EQ(m_last_field_values["proc.name"], "init"); EXPECT_EQ(m_last_field_values["evt.arg.path"], "/test/dir"); @@ -363,8 +335,7 @@ TEST_F(sinsp_formatter_test, multiple_fields_with_transformer_json) EXPECT_EQ(m_last_field_values["toupper(evt.arg.path)"], "/TEST/DIR"); } -TEST_F(sinsp_formatter_test, multiple_fields_with_transformer_no_blank) -{ +TEST_F(sinsp_formatter_test, multiple_fields_with_transformer_no_blank) { format("start%toupper(proc.name)and%toupper(evt.arg.path)end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "startINITand/TEST/DIRend"); @@ -375,8 +346,7 @@ TEST_F(sinsp_formatter_test, multiple_fields_with_transformer_no_blank) EXPECT_EQ(m_last_field_values["toupper(evt.arg.path)"], "/TEST/DIR"); } -TEST_F(sinsp_formatter_test, lenght_shorter_with_transformer) -{ +TEST_F(sinsp_formatter_test, lenght_shorter_with_transformer) { format("start %2toupper(proc.name) end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start IN end"); @@ -385,8 +355,7 @@ TEST_F(sinsp_formatter_test, lenght_shorter_with_transformer) EXPECT_EQ(m_last_field_values["toupper(proc.name)"], "INIT"); } -TEST_F(sinsp_formatter_test, lenght_larger_with_transformer) -{ +TEST_F(sinsp_formatter_test, lenght_larger_with_transformer) { format("start %10toupper(proc.name) end"); EXPECT_EQ(m_last_res, true); EXPECT_EQ(m_last_output, "start INIT end"); diff --git a/userspace/libsinsp/test/events_evt.ut.cpp b/userspace/libsinsp/test/events_evt.ut.cpp index ac5ac4b648..0c223eba96 100644 --- a/userspace/libsinsp/test/events_evt.ut.cpp +++ b/userspace/libsinsp/test/events_evt.ut.cpp @@ -22,19 +22,25 @@ limitations under the License. #include #include "test_utils.h" -TEST_F(sinsp_with_test_input, event_category) -{ +TEST_F(sinsp_with_test_input, event_category) { add_default_init_thread(); open_inspector(); - sinsp_evt* evt = NULL; + sinsp_evt *evt = NULL; std::string syscall_source_name = sinsp_syscall_event_source_name; int64_t fd = 4, mountfd = 5, test_errno = 0; /* Check that `EC_SYSCALL` category is not considered */ add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, 4, fd, mountfd, PPM_O_RDWR, "/tmp/the_file.txt"); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + 4, + fd, + mountfd, + PPM_O_RDWR, + "/tmp/the_file.txt"); ASSERT_EQ(evt->get_category(), EC_FILE); ASSERT_EQ(get_field_as_string(evt, "evt.category"), "file"); ASSERT_EQ(get_field_as_string(evt, "evt.source"), syscall_source_name); @@ -42,7 +48,14 @@ TEST_F(sinsp_with_test_input, event_category) ASSERT_EQ(get_field_as_string(evt, "evt.num"), "2"); /* Check that `EC_TRACEPOINT` category is not considered */ - evt = add_event_advance_ts(increasing_ts(), 1, PPME_PROCEXIT_1_E, 4, test_errno, test_errno, (uint8_t)0, (uint8_t)0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_PROCEXIT_1_E, + 4, + test_errno, + test_errno, + (uint8_t)0, + (uint8_t)0); ASSERT_EQ(evt->get_category(), EC_PROCESS); ASSERT_EQ(get_field_as_string(evt, "evt.category"), "process"); ASSERT_EQ(get_field_as_string(evt, "evt.source"), syscall_source_name); @@ -58,16 +71,20 @@ TEST_F(sinsp_with_test_input, event_category) ASSERT_EQ(get_field_as_string(evt, "evt.num"), "4"); } -TEST_F(sinsp_with_test_input, event_res) -{ +TEST_F(sinsp_with_test_input, event_res) { add_default_init_thread(); open_inspector(); - sinsp_evt * evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_E, 1, (uint32_t)-1); + sinsp_evt *evt = + add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_E, 1, (uint32_t)-1); EXPECT_FALSE(field_has_value(evt, "evt.res")); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_X, 1, (int64_t)-SE_EINVAL); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EPOLL_CREATE_X, + 1, + (int64_t)-SE_EINVAL); EXPECT_EQ(get_field_as_string(evt, "evt.res"), "EINVAL"); EXPECT_EQ(get_field_as_string(evt, "evt.rawres"), "-22"); @@ -75,22 +92,52 @@ TEST_F(sinsp_with_test_input, event_res) EXPECT_EQ(get_field_as_string(evt, "evt.failed"), "true"); EXPECT_EQ(get_field_as_string(evt, "evt.count.error"), "1"); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_E, 1, (uint32_t) 100); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_X, 1, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_E, 1, (uint32_t)100); + evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_X, 1, (uint64_t)0); EXPECT_EQ(get_field_as_string(evt, "evt.res"), "SUCCESS"); EXPECT_EQ(get_field_as_string(evt, "evt.rawres"), "0"); EXPECT_EQ(get_field_as_string(evt, "evt.failed"), "false"); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file.txt", 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (int64_t)123, "/tmp/the_file.txt", 0, 0, 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file.txt", + 0, + 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (int64_t)123, + "/tmp/the_file.txt", + 0, + 0, + 0, + (uint64_t)0); EXPECT_EQ(get_field_as_string(evt, "evt.res"), "SUCCESS"); EXPECT_EQ(get_field_as_string(evt, "evt.rawres"), "123"); EXPECT_EQ(get_field_as_string(evt, "evt.failed"), "false"); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file.txt", 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (int64_t)-SE_EACCES, "/tmp/the_file.txt", 0, 0, 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file.txt", + 0, + 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (int64_t)-SE_EACCES, + "/tmp/the_file.txt", + 0, + 0, + 0, + (uint64_t)0); EXPECT_EQ(get_field_as_string(evt, "evt.res"), "EACCES"); EXPECT_EQ(get_field_as_string(evt, "evt.rawres"), std::to_string(-SE_EACCES).c_str()); @@ -99,8 +146,7 @@ TEST_F(sinsp_with_test_input, event_res) EXPECT_EQ(get_field_as_string(evt, "evt.count.error.file"), "1"); } -TEST_F(sinsp_with_test_input, event_hostname) -{ +TEST_F(sinsp_with_test_input, event_hostname) { #ifdef __linux__ /* Set temporary env variable for hostname. * libscap cmake defaults to `set(SCAP_HOSTNAME_ENV_VAR "SCAP_HOSTNAME")` @@ -119,7 +165,16 @@ TEST_F(sinsp_with_test_input, event_hostname) int64_t dirfd = 3; const char *file_to_run = "/tmp/file_to_run"; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, file_to_run, 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, file_to_run, 0, 0, 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + file_to_run, + 0, + 0, + 0, + (uint64_t)0); /* Assert correct custom hostname. */ ASSERT_EQ(get_field_as_string(evt, "evt.hostname"), hostname); diff --git a/userspace/libsinsp/test/events_file.ut.cpp b/userspace/libsinsp/test/events_file.ut.cpp index 6d66dbc88e..e2d466b0c2 100644 --- a/userspace/libsinsp/test/events_file.ut.cpp +++ b/userspace/libsinsp/test/events_file.ut.cpp @@ -23,7 +23,7 @@ limitations under the License. #include #include -#define ASSERT_FD_FILTER_CHECK_NOT_FILE() \ +#define ASSERT_FD_FILTER_CHECK_NOT_FILE() \ ASSERT_EQ(get_field_as_string(evt, "fd.name"), ""); \ ASSERT_EQ(get_field_as_string(evt, "fd.l4proto"), ""); \ ASSERT_EQ(get_field_as_string(evt, "fd.is_server"), "false"); \ @@ -35,7 +35,7 @@ limitations under the License. ASSERT_EQ(get_field_as_string(evt, "fd.dev.minor"), "0"); \ ASSERT_EQ(get_field_as_string(evt, "fd.nameraw"), ""); -#define ASSERT_FD_GETTERS_NOT_FILE(x) \ +#define ASSERT_FD_GETTERS_NOT_FILE(x) \ ASSERT_EQ(x->m_name, ""); \ ASSERT_EQ(x->m_name_raw, ""); \ ASSERT_EQ(x->m_oldname, ""); \ @@ -51,8 +51,7 @@ limitations under the License. ASSERT_FALSE(x->is_file()); \ ASSERT_FALSE(x->is_directory()); -TEST_F(sinsp_with_test_input, file_open) -{ +TEST_F(sinsp_with_test_input, file_open) { add_default_init_thread(); open_inspector(); @@ -60,8 +59,23 @@ TEST_F(sinsp_with_test_input, file_open) // since adding and reading events happens on a single thread they can be interleaved. // tests may need to change if that will not be the case anymore - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", (uint32_t) PPM_O_RDWR, (uint32_t) 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (uint64_t)3, "/tmp/the_file", (uint32_t) PPM_O_RDWR, (uint32_t) 0, (uint32_t) 5, (uint64_t)123); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + (uint32_t)PPM_O_RDWR, + (uint32_t)0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)3, + "/tmp/the_file", + (uint32_t)PPM_O_RDWR, + (uint32_t)0, + (uint32_t)5, + (uint64_t)123); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_OPEN_X); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/the_file"); @@ -69,8 +83,7 @@ TEST_F(sinsp_with_test_input, file_open) ASSERT_EQ(get_field_as_string(evt, "fd.filename"), "the_file"); } -TEST_F(sinsp_with_test_input, dup_dup2_dup3) -{ +TEST_F(sinsp_with_test_input, dup_dup2_dup3) { add_default_init_thread(); open_inspector(); @@ -78,8 +91,23 @@ TEST_F(sinsp_with_test_input, dup_dup2_dup3) int64_t fd = 3, res = 1, oldfd = 3, newfd = 123; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/test", (uint32_t) (PPM_O_TRUNC | PPM_O_CREAT | PPM_O_WRONLY), (uint32_t) 0666); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, "/tmp/test", (uint32_t) (PPM_O_TRUNC | PPM_O_CREAT | PPM_O_WRONLY), (uint32_t) 0666, (uint32_t) 0xCA02, (uint64_t)123); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/test", + (uint32_t)(PPM_O_TRUNC | PPM_O_CREAT | PPM_O_WRONLY), + (uint32_t)0666); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + "/tmp/test", + (uint32_t)(PPM_O_TRUNC | PPM_O_CREAT | PPM_O_WRONLY), + (uint32_t)0666, + (uint32_t)0xCA02, + (uint64_t)123); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP_E, 1, fd); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP_X, 1, newfd); @@ -107,8 +135,7 @@ TEST_F(sinsp_with_test_input, dup_dup2_dup3) ASSERT_EQ(get_field_as_string(evt, "fd.num"), "1"); } -TEST_F(sinsp_with_test_input, open_by_handle_at) -{ +TEST_F(sinsp_with_test_input, open_by_handle_at) { add_default_init_thread(); open_inspector(); @@ -117,7 +144,14 @@ TEST_F(sinsp_with_test_input, open_by_handle_at) int64_t fd = 4, mountfd = 5; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, 4, fd, mountfd, PPM_O_RDWR, "/tmp/the_file.txt"); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + 4, + fd, + mountfd, + PPM_O_RDWR, + "/tmp/the_file.txt"); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/the_file.txt"); ASSERT_EQ(get_field_as_string(evt, "evt.abspath"), "/tmp/the_file.txt"); @@ -125,13 +159,19 @@ TEST_F(sinsp_with_test_input, open_by_handle_at) fd = 6; mountfd = 7; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, 4, fd, mountfd, PPM_O_RDWR, ""); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + 4, + fd, + mountfd, + PPM_O_RDWR, + ""); ASSERT_EQ(get_field_as_string(evt, "fd.name"), ""); } -TEST_F(sinsp_with_test_input, path_too_long) -{ +TEST_F(sinsp_with_test_input, path_too_long) { add_default_init_thread(); open_inspector(); @@ -150,27 +190,54 @@ TEST_F(sinsp_with_test_input, path_too_long) std::string long_path = long_path_ss.str(); int64_t fd = 3, mountfd = 5; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, long_path.c_str(), (uint32_t) PPM_O_RDWR, (uint32_t) 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, long_path.c_str(), (uint32_t) PPM_O_RDWR, (uint32_t) 0, (uint32_t) 5, (uint64_t)123); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + long_path.c_str(), + (uint32_t)PPM_O_RDWR, + (uint32_t)0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + long_path.c_str(), + (uint32_t)PPM_O_RDWR, + (uint32_t)0, + (uint32_t)5, + (uint64_t)123); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/PATH_TOO_LONG"); fd = 4; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, 4, fd, mountfd, PPM_O_RDWR, long_path.c_str()); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + 4, + fd, + mountfd, + PPM_O_RDWR, + long_path.c_str()); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/PATH_TOO_LONG"); ASSERT_EQ(get_field_as_string(evt, "evt.abspath"), "/PATH_TOO_LONG"); } -TEST_F(sinsp_with_test_input, creates_fd_generic) -{ +TEST_F(sinsp_with_test_input, creates_fd_generic) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; int64_t fd = 5; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_SIGNALFD_E, 3, (uint64_t)-1, 0, (uint8_t)0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_SIGNALFD_E, + 3, + (uint64_t)-1, + 0, + (uint8_t)0); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_SIGNALFD_X, 1, fd); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "signalfd"); ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "s"); @@ -184,7 +251,12 @@ TEST_F(sinsp_with_test_input, creates_fd_generic) ASSERT_EQ(get_field_as_string(evt, "fd.num"), "2"); fd = 6; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_TIMERFD_CREATE_E, 2, (uint8_t)0, (uint8_t)0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_TIMERFD_CREATE_E, + 2, + (uint8_t)0, + (uint8_t)0); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_TIMERFD_CREATE_X, 1, fd); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "timerfd"); ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "t"); @@ -213,7 +285,18 @@ TEST_F(sinsp_with_test_input, creates_fd_generic) fd = 10; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_IO_URING_SETUP_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_IO_URING_SETUP_X, 8, fd, 0, 0, 0, 0, 0, 0, 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_IO_URING_SETUP_X, + 8, + fd, + 0, + 0, + 0, + 0, + 0, + 0, + 0); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "io_uring"); ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "r"); ASSERT_EQ(get_field_as_string(evt, "fd.num"), "10"); @@ -234,19 +317,39 @@ TEST_F(sinsp_with_test_input, creates_fd_generic) int64_t fd1 = 3, fd2 = 4; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE_X, 4, (int64_t) 0, fd1, fd2, (uint64_t)81976492); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_PIPE_X, + 4, + (int64_t)0, + fd1, + fd2, + (uint64_t)81976492); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "pipe"); ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "p"); ASSERT_EQ(get_field_as_string(evt, "fd.num"), "4"); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE2_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE2_X, 5, (int64_t) 0, (int64_t)6, (int64_t)7, (uint64_t)81976492, (uint32_t)17); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_PIPE2_X, + 5, + (int64_t)0, + (int64_t)6, + (int64_t)7, + (uint64_t)81976492, + (uint32_t)17); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "pipe"); ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "p"); ASSERT_EQ(get_field_as_string(evt, "fd.num"), "7"); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_INOTIFY_INIT1_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_INOTIFY_INIT1_X, 2, (int64_t)12, (uint16_t)32); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_INOTIFY_INIT1_X, + 2, + (int64_t)12, + (uint16_t)32); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "inotify"); ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "i"); ASSERT_EQ(get_field_as_string(evt, "fd.num"), "12"); @@ -258,14 +361,18 @@ TEST_F(sinsp_with_test_input, creates_fd_generic) ASSERT_EQ(get_field_as_string(evt, "fd.num"), "34"); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EVENTFD2_E, 1, (uint64_t)0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EVENTFD2_X, 2, (int64_t)31, (uint16_t)34); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EVENTFD2_X, + 2, + (int64_t)31, + (uint16_t)34); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "event"); ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "e"); ASSERT_EQ(get_field_as_string(evt, "fd.num"), "31"); } -TEST_F(sinsp_with_test_input, umount) -{ +TEST_F(sinsp_with_test_input, umount) { add_default_init_thread(); open_inspector(); @@ -284,8 +391,7 @@ TEST_F(sinsp_with_test_input, umount) ASSERT_EQ(fdinfo, nullptr); } -TEST_F(sinsp_with_test_input, umount2) -{ +TEST_F(sinsp_with_test_input, umount2) { add_default_init_thread(); open_inspector(); @@ -305,8 +411,7 @@ TEST_F(sinsp_with_test_input, umount2) ASSERT_EQ(fdinfo, nullptr); } -TEST_F(sinsp_with_test_input, pipe) -{ +TEST_F(sinsp_with_test_input, pipe) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -318,9 +423,10 @@ TEST_F(sinsp_with_test_input, pipe) add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE_E, 0); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE_X, 4, res, fd1, fd2, ino); - /* `pipe` is particular because it generates 2 file descriptors but a single event can have at most one `fdinfo` associated. - * So in this case the associated file descriptor is the second one (`4`). Please note that both file descriptors are added to - * thread info, but in the `m_fdinfo` field we find only the second file descriptor. + /* `pipe` is particular because it generates 2 file descriptors but a single event can have at + * most one `fdinfo` associated. So in this case the associated file descriptor is the second + * one (`4`). Please note that both file descriptors are added to thread info, but in the + * `m_fdinfo` field we find only the second file descriptor. */ /* Here we assert some info regarding the second file descriptor `4` through filter-checks */ @@ -338,7 +444,8 @@ TEST_F(sinsp_with_test_input, pipe) ASSERT_EQ(fdinfo2->m_openflags, 0); ASSERT_FD_GETTERS_NOT_FILE(fdinfo2) - /* Now we get the first file descriptor (`3`) and we assert some fields directly through the `fdinfo` pointer. */ + /* Now we get the first file descriptor (`3`) and we assert some fields directly through the + * `fdinfo` pointer. */ ASSERT_NE(evt->get_thread_info(), nullptr); sinsp_fdinfo* fdinfo1 = evt->get_thread_info()->get_fd(fd1); @@ -351,8 +458,7 @@ TEST_F(sinsp_with_test_input, pipe) ASSERT_FD_GETTERS_NOT_FILE(fdinfo1) } -TEST_F(sinsp_with_test_input, pipe2) -{ +TEST_F(sinsp_with_test_input, pipe2) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -363,11 +469,20 @@ TEST_F(sinsp_with_test_input, pipe2) uint32_t flags = 17; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE2_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIPE2_X, 5, res, fd1, fd2, ino, flags); - - /* `pipe2` is particular because it generates 2 file descriptors but a single event can have at most one `fdinfo` associated. - * So in this case the associated file descriptor is the second one (`4`). Please note that both file descriptors are added to - * thread info, but in the `m_fdinfo` field we find only the second file descriptor. + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_PIPE2_X, + 5, + res, + fd1, + fd2, + ino, + flags); + + /* `pipe2` is particular because it generates 2 file descriptors but a single event can have at + * most one `fdinfo` associated. So in this case the associated file descriptor is the second + * one (`4`). Please note that both file descriptors are added to thread info, but in the + * `m_fdinfo` field we find only the second file descriptor. */ /* Here we assert some info regarding the second file descriptor `6` through filter-checks */ @@ -379,13 +494,15 @@ TEST_F(sinsp_with_test_input, pipe2) ASSERT_EQ(get_field_as_string(evt, "fd.ino"), std::to_string(ino)); ASSERT_FD_FILTER_CHECK_NOT_FILE() - /* Here we check the `openflags` field of the fdinfo2, it should be 17 since pipe2 has flags field */ + /* Here we check the `openflags` field of the fdinfo2, it should be 17 since pipe2 has flags + * field */ sinsp_fdinfo* fdinfo2 = evt->get_fd_info(); ASSERT_NE(fdinfo2, nullptr); ASSERT_EQ(fdinfo2->m_openflags, flags); ASSERT_FD_GETTERS_NOT_FILE(fdinfo2) - /* Now we get the first file descriptor (`3`) and we assert some fields directly through the `fdinfo` pointer. */ + /* Now we get the first file descriptor (`3`) and we assert some fields directly through the + * `fdinfo` pointer. */ ASSERT_NE(evt->get_thread_info(), nullptr); sinsp_fdinfo* fdinfo1 = evt->get_thread_info()->get_fd(fd1); ASSERT_NE(fdinfo1, nullptr); @@ -397,8 +514,7 @@ TEST_F(sinsp_with_test_input, pipe2) ASSERT_FD_GETTERS_NOT_FILE(fdinfo1) } -TEST_F(sinsp_with_test_input, inotify_init) -{ +TEST_F(sinsp_with_test_input, inotify_init) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -426,8 +542,7 @@ TEST_F(sinsp_with_test_input, inotify_init) ASSERT_FD_GETTERS_NOT_FILE(fdinfo) } -TEST_F(sinsp_with_test_input, inotify_init1) -{ +TEST_F(sinsp_with_test_input, inotify_init1) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -454,8 +569,7 @@ TEST_F(sinsp_with_test_input, inotify_init1) ASSERT_FD_GETTERS_NOT_FILE(fdinfo) } -TEST_F(sinsp_with_test_input, eventfd) -{ +TEST_F(sinsp_with_test_input, eventfd) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -484,8 +598,7 @@ TEST_F(sinsp_with_test_input, eventfd) ASSERT_FD_GETTERS_NOT_FILE(fdinfo) } -TEST_F(sinsp_with_test_input, eventfd2) -{ +TEST_F(sinsp_with_test_input, eventfd2) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -513,8 +626,7 @@ TEST_F(sinsp_with_test_input, eventfd2) ASSERT_FD_GETTERS_NOT_FILE(fdinfo) } -TEST_F(sinsp_with_test_input, signalfd) -{ +TEST_F(sinsp_with_test_input, signalfd) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -543,8 +655,7 @@ TEST_F(sinsp_with_test_input, signalfd) ASSERT_FD_GETTERS_NOT_FILE(fdinfo) } -TEST_F(sinsp_with_test_input, signalfd4) -{ +TEST_F(sinsp_with_test_input, signalfd4) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -573,12 +684,11 @@ TEST_F(sinsp_with_test_input, signalfd4) ASSERT_FD_GETTERS_NOT_FILE(fdinfo) } -TEST_F(sinsp_with_test_input, fchmod) -{ +TEST_F(sinsp_with_test_input, fchmod) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; - const char *path = "/tmp/test"; + const char* path = "/tmp/test"; int64_t fd = 3; int32_t flags = PPM_O_RDWR; uint32_t mode = 0; @@ -589,7 +699,16 @@ TEST_F(sinsp_with_test_input, fchmod) // We need to open a fd first so fchmod can act on it evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, path, flags, mode, dev, ino); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + path, + flags, + mode, + dev, + ino); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/test"); ASSERT_EQ(get_field_as_string(evt, "fd.num"), "3"); @@ -599,12 +718,11 @@ TEST_F(sinsp_with_test_input, fchmod) ASSERT_EQ(get_field_as_string(evt, "fd.num"), "3"); } -TEST_F(sinsp_with_test_input, fchown) -{ +TEST_F(sinsp_with_test_input, fchown) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; - const char *path = "/tmp/test"; + const char* path = "/tmp/test"; int64_t fd = 3; int32_t flags = PPM_O_RDWR; uint32_t mode = 0; @@ -617,7 +735,16 @@ TEST_F(sinsp_with_test_input, fchown) // We need to open a fd first so fchmod can act on it evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, path, flags, mode, dev, ino); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + path, + flags, + mode, + dev, + ino); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/test"); ASSERT_EQ(get_field_as_string(evt, "fd.num"), "3"); @@ -627,27 +754,24 @@ TEST_F(sinsp_with_test_input, fchown) ASSERT_EQ(get_field_as_string(evt, "fd.num"), "3"); } -TEST_F(sinsp_with_test_input, memfd_create) -{ +TEST_F(sinsp_with_test_input, memfd_create) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; - const char *name = "test_name"; + const char* name = "test_name"; int64_t fd = 4; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_MEMFD_CREATE_E, 0); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_MEMFD_CREATE_X, 3, fd, name, 0); - + ASSERT_EQ(evt->get_type(), PPME_SYSCALL_MEMFD_CREATE_X); ASSERT_EQ(get_field_as_string(evt, "fd.num"), std::to_string(fd)); ASSERT_EQ(get_field_as_string(evt, "fd.name"), name); - ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "m"); + ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "m"); ASSERT_EQ(get_field_as_string(evt, "fd.type"), "memfd"); - } -TEST_F(sinsp_with_test_input, test_fdtypes) -{ +TEST_F(sinsp_with_test_input, test_fdtypes) { add_default_init_thread(); open_inspector(); @@ -655,8 +779,23 @@ TEST_F(sinsp_with_test_input, test_fdtypes) // since adding and reading events happens on a single thread they can be interleaved. // tests may need to change if that will not be the case anymore - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", (uint32_t) PPM_O_RDWR, (uint32_t) 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (uint64_t) 1, "/tmp/the_file", (uint32_t) PPM_O_RDWR, (uint32_t) 0, (uint32_t) 5, (uint64_t) 123); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + (uint32_t)PPM_O_RDWR, + (uint32_t)0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)1, + "/tmp/the_file", + (uint32_t)PPM_O_RDWR, + (uint32_t)0, + (uint32_t)5, + (uint64_t)123); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_OPEN_X); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/the_file"); @@ -681,8 +820,7 @@ TEST_F(sinsp_with_test_input, test_fdtypes) ASSERT_EQ(get_field_as_string(evt, "fd.types"), "(bpf,file)"); } -TEST_F(sinsp_with_test_input, test_pidfd) -{ +TEST_F(sinsp_with_test_input, test_pidfd) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -692,25 +830,40 @@ TEST_F(sinsp_with_test_input, test_pidfd) int64_t fd = 4; /* Open a file descriptor */ - add_event_advance_ts(increasing_ts(), pid, PPME_SYSCALL_OPEN_X, 6, (uint64_t)target_fd, "/tmp/the_file", PPM_O_RDWR, 0, 5, (uint64_t)123); - + add_event_advance_ts(increasing_ts(), + pid, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)target_fd, + "/tmp/the_file", + PPM_O_RDWR, + 0, + 5, + (uint64_t)123); /* Create a pidfd using the same pid */ evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIDFD_OPEN_X, 3, pidfd, pid, 0); - + ASSERT_EQ(evt->get_type(), PPME_SYSCALL_PIDFD_OPEN_X); - ASSERT_EQ(get_field_as_string(evt,"fd.num"), std::to_string(pidfd)); - ASSERT_EQ(get_field_as_string(evt, "fd.typechar"),"P"); - ASSERT_EQ(get_field_as_string(evt, "fd.type"),"pidfd"); + ASSERT_EQ(get_field_as_string(evt, "fd.num"), std::to_string(pidfd)); + ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "P"); + ASSERT_EQ(get_field_as_string(evt, "fd.type"), "pidfd"); /* Duplicate the created fd created that is refrenced in pidfd */ - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PIDFD_GETFD_X, 4, fd, pidfd, target_fd, 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_PIDFD_GETFD_X, + 4, + fd, + pidfd, + target_fd, + 0); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_PIDFD_GETFD_X); - ASSERT_EQ(get_field_as_string(evt,"fd.num"), std::to_string(fd)); + ASSERT_EQ(get_field_as_string(evt, "fd.num"), std::to_string(fd)); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/the_file"); ASSERT_EQ(get_field_as_string(evt, "fd.directory"), "/tmp"); ASSERT_EQ(get_field_as_string(evt, "fd.filename"), "the_file"); - ASSERT_EQ(get_field_as_string(evt, "fd.typechar"),"f"); - ASSERT_EQ(get_field_as_string(evt, "fd.type"),"file"); + ASSERT_EQ(get_field_as_string(evt, "fd.typechar"), "f"); + ASSERT_EQ(get_field_as_string(evt, "fd.type"), "file"); } diff --git a/userspace/libsinsp/test/events_fspath.ut.cpp b/userspace/libsinsp/test/events_fspath.ut.cpp index 5168176304..6c992d7e8c 100644 --- a/userspace/libsinsp/test/events_fspath.ut.cpp +++ b/userspace/libsinsp/test/events_fspath.ut.cpp @@ -22,10 +22,8 @@ limitations under the License. #include -class fspath : public sinsp_with_test_input -{ +class fspath : public sinsp_with_test_input { protected: - const char *filename = "/tmp/random/dir.../..//../filename.txt"; const char *resolved_filename = "/tmp/filename.txt"; const char *rel_filename = "tmp/filename.txt"; @@ -33,10 +31,12 @@ class fspath : public sinsp_with_test_input const char *resolved_rel_filename2_cwd = "/root/tmp/name.txt"; const char *rel_filename_complex = "../\\.../../tmp/filename_complex"; - const char *resolved_rel_filename_complex = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/tmp/filename_complex"; + const char *resolved_rel_filename_complex = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/tmp/filename_complex"; const char *rel_filename_nopath = "nopath"; - const char *resolved_rel_filename_nopath = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/nopath"; + const char *resolved_rel_filename_nopath = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/nopath"; const char *path = "/tmp/path"; const char *dirfd_path = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8"; @@ -44,23 +44,28 @@ class fspath : public sinsp_with_test_input const char *name = "/tmp/random/dir...///../../name/"; const char *resolved_name = "/tmp/name"; const char *rel_name = "tmp/random/dir...///../../name.txt"; - const char *resolved_rel_name = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/name.txt"; + const char *resolved_rel_name = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/name.txt"; const char *oldpath = "/tmp/oldpath"; const char *newpath = "/tmp/newpath"; const char *rel_oldpath = "tmp/oldpath"; const char *rel_newpath = "tmp/newpath"; const char *resolved_rel_oldpath = "/root/tmp/oldpath"; - const char *resolved_rel_oldpath_at = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/oldpath"; + const char *resolved_rel_oldpath_at = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/oldpath"; const char *resolved_rel_newpath = "/root/tmp/newpath"; - const char *resolved_rel_newpath_at = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/newpath"; + const char *resolved_rel_newpath_at = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/newpath"; const char *linkpath = "/tmp/linkpath"; const char *targetpath = "/tmp/targetpath"; const char *rel_linkpath = "tmp/linkpath"; const char *rel_targetpath = "tmp/targetpath"; const char *resolved_rel_linkpath = "/root/tmp/linkpath"; - const char *resolved_rel_linkpath_at = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/linkpath"; + const char *resolved_rel_linkpath_at = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/linkpath"; const char *resolved_rel_targetpath = "/root/tmp/targetpath"; - const char *resolved_rel_targetpath_at = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/targetpath"; + const char *resolved_rel_targetpath_at = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/targetpath"; const char *mountpath = "/mnt/cdrom"; uint32_t mode = S_IFREG; int64_t res = 0; @@ -86,22 +91,28 @@ class fspath : public sinsp_with_test_input const char *fs_path_target = "fs.path.target"; const char *fs_path_targetraw = "fs.path.targetraw"; - void SetUp() - { + void SetUp() { sinsp_with_test_input::SetUp(); add_default_init_thread(); open_inspector(); } - void inject_open_event() - { - sinsp_evt * evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, path, open_flags, mode, dev, ino); + void inject_open_event() { + sinsp_evt *evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + path, + open_flags, + mode, + dev, + ino); ASSERT_STREQ(get_field_as_string(evt, "fd.name").c_str(), path); } - void verify_no_fields(sinsp_evt *evt) - { + void verify_no_fields(sinsp_evt *evt) { ASSERT_FALSE(field_has_value(evt, fs_path_name)); ASSERT_FALSE(field_has_value(evt, fs_path_nameraw)); ASSERT_FALSE(field_has_value(evt, fs_path_source)); @@ -110,15 +121,11 @@ class fspath : public sinsp_with_test_input ASSERT_FALSE(field_has_value(evt, fs_path_targetraw)); } - void verify_fd_name_same_fs_path_name(sinsp_evt *evt) - { + void verify_fd_name_same_fs_path_name(sinsp_evt *evt) { ASSERT_EQ(get_field_as_string(evt, fs_path_name), get_field_as_string(evt, "fd.name")); } - void verify_value_using_filters(sinsp_evt *evt, - const char *field, - const char *expected) - { + void verify_value_using_filters(sinsp_evt *evt, const char *field, const char *expected) { std::string fieldstr = field; std::string eq_filter_str = fieldstr + " = " + expected; @@ -131,98 +138,99 @@ class fspath : public sinsp_with_test_input EXPECT_TRUE(eval_filter(evt, pmatch_filter_str)); } - void verify_fields(ppm_event_code event_type, sinsp_evt *evt, - const char *expected_name, - const char *expected_nameraw, - const char *expected_source, - const char *expected_sourceraw, - const char *expected_target, - const char *expected_targetraw) - { - if(expected_name) - { + void verify_fields(ppm_event_code event_type, + sinsp_evt *evt, + const char *expected_name, + const char *expected_nameraw, + const char *expected_source, + const char *expected_sourceraw, + const char *expected_target, + const char *expected_targetraw) { + if(expected_name) { ASSERT_STREQ(get_field_as_string(evt, fs_path_name).c_str(), expected_name); verify_value_using_filters(evt, fs_path_name, expected_name); } - if(expected_nameraw) - { + if(expected_nameraw) { ASSERT_STREQ(get_field_as_string(evt, fs_path_nameraw).c_str(), expected_nameraw); verify_value_using_filters(evt, fs_path_nameraw, expected_nameraw); } - if(expected_source) - { + if(expected_source) { ASSERT_STREQ(get_field_as_string(evt, fs_path_source).c_str(), expected_source); verify_value_using_filters(evt, fs_path_source, expected_source); } - if(expected_sourceraw) - { + if(expected_sourceraw) { ASSERT_STREQ(get_field_as_string(evt, fs_path_sourceraw).c_str(), expected_sourceraw); verify_value_using_filters(evt, fs_path_sourceraw, expected_sourceraw); } - if(expected_target) - { + if(expected_target) { ASSERT_STREQ(get_field_as_string(evt, fs_path_target).c_str(), expected_target); verify_value_using_filters(evt, fs_path_target, expected_target); } - if(expected_targetraw) - { + if(expected_targetraw) { ASSERT_STREQ(get_field_as_string(evt, fs_path_targetraw).c_str(), expected_targetraw); verify_value_using_filters(evt, fs_path_targetraw, expected_targetraw); } - switch (event_type) - { - case PPME_SYSCALL_OPENAT_2_X: // involves dirfd resolution - case PPME_SYSCALL_OPENAT2_X: // involves dirfd resolution - case PPME_SYSCALL_OPEN_X: - case PPME_SYSCALL_OPEN_BY_HANDLE_AT_X: - { - verify_fd_name_same_fs_path_name(evt); - } - break; - default: - break; + switch(event_type) { + case PPME_SYSCALL_OPENAT_2_X: // involves dirfd resolution + case PPME_SYSCALL_OPENAT2_X: // involves dirfd resolution + case PPME_SYSCALL_OPEN_X: + case PPME_SYSCALL_OPEN_BY_HANDLE_AT_X: { + verify_fd_name_same_fs_path_name(evt); + } break; + default: + break; } } - void test_enter(ppm_event_code event_type, uint32_t n, ...) - { + void test_enter(ppm_event_code event_type, uint32_t n, ...) { va_list args; va_start(args, n); - sinsp_evt* evt = add_event_advance_ts_v(increasing_ts(), 1, event_type, n, args); + sinsp_evt *evt = add_event_advance_ts_v(increasing_ts(), 1, event_type, n, args); va_end(args); verify_no_fields(evt); } - void test_exit_path(const char *expected_name, const char *expected_name_raw, - ppm_event_code event_type, uint32_t n, ...) - { - + void test_exit_path(const char *expected_name, + const char *expected_name_raw, + ppm_event_code event_type, + uint32_t n, + ...) { va_list args; va_start(args, n); - sinsp_evt* evt; - switch (event_type) - { - case PPME_SYSCALL_OPENAT_2_X: - case PPME_SYSCALL_OPENAT2_X: - case PPME_SYSCALL_FCHMODAT_X: - case PPME_SYSCALL_FCHOWNAT_X: - case PPME_SYSCALL_UNLINKAT_2_X: - { - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT2_E, 2, evt_dirfd, dirfd_path); - // pass PPM_O_DIRECTORY since we are creating a folder! - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT2_X, 5, evt_dirfd, evt_dirfd, dirfd_path, open_flags | PPM_O_DIRECTORY, mode); - } - break; - default: - break; + sinsp_evt *evt; + switch(event_type) { + case PPME_SYSCALL_OPENAT_2_X: + case PPME_SYSCALL_OPENAT2_X: + case PPME_SYSCALL_FCHMODAT_X: + case PPME_SYSCALL_FCHOWNAT_X: + case PPME_SYSCALL_UNLINKAT_2_X: { + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT2_E, + 2, + evt_dirfd, + dirfd_path); + // pass PPM_O_DIRECTORY since we are creating a folder! + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT2_X, + 5, + evt_dirfd, + evt_dirfd, + dirfd_path, + open_flags | PPM_O_DIRECTORY, + mode); + } break; + default: + break; } - + evt = add_event_advance_ts_v(increasing_ts(), 1, event_type, n, args); va_end(args); @@ -230,202 +238,326 @@ class fspath : public sinsp_with_test_input } void test_exit_source_target(const char *expected_source, - const char *expected_sourceraw, - const char *expected_target, - const char *expected_targetraw, - ppm_event_code event_type, uint32_t n, ...) - { - + const char *expected_sourceraw, + const char *expected_target, + const char *expected_targetraw, + ppm_event_code event_type, + uint32_t n, + ...) { va_list args; va_start(args, n); - sinsp_evt* evt; - switch (event_type) - { - case PPME_SYSCALL_LINKAT_2_X: - case PPME_SYSCALL_SYMLINKAT_X: - case PPME_SYSCALL_RENAMEAT2_X: - { - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT2_E, 2, evt_dirfd, dirfd_path); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT2_X, 5, evt_dirfd, evt_dirfd, dirfd_path, open_flags | PPM_O_DIRECTORY, mode); - } - break; - default: - break; + sinsp_evt *evt; + switch(event_type) { + case PPME_SYSCALL_LINKAT_2_X: + case PPME_SYSCALL_SYMLINKAT_X: + case PPME_SYSCALL_RENAMEAT2_X: { + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT2_E, + 2, + evt_dirfd, + dirfd_path); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT2_X, + 5, + evt_dirfd, + evt_dirfd, + dirfd_path, + open_flags | PPM_O_DIRECTORY, + mode); + } break; + default: + break; } evt = add_event_advance_ts_v(increasing_ts(), 1, event_type, n, args); va_end(args); - verify_fields(event_type, evt, - NULL, NULL, - expected_source, expected_sourceraw, - expected_target, expected_targetraw); + verify_fields(event_type, + evt, + NULL, + NULL, + expected_source, + expected_sourceraw, + expected_target, + expected_targetraw); } - void test_failed_exit(ppm_event_code event_type, uint32_t n, ...) - { + void test_failed_exit(ppm_event_code event_type, uint32_t n, ...) { va_list args; va_start(args, n); - sinsp_evt* evt = add_event_advance_ts_v(increasing_ts(), 1, event_type, n, args); + sinsp_evt *evt = add_event_advance_ts_v(increasing_ts(), 1, event_type, n, args); va_end(args); verify_no_fields(evt); } }; -TEST_F(fspath, mkdir) -{ +TEST_F(fspath, mkdir) { test_enter(PPME_SYSCALL_MKDIR_E, 2, path, mode); test_exit_path(path, path, PPME_SYSCALL_MKDIR_X, 1, res); test_failed_exit(PPME_SYSCALL_MKDIR_X, 1, failed_res); } -TEST_F(fspath, mkdir_2) -{ +TEST_F(fspath, mkdir_2) { test_enter(PPME_SYSCALL_MKDIR_2_E, 1, mode); test_exit_path(path, path, PPME_SYSCALL_MKDIR_2_X, 2, res, path); test_failed_exit(PPME_SYSCALL_MKDIR_2_X, 2, failed_res, path); } -TEST_F(fspath, mkdirat) -{ +TEST_F(fspath, mkdirat) { test_enter(PPME_SYSCALL_MKDIRAT_E, 0); test_exit_path(path, path, PPME_SYSCALL_MKDIRAT_X, 4, res, evt_dirfd, path, mode); test_failed_exit(PPME_SYSCALL_MKDIRAT_X, 4, failed_res, evt_dirfd, path, mode); } -TEST_F(fspath, rmdir) -{ +TEST_F(fspath, rmdir) { test_enter(PPME_SYSCALL_RMDIR_E, 1, path); test_exit_path(path, path, PPME_SYSCALL_RMDIR_X, 1, res); test_failed_exit(PPME_SYSCALL_RMDIR_X, 1, failed_res); } -TEST_F(fspath, rmdir_2) -{ +TEST_F(fspath, rmdir_2) { test_enter(PPME_SYSCALL_RMDIR_2_E, 0); test_exit_path(path, path, PPME_SYSCALL_RMDIR_2_X, 2, res, path); test_failed_exit(PPME_SYSCALL_RMDIR_2_X, 2, failed_res, path); } -TEST_F(fspath, unlink) -{ +TEST_F(fspath, unlink) { test_enter(PPME_SYSCALL_UNLINK_E, 1, path); test_exit_path(path, path, PPME_SYSCALL_UNLINK_X, 1, res); test_failed_exit(PPME_SYSCALL_UNLINK_X, 1, failed_res); } -TEST_F(fspath, unlinkat) -{ +TEST_F(fspath, unlinkat) { test_enter(PPME_SYSCALL_UNLINKAT_E, 2, evt_dirfd, name); test_exit_path(resolved_name, name, PPME_SYSCALL_UNLINKAT_X, 1, res); test_failed_exit(PPME_SYSCALL_UNLINKAT_X, 1, failed_res); } -TEST_F(fspath, unlink_2) -{ +TEST_F(fspath, unlink_2) { test_enter(PPME_SYSCALL_UNLINK_2_E, 0); test_exit_path(path, path, PPME_SYSCALL_UNLINK_2_X, 2, res, path); test_failed_exit(PPME_SYSCALL_UNLINK_2_X, 2, failed_res, path); } -TEST_F(fspath, unlinkat_2) -{ +TEST_F(fspath, unlinkat_2) { test_enter(PPME_SYSCALL_UNLINKAT_2_E, 0); - test_exit_path(resolved_rel_name, rel_name, PPME_SYSCALL_UNLINKAT_2_X, 4, res, evt_dirfd, rel_name, flags); + test_exit_path(resolved_rel_name, + rel_name, + PPME_SYSCALL_UNLINKAT_2_X, + 4, + res, + evt_dirfd, + rel_name, + flags); test_failed_exit(PPME_SYSCALL_UNLINKAT_2_X, 4, failed_res, evt_dirfd, name, flags); } -TEST_F(fspath, open) -{ +TEST_F(fspath, open) { test_enter(PPME_SYSCALL_OPEN_E, 3, name, open_flags, mode); - test_exit_path(resolved_name, name, PPME_SYSCALL_OPEN_X, 6, fd, name, open_flags, mode, dev, ino); + test_exit_path(resolved_name, + name, + PPME_SYSCALL_OPEN_X, + 6, + fd, + name, + open_flags, + mode, + dev, + ino); test_failed_exit(PPME_SYSCALL_OPEN_X, 6, failed_res, "", open_flags, mode, dev, ino); } -TEST_F(fspath, openat) -{ +TEST_F(fspath, openat) { test_enter(PPME_SYSCALL_OPENAT_E, 4, evt_dirfd, name, open_flags, mode); test_exit_path(resolved_name, name, PPME_SYSCALL_OPENAT_X, 1, fd); test_failed_exit(PPME_SYSCALL_OPENAT_X, 6, failed_res); } -TEST_F(fspath, openat_2) -{ +TEST_F(fspath, openat_2) { test_enter(PPME_SYSCALL_OPENAT_2_E, 4, evt_dirfd, name, open_flags, mode); - test_exit_path(resolved_name, name, PPME_SYSCALL_OPENAT_2_X, 7, fd, evt_dirfd, name, open_flags, mode, dev, ino); - test_failed_exit(PPME_SYSCALL_OPENAT_2_X, 7, failed_res, evt_dirfd, name, open_flags, mode, dev, ino); -} - -TEST_F(fspath, openat_2_relative) -{ + test_exit_path(resolved_name, + name, + PPME_SYSCALL_OPENAT_2_X, + 7, + fd, + evt_dirfd, + name, + open_flags, + mode, + dev, + ino); + test_failed_exit(PPME_SYSCALL_OPENAT_2_X, + 7, + failed_res, + evt_dirfd, + name, + open_flags, + mode, + dev, + ino); +} + +TEST_F(fspath, openat_2_relative) { test_enter(PPME_SYSCALL_OPENAT_2_E, 4, evt_dirfd, name, open_flags, mode); - test_exit_path(resolved_rel_name, rel_name, PPME_SYSCALL_OPENAT_2_X, 7, fd, evt_dirfd, rel_name, open_flags, mode, dev, ino); - test_failed_exit(PPME_SYSCALL_OPENAT_2_X, 7, failed_res, evt_dirfd, name, open_flags, mode, dev, ino); -} - -TEST_F(fspath, openat2) -{ + test_exit_path(resolved_rel_name, + rel_name, + PPME_SYSCALL_OPENAT_2_X, + 7, + fd, + evt_dirfd, + rel_name, + open_flags, + mode, + dev, + ino); + test_failed_exit(PPME_SYSCALL_OPENAT_2_X, + 7, + failed_res, + evt_dirfd, + name, + open_flags, + mode, + dev, + ino); +} + +TEST_F(fspath, openat2) { test_enter(PPME_SYSCALL_OPENAT2_E, 5, evt_dirfd, name, open_flags, mode, resolve); - test_exit_path(resolved_name, name, PPME_SYSCALL_OPENAT2_X, 6, fd, evt_dirfd, name, open_flags, mode, resolve); - test_failed_exit(PPME_SYSCALL_OPENAT2_X, 6, failed_res, evt_dirfd, name, open_flags, mode, resolve); -} - -TEST_F(fspath, openat2_relative_dirfd) -{ + test_exit_path(resolved_name, + name, + PPME_SYSCALL_OPENAT2_X, + 6, + fd, + evt_dirfd, + name, + open_flags, + mode, + resolve); + test_failed_exit(PPME_SYSCALL_OPENAT2_X, + 6, + failed_res, + evt_dirfd, + name, + open_flags, + mode, + resolve); +} + +TEST_F(fspath, openat2_relative_dirfd) { test_enter(PPME_SYSCALL_OPENAT2_E, 5, evt_dirfd, name, open_flags, mode, resolve); - test_exit_path(resolved_rel_name, rel_name, PPME_SYSCALL_OPENAT2_X, 6, fd, evt_dirfd, rel_name, open_flags, mode, resolve); - test_failed_exit(PPME_SYSCALL_OPENAT2_X, 6, failed_res, evt_dirfd, name, open_flags, mode, resolve); -} - -TEST_F(fspath, openat2_relative_cwd) -{ - // Also test scenario where relative path should be interpreted relative to the cwd and not dirfd + test_exit_path(resolved_rel_name, + rel_name, + PPME_SYSCALL_OPENAT2_X, + 6, + fd, + evt_dirfd, + rel_name, + open_flags, + mode, + resolve); + test_failed_exit(PPME_SYSCALL_OPENAT2_X, + 6, + failed_res, + evt_dirfd, + name, + open_flags, + mode, + resolve); +} + +TEST_F(fspath, openat2_relative_cwd) { + // Also test scenario where relative path should be interpreted relative to the cwd and not + // dirfd test_enter(PPME_SYSCALL_OPENAT2_E, 5, evt_dirfd_cwd, name, open_flags, mode, resolve); - test_exit_path(resolved_rel_filename2_cwd, rel_name, PPME_SYSCALL_OPENAT2_X, 6, fd, evt_dirfd_cwd, rel_name, open_flags, mode, resolve); - test_failed_exit(PPME_SYSCALL_OPENAT2_X, 6, failed_res, evt_dirfd_cwd, name, open_flags, mode, resolve); -} - -TEST_F(fspath, fchmodat) -{ + test_exit_path(resolved_rel_filename2_cwd, + rel_name, + PPME_SYSCALL_OPENAT2_X, + 6, + fd, + evt_dirfd_cwd, + rel_name, + open_flags, + mode, + resolve); + test_failed_exit(PPME_SYSCALL_OPENAT2_X, + 6, + failed_res, + evt_dirfd_cwd, + name, + open_flags, + mode, + resolve); +} + +TEST_F(fspath, fchmodat) { test_enter(PPME_SYSCALL_FCHMODAT_E, 0); - test_exit_path(resolved_filename, filename, PPME_SYSCALL_FCHMODAT_X, 4, res, evt_dirfd, filename, mode); + test_exit_path(resolved_filename, + filename, + PPME_SYSCALL_FCHMODAT_X, + 4, + res, + evt_dirfd, + filename, + mode); test_failed_exit(PPME_SYSCALL_FCHMODAT_X, 4, failed_res, evt_dirfd, filename, mode); } -TEST_F(fspath, fchmodat_relative) -{ +TEST_F(fspath, fchmodat_relative) { test_enter(PPME_SYSCALL_FCHMODAT_E, 0); - test_exit_path(resolved_rel_name, rel_name, PPME_SYSCALL_FCHMODAT_X, 4, res, evt_dirfd, rel_name, mode); + test_exit_path(resolved_rel_name, + rel_name, + PPME_SYSCALL_FCHMODAT_X, + 4, + res, + evt_dirfd, + rel_name, + mode); } -TEST_F(fspath, fchmodat_relative_complex) -{ - +TEST_F(fspath, fchmodat_relative_complex) { test_enter(PPME_SYSCALL_FCHMODAT_E, 0); - test_exit_path(resolved_rel_filename_complex, rel_filename_complex, PPME_SYSCALL_FCHMODAT_X, 4, res, evt_dirfd, rel_filename_complex, mode); + test_exit_path(resolved_rel_filename_complex, + rel_filename_complex, + PPME_SYSCALL_FCHMODAT_X, + 4, + res, + evt_dirfd, + rel_filename_complex, + mode); } -TEST_F(fspath, fchmodat_relative_nopath) -{ +TEST_F(fspath, fchmodat_relative_nopath) { test_enter(PPME_SYSCALL_FCHMODAT_E, 0); - test_exit_path(resolved_rel_filename_nopath, rel_filename_nopath, PPME_SYSCALL_FCHMODAT_X, 4, res, evt_dirfd, rel_filename_nopath, mode); + test_exit_path(resolved_rel_filename_nopath, + rel_filename_nopath, + PPME_SYSCALL_FCHMODAT_X, + 4, + res, + evt_dirfd, + rel_filename_nopath, + mode); } -TEST_F(fspath, chmod) -{ +TEST_F(fspath, chmod) { test_enter(PPME_SYSCALL_CHMOD_E, 0); test_exit_path(resolved_filename, filename, PPME_SYSCALL_CHMOD_X, 3, res, filename, mode); test_failed_exit(PPME_SYSCALL_CHMOD_X, 3, failed_res, filename, mode); } -TEST_F(fspath, chmod_relative) -{ +TEST_F(fspath, chmod_relative) { test_enter(PPME_SYSCALL_CHMOD_E, 0); - test_exit_path(resolved_rel_filename_cwd, rel_filename, PPME_SYSCALL_CHMOD_X, 3, res, rel_filename, mode); + test_exit_path(resolved_rel_filename_cwd, + rel_filename, + PPME_SYSCALL_CHMOD_X, + 3, + res, + rel_filename, + mode); } -TEST_F(fspath, fchmod) -{ +TEST_F(fspath, fchmod) { // We need to open a fd first so fchmod can act on it inject_open_event(); @@ -434,22 +566,19 @@ TEST_F(fspath, fchmod) test_failed_exit(PPME_SYSCALL_FCHMOD_X, 3, failed_res, fd, mode); } -TEST_F(fspath, chown) -{ +TEST_F(fspath, chown) { test_enter(PPME_SYSCALL_CHOWN_E, 0); test_exit_path(path, path, PPME_SYSCALL_CHOWN_X, 4, res, path, uid, gid); test_failed_exit(PPME_SYSCALL_CHOWN_X, 4, failed_res, path, uid, gid); } -TEST_F(fspath, lchown) -{ +TEST_F(fspath, lchown) { test_enter(PPME_SYSCALL_LCHOWN_E, 0); test_exit_path(path, path, PPME_SYSCALL_LCHOWN_X, 4, res, path, uid, gid); test_failed_exit(PPME_SYSCALL_LCHOWN_X, 4, failed_res, path, uid, gid); } -TEST_F(fspath, fchown) -{ +TEST_F(fspath, fchown) { // We need to open a fd first so fchown can act on it inject_open_event(); @@ -458,29 +587,44 @@ TEST_F(fspath, fchown) test_failed_exit(PPME_SYSCALL_FCHOWN_X, 4, failed_res, fd, uid, gid); } -TEST_F(fspath, fchownat) -{ +TEST_F(fspath, fchownat) { // the term "pathname" is only used for this syscall, so not putting at class level const char *pathname = "/tmp/pathname"; test_enter(PPME_SYSCALL_FCHOWNAT_E, 0); - test_exit_path(pathname, pathname, PPME_SYSCALL_FCHOWNAT_X, 6, res, evt_dirfd, pathname, uid, gid, flags); + test_exit_path(pathname, + pathname, + PPME_SYSCALL_FCHOWNAT_X, + 6, + res, + evt_dirfd, + pathname, + uid, + gid, + flags); test_failed_exit(PPME_SYSCALL_FCHOWNAT_X, 6, failed_res, evt_dirfd, pathname, uid, gid, flags); } -TEST_F(fspath, fchownat_relative) -{ - +TEST_F(fspath, fchownat_relative) { // the term "pathname" is only used for this syscall, so not putting at class level const char *rel_pathname = "tmp/pathname"; - const char *resolved_rel_pathname = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/pathname"; + const char *resolved_rel_pathname = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/pathname"; test_enter(PPME_SYSCALL_FCHOWNAT_E, 0); - test_exit_path(resolved_rel_pathname, rel_pathname, PPME_SYSCALL_FCHOWNAT_X, 6, res, evt_dirfd, rel_pathname, uid, gid, flags); -} - -TEST_F(fspath, quotactl) -{ + test_exit_path(resolved_rel_pathname, + rel_pathname, + PPME_SYSCALL_FCHOWNAT_X, + 6, + res, + evt_dirfd, + rel_pathname, + uid, + gid, + flags); +} + +TEST_F(fspath, quotactl) { // All of these are only used here so not putting in class uint16_t cmd = 0; uint8_t type = 0; @@ -500,166 +644,304 @@ TEST_F(fspath, quotactl) uint8_t quota_fmt_out = 0; test_enter(PPME_SYSCALL_QUOTACTL_E, 4, cmd, type, id, quota_fmt); - test_exit_path(path, path, PPME_SYSCALL_QUOTACTL_X, 14, res, path, quotafilepath, - dqb_bhardlimit, dqb_bsoftlimit, dqb_curspace, dqb_ihardlimit, - dqb_isoftlimit, dqb_btime, dqb_itime, dqi_bgrace, - dqi_igrace, dqi_flags, quota_fmt_out); - test_failed_exit(PPME_SYSCALL_QUOTACTL_X, 14, failed_res, path, quotafilepath, - dqb_bhardlimit, dqb_bsoftlimit, dqb_curspace, dqb_ihardlimit, - dqb_isoftlimit, dqb_btime, dqb_itime, dqi_bgrace, dqi_igrace, - dqi_flags, quota_fmt_out); -} - -TEST_F(fspath, rename) -{ + test_exit_path(path, + path, + PPME_SYSCALL_QUOTACTL_X, + 14, + res, + path, + quotafilepath, + dqb_bhardlimit, + dqb_bsoftlimit, + dqb_curspace, + dqb_ihardlimit, + dqb_isoftlimit, + dqb_btime, + dqb_itime, + dqi_bgrace, + dqi_igrace, + dqi_flags, + quota_fmt_out); + test_failed_exit(PPME_SYSCALL_QUOTACTL_X, + 14, + failed_res, + path, + quotafilepath, + dqb_bhardlimit, + dqb_bsoftlimit, + dqb_curspace, + dqb_ihardlimit, + dqb_isoftlimit, + dqb_btime, + dqb_itime, + dqi_bgrace, + dqi_igrace, + dqi_flags, + quota_fmt_out); +} + +TEST_F(fspath, rename) { test_enter(PPME_SYSCALL_RENAME_E, 0); - test_exit_source_target(oldpath, oldpath, newpath, newpath, PPME_SYSCALL_RENAME_X, 3, res, oldpath, newpath); + test_exit_source_target(oldpath, + oldpath, + newpath, + newpath, + PPME_SYSCALL_RENAME_X, + 3, + res, + oldpath, + newpath); test_failed_exit(PPME_SYSCALL_RENAME_X, 3, failed_res, oldpath, newpath); } -TEST_F(fspath, renameat) -{ +TEST_F(fspath, renameat) { test_enter(PPME_SYSCALL_RENAMEAT_E, 0); - test_exit_source_target(oldpath, oldpath, newpath, newpath, PPME_SYSCALL_RENAMEAT_X, 5, res, olddirfd, oldpath, newdirfd, newpath); + test_exit_source_target(oldpath, + oldpath, + newpath, + newpath, + PPME_SYSCALL_RENAMEAT_X, + 5, + res, + olddirfd, + oldpath, + newdirfd, + newpath); test_failed_exit(PPME_SYSCALL_RENAMEAT_X, 5, failed_res, olddirfd, oldpath, newdirfd, newpath); } -TEST_F(fspath, renameat2) -{ +TEST_F(fspath, renameat2) { test_enter(PPME_SYSCALL_RENAMEAT2_E, 0); - test_exit_source_target(oldpath, oldpath, newpath, newpath, PPME_SYSCALL_RENAMEAT2_X, 5, res, olddirfd, oldpath, newdirfd, newpath, flags); - test_failed_exit(PPME_SYSCALL_RENAMEAT2_X, 5, failed_res, olddirfd, oldpath, newdirfd, newpath, flags); -} - -TEST_F(fspath, renameat2_relative) -{ + test_exit_source_target(oldpath, + oldpath, + newpath, + newpath, + PPME_SYSCALL_RENAMEAT2_X, + 5, + res, + olddirfd, + oldpath, + newdirfd, + newpath, + flags); + test_failed_exit(PPME_SYSCALL_RENAMEAT2_X, + 5, + failed_res, + olddirfd, + oldpath, + newdirfd, + newpath, + flags); +} + +TEST_F(fspath, renameat2_relative) { test_enter(PPME_SYSCALL_RENAMEAT2_E, 0); - test_exit_source_target(resolved_rel_oldpath_at, rel_oldpath, - resolved_rel_newpath_at, rel_newpath, - PPME_SYSCALL_RENAMEAT2_X, 5, res, olddirfd, rel_oldpath, newdirfd, rel_newpath, flags); -} - -TEST_F(fspath, link) -{ + test_exit_source_target(resolved_rel_oldpath_at, + rel_oldpath, + resolved_rel_newpath_at, + rel_newpath, + PPME_SYSCALL_RENAMEAT2_X, + 5, + res, + olddirfd, + rel_oldpath, + newdirfd, + rel_newpath, + flags); +} + +TEST_F(fspath, link) { test_enter(PPME_SYSCALL_LINK_E, 2, oldpath, newpath); test_exit_source_target(newpath, newpath, oldpath, oldpath, PPME_SYSCALL_LINK_X, 1, res); test_failed_exit(PPME_SYSCALL_LINK_X, 1, failed_res); } -TEST_F(fspath, link_relative) -{ - +TEST_F(fspath, link_relative) { test_enter(PPME_SYSCALL_LINK_E, 2, rel_oldpath, rel_newpath); - test_exit_source_target(resolved_rel_newpath, rel_newpath, - resolved_rel_oldpath, rel_oldpath, - PPME_SYSCALL_LINK_X, 1, res); + test_exit_source_target(resolved_rel_newpath, + rel_newpath, + resolved_rel_oldpath, + rel_oldpath, + PPME_SYSCALL_LINK_X, + 1, + res); } -TEST_F(fspath, linkat) -{ +TEST_F(fspath, linkat) { test_enter(PPME_SYSCALL_LINKAT_E, 4, olddirfd, oldpath, newdirfd, newpath); test_exit_source_target(newpath, newpath, oldpath, oldpath, PPME_SYSCALL_LINKAT_X, 1, res); test_failed_exit(PPME_SYSCALL_LINKAT_X, 1, failed_res); } -TEST_F(fspath, linkat_relative) -{ +TEST_F(fspath, linkat_relative) { test_enter(PPME_SYSCALL_LINKAT_E, 4, olddirfd, rel_oldpath, newdirfd, rel_newpath); - test_exit_source_target(resolved_rel_newpath, rel_newpath, - resolved_rel_oldpath, rel_oldpath, - PPME_SYSCALL_LINKAT_X, 1, res); + test_exit_source_target(resolved_rel_newpath, + rel_newpath, + resolved_rel_oldpath, + rel_oldpath, + PPME_SYSCALL_LINKAT_X, + 1, + res); } -TEST_F(fspath, link_2) -{ +TEST_F(fspath, link_2) { test_enter(PPME_SYSCALL_LINK_2_E, 0); - test_exit_source_target(newpath, newpath, oldpath, oldpath, PPME_SYSCALL_LINK_2_X, 3, res, oldpath, newpath); + test_exit_source_target(newpath, + newpath, + oldpath, + oldpath, + PPME_SYSCALL_LINK_2_X, + 3, + res, + oldpath, + newpath); test_failed_exit(PPME_SYSCALL_LINK_2_X, 3, failed_res, oldpath, newpath); } -TEST_F(fspath, link_2_relative) -{ - +TEST_F(fspath, link_2_relative) { test_enter(PPME_SYSCALL_LINK_2_E, 0); - test_exit_source_target(resolved_rel_newpath, rel_newpath, - resolved_rel_oldpath, rel_oldpath, - PPME_SYSCALL_LINK_2_X, 3, res, rel_oldpath, rel_newpath); -} - -TEST_F(fspath, linkat_2) -{ + test_exit_source_target(resolved_rel_newpath, + rel_newpath, + resolved_rel_oldpath, + rel_oldpath, + PPME_SYSCALL_LINK_2_X, + 3, + res, + rel_oldpath, + rel_newpath); +} + +TEST_F(fspath, linkat_2) { test_enter(PPME_SYSCALL_LINKAT_2_E, 0); - test_exit_source_target(newpath, newpath, oldpath, oldpath, PPME_SYSCALL_LINKAT_2_X, 6, res, olddirfd, oldpath, newdirfd, newpath, flags); - test_failed_exit(PPME_SYSCALL_LINKAT_2_X, 6, failed_res, olddirfd, oldpath, newdirfd, newpath, flags); -} - -TEST_F(fspath, linkat_2_relative) -{ + test_exit_source_target(newpath, + newpath, + oldpath, + oldpath, + PPME_SYSCALL_LINKAT_2_X, + 6, + res, + olddirfd, + oldpath, + newdirfd, + newpath, + flags); + test_failed_exit(PPME_SYSCALL_LINKAT_2_X, + 6, + failed_res, + olddirfd, + oldpath, + newdirfd, + newpath, + flags); +} + +TEST_F(fspath, linkat_2_relative) { test_enter(PPME_SYSCALL_LINKAT_2_E, 0); - test_exit_source_target(resolved_rel_newpath, rel_newpath, - resolved_rel_oldpath, rel_oldpath, - PPME_SYSCALL_LINKAT_2_X, 6, res, olddirfd, rel_oldpath, newdirfd, rel_newpath, flags); -} - -TEST_F(fspath, symlink) -{ + test_exit_source_target(resolved_rel_newpath, + rel_newpath, + resolved_rel_oldpath, + rel_oldpath, + PPME_SYSCALL_LINKAT_2_X, + 6, + res, + olddirfd, + rel_oldpath, + newdirfd, + rel_newpath, + flags); +} + +TEST_F(fspath, symlink) { test_enter(PPME_SYSCALL_SYMLINK_E, 0); - test_exit_source_target(linkpath, linkpath, targetpath, targetpath, PPME_SYSCALL_SYMLINK_X, 3, res, targetpath, linkpath); + test_exit_source_target(linkpath, + linkpath, + targetpath, + targetpath, + PPME_SYSCALL_SYMLINK_X, + 3, + res, + targetpath, + linkpath); test_failed_exit(PPME_SYSCALL_SYMLINK_X, 3, failed_res, targetpath, linkpath); } -TEST_F(fspath, symlink_relative) -{ +TEST_F(fspath, symlink_relative) { test_enter(PPME_SYSCALL_SYMLINK_E, 0); - test_exit_source_target(resolved_rel_linkpath, rel_linkpath, - resolved_rel_targetpath, rel_targetpath, - PPME_SYSCALL_SYMLINK_X, 3, res, rel_targetpath, rel_linkpath); -} - -TEST_F(fspath, symlinkat) -{ + test_exit_source_target(resolved_rel_linkpath, + rel_linkpath, + resolved_rel_targetpath, + rel_targetpath, + PPME_SYSCALL_SYMLINK_X, + 3, + res, + rel_targetpath, + rel_linkpath); +} + +TEST_F(fspath, symlinkat) { test_enter(PPME_SYSCALL_SYMLINKAT_E, 0); - test_exit_source_target(linkpath, linkpath, targetpath, targetpath, PPME_SYSCALL_SYMLINKAT_X, 4, res, targetpath, linkdirfd, linkpath); + test_exit_source_target(linkpath, + linkpath, + targetpath, + targetpath, + PPME_SYSCALL_SYMLINKAT_X, + 4, + res, + targetpath, + linkdirfd, + linkpath); test_failed_exit(PPME_SYSCALL_SYMLINKAT_X, 4, failed_res, targetpath, linkdirfd, linkpath); } -TEST_F(fspath, symlinkat_relative) -{ +TEST_F(fspath, symlinkat_relative) { const char *resolved_rel_targetpath_at_symlinkat = "tmp/targetpath"; - const char *resolved_rel_linkpath_at_symlinkat = "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/linkpath"; + const char *resolved_rel_linkpath_at_symlinkat = + "/tmp/dirfd1/dirfd2/dirfd3/dirfd4/dirfd5/dirfd6/dirfd7/dirfd8/tmp/linkpath"; test_enter(PPME_SYSCALL_SYMLINKAT_E, 0); - test_exit_source_target(resolved_rel_linkpath_at_symlinkat, rel_linkpath, - resolved_rel_targetpath_at_symlinkat, rel_targetpath, - PPME_SYSCALL_SYMLINKAT_X, 4, res, rel_targetpath, linkdirfd, rel_linkpath); -} - -TEST_F(fspath, mount) -{ + test_exit_source_target(resolved_rel_linkpath_at_symlinkat, + rel_linkpath, + resolved_rel_targetpath_at_symlinkat, + rel_targetpath, + PPME_SYSCALL_SYMLINKAT_X, + 4, + res, + rel_targetpath, + linkdirfd, + rel_linkpath); +} + +TEST_F(fspath, mount) { const char *devpath = "/dev/cdrom0"; const char *mounttype = "iso9660"; test_enter(PPME_SYSCALL_MOUNT_E, 1, flags); - test_exit_source_target(devpath, devpath, mountpath, mountpath, PPME_SYSCALL_MOUNT_X, 4, res, devpath, mountpath, mounttype); + test_exit_source_target(devpath, + devpath, + mountpath, + mountpath, + PPME_SYSCALL_MOUNT_X, + 4, + res, + devpath, + mountpath, + mounttype); test_failed_exit(PPME_SYSCALL_MOUNT_X, 4, failed_res, devpath, mountpath, mounttype); } -TEST_F(fspath, umount) -{ +TEST_F(fspath, umount) { test_enter(PPME_SYSCALL_UMOUNT_E, 1, flags); test_exit_path(mountpath, mountpath, PPME_SYSCALL_UMOUNT_X, 2, res, mountpath); test_failed_exit(PPME_SYSCALL_UMOUNT_X, 2, failed_res, mountpath); } -TEST_F(fspath, umount_1) -{ +TEST_F(fspath, umount_1) { test_enter(PPME_SYSCALL_UMOUNT_1_E, 0); test_exit_path(mountpath, mountpath, PPME_SYSCALL_UMOUNT_1_X, 2, res, mountpath); test_failed_exit(PPME_SYSCALL_UMOUNT_1_X, 2, failed_res, mountpath); } -TEST_F(fspath, umount2) -{ +TEST_F(fspath, umount2) { test_enter(PPME_SYSCALL_UMOUNT2_E, 1, flags); test_exit_path(mountpath, mountpath, PPME_SYSCALL_UMOUNT2_X, 2, res, mountpath); test_failed_exit(PPME_SYSCALL_UMOUNT2_X, 2, failed_res, mountpath); diff --git a/userspace/libsinsp/test/events_injection.ut.cpp b/userspace/libsinsp/test/events_injection.ut.cpp index 9ac5e02af7..4c4cfc2dd7 100644 --- a/userspace/libsinsp/test/events_injection.ut.cpp +++ b/userspace/libsinsp/test/events_injection.ut.cpp @@ -3,21 +3,32 @@ #include "sinsp_with_test_input.h" #include "test_utils.h" - -TEST_F(sinsp_with_test_input, event_async_queue) -{ +TEST_F(sinsp_with_test_input, event_async_queue) { open_inspector(); m_inspector.set_lastevent_ts(123); sinsp_evt* evt{}; - const scap_evt *scap_evt; + const scap_evt* scap_evt; - scap_evt = add_async_event(-1, -1, PPME_ASYNCEVENT_E, 3, - 100, "event_name", scap_const_sized_buffer{NULL, 0}); + scap_evt = add_async_event(-1, + -1, + PPME_ASYNCEVENT_E, + 3, + 100, + "event_name", + scap_const_sized_buffer{NULL, 0}); // create test input event - auto* scap_evt0 = add_event(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (uint64_t)3, "/tmp/the_file", - PPM_O_RDWR, 0, 5, (uint64_t)123); + auto* scap_evt0 = add_event(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)3, + "/tmp/the_file", + PPM_O_RDWR, + 0, + 5, + (uint64_t)123); // should pop injected event auto res = m_inspector.next(&evt); @@ -31,28 +42,39 @@ TEST_F(sinsp_with_test_input, event_async_queue) m_inspector.set_lastevent_ts(scap_evt0->ts - 10); uint64_t injected_ts = scap_evt0->ts + 10; - for (int i = 0; i < 10; ++i) - { - add_async_event(injected_ts + i, -1, PPME_ASYNCEVENT_E, 3, - 100, "event_name", scap_const_sized_buffer{NULL, 0}); + for(int i = 0; i < 10; ++i) { + add_async_event(injected_ts + i, + -1, + PPME_ASYNCEVENT_E, + 3, + 100, + "event_name", + scap_const_sized_buffer{NULL, 0}); } // create input[1] ivent - auto* scap_evt1 = add_event(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (uint64_t)3, "/tmp/the_file", - PPM_O_RDWR, 0, 5, (uint64_t)123); + auto* scap_evt1 = add_event(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)3, + "/tmp/the_file", + PPM_O_RDWR, + 0, + 5, + (uint64_t)123); // pop scap 0 event res = m_inspector.next(&evt); ASSERT_EQ(res, SCAP_SUCCESS); ASSERT_EQ(evt->get_scap_evt(), scap_evt0); auto last_ts = evt->get_scap_evt()->ts; - + // pop injected - for (int i= 0; i < 10; ++i) - { + for(int i = 0; i < 10; ++i) { res = m_inspector.next(&evt); ASSERT_EQ(res, SCAP_SUCCESS); - ASSERT_EQ(evt->get_scap_evt(), m_async_events[i+1]); + ASSERT_EQ(evt->get_scap_evt(), m_async_events[i + 1]); ASSERT_TRUE(last_ts <= evt->get_scap_evt()->ts); last_ts = evt->get_scap_evt()->ts; } @@ -63,4 +85,3 @@ TEST_F(sinsp_with_test_input, event_async_queue) ASSERT_EQ(res, SCAP_SUCCESS); ASSERT_EQ(evt->get_scap_evt(), scap_evt1); } - diff --git a/userspace/libsinsp/test/events_net.ut.cpp b/userspace/libsinsp/test/events_net.ut.cpp index 9b7d3c476a..f2b8025bef 100644 --- a/userspace/libsinsp/test/events_net.ut.cpp +++ b/userspace/libsinsp/test/events_net.ut.cpp @@ -28,19 +28,24 @@ int64_t return_value = 0; /* * For all network tests we can use the prefix `net` for tests */ -TEST_F(sinsp_with_test_input, net_socket) -{ +TEST_F(sinsp_with_test_input, net_socket) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; sinsp_fdinfo* fdinfo = NULL; int64_t client_fd = 9; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_STREAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_STREAM, + (uint32_t)0); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); fdinfo = evt->get_fd_info(); ASSERT_NE(fdinfo, nullptr); - ASSERT_EQ(fdinfo->get_l4proto(), SCAP_L4_NA); /// todo: probably this is not what we want + ASSERT_EQ(fdinfo->get_l4proto(), SCAP_L4_NA); /// todo: probably this is not what we want ASSERT_TRUE(fdinfo->is_ipv4_socket()); ASSERT_TRUE(fdinfo->is_tcp_socket()); ASSERT_TRUE(fdinfo->is_role_none()); @@ -49,7 +54,8 @@ TEST_F(sinsp_with_test_input, net_socket) ASSERT_FALSE(fdinfo->is_socket_connected()); ASSERT_EQ(get_field_as_string(evt, "fd.connected"), "false"); - ASSERT_EQ(get_field_as_string(evt, "fd.l4proto"), ""); /// todo: probably this is not what we want + ASSERT_EQ(get_field_as_string(evt, "fd.l4proto"), + ""); /// todo: probably this is not what we want ASSERT_EQ(get_field_as_string(evt, "fd.name"), ""); /* When the fd role is `none` all these fields return NULL */ ASSERT_FALSE(field_has_value(evt, "fd.sip")); @@ -62,8 +68,7 @@ TEST_F(sinsp_with_test_input, net_socket) ASSERT_FALSE(field_has_value(evt, "fd.rport")); } -TEST_F(sinsp_with_test_input, net_ipv4_connect) -{ +TEST_F(sinsp_with_test_input, net_ipv4_connect) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -72,14 +77,29 @@ TEST_F(sinsp_with_test_input, net_ipv4_connect) char ipv4_string[DEFAULT_IP_STRING_SIZE]; int64_t client_fd = 7; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_STREAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_STREAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); - sockaddr_in client = test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); - sockaddr_in server = test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); - - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + sockaddr_in client = + test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); + sockaddr_in server = + test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); + + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); /* See the `reset` logic for enter events with `EF_USES_FD` flag */ tinfo = evt->get_thread_info(false); @@ -88,12 +108,14 @@ TEST_F(sinsp_with_test_input, net_ipv4_connect) ASSERT_EQ(tinfo->m_lastevent_ts, evt->get_ts()); ASSERT_EQ(tinfo->m_latency, 0); - /* Here we should recover the fdinfo from the thread info since the socket call has already added the fdinfo into the thread. - * See `reset` logic, the fdinfo is recovered from the `client_fd` (first parameter). + /* Here we should recover the fdinfo from the thread info since the socket call has already + * added the fdinfo into the thread. See `reset` logic, the fdinfo is recovered from the + * `client_fd` (first parameter). */ fdinfo = evt->get_fd_info(); ASSERT_NE(fdinfo, nullptr); - ASSERT_TRUE(fdinfo->is_ipv4_socket()); /* in `parse_connect_enter` we set `SCAP_FD_IPV4_SOCK` as type */ + ASSERT_TRUE(fdinfo->is_ipv4_socket()); /* in `parse_connect_enter` we set `SCAP_FD_IPV4_SOCK` as + type */ ASSERT_TRUE(fdinfo->is_role_none()); /* The connect enter event is not able to set a role */ ASSERT_FALSE(fdinfo->is_role_client()); ASSERT_FALSE(fdinfo->is_role_server()); @@ -108,18 +130,29 @@ TEST_F(sinsp_with_test_input, net_ipv4_connect) ASSERT_EQ(get_field_as_string(evt, "fd.name"), ""); ASSERT_EQ(get_field_as_string(evt, "fd.connected"), "false"); - /* Since the role of the fd is none, all these fields are null. The fdinfo state is updated but we cannot use these info in the filterchecks */ + /* Since the role of the fd is none, all these fields are null. The fdinfo state is updated but + * we cannot use these info in the filterchecks */ ASSERT_FALSE(field_has_value(evt, "fd.sip")); - /* If the exit event is immediately consecutive we can obtain some info otherwise there is the risk we cannot update the fd */ - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + /* If the exit event is immediately consecutive we can obtain some info otherwise there is the + * risk we cannot update the fd */ + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); fdinfo = evt->get_fd_info(); ASSERT_NE(fdinfo, nullptr); ASSERT_TRUE(fdinfo->is_ipv4_socket()); - ASSERT_TRUE(fdinfo->is_socket_connected()); /* in the parse exit we set the socket as connected */ - ASSERT_TRUE(fdinfo->is_role_client()); /* The connect exit set the client role */ + ASSERT_TRUE( + fdinfo->is_socket_connected()); /* in the parse exit we set the socket as connected */ + ASSERT_TRUE(fdinfo->is_role_client()); /* The connect exit set the client role */ /* Check that ip and port are saved from the server socktuple */ inet_ntop(AF_INET, (uint8_t*)&(fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sip), ipv4_string, 100); @@ -133,9 +166,10 @@ TEST_F(sinsp_with_test_input, net_ipv4_connect) ASSERT_EQ(get_field_as_string(evt, "fd.connected"), "true"); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), DEFAULT_IPV4_SERVER_STRING); - /* The concept of remote ip is quite strange, we check if the client address is one of our interfaces, if yes - * the remote ip will be the server otherwise it will be the client! In this case, the client IP is completely random - * so it will be considered as remote, while the server ip will be local! + /* The concept of remote ip is quite strange, we check if the client address is one of our + * interfaces, if yes the remote ip will be the server otherwise it will be the client! In this + * case, the client IP is completely random so it will be considered as remote, while the server + * ip will be local! */ ASSERT_EQ(get_field_as_string(evt, "fd.rip"), DEFAULT_IPV4_CLIENT_STRING); ASSERT_EQ(get_field_as_string(evt, "fd.cip"), DEFAULT_IPV4_CLIENT_STRING); @@ -146,27 +180,55 @@ TEST_F(sinsp_with_test_input, net_ipv4_connect) ASSERT_EQ(get_field_as_string(evt, "fd.lport"), DEFAULT_SERVER_PORT_STRING); } -TEST_F(sinsp_with_test_input, net_ipv4_connect_with_intermediate_event) -{ +TEST_F(sinsp_with_test_input, net_ipv4_connect_with_intermediate_event) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; sinsp_fdinfo* fdinfo = NULL; int64_t client_fd = 8; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_STREAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_STREAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); - sockaddr_in client = test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); - - sockaddr_in server = test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); - - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); + sockaddr_in client = + test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); + + sockaddr_in server = + test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); + + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); /* This should never happen but could cause strange outcomes */ - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SENDTO_E, 3, client_fd, (uint32_t)102, scap_const_sized_buffer{socktuple.data(), socktuple.size()}); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SENDTO_E, + 3, + client_fd, + (uint32_t)102, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); /* We are able to recover the fdinfo in the connect exit event even when interleaved */ fdinfo = evt->get_fd_info(); @@ -176,35 +238,58 @@ TEST_F(sinsp_with_test_input, net_ipv4_connect_with_intermediate_event) ASSERT_EQ(get_field_as_string(evt, "fd.name"), "172.40.111.222:54321->142.251.111.147:443"); } -TEST_F(sinsp_with_test_input, net_ipv6_multiple_connects) -{ +TEST_F(sinsp_with_test_input, net_ipv6_multiple_connects) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; int64_t client_fd = 9; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET6, (uint32_t) SOCK_DGRAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET6, + (uint32_t)SOCK_DGRAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); - sockaddr_in6 client = test_utils::fill_sockaddr_in6(DEFAULT_CLIENT_PORT, DEFAULT_IPV6_CLIENT_STRING); - - sockaddr_in6 server1 = test_utils::fill_sockaddr_in6(DEFAULT_SERVER_PORT, DEFAULT_IPV6_SERVER_STRING); - - std::vector server1_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server1)); - - /* The connect enter event populates the destination ip and the destination port thanks to the `server_sockaddr` */ - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server1_sockaddr.data(), server1_sockaddr.size()}); - - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server1)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + sockaddr_in6 client = + test_utils::fill_sockaddr_in6(DEFAULT_CLIENT_PORT, DEFAULT_IPV6_CLIENT_STRING); + + sockaddr_in6 server1 = + test_utils::fill_sockaddr_in6(DEFAULT_SERVER_PORT, DEFAULT_IPV6_SERVER_STRING); + + std::vector server1_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server1)); + + /* The connect enter event populates the destination ip and the destination port thanks to the + * `server_sockaddr` */ + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server1_sockaddr.data(), server1_sockaddr.size()}); + + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server1)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); ASSERT_EQ(get_field_as_string(evt, "fd.name"), DEFAULT_IPV6_FDNAME); ASSERT_EQ(get_field_as_string(evt, "fd.connected"), "true"); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), DEFAULT_IPV6_SERVER_STRING); - /* The concept of remote ip is quite strange, we check if the client address is one of our interfaces, if yes - * the remote ip will be the server otherwise it will be the client! In this case, the client IP is completely random - * so it will be considered as remote, while the server ip will be local! + /* The concept of remote ip is quite strange, we check if the client address is one of our + * interfaces, if yes the remote ip will be the server otherwise it will be the client! In this + * case, the client IP is completely random so it will be considered as remote, while the server + * ip will be local! */ ASSERT_EQ(get_field_as_string(evt, "fd.rip"), DEFAULT_IPV6_CLIENT_STRING); ASSERT_EQ(get_field_as_string(evt, "fd.cip"), DEFAULT_IPV6_CLIENT_STRING); @@ -219,10 +304,18 @@ TEST_F(sinsp_with_test_input, net_ipv6_multiple_connects) std::string ipv6_server2 = "2001:4860:4860::8888"; std::string port_server2_string = "8"; sockaddr_in6 server2 = test_utils::fill_sockaddr_in6(port_server2, ipv6_server2.c_str()); - std::vector server2_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server2)); - - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server2_sockaddr.data(), server2_sockaddr.size()}); - /* check that upon entry to the new connect the fd name is the same as during the last connection */ + std::vector server2_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server2)); + + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server2_sockaddr.data(), server2_sockaddr.size()}); + /* check that upon entry to the new connect the fd name is the same as during the last + * connection */ ASSERT_EQ(get_field_as_string(evt, "fd.name"), DEFAULT_IPV6_FDNAME); /* server ip and port are updated with the new connect enter event */ ASSERT_EQ(get_field_as_string(evt, "fd.lip"), ipv6_server2); @@ -230,21 +323,35 @@ TEST_F(sinsp_with_test_input, net_ipv6_multiple_connects) ASSERT_EQ(get_field_as_string(evt, "fd.lport"), port_server2_string); ASSERT_EQ(get_field_as_string(evt, "fd.sport"), port_server2_string); - socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server2)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server2)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); ASSERT_EQ(get_field_as_string(evt, "fd.name_changed"), "true"); - std::string new_fd_name = std::string(DEFAULT_IPV6_CLIENT_STRING) + ":" + std::string(DEFAULT_CLIENT_PORT_STRING) + "->" + ipv6_server2 + ":" + port_server2_string; + std::string new_fd_name = std::string(DEFAULT_IPV6_CLIENT_STRING) + ":" + + std::string(DEFAULT_CLIENT_PORT_STRING) + "->" + ipv6_server2 + ":" + + port_server2_string; ASSERT_EQ(get_field_as_string(evt, "fd.name"), new_fd_name); scap_const_sized_buffer null_buf = scap_const_sized_buffer{nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SENDTO_E, 3, client_fd, (uint32_t) 6, null_buf); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SENDTO_E, + 3, + client_fd, + (uint32_t)6, + null_buf); /* the tuple of `sendto` is empty so we won't update anything */ ASSERT_EQ(get_field_as_string(evt, "fd.name"), new_fd_name); } /* test a basic server connection with ipv4 */ -TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv4) -{ +TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv4) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -252,17 +359,31 @@ TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv4) char ipv4_string[DEFAULT_IP_STRING_SIZE]; int64_t server_fd = 3; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_STREAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_STREAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, server_fd); /* We have no parsers for bind enter event */ evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_BIND_E, 1, server_fd); ASSERT_EQ(get_field_as_string(evt, "fd.name"), ""); - sockaddr_in server = test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_BIND_X, 2, return_value, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + sockaddr_in server = + test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_BIND_X, + 2, + return_value, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); fdinfo = evt->get_fd_info(); ASSERT_NE(fdinfo, nullptr); ASSERT_FALSE(fdinfo->is_ipv4_socket()); @@ -279,28 +400,42 @@ TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv4) ASSERT_EQ(fdinfo->m_sockinfo.m_ipv4serverinfo.m_port, DEFAULT_SERVER_PORT); /* The fdname is just the server ip + server port */ - std::string fdname = std::string(DEFAULT_IPV4_SERVER_STRING) + ":" + std::string(DEFAULT_SERVER_PORT_STRING); + std::string fdname = + std::string(DEFAULT_IPV4_SERVER_STRING) + ":" + std::string(DEFAULT_SERVER_PORT_STRING); ASSERT_EQ(get_field_as_string(evt, "fd.name"), fdname); ASSERT_EQ(get_field_as_string(evt, "fd.is_server"), "true"); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), DEFAULT_IPV4_SERVER_STRING); - ASSERT_FALSE(field_has_value(evt, "fd.cip")); /* we are not able to retrieve the client ip, the fdinfo type is SCAP_FD_IPV4_SERVSOCK */ - ASSERT_FALSE(field_has_value(evt, "fd.rip")); /* we are not able to retrieve remote ip, the fdinfo type is SCAP_FD_IPV4_SERVSOCK */ - ASSERT_FALSE(field_has_value(evt, "fd.lip")); /* we are not able to retrieve local ip, the fdinfo type is SCAP_FD_IPV4_SERVSOCK */ + ASSERT_FALSE(field_has_value(evt, "fd.cip")); /* we are not able to retrieve the client ip, the + fdinfo type is SCAP_FD_IPV4_SERVSOCK */ + ASSERT_FALSE(field_has_value(evt, "fd.rip")); /* we are not able to retrieve remote ip, the + fdinfo type is SCAP_FD_IPV4_SERVSOCK */ + ASSERT_FALSE(field_has_value(evt, "fd.lip")); /* we are not able to retrieve local ip, the + fdinfo type is SCAP_FD_IPV4_SERVSOCK */ ASSERT_EQ(get_field_as_string(evt, "fd.sport"), DEFAULT_SERVER_PORT_STRING); ASSERT_FALSE(field_has_value(evt, "fd.cport")); ASSERT_FALSE(field_has_value(evt, "fd.rport")); ASSERT_FALSE(field_has_value(evt, "fd.lport")); - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_LISTEN_E, 2, server_fd, (uint32_t) 5); + add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_LISTEN_E, 2, server_fd, (uint32_t)5); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_LISTEN_X, 1, return_value); - sockaddr_in client = test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); + sockaddr_in client = + test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); - std::vector st = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); + std::vector st = test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); int64_t new_connected_fd = 6; add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_ACCEPT_5_E, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_ACCEPT_5_X, 5, new_connected_fd, scap_const_sized_buffer{st.data(), st.size()}, (uint8_t) 0, (uint32_t) 0, (uint32_t) 5); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_ACCEPT_5_X, + 5, + new_connected_fd, + scap_const_sized_buffer{st.data(), st.size()}, + (uint8_t)0, + (uint32_t)0, + (uint32_t)5); ASSERT_EQ(get_field_as_string(evt, "fd.name"), DEFAULT_IPV4_FDNAME); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), DEFAULT_IPV4_SERVER_STRING); @@ -315,35 +450,59 @@ TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv4) } /* test a basic server connection with ipv6 */ -TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv6) -{ +TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv6) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; int64_t server_fd = 3; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET6, (uint32_t) SOCK_STREAM, 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET6, + (uint32_t)SOCK_STREAM, + 0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, server_fd); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_BIND_E, 1, server_fd); - sockaddr_in6 server = test_utils::fill_sockaddr_in6(DEFAULT_SERVER_PORT, DEFAULT_IPV6_SERVER_STRING); - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_BIND_X, 2, return_value, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - std::string fdname = std::string(DEFAULT_IPV6_SERVER_STRING) + ":" + std::string(DEFAULT_SERVER_PORT_STRING); + sockaddr_in6 server = + test_utils::fill_sockaddr_in6(DEFAULT_SERVER_PORT, DEFAULT_IPV6_SERVER_STRING); + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_BIND_X, + 2, + return_value, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + std::string fdname = + std::string(DEFAULT_IPV6_SERVER_STRING) + ":" + std::string(DEFAULT_SERVER_PORT_STRING); ASSERT_EQ(get_field_as_string(evt, "fd.name"), fdname); ASSERT_EQ(get_field_as_string(evt, "fd.is_server"), "true"); - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_LISTEN_E, 2, server_fd, (uint32_t) 5); + add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_LISTEN_E, 2, server_fd, (uint32_t)5); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_LISTEN_X, 1, return_value); - sockaddr_in6 client = test_utils::fill_sockaddr_in6(DEFAULT_CLIENT_PORT, DEFAULT_IPV6_CLIENT_STRING); + sockaddr_in6 client = + test_utils::fill_sockaddr_in6(DEFAULT_CLIENT_PORT, DEFAULT_IPV6_CLIENT_STRING); - std::vector st = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); + std::vector st = test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); int64_t new_connected_fd = 6; add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_ACCEPT_5_E, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_ACCEPT_5_X, 5, new_connected_fd, scap_const_sized_buffer{st.data(), st.size()}, (uint8_t) 0, (uint32_t) 0, (uint32_t) 5); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_ACCEPT_5_X, + 5, + new_connected_fd, + scap_const_sized_buffer{st.data(), st.size()}, + (uint8_t)0, + (uint32_t)0, + (uint32_t)5); ASSERT_EQ(get_field_as_string(evt, "fd.name"), DEFAULT_IPV6_FDNAME); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), DEFAULT_IPV6_SERVER_STRING); @@ -357,8 +516,7 @@ TEST_F(sinsp_with_test_input, net_bind_listen_accept_ipv6) ASSERT_EQ(get_field_as_string(evt, "fd.l4proto"), "tcp"); } -TEST_F(sinsp_with_test_input, net_connect_exit_event_fails) -{ +TEST_F(sinsp_with_test_input, net_connect_exit_event_fails) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -366,20 +524,43 @@ TEST_F(sinsp_with_test_input, net_connect_exit_event_fails) char ipv4_string[DEFAULT_IP_STRING_SIZE]; int64_t client_fd = 7; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_STREAM, 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_STREAM, + 0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); - sockaddr_in client = test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); + sockaddr_in client = + test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); - sockaddr_in server = test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); + sockaddr_in server = + test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); /* First connection to populate the fdinfo */ - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); fdinfo = evt->get_fd_info(); ASSERT_NE(fdinfo, nullptr); @@ -393,16 +574,31 @@ TEST_F(sinsp_with_test_input, net_connect_exit_event_fails) sockaddr_in server2 = test_utils::fill_sockaddr_in(port_server2, ipv4_server2.c_str()); server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server2)); - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - - socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server2)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, (int64_t)-2, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); - - /* Filterchecks will get an updated fdname since the extraction happens directly on the params, while the fdinfo fdname is not updated. - * Ip and port of the new server are updated by the PPME_SOCKET_CONNECT_E event so both filterchecks and internal state are aligned + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + + socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server2)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + (int64_t)-2, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); + + /* Filterchecks will get an updated fdname since the extraction happens directly on the params, + * while the fdinfo fdname is not updated. Ip and port of the new server are updated by the + * PPME_SOCKET_CONNECT_E event so both filterchecks and internal state are aligned */ - std::string fdname = std::string(DEFAULT_IPV4_CLIENT_STRING) + ":" + std::string(DEFAULT_CLIENT_PORT_STRING) + "->" + ipv4_server2 + ":" + port_server2_string; + std::string fdname = std::string(DEFAULT_IPV4_CLIENT_STRING) + ":" + + std::string(DEFAULT_CLIENT_PORT_STRING) + "->" + ipv4_server2 + ":" + + port_server2_string; ASSERT_EQ(get_field_as_string(evt, "fd.name"), fdname); ASSERT_EQ(get_field_as_string(evt, "fd.connected"), "true"); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), ipv4_server2); @@ -414,7 +610,8 @@ TEST_F(sinsp_with_test_input, net_connect_exit_event_fails) ASSERT_EQ(get_field_as_string(evt, "fd.rport"), DEFAULT_CLIENT_PORT_STRING); ASSERT_EQ(get_field_as_string(evt, "fd.lport"), port_server2_string); - /* The parser is not able to obtain an updated fdname because the syscall fails and the parser flow is truncated */ + /* The parser is not able to obtain an updated fdname because the syscall fails and the parser + * flow is truncated */ fdinfo = evt->get_fd_info(); ASSERT_NE(fdinfo, nullptr); ASSERT_STREQ(fdinfo->m_name.c_str(), DEFAULT_IPV4_FDNAME); @@ -430,8 +627,7 @@ TEST_F(sinsp_with_test_input, net_connect_exit_event_fails) ASSERT_EQ(fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport, DEFAULT_CLIENT_PORT); } -TEST_F(sinsp_with_test_input, net_connect_enter_event_is_empty) -{ +TEST_F(sinsp_with_test_input, net_connect_enter_event_is_empty) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -439,22 +635,45 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_empty) char ipv4_string[DEFAULT_IP_STRING_SIZE]; int64_t client_fd = 7; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_DGRAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_DGRAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); - sockaddr_in client = test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); + sockaddr_in client = + test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); - sockaddr_in server = test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); + sockaddr_in server = + test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); /* First connection to populate the fdinfo */ - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); - - /* Second connection with an empty sockaddr in the PPME_SOCKET_CONNECT_E event, new client and new server */ + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); + + /* Second connection with an empty sockaddr in the PPME_SOCKET_CONNECT_E event, new client and + * new server */ int port_client2 = 12; std::string ipv4_client2 = "80.9.11.45"; @@ -469,11 +688,19 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_empty) scap_const_sized_buffer null_buf = scap_const_sized_buffer{nullptr, 0}; add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, null_buf); - socktuple = test_utils::pack_socktuple(reinterpret_cast(&client2), reinterpret_cast(&server2)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, (int64_t)-2, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + socktuple = test_utils::pack_socktuple(reinterpret_cast(&client2), + reinterpret_cast(&server2)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + (int64_t)-2, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); /* Only filterchecks will see the new tuple in the fdname all the rest is not updated */ - std::string fdname = ipv4_client2 + ":" + port_client2_string + "->" + ipv4_server2 + ":" + port_server2_string; + std::string fdname = ipv4_client2 + ":" + port_client2_string + "->" + ipv4_server2 + ":" + + port_server2_string; ASSERT_EQ(get_field_as_string(evt, "fd.name"), fdname); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), DEFAULT_IPV4_SERVER_STRING); ASSERT_EQ(get_field_as_string(evt, "fd.cip"), DEFAULT_IPV4_CLIENT_STRING); @@ -485,7 +712,8 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_empty) ASSERT_EQ(get_field_as_string(evt, "fd.rport"), DEFAULT_CLIENT_PORT_STRING); ASSERT_EQ(get_field_as_string(evt, "fd.lport"), DEFAULT_SERVER_PORT_STRING); - /* The parser is not able to obtain an updated fdname because the syscall fails and the parser flow is truncated */ + /* The parser is not able to obtain an updated fdname because the syscall fails and the parser + * flow is truncated */ fdinfo = evt->get_fd_info(); ASSERT_NE(fdinfo, nullptr); ASSERT_STREQ(fdinfo->m_name.c_str(), DEFAULT_IPV4_FDNAME); @@ -500,8 +728,7 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_empty) ASSERT_EQ(fdinfo->m_sockinfo.m_ipv4info.m_fields.m_sport, DEFAULT_CLIENT_PORT); } -TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing) -{ +TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -509,7 +736,13 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing) char ipv4_string[DEFAULT_IP_STRING_SIZE]; int64_t client_fd = 7; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_DGRAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_DGRAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); int port_client = 12; @@ -524,11 +757,20 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing) /* We dropped connect enter! */ - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); /* Check that everything is updated anyway, even if we lost connect enter */ - std::string fdname = ipv4_client + ":" + port_client_string + "->" + ipv4_server + ":" + port_server_string; + std::string fdname = + ipv4_client + ":" + port_client_string + "->" + ipv4_server + ":" + port_server_string; ASSERT_EQ(get_field_as_string(evt, "fd.name"), fdname); ASSERT_EQ(get_field_as_string(evt, "fd.sip"), ipv4_server); ASSERT_EQ(get_field_as_string(evt, "fd.cip"), ipv4_client); @@ -558,15 +800,20 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing) * Test that old connect exit event without the third `fd` argument * were not able to load fd related data if connect enter was dropped. */ -TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing_wo_fd_param_exit) -{ +TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing_wo_fd_param_exit) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; sinsp_fdinfo* fdinfo = NULL; int64_t client_fd = 7; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_DGRAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_DGRAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); int port_client = 12; @@ -582,8 +829,15 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing_wo_fd_param_exi /* We dropped connect enter! */ /* We read an old scap file with a connect exit event with just 2 params (no fd!) */ - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 2, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}); + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 2, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}); /* Check that we are not able to load any info */ ASSERT_EQ(get_field_as_string(evt, "fd.name"), ""); @@ -596,7 +850,8 @@ TEST_F(sinsp_with_test_input, net_connect_enter_event_is_missing_wo_fd_param_exi ASSERT_FALSE(field_has_value(evt, "fd.lport")); ASSERT_FALSE(field_has_value(evt, "fd.rport")); - /* The parser is not able to obtain an updated fdname because the syscall fails and the parser flow is truncated */ + /* The parser is not able to obtain an updated fdname because the syscall fails and the parser + * flow is truncated */ fdinfo = evt->get_fd_info(); ASSERT_EQ(fdinfo, nullptr); } diff --git a/userspace/libsinsp/test/events_param.ut.cpp b/userspace/libsinsp/test/events_param.ut.cpp index 9dcb30f814..a9e466d9f9 100644 --- a/userspace/libsinsp/test/events_param.ut.cpp +++ b/userspace/libsinsp/test/events_param.ut.cpp @@ -24,12 +24,11 @@ limitations under the License. #include "test_utils.h" /* - Tests that check proper parameter parsing from kmod/ebpf + Tests that check proper parameter parsing from kmod/ebpf */ /* Assert that empty (`PT_CHARBUF`, `PT_FSPATH`, `PT_FSRELPATH`) params are converted to `` */ -TEST_F(sinsp_with_test_input, charbuf_empty_param) -{ +TEST_F(sinsp_with_test_input, charbuf_empty_param) { add_default_init_thread(); open_inspector(); @@ -43,8 +42,8 @@ TEST_F(sinsp_with_test_input, charbuf_empty_param) evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_CHDIR_X, 2, test_errno, NULL); ASSERT_EQ(get_field_as_string(evt, "evt.arg.path"), ""); - // this, and the following similar checks, verify that the internal state is set as we need right now. - // if the internal state changes we can remove or update this check + // this, and the following similar checks, verify that the internal state is set as we need + // right now. if the internal state changes we can remove or update this check ASSERT_EQ(evt->get_param(1)->as(), ""); /* `PPME_SYSCALL_CREAT_E` is a simple event that uses a `PT_FSPATH` @@ -67,8 +66,7 @@ TEST_F(sinsp_with_test_input, charbuf_empty_param) } /* Assert that a `PT_CHARBUF` with `len==1` (just the `\0`) is not changed. */ -TEST_F(sinsp_with_test_input, param_charbuf_len_1) -{ +TEST_F(sinsp_with_test_input, param_charbuf_len_1) { add_default_init_thread(); open_inspector(); @@ -90,8 +88,7 @@ TEST_F(sinsp_with_test_input, param_charbuf_len_1) * Only scap-file could send a `PT_CHARBUF` with "(NULL)", in our * actual drivers this value is no more supported. */ -TEST_F(sinsp_with_test_input, charbuf_NULL_param) -{ +TEST_F(sinsp_with_test_input, charbuf_NULL_param) { add_default_init_thread(); open_inspector(); @@ -107,8 +104,7 @@ TEST_F(sinsp_with_test_input, charbuf_NULL_param) } /* Assert that an empty `PT_BYTEBUF` param is NOT converted to `` */ -TEST_F(sinsp_with_test_input, bytebuf_empty_param) -{ +TEST_F(sinsp_with_test_input, bytebuf_empty_param) { add_default_init_thread(); open_inspector(); @@ -121,16 +117,22 @@ TEST_F(sinsp_with_test_input, bytebuf_empty_param) scap_const_sized_buffer bytebuf_param; bytebuf_param.buf = NULL; bytebuf_param.size = 0; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_PWRITE_X, 2, test_errno, bytebuf_param); - ASSERT_EQ(get_field_as_string(evt, "evt.arg.data"), "NULL"); // "NULL" is the string representation output of the empty buffer + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_PWRITE_X, + 2, + test_errno, + bytebuf_param); + ASSERT_EQ(get_field_as_string(evt, "evt.arg.data"), + "NULL"); // "NULL" is the string representation output of the empty buffer param = evt->get_param(1); ASSERT_EQ(param->m_len, 0); } -/* Assert that empty (`PT_SOCKADDR`, `PT_SOCKTUPLE`, `PT_FDLIST`) params are NOT converted to `` */ -TEST_F(sinsp_with_test_input, sockaddr_empty_param) -{ +/* Assert that empty (`PT_SOCKADDR`, `PT_SOCKTUPLE`, `PT_FDLIST`) params are NOT converted to `` + */ +TEST_F(sinsp_with_test_input, sockaddr_empty_param) { add_default_init_thread(); open_inspector(); @@ -151,7 +153,13 @@ TEST_F(sinsp_with_test_input, sockaddr_empty_param) scap_const_sized_buffer socktuple_param; socktuple_param.buf = NULL; socktuple_param.size = 0; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, fd, socktuple_param, fd); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + fd, + socktuple_param, + fd); param = evt->get_param(1); ASSERT_EQ(param->m_len, 0); @@ -164,35 +172,62 @@ TEST_F(sinsp_with_test_input, sockaddr_empty_param) ASSERT_EQ(param->m_len, 0); } -TEST_F(sinsp_with_test_input, filename_toctou) -{ - // for more information see https://github.com/falcosecurity/falco/security/advisories/GHSA-6v9j-2vm2-ghf7 +TEST_F(sinsp_with_test_input, filename_toctou) { + // for more information see + // https://github.com/falcosecurity/falco/security/advisories/GHSA-6v9j-2vm2-ghf7 add_default_init_thread(); - sinsp_evt *evt; + sinsp_evt* evt; open_inspector(); int64_t fd = 1, dirfd = 3; add_event(increasing_ts(), 3, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", 0, 0); - evt = add_event_advance_ts(increasing_ts(), 3, PPME_SYSCALL_OPEN_X, 6, fd, "/tmp/some_other_file", 0, 0, 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 3, + PPME_SYSCALL_OPEN_X, + 6, + fd, + "/tmp/some_other_file", + 0, + 0, + 0, + (uint64_t)0); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/the_file"); fd = 2; add_event(increasing_ts(), 1, PPME_SYSCALL_OPENAT_2_E, 4, dirfd, "/tmp/the_file", 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT_2_X, 7, fd, dirfd, "/tmp/some_other_file", 0, 0, 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT_2_X, + 7, + fd, + dirfd, + "/tmp/some_other_file", + 0, + 0, + 0, + (uint64_t)0); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/the_file"); fd = 4; add_event(increasing_ts(), 2, PPME_SYSCALL_CREAT_E, 2, "/tmp/the_file", 0); - evt = add_event_advance_ts(increasing_ts(), 2, PPME_SYSCALL_CREAT_X, 6, fd, "/tmp/some_other_file", 0, 0, (uint64_t) 0, (uint16_t) PPM_FD_LOWER_LAYER_CREAT); + evt = add_event_advance_ts(increasing_ts(), + 2, + PPME_SYSCALL_CREAT_X, + 6, + fd, + "/tmp/some_other_file", + 0, + 0, + (uint64_t)0, + (uint16_t)PPM_FD_LOWER_LAYER_CREAT); ASSERT_EQ(get_field_as_string(evt, "fd.name"), "/tmp/the_file"); } /* Assert that invalid params in enter events are not considered in the TOCTOU prevention logic. */ -TEST_F(sinsp_with_test_input, enter_event_retrieval) -{ +TEST_F(sinsp_with_test_input, enter_event_retrieval) { add_default_init_thread(); open_inspector(); @@ -206,12 +241,29 @@ TEST_F(sinsp_with_test_input, enter_event_retrieval) /* Check `openat` syscall. * `(NULL)` should be converted to `` and recognized as an invalid param. */ - for (const char *enter_filename : invalid_inputs) - { - std::string test_context = std::string("openat with filename ") + test_utils::describe_string(enter_filename); - - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT_2_E, 4, dirfd, enter_filename, 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT_2_X, 7, new_fd, dirfd, expected_string, 0, 0, 0, (uint64_t) 0); + for(const char* enter_filename : invalid_inputs) { + std::string test_context = + std::string("openat with filename ") + test_utils::describe_string(enter_filename); + + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT_2_E, + 4, + dirfd, + enter_filename, + 0, + 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT_2_X, + 7, + new_fd, + dirfd, + expected_string, + 0, + 0, + 0, + (uint64_t)0); ASSERT_NE(evt->get_thread_info(), nullptr) << test_context; ASSERT_NE(evt->get_thread_info()->get_fd(new_fd), nullptr) << test_context; @@ -224,12 +276,21 @@ TEST_F(sinsp_with_test_input, enter_event_retrieval) } /* Check `openat2` syscall. */ - for (const char *enter_filename : invalid_inputs) - { - std::string test_context = std::string("openat2 with filename ") + test_utils::describe_string(enter_filename); + for(const char* enter_filename : invalid_inputs) { + std::string test_context = + std::string("openat2 with filename ") + test_utils::describe_string(enter_filename); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT2_E, 5, dirfd, "", 0, 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT2_X, 6, new_fd, dirfd, expected_string, 0, 0, 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT2_X, + 6, + new_fd, + dirfd, + expected_string, + 0, + 0, + 0); ASSERT_NE(evt->get_thread_info(), nullptr) << test_context; ASSERT_NE(evt->get_thread_info()->get_fd(new_fd), nullptr) << test_context; @@ -242,12 +303,21 @@ TEST_F(sinsp_with_test_input, enter_event_retrieval) } /* Check `open` syscall. */ - for (const char *enter_filename : invalid_inputs) - { - std::string test_context = std::string("open with filename ") + test_utils::describe_string(enter_filename); + for(const char* enter_filename : invalid_inputs) { + std::string test_context = + std::string("open with filename ") + test_utils::describe_string(enter_filename); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, NULL, 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, new_fd, expected_string, 0, 0, 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + new_fd, + expected_string, + 0, + 0, + 0, + (uint64_t)0); ASSERT_NE(evt->get_thread_info(), nullptr) << test_context; ASSERT_NE(evt->get_thread_info()->get_fd(new_fd), nullptr) << test_context; @@ -259,12 +329,20 @@ TEST_F(sinsp_with_test_input, enter_event_retrieval) } /* Check `creat` syscall. */ - for (const char *enter_filename : invalid_inputs) - { - std::string test_context = std::string("creat with filename ") + test_utils::describe_string(enter_filename); + for(const char* enter_filename : invalid_inputs) { + std::string test_context = + std::string("creat with filename ") + test_utils::describe_string(enter_filename); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_CREAT_E, 2, NULL, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_CREAT_X, 5, new_fd, expected_string, 0, 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_CREAT_X, + 5, + new_fd, + expected_string, + 0, + 0, + (uint64_t)0); ASSERT_NE(evt->get_thread_info(), nullptr) << test_context; ASSERT_NE(evt->get_thread_info()->get_fd(new_fd), nullptr) << test_context; @@ -274,22 +352,46 @@ TEST_F(sinsp_with_test_input, enter_event_retrieval) new_fd++; } - } -// Check that the path in case of execve is correctly overwritten in case it was not possible to collect it from the -// entry event but it is possible to collect it from the exit event -TEST_F(sinsp_with_test_input, execve_invalid_path_entry) -{ +// Check that the path in case of execve is correctly overwritten in case it was not possible to +// collect it from the entry event but it is possible to collect it from the exit event +TEST_F(sinsp_with_test_input, execve_invalid_path_entry) { add_default_init_thread(); open_inspector(); - sinsp_evt *evt = NULL; + sinsp_evt* evt = NULL; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVE_19_E, 1, ""); scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVE_19_X, 23, (int64_t) 0, "/bin/test-exe", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "test-exe", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVE_19_X, + 23, + (int64_t)0, + "/bin/test-exe", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "test-exe", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); ASSERT_EQ(get_field_as_string(evt, "proc.name"), "test-exe"); } @@ -297,8 +399,7 @@ TEST_F(sinsp_with_test_input, execve_invalid_path_entry) /* Check that enum flags are correctly handled, * even when a single enum value is matched by multiple flags. */ -TEST_F(sinsp_with_test_input, enumparams) -{ +TEST_F(sinsp_with_test_input, enumparams) { add_default_init_thread(); open_inspector(); @@ -309,15 +410,14 @@ TEST_F(sinsp_with_test_input, enumparams) ASSERT_EQ(evt->get_param(0)->as(), PPM_AF_UNIX); - const char *val_str = NULL; + const char* val_str = NULL; evt->get_param_as_str(0, &val_str); // Since the enum value "1" matches multiple flags values, // we expect a space-separated list of them ASSERT_STREQ(val_str, "AF_LOCAL|AF_UNIX"); } -TEST_F(sinsp_with_test_input, enumparams_fcntl_dupfd) -{ +TEST_F(sinsp_with_test_input, enumparams_fcntl_dupfd) { add_default_init_thread(); open_inspector(); @@ -325,19 +425,18 @@ TEST_F(sinsp_with_test_input, enumparams_fcntl_dupfd) /* `PPME_SYSCALL_FCNTL_E` is a simple event that uses a PT_ENUMFLAGS32 (param 2) */ uint8_t flag = PPM_FCNTL_F_DUPFD; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_FCNTL_E, 2, (int64_t) 0, flag); + evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_FCNTL_E, 2, (int64_t)0, flag); ASSERT_EQ(evt->get_param(1)->as(), PPM_FCNTL_F_DUPFD); - const char *val_str = NULL; + const char* val_str = NULL; evt->get_param_as_str(1, &val_str); ASSERT_STREQ(val_str, "F_DUPFD"); } /* Check that bitmask flags are correctly handled */ -TEST_F(sinsp_with_test_input, bitmaskparams) -{ +TEST_F(sinsp_with_test_input, bitmaskparams) { add_default_init_thread(); open_inspector(); @@ -345,31 +444,37 @@ TEST_F(sinsp_with_test_input, bitmaskparams) int64_t dirfd = 0; /* `PPME_SYSCALL_OPENAT_E` is a simple event that uses a PT_FLAGS32 (param 3) */ - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPENAT_E, 4, dirfd, "/tmp/foo", PPM_O_RDONLY|PPM_O_CLOEXEC, 0); - - ASSERT_EQ(evt->get_param(2)->as(), PPM_O_RDONLY|PPM_O_CLOEXEC); - - const char *val_str = NULL; + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPENAT_E, + 4, + dirfd, + "/tmp/foo", + PPM_O_RDONLY | PPM_O_CLOEXEC, + 0); + + ASSERT_EQ(evt->get_param(2)->as(), PPM_O_RDONLY | PPM_O_CLOEXEC); + + const char* val_str = NULL; evt->get_param_as_str(2, &val_str); ASSERT_STREQ(val_str, "O_RDONLY|O_CLOEXEC"); } -TEST_F(sinsp_with_test_input, invalid_string_len) -{ +TEST_F(sinsp_with_test_input, invalid_string_len) { add_default_init_thread(); open_inspector(); int64_t test_errno = 0; - const char *content = "01234567890123456789"; + const char* content = "01234567890123456789"; size_t content_len = strlen(content); // `PPME_SYSCALL_CHDIR_X` is a simple event that uses a `PT_CHARBUF`. add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_CHDIR_E, 0); // create a regular event with a string - scap_evt *sevt = add_event(increasing_ts(), 1, PPME_SYSCALL_CHDIR_X, 2, test_errno, content); - + scap_evt* sevt = add_event(increasing_ts(), 1, PPME_SYSCALL_CHDIR_X, 2, test_errno, content); + // corrupt the event by overwriting a \0 in the middle of the string void* content_ptr = memmem(sevt, sevt->len, content, content_len); static_cast(content_ptr)[10] = '\0'; @@ -378,7 +483,8 @@ TEST_F(sinsp_with_test_input, invalid_string_len) libsinsp_logger()->add_stderr_log(); libsinsp_logger()->set_severity(sinsp_logger::SEV_DEBUG); - libsinsp_logger()->log("An error message and data dump is expected in this test.", sinsp_logger::SEV_DEBUG); + libsinsp_logger()->log("An error message and data dump is expected in this test.", + sinsp_logger::SEV_DEBUG); // process the event and generate an error. It will be printed. EXPECT_THROW(advance_ts_get_event(sevt->ts), sinsp_exception); } diff --git a/userspace/libsinsp/test/events_plugin.ut.cpp b/userspace/libsinsp/test/events_plugin.ut.cpp index 32b6939fdf..5ea139e2c1 100644 --- a/userspace/libsinsp/test/events_plugin.ut.cpp +++ b/userspace/libsinsp/test/events_plugin.ut.cpp @@ -21,74 +21,61 @@ limitations under the License. #include #include "test_utils.h" -const char* mock_plugin_get_version() -{ +const char* mock_plugin_get_version() { return "0.1.0"; } -const char* mock_plugin_get_required_api_version() -{ +const char* mock_plugin_get_required_api_version() { return PLUGIN_API_VERSION_STR; } -static const char* mock_plugin_get_name() -{ +static const char* mock_plugin_get_name() { return "sample_plugin"; } -const char* mock_plugin_get_description() -{ +const char* mock_plugin_get_description() { return "some sample plugin"; } -const char* mock_plugin_get_contact() -{ +const char* mock_plugin_get_contact() { return "some contact"; } -static uint32_t mock_plugin_get_id() -{ +static uint32_t mock_plugin_get_id() { return 999; } -static const char* mock_plugin_get_event_source() -{ +static const char* mock_plugin_get_event_source() { return "sample_source"; } -static ss_plugin_t* mock_plugin_init(const ss_plugin_init_input *input, ss_plugin_rc *rc) -{ +static ss_plugin_t* mock_plugin_init(const ss_plugin_init_input* input, ss_plugin_rc* rc) { *rc = SS_PLUGIN_SUCCESS; return NULL; } -static void mock_plugin_destroy(ss_plugin_t* p) -{ -} +static void mock_plugin_destroy(ss_plugin_t* p) {} -static const char* mock_plugin_get_last_error(ss_plugin_t* s) -{ +static const char* mock_plugin_get_last_error(ss_plugin_t* s) { return NULL; } -static ss_instance_t* mock_plugin_open(ss_plugin_t* s, const char* params, ss_plugin_rc* rc) -{ +static ss_instance_t* mock_plugin_open(ss_plugin_t* s, const char* params, ss_plugin_rc* rc) { *rc = SS_PLUGIN_FAILURE; return NULL; } -static void mock_plugin_close(ss_plugin_t* s, ss_instance_t* i) -{ -} +static void mock_plugin_close(ss_plugin_t* s, ss_instance_t* i) {} -static ss_plugin_rc mock_plugin_next_batch(ss_plugin_t* s, ss_instance_t* i, uint32_t *nevts, ss_plugin_event ***evts) -{ +static ss_plugin_rc mock_plugin_next_batch(ss_plugin_t* s, + ss_instance_t* i, + uint32_t* nevts, + ss_plugin_event*** evts) { *nevts = 0; return SS_PLUGIN_EOF; } -static void set_mock_plugin_api(plugin_api& api) -{ +static void set_mock_plugin_api(plugin_api& api) { memset(&api, 0, sizeof(plugin_api)); api.get_required_api_version = mock_plugin_get_required_api_version; api.get_version = mock_plugin_get_version; @@ -105,27 +92,24 @@ static void set_mock_plugin_api(plugin_api& api) api.next_batch = mock_plugin_next_batch; } -static std::shared_ptr register_plugin_api( - sinsp* i, - plugin_api& api, - const std::string& initcfg = "") -{ +static std::shared_ptr register_plugin_api(sinsp* i, + plugin_api& api, + const std::string& initcfg = "") { std::string err; auto pl = i->register_plugin(&api); - if (!pl->init(initcfg, err)) - { + if(!pl->init(initcfg, err)) { throw sinsp_exception(err); } return pl; } -TEST_F(sinsp_with_test_input, event_sources) -{ +TEST_F(sinsp_with_test_input, event_sources) { sinsp_evt* evt = NULL; - size_t syscall_source_idx = 0; // the "syscall" evt source is always the first one + size_t syscall_source_idx = 0; // the "syscall" evt source is always the first one std::string syscall_source_name = sinsp_syscall_event_source_name; const char sample_plugin_evtdata[256] = "hello world"; - auto plugindata = scap_const_sized_buffer{&sample_plugin_evtdata, strlen(sample_plugin_evtdata) + 1}; + auto plugindata = + scap_const_sized_buffer{&sample_plugin_evtdata, strlen(sample_plugin_evtdata) + 1}; add_default_init_thread(); open_inspector(); @@ -136,7 +120,16 @@ TEST_F(sinsp_with_test_input, event_sources) ASSERT_NO_THROW(register_plugin_api(&m_inspector, mock_api)); // regular events have the "syscall" event source - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (uint64_t)3, "/tmp/the_file", PPM_O_RDWR, 0, 5, (uint64_t)123); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)3, + "/tmp/the_file", + PPM_O_RDWR, + 0, + 5, + (uint64_t)123); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_OPEN_X); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx); ASSERT_EQ(std::string(evt->get_source_name()), syscall_source_name); @@ -150,7 +143,11 @@ TEST_F(sinsp_with_test_input, event_sources) container->m_id = "3ad7b26ded6d"; container->set_lookup_status(sinsp_container_lookup::state::SUCCESSFUL); std::string container_json = m_inspector.m_container_manager.container_to_json(*container); - evt = add_event_advance_ts(increasing_ts(), -1, PPME_CONTAINER_JSON_2_E, 1, container_json.c_str()); + evt = add_event_advance_ts(increasing_ts(), + -1, + PPME_CONTAINER_JSON_2_E, + 1, + container_json.c_str()); ASSERT_EQ(evt->get_type(), PPME_CONTAINER_JSON_2_E); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx); ASSERT_EQ(std::string(evt->get_source_name()), syscall_source_name); @@ -159,7 +156,7 @@ TEST_F(sinsp_with_test_input, event_sources) ASSERT_EQ(get_field_as_string(evt, "evt.asynctype"), "container"); // events coming from unknown plugins should have no event source - evt = add_event_advance_ts(increasing_ts(), 1, PPME_PLUGINEVENT_E, 2, (uint32_t) 1, plugindata); + evt = add_event_advance_ts(increasing_ts(), 1, PPME_PLUGINEVENT_E, 2, (uint32_t)1, plugindata); ASSERT_EQ(evt->get_type(), PPME_PLUGINEVENT_E); ASSERT_EQ(evt->get_source_idx(), sinsp_no_event_source_idx); ASSERT_EQ(evt->get_source_name(), sinsp_no_event_source_name); @@ -168,7 +165,12 @@ TEST_F(sinsp_with_test_input, event_sources) ASSERT_FALSE(field_has_value(evt, "evt.asynctype")); // events coming from registered plugins should have their event source - evt = add_event_advance_ts(increasing_ts(), 1, PPME_PLUGINEVENT_E, 2, (uint32_t) 999, plugindata); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_PLUGINEVENT_E, + 2, + (uint32_t)999, + plugindata); ASSERT_EQ(evt->get_type(), PPME_PLUGINEVENT_E); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx + 1); ASSERT_EQ(std::string(evt->get_source_name()), std::string(mock_plugin_get_event_source())); @@ -178,7 +180,13 @@ TEST_F(sinsp_with_test_input, event_sources) // async events with no plugin ID should have "syscall" source auto asyncname = "sampleasync"; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_ASYNCEVENT_E, 3, (uint32_t) 0, asyncname, plugindata); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_ASYNCEVENT_E, + 3, + (uint32_t)0, + asyncname, + plugindata); ASSERT_EQ(evt->get_type(), PPME_ASYNCEVENT_E); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx); ASSERT_EQ(std::string(evt->get_source_name()), syscall_source_name); @@ -188,7 +196,13 @@ TEST_F(sinsp_with_test_input, event_sources) ASSERT_EQ(get_field_as_string(evt, "evt.type"), "sampleasync"); // async events with a registered plugin ID should have the plugin's event source - evt = add_event_advance_ts(increasing_ts(), 1, PPME_ASYNCEVENT_E, 3, (uint32_t) 999, asyncname, plugindata); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_ASYNCEVENT_E, + 3, + (uint32_t)999, + asyncname, + plugindata); ASSERT_EQ(evt->get_type(), PPME_ASYNCEVENT_E); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx + 1); ASSERT_EQ(std::string(evt->get_source_name()), std::string(mock_plugin_get_event_source())); @@ -199,7 +213,13 @@ TEST_F(sinsp_with_test_input, event_sources) // async events with unknown plugin ID should have unknown event source // async events with a registered plugin ID should have the plugin's event source - evt = add_event_advance_ts(increasing_ts(), 1, PPME_ASYNCEVENT_E, 3, (uint32_t) 1, asyncname, plugindata); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_ASYNCEVENT_E, + 3, + (uint32_t)1, + asyncname, + plugindata); ASSERT_EQ(evt->get_type(), PPME_ASYNCEVENT_E); ASSERT_EQ(evt->get_source_idx(), sinsp_no_event_source_idx); ASSERT_EQ(evt->get_source_name(), sinsp_no_event_source_name); diff --git a/userspace/libsinsp/test/events_proc.ut.cpp b/userspace/libsinsp/test/events_proc.ut.cpp index 17d56cde55..e2f7588411 100644 --- a/userspace/libsinsp/test/events_proc.ut.cpp +++ b/userspace/libsinsp/test/events_proc.ut.cpp @@ -27,8 +27,7 @@ limitations under the License. * - `AT_EMPTY_PATH` flag * - an invalid `pathname` (), this is not considered if `AT_EMPTY_PATH` is specified */ -TEST_F(sinsp_with_test_input, execveat_empty_path_flag) -{ +TEST_F(sinsp_with_test_input, execveat_empty_path_flag) { add_default_init_thread(); open_inspector(); @@ -40,16 +39,57 @@ TEST_F(sinsp_with_test_input, execveat_empty_path_flag) int64_t dirfd = 3; const char *file_to_run = "/tmp/file_to_run"; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, file_to_run, 0, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, file_to_run, 0, 0, 0, (uint64_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + file_to_run, + 0, + 0, + 0, + (uint64_t)0); /* Now we call the `execveat_e` event,`sinsp` will store this enter * event in the thread storage, in this way the exit event can use it. */ - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_E, 3, dirfd, "", PPM_EXVAT_AT_EMPTY_PATH); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_E, + 3, + dirfd, + "", + PPM_EXVAT_AT_EMPTY_PATH); /* Please note the exit event for an `execveat` is an `execve` if the syscall succeeds. */ scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVE_19_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVE_19_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be the file pointed by the `dirfd` since `execveat` is called with * `AT_EMPTY_PATH` flag. @@ -60,15 +100,13 @@ TEST_F(sinsp_with_test_input, execveat_empty_path_flag) ASSERT_EQ(get_field_as_string(evt, "proc.exepath"), file_to_run); } - /* Assert if the thread `exepath` is set to the right value * if we call `execveat` in the following way: * - valid `dirfd` that points to the directory that contains the file we want to run. * - flags=0. * - a valid `pathname` relative to dirfd. */ -TEST_F(sinsp_with_test_input, execveat_relative_path) -{ +TEST_F(sinsp_with_test_input, execveat_relative_path) { add_default_init_thread(); open_inspector(); @@ -80,7 +118,16 @@ TEST_F(sinsp_with_test_input, execveat_relative_path) int64_t dirfd = 3; const char *directory = "/tmp/dir"; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, directory, 0, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, directory, 0, 0, 0, (uint64_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + directory, + 0, + 0, + 0, + (uint64_t)0); /* Now we call the `execveat_e` event,`sinsp` will store this enter * event in the thread storage, in this way the exit event can use it. @@ -89,7 +136,33 @@ TEST_F(sinsp_with_test_input, execveat_relative_path) /* Please note the exit event for an `execveat` is an `execve` if the syscall succeeds. */ scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVE_19_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVE_19_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be the directory pointed by the `dirfd` + the pathname * specified in the `execveat` enter event. @@ -109,8 +182,7 @@ TEST_F(sinsp_with_test_input, execveat_relative_path) * This test simulates the case in which we are not able to retrieve the path from the syscall * in the kernel. */ -TEST_F(sinsp_with_test_input, execveat_invalid_path) -{ +TEST_F(sinsp_with_test_input, execveat_invalid_path) { add_default_init_thread(); open_inspector(); @@ -122,7 +194,16 @@ TEST_F(sinsp_with_test_input, execveat_invalid_path) int64_t dirfd = 3; const char *directory = "/tmp/dir"; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, directory, 0, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, directory, 0, 0, 0, (uint64_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + directory, + 0, + 0, + 0, + (uint64_t)0); /* Now we call the `execveat_e` event,`sinsp` will store this enter * event in the thread storage, in this way the exit event can use it. @@ -131,7 +212,33 @@ TEST_F(sinsp_with_test_input, execveat_invalid_path) /* Please note the exit event for an `execveat` is an `execve` if the syscall succeeds. */ scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVE_19_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVE_19_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be ``, sinsp should recognize that the `pathname` * is invalid and should set ``. @@ -148,8 +255,7 @@ TEST_F(sinsp_with_test_input, execveat_invalid_path) * - flags=0. * - a valid absolute `pathname`. */ -TEST_F(sinsp_with_test_input, execveat_absolute_path) -{ +TEST_F(sinsp_with_test_input, execveat_absolute_path) { add_default_init_thread(); open_inspector(); @@ -159,11 +265,43 @@ TEST_F(sinsp_with_test_input, execveat_absolute_path) * event in the thread storage, in this way the exit event can use it. */ uint64_t invalid_dirfd = 0; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_E, 3, invalid_dirfd, "/tmp/file", (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_E, + 3, + invalid_dirfd, + "/tmp/file", + (uint32_t)0); /* Please note the exit event for an `execveat` is an `execve` if the syscall succeeds. */ scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVE_19_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVE_19_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be the absolute file path that we passed in the * `execveat` enter event. @@ -178,8 +316,7 @@ TEST_F(sinsp_with_test_input, execveat_absolute_path) * since on s390x architectures the `execveat` syscall correctly returns a `PPME_SYSCALL_EXECVEAT_X` * exit event in case of success. */ -TEST_F(sinsp_with_test_input, execveat_empty_path_flag_s390) -{ +TEST_F(sinsp_with_test_input, execveat_empty_path_flag_s390) { add_default_init_thread(); open_inspector(); @@ -191,15 +328,56 @@ TEST_F(sinsp_with_test_input, execveat_empty_path_flag_s390) int64_t dirfd = 3; const char *file_to_run = "/tmp/s390x/file_to_run"; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, file_to_run, 0, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, file_to_run, 0, 0, 0, (uint64_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + file_to_run, + 0, + 0, + 0, + (uint64_t)0); /* Now we call the `execveat_e` event,`sinsp` will store this enter * event in the thread storage, in this way the exit event can use it. */ - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_E, 3, dirfd, "", PPM_EXVAT_AT_EMPTY_PATH); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_E, + 3, + dirfd, + "", + PPM_EXVAT_AT_EMPTY_PATH); scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be the file pointed by the `dirfd` since `execveat` is called with * `AT_EMPTY_PATH` flag. @@ -214,8 +392,7 @@ TEST_F(sinsp_with_test_input, execveat_empty_path_flag_s390) * since on s390x architectures the `execveat` syscall correctly returns a `PPME_SYSCALL_EXECVEAT_X` * exit event in case of success. */ -TEST_F(sinsp_with_test_input, execveat_relative_path_s390) -{ +TEST_F(sinsp_with_test_input, execveat_relative_path_s390) { add_default_init_thread(); open_inspector(); @@ -227,7 +404,16 @@ TEST_F(sinsp_with_test_input, execveat_relative_path_s390) int64_t dirfd = 3; const char *directory = "/tmp/s390x/dir"; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, directory, 0, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, directory, 0, 0, 0, (uint64_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + directory, + 0, + 0, + 0, + (uint64_t)0); /* Now we call the `execveat_e` event,`sinsp` will store this enter * event in the thread storage, in this way the exit event can use it. @@ -235,7 +421,33 @@ TEST_F(sinsp_with_test_input, execveat_relative_path_s390) add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_E, 3, dirfd, "file", 0); scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be the directory pointed by the `dirfd` + the pathname * specified in the `execveat` enter event. @@ -251,8 +463,7 @@ TEST_F(sinsp_with_test_input, execveat_relative_path_s390) * since on s390x architectures the `execveat` syscall correctly returns a `PPME_SYSCALL_EXECVEAT_X` * exit event in case of success. */ -TEST_F(sinsp_with_test_input, execveat_absolute_path_s390) -{ +TEST_F(sinsp_with_test_input, execveat_absolute_path_s390) { add_default_init_thread(); open_inspector(); @@ -262,10 +473,42 @@ TEST_F(sinsp_with_test_input, execveat_absolute_path_s390) * event in the thread storage, in this way the exit event can use it. */ uint64_t invalid_dirfd = 0; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_E, 3, invalid_dirfd, "/tmp/s390/file", 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_E, + 3, + invalid_dirfd, + "/tmp/s390/file", + 0); scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be the absolute file path that we passed in the * `execveat` enter event. @@ -280,8 +523,7 @@ TEST_F(sinsp_with_test_input, execveat_absolute_path_s390) * since on s390x architectures the `execveat` syscall correctly returns a `PPME_SYSCALL_EXECVEAT_X` * exit event in case of success. */ -TEST_F(sinsp_with_test_input, execveat_invalid_path_s390) -{ +TEST_F(sinsp_with_test_input, execveat_invalid_path_s390) { add_default_init_thread(); open_inspector(); @@ -293,7 +535,16 @@ TEST_F(sinsp_with_test_input, execveat_invalid_path_s390) int64_t dirfd = 3; const char *directory = "/tmp/s390/dir"; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, directory, 0, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, directory, 0, 0, 0, (uint64_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + directory, + 0, + 0, + 0, + (uint64_t)0); /* Now we call the `execveat_e` event,`sinsp` will store this enter * event in the thread storage, in this way the exit event can use it. @@ -301,7 +552,33 @@ TEST_F(sinsp_with_test_input, execveat_invalid_path_s390) add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_E, 3, dirfd, "", 0); scap_const_sized_buffer empty_bytebuf = {nullptr, 0}; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EXECVEAT_X, 23, (int64_t) 0, "", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 1, "", (uint64_t) 0, (uint64_t) 0, (uint64_t) 0, 0, 0, 0, "", empty_bytebuf, empty_bytebuf, 0, (uint64_t) 0, 0, 0, (uint64_t) 0, (uint64_t) 0, (uint64_t) 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_EXECVEAT_X, + 23, + (int64_t)0, + "", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)1, + "", + (uint64_t)0, + (uint64_t)0, + (uint64_t)0, + 0, + 0, + 0, + "", + empty_bytebuf, + empty_bytebuf, + 0, + (uint64_t)0, + 0, + 0, + (uint64_t)0, + (uint64_t)0, + (uint64_t)0); /* The `exepath` should be ``, sinsp should recognize that the `pathname` * is invalid and should set ``. @@ -312,12 +589,11 @@ TEST_F(sinsp_with_test_input, execveat_invalid_path_s390) ASSERT_EQ(get_field_as_string(evt, "proc.exepath"), ""); } -TEST_F(sinsp_with_test_input, spawn_process) -{ +TEST_F(sinsp_with_test_input, spawn_process) { add_default_init_thread(); open_inspector(); - sinsp_evt* evt = NULL; + sinsp_evt *evt = NULL; uint64_t parent_pid = 1, parent_tid = 1, child_pid = 20, child_tid = 20, null_pid = 0; uint64_t fdlimit = 1024, pgft_maj = 0, pgft_min = 1; @@ -327,24 +603,116 @@ TEST_F(sinsp_with_test_input, spawn_process) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - std::vector cgroups = {"cpuset=/", "cpu=/user.slice", "cpuacct=/user.slice", "io=/user.slice", "memory=/user.slice/user-1000.slice/session-1.scope", "devices=/user.slice", "freezer=/", "net_cls=/", "perf_event=/", "net_prio=/", "hugetlb=/", "pids=/user.slice/user-1000.slice/session-1.scope", "rdma=/", "misc=/"}; + std::vector cgroups = {"cpuset=/", + "cpu=/user.slice", + "cpuacct=/user.slice", + "io=/user.slice", + "memory=/user.slice/user-1000.slice/session-1.scope", + "devices=/user.slice", + "freezer=/", + "net_cls=/", + "perf_event=/", + "net_prio=/", + "hugetlb=/", + "pids=/user.slice/user-1000.slice/session-1.scope", + "rdma=/", + "misc=/"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); - std::vector env = {"SHELL=/bin/bash", "SHELL_NEW=/bin/sh", "PWD=/home/user", "HOME=/home/user"}; + std::vector env = {"SHELL=/bin/bash", + "SHELL_NEW=/bin/sh", + "PWD=/home/user", + "HOME=/home/user"}; std::string envv = test_utils::to_null_delimited(env); std::vector args = {"-c", "'echo aGVsbG8K | base64 -d'"}; std::string argsv = test_utils::to_null_delimited(args); /* Parent clone exit event */ - add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, parent_pid, parent_tid, null_pid, "", fdlimit, pgft_maj, pgft_min, (uint32_t)12088, (uint32_t)7208, (uint32_t)0, "init", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t)1000, (uint32_t)1000, parent_pid, parent_tid); + add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + parent_pid, + parent_tid, + null_pid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "init", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + parent_pid, + parent_tid); /* Child clone exit event */ - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (uint64_t)0, "bash", empty_bytebuf, child_pid, child_tid, parent_tid, "", fdlimit, pgft_maj, pgft_min, (uint32_t)12088, (uint32_t)3764, (uint32_t)0, "init", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t)1000, (uint32_t)1000, child_pid, child_tid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (uint64_t)0, + "bash", + empty_bytebuf, + child_pid, + child_tid, + parent_tid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "init", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + child_pid, + child_tid); /* Execve enter event */ add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); /* Execve exit event */ - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 27, (int64_t)0, "/bin/test-exe", scap_const_sized_buffer{argsv.data(), argsv.size()}, child_tid, child_pid, parent_tid, "", fdlimit, pgft_maj, pgft_min, (uint32_t)29612, (uint32_t)4, (uint32_t)0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, scap_const_sized_buffer{envv.data(), envv.size()}, (int32_t)34818, parent_pid, loginuid, (int32_t)PPM_EXE_WRITABLE, parent_pid, parent_pid, parent_pid, exe_ino, ctime, mtime, euid); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 27, + (int64_t)0, + "/bin/test-exe", + scap_const_sized_buffer{argsv.data(), argsv.size()}, + child_tid, + child_pid, + parent_tid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + scap_const_sized_buffer{envv.data(), envv.size()}, + (int32_t)34818, + parent_pid, + loginuid, + (int32_t)PPM_EXE_WRITABLE, + parent_pid, + parent_pid, + parent_pid, + exe_ino, + ctime, + mtime, + euid); // check that the cwd is inherited from the parent (default process has /root/) ASSERT_EQ(get_field_as_string(evt, "proc.cwd"), "/root/"); @@ -376,7 +744,7 @@ TEST_F(sinsp_with_test_input, spawn_process) ASSERT_EQ(get_field_as_string(evt, "proc.sid.exepath"), "/sbin/init"); ASSERT_EQ(get_field_as_string(evt, "proc.is_sid_leader"), "false"); - //check process group leader (vpgid) related fields + // check process group leader (vpgid) related fields ASSERT_EQ(get_field_as_string(evt, "proc.vpgid"), "1"); ASSERT_EQ(get_field_as_string(evt, "proc.is_vpgid_leader"), "false"); ASSERT_EQ(get_field_as_string(evt, "proc.vpgid.name"), "init"); @@ -404,14 +772,16 @@ TEST_F(sinsp_with_test_input, spawn_process) ASSERT_FALSE(field_has_value(evt, "proc.apid[2]")); ASSERT_EQ(get_field_as_string(evt, "proc.cmdline"), "test-exe -c 'echo aGVsbG8K | base64 -d'"); ASSERT_EQ(get_field_as_string(evt, "proc.pcmdline"), "init"); - ASSERT_EQ(get_field_as_string(evt, "proc.acmdline[0]"), "test-exe -c 'echo aGVsbG8K | base64 -d'"); + ASSERT_EQ(get_field_as_string(evt, "proc.acmdline[0]"), + "test-exe -c 'echo aGVsbG8K | base64 -d'"); ASSERT_EQ(get_field_as_string(evt, "proc.acmdline"), "test-exe -c 'echo aGVsbG8K | base64 -d'"); ASSERT_EQ(get_field_as_string(evt, "proc.acmdline[1]"), "init"); ASSERT_FALSE(field_has_value(evt, "proc.acmdline[2]")); // check more fields ASSERT_EQ(get_field_as_string(evt, "proc.args"), "-c 'echo aGVsbG8K | base64 -d'"); - ASSERT_EQ(get_field_as_string(evt, "proc.exeline"), "/bin/test-exe -c 'echo aGVsbG8K | base64 -d'"); + ASSERT_EQ(get_field_as_string(evt, "proc.exeline"), + "/bin/test-exe -c 'echo aGVsbG8K | base64 -d'"); ASSERT_EQ(get_field_as_string(evt, "proc.tty"), "34818"); ASSERT_EQ(get_field_as_string(evt, "proc.vpgid"), "1"); ASSERT_EQ(get_field_as_string(evt, "user.loginuid"), "4294967294"); @@ -431,26 +801,33 @@ TEST_F(sinsp_with_test_input, spawn_process) ASSERT_EQ(get_field_as_string(evt, "proc.cmdlenargs"), "29"); ASSERT_EQ(get_field_as_string(evt, "proc.sname"), "init"); - ASSERT_EQ(get_field_as_string(evt, "proc.env"), "SHELL=/bin/bash SHELL_NEW=/bin/sh PWD=/home/user HOME=/home/user"); + ASSERT_EQ(get_field_as_string(evt, "proc.env"), + "SHELL=/bin/bash SHELL_NEW=/bin/sh PWD=/home/user HOME=/home/user"); ASSERT_EQ(get_field_as_string(evt, "proc.env[HOME]"), "/home/user"); ASSERT_EQ(get_field_as_string(evt, "proc.env[SHELL]"), "/bin/bash"); - ASSERT_EQ(get_field_as_string(evt, "proc.env[SHELL_NEW]"), "/bin/sh"); // test for prefix similarity - ASSERT_EQ(get_field_as_string(evt, "proc.aenv"), "SHELL=/bin/bash SHELL_NEW=/bin/sh PWD=/home/user HOME=/home/user"); - ASSERT_EQ(get_field_as_string(evt, "proc.aenv[0]"), "SHELL=/bin/bash SHELL_NEW=/bin/sh PWD=/home/user HOME=/home/user"); - ASSERT_EQ(get_field_as_string(evt, "proc.aenv[1]"), "TEST_ENV_PARENT_LINEAGE=secret HOME=/home/user/parent"); - ASSERT_EQ(get_field_as_string(evt, "proc.aenv[HOME]"), "/home/user/parent"); // the parent has /home/user/parent vs /home/user in the same named HOME env variable of the current proc + ASSERT_EQ(get_field_as_string(evt, "proc.env[SHELL_NEW]"), + "/bin/sh"); // test for prefix similarity + ASSERT_EQ(get_field_as_string(evt, "proc.aenv"), + "SHELL=/bin/bash SHELL_NEW=/bin/sh PWD=/home/user HOME=/home/user"); + ASSERT_EQ(get_field_as_string(evt, "proc.aenv[0]"), + "SHELL=/bin/bash SHELL_NEW=/bin/sh PWD=/home/user HOME=/home/user"); + ASSERT_EQ(get_field_as_string(evt, "proc.aenv[1]"), + "TEST_ENV_PARENT_LINEAGE=secret HOME=/home/user/parent"); + ASSERT_EQ(get_field_as_string(evt, "proc.aenv[HOME]"), + "/home/user/parent"); // the parent has /home/user/parent vs /home/user in the same + // named HOME env variable of the current proc ASSERT_EQ(get_field_as_string(evt, "proc.aenv[SHELL]"), ""); ASSERT_EQ(get_field_as_string(evt, "proc.aenv[TEST_ENV_PARENT_LINEAGE]"), "secret"); } // check parsing of container events (possibly from capture files) -#if !defined(MINIMAL_BUILD) and !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all -TEST_F(sinsp_with_test_input, spawn_process_container) -{ +#if !defined(MINIMAL_BUILD) and \ + !defined(__EMSCRIPTEN__) // MINIMAL_BUILD and emscripten don't support containers at all +TEST_F(sinsp_with_test_input, spawn_process_container) { add_default_init_thread(); open_inspector(); - sinsp_evt* evt = NULL; + sinsp_evt *evt = NULL; uint64_t parent_pid = 1, parent_tid = 1, child_pid = 20, child_tid = 20; uint64_t fdlimit = 1024, pgft_maj = 0, pgft_min = 1; @@ -460,26 +837,120 @@ TEST_F(sinsp_with_test_input, spawn_process_container) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - std::vector cgroups = {"cgroups=cpuset=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "cpu=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "cpuacct=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "io=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "memory=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "devices=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "freezer=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "net_cls=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "perf_event=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "net_prio=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "hugetlb=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "pids=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "rdma=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", "misc=/"}; + std::vector cgroups = { + "cgroups=cpuset=/docker/" + "f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "cpu=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "cpuacct=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "io=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "memory=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "devices=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "freezer=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "net_cls=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "perf_event=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "net_prio=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "hugetlb=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "pids=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "rdma=/docker/f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066", + "misc=/"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); std::vector env = {"SHELL=/bin/bash", "PWD=/home/user", "HOME=/home/user"}; std::string envv = test_utils::to_null_delimited(env); std::vector args = {"-c", "'echo aGVsbG8K | base64 -d'"}; std::string argsv = test_utils::to_null_delimited(args); - std::string container = R"({"container":{"Mounts":[],"cpu_period":100000,"cpu_quota":0,"cpu_shares":1024,"cpuset_cpu_count":0,"created_time":1663770709,"env":[],"full_id":"f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066","id":"f9c7a020960a","image":"ubuntu","imagedigest":"sha256:a0d9e826ab87bd665cfc640598a871b748b4b70a01a4f3d174d4fb02adad07a9","imageid":"597ce1600cf4ac5f449b66e75e840657bb53864434d6bd82f00b172544c32ee2","imagerepo":"ubuntu","imagetag":"latest","ip":"172.17.0.2","is_pod_sandbox":false,"labels":null,"lookup_state":1,"memory_limit":0,"metadata_deadline":0,"name":"eloquent_mirzakhani","port_mappings":[],"privileged":false,"swap_limit":0,"type":0}})"; + std::string container = + R"({"container":{"Mounts":[],"cpu_period":100000,"cpu_quota":0,"cpu_shares":1024,"cpuset_cpu_count":0,"created_time":1663770709,"env":[],"full_id":"f9c7a020960a15738167a77594bff1f7ac5f5bfdb6646ecbc9b17c7ed7ec5066","id":"f9c7a020960a","image":"ubuntu","imagedigest":"sha256:a0d9e826ab87bd665cfc640598a871b748b4b70a01a4f3d174d4fb02adad07a9","imageid":"597ce1600cf4ac5f449b66e75e840657bb53864434d6bd82f00b172544c32ee2","imagerepo":"ubuntu","imagetag":"latest","ip":"172.17.0.2","is_pod_sandbox":false,"labels":null,"lookup_state":1,"memory_limit":0,"metadata_deadline":0,"name":"eloquent_mirzakhani","port_mappings":[],"privileged":false,"swap_limit":0,"type":0}})"; /* Caller clone exit event. * The child is in a container the caller event won't generate the child thread info */ - add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, (uint64_t) 1, (uint64_t) 1, (uint64_t) 0, "", fdlimit, pgft_maj, pgft_min, (uint32_t) 12088, (uint32_t) 7208, (uint32_t) 0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t) (PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t) 1000, (uint32_t) 1000, (uint64_t) parent_tid, (uint64_t) parent_pid); + add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + (uint64_t)1, + (uint64_t)1, + (uint64_t)0, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)parent_tid, + (uint64_t)parent_pid); /* Child clone exit event */ - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (uint64_t) 0, "bash", empty_bytebuf, child_tid, child_pid, (uint64_t) 1, "", fdlimit, pgft_maj, pgft_min, (uint32_t) 12088, (uint32_t) 3764, (uint32_t) 0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t) (PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), (uint32_t) 1000, (uint32_t) 1000, (uint64_t) 1, (uint64_t) 1); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (uint64_t)0, + "bash", + empty_bytebuf, + child_tid, + child_pid, + (uint64_t)1, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID | + PPM_CL_CLONE_NEWPID | PPM_CL_CHILD_IN_PIDNS), + (uint32_t)1000, + (uint32_t)1000, + (uint64_t)1, + (uint64_t)1); add_event_advance_ts(increasing_ts(), -1, PPME_CONTAINER_JSON_2_E, 1, container.c_str()); add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 27, (int64_t) 0, "/bin/test-exe", scap_const_sized_buffer{argsv.data(), argsv.size()}, child_tid, child_pid, parent_tid, "", fdlimit, pgft_maj, pgft_min, (uint32_t) 29612, (uint32_t) 4, (uint32_t) 0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, scap_const_sized_buffer{envv.data(), envv.size()}, (int32_t) 34818, parent_pid, loginuid, (int32_t) PPM_EXE_UPPER_LAYER, parent_pid, parent_pid, parent_pid, exe_ino, ctime, mtime, euid); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 27, + (int64_t)0, + "/bin/test-exe", + scap_const_sized_buffer{argsv.data(), argsv.size()}, + child_tid, + child_pid, + parent_tid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + scap_const_sized_buffer{envv.data(), envv.size()}, + (int32_t)34818, + parent_pid, + loginuid, + (int32_t)PPM_EXE_UPPER_LAYER, + parent_pid, + parent_pid, + parent_pid, + exe_ino, + ctime, + mtime, + euid); // check that the container has been correctly detected and the short ID is correct ASSERT_EQ(get_field_as_string(evt, "container.id"), "f9c7a020960a"); @@ -493,23 +964,42 @@ TEST_F(sinsp_with_test_input, spawn_process_container) ASSERT_EQ(get_field_as_string(evt, "proc.is_exe_upper_layer"), "true"); ASSERT_EQ(get_field_as_string(evt, "user.uid"), "4294967295"); } -#endif // MINIMAL_BUILD +#endif // MINIMAL_BUILD -TEST_F(sinsp_with_test_input, chdir_fchdir) -{ +TEST_F(sinsp_with_test_input, chdir_fchdir) { add_default_init_thread(); open_inspector(); sinsp_evt *evt = NULL; add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_CHDIR_E, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_CHDIR_X, 2, (int64_t) 0, "/tmp/target-directory"); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_CHDIR_X, + 2, + (int64_t)0, + "/tmp/target-directory"); ASSERT_EQ(get_field_as_string(evt, "proc.cwd"), "/tmp/target-directory/"); // generate a fd associated with the directory we wish to change to int64_t dirfd = 3, test_errno = 0; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/target-directory-fd", 0, 0); - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, "/tmp/target-directory-fd", (uint32_t)0, (uint32_t)0, (uint32_t)0, (uint64_t)0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/target-directory-fd", + 0, + 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + "/tmp/target-directory-fd", + (uint32_t)0, + (uint32_t)0, + (uint32_t)0, + (uint64_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_FCHDIR_E, 1, dirfd); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_FCHDIR_X, 1, test_errno); @@ -519,12 +1009,11 @@ TEST_F(sinsp_with_test_input, chdir_fchdir) // Falco libs allow pid over 32bit, those are used to hold extra values in the high bits. // For example, this is used in gVisor to save the sandbox ID. // These PIDs are not meaningful to the user and should not be displayed -TEST_F(sinsp_with_test_input, pid_over_32bit) -{ +TEST_F(sinsp_with_test_input, pid_over_32bit) { add_default_init_thread(); open_inspector(); - sinsp_evt* evt = NULL; + sinsp_evt *evt = NULL; uint64_t parent_pid = 1, parent_tid = 1; uint64_t child_pid = 0x0000000100000010, child_tid = 0x0000000100000010; @@ -535,7 +1024,20 @@ TEST_F(sinsp_with_test_input, pid_over_32bit) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - std::vector cgroups = {"cpuset=/", "cpu=/user.slice", "cpuacct=/user.slice", "io=/user.slice", "memory=/user.slice/user-1000.slice/session-1.scope", "devices=/user.slice", "freezer=/", "net_cls=/", "perf_event=/", "net_prio=/", "hugetlb=/", "pids=/user.slice/user-1000.slice/session-1.scope", "rdma=/", "misc=/"}; + std::vector cgroups = {"cpuset=/", + "cpu=/user.slice", + "cpuacct=/user.slice", + "io=/user.slice", + "memory=/user.slice/user-1000.slice/session-1.scope", + "devices=/user.slice", + "freezer=/", + "net_cls=/", + "perf_event=/", + "net_prio=/", + "hugetlb=/", + "pids=/user.slice/user-1000.slice/session-1.scope", + "rdma=/", + "misc=/"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); std::vector env = {"SHELL=/bin/bash", "PWD=/home/user", "HOME=/home/user"}; std::string envv = test_utils::to_null_delimited(env); @@ -543,21 +1045,91 @@ TEST_F(sinsp_with_test_input, pid_over_32bit) std::string argsv = test_utils::to_null_delimited(args); /* Parent clone exit event */ - add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, parent_pid, parent_tid, (int64_t) 0, "", fdlimit, pgft_maj, pgft_min, (uint32_t)12088, (uint32_t)7208, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t) (PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t) 1000, (uint32_t) 1000, parent_pid, parent_tid); + add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + parent_pid, + parent_tid, + (int64_t)0, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + parent_pid, + parent_tid); /* Child clone exit event */ - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (int64_t) 0, "bash", empty_bytebuf, child_pid, child_tid, parent_tid, "", fdlimit, pgft_maj, pgft_min, (uint32_t)12088, (uint32_t)3764, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t) (PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t) 1000, (uint32_t) 1000, child_vpid, child_vtid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (int64_t)0, + "bash", + empty_bytebuf, + child_pid, + child_tid, + parent_tid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + child_vpid, + child_vtid); /* Execve enter event */ add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); /* Execve exit event */ - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 20, (int64_t) 0, "/bin/test-exe", scap_const_sized_buffer{argsv.data(), argsv.size()}, child_tid, child_pid, parent_tid, "", (uint64_t) 1024, (uint64_t) 0, (uint64_t) 28, (uint32_t) 29612, (uint32_t) 4, (uint32_t) 0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, scap_const_sized_buffer{envv.data(), envv.size()}, (uint32_t) 34818, parent_pid, (int32_t) 1000, (uint32_t) 1); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 20, + (int64_t)0, + "/bin/test-exe", + scap_const_sized_buffer{argsv.data(), argsv.size()}, + child_tid, + child_pid, + parent_tid, + "", + (uint64_t)1024, + (uint64_t)0, + (uint64_t)28, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + scap_const_sized_buffer{envv.data(), envv.size()}, + (uint32_t)34818, + parent_pid, + (int32_t)1000, + (uint32_t)1); ASSERT_FALSE(field_has_value(evt, "proc.pid")); ASSERT_FALSE(field_has_value(evt, "thread.tid")); - /* In the clone caller exit event we set `vtid=tid` and `vpid=pid` since we are never in a container. */ + /* In the clone caller exit event we set `vtid=tid` and `vpid=pid` since we are never in a + * container. */ ASSERT_EQ(get_field_as_string(evt, "proc.vpid"), "4294967312"); ASSERT_EQ(get_field_as_string(evt, "thread.vtid"), "4294967312"); @@ -567,16 +1139,89 @@ TEST_F(sinsp_with_test_input, pid_over_32bit) /* Child clone exit event * Please note that now we are calling the child exit event before the parent one. */ - add_event_advance_ts(increasing_ts(), child2_tid, PPME_SYSCALL_CLONE_20_X, 20, (int64_t) 0, "/bin/test-exe", empty_bytebuf, child2_pid, child2_tid, child_tid, "", fdlimit, pgft_maj, pgft_min, (uint32_t) 12088, (uint32_t) 3764, (uint32_t) 0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t) (PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t) 1000, (uint32_t) 1000, child2_vpid, child2_vtid); + add_event_advance_ts(increasing_ts(), + child2_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (int64_t)0, + "/bin/test-exe", + empty_bytebuf, + child2_pid, + child2_tid, + child_tid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + child2_vpid, + child2_vtid); /* Parent clone exit event */ - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, child2_tid, "/bin/test-exe", empty_bytebuf, child_pid, child_tid, child_tid, "", fdlimit, pgft_maj, pgft_min, (uint32_t) 12088, (uint32_t) 7208, (uint32_t) 0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t) (PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t) 1000, (uint32_t) 1000, child_vpid, child_vtid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child2_tid, + "/bin/test-exe", + empty_bytebuf, + child_pid, + child_tid, + child_tid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + child_vpid, + child_vtid); /* Execve enter event */ - add_event_advance_ts(increasing_ts(), child2_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe2"); + add_event_advance_ts(increasing_ts(), + child2_tid, + PPME_SYSCALL_EXECVE_19_E, + 1, + "/bin/test-exe2"); /* Execve exit event */ - evt = add_event_advance_ts(increasing_ts(), child2_tid, PPME_SYSCALL_EXECVE_19_X, 20, (int64_t) 0, "/bin/test-exe2", scap_const_sized_buffer{argsv.data(), argsv.size()}, child2_tid, child2_pid, child_tid, "", fdlimit, pgft_maj, pgft_min, (uint32_t) 29612, (uint32_t) 4, (uint32_t) 0, "test-exe2", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, scap_const_sized_buffer{envv.data(), envv.size()}, (uint32_t) 34818, child_pid, (int32_t) 1000, (uint32_t) 1); + evt = add_event_advance_ts(increasing_ts(), + child2_tid, + PPME_SYSCALL_EXECVE_19_X, + 20, + (int64_t)0, + "/bin/test-exe2", + scap_const_sized_buffer{argsv.data(), argsv.size()}, + child2_tid, + child2_pid, + child_tid, + "", + fdlimit, + pgft_maj, + pgft_min, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe2", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + scap_const_sized_buffer{envv.data(), envv.size()}, + (uint32_t)34818, + child_pid, + (int32_t)1000, + (uint32_t)1); ASSERT_FALSE(field_has_value(evt, "proc.pid")); ASSERT_FALSE(field_has_value(evt, "thread.tid")); @@ -588,8 +1233,7 @@ TEST_F(sinsp_with_test_input, pid_over_32bit) ASSERT_EQ(get_field_as_string(evt, "thread.vtid"), "3"); } -TEST_F(sinsp_with_test_input, existing_proc) -{ +TEST_F(sinsp_with_test_input, existing_proc) { add_default_init_thread(); open_inspector(); @@ -597,12 +1241,11 @@ TEST_F(sinsp_with_test_input, existing_proc) ASSERT_EQ(m_inspector.m_thread_manager->get_thread_count(), 1); } -TEST_F(sinsp_with_test_input, last_exec_ts) -{ +TEST_F(sinsp_with_test_input, last_exec_ts) { add_default_init_thread(); open_inspector(); - sinsp_evt* evt = NULL; + sinsp_evt *evt = NULL; uint64_t parent_pid = 1, parent_tid = 1; uint64_t child_pid = 0x0000000100000010, child_tid = 0x0000000100000010; @@ -610,21 +1253,103 @@ TEST_F(sinsp_with_test_input, last_exec_ts) scap_const_sized_buffer empty_bytebuf = {.buf = nullptr, .size = 0}; add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_E, 0); - std::vector cgroups = {"cpuset=/", "cpu=/user.slice", "cpuacct=/user.slice", "io=/user.slice", "memory=/user.slice/user-1000.slice/session-1.scope", "devices=/user.slice", "freezer=/", "net_cls=/", "perf_event=/", "net_prio=/", "hugetlb=/", "pids=/user.slice/user-1000.slice/session-1.scope", "rdma=/", "misc=/"}; + std::vector cgroups = {"cpuset=/", + "cpu=/user.slice", + "cpuacct=/user.slice", + "io=/user.slice", + "memory=/user.slice/user-1000.slice/session-1.scope", + "devices=/user.slice", + "freezer=/", + "net_cls=/", + "perf_event=/", + "net_prio=/", + "hugetlb=/", + "pids=/user.slice/user-1000.slice/session-1.scope", + "rdma=/", + "misc=/"}; std::string cgroupsv = test_utils::to_null_delimited(cgroups); std::vector env = {"SHELL=/bin/bash", "PWD=/home/user", "HOME=/home/user"}; std::string envv = test_utils::to_null_delimited(env); std::vector args = {"--help"}; std::string argsv = test_utils::to_null_delimited(args); - evt = add_event_advance_ts(increasing_ts(), parent_tid, PPME_SYSCALL_CLONE_20_X, 20, child_tid, "bash", empty_bytebuf, parent_pid, parent_tid, (uint64_t)0, "", (uint64_t)1024, (uint64_t)0, (uint64_t)68633, (uint32_t)12088, (uint32_t)7208, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t)1000, (uint32_t)1000, parent_pid, parent_tid); + evt = add_event_advance_ts(increasing_ts(), + parent_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + child_tid, + "bash", + empty_bytebuf, + parent_pid, + parent_tid, + (uint64_t)0, + "", + (uint64_t)1024, + (uint64_t)0, + (uint64_t)68633, + (uint32_t)12088, + (uint32_t)7208, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + parent_pid, + parent_tid); ASSERT_TRUE(evt->get_thread_info()); // Check we initialize lastexec time to zero ASSERT_EQ(evt->get_thread_info()->m_lastexec_ts, 0); - add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_CLONE_20_X, 20, (uint64_t)0, "bash", empty_bytebuf, child_pid, child_tid, parent_tid, "", (uint64_t)1024, (uint64_t)0, (uint64_t)1, (uint32_t)12088, (uint32_t)3764, (uint32_t)0, "bash", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), (uint32_t)1000, (uint32_t)1000, child_vpid, child_vtid); + add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_CLONE_20_X, + 20, + (uint64_t)0, + "bash", + empty_bytebuf, + child_pid, + child_tid, + parent_tid, + "", + (uint64_t)1024, + (uint64_t)0, + (uint64_t)1, + (uint32_t)12088, + (uint32_t)3764, + (uint32_t)0, + "bash", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + (uint32_t)(PPM_CL_CLONE_CHILD_CLEARTID | PPM_CL_CLONE_CHILD_SETTID), + (uint32_t)1000, + (uint32_t)1000, + child_vpid, + child_vtid); add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_E, 1, "/bin/test-exe"); - evt = add_event_advance_ts(increasing_ts(), child_tid, PPME_SYSCALL_EXECVE_19_X, 20, (int64_t) 0, "/bin/test-exe", scap_const_sized_buffer{argsv.data(), argsv.size()}, child_tid, child_pid, parent_tid, "", (uint64_t)1024, (uint64_t)0, (uint64_t)28, (uint32_t)29612, (uint32_t)4, (uint32_t)0, "test-exe", scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, scap_const_sized_buffer{envv.data(), envv.size()}, (uint32_t)34818, parent_pid, (uint32_t)1000, (uint32_t)1); + evt = add_event_advance_ts(increasing_ts(), + child_tid, + PPME_SYSCALL_EXECVE_19_X, + 20, + (int64_t)0, + "/bin/test-exe", + scap_const_sized_buffer{argsv.data(), argsv.size()}, + child_tid, + child_pid, + parent_tid, + "", + (uint64_t)1024, + (uint64_t)0, + (uint64_t)28, + (uint32_t)29612, + (uint32_t)4, + (uint32_t)0, + "test-exe", + scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}, + scap_const_sized_buffer{envv.data(), envv.size()}, + (uint32_t)34818, + parent_pid, + (uint32_t)1000, + (uint32_t)1); // Check last exec was recorded ASSERT_GT(evt->get_thread_info()->m_lastexec_ts, 0); diff --git a/userspace/libsinsp/test/events_user.ut.cpp b/userspace/libsinsp/test/events_user.ut.cpp index cf340cf3be..94923a1b7a 100644 --- a/userspace/libsinsp/test/events_user.ut.cpp +++ b/userspace/libsinsp/test/events_user.ut.cpp @@ -21,10 +21,8 @@ limitations under the License. #include #include "test_utils.h" - // test user tracking with setuid -TEST_F(sinsp_with_test_input, setuid_setgid) -{ +TEST_F(sinsp_with_test_input, setuid_setgid) { add_default_init_thread(); open_inspector(); sinsp_evt* evt; @@ -64,10 +62,8 @@ TEST_F(sinsp_with_test_input, setuid_setgid) ASSERT_EQ(get_field_as_string(evt, "group.gid"), "600"); } - // test user tracking with setresuid -TEST_F(sinsp_with_test_input, setresuid_setresgid) -{ +TEST_F(sinsp_with_test_input, setresuid_setresgid) { add_default_init_thread(); open_inspector(); sinsp_evt* evt; diff --git a/userspace/libsinsp/test/external_processor.ut.cpp b/userspace/libsinsp/test/external_processor.ut.cpp index 718988c976..29a64abba0 100644 --- a/userspace/libsinsp/test/external_processor.ut.cpp +++ b/userspace/libsinsp/test/external_processor.ut.cpp @@ -21,14 +21,12 @@ limitations under the License. using namespace libsinsp; -class sinsp_external_processor_dummy : public event_processor -{ +class sinsp_external_processor_dummy : public event_processor { void on_capture_start() override {} void process_event(sinsp_evt* evt, event_return rc) override {} }; -TEST(sinsp, external_event_processor_initialization) -{ +TEST(sinsp, external_event_processor_initialization) { sinsp my_sinsp; EXPECT_EQ(my_sinsp.get_external_event_processor(), nullptr); sinsp_external_processor_dummy processor; diff --git a/userspace/libsinsp/test/filter_compiler.ut.cpp b/userspace/libsinsp/test/filter_compiler.ut.cpp index 1a9a15aedf..701fccbd1d 100644 --- a/userspace/libsinsp/test/filter_compiler.ut.cpp +++ b/userspace/libsinsp/test/filter_compiler.ut.cpp @@ -9,67 +9,56 @@ using namespace std; // A mock filtercheck that returns always true or false depending on // the passed-in field name. The operation is ignored. -class mock_compiler_filter_check : public sinsp_filter_check -{ +class mock_compiler_filter_check : public sinsp_filter_check { public: - int32_t parse_field_name(std::string_view str, bool alloc_state, bool needed_for_filtering) override - { - static const std::unordered_set s_supported_fields = { - "c.true", "c.false", "c.buffer", "c.doublequote", "c.singlequote" - }; + int32_t parse_field_name(std::string_view str, + bool alloc_state, + bool needed_for_filtering) override { + static const std::unordered_set s_supported_fields = {"c.true", + "c.false", + "c.buffer", + "c.doublequote", + "c.singlequote"}; m_name = str; - if (str == "c.buffer") - { + if(str == "c.buffer") { m_field_info.m_type = PT_BYTEBUF; } - if (s_supported_fields.find(m_name) != s_supported_fields.end()) - { + if(s_supported_fields.find(m_name) != s_supported_fields.end()) { return m_name.size(); } return -1; } - inline bool compare(sinsp_evt*) override - { - if (m_name == "c.true") - { + inline bool compare(sinsp_evt*) override { + if(m_name == "c.true") { return true; } - if (m_name == "c.false" || m_name == "c.buffer") - { + if(m_name == "c.false" || m_name == "c.buffer") { return false; } - if (m_name == "c.doublequote") - { + if(m_name == "c.doublequote") { return m_value == "hello \"quoted\""; } - if (m_name == "c.singlequote") - { + if(m_name == "c.singlequote") { return m_value == "hello 'quoted'"; } return false; } - const filtercheck_field_info* get_field_info() const override - { - return &m_field_info; - } + const filtercheck_field_info* get_field_info() const override { return &m_field_info; } - inline void add_filter_value(const char* str, uint32_t l, uint32_t i) override - { + inline void add_filter_value(const char* str, uint32_t l, uint32_t i) override { m_value = string(str, l); } - inline void add_filter_value(std::unique_ptr f) override - { + inline void add_filter_value(std::unique_ptr f) override { throw sinsp_exception("unexpected right-hand side filter comparison"); } - inline bool extract_nocache(sinsp_evt *e, vector& v, bool) override - { + inline bool extract_nocache(sinsp_evt* e, vector& v, bool) override { return false; } @@ -78,62 +67,56 @@ class mock_compiler_filter_check : public sinsp_filter_check filtercheck_field_info m_field_info{PT_CHARBUF, 0, PF_NA, "", "", ""}; }; -struct test_sinsp_filter_cache_factory: public exprstr_sinsp_filter_cache_factory -{ +struct test_sinsp_filter_cache_factory : public exprstr_sinsp_filter_cache_factory { bool docache = true; - const std::shared_ptr metrics = std::make_shared(); + const std::shared_ptr metrics = + std::make_shared(); virtual ~test_sinsp_filter_cache_factory() = default; - test_sinsp_filter_cache_factory(bool cached = true): docache(cached) { } + test_sinsp_filter_cache_factory(bool cached = true): docache(cached) {} - std::shared_ptr new_extract_cache(const ast_expr_t* e, node_info_t& info) override - { - if (!docache) - { + std::shared_ptr new_extract_cache(const ast_expr_t* e, + node_info_t& info) override { + if(!docache) { return nullptr; } return exprstr_sinsp_filter_cache_factory::new_extract_cache(e, info); - } + } - std::shared_ptr new_compare_cache(const ast_expr_t* e, node_info_t& info) override - { - if (!docache) - { + std::shared_ptr new_compare_cache(const ast_expr_t* e, + node_info_t& info) override { + if(!docache) { return nullptr; } return exprstr_sinsp_filter_cache_factory::new_compare_cache(e, info); - } + } - std::shared_ptr new_metrics(const ast_expr_t* e, node_info_t& info) override - { - return metrics; - } + std::shared_ptr new_metrics(const ast_expr_t* e, + node_info_t& info) override { + return metrics; + } }; // A factory that creates mock filterchecks -class mock_compiler_filter_factory: public sinsp_filter_factory -{ +class mock_compiler_filter_factory : public sinsp_filter_factory { public: - mock_compiler_filter_factory(sinsp *inspector): sinsp_filter_factory(inspector, m_filterlist) {} + mock_compiler_filter_factory(sinsp* inspector): sinsp_filter_factory(inspector, m_filterlist) {} - inline std::unique_ptr new_filtercheck(std::string_view fldname) const override - { - if (mock_compiler_filter_check{}.parse_field_name(fldname, false, true) > 0) - { + inline std::unique_ptr new_filtercheck( + std::string_view fldname) const override { + if(mock_compiler_filter_check{}.parse_field_name(fldname, false, true) > 0) { return std::make_unique(); } - if (auto check = sinsp_filter_factory::new_filtercheck(fldname); check != nullptr) - { + if(auto check = sinsp_filter_factory::new_filtercheck(fldname); check != nullptr) { return check; } return nullptr; } - inline list get_fields() const override - { + inline list get_fields() const override { return m_list; } @@ -144,65 +127,48 @@ class mock_compiler_filter_factory: public sinsp_filter_factory // Compile a filter, pass a mock event to it, and // check that the result of the boolean evaluation is // the expected one -void test_filter_run(bool result, string filter_str) -{ +void test_filter_run(bool result, string filter_str) { sinsp inspector; auto factory = std::make_shared(&inspector); sinsp_filter_compiler compiler(factory, filter_str); - try - { + try { auto filter = compiler.compile(); - if (filter->run(NULL) != result) - { + if(filter->run(NULL) != result) { FAIL() << filter_str << " -> unexpected '" << (result ? "false" : "true") << "' result"; } - } - catch(const std::exception& e) - { + } catch(const std::exception& e) { FAIL() << filter_str << " -> " << e.what(); - } - catch(...) - { + } catch(...) { FAIL() << filter_str << " -> " << "UNKNOWN ERROR"; } } -void test_filter_compile( - std::shared_ptr factory, - string filter_str, - bool expect_fail=false, - size_t expected_warnings=0) -{ +void test_filter_compile(std::shared_ptr factory, + string filter_str, + bool expect_fail = false, + size_t expected_warnings = 0) { sinsp_filter_compiler compiler(factory, filter_str); - try - { + try { auto filter = compiler.compile(); - if (expect_fail) - { + if(expect_fail) { FAIL() << filter_str << " -> expected failure but compilation was successful"; } - } - catch(const std::exception& e) - { - if (!expect_fail) - { + } catch(const std::exception& e) { + if(!expect_fail) { FAIL() << filter_str << " -> " << e.what(); } - } - catch(...) - { - if (!expect_fail) - { + } catch(...) { + if(!expect_fail) { FAIL() << filter_str << " -> " << "UNKNOWN ERROR"; } } std::string warnings_fmt; - for (const auto& warn : compiler.get_warnings()) - { + for(const auto& warn : compiler.get_warnings()) { warnings_fmt.append("\n").append(warn.pos.as_string()).append(" -> ").append(warn.msg); } - ASSERT_EQ(compiler.get_warnings().size(), expected_warnings) << "filter: " + filter_str + "\nactual warnings: " + warnings_fmt; + ASSERT_EQ(compiler.get_warnings().size(), expected_warnings) + << "filter: " + filter_str + "\nactual warnings: " + warnings_fmt; } // In each of these test cases, we compile filter expression @@ -210,44 +176,42 @@ void test_filter_compile( // so that we can deterministically check the result of running // a mock event in the compiled filters. The purpose is verifying // that the compiler constructs valid boolean expressions. -TEST(sinsp_filter_compiler, boolean_evaluation) -{ - test_filter_run(true, "c.true=1"); +TEST(sinsp_filter_compiler, boolean_evaluation) { + test_filter_run(true, "c.true=1"); test_filter_run(false, "c.false=1"); test_filter_run(false, "not c.true=1"); test_filter_run(false, "not(c.true=1)"); - test_filter_run(true, "not not c.true=1"); - test_filter_run(true, "not not(c.true=1)"); - test_filter_run(true, "not (not c.true=1)"); + test_filter_run(true, "not not c.true=1"); + test_filter_run(true, "not not(c.true=1)"); + test_filter_run(true, "not (not c.true=1)"); test_filter_run(false, "not not not c.true=1"); test_filter_run(false, "not not not(c.true=1)"); test_filter_run(false, "not (not (not c.true=1))"); test_filter_run(false, "not(not(not c.true=1))"); - test_filter_run(true, "not not not not c.true=1"); - test_filter_run(true, "not not(not not c.true=1)"); - test_filter_run(true, "c.true=1 and c.true=1"); + test_filter_run(true, "not not not not c.true=1"); + test_filter_run(true, "not not(not not c.true=1)"); + test_filter_run(true, "c.true=1 and c.true=1"); test_filter_run(false, "c.true=1 and c.false=1"); test_filter_run(false, "c.false=1 and c.true=1"); test_filter_run(false, "c.false=1 and c.false=1"); test_filter_run(false, "c.true=1 and not c.true=1"); test_filter_run(false, "not c.true=1 and c.true=1"); - test_filter_run(true, "c.true=1 or c.true=1"); - test_filter_run(true, "c.true=1 or c.false=1"); - test_filter_run(true, "c.false=1 or c.true=1"); + test_filter_run(true, "c.true=1 or c.true=1"); + test_filter_run(true, "c.true=1 or c.false=1"); + test_filter_run(true, "c.false=1 or c.true=1"); test_filter_run(false, "c.false=1 or c.false=1"); - test_filter_run(true, "c.false=1 or not c.false=1"); - test_filter_run(true, "not c.false=1 or c.false=1"); - test_filter_run(true, "c.true=1 or c.true=1 and c.false=1"); + test_filter_run(true, "c.false=1 or not c.false=1"); + test_filter_run(true, "not c.false=1 or c.false=1"); + test_filter_run(true, "c.true=1 or c.true=1 and c.false=1"); test_filter_run(false, "(c.true=1 or c.true=1) and c.false=1"); - test_filter_run(true, "not (not (c.true=1 or c.true=1) and c.false=1)"); + test_filter_run(true, "not (not (c.true=1 or c.true=1) and c.false=1)"); test_filter_run(false, "not (c.false=1 or c.false=1 or c.true=1)"); - test_filter_run(true, "not (c.false=1 or c.false=1 and not c.true=1)"); + test_filter_run(true, "not (c.false=1 or c.false=1 and not c.true=1)"); test_filter_run(false, "not (c.false=1 or not c.false=1 and c.true=1)"); test_filter_run(false, "not ((c.false=1 or not (c.false=1 and not c.true=1)) and c.true=1)"); } -TEST(sinsp_filter_compiler, str_escape) -{ +TEST(sinsp_filter_compiler, str_escape) { test_filter_run(true, "c.singlequote = 'hello \\'quoted\\''"); test_filter_run(true, "c.singlequote = \"hello 'quoted'\""); test_filter_run(true, "c.doublequote = 'hello \"quoted\"'"); @@ -259,8 +223,7 @@ TEST(sinsp_filter_compiler, str_escape) test_filter_run(false, "c.doublequote = 'hello \"\"quoted\"\"'"); } -TEST(sinsp_filter_compiler, supported_operators) -{ +TEST(sinsp_filter_compiler, supported_operators) { sinsp inspector; std::shared_ptr factory(new mock_compiler_filter_factory(&inspector)); @@ -294,8 +257,7 @@ TEST(sinsp_filter_compiler, supported_operators) test_filter_compile(factory, "c.buffer bstartswith abc_1", true); } -TEST(sinsp_filter_compiler, operators_field_types_compatibility) -{ +TEST(sinsp_filter_compiler, operators_field_types_compatibility) { sinsp inspector; sinsp_filter_check_list filterlist; auto factory = std::make_shared(&inspector, filterlist); @@ -320,7 +282,7 @@ TEST(sinsp_filter_compiler, operators_field_types_compatibility) test_filter_compile(factory, "evt.rawtime bstartswith 303000", true); test_filter_compile(factory, "evt.rawtime iglob 1", true); test_filter_compile(factory, "evt.rawtime regex '1'", true); - + // PT_BOOL test_filter_compile(factory, "evt.is_io exists"); test_filter_compile(factory, "evt.is_io = true"); @@ -597,8 +559,7 @@ TEST(sinsp_filter_compiler, operators_field_types_compatibility) test_filter_compile(factory, "evt.num regex '1'", true); } -TEST(sinsp_filter_compiler, complex_filter) -{ +TEST(sinsp_filter_compiler, complex_filter) { sinsp inspector; std::shared_ptr factory(new mock_compiler_filter_factory(&inspector)); @@ -608,34 +569,34 @@ TEST(sinsp_filter_compiler, complex_filter) // The rule has been expanded with all its Falco macros, lists, // and exceptions, so it makes a good integration test case. string filter_str = - "(" - " (evt.type = open or evt.type = openat)" - " and evt.is_open_write = true" - " and fd.typechar = f" - " and fd.num >= 0" - ")" - "and (" - " fd.filename in (" - " .bashrc, .bash_profile, .bash_history, .bash_login," - " .bash_logout, .inputrc, .profile, .cshrc, .login, .logout," - " .history, .tcshrc, .cshdirs, .zshenv, .zprofile, .zshrc," - " .zlogin, .zlogout" - " )" - " or fd.name in (/etc/profile, /etc/bashrc, /etc/csh.cshrc, /etc/csh.login)" - " or fd.directory in (/etc/zsh)" - ")" - "and not proc.name in (ash, bash, csh, ksh, sh, tcsh, zsh, dash)" - "and not (" - " proc.name = exe" - " and (proc.cmdline contains \"/var/lib/docker\" or proc.cmdline contains '/var/run/docker')" - " and proc.pname in (dockerd, docker, dockerd-current, docker-current)" - ")"; + "(" + " (evt.type = open or evt.type = openat)" + " and evt.is_open_write = true" + " and fd.typechar = f" + " and fd.num >= 0" + ")" + "and (" + " fd.filename in (" + " .bashrc, .bash_profile, .bash_history, .bash_login," + " .bash_logout, .inputrc, .profile, .cshrc, .login, .logout," + " .history, .tcshrc, .cshdirs, .zshenv, .zprofile, .zshrc," + " .zlogin, .zlogout" + " )" + " or fd.name in (/etc/profile, /etc/bashrc, /etc/csh.cshrc, /etc/csh.login)" + " or fd.directory in (/etc/zsh)" + ")" + "and not proc.name in (ash, bash, csh, ksh, sh, tcsh, zsh, dash)" + "and not (" + " proc.name = exe" + " and (proc.cmdline contains \"/var/lib/docker\" or proc.cmdline contains " + "'/var/run/docker')" + " and proc.pname in (dockerd, docker, dockerd-current, docker-current)" + ")"; test_filter_compile(factory, filter_str); } -TEST(sinsp_filter_compiler, compilation_warnings) -{ +TEST(sinsp_filter_compiler, compilation_warnings) { sinsp inspector; std::shared_ptr factory(new mock_compiler_filter_factory(&inspector)); @@ -671,24 +632,22 @@ TEST(sinsp_filter_compiler, compilation_warnings) // Test filter strings against real events. ////////////////////////////// -TEST_F(sinsp_with_test_input, filter_simple_evaluation) -{ +TEST_F(sinsp_with_test_input, filter_simple_evaluation) { // Basic case just to assert that the basic setup works add_default_init_thread(); open_inspector(); - sinsp_evt * evt = generate_getcwd_failed_entry_event(); + sinsp_evt* evt = generate_getcwd_failed_entry_event(); ASSERT_TRUE(eval_filter(evt, "(evt.type = getcwd)")); ASSERT_TRUE(eval_filter(evt, "(evt.arg.res = val(evt.arg.res))")); } -TEST_F(sinsp_with_test_input, filter_val_transformer) -{ +TEST_F(sinsp_with_test_input, filter_val_transformer) { add_default_init_thread(); open_inspector(); - // Please note that with `evt.args = evt.args` we are evaluating the field `evt.args` against the const value - // `evt.args`. + // Please note that with `evt.args = evt.args` we are evaluating the field `evt.args` against + // the const value `evt.args`. - sinsp_evt * evt = generate_getcwd_failed_entry_event(); + sinsp_evt* evt = generate_getcwd_failed_entry_event(); ASSERT_FALSE(eval_filter(evt, "(evt.args = evt.args)")); ASSERT_TRUE(eval_filter(evt, "(evt.args = val(evt.args))")); @@ -703,31 +662,29 @@ TEST_F(sinsp_with_test_input, filter_val_transformer) ASSERT_FALSE(filter_compiles("(syscall.type = val(syscall.type, evt.type))")); } -TEST_F(sinsp_with_test_input, filter_transformers_combination) -{ +TEST_F(sinsp_with_test_input, filter_transformers_combination) { add_default_init_thread(); open_inspector(); - sinsp_evt * evt = generate_getcwd_failed_entry_event(); + sinsp_evt* evt = generate_getcwd_failed_entry_event(); ASSERT_TRUE(eval_filter(evt, "(tolower(syscall.type) = getcwd)")); ASSERT_TRUE(eval_filter(evt, "(toupper(syscall.type) = GETCWD)")); ASSERT_TRUE(eval_filter(evt, "(tolower(toupper(syscall.type)) = getcwd)")); ASSERT_TRUE(eval_filter(evt, "(tolower(syscall.type) = tolower(syscall.type))")); ASSERT_TRUE(eval_filter(evt, "(toupper(syscall.type) = toupper(syscall.type))")); - ASSERT_TRUE(eval_filter(evt, "(tolower(toupper(syscall.type)) = tolower(toupper(syscall.type)))")); + ASSERT_TRUE( + eval_filter(evt, "(tolower(toupper(syscall.type)) = tolower(toupper(syscall.type)))")); } -TEST_F(sinsp_with_test_input, filter_different_types) -{ +TEST_F(sinsp_with_test_input, filter_different_types) { add_default_init_thread(); open_inspector(); ASSERT_FALSE(filter_compiles("syscall.type = val(evt.is_wait)")); } -TEST_F(sinsp_with_test_input, filter_not_supported_rhs_field) -{ +TEST_F(sinsp_with_test_input, filter_not_supported_rhs_field) { add_default_init_thread(); open_inspector(); @@ -738,8 +695,7 @@ TEST_F(sinsp_with_test_input, filter_not_supported_rhs_field) ASSERT_FALSE(filter_compiles("evt.around[1404996934793590564] = val(evt.buflen.in)")); } -TEST_F(sinsp_with_test_input, filter_not_supported_transformers) -{ +TEST_F(sinsp_with_test_input, filter_not_supported_transformers) { add_default_init_thread(); open_inspector(); @@ -747,8 +703,7 @@ TEST_F(sinsp_with_test_input, filter_not_supported_transformers) ASSERT_FALSE(filter_compiles("toupper(evt.rawarg.res) = -1")); } -TEST_F(sinsp_with_test_input, filter_transformers_wrong_input_type) -{ +TEST_F(sinsp_with_test_input, filter_transformers_wrong_input_type) { add_default_init_thread(); open_inspector(); @@ -757,8 +712,7 @@ TEST_F(sinsp_with_test_input, filter_transformers_wrong_input_type) ASSERT_FALSE(filter_compiles("b64(evt.rawres) = -1")); } -TEST_F(sinsp_with_test_input, filter_cache_disabled) -{ +TEST_F(sinsp_with_test_input, filter_cache_disabled) { add_default_init_thread(); open_inspector(); @@ -776,8 +730,7 @@ TEST_F(sinsp_with_test_input, filter_cache_disabled) EXPECT_EQ(cf->metrics->m_num_extract_cache, 0); } -TEST_F(sinsp_with_test_input, filter_cache_enabled) -{ +TEST_F(sinsp_with_test_input, filter_cache_enabled) { add_default_init_thread(); open_inspector(); @@ -795,8 +748,7 @@ TEST_F(sinsp_with_test_input, filter_cache_enabled) EXPECT_EQ(cf->metrics->m_num_extract_cache, 2); } -TEST_F(sinsp_with_test_input, filter_cache_corner_cases) -{ +TEST_F(sinsp_with_test_input, filter_cache_corner_cases) { sinsp_filter_check_list flist; add_default_init_thread(); @@ -810,7 +762,7 @@ TEST_F(sinsp_with_test_input, filter_cache_corner_cases) ASSERT_TRUE(pl->init("", err)) << err; flist.add_filter_check(m_inspector.new_generic_filtercheck()); flist.add_filter_check(sinsp_plugin::new_filtercheck(pl)); - + auto ff = std::make_shared(&m_inspector, flist); auto cf = std::make_shared(); auto evt = generate_getcwd_failed_entry_event(); @@ -820,7 +772,8 @@ TEST_F(sinsp_with_test_input, filter_cache_corner_cases) ASSERT_TRUE(eval_filter(evt, "sample.is_open = 0", ff, cf)); EXPECT_EQ(cf->metrics->m_num_compare, 3); EXPECT_EQ(cf->metrics->m_num_compare_cache, 1); - EXPECT_EQ(cf->metrics->m_num_extract, 2); // the third extraction never happens as the check is cached + EXPECT_EQ(cf->metrics->m_num_extract, + 2); // the third extraction never happens as the check is cached EXPECT_EQ(cf->metrics->m_num_extract_cache, 1); cf->metrics->reset(); @@ -829,7 +782,7 @@ TEST_F(sinsp_with_test_input, filter_cache_corner_cases) ASSERT_FALSE(eval_filter(evt, "fd.ip = 10.0.0.1", ff, cf)); EXPECT_EQ(cf->metrics->m_num_compare, 3); EXPECT_EQ(cf->metrics->m_num_compare_cache, 1); - EXPECT_EQ(cf->metrics->m_num_extract, 0); // special logic avoids extraction entirely :/ + EXPECT_EQ(cf->metrics->m_num_extract, 0); // special logic avoids extraction entirely :/ EXPECT_EQ(cf->metrics->m_num_extract_cache, 0); cf->metrics->reset(); @@ -852,7 +805,8 @@ TEST_F(sinsp_with_test_input, filter_cache_corner_cases) cf->metrics->reset(); // fields with transformers - ASSERT_TRUE(eval_filter(evt, "toupper(evt.source) = SYS or toupper(evt.source) = SYSCALL", ff, cf)); + ASSERT_TRUE( + eval_filter(evt, "toupper(evt.source) = SYS or toupper(evt.source) = SYSCALL", ff, cf)); ASSERT_TRUE(eval_filter(evt, "toupper(evt.source) = SYSCALL", ff, cf)); EXPECT_EQ(cf->metrics->m_num_compare, 3); EXPECT_EQ(cf->metrics->m_num_compare_cache, 1); @@ -861,7 +815,10 @@ TEST_F(sinsp_with_test_input, filter_cache_corner_cases) cf->metrics->reset(); // field-to-field comparisons - ASSERT_TRUE(eval_filter(evt, "evt.source = val(evt.plugininfo) or evt.source = val(evt.source)", ff, cf)); + ASSERT_TRUE(eval_filter(evt, + "evt.source = val(evt.plugininfo) or evt.source = val(evt.source)", + ff, + cf)); ASSERT_TRUE(eval_filter(evt, "evt.source = val(evt.source)", ff, cf)); EXPECT_EQ(cf->metrics->m_num_compare, 3); EXPECT_EQ(cf->metrics->m_num_compare_cache, 1); @@ -870,8 +827,7 @@ TEST_F(sinsp_with_test_input, filter_cache_corner_cases) cf->metrics->reset(); } -TEST_F(sinsp_with_test_input, filter_regex_operator_evaluation) -{ +TEST_F(sinsp_with_test_input, filter_regex_operator_evaluation) { // Basic case just to assert that the basic setup works add_default_init_thread(); open_inspector(); @@ -880,7 +836,7 @@ TEST_F(sinsp_with_test_input, filter_regex_operator_evaluation) // legit use case with a string EXPECT_TRUE(eval_filter(evt, "evt.source regex '^[s]{1}ysca[l]{2}$'")); - + // respect anchors EXPECT_FALSE(eval_filter(evt, "evt.source regex 'yscal.*'")); EXPECT_FALSE(eval_filter(evt, "evt.source regex '.*yscal'")); @@ -894,4 +850,4 @@ TEST_F(sinsp_with_test_input, filter_regex_operator_evaluation) // can't be used with field-to-field comparisons EXPECT_THROW(eval_filter(evt, "evt.plugininfo regex val(evt.source)"), sinsp_exception); -} \ No newline at end of file +} diff --git a/userspace/libsinsp/test/filter_escaping.ut.cpp b/userspace/libsinsp/test/filter_escaping.ut.cpp index f2418d1a0c..8132ee971c 100644 --- a/userspace/libsinsp/test/filter_escaping.ut.cpp +++ b/userspace/libsinsp/test/filter_escaping.ut.cpp @@ -21,68 +21,58 @@ limitations under the License. using namespace libsinsp::filter; -class filter_escaping_test : public testing::Test -{ +class filter_escaping_test : public testing::Test { protected: - void unidirectional(const std::string& in, const std::string& out) - { + void unidirectional(const std::string& in, const std::string& out) { ASSERT_STREQ(libsinsp::filter::escape_str(in).c_str(), out.c_str()); } - void bidirectional(const std::string& in) - { + void bidirectional(const std::string& in) { ASSERT_STREQ(in.c_str(), - libsinsp::filter::unescape_str(libsinsp::filter::escape_str(in)).c_str()); + libsinsp::filter::unescape_str(libsinsp::filter::escape_str(in)).c_str()); } }; -TEST_F(filter_escaping_test, spaces) -{ +TEST_F(filter_escaping_test, spaces) { std::string in = "some string"; std::string out = "\"some string\""; unidirectional(in, out); } -TEST_F(filter_escaping_test, spaces_bidirectional) -{ +TEST_F(filter_escaping_test, spaces_bidirectional) { std::string in = "some string"; bidirectional(in); } -TEST_F(filter_escaping_test, ws_chars) -{ +TEST_F(filter_escaping_test, ws_chars) { std::string in = "some\\b\\f\\n\\r\\tstring"; std::string out = "\"some\\\\b\\\\f\\\\n\\\\r\\\\tstring\""; unidirectional(in, out); } -TEST_F(filter_escaping_test, ws_chars_bidirectional) -{ +TEST_F(filter_escaping_test, ws_chars_bidirectional) { std::string in = "some\\b\\f\\n\\r\\tstring"; bidirectional(in); } -TEST_F(filter_escaping_test, double_quotes) -{ +TEST_F(filter_escaping_test, double_quotes) { std::string in = "some \"quoted string\""; std::string out = "\"some \\\"quoted string\\\"\""; unidirectional(in, out); } -TEST_F(filter_escaping_test, double_quotes_bidirectional) -{ +TEST_F(filter_escaping_test, double_quotes_bidirectional) { std::string in = "some \"quoted string\""; bidirectional(in); } -TEST_F(filter_escaping_test, single_quotes) -{ +TEST_F(filter_escaping_test, single_quotes) { std::string in = "some 'quoted string'"; std::string out = "\"some 'quoted string'\""; @@ -93,11 +83,10 @@ TEST_F(filter_escaping_test, single_quotes) // ensures that the unescaping can be done, although it results in a // different string than the original. -TEST_F(filter_escaping_test, single_quotes_bidirectional) -{ +TEST_F(filter_escaping_test, single_quotes_bidirectional) { std::string in = "some 'quoted string'"; std::string out = "some 'quoted string'"; ASSERT_STREQ(out.c_str(), - libsinsp::filter::unescape_str(libsinsp::filter::escape_str(in)).c_str()); + libsinsp::filter::unescape_str(libsinsp::filter::escape_str(in)).c_str()); } diff --git a/userspace/libsinsp/test/filter_op_bcontains.ut.cpp b/userspace/libsinsp/test/filter_op_bcontains.ut.cpp index 82ac99a7e6..e5c236fdab 100644 --- a/userspace/libsinsp/test/filter_op_bcontains.ut.cpp +++ b/userspace/libsinsp/test/filter_op_bcontains.ut.cpp @@ -21,14 +21,18 @@ limitations under the License. #include -TEST_F(sinsp_with_test_input, bcontains_bstartswith) -{ +TEST_F(sinsp_with_test_input, bcontains_bstartswith) { add_default_init_thread(); open_inspector(); uint8_t read_buf[] = {'h', 'e', 'l', 'l', 'o'}; - sinsp_evt * evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_READ_X, 2, (int64_t) 0, scap_const_sized_buffer{read_buf, sizeof(read_buf)}); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_READ_X, + 2, + (int64_t)0, + scap_const_sized_buffer{read_buf, sizeof(read_buf)}); // test filters with bcontains EXPECT_FALSE(filter_compiles("evt.buffer bcontains")); diff --git a/userspace/libsinsp/test/filter_op_contains.ut.cpp b/userspace/libsinsp/test/filter_op_contains.ut.cpp index 393db2fb35..14f9c8534c 100644 --- a/userspace/libsinsp/test/filter_op_contains.ut.cpp +++ b/userspace/libsinsp/test/filter_op_contains.ut.cpp @@ -21,14 +21,22 @@ limitations under the License. #include -TEST_F(sinsp_with_test_input, contains_icontains) -{ +TEST_F(sinsp_with_test_input, contains_icontains) { add_default_init_thread(); open_inspector(); int64_t fd = 1; - sinsp_evt * evt = add_event_advance_ts(increasing_ts(), 3, PPME_SYSCALL_OPEN_X, 6, fd, "/opt/dir/SUBDIR/file.txt", PPM_O_RDWR | PPM_O_CREAT, 0, 0, (uint64_t) 0); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 3, + PPME_SYSCALL_OPEN_X, + 6, + fd, + "/opt/dir/SUBDIR/file.txt", + PPM_O_RDWR | PPM_O_CREAT, + 0, + 0, + (uint64_t)0); EXPECT_TRUE(eval_filter(evt, "evt.arg.flags contains O_CREAT")); EXPECT_FALSE(eval_filter(evt, "evt.arg.flags contains O_TMPFILE")); diff --git a/userspace/libsinsp/test/filter_op_net_compare.ut.cpp b/userspace/libsinsp/test/filter_op_net_compare.ut.cpp index dcda739df8..305317cc80 100644 --- a/userspace/libsinsp/test/filter_op_net_compare.ut.cpp +++ b/userspace/libsinsp/test/filter_op_net_compare.ut.cpp @@ -21,14 +21,19 @@ limitations under the License. #include -TEST_F(sinsp_with_test_input, net_ipv4_compare) -{ +TEST_F(sinsp_with_test_input, net_ipv4_compare) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; int64_t client_fd = 9; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_STREAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_STREAM, + (uint32_t)0); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); int64_t return_value = 0; @@ -36,11 +41,26 @@ TEST_F(sinsp_with_test_input, net_ipv4_compare) sockaddr_in client = test_utils::fill_sockaddr_in(54321, "172.40.111.222"); sockaddr_in server = test_utils::fill_sockaddr_in(443, "142.251.111.147"); - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); EXPECT_TRUE(eval_filter(evt, "fd.ip == 142.251.111.147")); EXPECT_TRUE(eval_filter(evt, "fd.sip == 142.251.111.147")); @@ -64,14 +84,19 @@ TEST_F(sinsp_with_test_input, net_ipv4_compare) EXPECT_FALSE(eval_filter(evt, "fd.net == 2001:db8:abcd:0012::0/64")); } -TEST_F(sinsp_with_test_input, net_ipv6_compare) -{ +TEST_F(sinsp_with_test_input, net_ipv6_compare) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; int64_t client_fd = 9; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET6, (uint32_t) SOCK_DGRAM, (uint32_t) 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET6, + (uint32_t)SOCK_DGRAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); int64_t return_value = 0; @@ -79,12 +104,26 @@ TEST_F(sinsp_with_test_input, net_ipv6_compare) sockaddr_in6 client = test_utils::fill_sockaddr_in6(54321, "::1"); sockaddr_in6 server1 = test_utils::fill_sockaddr_in6(443, "2001:4860:4860::8888"); - std::vector server1_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server1)); - - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server1_sockaddr.data(), server1_sockaddr.size()}); - - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server1)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + std::vector server1_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server1)); + + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server1_sockaddr.data(), server1_sockaddr.size()}); + + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server1)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); EXPECT_TRUE(eval_filter(evt, "fd.ip == 2001:4860:4860::8888")); EXPECT_TRUE(eval_filter(evt, "fd.sip == 2001:4860:4860::8888")); diff --git a/userspace/libsinsp/test/filter_op_numeric_compare.ut.cpp b/userspace/libsinsp/test/filter_op_numeric_compare.ut.cpp index d73fd9a213..16bb78e726 100644 --- a/userspace/libsinsp/test/filter_op_numeric_compare.ut.cpp +++ b/userspace/libsinsp/test/filter_op_numeric_compare.ut.cpp @@ -21,13 +21,13 @@ limitations under the License. #include -TEST_F(sinsp_with_test_input, signed_int_compare) -{ +TEST_F(sinsp_with_test_input, signed_int_compare) { add_default_init_thread(); open_inspector(); - sinsp_evt * evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_X, 1, (uint64_t)-22); + sinsp_evt* evt = + add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_EPOLL_CREATE_X, 1, (uint64_t)-22); EXPECT_EQ(get_field_as_string(evt, "evt.cpu"), "1"); @@ -47,8 +47,23 @@ TEST_F(sinsp_with_test_input, signed_int_compare) EXPECT_TRUE(eval_filter(evt, "evt.rawarg.res < -1")); EXPECT_TRUE(eval_filter(evt, "evt.rawarg.res > -65535")); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_NONE, 0666); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (int64_t)(-1), "/tmp/the_file", PPM_O_NONE, 0666, 123, (uint64_t)456); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_NONE, + 0666); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (int64_t)(-1), + "/tmp/the_file", + PPM_O_NONE, + 0666, + 123, + (uint64_t)456); EXPECT_FALSE(eval_filter(evt, "fd.num >= 0")); EXPECT_FALSE(eval_filter(evt, "fd.num > 0")); diff --git a/userspace/libsinsp/test/filter_op_pmatch.ut.cpp b/userspace/libsinsp/test/filter_op_pmatch.ut.cpp index 7b8f92fbb1..52cb404c99 100644 --- a/userspace/libsinsp/test/filter_op_pmatch.ut.cpp +++ b/userspace/libsinsp/test/filter_op_pmatch.ut.cpp @@ -21,15 +21,22 @@ limitations under the License. #include - -TEST_F(sinsp_with_test_input, pmatch) -{ +TEST_F(sinsp_with_test_input, pmatch) { add_default_init_thread(); open_inspector(); int64_t fd = 1; - sinsp_evt * evt = add_event_advance_ts(increasing_ts(), 3, PPME_SYSCALL_OPEN_X, 6, fd, "/opt/dir/subdir/file.txt", 0, 0, 0, (uint64_t) 0); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 3, + PPME_SYSCALL_OPEN_X, + 6, + fd, + "/opt/dir/subdir/file.txt", + 0, + 0, + 0, + (uint64_t)0); EXPECT_TRUE(eval_filter(evt, "fd.name pmatch (/opt/dir)")); EXPECT_TRUE(eval_filter(evt, "fd.name pmatch (/opt/dir/subdir)")); diff --git a/userspace/libsinsp/test/filter_parser.ut.cpp b/userspace/libsinsp/test/filter_parser.ut.cpp index 8a0b213dfe..2ca3282595 100644 --- a/userspace/libsinsp/test/filter_parser.ut.cpp +++ b/userspace/libsinsp/test/filter_parser.ut.cpp @@ -5,61 +5,45 @@ using namespace std; using namespace libsinsp::filter; using namespace libsinsp::filter::ast; -static void test_equal_ast(const string& in, expr* ast) -{ +static void test_equal_ast(const string& in, expr* ast) { parser parser(in); - try - { + try { auto res = parser.parse(); - if (!res->is_equal(ast)) - { - + if(!res->is_equal(ast)) { FAIL() << "parsed ast is not equal to the expected one" << std::endl - << " expected: " << in << std::endl - << " actual: " << as_string(res.get()); + << " expected: " << in << std::endl + << " actual: " << as_string(res.get()); } - } - catch (runtime_error& e) - { + } catch(runtime_error& e) { auto pos = parser.get_pos(); FAIL() << "at " << pos.as_string() << ": " << e.what() << " -> " << in; } }; -static void test_accept(string in, ast::pos_info* out_pos = NULL) -{ +static void test_accept(string in, ast::pos_info* out_pos = NULL) { parser parser(in); - try - { - parser.parse(); - } - catch (runtime_error& e) - { + try { + parser.parse(); + } catch(runtime_error& e) { auto pos = parser.get_pos(); FAIL() << "at " << pos.as_string() << ": " << e.what() << " -> " << in; } - if (out_pos) - { + if(out_pos) { *out_pos = parser.get_pos(); } } -static void test_reject(string in) -{ +static void test_reject(string in) { parser parser(in); - try - { + try { parser.parse(); FAIL() << "error expected but not received -> " << in; - } - catch (runtime_error& e) - { + } catch(runtime_error& e) { // all good } } -TEST(pos_info, equality_assignments) -{ +TEST(pos_info, equality_assignments) { pos_info a; pos_info b(5, 1, 3); ASSERT_EQ(a.idx, 0); @@ -77,48 +61,38 @@ TEST(pos_info, equality_assignments) ASSERT_EQ(a, b); } -TEST(parser, supported_operators) -{ +TEST(parser, supported_operators) { static vector expected_all = { - "=", "==", "!=", "<=", ">=", "<", ">", "exists", - "contains", "icontains", "bcontains", "glob", "iglob", "bstartswith", - "startswith", "endswith", "in", "intersects", "pmatch", "regex"}; - static vector expected_list_only = { - "in", "intersects", "pmatch"}; - + "=", "==", "!=", "<=", ">=", "<", ">", + "exists", "contains", "icontains", "bcontains", "glob", "iglob", "bstartswith", + "startswith", "endswith", "in", "intersects", "pmatch", "regex"}; + static vector expected_list_only = {"in", "intersects", "pmatch"}; + auto actual_all = parser::supported_operators(); ASSERT_EQ(actual_all.size(), expected_all.size()); - for (auto &op : expected_all) - { - if (count(actual_all.begin(), actual_all.end(), op) != 1) - { + for(auto& op : expected_all) { + if(count(actual_all.begin(), actual_all.end(), op) != 1) { FAIL() << "expected support for operator: " << op; } } auto actual_list_only = parser::supported_operators(true); ASSERT_EQ(actual_list_only.size(), actual_list_only.size()); - for (auto &op : expected_list_only) - { - if (count(actual_list_only.begin(), actual_list_only.end(), op) != 1) - { + for(auto& op : expected_list_only) { + if(count(actual_list_only.begin(), actual_list_only.end(), op) != 1) { FAIL() << "expected support for list operator: " << op; } } } -TEST(parser, supported_field_transformers) -{ +TEST(parser, supported_field_transformers) { std::string expected_val = "val"; - std::vector expected = { - "tolower", "toupper", "b64", "basename" }; - + std::vector expected = {"tolower", "toupper", "b64", "basename"}; + auto actual = parser::supported_field_transformers(); ASSERT_EQ(actual.size(), expected.size()); - for (auto &op : expected) - { - if (count(actual.begin(), actual.end(), op) != 1) - { + for(auto& op : expected) { + if(count(actual.begin(), actual.end(), op) != 1) { FAIL() << "expected support for field transformer: " << op; } } @@ -126,10 +100,8 @@ TEST(parser, supported_field_transformers) actual = parser::supported_field_transformers(true); expected.insert(expected.begin(), expected_val); ASSERT_EQ(actual.size(), expected.size()); - for (auto &op : expected) - { - if (count(actual.begin(), actual.end(), op) != 1) - { + for(auto& op : expected) { + if(count(actual.begin(), actual.end(), op) != 1) { FAIL() << "expected support for field transformer: " << op; } } @@ -137,8 +109,7 @@ TEST(parser, supported_field_transformers) // Based on and extended Falco's parser smoke tests: // https://github.com/falcosecurity/falco/blob/204f9ff875be035e620ca1affdf374dd1c610a98/userspace/engine/lua/parser-smoke.sh#L41 -TEST(parser, parse_smoke_test) -{ +TEST(parser, parse_smoke_test) { // good test_accept(" a"); test_accept("(a)"); @@ -235,8 +206,7 @@ TEST(parser, parse_smoke_test) test_reject("evt.dir=> and fd.name=/var/lo);g/httpd.log"); } -TEST(parser, parse_str) -{ +TEST(parser, parse_str) { // valid bare strings test_accept("test.str = testval"); test_accept("test.str = 0a!@#456:/\\.;!$%^&*[]{}|"); @@ -264,7 +234,8 @@ TEST(parser, parse_str) test_accept("test.str = 'multiple escape single quote \\' \\\\''"); test_accept("test.str = 'mixed \"'"); test_accept("test.str = \"mixed '\""); - test_accept("test.str = \"bad escape \\ \" "); // todo(jasondellaluce): reject this case in the future + test_accept("test.str = \"bad escape \\ \" "); // todo(jasondellaluce): reject this case in the + // future // invalid bare strings test_reject("test.str = a,"); @@ -297,8 +268,7 @@ TEST(parser, parse_str) test_reject("test.str] = testval"); } -TEST(parser, parse_numbers) -{ +TEST(parser, parse_numbers) { // valid numbers test_accept("test.num > 1000"); test_accept("test.num < +1"); @@ -323,8 +293,7 @@ TEST(parser, parse_numbers) test_reject("test.num <= a"); } -TEST(parser, parse_lists) -{ +TEST(parser, parse_lists) { // valid list test_accept("test.list in ()"); test_accept("test.list in (a)"); @@ -357,8 +326,7 @@ TEST(parser, parse_lists) test_reject("test.list icontains (value)"); } -TEST(parser, parse_operators) -{ +TEST(parser, parse_operators) { // valid operators test_accept("test.op exists and macro"); test_accept("test.op exists"); @@ -398,8 +366,7 @@ TEST(parser, parse_operators) test_reject("test.op iglobvalue"); } -TEST(parser, parse_transformers_left_hand) -{ +TEST(parser, parse_transformers_left_hand) { // testing supported transformers test_accept("tolower(test.field) exists"); test_accept("toupper(test.field) exists"); @@ -452,7 +419,7 @@ TEST(parser, parse_transformers_left_hand) test_reject("some_fake_transformer(test.field) exists"); test_reject("some_fake_transformer (test.field) exists"); test_reject("some.fake.transformer(test.field) exists"); - test_reject("b64 (test.field) exists"); // no space is allowed before '(' + test_reject("b64 (test.field) exists"); // no space is allowed before '(' test_reject("b64,(test.field) exists"); test_reject("b64(testfield)) exists"); test_reject("b64(test_field)) exists"); @@ -471,8 +438,7 @@ TEST(parser, parse_transformers_left_hand) test_reject("a(b(test.field)) exists"); } -TEST(parser, parse_transformers_right_hand) -{ +TEST(parser, parse_transformers_right_hand) { // note: using a field as right-hand without using any transformer // will end up making the parser read it as a bare string value, and not // as an actual field. This is something we can't catch or distinguish @@ -554,7 +520,9 @@ TEST(parser, parse_transformers_right_hand) // testing left-hand transformers together with right-hand transformers test_accept("tolower(some.field) = b64(test.field)"); - test_accept("tolower(some.field) = b64(test.field) or tolower(other.field) = tolower(anoter.field)"); + test_accept( + "tolower(some.field) = b64(test.field) or tolower(other.field) = " + "tolower(anoter.field)"); // these are non-transformer use cases that are a bit ambiguous test_reject("some.field = b64and(some_macro)"); @@ -569,10 +537,10 @@ TEST(parser, parse_transformers_right_hand) test_reject("some.field = some_fake_transformer(test.field)"); test_reject("some.field = some_fake_transformer (test.field)"); test_reject("some.field = some.fake.transformer(test.field)"); - test_reject("some.field = val(val(test.field))"); // val cannot have nested transformers + test_reject("some.field = val(val(test.field))"); // val cannot have nested transformers test_reject("some.field = val(toupper(test.field))"); - test_reject("some.field = b64(val(test.field))"); // val can't be nested - test_reject("some.field = b64 (test.field)"); // no space is allowed before '(' + test_reject("some.field = b64(val(test.field))"); // val can't be nested + test_reject("some.field = b64 (test.field)"); // no space is allowed before '(' test_reject("some.field = b64,(test.field)"); test_reject("some.field = (b64(test.field))"); test_reject("some.field = (b64(test.field)"); @@ -600,8 +568,7 @@ TEST(parser, parse_transformers_right_hand) test_reject("some.field in (a, b, b64(test.field))"); } -TEST(parser, parse_position_info) -{ +TEST(parser, parse_position_info) { ast::pos_info pos; test_accept("a and b", &pos); @@ -635,205 +602,190 @@ TEST(parser, parse_position_info) } // complex test case with all supported node types -TEST(parser, expr_all_node_types) -{ +TEST(parser, expr_all_node_types) { std::vector> and_children; and_children.push_back(unary_check_expr::create(field_expr::create("evt.name", ""), "exists")); - and_children.push_back(binary_check_expr::create(field_expr::create("evt.type", ""), "in", list_expr::create({"a", "b"}))); - and_children.push_back(not_expr::create(binary_check_expr::create(field_expr::create("evt.dir", ""), "=", value_expr::create("<")))); + and_children.push_back(binary_check_expr::create(field_expr::create("evt.type", ""), + "in", + list_expr::create({"a", "b"}))); + and_children.push_back( + not_expr::create(binary_check_expr::create(field_expr::create("evt.dir", ""), + "=", + value_expr::create("<")))); std::vector> or_children; or_children.push_back(and_expr::create(and_children)); - or_children.push_back(binary_check_expr::create(field_expr::create("proc.name", ""), "=", value_expr::create("cat"))); + or_children.push_back(binary_check_expr::create(field_expr::create("proc.name", ""), + "=", + value_expr::create("cat"))); std::unique_ptr ast = or_expr::create(or_children); - test_equal_ast( - "evt.name exists and evt.type in (a, b) and not evt.dir=< or proc.name=cat", - ast.get() - ); + test_equal_ast("evt.name exists and evt.type in (a, b) and not evt.dir=< or proc.name=cat", + ast.get()); } -TEST(parser, expr_transformers) -{ +TEST(parser, expr_transformers) { std::vector> and_children; - and_children.push_back( - unary_check_expr::create( - field_transformer_expr::create("b64", field_expr::create("evt.name", "")), - "exists")); - and_children.push_back( - binary_check_expr::create( - field_transformer_expr::create("tolower", field_transformer_expr::create("toupper", field_expr::create("evt.type", ""))), - "in", - field_transformer_expr::create("val", field_expr::create("some.field", "")))); - and_children.push_back( - not_expr::create( - binary_check_expr::create( - field_expr::create("evt.dir", ""), - "=", - field_transformer_expr::create("b64", field_expr::create("some.field", ""))))); + and_children.push_back(unary_check_expr::create( + field_transformer_expr::create("b64", field_expr::create("evt.name", "")), + "exists")); + and_children.push_back(binary_check_expr::create( + field_transformer_expr::create( + "tolower", + field_transformer_expr::create("toupper", field_expr::create("evt.type", ""))), + "in", + field_transformer_expr::create("val", field_expr::create("some.field", "")))); + and_children.push_back(not_expr::create(binary_check_expr::create( + field_expr::create("evt.dir", ""), + "=", + field_transformer_expr::create("b64", field_expr::create("some.field", ""))))); std::vector> or_children; or_children.push_back(and_expr::create(and_children)); - or_children.push_back( - binary_check_expr::create( - field_expr::create("proc.name", ""), - "=", - field_transformer_expr::create("b64", field_transformer_expr::create("tolower", field_expr::create("some.field", ""))))); + or_children.push_back(binary_check_expr::create( + field_expr::create("proc.name", ""), + "=", + field_transformer_expr::create( + "b64", + field_transformer_expr::create("tolower", + field_expr::create("some.field", ""))))); std::unique_ptr ast = or_expr::create(or_children); test_equal_ast( - "b64(evt.name) exists and tolower(toupper(evt.type)) in val(some.field) and not evt.dir=b64(some.field) or proc.name=b64(tolower(some.field))", - ast.get() - ); + "b64(evt.name) exists and tolower(toupper(evt.type)) in val(some.field) and not " + "evt.dir=b64(some.field) or proc.name=b64(tolower(some.field))", + ast.get()); } // complex example with parenthesis -TEST(parser, expr_parenthesis) -{ +TEST(parser, expr_parenthesis) { std::vector> and_children; and_children.push_back(unary_check_expr::create(field_expr::create("evt.name", ""), "exists")); - and_children.push_back(binary_check_expr::create(field_expr::create("evt.type", ""), "in", list_expr::create({"a", "b"}))); - and_children.push_back(not_expr::create(binary_check_expr::create(field_expr::create("evt.dir", ""), "=", value_expr::create("<")))); + and_children.push_back(binary_check_expr::create(field_expr::create("evt.type", ""), + "in", + list_expr::create({"a", "b"}))); + and_children.push_back( + not_expr::create(binary_check_expr::create(field_expr::create("evt.dir", ""), + "=", + value_expr::create("<")))); std::vector> or_children; or_children.push_back(and_expr::create(and_children)); - or_children.push_back(binary_check_expr::create(field_expr::create("proc.name", ""), "=", value_expr::create("cat"))); + or_children.push_back(binary_check_expr::create(field_expr::create("proc.name", ""), + "=", + value_expr::create("cat"))); std::unique_ptr ast = or_expr::create(or_children); - test_equal_ast( - "evt.name exists and evt.type in (a, b) and not evt.dir=< or proc.name=cat", - ast.get() - ); + test_equal_ast("evt.name exists and evt.type in (a, b) and not evt.dir=< or proc.name=cat", + ast.get()); } // stressing nested negation and identifiers -TEST(parser, expr_multi_negation) -{ +TEST(parser, expr_multi_negation) { std::vector> and_children; and_children.push_back(unary_check_expr::create(field_expr::create("evt.name", ""), "exists")); - and_children.push_back(binary_check_expr::create(field_expr::create("evt.type", ""), "in", list_expr::create({"a", "b"}))); - and_children.push_back(not_expr::create(binary_check_expr::create(field_expr::create("evt.dir", ""), "=", value_expr::create("<")))); + and_children.push_back(binary_check_expr::create(field_expr::create("evt.type", ""), + "in", + list_expr::create({"a", "b"}))); + and_children.push_back( + not_expr::create(binary_check_expr::create(field_expr::create("evt.dir", ""), + "=", + value_expr::create("<")))); std::vector> or_children; or_children.push_back(and_expr::create(and_children)); - or_children.push_back(binary_check_expr::create(field_expr::create("proc.name", ""), "=", value_expr::create("cat"))); + or_children.push_back(binary_check_expr::create(field_expr::create("proc.name", ""), + "=", + value_expr::create("cat"))); std::unique_ptr ast = or_expr::create(or_children); - test_equal_ast( - "evt.name exists and evt.type in (a, b) and not evt.dir=< or proc.name=cat", - ast.get() - ); + test_equal_ast("evt.name exists and evt.type in (a, b) and not evt.dir=< or proc.name=cat", + ast.get()); ast = not_expr::create(not_expr::create(identifier_expr::create("not_macro"))); - test_equal_ast( - "not not not not not(not not(not not_macro))", - ast.get() - ); + test_equal_ast("not not not not not(not not(not not_macro))", ast.get()); } -struct pos_visitor : public expr_visitor -{ +struct pos_visitor : public expr_visitor { public: - void visit(and_expr* e) override - { - visit_logical_op("and", e->get_pos(), e->children); - }; - - virtual void visit(or_expr* e) override - { - visit_logical_op("or", e->get_pos(), e->children); - } + void visit(and_expr* e) override { visit_logical_op("and", e->get_pos(), e->children); }; - virtual void visit(not_expr* e) override - { + virtual void visit(or_expr* e) override { visit_logical_op("or", e->get_pos(), e->children); } + + virtual void visit(not_expr* e) override { m_str += "not"; add_pos(e->get_pos()); e->child->accept(this); } - virtual void visit(identifier_expr* e) override - { + virtual void visit(identifier_expr* e) override { m_str += "identifier"; add_pos(e->get_pos()); } - virtual void visit(value_expr* e) override - { + virtual void visit(value_expr* e) override { m_str += "value"; add_pos(e->get_pos()); } - virtual void visit(list_expr* e) override - { + virtual void visit(list_expr* e) override { m_str += "list"; add_pos(e->get_pos()); } - virtual void visit(unary_check_expr* e) override - { + virtual void visit(unary_check_expr* e) override { m_str += "unary"; add_pos(e->get_pos()); e->left->accept(this); } - virtual void visit(binary_check_expr* e) override - { + virtual void visit(binary_check_expr* e) override { m_str += "binary"; add_pos(e->get_pos()); e->left->accept(this); e->right->accept(this); } - virtual void visit(field_expr* e) override - { + virtual void visit(field_expr* e) override { m_str += "field"; add_pos(e->get_pos()); } - virtual void visit(field_transformer_expr* e) override - { + virtual void visit(field_transformer_expr* e) override { m_str += "transformer"; add_pos(e->get_pos()); e->value->accept(this); } - const std::string& as_string() { - return m_str; - }; + const std::string& as_string() { return m_str; }; private: - void visit_logical_op(const char* op, - const pos_info& pos, - const std::vector> &children) - { + const pos_info& pos, + const std::vector>& children) { m_str += op; add_pos(pos); - for(auto&c : children) - { + for(auto& c : children) { c->accept(this); } } - void add_pos(const pos_info& pos) - { - m_str += std::to_string(pos.idx) + " " + - std::to_string(pos.line) + " " + - std::to_string(pos.col); + void add_pos(const pos_info& pos) { + m_str += std::to_string(pos.idx) + " " + std::to_string(pos.line) + " " + + std::to_string(pos.col); } std::string m_str; }; -TEST(parser, position_unary_check) -{ +TEST(parser, position_unary_check) { parser parser("proc.name exists"); auto expr = parser.parse(); pos_visitor pv; @@ -841,8 +793,7 @@ TEST(parser, position_unary_check) EXPECT_STREQ(pv.as_string().c_str(), "unary0 1 1field0 1 1"); } -TEST(parser, position_binary_check) -{ +TEST(parser, position_binary_check) { parser parser("proc.name=nginx"); auto expr = parser.parse(); pos_visitor pv; @@ -850,8 +801,7 @@ TEST(parser, position_binary_check) EXPECT_STREQ(pv.as_string().c_str(), "binary0 1 1field0 1 1value10 1 11"); } -TEST(parser, position_binary_check_params) -{ +TEST(parser, position_binary_check_params) { parser parser("proc.aname[3]=nginx"); auto expr = parser.parse(); pos_visitor pv; @@ -859,8 +809,7 @@ TEST(parser, position_binary_check_params) EXPECT_STREQ(pv.as_string().c_str(), "binary0 1 1field0 1 1value14 1 15"); } -TEST(parser, position_binary_check_space_before) -{ +TEST(parser, position_binary_check_space_before) { parser parser("proc.name =nginx"); auto expr = parser.parse(); pos_visitor pv; @@ -868,8 +817,7 @@ TEST(parser, position_binary_check_space_before) EXPECT_STREQ(pv.as_string().c_str(), "binary0 1 1field0 1 1value11 1 12"); } -TEST(parser, position_binary_check_space_after) -{ +TEST(parser, position_binary_check_space_after) { parser parser("proc.name= nginx"); auto expr = parser.parse(); pos_visitor pv; @@ -877,8 +825,7 @@ TEST(parser, position_binary_check_space_after) EXPECT_STREQ(pv.as_string().c_str(), "binary0 1 1field0 1 1value11 1 12"); } -TEST(parser, position_binary_check_space_both) -{ +TEST(parser, position_binary_check_space_both) { parser parser("proc.name = nginx"); auto expr = parser.parse(); pos_visitor pv; @@ -886,8 +833,7 @@ TEST(parser, position_binary_check_space_both) EXPECT_STREQ(pv.as_string().c_str(), "binary0 1 1field0 1 1value12 1 13"); } -TEST(parser, position_binary_check_list) -{ +TEST(parser, position_binary_check_list) { parser parser("proc.name in (nginx, apache)"); auto expr = parser.parse(); pos_visitor pv; @@ -895,8 +841,7 @@ TEST(parser, position_binary_check_list) EXPECT_STREQ(pv.as_string().c_str(), "binary0 1 1field0 1 1list13 1 14"); } -TEST(parser, position_binary_check_list_space_after) -{ +TEST(parser, position_binary_check_list_space_after) { parser parser("proc.name in ( nginx, apache)"); auto expr = parser.parse(); pos_visitor pv; @@ -904,8 +849,7 @@ TEST(parser, position_binary_check_list_space_after) EXPECT_STREQ(pv.as_string().c_str(), "binary0 1 1field0 1 1list13 1 14"); } -TEST(parser, position_not) -{ +TEST(parser, position_not) { parser parser("not proc.name=nginx"); auto expr = parser.parse(); pos_visitor pv; @@ -913,53 +857,56 @@ TEST(parser, position_not) EXPECT_STREQ(pv.as_string().c_str(), "not0 1 1binary4 1 5field4 1 5value14 1 15"); } -TEST(parser, position_or) -{ +TEST(parser, position_or) { parser parser("proc.name=nginx or proc.name=apache"); auto expr = parser.parse(); pos_visitor pv; expr->accept(&pv); - EXPECT_STREQ(pv.as_string().c_str(), "or0 1 1binary0 1 1field0 1 1value10 1 11binary19 1 20field19 1 20value29 1 30"); + EXPECT_STREQ(pv.as_string().c_str(), + "or0 1 1binary0 1 1field0 1 1value10 1 11binary19 1 20field19 1 20value29 1 30"); } -TEST(parser, position_or_parens) -{ +TEST(parser, position_or_parens) { parser parser("(proc.name=nginx or proc.name=apache)"); auto expr = parser.parse(); pos_visitor pv; expr->accept(&pv); - EXPECT_STREQ(pv.as_string().c_str(), "or1 1 2binary1 1 2field1 1 2value11 1 12binary20 1 21field20 1 21value30 1 31"); + EXPECT_STREQ(pv.as_string().c_str(), + "or1 1 2binary1 1 2field1 1 2value11 1 12binary20 1 21field20 1 21value30 1 31"); } -TEST(parser, position_and) -{ +TEST(parser, position_and) { parser parser("proc.name=nginx and proc.name=apache"); auto expr = parser.parse(); pos_visitor pv; expr->accept(&pv); - EXPECT_STREQ(pv.as_string().c_str(), "and0 1 1binary0 1 1field0 1 1value10 1 11binary20 1 21field20 1 21value30 1 31"); + EXPECT_STREQ(pv.as_string().c_str(), + "and0 1 1binary0 1 1field0 1 1value10 1 11binary20 1 21field20 1 21value30 1 31"); } -TEST(parser, position_and_parens) -{ +TEST(parser, position_and_parens) { parser parser("(proc.name=nginx and proc.name=apache)"); auto expr = parser.parse(); pos_visitor pv; expr->accept(&pv); - EXPECT_STREQ(pv.as_string().c_str(), "and1 1 2binary1 1 2field1 1 2value11 1 12binary21 1 22field21 1 22value31 1 32"); + EXPECT_STREQ(pv.as_string().c_str(), + "and1 1 2binary1 1 2field1 1 2value11 1 12binary21 1 22field21 1 22value31 1 32"); } -TEST(parser, position_complex) -{ - parser parser("(proc.aname[2]=nginx and evt.type in (connect,accept)) or (not fd.name exists) or (proc.name=apache and evt.type=switch)"); +TEST(parser, position_complex) { + parser parser( + "(proc.aname[2]=nginx and evt.type in (connect,accept)) or (not fd.name exists) or " + "(proc.name=apache and evt.type=switch)"); auto expr = parser.parse(); pos_visitor pv; expr->accept(&pv); - EXPECT_STREQ(pv.as_string().c_str(), "or0 1 1and1 1 2binary1 1 2field1 1 2value15 1 16binary25 1 26field25 1 26list37 1 38not59 1 60unary63 1 64field63 1 64and83 1 84binary83 1 84field83 1 84value93 1 94binary104 1 105field104 1 105value113 1 114"); + EXPECT_STREQ(pv.as_string().c_str(), + "or0 1 1and1 1 2binary1 1 2field1 1 2value15 1 16binary25 1 26field25 1 26list37 " + "1 38not59 1 60unary63 1 64field63 1 64and83 1 84binary83 1 84field83 1 84value93 " + "1 94binary104 1 105field104 1 105value113 1 114"); } -TEST(parser, position_complex_multiline) -{ +TEST(parser, position_complex_multiline) { const char* str = R"EOF( (proc.aname[2]=nginx and evt.type in (connect,accept)) @@ -971,14 +918,22 @@ TEST(parser, position_complex_multiline) auto expr = parser.parse(); pos_visitor pv; expr->accept(&pv); - EXPECT_STREQ(pv.as_string().c_str(), "or0 1 1and2 2 2binary2 2 2field2 2 2value16 2 16binary31 3 10field31 3 10list43 3 22not68 4 8unary72 4 12field72 4 12and95 5 8binary95 5 8field95 5 8value105 5 18binary123 6 12field123 6 12value132 6 21"); + EXPECT_STREQ(pv.as_string().c_str(), + "or0 1 1and2 2 2binary2 2 2field2 2 2value16 2 16binary31 3 10field31 3 10list43 " + "3 22not68 4 8unary72 4 12field72 4 12and95 5 8binary95 5 8field95 5 8value105 5 " + "18binary123 6 12field123 6 12value132 6 21"); } -TEST(parser, position_complex_transformers) -{ - parser parser("b64(evt.name) exists and tolower(toupper(evt.type)) in val(some.field) and not evt.dir=b64(some.field) or proc.name=b64(tolower(some.field))"); +TEST(parser, position_complex_transformers) { + parser parser( + "b64(evt.name) exists and tolower(toupper(evt.type)) in val(some.field) and not " + "evt.dir=b64(some.field) or proc.name=b64(tolower(some.field))"); auto expr = parser.parse(); pos_visitor pv; expr->accept(&pv); - EXPECT_STREQ(pv.as_string().c_str(), "or0 1 1and0 1 1unary0 1 1transformer0 1 1field4 1 5binary25 1 26transformer25 1 26transformer33 1 34field41 1 42transformer55 1 56field59 1 60not75 1 76binary79 1 80field79 1 80transformer87 1 88field91 1 92binary106 1 107field106 1 107transformer116 1 117transformer120 1 121field128 1 129"); + EXPECT_STREQ(pv.as_string().c_str(), + "or0 1 1and0 1 1unary0 1 1transformer0 1 1field4 1 5binary25 1 26transformer25 1 " + "26transformer33 1 34field41 1 42transformer55 1 56field59 1 60not75 1 76binary79 " + "1 80field79 1 80transformer87 1 88field91 1 92binary106 1 107field106 1 " + "107transformer116 1 117transformer120 1 121field128 1 129"); } diff --git a/userspace/libsinsp/test/filter_ppm_codes.ut.cpp b/userspace/libsinsp/test/filter_ppm_codes.ut.cpp index c710d9d8fd..53052338fe 100644 --- a/userspace/libsinsp/test/filter_ppm_codes.ut.cpp +++ b/userspace/libsinsp/test/filter_ppm_codes.ut.cpp @@ -20,75 +20,68 @@ limitations under the License. #include // helps testing that ppm_sc_codes are correctly found in a filter -struct testdata_sc_set -{ - using set_t = libsinsp::events::set; - const set_t close_set = { PPM_SC_CLOSE }; - const set_t openat_set = { PPM_SC_OPENAT }; - - virtual set_t all_set() const { return libsinsp::events::all_sc_set(); }; - virtual set_t filter_set(const std::string filter) const - { - return libsinsp::filter::ast::ppm_sc_codes( - libsinsp::filter::parser(filter).parse().get()); - } +struct testdata_sc_set { + using set_t = libsinsp::events::set; + const set_t close_set = {PPM_SC_CLOSE}; + const set_t openat_set = {PPM_SC_OPENAT}; + + virtual set_t all_set() const { return libsinsp::events::all_sc_set(); }; + virtual set_t filter_set(const std::string filter) const { + return libsinsp::filter::ast::ppm_sc_codes(libsinsp::filter::parser(filter).parse().get()); + } }; // helps testing that ppm_event_codes are correctly found in a filter -struct testdata_event_set -{ - using set_t = libsinsp::events::set; - const set_t close_set = { PPME_SYSCALL_CLOSE_E, PPME_SYSCALL_CLOSE_X }; - const set_t openat_set = { - PPME_SYSCALL_OPENAT_E, PPME_SYSCALL_OPENAT_X, - PPME_SYSCALL_OPENAT_2_E, PPME_SYSCALL_OPENAT_2_X }; - - virtual set_t all_set() const { return libsinsp::events::all_event_set(); }; - virtual set_t filter_set(const std::string filter) const - { - return libsinsp::filter::ast::ppm_event_codes( - libsinsp::filter::parser(filter).parse().get()); - } +struct testdata_event_set { + using set_t = libsinsp::events::set; + const set_t close_set = {PPME_SYSCALL_CLOSE_E, PPME_SYSCALL_CLOSE_X}; + const set_t openat_set = {PPME_SYSCALL_OPENAT_E, + PPME_SYSCALL_OPENAT_X, + PPME_SYSCALL_OPENAT_2_E, + PPME_SYSCALL_OPENAT_2_X}; + + virtual set_t all_set() const { return libsinsp::events::all_event_set(); }; + virtual set_t filter_set(const std::string filter) const { + return libsinsp::filter::ast::ppm_event_codes( + libsinsp::filter::parser(filter).parse().get()); + } }; // helps testing that ppm_event_codes can be obtained by searching for // ppm_sc_codes in a filter, and then using the // libsinsp::events::sc_set_to_event_set conversion utility -struct testdata_event_set_converted: testdata_event_set -{ - set_t all_set() const override { - return libsinsp::events::all_event_set().filter([](ppm_event_code e) { - // the following categories are expected to have information loss - // loss as they are not mappable through the PPM_SC enumerative, - // due to them not being related to actual linux kernel events. - return !libsinsp::events::is_unused_event(e) - && !libsinsp::events::is_metaevent(e) - && !libsinsp::events::is_plugin_event(e); - }); - }; - - set_t filter_set(const std::string filter) const override - { - testdata_sc_set s; - return libsinsp::events::sc_set_to_event_set(s.filter_set(filter)); - } +struct testdata_event_set_converted : testdata_event_set { + set_t all_set() const override { + return libsinsp::events::all_event_set().filter([](ppm_event_code e) { + // the following categories are expected to have information loss + // loss as they are not mappable through the PPM_SC enumerative, + // due to them not being related to actual linux kernel events. + return !libsinsp::events::is_unused_event(e) && !libsinsp::events::is_metaevent(e) && + !libsinsp::events::is_plugin_event(e); + }); + }; + + set_t filter_set(const std::string filter) const override { + testdata_sc_set s; + return libsinsp::events::sc_set_to_event_set(s.filter_set(filter)); + } }; // helps testing that ppm_sc_codes can be obtained by searching for // ppm_event_codes in a filter, and then using the // libsinsp::events::event_set_to_sc_set conversion utility -struct testdata_sc_set_converted: testdata_sc_set -{ - set_t filter_set(const std::string filter) const override - { - testdata_event_set s; - return libsinsp::events::event_set_to_sc_set(s.filter_set(filter)); - } +struct testdata_sc_set_converted : testdata_sc_set { + set_t filter_set(const std::string filter) const override { + testdata_event_set s; + return libsinsp::events::event_set_to_sc_set(s.filter_set(filter)); + } }; // helpers to make comparisons easier and more expressive in case of fail -#define ASSERT_FILTER_EQ(t, a, b) { ASSERT_EQ(t.filter_set(a), t.filter_set(b)); } -#define ASSERT_FILTER_SET_EQ(t, a, b) { ASSERT_EQ(t.filter_set(a), b); } +#define ASSERT_FILTER_EQ(t, a, b) \ + { ASSERT_EQ(t.filter_set(a), t.filter_set(b)); } +#define ASSERT_FILTER_SET_EQ(t, a, b) \ + { ASSERT_EQ(t.filter_set(a), b); } // helper for making sure tests are run on multiple testdata, // so that we're sure that the tests covers the high-level semantics no @@ -99,233 +92,272 @@ struct testdata_sc_set_converted: testdata_sc_set // ppm_sc_code <-> ppm_event_code, which in general can cause information loss. // However, in none of the tests below this is significant, because no filter // deals with corner cases such as generic events, meta events, etc. -#define TEST_CODES(test_suite_name, test_name) \ - template void test_##test_name(); \ - TEST(test_suite_name, sc_##test_name) {test_##test_name();}; \ - TEST(test_suite_name, event_##test_name) {test_##test_name();}; \ - TEST(test_suite_name, sc_converted_##test_name) {test_##test_name();}; \ - TEST(test_suite_name, event_converted_##test_name) {test_##test_name();}; \ - template void test_##test_name() - - -TEST_CODES(filter_ppm_codes, check_openat) -{ - T t; - auto openat_only = t.openat_set; - auto not_openat = t.all_set().diff(openat_only); - - /* `openat_only` */ - ASSERT_FILTER_SET_EQ(t, "evt.type=openat", openat_only); - ASSERT_FILTER_SET_EQ(t, "evt.type = openat", openat_only); - ASSERT_FILTER_SET_EQ(t, "not evt.type != openat", openat_only); - ASSERT_FILTER_SET_EQ(t, "not not evt.type = openat", openat_only); - ASSERT_FILTER_SET_EQ(t, "not not not not evt.type = openat", openat_only); - ASSERT_FILTER_SET_EQ(t, "evt.type in (openat)", openat_only); - ASSERT_FILTER_SET_EQ(t, "not (not evt.type=openat)", openat_only); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat and proc.name=nginx", openat_only); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat and not proc.name=nginx", openat_only); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat and (proc.name=nginx)", openat_only); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat and not (evt.type=close and proc.name=nginx)", openat_only); - - /* `not_openat` */ - ASSERT_FILTER_SET_EQ(t, "evt.type!=openat", not_openat); - ASSERT_FILTER_SET_EQ(t, "not not not evt.type = openat", not_openat); - ASSERT_FILTER_SET_EQ(t, "not evt.type=openat", not_openat); - ASSERT_FILTER_SET_EQ(t, "evt.type=close or evt.type!=openat", not_openat); +#define TEST_CODES(test_suite_name, test_name) \ + template \ + void test_##test_name(); \ + TEST(test_suite_name, sc_##test_name) { \ + test_##test_name(); \ + }; \ + TEST(test_suite_name, event_##test_name) { \ + test_##test_name(); \ + }; \ + TEST(test_suite_name, sc_converted_##test_name) { \ + test_##test_name(); \ + }; \ + TEST(test_suite_name, event_converted_##test_name) { \ + test_##test_name(); \ + }; \ + template \ + void test_##test_name() + +TEST_CODES(filter_ppm_codes, check_openat) { + T t; + auto openat_only = t.openat_set; + auto not_openat = t.all_set().diff(openat_only); + + /* `openat_only` */ + ASSERT_FILTER_SET_EQ(t, "evt.type=openat", openat_only); + ASSERT_FILTER_SET_EQ(t, "evt.type = openat", openat_only); + ASSERT_FILTER_SET_EQ(t, "not evt.type != openat", openat_only); + ASSERT_FILTER_SET_EQ(t, "not not evt.type = openat", openat_only); + ASSERT_FILTER_SET_EQ(t, "not not not not evt.type = openat", openat_only); + ASSERT_FILTER_SET_EQ(t, "evt.type in (openat)", openat_only); + ASSERT_FILTER_SET_EQ(t, "not (not evt.type=openat)", openat_only); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat and proc.name=nginx", openat_only); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat and not proc.name=nginx", openat_only); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat and (proc.name=nginx)", openat_only); + ASSERT_FILTER_SET_EQ(t, + "evt.type=openat and not (evt.type=close and proc.name=nginx)", + openat_only); + + /* `not_openat` */ + ASSERT_FILTER_SET_EQ(t, "evt.type!=openat", not_openat); + ASSERT_FILTER_SET_EQ(t, "not not not evt.type = openat", not_openat); + ASSERT_FILTER_SET_EQ(t, "not evt.type=openat", not_openat); + ASSERT_FILTER_SET_EQ(t, "evt.type=close or evt.type!=openat", not_openat); } -TEST_CODES(filter_ppm_codes, check_openat_or_close) -{ - T t; - auto openat_close_only = t.openat_set.merge(t.close_set); - auto not_openat_close = t.all_set().diff(openat_close_only); - - /* `openat_close_only` */ - ASSERT_FILTER_SET_EQ(t, "evt.type in (openat, close)", openat_close_only); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat or evt.type=close", openat_close_only); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat or (evt.type=close and proc.name=nginx)", openat_close_only); - ASSERT_FILTER_SET_EQ(t, "evt.type=close or (evt.type=openat and proc.name=nginx)", openat_close_only); - - /* not `not_openat_close` */ - ASSERT_FILTER_SET_EQ(t, "not evt.type in (openat, close)", not_openat_close); - ASSERT_FILTER_SET_EQ(t, "not not not evt.type in (openat, close)", not_openat_close); - ASSERT_FILTER_SET_EQ(t, "evt.type!=openat and evt.type!=close", not_openat_close); +TEST_CODES(filter_ppm_codes, check_openat_or_close) { + T t; + auto openat_close_only = t.openat_set.merge(t.close_set); + auto not_openat_close = t.all_set().diff(openat_close_only); + + /* `openat_close_only` */ + ASSERT_FILTER_SET_EQ(t, "evt.type in (openat, close)", openat_close_only); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat or evt.type=close", openat_close_only); + ASSERT_FILTER_SET_EQ(t, + "evt.type=openat or (evt.type=close and proc.name=nginx)", + openat_close_only); + ASSERT_FILTER_SET_EQ(t, + "evt.type=close or (evt.type=openat and proc.name=nginx)", + openat_close_only); + + /* not `not_openat_close` */ + ASSERT_FILTER_SET_EQ(t, "not evt.type in (openat, close)", not_openat_close); + ASSERT_FILTER_SET_EQ(t, "not not not evt.type in (openat, close)", not_openat_close); + ASSERT_FILTER_SET_EQ(t, "evt.type!=openat and evt.type!=close", not_openat_close); } -TEST_CODES(filter_ppm_codes, check_all_events) -{ - /* Computed as a difference of the empty set */ - T t; - auto all_events = t.all_set(); - - ASSERT_FILTER_SET_EQ(t, "evt.type!=openat or evt.type!=close", all_events); - ASSERT_FILTER_SET_EQ(t, "proc.name=nginx", all_events); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat or proc.name=nginx", all_events); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat or (proc.name=nginx)", all_events); - ASSERT_FILTER_SET_EQ(t, "(evt.type=openat) or proc.name=nginx", all_events); - ASSERT_FILTER_SET_EQ(t, "evt.type=close or not (evt.type=openat and proc.name=nginx)", all_events); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat or not (evt.type=close and proc.name=nginx)", all_events); +TEST_CODES(filter_ppm_codes, check_all_events) { + /* Computed as a difference of the empty set */ + T t; + auto all_events = t.all_set(); + + ASSERT_FILTER_SET_EQ(t, "evt.type!=openat or evt.type!=close", all_events); + ASSERT_FILTER_SET_EQ(t, "proc.name=nginx", all_events); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat or proc.name=nginx", all_events); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat or (proc.name=nginx)", all_events); + ASSERT_FILTER_SET_EQ(t, "(evt.type=openat) or proc.name=nginx", all_events); + ASSERT_FILTER_SET_EQ(t, + "evt.type=close or not (evt.type=openat and proc.name=nginx)", + all_events); + ASSERT_FILTER_SET_EQ(t, + "evt.type=openat or not (evt.type=close and proc.name=nginx)", + all_events); } -TEST_CODES(filter_ppm_codes, check_no_events) -{ - T t; - auto no_events = t.all_set(); - no_events.clear(); +TEST_CODES(filter_ppm_codes, check_no_events) { + T t; + auto no_events = t.all_set(); + no_events.clear(); - ASSERT_FILTER_SET_EQ(t, "evt.type=close and evt.type=openat", no_events); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat and (evt.type=close and proc.name=nginx)", no_events); - ASSERT_FILTER_SET_EQ(t, "evt.type=openat and (evt.type=close)", no_events); + ASSERT_FILTER_SET_EQ(t, "evt.type=close and evt.type=openat", no_events); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat and (evt.type=close and proc.name=nginx)", no_events); + ASSERT_FILTER_SET_EQ(t, "evt.type=openat and (evt.type=close)", no_events); } -TEST_CODES(filter_ppm_codes, check_properties) -{ - T t; - auto no_events = t.all_set(); - no_events.clear(); - - // see: https://github.com/falcosecurity/libs/pull/854#issuecomment-1411151732 - ASSERT_FILTER_EQ(t, - "evt.type in (connect, execve, accept, mmap, container) and not (proc.name=cat and evt.type=mmap)", - "evt.type in (accept, connect, container, execve, mmap)"); - ASSERT_FILTER_SET_EQ(t, "(evt.type=mmap and not evt.type=mmap)", no_events); - - // defining algebraic base sets - std::string zerof = "(evt.type in ())"; ///< "zero"-set: no evt type should matches the filter - std::string onef = "(evt.type exists)"; ///< "one"-set: all evt types should match the filter - std::string neutral1 = "(proc.name=cat)"; ///< "neutral"-sets: evt types are not checked in the filter - std::string neutral2 = "(not proc.name=cat)"; - ASSERT_FILTER_EQ(t, onef, neutral1); - ASSERT_FILTER_EQ(t, onef, neutral2); - - // algebraic set properties - // 1' = 0 - ASSERT_FILTER_EQ(t, "not " + onef, zerof); - // 0' = 1 - ASSERT_FILTER_EQ(t, "not " + zerof, onef); - // (A')' = A - ASSERT_FILTER_EQ(t, "evt.type=mmap", "not (not evt.type=mmap)"); - // A * A' = 0 - ASSERT_FILTER_SET_EQ(t, (zerof), no_events); - // A + A' = 1 - ASSERT_FILTER_EQ(t, "evt.type=mmap or not evt.type=mmap", onef); - ASSERT_FILTER_EQ(t, "evt.type=mmap or not evt.type=mmap", neutral1); - ASSERT_FILTER_EQ(t, "evt.type=mmap or not evt.type=mmap", neutral2); - // 0 * 1 = 0 - ASSERT_FILTER_EQ(t, zerof + " and " + onef, zerof); - ASSERT_FILTER_EQ(t, zerof + " and " + neutral1, zerof); - ASSERT_FILTER_EQ(t, zerof + " and " + neutral2, zerof); - // 0 + 1 = 1 - ASSERT_FILTER_EQ(t, zerof + " or " + onef, onef); - ASSERT_FILTER_EQ(t, zerof + " or " + neutral1, onef); - ASSERT_FILTER_EQ(t, zerof + " or " + neutral2, onef); - // A * 0 = 0 - ASSERT_FILTER_EQ(t, "evt.type=mmap and " + zerof, zerof); - // A * 1 = A - ASSERT_FILTER_EQ(t, "evt.type=mmap and " + onef, "evt.type=mmap"); - ASSERT_FILTER_EQ(t, "evt.type=mmap and " + neutral1, "evt.type=mmap"); - ASSERT_FILTER_EQ(t, "evt.type=mmap and " + neutral2, "evt.type=mmap"); - // A + 0 = A - ASSERT_FILTER_EQ(t, "evt.type=mmap or " + zerof, "evt.type=mmap"); - // A + 1 = 1 - ASSERT_FILTER_EQ(t, "evt.type=mmap or " + onef, onef); - ASSERT_FILTER_EQ(t, "evt.type=mmap or " + neutral1, onef); - ASSERT_FILTER_EQ(t, "evt.type=mmap or " + neutral2, onef); - // A + A = A - ASSERT_FILTER_EQ(t, "evt.type=mmap or evt.type=mmap", "evt.type=mmap"); - // A * A = A - ASSERT_FILTER_EQ(t, "evt.type=mmap and evt.type=mmap", "evt.type=mmap"); - - // de morgan's laws - ASSERT_FILTER_EQ(t, - "not (proc.name=cat or evt.type=mmap)", - "not proc.name=cat and not evt.type=mmap"); - ASSERT_FILTER_EQ(t, - "not (proc.name=cat or fd.type=file)", - "not proc.name=cat and not fd.type=file"); - ASSERT_FILTER_EQ(t, - "not (evt.type=execve or evt.type=mmap)", - "not evt.type=execve and not evt.type=mmap"); - ASSERT_FILTER_EQ(t, - "not (evt.type=mmap or evt.type=mmap)", - "not evt.type=mmap and not evt.type=mmap"); - ASSERT_FILTER_EQ(t, - "not (proc.name=cat and evt.type=mmap)", - "not proc.name=cat or not evt.type=mmap"); - ASSERT_FILTER_EQ(t, - "not (proc.name=cat and fd.type=file)", - "not proc.name=cat or not fd.type=file"); - ASSERT_FILTER_EQ(t, - "not (evt.type=execve and evt.type=mmap)", - "not evt.type=execve or not evt.type=mmap"); - ASSERT_FILTER_EQ(t, - "not (evt.type=mmap and evt.type=mmap)", - "not evt.type=mmap or not evt.type=mmap"); - - // negation isomorphism - ASSERT_FILTER_EQ(t, "not evt.type=mmap", "evt.type!=mmap"); - ASSERT_FILTER_EQ(t, "not proc.name=cat", "proc.name!=cat"); - - // commutative property (and) - ASSERT_FILTER_EQ(t, "evt.type=execve and evt.type=mmap", "evt.type=mmap and evt.type=execve"); - ASSERT_FILTER_EQ(t, "not (evt.type=execve and evt.type=mmap)", "not (evt.type=mmap and evt.type=execve)"); - ASSERT_FILTER_EQ(t, "not evt.type=execve and not evt.type=mmap", "not evt.type=mmap and not evt.type=execve"); - ASSERT_FILTER_EQ(t, "proc.name=cat and evt.type=mmap", "evt.type=mmap and proc.name=cat"); - ASSERT_FILTER_EQ(t, "not (proc.name=cat and evt.type=mmap)", "not (evt.type=mmap and proc.name=cat)"); - ASSERT_FILTER_EQ(t, "not proc.name=cat and not evt.type=mmap", "not evt.type=mmap and not proc.name=cat"); - ASSERT_FILTER_EQ(t, "proc.name=cat and fd.type=file", "fd.type=file and proc.name=cat"); - ASSERT_FILTER_EQ(t, "not (proc.name=cat and fd.type=file)", "not (fd.type=file and proc.name=cat)"); - ASSERT_FILTER_EQ(t, "not proc.name=cat and not fd.type=file", "not fd.type=file and not proc.name=cat"); - - // commutative property (or) - ASSERT_FILTER_EQ(t, "evt.type=execve or evt.type=mmap", "evt.type=mmap or evt.type=execve"); - ASSERT_FILTER_EQ(t, "not (evt.type=execve or evt.type=mmap)", "not (evt.type=mmap or evt.type=execve)"); - ASSERT_FILTER_EQ(t, "not evt.type=execve or not evt.type=mmap", "not evt.type=mmap or not evt.type=execve"); - ASSERT_FILTER_EQ(t, "proc.name=cat or evt.type=mmap", "evt.type=mmap or proc.name=cat"); - ASSERT_FILTER_EQ(t, "not (proc.name=cat or evt.type=mmap)", "not (evt.type=mmap or proc.name=cat)"); - ASSERT_FILTER_EQ(t, "not proc.name=cat or not evt.type=mmap", "not evt.type=mmap or not proc.name=cat"); - ASSERT_FILTER_EQ(t, "proc.name=cat or fd.type=file", "fd.type=file or proc.name=cat"); - ASSERT_FILTER_EQ(t, "not (proc.name=cat or fd.type=file)", "not (fd.type=file or proc.name=cat)"); - ASSERT_FILTER_EQ(t, "not proc.name=cat or not fd.type=file", "not fd.type=file or not proc.name=cat"); +TEST_CODES(filter_ppm_codes, check_properties) { + T t; + auto no_events = t.all_set(); + no_events.clear(); + + // see: https://github.com/falcosecurity/libs/pull/854#issuecomment-1411151732 + ASSERT_FILTER_EQ(t, + "evt.type in (connect, execve, accept, mmap, container) and not " + "(proc.name=cat and evt.type=mmap)", + "evt.type in (accept, connect, container, execve, mmap)"); + ASSERT_FILTER_SET_EQ(t, "(evt.type=mmap and not evt.type=mmap)", no_events); + + // defining algebraic base sets + std::string zerof = "(evt.type in ())"; ///< "zero"-set: no evt type should matches the filter + std::string onef = "(evt.type exists)"; ///< "one"-set: all evt types should match the filter + std::string neutral1 = + "(proc.name=cat)"; ///< "neutral"-sets: evt types are not checked in the filter + std::string neutral2 = "(not proc.name=cat)"; + ASSERT_FILTER_EQ(t, onef, neutral1); + ASSERT_FILTER_EQ(t, onef, neutral2); + + // algebraic set properties + // 1' = 0 + ASSERT_FILTER_EQ(t, "not " + onef, zerof); + // 0' = 1 + ASSERT_FILTER_EQ(t, "not " + zerof, onef); + // (A')' = A + ASSERT_FILTER_EQ(t, "evt.type=mmap", "not (not evt.type=mmap)"); + // A * A' = 0 + ASSERT_FILTER_SET_EQ(t, (zerof), no_events); + // A + A' = 1 + ASSERT_FILTER_EQ(t, "evt.type=mmap or not evt.type=mmap", onef); + ASSERT_FILTER_EQ(t, "evt.type=mmap or not evt.type=mmap", neutral1); + ASSERT_FILTER_EQ(t, "evt.type=mmap or not evt.type=mmap", neutral2); + // 0 * 1 = 0 + ASSERT_FILTER_EQ(t, zerof + " and " + onef, zerof); + ASSERT_FILTER_EQ(t, zerof + " and " + neutral1, zerof); + ASSERT_FILTER_EQ(t, zerof + " and " + neutral2, zerof); + // 0 + 1 = 1 + ASSERT_FILTER_EQ(t, zerof + " or " + onef, onef); + ASSERT_FILTER_EQ(t, zerof + " or " + neutral1, onef); + ASSERT_FILTER_EQ(t, zerof + " or " + neutral2, onef); + // A * 0 = 0 + ASSERT_FILTER_EQ(t, "evt.type=mmap and " + zerof, zerof); + // A * 1 = A + ASSERT_FILTER_EQ(t, "evt.type=mmap and " + onef, "evt.type=mmap"); + ASSERT_FILTER_EQ(t, "evt.type=mmap and " + neutral1, "evt.type=mmap"); + ASSERT_FILTER_EQ(t, "evt.type=mmap and " + neutral2, "evt.type=mmap"); + // A + 0 = A + ASSERT_FILTER_EQ(t, "evt.type=mmap or " + zerof, "evt.type=mmap"); + // A + 1 = 1 + ASSERT_FILTER_EQ(t, "evt.type=mmap or " + onef, onef); + ASSERT_FILTER_EQ(t, "evt.type=mmap or " + neutral1, onef); + ASSERT_FILTER_EQ(t, "evt.type=mmap or " + neutral2, onef); + // A + A = A + ASSERT_FILTER_EQ(t, "evt.type=mmap or evt.type=mmap", "evt.type=mmap"); + // A * A = A + ASSERT_FILTER_EQ(t, "evt.type=mmap and evt.type=mmap", "evt.type=mmap"); + + // de morgan's laws + ASSERT_FILTER_EQ(t, + "not (proc.name=cat or evt.type=mmap)", + "not proc.name=cat and not evt.type=mmap"); + ASSERT_FILTER_EQ(t, + "not (proc.name=cat or fd.type=file)", + "not proc.name=cat and not fd.type=file"); + ASSERT_FILTER_EQ(t, + "not (evt.type=execve or evt.type=mmap)", + "not evt.type=execve and not evt.type=mmap"); + ASSERT_FILTER_EQ(t, + "not (evt.type=mmap or evt.type=mmap)", + "not evt.type=mmap and not evt.type=mmap"); + ASSERT_FILTER_EQ(t, + "not (proc.name=cat and evt.type=mmap)", + "not proc.name=cat or not evt.type=mmap"); + ASSERT_FILTER_EQ(t, + "not (proc.name=cat and fd.type=file)", + "not proc.name=cat or not fd.type=file"); + ASSERT_FILTER_EQ(t, + "not (evt.type=execve and evt.type=mmap)", + "not evt.type=execve or not evt.type=mmap"); + ASSERT_FILTER_EQ(t, + "not (evt.type=mmap and evt.type=mmap)", + "not evt.type=mmap or not evt.type=mmap"); + + // negation isomorphism + ASSERT_FILTER_EQ(t, "not evt.type=mmap", "evt.type!=mmap"); + ASSERT_FILTER_EQ(t, "not proc.name=cat", "proc.name!=cat"); + + // commutative property (and) + ASSERT_FILTER_EQ(t, "evt.type=execve and evt.type=mmap", "evt.type=mmap and evt.type=execve"); + ASSERT_FILTER_EQ(t, + "not (evt.type=execve and evt.type=mmap)", + "not (evt.type=mmap and evt.type=execve)"); + ASSERT_FILTER_EQ(t, + "not evt.type=execve and not evt.type=mmap", + "not evt.type=mmap and not evt.type=execve"); + ASSERT_FILTER_EQ(t, "proc.name=cat and evt.type=mmap", "evt.type=mmap and proc.name=cat"); + ASSERT_FILTER_EQ(t, + "not (proc.name=cat and evt.type=mmap)", + "not (evt.type=mmap and proc.name=cat)"); + ASSERT_FILTER_EQ(t, + "not proc.name=cat and not evt.type=mmap", + "not evt.type=mmap and not proc.name=cat"); + ASSERT_FILTER_EQ(t, "proc.name=cat and fd.type=file", "fd.type=file and proc.name=cat"); + ASSERT_FILTER_EQ(t, + "not (proc.name=cat and fd.type=file)", + "not (fd.type=file and proc.name=cat)"); + ASSERT_FILTER_EQ(t, + "not proc.name=cat and not fd.type=file", + "not fd.type=file and not proc.name=cat"); + + // commutative property (or) + ASSERT_FILTER_EQ(t, "evt.type=execve or evt.type=mmap", "evt.type=mmap or evt.type=execve"); + ASSERT_FILTER_EQ(t, + "not (evt.type=execve or evt.type=mmap)", + "not (evt.type=mmap or evt.type=execve)"); + ASSERT_FILTER_EQ(t, + "not evt.type=execve or not evt.type=mmap", + "not evt.type=mmap or not evt.type=execve"); + ASSERT_FILTER_EQ(t, "proc.name=cat or evt.type=mmap", "evt.type=mmap or proc.name=cat"); + ASSERT_FILTER_EQ(t, + "not (proc.name=cat or evt.type=mmap)", + "not (evt.type=mmap or proc.name=cat)"); + ASSERT_FILTER_EQ(t, + "not proc.name=cat or not evt.type=mmap", + "not evt.type=mmap or not proc.name=cat"); + ASSERT_FILTER_EQ(t, "proc.name=cat or fd.type=file", "fd.type=file or proc.name=cat"); + ASSERT_FILTER_EQ(t, + "not (proc.name=cat or fd.type=file)", + "not (fd.type=file or proc.name=cat)"); + ASSERT_FILTER_EQ(t, + "not proc.name=cat or not fd.type=file", + "not fd.type=file or not proc.name=cat"); } -TEST_CODES(filter_ppm_codes, field_transformers) -{ - auto parse = [](const std::string& f) { - libsinsp::filter::ast::ppm_event_codes(libsinsp::filter::parser(f).parse().get()); - }; - - ASSERT_NO_THROW(parse("evt.type = close")); - ASSERT_NO_THROW(parse("b64(proc.name) = cat")); - ASSERT_NO_THROW(parse("proc.name = b64(fd.name)")); - ASSERT_NO_THROW(parse("b64(proc.name) = b64(fd.name)")); - ASSERT_NO_THROW(parse("evt.type != close")); - ASSERT_NO_THROW(parse("b64(proc.name) != cat")); - ASSERT_NO_THROW(parse("proc.name != b64(fd.name)")); - ASSERT_NO_THROW(parse("b64(proc.name) != b64(fd.name)")); - ASSERT_NO_THROW(parse("not evt.type = close")); - ASSERT_NO_THROW(parse("not b64(proc.name) = cat")); - ASSERT_NO_THROW(parse("not proc.name = b64(fd.name)")); - ASSERT_NO_THROW(parse("not b64(proc.name) = b64(fd.name)")); - ASSERT_NO_THROW(parse("not evt.type != close")); - ASSERT_NO_THROW(parse("not b64(proc.name) != cat")); - ASSERT_NO_THROW(parse("not proc.name != b64(fd.name)")); - ASSERT_NO_THROW(parse("not b64(proc.name) != b64(fd.name)")); - - ASSERT_ANY_THROW(parse("b64(evt.type) = close")); - ASSERT_ANY_THROW(parse("evt.type = b64(proc.name)")); - ASSERT_ANY_THROW(parse("evt.type = val(proc.name)")); - ASSERT_ANY_THROW(parse("b64(evt.type) = val(proc.name)")); - ASSERT_ANY_THROW(parse("b64(evt.type) != close")); - ASSERT_ANY_THROW(parse("evt.type != b64(proc.name)")); - ASSERT_ANY_THROW(parse("evt.type != val(proc.name)")); - ASSERT_ANY_THROW(parse("b64(evt.type) != val(proc.name)")); - ASSERT_ANY_THROW(parse("not b64(evt.type) = close")); - ASSERT_ANY_THROW(parse("not evt.type = b64(proc.name)")); - ASSERT_ANY_THROW(parse("not evt.type = val(proc.name)")); - ASSERT_ANY_THROW(parse("not b64(evt.type) = val(proc.name)")); - ASSERT_ANY_THROW(parse("not b64(evt.type) != close")); - ASSERT_ANY_THROW(parse("not evt.type != b64(proc.name)")); - ASSERT_ANY_THROW(parse("not evt.type != val(proc.name)")); - ASSERT_ANY_THROW(parse("not b64(evt.type) != val(proc.name)")); +TEST_CODES(filter_ppm_codes, field_transformers) { + auto parse = [](const std::string& f) { + libsinsp::filter::ast::ppm_event_codes(libsinsp::filter::parser(f).parse().get()); + }; + + ASSERT_NO_THROW(parse("evt.type = close")); + ASSERT_NO_THROW(parse("b64(proc.name) = cat")); + ASSERT_NO_THROW(parse("proc.name = b64(fd.name)")); + ASSERT_NO_THROW(parse("b64(proc.name) = b64(fd.name)")); + ASSERT_NO_THROW(parse("evt.type != close")); + ASSERT_NO_THROW(parse("b64(proc.name) != cat")); + ASSERT_NO_THROW(parse("proc.name != b64(fd.name)")); + ASSERT_NO_THROW(parse("b64(proc.name) != b64(fd.name)")); + ASSERT_NO_THROW(parse("not evt.type = close")); + ASSERT_NO_THROW(parse("not b64(proc.name) = cat")); + ASSERT_NO_THROW(parse("not proc.name = b64(fd.name)")); + ASSERT_NO_THROW(parse("not b64(proc.name) = b64(fd.name)")); + ASSERT_NO_THROW(parse("not evt.type != close")); + ASSERT_NO_THROW(parse("not b64(proc.name) != cat")); + ASSERT_NO_THROW(parse("not proc.name != b64(fd.name)")); + ASSERT_NO_THROW(parse("not b64(proc.name) != b64(fd.name)")); + + ASSERT_ANY_THROW(parse("b64(evt.type) = close")); + ASSERT_ANY_THROW(parse("evt.type = b64(proc.name)")); + ASSERT_ANY_THROW(parse("evt.type = val(proc.name)")); + ASSERT_ANY_THROW(parse("b64(evt.type) = val(proc.name)")); + ASSERT_ANY_THROW(parse("b64(evt.type) != close")); + ASSERT_ANY_THROW(parse("evt.type != b64(proc.name)")); + ASSERT_ANY_THROW(parse("evt.type != val(proc.name)")); + ASSERT_ANY_THROW(parse("b64(evt.type) != val(proc.name)")); + ASSERT_ANY_THROW(parse("not b64(evt.type) = close")); + ASSERT_ANY_THROW(parse("not evt.type = b64(proc.name)")); + ASSERT_ANY_THROW(parse("not evt.type = val(proc.name)")); + ASSERT_ANY_THROW(parse("not b64(evt.type) = val(proc.name)")); + ASSERT_ANY_THROW(parse("not b64(evt.type) != close")); + ASSERT_ANY_THROW(parse("not evt.type != b64(proc.name)")); + ASSERT_ANY_THROW(parse("not evt.type != val(proc.name)")); + ASSERT_ANY_THROW(parse("not b64(evt.type) != val(proc.name)")); } diff --git a/userspace/libsinsp/test/filter_transformer.ut.cpp b/userspace/libsinsp/test/filter_transformer.ut.cpp index 5ecddfe656..b4b6d61e47 100644 --- a/userspace/libsinsp/test/filter_transformer.ut.cpp +++ b/userspace/libsinsp/test/filter_transformer.ut.cpp @@ -23,284 +23,261 @@ limitations under the License. #include #include -static std::unordered_set all_param_types() -{ - std::unordered_set ret; - for (auto i = PT_NONE; i < PT_MAX; i = (ppm_param_type) ((size_t) i + 1)) - { - ret.insert(i); - } - return ret; +static std::unordered_set all_param_types() { + std::unordered_set ret; + for(auto i = PT_NONE; i < PT_MAX; i = (ppm_param_type)((size_t)i + 1)) { + ret.insert(i); + } + return ret; } -static std::string supported_type_msg(ppm_param_type t, bool support_expected) -{ - return "expected param type to" - + std::string((support_expected ? " " : " not ")) - + "be supported: " - + std::string(param_type_to_string(t)); +static std::string supported_type_msg(ppm_param_type t, bool support_expected) { + return "expected param type to" + std::string((support_expected ? " " : " not ")) + + "be supported: " + std::string(param_type_to_string(t)); } -static std::string eq_test_msg(const std::pair &tc) -{ - return "expected '" - + tc.first + "' (length: " + std::to_string(tc.first.length()) + ")" - + " to be equal to '" + tc.second + "' (length: " + std::to_string(tc.second.length()) + ")"; +static std::string eq_test_msg(const std::pair &tc) { + return "expected '" + tc.first + "' (length: " + std::to_string(tc.first.length()) + ")" + + " to be equal to '" + tc.second + "' (length: " + std::to_string(tc.second.length()) + + ")"; } -static extract_value_t const_str_to_extract_value(const char* v) -{ - extract_value_t ret; - ret.ptr = (uint8_t*) v; - ret.len = strlen(v) + 1; - return ret; +static extract_value_t const_str_to_extract_value(const char *v) { + extract_value_t ret; + ret.ptr = (uint8_t *)v; + ret.len = strlen(v) + 1; + return ret; } -TEST(sinsp_filter_transformer, toupper) -{ - sinsp_filter_transformer tr(filter_transformer_type::FTR_TOUPPER); - - auto all_types = all_param_types(); - - auto supported_types = std::unordered_set({ - PT_CHARBUF, PT_FSPATH, PT_FSRELPATH }); - - auto test_cases = std::vector>{ - {"hello", "HELLO"}, - {"world", "WORLD"}, - {"eXcItED", "EXCITED"}, - {"", ""}, - }; - - std::vector sample_vals; - - for (auto& tc : test_cases) - { - sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); - } - - // check for unsupported types - for (auto t : all_types) - { - if (supported_types.find(t) == supported_types.end()) - { - auto vals = sample_vals; - EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); - EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); - } - } - - // check for supported types - for (auto t : supported_types) - { - auto original = t; - EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); // note: toupper is expected not to alter the type - - auto vals = sample_vals; - EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); - EXPECT_EQ(vals.size(), test_cases.size()); - - for (uint32_t i = 0; i < test_cases.size(); i++) - { - EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) << eq_test_msg(test_cases[i]); - EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); - } - } +TEST(sinsp_filter_transformer, toupper) { + sinsp_filter_transformer tr(filter_transformer_type::FTR_TOUPPER); + + auto all_types = all_param_types(); + + auto supported_types = + std::unordered_set({PT_CHARBUF, PT_FSPATH, PT_FSRELPATH}); + + auto test_cases = std::vector>{ + {"hello", "HELLO"}, + {"world", "WORLD"}, + {"eXcItED", "EXCITED"}, + {"", ""}, + }; + + std::vector sample_vals; + + for(auto &tc : test_cases) { + sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); + } + + // check for unsupported types + for(auto t : all_types) { + if(supported_types.find(t) == supported_types.end()) { + auto vals = sample_vals; + EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); + EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); + } + } + + // check for supported types + for(auto t : supported_types) { + auto original = t; + EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); // note: toupper is expected not to alter the type + + auto vals = sample_vals; + EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); + EXPECT_EQ(vals.size(), test_cases.size()); + + for(uint32_t i = 0; i < test_cases.size(); i++) { + EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) + << eq_test_msg(test_cases[i]); + EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); + } + } } -TEST(sinsp_filter_transformer, tolower) -{ - sinsp_filter_transformer tr(filter_transformer_type::FTR_TOLOWER); - - auto all_types = all_param_types(); - - auto supported_types = std::unordered_set({ - PT_CHARBUF, PT_FSPATH, PT_FSRELPATH }); - - auto test_cases = std::vector>{ - {"HELLO", "hello"}, - {"world", "world"}, - {"NoT_eXcItED", "not_excited"}, - {"", ""}, - }; - - std::vector sample_vals; - - for (auto& tc : test_cases) - { - sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); - } - - // check for unsupported types - for (auto t : all_types) - { - if (supported_types.find(t) == supported_types.end()) - { - auto vals = sample_vals; - EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); - EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); - } - } - - // check for supported types - for (auto t : supported_types) - { - auto original = t; - EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); // note: tolower is expected not to alter the type - - auto vals = sample_vals; - EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); - EXPECT_EQ(vals.size(), test_cases.size()); - - for (uint32_t i = 0; i < test_cases.size(); i++) - { - EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) << eq_test_msg(test_cases[i]); - EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); - } - } +TEST(sinsp_filter_transformer, tolower) { + sinsp_filter_transformer tr(filter_transformer_type::FTR_TOLOWER); + + auto all_types = all_param_types(); + + auto supported_types = + std::unordered_set({PT_CHARBUF, PT_FSPATH, PT_FSRELPATH}); + + auto test_cases = std::vector>{ + {"HELLO", "hello"}, + {"world", "world"}, + {"NoT_eXcItED", "not_excited"}, + {"", ""}, + }; + + std::vector sample_vals; + + for(auto &tc : test_cases) { + sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); + } + + // check for unsupported types + for(auto t : all_types) { + if(supported_types.find(t) == supported_types.end()) { + auto vals = sample_vals; + EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); + EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); + } + } + + // check for supported types + for(auto t : supported_types) { + auto original = t; + EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); // note: tolower is expected not to alter the type + + auto vals = sample_vals; + EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); + EXPECT_EQ(vals.size(), test_cases.size()); + + for(uint32_t i = 0; i < test_cases.size(); i++) { + EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) + << eq_test_msg(test_cases[i]); + EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); + } + } } -TEST(sinsp_filter_transformer, b64) -{ - sinsp_filter_transformer tr(filter_transformer_type::FTR_BASE64); - - auto all_types = all_param_types(); - - auto supported_types = std::unordered_set({ - PT_CHARBUF, PT_BYTEBUF }); - - auto test_cases = std::vector>{ - {"aGVsbG8=", "hello"}, - {"d29ybGQgIQ==", "world !"}, - {"", ""}, - }; - - std::vector invalid_test_cases { - "!!!" - }; - - std::vector sample_vals; - for (auto& tc : test_cases) - { - sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); - } - - // check for unsupported types - for (auto t : all_types) - { - if (supported_types.find(t) == supported_types.end()) - { - auto vals = sample_vals; - EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); - EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); - } - } - - // check for supported types - for (auto t : supported_types) - { - auto original = t; - EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); // note: tolower is expected not to alter the type - - auto vals = sample_vals; - EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); - EXPECT_EQ(vals.size(), test_cases.size()); - - for (uint32_t i = 0; i < test_cases.size(); i++) - { - EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) << eq_test_msg(test_cases[i]); - EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); - } - } - - std::vector invalid_vals; - for (auto& tc : invalid_test_cases) - { - invalid_vals.push_back(const_str_to_extract_value(tc.c_str())); - } - - // check invalid input being rejected - { - auto t = PT_CHARBUF; - EXPECT_FALSE(tr.transform_values(invalid_vals, t)); - EXPECT_EQ(t, PT_CHARBUF); - } +TEST(sinsp_filter_transformer, b64) { + sinsp_filter_transformer tr(filter_transformer_type::FTR_BASE64); + + auto all_types = all_param_types(); + + auto supported_types = std::unordered_set({PT_CHARBUF, PT_BYTEBUF}); + + auto test_cases = std::vector>{ + {"aGVsbG8=", "hello"}, + {"d29ybGQgIQ==", "world !"}, + {"", ""}, + }; + + std::vector invalid_test_cases{"!!!"}; + + std::vector sample_vals; + for(auto &tc : test_cases) { + sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); + } + + // check for unsupported types + for(auto t : all_types) { + if(supported_types.find(t) == supported_types.end()) { + auto vals = sample_vals; + EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); + EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); + } + } + + // check for supported types + for(auto t : supported_types) { + auto original = t; + EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); // note: tolower is expected not to alter the type + + auto vals = sample_vals; + EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); + EXPECT_EQ(vals.size(), test_cases.size()); + + for(uint32_t i = 0; i < test_cases.size(); i++) { + EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) + << eq_test_msg(test_cases[i]); + EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); + } + } + + std::vector invalid_vals; + for(auto &tc : invalid_test_cases) { + invalid_vals.push_back(const_str_to_extract_value(tc.c_str())); + } + + // check invalid input being rejected + { + auto t = PT_CHARBUF; + EXPECT_FALSE(tr.transform_values(invalid_vals, t)); + EXPECT_EQ(t, PT_CHARBUF); + } } -TEST(sinsp_filter_transformer, basename) -{ - sinsp_filter_transformer tr(filter_transformer_type::FTR_BASENAME); - - auto all_types = all_param_types(); - - auto supported_types = std::unordered_set({PT_CHARBUF, PT_FSPATH, PT_FSRELPATH }); - - auto test_cases = std::vector>{ - {"/home/ubuntu/hello.txt", "hello.txt"}, - {"/usr/local/bin/cat", "cat"}, - {"/", ""}, - {"", ""}, - {"/hello/", ""}, - {"hello", "hello"}, - }; - - - std::vector sample_vals; - - for (auto& tc : test_cases) - { - sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); - } - - // check for unsupported types - for (auto t : all_types) - { - if (supported_types.find(t) == supported_types.end()) - { - auto vals = sample_vals; - EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); - EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); - } - } - - // check for supported types - for (auto t : supported_types) - { - auto original = t; - EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); // note: basename is expected not to alter the type - - auto vals = sample_vals; - EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); - EXPECT_EQ(original, t); - EXPECT_EQ(vals.size(), test_cases.size()); - - for (uint32_t i = 0; i < test_cases.size(); i++) - { - EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) << eq_test_msg(test_cases[i]); - EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); - } - } +TEST(sinsp_filter_transformer, basename) { + sinsp_filter_transformer tr(filter_transformer_type::FTR_BASENAME); + + auto all_types = all_param_types(); + + auto supported_types = + std::unordered_set({PT_CHARBUF, PT_FSPATH, PT_FSRELPATH}); + + auto test_cases = std::vector>{ + {"/home/ubuntu/hello.txt", "hello.txt"}, + {"/usr/local/bin/cat", "cat"}, + {"/", ""}, + {"", ""}, + {"/hello/", ""}, + {"hello", "hello"}, + }; + + std::vector sample_vals; + + for(auto &tc : test_cases) { + sample_vals.push_back(const_str_to_extract_value(tc.first.c_str())); + } + + // check for unsupported types + for(auto t : all_types) { + if(supported_types.find(t) == supported_types.end()) { + auto vals = sample_vals; + EXPECT_FALSE(tr.transform_type(t)) << supported_type_msg(t, false); + EXPECT_ANY_THROW(tr.transform_values(vals, t)) << supported_type_msg(t, false); + } + } + + // check for supported types + for(auto t : supported_types) { + auto original = t; + EXPECT_TRUE(tr.transform_type(t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); // note: basename is expected not to alter the type + + auto vals = sample_vals; + EXPECT_TRUE(tr.transform_values(vals, t)) << supported_type_msg(original, true); + EXPECT_EQ(original, t); + EXPECT_EQ(vals.size(), test_cases.size()); + + for(uint32_t i = 0; i < test_cases.size(); i++) { + EXPECT_EQ(std::string((const char *)vals[i].ptr), test_cases[i].second) + << eq_test_msg(test_cases[i]); + EXPECT_EQ(vals[i].len, test_cases[i].second.length() + 1) << eq_test_msg(test_cases[i]); + } + } } -TEST_F(sinsp_with_test_input, basename_transformer) -{ - add_default_init_thread(); - open_inspector(); - - sinsp_evt *evt; - - int64_t dirfd = 3; - const char *file_to_run = "/tmp/file_to_run"; - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, file_to_run, 0, 0); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, dirfd, file_to_run, 0, 0, 0, (uint64_t) 0); - - EXPECT_TRUE(eval_filter(evt, "basename(fd.name) = file_to_run")); - EXPECT_FALSE(eval_filter(evt, "basename(fd.name) = /tmp/file_to_run")); +TEST_F(sinsp_with_test_input, basename_transformer) { + add_default_init_thread(); + open_inspector(); + + sinsp_evt *evt; + + int64_t dirfd = 3; + const char *file_to_run = "/tmp/file_to_run"; + add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, file_to_run, 0, 0); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + dirfd, + file_to_run, + 0, + 0, + 0, + (uint64_t)0); + + EXPECT_TRUE(eval_filter(evt, "basename(fd.name) = file_to_run")); + EXPECT_FALSE(eval_filter(evt, "basename(fd.name) = /tmp/file_to_run")); } diff --git a/userspace/libsinsp/test/filtercheck_has_args.ut.cpp b/userspace/libsinsp/test/filtercheck_has_args.ut.cpp index 4e96b339e9..0e62092236 100644 --- a/userspace/libsinsp/test/filtercheck_has_args.ut.cpp +++ b/userspace/libsinsp/test/filtercheck_has_args.ut.cpp @@ -22,8 +22,7 @@ limitations under the License. #include #include -TEST(filtercheck_has_args, has_args) -{ +TEST(filtercheck_has_args, has_args) { sinsp_filter_check_list sinsp_filter_checks; sinsp inspector; @@ -31,43 +30,31 @@ TEST(filtercheck_has_args, has_args) sinsp_filter_checks.get_all_fields(checks_info); - for(auto& check_info : checks_info) - { - for(int32_t i = 0; i < check_info->m_nfields; i++) - { + for(auto &check_info : checks_info) { + for(int32_t i = 0; i < check_info->m_nfields; i++) { const filtercheck_field_info *field_info = &(check_info->m_fields[i]); std::string field_str = field_info->m_name; bool expected = false; - if((field_info->m_flags & EPF_DEPRECATED)) - { + if((field_info->m_flags & EPF_DEPRECATED)) { continue; } if((field_info->m_flags & EPF_ARG_REQUIRED) || - (field_info->m_flags & EPF_ARG_ALLOWED)) - { + (field_info->m_flags & EPF_ARG_ALLOWED)) { expected = true; // A few fields explicitly require // .xxx arguments. For others, just // use a generic bracket based // argument. - if(field_str == "evt.type.is") - { + if(field_str == "evt.type.is") { field_str += ".open"; - } - else if (field_str == "evt.arg" || - field_str == "evt.rawarg") - { + } else if(field_str == "evt.arg" || field_str == "evt.rawarg") { field_str += ".res"; - } - else if (field_str == "thread.cgroup") - { + } else if(field_str == "thread.cgroup") { field_str += ".cpuacct"; - } - else - { + } else { field_str += "[1]"; } } @@ -76,11 +63,15 @@ TEST(filtercheck_has_args, has_args) bool needed_for_filtering = true; std::unique_ptr filtercheck( - sinsp_filter_checks.new_filter_check_from_fldname(field_str, &inspector, false)); + sinsp_filter_checks.new_filter_check_from_fldname(field_str, + &inspector, + false)); filtercheck->parse_field_name(field_str, alloc_state, needed_for_filtering); - EXPECT_EQ(expected, filtercheck->get_field_info()->is_arg_supported()) << "Field " + field_str + " did not return expected value " + std::to_string(expected) + " for is_arg_supported()"; + EXPECT_EQ(expected, filtercheck->get_field_info()->is_arg_supported()) + << "Field " + field_str + " did not return expected value " + + std::to_string(expected) + " for is_arg_supported()"; } } } diff --git a/userspace/libsinsp/test/filterchecks/evt.cpp b/userspace/libsinsp/test/filterchecks/evt.cpp index 8cafa278fd..5924e47cd1 100644 --- a/userspace/libsinsp/test/filterchecks/evt.cpp +++ b/userspace/libsinsp/test/filterchecks/evt.cpp @@ -18,8 +18,7 @@ limitations under the License. #include -TEST_F(sinsp_with_test_input, EVT_FILTER_is_open_create) -{ +TEST_F(sinsp_with_test_input, EVT_FILTER_is_open_create) { add_default_init_thread(); open_inspector(); @@ -28,24 +27,35 @@ TEST_F(sinsp_with_test_input, EVT_FILTER_is_open_create) int64_t fd = 3; // In the enter event we don't send the `PPM_O_F_CREATED` - sinsp_evt* evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, path.c_str(), - (uint32_t)PPM_O_RDWR | PPM_O_CREAT, (uint32_t)0); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + path.c_str(), + (uint32_t)PPM_O_RDWR | PPM_O_CREAT, + (uint32_t)0); ASSERT_EQ(get_field_as_string(evt, "evt.is_open_create"), "false"); // The `fdinfo` is not populated in the enter event ASSERT_FALSE(evt->get_fd_info()); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, path.c_str(), - (uint32_t)PPM_O_RDWR | PPM_O_CREAT | PPM_O_F_CREATED, (uint32_t)0, (uint32_t)5, - (uint64_t)123); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + path.c_str(), + (uint32_t)PPM_O_RDWR | PPM_O_CREAT | PPM_O_F_CREATED, + (uint32_t)0, + (uint32_t)5, + (uint64_t)123); ASSERT_EQ(get_field_as_string(evt, "evt.is_open_create"), "true"); ASSERT_TRUE(evt->get_fd_info()); ASSERT_EQ(evt->get_fd_info()->m_openflags, PPM_O_RDWR | PPM_O_CREAT | PPM_O_F_CREATED); } -TEST_F(sinsp_with_test_input, EVT_FILTER_is_lower_layer) -{ +TEST_F(sinsp_with_test_input, EVT_FILTER_is_lower_layer) { add_default_init_thread(); open_inspector(); @@ -54,15 +64,27 @@ TEST_F(sinsp_with_test_input, EVT_FILTER_is_lower_layer) int64_t fd = 3; // In the enter event we don't send the `PPM_O_F_CREATED` - sinsp_evt* evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, path.c_str(), - (uint32_t)PPM_O_RDONLY, (uint32_t)0); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + path.c_str(), + (uint32_t)PPM_O_RDONLY, + (uint32_t)0); // The `fdinfo` is not populated in the enter event ASSERT_FALSE(evt->get_fd_info()); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, path.c_str(), - (uint32_t)PPM_O_RDONLY | PPM_FD_LOWER_LAYER, (uint32_t)0, (uint32_t)5, - (uint64_t)123); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + path.c_str(), + (uint32_t)PPM_O_RDONLY | PPM_FD_LOWER_LAYER, + (uint32_t)0, + (uint32_t)5, + (uint64_t)123); ASSERT_EQ(get_field_as_string(evt, "fd.is_lower_layer"), "true"); ASSERT_EQ(get_field_as_string(evt, "fd.is_upper_layer"), "false"); ASSERT_TRUE(evt->get_fd_info()); @@ -71,8 +93,7 @@ TEST_F(sinsp_with_test_input, EVT_FILTER_is_lower_layer) ASSERT_EQ(evt->get_fd_info()->is_overlay_upper(), false); } -TEST_F(sinsp_with_test_input, EVT_FILTER_is_upper_layer) -{ +TEST_F(sinsp_with_test_input, EVT_FILTER_is_upper_layer) { add_default_init_thread(); open_inspector(); @@ -81,15 +102,27 @@ TEST_F(sinsp_with_test_input, EVT_FILTER_is_upper_layer) int64_t fd = 3; // In the enter event we don't send the `PPM_O_F_CREATED` - sinsp_evt* evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, path.c_str(), - (uint32_t)PPM_O_RDONLY, (uint32_t)0); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + path.c_str(), + (uint32_t)PPM_O_RDONLY, + (uint32_t)0); // The `fdinfo` is not populated in the enter event ASSERT_FALSE(evt->get_fd_info()); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, fd, path.c_str(), - (uint32_t)PPM_O_RDONLY | PPM_FD_UPPER_LAYER, (uint32_t)0, (uint32_t)5, - (uint64_t)123); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + fd, + path.c_str(), + (uint32_t)PPM_O_RDONLY | PPM_FD_UPPER_LAYER, + (uint32_t)0, + (uint32_t)5, + (uint64_t)123); ASSERT_EQ(get_field_as_string(evt, "fd.is_lower_layer"), "false"); ASSERT_EQ(get_field_as_string(evt, "fd.is_upper_layer"), "true"); ASSERT_TRUE(evt->get_fd_info()); @@ -98,18 +131,17 @@ TEST_F(sinsp_with_test_input, EVT_FILTER_is_upper_layer) ASSERT_EQ(evt->get_fd_info()->is_overlay_upper(), true); } -TEST_F(sinsp_with_test_input, EVT_FILTER_rawarg_int) -{ +TEST_F(sinsp_with_test_input, EVT_FILTER_rawarg_int) { add_default_init_thread(); open_inspector(); - sinsp_evt* evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_SETUID_E, 1, (uint32_t)1000); + sinsp_evt* evt = + add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_SETUID_E, 1, (uint32_t)1000); ASSERT_EQ(get_field_as_string(evt, "evt.rawarg.uid"), "1000"); } -TEST_F(sinsp_with_test_input, EVT_FILTER_rawarg_str) -{ +TEST_F(sinsp_with_test_input, EVT_FILTER_rawarg_str) { add_default_init_thread(); open_inspector(); @@ -117,25 +149,33 @@ TEST_F(sinsp_with_test_input, EVT_FILTER_rawarg_str) std::string path = "/home/file.txt"; // In the enter event we don't send the `PPM_O_F_CREATED` - sinsp_evt* evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, path.c_str(), - (uint32_t)0, (uint32_t)0); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + path.c_str(), + (uint32_t)0, + (uint32_t)0); ASSERT_EQ(get_field_as_string(evt, "evt.rawarg.name"), path); } -TEST_F(sinsp_with_test_input, EVT_FILTER_cmd_str) -{ +TEST_F(sinsp_with_test_input, EVT_FILTER_cmd_str) { add_default_init_thread(); - + open_inspector(); uint64_t fd = 1; - sinsp_evt* evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_BPF_2_X, 2, fd, PPM_BPF_PROG_LOAD); + sinsp_evt* evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_BPF_2_X, + 2, + fd, + PPM_BPF_PROG_LOAD); ASSERT_EQ(get_field_as_string(evt, "evt.arg.cmd"), "BPF_PROG_LOAD"); } -TEST_F(sinsp_with_test_input, EVT_FILTER_check_evt_arg_uid) -{ +TEST_F(sinsp_with_test_input, EVT_FILTER_check_evt_arg_uid) { add_default_init_thread(); open_inspector(); @@ -154,7 +194,8 @@ TEST_F(sinsp_with_test_input, EVT_FILTER_check_evt_arg_uid) ASSERT_EQ(get_field_as_string(evt, "evt.args"), "uid=5()"); // we are adding a user on the host so the `pid` parameter is not considered - ASSERT_TRUE(m_inspector.m_usergroup_manager.add_user(container_id, 0, user_id, 6, "test", "/test", "/bin/test")); + ASSERT_TRUE(m_inspector.m_usergroup_manager + .add_user(container_id, 0, user_id, 6, "test", "/test", "/bin/test")); // Now we should have the necessary info ASSERT_EQ(get_field_as_string(evt, "evt.arg.uid"), "test"); diff --git a/userspace/libsinsp/test/filterchecks/fd.cpp b/userspace/libsinsp/test/filterchecks/fd.cpp index 7f8b595afd..1c0829037f 100644 --- a/userspace/libsinsp/test/filterchecks/fd.cpp +++ b/userspace/libsinsp/test/filterchecks/fd.cpp @@ -18,8 +18,7 @@ limitations under the License. #include -TEST_F(sinsp_with_test_input, FD_FILTER_extract_from_null_type_filename) -{ +TEST_F(sinsp_with_test_input, FD_FILTER_extract_from_null_type_filename) { add_default_init_thread(); open_inspector(); @@ -28,20 +27,46 @@ TEST_F(sinsp_with_test_input, FD_FILTER_extract_from_null_type_filename) int64_t fd = 3; int64_t dirfd = 4; - auto evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SYSCALL_OPEN_E, fd, path.c_str(), - (uint32_t)PPM_O_RDWR | PPM_O_CREAT, (uint32_t)0); + auto evt = add_event_advance_ts(increasing_ts(), + INIT_TID, + PPME_SYSCALL_OPEN_E, + fd, + path.c_str(), + (uint32_t)PPM_O_RDWR | PPM_O_CREAT, + (uint32_t)0); ASSERT_FALSE(field_has_value(evt, "fd.filename")); - evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SYSCALL_OPENAT_2_E, 4, dirfd, path.c_str(), 0, 0); + evt = add_event_advance_ts(increasing_ts(), + INIT_TID, + PPME_SYSCALL_OPENAT_2_E, + 4, + dirfd, + path.c_str(), + 0, + 0); ASSERT_FALSE(field_has_value(evt, "fd.filename")); - evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SYSCALL_OPENAT2_E, 5, dirfd, path.c_str(), 0, 0, 0); + evt = add_event_advance_ts(increasing_ts(), + INIT_TID, + PPME_SYSCALL_OPENAT2_E, + 5, + dirfd, + path.c_str(), + 0, + 0, + 0); ASSERT_FALSE(field_has_value(evt, "fd.filename")); evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SYSCALL_CREAT_E, 2, path.c_str(), 0); ASSERT_FALSE(field_has_value(evt, "fd.filename")); - evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SYSCALL_OPENAT_E, 4, dirfd, path.c_str(), - PPM_O_RDONLY | PPM_O_CLOEXEC, 0); + evt = add_event_advance_ts(increasing_ts(), + INIT_TID, + PPME_SYSCALL_OPENAT_E, + 4, + dirfd, + path.c_str(), + PPM_O_RDONLY | PPM_O_CLOEXEC, + 0); ASSERT_FALSE(field_has_value(evt, "fd.filename")); } diff --git a/userspace/libsinsp/test/filterchecks/k8s.cpp b/userspace/libsinsp/test/filterchecks/k8s.cpp index eb8133ba34..b11100735a 100644 --- a/userspace/libsinsp/test/filterchecks/k8s.cpp +++ b/userspace/libsinsp/test/filterchecks/k8s.cpp @@ -13,8 +13,7 @@ limitations under the License. */ #include -TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_presence) -{ +TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_presence) { add_default_init_thread(); open_inspector(); auto evt = generate_random_event(); @@ -77,31 +76,33 @@ TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_presence) ASSERT_FALSE(field_has_value(evt, "k8s.deployment.labels")); } -TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_value) -{ +TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_value) { add_default_init_thread(); open_inspector(); - uint32_t ip = 0xC0A80101; // 192.168.1.1 + uint32_t ip = 0xC0A80101; // 192.168.1.1 std::string ip_string = "192.168.1.1"; std::string cni_json = "cni.pod"; std::string container_id = "fce2a82f930f"; - std::string container_full_id = "fce2a82f930fa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6"; + std::string container_full_id = + "fce2a82f930fa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6"; std::string container_name = "kind-control-plane"; std::string pod_name = "nginx"; std::string pod_uid = "5eaeeca9-2277-460b-a4bf-5a0783f6d49f"; std::string pod_sandbox_id = "1f04600dc694"; - std::string pod_full_sandbox_id = "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"; + std::string pod_full_sandbox_id = + "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"; std::string pod_namespace = "default"; std::map container_labels = { - {"io.kubernetes.sandbox.id", pod_full_sandbox_id}, - {"io.kubernetes.pod.name", pod_name}, - {"io.kubernetes.pod.uid", pod_uid}, - {"io.kubernetes.pod.namespace", pod_namespace}}; - std::map pod_sandbox_labels = {{"io.x-k8s.kind.cluster", "kind"}, - {"io.x-k8s.kind.role", "control-plane"}, - {"app.kubernetes-io/name_one", "example"}, - {"sample", "nginx"}}; + {"io.kubernetes.sandbox.id", pod_full_sandbox_id}, + {"io.kubernetes.pod.name", pod_name}, + {"io.kubernetes.pod.uid", pod_uid}, + {"io.kubernetes.pod.namespace", pod_namespace}}; + std::map pod_sandbox_labels = { + {"io.x-k8s.kind.cluster", "kind"}, + {"io.x-k8s.kind.role", "control-plane"}, + {"app.kubernetes-io/name_one", "example"}, + {"sample", "nginx"}}; auto init_thread_info = m_inspector.get_thread_ref(INIT_TID).get(); auto container_info = std::make_shared(); @@ -128,8 +129,9 @@ TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_value) // k8s filterchecks, populated because our mock container is in a pod ASSERT_EQ(get_field_as_string(evt, "k8s.pod.name"), pod_name); - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), pod_uid); // legacy pod UID - ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.id"), pod_uid); // legacy pod UID + ASSERT_EQ(get_field_as_string(evt, "k8s.pod.uid"), + get_field_as_string(evt, "k8s.pod.id")); // new semantically correct pod UID ASSERT_EQ(get_field_as_string(evt, "k8s.pod.sandbox_id"), pod_sandbox_id); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.full_sandbox_id"), pod_full_sandbox_id); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label.sample"), "nginx"); @@ -137,7 +139,8 @@ TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_value) ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label.app.kubernetes-io/name_one"), "example"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.label[app.kubernetes-io/name_one]"), "example"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.labels"), - "app.kubernetes-io/name_one:example, io.x-k8s.kind.cluster:kind, io.x-k8s.kind.role:control-plane, sample:nginx"); + "app.kubernetes-io/name_one:example, io.x-k8s.kind.cluster:kind, " + "io.x-k8s.kind.role:control-plane, sample:nginx"); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.ip"), ip_string); ASSERT_EQ(get_field_as_string(evt, "k8s.pod.cni.json"), cni_json); @@ -163,21 +166,22 @@ TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_value) ASSERT_FALSE(field_has_value(evt, "k8s.deployment.labels")); } -TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_value_with_no_labels) -{ +TEST_F(sinsp_with_test_input, K8S_FILTER_check_fields_value_with_no_labels) { add_default_init_thread(); open_inspector(); - uint32_t ip = 0xC0A80101; // 192.168.1.1 + uint32_t ip = 0xC0A80101; // 192.168.1.1 std::string ip_string = "192.168.1.1"; std::string cni_json = "cni.pod"; std::string container_id = "fce2a82f930f"; - std::string container_full_id = "fce2a82f930fa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6"; + std::string container_full_id = + "fce2a82f930fa803ab559f2393776b151f99fc5b05035b21db66b3b62246ad6"; std::string container_name = "kind-control-plane"; std::string pod_name = "nginx"; std::string pod_uid = "5eaeeca9-2277-460b-a4bf-5a0783f6d49f"; std::string pod_sandbox_id = "1f04600dc694"; - std::string pod_full_sandbox_id = "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"; + std::string pod_full_sandbox_id = + "1f04600dc6949359da68eee5fe7c4069706a567c07d1ef89fe3bbfdeac7a6dca"; std::string pod_namespace = "default"; std::map container_labels = {{"sample", "nginx"}}; std::map pod_sandbox_labels = {{"sample", "nginx"}}; diff --git a/userspace/libsinsp/test/filterchecks/mock.cpp b/userspace/libsinsp/test/filterchecks/mock.cpp index 4b1a971f95..8eae7d7b4d 100644 --- a/userspace/libsinsp/test/filterchecks/mock.cpp +++ b/userspace/libsinsp/test/filterchecks/mock.cpp @@ -22,35 +22,31 @@ limitations under the License. #include #include -#define RETURN_EXTRACT_VAR(x) \ - do \ - { \ - *len = sizeof((x)); \ - return (uint8_t*)&(x); \ +#define RETURN_EXTRACT_VAR(x) \ + do { \ + *len = sizeof((x)); \ + return (uint8_t*)&(x); \ } while(0) -#define RETURN_EXTRACT_STRING(x) \ - do \ - { \ - *len = (x).size(); \ - return (uint8_t*)(x).c_str(); \ +#define RETURN_EXTRACT_STRING(x) \ + do { \ + *len = (x).size(); \ + return (uint8_t*)(x).c_str(); \ } while(0) static const filtercheck_field_info sinsp_filter_check_mock_fields[] = { - {PT_INT64, EPF_NONE, PF_ID, "test.int64", "", ""}, - {PT_CHARBUF, EPF_NONE, PF_NA, "test.charbuf", "", ""}, - {PT_BYTEBUF, EPF_NONE, PF_NA, "test.bytebuf", "", ""}, - {PT_CHARBUF, EPF_IS_LIST | EPF_NO_TRANSFORMER, PF_NA, "test.list", "", ""}, - {PT_CHARBUF, EPF_IS_LIST, PF_NA, "test.another_list", "", ""}, - {PT_CHARBUF, EPF_NONE, PF_NA, "test.more_than_256", "", ""}, - {PT_CHARBUF, EPF_NONE, PF_NA, "test.base64", "", ""}, + {PT_INT64, EPF_NONE, PF_ID, "test.int64", "", ""}, + {PT_CHARBUF, EPF_NONE, PF_NA, "test.charbuf", "", ""}, + {PT_BYTEBUF, EPF_NONE, PF_NA, "test.bytebuf", "", ""}, + {PT_CHARBUF, EPF_IS_LIST | EPF_NO_TRANSFORMER, PF_NA, "test.list", "", ""}, + {PT_CHARBUF, EPF_IS_LIST, PF_NA, "test.another_list", "", ""}, + {PT_CHARBUF, EPF_NONE, PF_NA, "test.more_than_256", "", ""}, + {PT_CHARBUF, EPF_NONE, PF_NA, "test.base64", "", ""}, }; -class sinsp_filter_check_mock : public sinsp_filter_check -{ +class sinsp_filter_check_mock : public sinsp_filter_check { public: - enum check_type - { + enum check_type { TYPE_INT64 = 0, TYPE_CHARBUF, TYPE_BYTEBUF, @@ -60,30 +56,29 @@ class sinsp_filter_check_mock : public sinsp_filter_check TYPE_BASE64, }; - sinsp_filter_check_mock() - { + sinsp_filter_check_mock() { m_finfo.m_name = "test"; m_finfo.m_desc = ""; m_finfo.m_fields = sinsp_filter_check_mock_fields; - m_finfo.m_nfields = sizeof(sinsp_filter_check_mock_fields) / sizeof(sinsp_filter_check_mock_fields[0]); + m_finfo.m_nfields = + sizeof(sinsp_filter_check_mock_fields) / sizeof(sinsp_filter_check_mock_fields[0]); m_info = &m_finfo; } virtual ~sinsp_filter_check_mock() = default; - std::unique_ptr allocate_new() override - { + std::unique_ptr allocate_new() override { return std::make_unique(); } protected: - bool extract_nocache(sinsp_evt* evt, std::vector& values, bool sanitize_strings) override - { + bool extract_nocache(sinsp_evt* evt, + std::vector& values, + bool sanitize_strings) override { static const char* list_value_1 = "value1"; static const char* list_value_2 = "charbuf"; values.clear(); - if(m_field_id == TYPE_LIST || m_field_id == TYPE_ANOTHER_LIST) - { + if(m_field_id == TYPE_LIST || m_field_id == TYPE_ANOTHER_LIST) { extract_value_t val1; val1.ptr = (uint8_t*)list_value_1; val1.len = strlen(list_value_1); @@ -99,11 +94,9 @@ class sinsp_filter_check_mock : public sinsp_filter_check return sinsp_filter_check::extract_nocache(evt, values, sanitize_strings); } - uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override - { + uint8_t* extract_single(sinsp_evt*, uint32_t* len, bool sanitize_strings = true) override { *len = 0; - switch(m_field_id) - { + switch(m_field_id) { case TYPE_INT64: m_u64_val = 1; RETURN_EXTRACT_VAR(m_u64_val); @@ -117,7 +110,7 @@ class sinsp_filter_check_mock : public sinsp_filter_check m_str_val = std::string(257, 'a'); RETURN_EXTRACT_STRING(m_str_val); case TYPE_BASE64: - m_str_val = "Y2hhcmJ1Zg=="; // base64("charbuf") + m_str_val = "Y2hhcmJ1Zg=="; // base64("charbuf") RETURN_EXTRACT_STRING(m_str_val); default: throw std::runtime_error("unknown field id: " + std::to_string(m_field_id)); @@ -133,9 +126,9 @@ class sinsp_filter_check_mock : public sinsp_filter_check }; // Note the we create a filter check without values on purpose. -static std::unique_ptr create_filtercheck_from_field(sinsp* inspector, std::string_view field, - enum cmpop op = CO_EQ) -{ +static std::unique_ptr create_filtercheck_from_field(sinsp* inspector, + std::string_view field, + enum cmpop op = CO_EQ) { sinsp_filter_check_list filter_list; filter_list.add_filter_check(std::make_unique()); sinsp_filter_factory factory(inspector, filter_list); @@ -146,16 +139,14 @@ static std::unique_ptr create_filtercheck_from_field(sinsp* return check; } -static void add_filtercheck_value_vec(sinsp_filter_check* chk, const std::vector& vec) -{ - for(size_t i = 0; i < vec.size(); i++) - { +static void add_filtercheck_value_vec(sinsp_filter_check* chk, + const std::vector& vec) { + for(size_t i = 0; i < vec.size(); i++) { chk->add_filter_value(vec[i].c_str(), vec[i].size(), i); } } -TEST(mock_filtercheck_creation, simple_const_value) -{ +TEST(mock_filtercheck_creation, simple_const_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.int64"); add_filtercheck_value_vec(chk.get(), {"64"}); @@ -164,8 +155,7 @@ TEST(mock_filtercheck_creation, simple_const_value) ASSERT_FALSE(chk->get_filter_values().empty()); } -TEST(mock_filtercheck_creation, simple_const_list) -{ +TEST(mock_filtercheck_creation, simple_const_list) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list"); add_filtercheck_value_vec(chk.get(), {"2", "3"}); @@ -173,8 +163,7 @@ TEST(mock_filtercheck_creation, simple_const_list) ASSERT_FALSE(chk->has_filtercheck_value()); } -TEST(mock_filtercheck_creation, value_list_with_eq_operator) -{ +TEST(mock_filtercheck_creation, value_list_with_eq_operator) { // note(jasondellaluce): we are adding more than one value on a field that doesn't // support it due to the `EQ` operator, as we don't allow a syntax like // `test.charbuf = (charbuf, not-charbuf)`. However, we should be protected @@ -188,8 +177,7 @@ TEST(mock_filtercheck_creation, value_list_with_eq_operator) ASSERT_FALSE(chk->has_filtercheck_value()); } -TEST(mock_filtercheck_creation, bytebuf_value_too_long) -{ +TEST(mock_filtercheck_creation, bytebuf_value_too_long) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.bytebuf"); // For BYTEBUF values there is a limit on the len. (at max 256 chars) @@ -197,8 +185,7 @@ TEST(mock_filtercheck_creation, bytebuf_value_too_long) ASSERT_THROW(add_filtercheck_value_vec(chk.get(), {long_string}), sinsp_exception); } -TEST(mock_filtercheck_creation, charbuf_value_too_long) -{ +TEST(mock_filtercheck_creation, charbuf_value_too_long) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); // For CHARBUF values (and others) there is a limit on the len. (at max 256 chars) @@ -206,8 +193,7 @@ TEST(mock_filtercheck_creation, charbuf_value_too_long) ASSERT_THROW(add_filtercheck_value_vec(chk.get(), {long_string}), sinsp_exception); } -TEST(mock_filtercheck_creation, rhs_filter_with_same_type) -{ +TEST(mock_filtercheck_creation, rhs_filter_with_same_type) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); auto rhs_chk = create_filtercheck_from_field(&insp, "test.more_than_256"); @@ -215,8 +201,7 @@ TEST(mock_filtercheck_creation, rhs_filter_with_same_type) ASSERT_TRUE(chk->has_filtercheck_value()); } -TEST(mock_filtercheck_creation, rhs_filter_after_const_value) -{ +TEST(mock_filtercheck_creation, rhs_filter_after_const_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); add_filtercheck_value_vec(chk.get(), {"test"}); @@ -225,8 +210,7 @@ TEST(mock_filtercheck_creation, rhs_filter_after_const_value) ASSERT_THROW(chk->add_filter_value(std::move(rhs_chk)), sinsp_exception); } -TEST(mock_filtercheck_creation, const_value_after_rhs_filter) -{ +TEST(mock_filtercheck_creation, const_value_after_rhs_filter) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); auto rhs_chk = create_filtercheck_from_field(&insp, "test.more_than_256"); @@ -234,8 +218,7 @@ TEST(mock_filtercheck_creation, const_value_after_rhs_filter) ASSERT_THROW(add_filtercheck_value_vec(chk.get(), {"test"}), sinsp_exception); } -TEST(mock_filtercheck_creation, more_than_one_rhs_filter) -{ +TEST(mock_filtercheck_creation, more_than_one_rhs_filter) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); auto rhs_chk = create_filtercheck_from_field(&insp, "test.more_than_256"); @@ -244,47 +227,42 @@ TEST(mock_filtercheck_creation, more_than_one_rhs_filter) ASSERT_THROW(chk->add_filter_value(std::move(rhs_chk2)), sinsp_exception); } -TEST(mock_filtercheck_compare, single_value_CO_EQ_list) -{ +TEST(mock_filtercheck_compare, single_value_CO_EQ_list) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf", CO_EQ); add_filtercheck_value_vec(chk.get(), {"charbuf", "not-charbuf"}); ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, single_value_CO_EQ_rhs_filter_value) -{ +TEST(mock_filtercheck_compare, single_value_CO_EQ_rhs_filter_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf", CO_EQ); chk->add_filter_value(create_filtercheck_from_field(&insp, "test.base64")); ASSERT_FALSE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, single_value_CO_EQ_rhs_filter_list) -{ +TEST(mock_filtercheck_compare, single_value_CO_EQ_rhs_filter_list) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf", CO_EQ); - ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "test.list")), sinsp_exception); + ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "test.list")), + sinsp_exception); } -TEST(mock_filtercheck_compare, single_value_CO_IN_list) -{ +TEST(mock_filtercheck_compare, single_value_CO_IN_list) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf", CO_IN); add_filtercheck_value_vec(chk.get(), {"charbuf", "not-charbuf"}); ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, single_value_CO_IN_rhs_filter_value) -{ +TEST(mock_filtercheck_compare, single_value_CO_IN_rhs_filter_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf", CO_IN); chk->add_filter_value(create_filtercheck_from_field(&insp, "test.base64")); ASSERT_FALSE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, list_CO_EQ_value) -{ +TEST(mock_filtercheck_compare, list_CO_EQ_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list", CO_EQ); add_filtercheck_value_vec(chk.get(), {"charbuf"}); @@ -292,54 +270,49 @@ TEST(mock_filtercheck_compare, list_CO_EQ_value) ASSERT_THROW(chk->compare(nullptr), sinsp_exception); } -TEST(mock_filtercheck_compare, list_CO_EQ_rhs_filter_value) -{ +TEST(mock_filtercheck_compare, list_CO_EQ_rhs_filter_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list", CO_EQ); - ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "test.charbuf")), sinsp_exception); + ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "test.charbuf")), + sinsp_exception); } -TEST(mock_filtercheck_compare, list_CO_IN_value) -{ +TEST(mock_filtercheck_compare, list_CO_IN_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list", CO_IN); add_filtercheck_value_vec(chk.get(), {"value1"}); ASSERT_FALSE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, list_CO_IN_rhs_filter_list) -{ +TEST(mock_filtercheck_compare, list_CO_IN_rhs_filter_list) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list", CO_IN); chk->add_filter_value(create_filtercheck_from_field(&insp, "test.another_list")); ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, list_CO_INTERSECTS_value) -{ +TEST(mock_filtercheck_compare, list_CO_INTERSECTS_value) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list", CO_INTERSECTS); add_filtercheck_value_vec(chk.get(), {"value1"}); ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, list_CO_INTERSECTS_rhs_filter_list) -{ +TEST(mock_filtercheck_compare, list_CO_INTERSECTS_rhs_filter_list) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list", CO_INTERSECTS); chk->add_filter_value(create_filtercheck_from_field(&insp, "test.another_list")); ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_compare, rhs_filter_CO_PMATCH_not_supported) -{ +TEST(mock_filtercheck_compare, rhs_filter_CO_PMATCH_not_supported) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf", CO_PMATCH); - ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "test.charbuf")), sinsp_exception); + ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "test.charbuf")), + sinsp_exception); } -TEST(mock_filtercheck_compare, rhs_filter_EPF_NO_RHS_flag) -{ +TEST(mock_filtercheck_compare, rhs_filter_EPF_NO_RHS_flag) { sinsp insp; { @@ -351,19 +324,20 @@ TEST(mock_filtercheck_compare, rhs_filter_EPF_NO_RHS_flag) { // "fd.ip" is not allowed to be used on the left since it has the `EPF_NO_RHS` flag. auto chk = create_filtercheck_from_field(&insp, "fd.ip"); - ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "fd.sip")), sinsp_exception); + ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "fd.sip")), + sinsp_exception); } { // "fd.ip" is not allowed to be used on the right since it has the `EPF_NO_RHS` flag. auto chk = create_filtercheck_from_field(&insp, "fd.sip"); - ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "fd.ip")), sinsp_exception); + ASSERT_THROW(chk->add_filter_value(create_filtercheck_from_field(&insp, "fd.ip")), + sinsp_exception); } } #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(__APPLE__) -TEST_F(sinsp_with_test_input, check_some_fd_fields) -{ +TEST_F(sinsp_with_test_input, check_some_fd_fields) { add_default_init_thread(); open_inspector(); @@ -371,22 +345,41 @@ TEST_F(sinsp_with_test_input, check_some_fd_fields) int64_t client_fd = 9; int64_t return_value = 0; - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t)PPM_AF_INET6, (uint32_t)SOCK_DGRAM, - (uint32_t)0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET6, + (uint32_t)SOCK_DGRAM, + (uint32_t)0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); - sockaddr_in6 client = test_utils::fill_sockaddr_in6(DEFAULT_CLIENT_PORT, DEFAULT_IPV6_CLIENT_STRING); - sockaddr_in6 server = test_utils::fill_sockaddr_in6(DEFAULT_SERVER_PORT, DEFAULT_IPV6_SERVER_STRING); - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); + sockaddr_in6 client = + test_utils::fill_sockaddr_in6(DEFAULT_CLIENT_PORT, DEFAULT_IPV6_CLIENT_STRING); + sockaddr_in6 server = + test_utils::fill_sockaddr_in6(DEFAULT_SERVER_PORT, DEFAULT_IPV6_SERVER_STRING); + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); - /* The connect enter event populates the destination ip and the destination port thanks to the `server_sockaddr` + /* The connect enter event populates the destination ip and the destination port thanks to the + * `server_sockaddr` */ - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, - scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); std::vector socktuple = - test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - auto evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, - scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + auto evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); { // fd.cip will extract an ipv6 we cannot compare it with an ipv4, so we expect false @@ -421,17 +414,17 @@ TEST_F(sinsp_with_test_input, check_some_fd_fields) // fd.types with rhs filter check ASSERT_EQ(get_field_as_string(evt, "fd.types"), "(ipv6,file)"); auto chk = create_filtercheck_from_field(&m_inspector, "fd.types", CO_IN); - ASSERT_ANY_THROW(chk->add_filter_value(create_filtercheck_from_field(&m_inspector, "fd.types"))); + ASSERT_ANY_THROW( + chk->add_filter_value(create_filtercheck_from_field(&m_inspector, "fd.types"))); } } -#endif // !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(__APPLE__) +#endif // !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(__APPLE__) ///////////////////// // TRANSFORMERS ///////////////////// -TEST(mock_filtercheck_transformers, to_string_method_with_transformers) -{ +TEST(mock_filtercheck_transformers, to_string_method_with_transformers) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); chk->add_transformer(filter_transformer_type::FTR_TOUPPER); @@ -439,8 +432,7 @@ TEST(mock_filtercheck_transformers, to_string_method_with_transformers) ASSERT_EQ(std::string(chk->tostring(nullptr)), "CHARBUF"); } -TEST(mock_filtercheck_transformers, simple_compare_with_transformers) -{ +TEST(mock_filtercheck_transformers, simple_compare_with_transformers) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); chk->add_transformer(filter_transformer_type::FTR_TOUPPER); @@ -448,8 +440,7 @@ TEST(mock_filtercheck_transformers, simple_compare_with_transformers) ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_transformers, same_transformer_multiple_times) -{ +TEST(mock_filtercheck_transformers, same_transformer_multiple_times) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); chk->add_transformer(filter_transformer_type::FTR_TOUPPER); @@ -460,15 +451,13 @@ TEST(mock_filtercheck_transformers, same_transformer_multiple_times) ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_transformers, filter_with_not_supported_transformer) -{ +TEST(mock_filtercheck_transformers, filter_with_not_supported_transformer) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.list"); ASSERT_THROW(chk->add_transformer(filter_transformer_type::FTR_TOUPPER), sinsp_exception); } -TEST(mock_filtercheck_transformers, specular_expression) -{ +TEST(mock_filtercheck_transformers, specular_expression) { sinsp insp; // we want to check this filter `toupper(test.charbuf) = toupper(test.charbuf)` returns `true`. auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); @@ -481,8 +470,7 @@ TEST(mock_filtercheck_transformers, specular_expression) ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_transformers, toupper_plus_tolower) -{ +TEST(mock_filtercheck_transformers, toupper_plus_tolower) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.charbuf"); chk->add_transformer(filter_transformer_type::FTR_TOUPPER); @@ -491,8 +479,7 @@ TEST(mock_filtercheck_transformers, toupper_plus_tolower) ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_transformers, base64) -{ +TEST(mock_filtercheck_transformers, base64) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.base64"); chk->add_transformer(filter_transformer_type::FTR_BASE64); @@ -501,8 +488,7 @@ TEST(mock_filtercheck_transformers, base64) ASSERT_TRUE(chk->compare(nullptr)); } -TEST(mock_filtercheck_transformers, reflect_base64) -{ +TEST(mock_filtercheck_transformers, reflect_base64) { sinsp insp; auto chk = create_filtercheck_from_field(&insp, "test.base64"); chk->add_transformer(filter_transformer_type::FTR_BASE64); diff --git a/userspace/libsinsp/test/filterchecks/proc.cpp b/userspace/libsinsp/test/filterchecks/proc.cpp index fa024d8903..cfb8157bd5 100644 --- a/userspace/libsinsp/test/filterchecks/proc.cpp +++ b/userspace/libsinsp/test/filterchecks/proc.cpp @@ -18,8 +18,7 @@ limitations under the License. #include -TEST_F(sinsp_with_test_input, PROC_FILTER_nthreads) -{ +TEST_F(sinsp_with_test_input, PROC_FILTER_nthreads) { DEFAULT_TREE /* we call a random event to obtain an event associated with this thread info */ @@ -39,8 +38,7 @@ TEST_F(sinsp_with_test_input, PROC_FILTER_nthreads) ASSERT_EQ(get_field_as_string(evt, "proc.nthreads"), "0"); } -TEST_F(sinsp_with_test_input, PROC_FILTER_nchilds) -{ +TEST_F(sinsp_with_test_input, PROC_FILTER_nchilds) { DEFAULT_TREE /* we call a random event to obtain an event associated with this thread info */ @@ -65,37 +63,71 @@ TEST_F(sinsp_with_test_input, PROC_FILTER_nchilds) ASSERT_EQ(get_field_as_string(evt, "proc.nchilds"), "0"); } -TEST_F(sinsp_with_test_input, PROC_FILTER_exepath) -{ +TEST_F(sinsp_with_test_input, PROC_FILTER_exepath) { DEFAULT_TREE /* Now we call an execve on p6_t1 */ - auto evt = generate_execve_enter_and_exit_event(0, p6_t1_tid, p6_t1_tid, p6_t1_pid, p6_t1_ptid, "/good-exe", "good-exe", "/usr/bin/bad-exe"); + auto evt = generate_execve_enter_and_exit_event(0, + p6_t1_tid, + p6_t1_tid, + p6_t1_pid, + p6_t1_ptid, + "/good-exe", + "good-exe", + "/usr/bin/bad-exe"); ASSERT_EQ(get_field_as_string(evt, "proc.exepath"), "/usr/bin/bad-exe"); ASSERT_EQ(get_field_as_string(evt, "proc.name"), "good-exe"); } -TEST_F(sinsp_with_test_input, PROC_FILTER_pexepath_aexepath) -{ +TEST_F(sinsp_with_test_input, PROC_FILTER_pexepath_aexepath) { DEFAULT_TREE /* p3_t1 call execve to set an exepath */ - generate_execve_enter_and_exit_event(0, p3_t1_tid, p3_t1_tid, p3_t1_pid, p3_t1_ptid, "/p3_t1_exepath", "p3_t1", "/usr/bin/p3_t1_trusted_exepath"); + generate_execve_enter_and_exit_event(0, + p3_t1_tid, + p3_t1_tid, + p3_t1_pid, + p3_t1_ptid, + "/p3_t1_exepath", + "p3_t1", + "/usr/bin/p3_t1_trusted_exepath"); /* p4_t2 call execve to set an exepath */ - generate_execve_enter_and_exit_event(0, p4_t2_tid, p4_t1_tid, p4_t1_pid, p4_t1_ptid, "/p4_t1_exepath", "p4_t1", "/usr/bin/p4_t1_trusted_exepath"); + generate_execve_enter_and_exit_event(0, + p4_t2_tid, + p4_t1_tid, + p4_t1_pid, + p4_t1_ptid, + "/p4_t1_exepath", + "p4_t1", + "/usr/bin/p4_t1_trusted_exepath"); /* p5_t2 call execve to set an exepath */ - generate_execve_enter_and_exit_event(0, p5_t2_tid, p5_t1_tid, p5_t1_pid, p5_t1_ptid, "/p5_t1_exepath", "p5_t1", "/usr/bin/p5_t1_trusted_exepath"); + generate_execve_enter_and_exit_event(0, + p5_t2_tid, + p5_t1_tid, + p5_t1_pid, + p5_t1_ptid, + "/p5_t1_exepath", + "p5_t1", + "/usr/bin/p5_t1_trusted_exepath"); /* Now we call an execve on p6_t1 and we check for `pexepath` and `aexepath` */ - auto evt = generate_execve_enter_and_exit_event(0, p6_t1_tid, p6_t1_tid, p6_t1_pid, p6_t1_ptid, "/p6_t1_exepath", "p6_t1", "/usr/bin/p6_t1_trusted_exepath"); + auto evt = generate_execve_enter_and_exit_event(0, + p6_t1_tid, + p6_t1_tid, + p6_t1_pid, + p6_t1_ptid, + "/p6_t1_exepath", + "p6_t1", + "/usr/bin/p6_t1_trusted_exepath"); ASSERT_EQ(get_field_as_string(evt, "proc.exepath"), "/usr/bin/p6_t1_trusted_exepath"); ASSERT_EQ(get_field_as_string(evt, "proc.aexepath[0]"), "/usr/bin/p6_t1_trusted_exepath"); ASSERT_EQ(get_field_as_string(evt, "proc.pexepath"), "/usr/bin/p5_t1_trusted_exepath"); - ASSERT_EQ(get_field_as_string(evt, "proc.aexepath[1]"), get_field_as_string(evt, "proc.pexepath")); + ASSERT_EQ(get_field_as_string(evt, "proc.aexepath[1]"), + get_field_as_string(evt, "proc.pexepath")); ASSERT_EQ(get_field_as_string(evt, "proc.aexepath[2]"), "/usr/bin/p4_t1_trusted_exepath"); ASSERT_EQ(get_field_as_string(evt, "proc.aexepath[3]"), "/usr/bin/p3_t1_trusted_exepath"); /* p2_t1 never calls an execve so it takes the exepath from `init` */ @@ -106,12 +138,19 @@ TEST_F(sinsp_with_test_input, PROC_FILTER_pexepath_aexepath) ASSERT_FALSE(field_has_value(evt, "proc.aexepath[6]")); } -TEST_F(sinsp_with_test_input, PROC_FILTER_aname) -{ +TEST_F(sinsp_with_test_input, PROC_FILTER_aname) { DEFAULT_TREE - // proc.aname[0]=good-exe, proc.aname[1]=bash, proc.aname[2]=bash, proc.aname[3]=bash, proc.aname[4]=bash, proc.aname[5]=init - auto evt = generate_execve_enter_and_exit_event(0, p6_t1_tid, p6_t1_tid, p6_t1_pid, p6_t1_ptid, "/good-exe", "good-exe", "/good-exe"); + // proc.aname[0]=good-exe, proc.aname[1]=bash, proc.aname[2]=bash, proc.aname[3]=bash, + // proc.aname[4]=bash, proc.aname[5]=init + auto evt = generate_execve_enter_and_exit_event(0, + p6_t1_tid, + p6_t1_tid, + p6_t1_pid, + p6_t1_ptid, + "/good-exe", + "good-exe", + "/good-exe"); EXPECT_TRUE(eval_filter(evt, "proc.aname in (init)")); EXPECT_TRUE(eval_filter(evt, "proc.aname in (bash)")); @@ -125,44 +164,94 @@ TEST_F(sinsp_with_test_input, PROC_FILTER_aname) } #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(__APPLE__) -TEST_F(sinsp_with_test_input, PROC_FILTER_stdin_stdout_stderr) -{ +TEST_F(sinsp_with_test_input, PROC_FILTER_stdin_stdout_stderr) { DEFAULT_TREE sinsp_evt* evt = NULL; int64_t client_fd = 3, return_value = 0; int64_t stdin_fd = 0, stdout_fd = 1, stderr_fd = 2; // Create a connected socket - add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_E, 3, (uint32_t) PPM_AF_INET, (uint32_t) SOCK_STREAM, 0); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_INET, + (uint32_t)SOCK_STREAM, + 0); add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_SOCKET_X, 1, client_fd); - - sockaddr_in client = test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); - sockaddr_in server = test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); - - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_E, 2, client_fd, scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - - std::vector socktuple = test_utils::pack_socktuple(reinterpret_cast(&client), reinterpret_cast(&server)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SOCKET_CONNECT_X, 3, return_value, scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + sockaddr_in client = + test_utils::fill_sockaddr_in(DEFAULT_CLIENT_PORT, DEFAULT_IPV4_CLIENT_STRING); + + sockaddr_in server = + test_utils::fill_sockaddr_in(DEFAULT_SERVER_PORT, DEFAULT_IPV4_SERVER_STRING); + + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&server)); + evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_SOCKET_CONNECT_E, + 2, + client_fd, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + + std::vector socktuple = + test_utils::pack_socktuple(reinterpret_cast(&client), + reinterpret_cast(&server)); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); // The socket is duped to stdin, stdout, stderr evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP2_E, 1, client_fd); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP2_X, 3, stdin_fd, client_fd, stdin_fd); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_DUP2_X, + 3, + stdin_fd, + client_fd, + stdin_fd); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP2_E, 1, client_fd); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP2_X, 3, stdout_fd, client_fd, stdout_fd); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_DUP2_X, + 3, + stdout_fd, + client_fd, + stdout_fd); evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP2_E, 1, client_fd); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_DUP2_X, 3, stderr_fd, client_fd, stderr_fd); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_DUP2_X, + 3, + stderr_fd, + client_fd, + stderr_fd); // Exec a process and check stdin, stdout and stderr types and names - evt = generate_execve_enter_and_exit_event(0, 1, 1, 1, 1, "/proc_filter_stdin_stdout_stderr", "proc_filter_stdin_stdout_stderr", "/usr/bin/proc_filter_stdin_stdout_stderr"); + evt = generate_execve_enter_and_exit_event(0, + 1, + 1, + 1, + 1, + "/proc_filter_stdin_stdout_stderr", + "proc_filter_stdin_stdout_stderr", + "/usr/bin/proc_filter_stdin_stdout_stderr"); ASSERT_EQ(get_field_as_string(evt, "proc.stdin.type"), "ipv4"); ASSERT_EQ(get_field_as_string(evt, "proc.stdout.type"), "ipv4"); ASSERT_EQ(get_field_as_string(evt, "proc.stderr.type"), "ipv4"); - std::string tuple_str = std::string(DEFAULT_IPV4_CLIENT_STRING) + ":" + std::to_string(DEFAULT_CLIENT_PORT) + "->" + std::string(DEFAULT_IPV4_SERVER_STRING) + ":" + std::to_string(DEFAULT_SERVER_PORT); + std::string tuple_str = std::string(DEFAULT_IPV4_CLIENT_STRING) + ":" + + std::to_string(DEFAULT_CLIENT_PORT) + "->" + + std::string(DEFAULT_IPV4_SERVER_STRING) + ":" + + std::to_string(DEFAULT_SERVER_PORT); ASSERT_EQ(get_field_as_string(evt, "proc.stdin.name"), tuple_str); ASSERT_EQ(get_field_as_string(evt, "proc.stdout.name"), tuple_str); ASSERT_EQ(get_field_as_string(evt, "proc.stderr.name"), tuple_str); } -#endif \ No newline at end of file +#endif diff --git a/userspace/libsinsp/test/gvisor_config.ut.cpp b/userspace/libsinsp/test/gvisor_config.ut.cpp index c96223c954..6e4d9c1558 100644 --- a/userspace/libsinsp/test/gvisor_config.ut.cpp +++ b/userspace/libsinsp/test/gvisor_config.ut.cpp @@ -24,8 +24,7 @@ limitations under the License. #include #include -TEST(gvisor_config, generate_parse) -{ +TEST(gvisor_config, generate_parse) { std::string socket_path = "/run/falco/gvisor.sock"; std::string config = gvisor_config::generate(socket_path); Json::Value root; @@ -38,6 +37,7 @@ TEST(gvisor_config, generate_parse) EXPECT_TRUE(json_parse) << "Could not parse configuration file contents: " + err; // check that the sink is defined - // according to https://github.com/google/gvisor/blob/master/tools/tracereplay/README.md#how-to-use-it + // according to + // https://github.com/google/gvisor/blob/master/tools/tracereplay/README.md#how-to-use-it EXPECT_EQ(root["trace_session"]["sinks"][0]["config"]["endpoint"].asCString(), socket_path); } diff --git a/userspace/libsinsp/test/helpers/scap_file_helpers.cpp b/userspace/libsinsp/test/helpers/scap_file_helpers.cpp index 532690b5be..89dd43d944 100644 --- a/userspace/libsinsp/test/helpers/scap_file_helpers.cpp +++ b/userspace/libsinsp/test/helpers/scap_file_helpers.cpp @@ -18,37 +18,30 @@ limitations under the License. #include -namespace scap_file_test_helpers -{ +namespace scap_file_test_helpers { -sinsp_evt* capture_search_evt_by_num(sinsp* inspector, uint64_t evt_num) -{ +sinsp_evt* capture_search_evt_by_num(sinsp* inspector, uint64_t evt_num) { sinsp_evt* evt; int ret = SCAP_SUCCESS; - while(ret != SCAP_EOF) - { + while(ret != SCAP_EOF) { ret = inspector->next(&evt); - if(ret == SCAP_SUCCESS && evt->get_num() == evt_num) - { + if(ret == SCAP_SUCCESS && evt->get_num() == evt_num) { return evt; } } return NULL; } -sinsp_evt* capture_search_evt_by_type_and_tid(sinsp* inspector, uint64_t type, int64_t tid) -{ +sinsp_evt* capture_search_evt_by_type_and_tid(sinsp* inspector, uint64_t type, int64_t tid) { sinsp_evt* evt; int ret = SCAP_SUCCESS; - while(ret != SCAP_EOF) - { + while(ret != SCAP_EOF) { ret = inspector->next(&evt); - if(ret == SCAP_SUCCESS && evt->get_type() == type && evt->get_tid() == tid) - { + if(ret == SCAP_SUCCESS && evt->get_type() == type && evt->get_tid() == tid) { return evt; } } return NULL; } -} // namespace scap_file_test_helpers +} // namespace scap_file_test_helpers diff --git a/userspace/libsinsp/test/helpers/scap_file_helpers.h b/userspace/libsinsp/test/helpers/scap_file_helpers.h index 2618bc1dd5..dc40d0a36c 100644 --- a/userspace/libsinsp/test/helpers/scap_file_helpers.h +++ b/userspace/libsinsp/test/helpers/scap_file_helpers.h @@ -22,10 +22,9 @@ limitations under the License. #include #include -namespace scap_file_test_helpers -{ +namespace scap_file_test_helpers { sinsp_evt* capture_search_evt_by_num(sinsp* inspector, uint64_t evt_num); sinsp_evt* capture_search_evt_by_type_and_tid(sinsp* inspector, uint64_t type, int64_t tid); -} // namespace scap_file_test_helpers +} // namespace scap_file_test_helpers diff --git a/userspace/libsinsp/test/helpers/scoped_file_descriptor.cpp b/userspace/libsinsp/test/helpers/scoped_file_descriptor.cpp index 85f88f8a02..46dc56e6a8 100644 --- a/userspace/libsinsp/test/helpers/scoped_file_descriptor.cpp +++ b/userspace/libsinsp/test/helpers/scoped_file_descriptor.cpp @@ -24,27 +24,22 @@ limitations under the License. using namespace test_helpers; -scoped_file_descriptor::scoped_file_descriptor(const int fd) : m_fd(fd), m_closed(false) {} +scoped_file_descriptor::scoped_file_descriptor(const int fd): m_fd(fd), m_closed(false) {} -scoped_file_descriptor::~scoped_file_descriptor() -{ +scoped_file_descriptor::~scoped_file_descriptor() { close(); } -int scoped_file_descriptor::get_fd() const -{ +int scoped_file_descriptor::get_fd() const { return m_fd; } -bool scoped_file_descriptor::is_valid() const -{ +bool scoped_file_descriptor::is_valid() const { return m_fd >= 0; } -void scoped_file_descriptor::close() -{ - if (is_valid() && !m_closed) - { +void scoped_file_descriptor::close() { + if(is_valid() && !m_closed) { ::close(m_fd); m_fd = -1; } diff --git a/userspace/libsinsp/test/helpers/scoped_file_descriptor.h b/userspace/libsinsp/test/helpers/scoped_file_descriptor.h index 7e0ce24c07..c65cded277 100644 --- a/userspace/libsinsp/test/helpers/scoped_file_descriptor.h +++ b/userspace/libsinsp/test/helpers/scoped_file_descriptor.h @@ -18,15 +18,13 @@ limitations under the License. #pragma once -namespace test_helpers -{ +namespace test_helpers { /** * Wraps a file descriptor for the lifetime of the object, and closes the * file descriptor (if not already closed) when destroyed. */ -class scoped_file_descriptor -{ +class scoped_file_descriptor { public: scoped_file_descriptor(int fd); ~scoped_file_descriptor(); diff --git a/userspace/libsinsp/test/helpers/scoped_pipe.cpp b/userspace/libsinsp/test/helpers/scoped_pipe.cpp index fdbfd6ecd9..2a8caa715a 100644 --- a/userspace/libsinsp/test/helpers/scoped_pipe.cpp +++ b/userspace/libsinsp/test/helpers/scoped_pipe.cpp @@ -30,12 +30,10 @@ limitations under the License. using namespace test_helpers; -scoped_pipe::scoped_pipe() -{ +scoped_pipe::scoped_pipe() { int fds[2] = {}; - if (pipe(fds) < 0) - { + if(pipe(fds) < 0) { std::stringstream out; out << "scoped_pipe: Failed to create pipe, error: " << strerror(errno); @@ -47,18 +45,15 @@ scoped_pipe::scoped_pipe() m_write_end = std::make_unique(fds[1]); } -scoped_file_descriptor& scoped_pipe::read_end() -{ +scoped_file_descriptor& scoped_pipe::read_end() { return *m_read_end; } -scoped_file_descriptor& scoped_pipe::write_end() -{ +scoped_file_descriptor& scoped_pipe::write_end() { return *m_write_end; } -void scoped_pipe::close() -{ +void scoped_pipe::close() { m_read_end->close(); m_write_end->close(); } diff --git a/userspace/libsinsp/test/helpers/scoped_pipe.h b/userspace/libsinsp/test/helpers/scoped_pipe.h index 3757ecc4d6..4212414d34 100644 --- a/userspace/libsinsp/test/helpers/scoped_pipe.h +++ b/userspace/libsinsp/test/helpers/scoped_pipe.h @@ -20,8 +20,7 @@ limitations under the License. #include -namespace test_helpers -{ +namespace test_helpers { class scoped_file_descriptor; @@ -29,8 +28,7 @@ class scoped_file_descriptor; * A scoped_pipe wraps the pipe() system call and exposes two scoped file * descriptors corresponding to the read- and write-ends of the pipe. */ -class scoped_pipe -{ +class scoped_pipe { public: /** * Creates a new pipe and initializes this scoped_pipe with its diff --git a/userspace/libsinsp/test/helpers/threads_helpers.h b/userspace/libsinsp/test/helpers/threads_helpers.h index 1e5c84824a..173ddd31e2 100644 --- a/userspace/libsinsp/test/helpers/threads_helpers.h +++ b/userspace/libsinsp/test/helpers/threads_helpers.h @@ -22,124 +22,113 @@ limitations under the License. #define HUGE_THREAD_NUMBER 150 -#define ASSERT_THREAD_INFO_PIDS_IN_CONTAINER(tid, pid, ptid, vtid, vpid) \ - { \ - sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ - ASSERT_TRUE(tinfo); \ - ASSERT_EQ(tinfo->m_tid, tid); \ - ASSERT_EQ(tinfo->m_pid, pid); \ - ASSERT_EQ(tinfo->m_ptid, ptid); \ - ASSERT_EQ(tinfo->m_vtid, vtid); \ - ASSERT_EQ(tinfo->m_vpid, vpid); \ - ASSERT_EQ(tinfo->is_main_thread(), tinfo->m_tid == tinfo->m_pid); \ +#define ASSERT_THREAD_INFO_PIDS_IN_CONTAINER(tid, pid, ptid, vtid, vpid) \ + { \ + sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ + ASSERT_TRUE(tinfo); \ + ASSERT_EQ(tinfo->m_tid, tid); \ + ASSERT_EQ(tinfo->m_pid, pid); \ + ASSERT_EQ(tinfo->m_ptid, ptid); \ + ASSERT_EQ(tinfo->m_vtid, vtid); \ + ASSERT_EQ(tinfo->m_vpid, vpid); \ + ASSERT_EQ(tinfo->is_main_thread(), tinfo->m_tid == tinfo->m_pid); \ } -#define ASSERT_THREAD_INFO_PIDS(tid, pid, ppid) \ - { \ - ASSERT_THREAD_INFO_PIDS_IN_CONTAINER(tid, pid, ppid, tid, pid) \ - } +#define ASSERT_THREAD_INFO_PIDS(tid, pid, ppid) \ + {ASSERT_THREAD_INFO_PIDS_IN_CONTAINER(tid, pid, ppid, tid, pid)} -#define ASSERT_THREAD_GROUP_INFO(tg_pid, alive_threads, reaper_enabled, threads_num, not_expired, ...) \ - { \ - auto tginfo = m_inspector.m_thread_manager->get_thread_group_info(tg_pid).get(); \ - ASSERT_TRUE(tginfo); \ - ASSERT_EQ(tginfo->get_thread_count(), alive_threads); \ - ASSERT_EQ(tginfo->is_reaper(), reaper_enabled); \ - ASSERT_EQ(tginfo->get_tgroup_pid(), tg_pid); \ - ASSERT_EQ(tginfo->get_thread_list().size(), threads_num); \ - std::set tid_to_assert{__VA_ARGS__}; \ - for(const auto& tid : tid_to_assert) \ - { \ - sinsp_threadinfo* tid_tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ - ASSERT_TRUE(tid_tinfo); \ - ASSERT_EQ(tid_tinfo->m_pid, tg_pid) << "Thread '" + std::to_string(tid_tinfo->m_tid) + \ - "' doesn't belong to the thread group id '" + \ - std::to_string(tg_pid) + "'"; \ - bool found = false; \ - for(const auto& thread : tginfo->get_thread_list()) \ - { \ - if(thread.lock().get() == tid_tinfo) \ - { \ - found = true; \ - } \ - } \ - ASSERT_TRUE(found); \ - } \ - uint64_t not_expired_count = 0; \ - for(const auto& thread : tginfo->get_thread_list()) \ - { \ - if(!thread.expired()) \ - { \ - not_expired_count++; \ - } \ - } \ - ASSERT_EQ(not_expired_count, not_expired); \ +#define ASSERT_THREAD_GROUP_INFO(tg_pid, \ + alive_threads, \ + reaper_enabled, \ + threads_num, \ + not_expired, \ + ...) \ + { \ + auto tginfo = m_inspector.m_thread_manager->get_thread_group_info(tg_pid).get(); \ + ASSERT_TRUE(tginfo); \ + ASSERT_EQ(tginfo->get_thread_count(), alive_threads); \ + ASSERT_EQ(tginfo->is_reaper(), reaper_enabled); \ + ASSERT_EQ(tginfo->get_tgroup_pid(), tg_pid); \ + ASSERT_EQ(tginfo->get_thread_list().size(), threads_num); \ + std::set tid_to_assert{__VA_ARGS__}; \ + for(const auto& tid : tid_to_assert) { \ + sinsp_threadinfo* tid_tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ + ASSERT_TRUE(tid_tinfo); \ + ASSERT_EQ(tid_tinfo->m_pid, tg_pid) \ + << "Thread '" + std::to_string(tid_tinfo->m_tid) + \ + "' doesn't belong to the thread group id '" + \ + std::to_string(tg_pid) + "'"; \ + bool found = false; \ + for(const auto& thread : tginfo->get_thread_list()) { \ + if(thread.lock().get() == tid_tinfo) { \ + found = true; \ + } \ + } \ + ASSERT_TRUE(found); \ + } \ + uint64_t not_expired_count = 0; \ + for(const auto& thread : tginfo->get_thread_list()) { \ + if(!thread.expired()) { \ + not_expired_count++; \ + } \ + } \ + ASSERT_EQ(not_expired_count, not_expired); \ } -#define ASSERT_THREAD_CHILDREN(parent_tid, children_num, not_expired, ...) \ - { \ - sinsp_threadinfo* parent_tinfo = m_inspector.get_thread_ref(parent_tid, false, true).get(); \ - ASSERT_TRUE(parent_tinfo); \ - ASSERT_EQ(parent_tinfo->m_children.size(), children_num); \ - std::set tid_to_assert{__VA_ARGS__}; \ - for(const auto& tid : tid_to_assert) \ - { \ - sinsp_threadinfo* tid_tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ - ASSERT_TRUE(tid_tinfo); \ - bool found = false; \ - for(const auto& child : parent_tinfo->m_children) \ - { \ - if(child.lock().get() == tid_tinfo) \ - { \ - found = true; \ - } \ - } \ - ASSERT_TRUE(found); \ - } \ - uint16_t not_expired_count = 0; \ - for(const auto& child : parent_tinfo->m_children) \ - { \ - if(!child.expired()) \ - { \ - not_expired_count++; \ - } \ - } \ - ASSERT_EQ(not_expired_count, not_expired); \ - ASSERT_EQ(not_expired_count, parent_tinfo->m_not_expired_children); \ +#define ASSERT_THREAD_CHILDREN(parent_tid, children_num, not_expired, ...) \ + { \ + sinsp_threadinfo* parent_tinfo = \ + m_inspector.get_thread_ref(parent_tid, false, true).get(); \ + ASSERT_TRUE(parent_tinfo); \ + ASSERT_EQ(parent_tinfo->m_children.size(), children_num); \ + std::set tid_to_assert{__VA_ARGS__}; \ + for(const auto& tid : tid_to_assert) { \ + sinsp_threadinfo* tid_tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ + ASSERT_TRUE(tid_tinfo); \ + bool found = false; \ + for(const auto& child : parent_tinfo->m_children) { \ + if(child.lock().get() == tid_tinfo) { \ + found = true; \ + } \ + } \ + ASSERT_TRUE(found); \ + } \ + uint16_t not_expired_count = 0; \ + for(const auto& child : parent_tinfo->m_children) { \ + if(!child.expired()) { \ + not_expired_count++; \ + } \ + } \ + ASSERT_EQ(not_expired_count, not_expired); \ + ASSERT_EQ(not_expired_count, parent_tinfo->m_not_expired_children); \ } /* if `missing==true` we shouldn't find the thread info */ -#define ASSERT_MISSING_THREAD_INFO(tid_to_check, missing) \ - { \ - if(missing) \ - { \ - ASSERT_FALSE(m_inspector.get_thread_ref(tid_to_check, false)); \ - } \ - else \ - { \ - ASSERT_TRUE(m_inspector.get_thread_ref(tid_to_check, false)); \ - } \ +#define ASSERT_MISSING_THREAD_INFO(tid_to_check, missing) \ + { \ + if(missing) { \ + ASSERT_FALSE(m_inspector.get_thread_ref(tid_to_check, false)); \ + } else { \ + ASSERT_TRUE(m_inspector.get_thread_ref(tid_to_check, false)); \ + } \ } -#define ASSERT_THREAD_INFO_FLAG(tid, flag, present) \ - { \ - sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ - ASSERT_TRUE(tinfo); \ - if(present) \ - { \ - ASSERT_TRUE(tinfo->m_flags& flag); \ - } \ - else \ - { \ - ASSERT_FALSE(tinfo->m_flags& flag); \ - } \ +#define ASSERT_THREAD_INFO_FLAG(tid, flag, present) \ + { \ + sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(tid, false, true).get(); \ + ASSERT_TRUE(tinfo); \ + if(present) { \ + ASSERT_TRUE(tinfo->m_flags& flag); \ + } else { \ + ASSERT_FALSE(tinfo->m_flags& flag); \ + } \ } -#define ASSERT_THREAD_INFO_COMM(tid, comm) \ - { \ - sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(tid, false).get(); \ - ASSERT_TRUE(tinfo); \ - ASSERT_EQ(tinfo->m_comm, comm); \ +#define ASSERT_THREAD_INFO_COMM(tid, comm) \ + { \ + sinsp_threadinfo* tinfo = m_inspector.get_thread_ref(tid, false).get(); \ + ASSERT_TRUE(tinfo); \ + ASSERT_EQ(tinfo->m_comm, comm); \ } #define DEFAULT_TREE_NUM_PROCS 12 @@ -158,161 +147,191 @@ limitations under the License. * - (p_2 - t2) tid 23 pid 25 ptid 1 * - (p_2 - t3) tid 24 pid 25 ptid 1 */ -#define DEFAULT_TREE \ - add_default_init_thread(); \ - open_inspector(); \ - \ - /* Init process creates a child process */ \ - \ - /*=============================== p1_t1 ===========================*/ \ - \ - [[maybe_unused]] int64_t p1_t1_tid = 2; \ - [[maybe_unused]] int64_t p1_t1_pid = p1_t1_tid; \ - [[maybe_unused]] int64_t p1_t1_ptid = INIT_TID; \ - \ - /* Parent exit event */ \ - generate_clone_x_event(p1_t1_tid, INIT_TID, INIT_PID, INIT_PTID); \ - \ - /*=============================== p1_t1 ===========================*/ \ - \ - /* p1 process creates a second thread */ \ - \ - /*=============================== p1_t2 ===========================*/ \ - \ - [[maybe_unused]] int64_t p1_t2_tid = 6; \ - [[maybe_unused]] int64_t p1_t2_pid = p1_t1_pid; \ - [[maybe_unused]] int64_t p1_t2_ptid = INIT_TID; \ - \ - /* Parent exit event */ \ - generate_clone_x_event(p1_t2_tid, p1_t1_tid, p1_t1_pid, p1_t1_ptid, PPM_CL_CLONE_THREAD); \ - \ - /*=============================== p1_t2 ===========================*/ \ - \ - /* The second thread of p1 create a new process p2 */ \ - \ - /*=============================== p2_t1 ===========================*/ \ - \ - [[maybe_unused]] int64_t p2_t1_tid = 25; \ - [[maybe_unused]] int64_t p2_t1_pid = 25; \ - [[maybe_unused]] int64_t p2_t1_ptid = INIT_TID; \ - \ - /* Parent exit event */ \ - generate_clone_x_event(p2_t1_tid, p1_t2_tid, p1_t2_pid, p1_t2_ptid, PPM_CL_CLONE_PARENT); \ - /* Here we need also the child exit event because the caller doesn't generate*/ \ - /* the child thread info if we use the `PPM_CL_CLONE_PARENT` flag due to runc! */ \ - /* See the clone_parser code. */ \ - generate_clone_x_event(0, p2_t1_tid, p2_t1_pid, p2_t1_ptid, PPM_CL_CLONE_PARENT); \ - \ - /*=============================== p2_t1 ===========================*/ \ - \ - /* p2 process creates a second thread */ \ - \ - /*=============================== p2_t2 ===========================*/ \ - \ - [[maybe_unused]] int64_t p2_t2_tid = 23; \ - [[maybe_unused]] int64_t p2_t2_pid = p2_t1_pid; \ - [[maybe_unused]] int64_t p2_t2_ptid = INIT_TID; /* p2_t2 will have the same parent of p2_t1 */ \ - \ - /* Parent exit event */ \ - generate_clone_x_event(p2_t2_tid, p2_t1_tid, p2_t1_pid, p2_t1_ptid, PPM_CL_CLONE_THREAD); \ - \ - /*=============================== p2_t2 ===========================*/ \ - \ - /* p2_t2 creates a new thread p2_t3 */ \ - \ - /*=============================== p2_t3 ===========================*/ \ - \ - [[maybe_unused]] int64_t p2_t3_tid = 24; \ - [[maybe_unused]] int64_t p2_t3_pid = p2_t1_pid; \ - [[maybe_unused]] int64_t p2_t3_ptid = INIT_TID; \ - \ - /* Parent exit event */ \ - generate_clone_x_event(p2_t3_tid, p2_t2_tid, p2_t2_pid, p2_t2_ptid, PPM_CL_CLONE_THREAD); \ - \ - /*=============================== p2_t3 ===========================*/ \ - \ - /* The leader thread of p2 create a new process p3 */ \ - \ - /*=============================== p3_t1 ===========================*/ \ - \ - [[maybe_unused]] int64_t p3_t1_tid = 72; \ - [[maybe_unused]] int64_t p3_t1_pid = p3_t1_tid; \ - [[maybe_unused]] int64_t p3_t1_ptid = p2_t1_tid; \ - \ - /* Parent exit event */ \ - generate_clone_x_event(p3_t1_tid, p2_t1_tid, p2_t1_pid, p2_t1_ptid); \ - \ - /*=============================== p3_t1 ===========================*/ \ - \ - /* The leader thread of p3 create a new process p4 in a new container */ \ - \ - /*=============================== p4_t1 ===========================*/ \ - \ - [[maybe_unused]] int64_t p4_t1_tid = 76; \ - [[maybe_unused]] int64_t p4_t1_pid = p4_t1_tid; \ - [[maybe_unused]] int64_t p4_t1_ptid = p3_t1_tid; \ - [[maybe_unused]] int64_t p4_t1_vtid = 1; /* This process will be the `init` one in the new namespace */ \ - [[maybe_unused]] int64_t p4_t1_vpid = p4_t1_vtid; \ - \ - generate_clone_x_event(p4_t1_tid, p3_t1_tid, p3_t1_pid, p3_t1_ptid, PPM_CL_CLONE_NEWPID); \ - \ - /* Check fields after parent parsing \ - * Note: here we cannot assert anything because the child will be in a container \ - * and so the parent doesn't create the `thread-info` for the child. \ - */ \ - \ - /* Child exit event */ \ - /* On arm64 the flag `PPM_CL_CLONE_NEWPID` is not sent by the child, so we simulate the \ - * worst case */ \ - generate_clone_x_event(0, p4_t1_tid, p4_t1_pid, p4_t1_ptid, PPM_CL_CHILD_IN_PIDNS, p4_t1_vtid, p4_t1_vpid); \ - \ - /*=============================== p4_t1 ===========================*/ \ - \ - /*=============================== p4_t2 ===========================*/ \ - \ - [[maybe_unused]] int64_t p4_t2_tid = 79; \ - [[maybe_unused]] int64_t p4_t2_pid = p4_t1_pid; \ - [[maybe_unused]] int64_t p4_t2_ptid = p3_t1_tid; \ - [[maybe_unused]] int64_t p4_t2_vtid = 2; \ - [[maybe_unused]] int64_t p4_t2_vpid = p4_t1_vpid; \ - \ - generate_clone_x_event(0, p4_t2_tid, p4_t2_pid, p4_t2_ptid, PPM_CL_CLONE_THREAD | PPM_CL_CHILD_IN_PIDNS, \ - p4_t2_vtid, p4_t2_vpid); \ - \ - /*=============================== p4_t2 ===========================*/ \ - \ - /*=============================== p5_t1 ===========================*/ \ - \ - [[maybe_unused]] int64_t p5_t1_tid = 82; \ - [[maybe_unused]] int64_t p5_t1_pid = p5_t1_tid; \ - [[maybe_unused]] int64_t p5_t1_ptid = p4_t2_tid; \ - [[maybe_unused]] int64_t p5_t1_vtid = 10; \ - [[maybe_unused]] int64_t p5_t1_vpid = p5_t1_vtid; \ - \ - generate_clone_x_event(0, p5_t1_tid, p5_t1_pid, p5_t1_ptid, PPM_CL_CHILD_IN_PIDNS, p5_t1_vtid, p5_t1_vpid); \ - \ - /*=============================== p5_t1 ===========================*/ \ - \ - /*=============================== p5_t2 ===========================*/ \ - \ - [[maybe_unused]] int64_t p5_t2_tid = 84; \ - [[maybe_unused]] int64_t p5_t2_pid = p5_t1_pid; \ - [[maybe_unused]] int64_t p5_t2_ptid = p4_t2_tid; \ - [[maybe_unused]] int64_t p5_t2_vtid = 12; \ - [[maybe_unused]] int64_t p5_t2_vpid = p5_t1_vpid; \ - \ - generate_clone_x_event(0, p5_t2_tid, p5_t2_pid, p5_t2_ptid, PPM_CL_CHILD_IN_PIDNS, p5_t2_vtid, p5_t2_vpid); \ - \ - /*=============================== p5_t2 ===========================*/ \ - \ - /*=============================== p6_t1 ===========================*/ \ - \ - [[maybe_unused]] int64_t p6_t1_tid = 87; \ - [[maybe_unused]] int64_t p6_t1_pid = p6_t1_tid; \ - [[maybe_unused]] int64_t p6_t1_ptid = p5_t2_tid; \ - [[maybe_unused]] int64_t p6_t1_vtid = 17; \ - [[maybe_unused]] int64_t p6_t1_vpid = p6_t1_vtid; \ - \ - generate_clone_x_event(0, p6_t1_tid, p6_t1_pid, p6_t1_ptid, PPM_CL_CHILD_IN_PIDNS, p6_t1_vtid, p6_t1_vpid); \ - \ +#define DEFAULT_TREE \ + add_default_init_thread(); \ + open_inspector(); \ + \ + /* Init process creates a child process */ \ + \ + /*=============================== p1_t1 ===========================*/ \ + \ + [[maybe_unused]] int64_t p1_t1_tid = 2; \ + [[maybe_unused]] int64_t p1_t1_pid = p1_t1_tid; \ + [[maybe_unused]] int64_t p1_t1_ptid = INIT_TID; \ + \ + /* Parent exit event */ \ + generate_clone_x_event(p1_t1_tid, INIT_TID, INIT_PID, INIT_PTID); \ + \ + /*=============================== p1_t1 ===========================*/ \ + \ + /* p1 process creates a second thread */ \ + \ + /*=============================== p1_t2 ===========================*/ \ + \ + [[maybe_unused]] int64_t p1_t2_tid = 6; \ + [[maybe_unused]] int64_t p1_t2_pid = p1_t1_pid; \ + [[maybe_unused]] int64_t p1_t2_ptid = INIT_TID; \ + \ + /* Parent exit event */ \ + generate_clone_x_event(p1_t2_tid, p1_t1_tid, p1_t1_pid, p1_t1_ptid, PPM_CL_CLONE_THREAD); \ + \ + /*=============================== p1_t2 ===========================*/ \ + \ + /* The second thread of p1 create a new process p2 */ \ + \ + /*=============================== p2_t1 ===========================*/ \ + \ + [[maybe_unused]] int64_t p2_t1_tid = 25; \ + [[maybe_unused]] int64_t p2_t1_pid = 25; \ + [[maybe_unused]] int64_t p2_t1_ptid = INIT_TID; \ + \ + /* Parent exit event */ \ + generate_clone_x_event(p2_t1_tid, p1_t2_tid, p1_t2_pid, p1_t2_ptid, PPM_CL_CLONE_PARENT); \ + /* Here we need also the child exit event because the caller doesn't generate*/ \ + /* the child thread info if we use the `PPM_CL_CLONE_PARENT` flag due to runc! */ \ + /* See the clone_parser code. */ \ + generate_clone_x_event(0, p2_t1_tid, p2_t1_pid, p2_t1_ptid, PPM_CL_CLONE_PARENT); \ + \ + /*=============================== p2_t1 ===========================*/ \ + \ + /* p2 process creates a second thread */ \ + \ + /*=============================== p2_t2 ===========================*/ \ + \ + [[maybe_unused]] int64_t p2_t2_tid = 23; \ + [[maybe_unused]] int64_t p2_t2_pid = p2_t1_pid; \ + [[maybe_unused]] int64_t p2_t2_ptid = INIT_TID; /* p2_t2 will have the same parent of p2_t1 */ \ + \ + /* Parent exit event */ \ + generate_clone_x_event(p2_t2_tid, p2_t1_tid, p2_t1_pid, p2_t1_ptid, PPM_CL_CLONE_THREAD); \ + \ + /*=============================== p2_t2 ===========================*/ \ + \ + /* p2_t2 creates a new thread p2_t3 */ \ + \ + /*=============================== p2_t3 ===========================*/ \ + \ + [[maybe_unused]] int64_t p2_t3_tid = 24; \ + [[maybe_unused]] int64_t p2_t3_pid = p2_t1_pid; \ + [[maybe_unused]] int64_t p2_t3_ptid = INIT_TID; \ + \ + /* Parent exit event */ \ + generate_clone_x_event(p2_t3_tid, p2_t2_tid, p2_t2_pid, p2_t2_ptid, PPM_CL_CLONE_THREAD); \ + \ + /*=============================== p2_t3 ===========================*/ \ + \ + /* The leader thread of p2 create a new process p3 */ \ + \ + /*=============================== p3_t1 ===========================*/ \ + \ + [[maybe_unused]] int64_t p3_t1_tid = 72; \ + [[maybe_unused]] int64_t p3_t1_pid = p3_t1_tid; \ + [[maybe_unused]] int64_t p3_t1_ptid = p2_t1_tid; \ + \ + /* Parent exit event */ \ + generate_clone_x_event(p3_t1_tid, p2_t1_tid, p2_t1_pid, p2_t1_ptid); \ + \ + /*=============================== p3_t1 ===========================*/ \ + \ + /* The leader thread of p3 create a new process p4 in a new container */ \ + \ + /*=============================== p4_t1 ===========================*/ \ + \ + [[maybe_unused]] int64_t p4_t1_tid = 76; \ + [[maybe_unused]] int64_t p4_t1_pid = p4_t1_tid; \ + [[maybe_unused]] int64_t p4_t1_ptid = p3_t1_tid; \ + [[maybe_unused]] int64_t p4_t1_vtid = \ + 1; /* This process will be the `init` one in the new namespace */ \ + [[maybe_unused]] int64_t p4_t1_vpid = p4_t1_vtid; \ + \ + generate_clone_x_event(p4_t1_tid, p3_t1_tid, p3_t1_pid, p3_t1_ptid, PPM_CL_CLONE_NEWPID); \ + \ + /* Check fields after parent parsing \ + * Note: here we cannot assert anything because the child will be in a container \ + * and so the parent doesn't create the `thread-info` for the child. \ + */ \ + \ + /* Child exit event */ \ + /* On arm64 the flag `PPM_CL_CLONE_NEWPID` is not sent by the child, so we simulate the \ + * worst case */ \ + generate_clone_x_event(0, \ + p4_t1_tid, \ + p4_t1_pid, \ + p4_t1_ptid, \ + PPM_CL_CHILD_IN_PIDNS, \ + p4_t1_vtid, \ + p4_t1_vpid); \ + \ + /*=============================== p4_t1 ===========================*/ \ + \ + /*=============================== p4_t2 ===========================*/ \ + \ + [[maybe_unused]] int64_t p4_t2_tid = 79; \ + [[maybe_unused]] int64_t p4_t2_pid = p4_t1_pid; \ + [[maybe_unused]] int64_t p4_t2_ptid = p3_t1_tid; \ + [[maybe_unused]] int64_t p4_t2_vtid = 2; \ + [[maybe_unused]] int64_t p4_t2_vpid = p4_t1_vpid; \ + \ + generate_clone_x_event(0, \ + p4_t2_tid, \ + p4_t2_pid, \ + p4_t2_ptid, \ + PPM_CL_CLONE_THREAD | PPM_CL_CHILD_IN_PIDNS, \ + p4_t2_vtid, \ + p4_t2_vpid); \ + \ + /*=============================== p4_t2 ===========================*/ \ + \ + /*=============================== p5_t1 ===========================*/ \ + \ + [[maybe_unused]] int64_t p5_t1_tid = 82; \ + [[maybe_unused]] int64_t p5_t1_pid = p5_t1_tid; \ + [[maybe_unused]] int64_t p5_t1_ptid = p4_t2_tid; \ + [[maybe_unused]] int64_t p5_t1_vtid = 10; \ + [[maybe_unused]] int64_t p5_t1_vpid = p5_t1_vtid; \ + \ + generate_clone_x_event(0, \ + p5_t1_tid, \ + p5_t1_pid, \ + p5_t1_ptid, \ + PPM_CL_CHILD_IN_PIDNS, \ + p5_t1_vtid, \ + p5_t1_vpid); \ + \ + /*=============================== p5_t1 ===========================*/ \ + \ + /*=============================== p5_t2 ===========================*/ \ + \ + [[maybe_unused]] int64_t p5_t2_tid = 84; \ + [[maybe_unused]] int64_t p5_t2_pid = p5_t1_pid; \ + [[maybe_unused]] int64_t p5_t2_ptid = p4_t2_tid; \ + [[maybe_unused]] int64_t p5_t2_vtid = 12; \ + [[maybe_unused]] int64_t p5_t2_vpid = p5_t1_vpid; \ + \ + generate_clone_x_event(0, \ + p5_t2_tid, \ + p5_t2_pid, \ + p5_t2_ptid, \ + PPM_CL_CHILD_IN_PIDNS, \ + p5_t2_vtid, \ + p5_t2_vpid); \ + \ + /*=============================== p5_t2 ===========================*/ \ + \ + /*=============================== p6_t1 ===========================*/ \ + \ + [[maybe_unused]] int64_t p6_t1_tid = 87; \ + [[maybe_unused]] int64_t p6_t1_pid = p6_t1_tid; \ + [[maybe_unused]] int64_t p6_t1_ptid = p5_t2_tid; \ + [[maybe_unused]] int64_t p6_t1_vtid = 17; \ + [[maybe_unused]] int64_t p6_t1_vpid = p6_t1_vtid; \ + \ + generate_clone_x_event(0, \ + p6_t1_tid, \ + p6_t1_pid, \ + p6_t1_ptid, \ + PPM_CL_CHILD_IN_PIDNS, \ + p6_t1_vtid, \ + p6_t1_vpid); \ + \ /*=============================== p6_t1 ===========================*/ diff --git a/userspace/libsinsp/test/ifinfo.ut.cpp b/userspace/libsinsp/test/ifinfo.ut.cpp index 8b197347ee..7b5cd65e3a 100644 --- a/userspace/libsinsp/test/ifinfo.ut.cpp +++ b/userspace/libsinsp/test/ifinfo.ut.cpp @@ -22,8 +22,7 @@ limitations under the License. #include -static uint32_t parse_ipv4_addr(const char *dotted_notation) -{ +static uint32_t parse_ipv4_addr(const char *dotted_notation) { uint32_t a, b, c, d; sscanf(dotted_notation, "%d.%d.%d.%d", &a, &b, &c, &d); #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ @@ -33,70 +32,63 @@ static uint32_t parse_ipv4_addr(const char *dotted_notation) #endif } -static uint32_t parse_ipv4_netmask(const char *dotted_notation) -{ +static uint32_t parse_ipv4_netmask(const char *dotted_notation) { return parse_ipv4_addr(dotted_notation); } -static uint32_t parse_ipv4_broadcast(const char *dotted_notation) -{ +static uint32_t parse_ipv4_broadcast(const char *dotted_notation) { return parse_ipv4_addr(dotted_notation); } -static sinsp_ipv4_ifinfo make_ipv4_interface(const char *addr, const char *netmask, const char* broadcast, const char *name) -{ - return sinsp_ipv4_ifinfo( - parse_ipv4_addr(addr), - parse_ipv4_netmask(netmask), - parse_ipv4_broadcast(broadcast), - name); +static sinsp_ipv4_ifinfo make_ipv4_interface(const char *addr, + const char *netmask, + const char *broadcast, + const char *name) { + return sinsp_ipv4_ifinfo(parse_ipv4_addr(addr), + parse_ipv4_netmask(netmask), + parse_ipv4_broadcast(broadcast), + name); } -static sinsp_ipv4_ifinfo make_ipv4_localhost() -{ +static sinsp_ipv4_ifinfo make_ipv4_localhost() { return make_ipv4_interface("127.0.0.1", "255.0.0.0", "127.0.0.1", "lo"); } - -static void convert_to_string(char* dest, size_t len, uint32_t addr) -{ +static void convert_to_string(char *dest, size_t len, uint32_t addr) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ - snprintf( - dest, - len, - "%d.%d.%d.%d", - (addr & 0xFF), - ((addr & 0xFF00) >> 8), - ((addr & 0xFF0000) >> 16), - ((addr & 0xFF000000) >> 24)); + snprintf(dest, + len, + "%d.%d.%d.%d", + (addr & 0xFF), + ((addr & 0xFF00) >> 8), + ((addr & 0xFF0000) >> 16), + ((addr & 0xFF000000) >> 24)); #else - snprintf( - dest, - len, - "%d.%d.%d.%d", - ((addr >> 24) & 0xFF), - ((addr >> 16) & 0xFF), - ((addr >> 8) & 0xFF), - (addr & 0xFF)); + snprintf(dest, + len, + "%d.%d.%d.%d", + ((addr >> 24) & 0xFF), + ((addr >> 16) & 0xFF), + ((addr >> 8) & 0xFF), + (addr & 0xFF)); #endif } -#define EXPECT_ADDR_EQ(dotted_notation,addr) {\ - char buf[17];\ - convert_to_string(buf, sizeof(buf), addr);\ - EXPECT_STREQ(dotted_notation,buf);\ -}; +#define EXPECT_ADDR_EQ(dotted_notation, addr) \ + { \ + char buf[17]; \ + convert_to_string(buf, sizeof(buf), addr); \ + EXPECT_STREQ(dotted_notation, buf); \ + }; -TEST(sinsp_network_interfaces, fd_is_of_wrong_type) -{ +TEST(sinsp_network_interfaces, fd_is_of_wrong_type) { sinsp_fdinfo fd; fd.m_type = SCAP_FD_UNKNOWN; sinsp_network_interfaces interfaces; interfaces.update_fd(fd); } -TEST(sinsp_network_interfaces, socket_is_of_wrong_type) -{ +TEST(sinsp_network_interfaces, socket_is_of_wrong_type) { sinsp_fdinfo fd; fd.m_type = SCAP_FD_IPV4_SOCK; fd.m_sockinfo.m_ipv4info.m_fields.m_l4proto = SCAP_L4_TCP; @@ -104,8 +96,7 @@ TEST(sinsp_network_interfaces, socket_is_of_wrong_type) interfaces.update_fd(fd); } -TEST(sinsp_network_interfaces, sip_and_dip_are_not_zero) -{ +TEST(sinsp_network_interfaces, sip_and_dip_are_not_zero) { sinsp_fdinfo fd; fd.m_type = SCAP_FD_IPV4_SOCK; fd.m_sockinfo.m_ipv4info.m_fields.m_l4proto = SCAP_L4_UDP; @@ -115,43 +106,45 @@ TEST(sinsp_network_interfaces, sip_and_dip_are_not_zero) interfaces.update_fd(fd); } -TEST(sinsp_network_interfaces, infer_finds_exact_match) -{ +TEST(sinsp_network_interfaces, infer_finds_exact_match) { sinsp_network_interfaces interfaces; interfaces.get_ipv4_list()->push_back(make_ipv4_localhost()); - interfaces.get_ipv4_list()->push_back(make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0")); - EXPECT_ADDR_EQ("127.0.0.1",interfaces.infer_ipv4_address(parse_ipv4_addr("127.0.0.1"))); - EXPECT_ADDR_EQ("192.168.22.149",interfaces.infer_ipv4_address(parse_ipv4_addr("192.168.22.149"))); + interfaces.get_ipv4_list()->push_back( + make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0")); + EXPECT_ADDR_EQ("127.0.0.1", interfaces.infer_ipv4_address(parse_ipv4_addr("127.0.0.1"))); + EXPECT_ADDR_EQ("192.168.22.149", + interfaces.infer_ipv4_address(parse_ipv4_addr("192.168.22.149"))); } -TEST(sinsp_network_interfaces, infer_finds_same_subnet) -{ +TEST(sinsp_network_interfaces, infer_finds_same_subnet) { sinsp_network_interfaces interfaces; interfaces.get_ipv4_list()->push_back(make_ipv4_localhost()); - interfaces.get_ipv4_list()->push_back(make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0")); - EXPECT_ADDR_EQ("192.168.22.149",interfaces.infer_ipv4_address(parse_ipv4_addr("192.168.22.11"))); + interfaces.get_ipv4_list()->push_back( + make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0")); + EXPECT_ADDR_EQ("192.168.22.149", + interfaces.infer_ipv4_address(parse_ipv4_addr("192.168.22.11"))); } -TEST(sinsp_network_interfaces, infer_defaults_to_first_non_loopback) -{ +TEST(sinsp_network_interfaces, infer_defaults_to_first_non_loopback) { sinsp_network_interfaces interfaces; interfaces.get_ipv4_list()->push_back(make_ipv4_localhost()); - interfaces.get_ipv4_list()->push_back(make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0")); - interfaces.get_ipv4_list()->push_back(make_ipv4_interface("192.168.22.150", "255.255.255.0", "192.168.22.255", "eth1")); - EXPECT_ADDR_EQ("192.168.22.149",interfaces.infer_ipv4_address(parse_ipv4_addr("193.168.22.11"))); + interfaces.get_ipv4_list()->push_back( + make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0")); + interfaces.get_ipv4_list()->push_back( + make_ipv4_interface("192.168.22.150", "255.255.255.0", "192.168.22.255", "eth1")); + EXPECT_ADDR_EQ("192.168.22.149", + interfaces.infer_ipv4_address(parse_ipv4_addr("193.168.22.11"))); } -TEST(sinsp_network_interfaces, ipv4_addr_to_string) -{ - std::vector> ipv4_test_cases = - { - {make_ipv4_localhost(), "127.0.0.1"}, - {make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0"), "192.168.22.149"}, - {make_ipv4_interface("192.168.22.150", "255.255.255.0", "192.168.22.255", "eth1"), "192.168.22.150"} - }; +TEST(sinsp_network_interfaces, ipv4_addr_to_string) { + std::vector> ipv4_test_cases = { + {make_ipv4_localhost(), "127.0.0.1"}, + {make_ipv4_interface("192.168.22.149", "255.255.255.0", "192.168.22.255", "eth0"), + "192.168.22.149"}, + {make_ipv4_interface("192.168.22.150", "255.255.255.0", "192.168.22.255", "eth1"), + "192.168.22.150"}}; - for (const auto& ipv4_test_case : ipv4_test_cases) - { + for(const auto &ipv4_test_case : ipv4_test_cases) { std::string ip_str = ipv4_test_case.first.addr_to_string(ipv4_test_case.first.m_addr); ASSERT_EQ(ip_str, ipv4_test_case.second); ip_str = ipv4_test_case.first.addr_to_string(); @@ -159,20 +152,18 @@ TEST(sinsp_network_interfaces, ipv4_addr_to_string) } } -TEST(sinsp_network_interfaces, ipv6_addr_to_string) -{ +TEST(sinsp_network_interfaces, ipv6_addr_to_string) { sinsp_ipv6_ifinfo ifinfo; - std::vector> ipv6_test_cases = - { - {ipv6addr("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), "2001:db8:85a3:0:0:8a2e:370:7334"}, - {ipv6addr("fe80:0:0:0:2aa:ff:fe9a:4ca3"), "fe80:0:0:0:2aa:ff:fe9a:4ca3"}, - {ipv6addr("0:0:0:0:0:0:0:0"), "0:0:0:0:0:0:0:0"}, - {ipv6addr("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"} - }; + std::vector> ipv6_test_cases = { + {ipv6addr("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), + "2001:db8:85a3:0:0:8a2e:370:7334"}, + {ipv6addr("fe80:0:0:0:2aa:ff:fe9a:4ca3"), "fe80:0:0:0:2aa:ff:fe9a:4ca3"}, + {ipv6addr("0:0:0:0:0:0:0:0"), "0:0:0:0:0:0:0:0"}, + {ipv6addr("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"}}; - for (const auto& ipv6_test_case : ipv6_test_cases) - { + for(const auto &ipv6_test_case : ipv6_test_cases) { ifinfo.m_net = ipv6_test_case.first; std::string addr_str = ifinfo.addr_to_string(); ASSERT_EQ(addr_str, ipv6_test_case.second); diff --git a/userspace/libsinsp/test/mpsc_priority_queue.ut.cpp b/userspace/libsinsp/test/mpsc_priority_queue.ut.cpp index b0c59fb953..0cc59ad170 100644 --- a/userspace/libsinsp/test/mpsc_priority_queue.ut.cpp +++ b/userspace/libsinsp/test/mpsc_priority_queue.ut.cpp @@ -21,189 +21,159 @@ limitations under the License. #include #include -TEST(mpsc_priority_queue, order_consistency) -{ - struct val - { - int v; - int order; - }; - - struct val_less - { - bool operator()(const val& l, const val& r) - { - return std::greater_equal{}(l.v, r.v); - } - }; - - using val_t = std::unique_ptr; - - mpsc_priority_queue q; - for (int i = 0; i < 100; i++) - { - for (int j = 0; j < 100; j++) - { - // j is used only for tracking the order in which elements - // are pushed for checking it later - q.push(val_t{new val{i,j}}); - } - } - - val_t cur{nullptr}; - val_t prev{nullptr}; - while (!q.empty()) - { - ASSERT_TRUE(q.try_pop(cur)); - if (prev != nullptr) - { - ASSERT_GE(cur->v, prev->v); - if (cur->v == prev->v) - { - ASSERT_GT(cur->order, prev->order); - } - } - prev = std::move(cur); - } - +TEST(mpsc_priority_queue, order_consistency) { + struct val { + int v; + int order; + }; + + struct val_less { + bool operator()(const val& l, const val& r) { return std::greater_equal{}(l.v, r.v); } + }; + + using val_t = std::unique_ptr; + + mpsc_priority_queue q; + for(int i = 0; i < 100; i++) { + for(int j = 0; j < 100; j++) { + // j is used only for tracking the order in which elements + // are pushed for checking it later + q.push(val_t{new val{i, j}}); + } + } + + val_t cur{nullptr}; + val_t prev{nullptr}; + while(!q.empty()) { + ASSERT_TRUE(q.try_pop(cur)); + if(prev != nullptr) { + ASSERT_GE(cur->v, prev->v); + if(cur->v == prev->v) { + ASSERT_GT(cur->order, prev->order); + } + } + prev = std::move(cur); + } } // note: emscripten does not support launching threads #ifndef __EMSCRIPTEN__ -TEST(mpsc_priority_queue, single_concurrent_producer) -{ - using val_t = std::unique_ptr; - const int max_value = 1000; - - mpsc_priority_queue> q; - - // single producer - auto p = std::thread([&](){ - for (int i = 0; i < max_value; i++) - { - std::this_thread::sleep_for(std::chrono::microseconds(100)); - q.push(std::make_unique(i)); - } - }); - - // single consumer - val_t v; - int i = 0; - int failed = 0; - while (i < max_value) - { - std::this_thread::sleep_for(std::chrono::microseconds(100)); - if (q.empty()) - { - continue; - } - - if (!q.try_pop(v)) - { - failed++; - continue; - } - - failed += (*v != i) ? 1 : 0; - i++; - } - - // wait for producer to stop - p.join(); - - // check we received everything in order - ASSERT_EQ(failed, 0); +TEST(mpsc_priority_queue, single_concurrent_producer) { + using val_t = std::unique_ptr; + const int max_value = 1000; + + mpsc_priority_queue> q; + + // single producer + auto p = std::thread([&]() { + for(int i = 0; i < max_value; i++) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + q.push(std::make_unique(i)); + } + }); + + // single consumer + val_t v; + int i = 0; + int failed = 0; + while(i < max_value) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + if(q.empty()) { + continue; + } + + if(!q.try_pop(v)) { + failed++; + continue; + } + + failed += (*v != i) ? 1 : 0; + i++; + } + + // wait for producer to stop + p.join(); + + // check we received everything in order + ASSERT_EQ(failed, 0); } #if defined(__x86_64__) -TEST(mpsc_priority_queue, multi_concurrent_producers) -{ - using val_t = std::unique_ptr; - const constexpr int64_t timeout_secs = 30; - const constexpr int num_values = 100; - const constexpr int num_producers = 10; - const constexpr int num_total_elems = num_values * num_producers; - - mpsc_priority_queue> q; - std::atomic counter{1}; - - // multiple producer - std::vector producers; - for (int i = 0; i < num_producers; i++) - { - producers.emplace_back([&](){ - for (int i = 0; i <= num_values; i++) - { - std::this_thread::sleep_for(std::chrono::microseconds(100)); - q.push(std::make_unique(counter++)); - } - }); - } - - // single consumer - val_t v; - int i = 0; - int failed = 0; - int last_val = 0; - int64_t elapsed_secs = 0; - auto start = std::chrono::steady_clock::now(); - while (i < num_total_elems) - { - auto now = std::chrono::steady_clock::now(); - elapsed_secs = std::chrono::duration_cast(now - start).count(); - if (elapsed_secs >= timeout_secs) - { - break; - } - - std::this_thread::sleep_for(std::chrono::microseconds(100)); - if (q.empty()) - { - continue; - } - - if (!q.try_pop_if(v, [&](const int& n) { return n >= last_val; })) - { - failed++; - } - - last_val = *v; - i++; - } - - // wait for producers to stop - bool all_joinable = false; - while (!all_joinable) - { - all_joinable = true; - for (int j = 0; j < num_producers; j++) - { - if (!producers[j].joinable()) - { - all_joinable = false; - break; - } - } - } - for (int j = 0; j < num_producers; j++) - { - producers[j].join(); - } - - if (elapsed_secs >= timeout_secs) - { - FAIL() << "timout expired, test stopped after " - << elapsed_secs << " seconds. Received " - << i << "/" << num_total_elems << " elements, of which " - << failed << " out of order" << std::endl; - } - - // check we received everything in order - ASSERT_EQ(failed, 0) << "received " << failed << " elements out of order"; +TEST(mpsc_priority_queue, multi_concurrent_producers) { + using val_t = std::unique_ptr; + const constexpr int64_t timeout_secs = 30; + const constexpr int num_values = 100; + const constexpr int num_producers = 10; + const constexpr int num_total_elems = num_values * num_producers; + + mpsc_priority_queue> q; + std::atomic counter{1}; + + // multiple producer + std::vector producers; + for(int i = 0; i < num_producers; i++) { + producers.emplace_back([&]() { + for(int i = 0; i <= num_values; i++) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + q.push(std::make_unique(counter++)); + } + }); + } + + // single consumer + val_t v; + int i = 0; + int failed = 0; + int last_val = 0; + int64_t elapsed_secs = 0; + auto start = std::chrono::steady_clock::now(); + while(i < num_total_elems) { + auto now = std::chrono::steady_clock::now(); + elapsed_secs = std::chrono::duration_cast(now - start).count(); + if(elapsed_secs >= timeout_secs) { + break; + } + + std::this_thread::sleep_for(std::chrono::microseconds(100)); + if(q.empty()) { + continue; + } + + if(!q.try_pop_if(v, [&](const int& n) { return n >= last_val; })) { + failed++; + } + + last_val = *v; + i++; + } + + // wait for producers to stop + bool all_joinable = false; + while(!all_joinable) { + all_joinable = true; + for(int j = 0; j < num_producers; j++) { + if(!producers[j].joinable()) { + all_joinable = false; + break; + } + } + } + for(int j = 0; j < num_producers; j++) { + producers[j].join(); + } + + if(elapsed_secs >= timeout_secs) { + FAIL() << "timout expired, test stopped after " << elapsed_secs << " seconds. Received " + << i << "/" << num_total_elems << " elements, of which " << failed << " out of order" + << std::endl; + } + + // check we received everything in order + ASSERT_EQ(failed, 0) << "received " << failed << " elements out of order"; } -#endif // __x86_64__ +#endif // __x86_64__ -#endif // __EMSCRIPTEN__ +#endif // __EMSCRIPTEN__ diff --git a/userspace/libsinsp/test/parsers/parse_clone.cpp b/userspace/libsinsp/test/parsers/parse_clone.cpp index 070496cc3b..e7c6653284 100644 --- a/userspace/libsinsp/test/parsers/parse_clone.cpp +++ b/userspace/libsinsp/test/parsers/parse_clone.cpp @@ -20,8 +20,7 @@ limitations under the License. /*=============================== CLONE CALLER EXIT EVENT ===========================*/ -TEST_F(sinsp_with_test_input, CLONE_CALLER_failed) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_failed) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -42,8 +41,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_failed) ASSERT_FALSE(p1_t1_tinfo); } -TEST_F(sinsp_with_test_input, CLONE_CALLER_in_container) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_in_container) { add_default_init_thread(); open_inspector(); @@ -61,8 +59,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_in_container) ASSERT_FALSE(p1_t1_tinfo); } -TEST_F(sinsp_with_test_input, CLONE_CALLER_tid_collision) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_tid_collision) { add_default_init_thread(); open_inspector(); @@ -73,9 +70,16 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_tid_collision) int64_t p1_t1_pid = 24; int64_t p1_t1_ptid = INIT_PID; - /* Child clone exit event, we set a comm to understand if the final thread_info is overwritten or no */ - generate_clone_x_event(0, p1_t1_tid, p1_t1_pid, p1_t1_ptid, DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE, - "old_bash"); + /* Child clone exit event, we set a comm to understand if the final thread_info is overwritten + * or no */ + generate_clone_x_event(0, + p1_t1_tid, + p1_t1_pid, + p1_t1_ptid, + DEFAULT_VALUE, + DEFAULT_VALUE, + DEFAULT_VALUE, + "old_bash"); sinsp_threadinfo* p1_t1_tinfo = m_inspector.get_thread_ref(p1_t1_tid, false, true).get(); ASSERT_TRUE(p1_t1_tinfo); @@ -88,8 +92,14 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_tid_collision) /* The parent considers the existing child entry stale and removes it. * It will populate a new thread info */ - generate_clone_x_event(p1_t1_tid, INIT_TID, INIT_PID, INIT_PTID, DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE, - "new_bash"); + generate_clone_x_event(p1_t1_tid, + INIT_TID, + INIT_PID, + INIT_PTID, + DEFAULT_VALUE, + DEFAULT_VALUE, + DEFAULT_VALUE, + "new_bash"); p1_t1_tinfo = m_inspector.get_thread_ref(p1_t1_tid, false, true).get(); ASSERT_TRUE(p1_t1_tinfo); @@ -97,8 +107,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_tid_collision) ASSERT_EQ(p1_t1_tinfo->m_comm, "new_bash"); } -TEST_F(sinsp_with_test_input, CLONE_CALLER_keep_existing_child) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_keep_existing_child) { add_default_init_thread(); open_inspector(); @@ -110,24 +119,35 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_keep_existing_child) int64_t p1_t1_ptid = INIT_PID; /* Child clone exit event */ - generate_clone_x_event(0, p1_t1_tid, p1_t1_pid, p1_t1_ptid, DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE, - "old_bash"); + generate_clone_x_event(0, + p1_t1_tid, + p1_t1_pid, + p1_t1_ptid, + DEFAULT_VALUE, + DEFAULT_VALUE, + DEFAULT_VALUE, + "old_bash"); sinsp_threadinfo* p1_t1_tinfo = m_inspector.get_thread_ref(p1_t1_tid, false, true).get(); ASSERT_TRUE(p1_t1_tinfo); ASSERT_EQ(p1_t1_tinfo->m_comm, "old_bash"); /* Parent clone exit event */ - generate_clone_x_event(p1_t1_tid, INIT_TID, INIT_PID, INIT_PTID, DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE, - "new_bash"); + generate_clone_x_event(p1_t1_tid, + INIT_TID, + INIT_PID, + INIT_PTID, + DEFAULT_VALUE, + DEFAULT_VALUE, + DEFAULT_VALUE, + "new_bash"); p1_t1_tinfo = m_inspector.get_thread_ref(p1_t1_tid, false, true).get(); ASSERT_TRUE(p1_t1_tinfo); ASSERT_EQ(p1_t1_tinfo->m_comm, "old_bash"); } -TEST_F(sinsp_with_test_input, CLONE_CALLER_new_main_thread) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_new_main_thread) { add_default_init_thread(); open_inspector(); @@ -148,8 +168,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_new_main_thread) ASSERT_THREAD_CHILDREN(INIT_TID, 1, 1, p1_t1_tid) } -TEST_F(sinsp_with_test_input, CLONE_CALLER_flag_CLONE_PARENT) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_flag_CLONE_PARENT) { add_default_init_thread(); open_inspector(); @@ -192,8 +211,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_flag_CLONE_PARENT) ASSERT_THREAD_CHILDREN(INIT_TID, 2, 2, p1_t1_tid, p2_t1_tid) } -TEST_F(sinsp_with_test_input, CLONE_CALLER_flag_CLONE_THREAD) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_flag_CLONE_THREAD) { add_default_init_thread(); open_inspector(); @@ -229,8 +247,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_flag_CLONE_THREAD) ASSERT_THREAD_INFO_FLAG(p1_t2_tid, PPM_CL_CLONE_FILES, true); } -TEST_F(sinsp_with_test_input, CLONE_CALLER_check_event_tinfo) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_check_event_tinfo) { add_default_init_thread(); open_inspector(); @@ -267,8 +284,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_check_event_tinfo) ASSERT_EQ(evt->get_tinfo()->m_tid, 38); } -TEST_F(sinsp_with_test_input, CLONE_CALLER_missing_both_clone_events_create_leader_thread) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_missing_both_clone_events_create_leader_thread) { /* The schema is: * - init * - p1_t1 @@ -287,8 +303,8 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_missing_both_clone_events_create_lead generate_clone_x_event(p1_t1_tid, INIT_TID, INIT_PID, INIT_PTID); ASSERT_THREAD_INFO_PIDS(p1_t1_tid, p1_t1_pid, p1_t1_ptid) - /* The process p1 creates a second process p2 but we miss both clone events (child, caller) so we know nothing - * about it */ + /* The process p1 creates a second process p2 but we miss both clone events (child, caller) so + * we know nothing about it */ int64_t p2_t1_tid = 30; int64_t p2_t1_pid = 30; int64_t p2_t1_ptid = p1_t1_tid; @@ -310,8 +326,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_missing_both_clone_events_create_lead ASSERT_THREAD_CHILDREN(p1_t1_tid, 1, 1, p2_t1_tid); } -TEST_F(sinsp_with_test_input, CLONE_CALLER_missing_both_clone_events_create_secondary_threads) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_missing_both_clone_events_create_secondary_threads) { /* The schema is: * - init * - p1_t1 (we miss this thread info) @@ -343,8 +358,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_missing_both_clone_events_create_seco ASSERT_THREAD_INFO_PIDS(p1_t2_tid, p1_t2_pid, p1_t2_ptid) } -TEST_F(sinsp_with_test_input, CLONE_CALLER_comm_update) -{ +TEST_F(sinsp_with_test_input, CLONE_CALLER_comm_update) { add_default_init_thread(); /* Create process p1_t1 */ @@ -357,8 +371,8 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_comm_update) /* Now imagine that process p1 calls a prctl and changes its name... */ - /* p1_t1 create a new process p2_t1. The clone caller exit event contains the new comm and should update the - * comm of p1 + /* p1_t1 create a new process p2_t1. The clone caller exit event contains the new comm and + * should update the comm of p1 */ int64_t p2_t1_tid = 26; @@ -366,8 +380,14 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_comm_update) [[maybe_unused]] int64_t p2_t1_ptid = p1_t1_tid; ASSERT_THREAD_INFO_COMM(p1_t1_tid, "old-name"); - generate_clone_x_event(p2_t1_tid, p1_t1_tid, p1_t1_pid, p1_t1_ptid, DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE, - "new-name"); + generate_clone_x_event(p2_t1_tid, + p1_t1_tid, + p1_t1_pid, + p1_t1_ptid, + DEFAULT_VALUE, + DEFAULT_VALUE, + DEFAULT_VALUE, + "new-name"); /* The caller has a new comm but we don't catch it! */ ASSERT_THREAD_INFO_COMM(p1_t1_tid, "old-name"); @@ -379,8 +399,7 @@ TEST_F(sinsp_with_test_input, CLONE_CALLER_comm_update) /*=============================== CLONE CHILD EXIT EVENT ===========================*/ -TEST_F(sinsp_with_test_input, CLONE_CHILD_in_container) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_in_container) { add_default_init_thread(); open_inspector(); @@ -395,15 +414,20 @@ TEST_F(sinsp_with_test_input, CLONE_CHILD_in_container) /* if we use `sched_proc_fork` tracepoint `PPM_CL_CLONE_NEWPID` won't be sent so we don't * use it here, we use just `PPM_CL_CHILD_IN_PIDNS` */ - generate_clone_x_event(0, p1_t1_tid, p1_t1_pid, p1_t1_ptid, PPM_CL_CHILD_IN_PIDNS, p1_t1_vtid, p1_t1_vpid); + generate_clone_x_event(0, + p1_t1_tid, + p1_t1_pid, + p1_t1_ptid, + PPM_CL_CHILD_IN_PIDNS, + p1_t1_vtid, + p1_t1_vpid); ASSERT_THREAD_INFO_PIDS_IN_CONTAINER(p1_t1_tid, p1_t1_pid, p1_t1_ptid, p1_t1_vtid, p1_t1_vpid) ASSERT_THREAD_GROUP_INFO(p1_t1_pid, 1, false, 1, 1, p1_t1_tid) ASSERT_THREAD_CHILDREN(INIT_TID, 1, 1, p1_t1_tid) } -TEST_F(sinsp_with_test_input, CLONE_CHILD_already_there) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_already_there) { add_default_init_thread(); open_inspector(); @@ -432,8 +456,7 @@ TEST_F(sinsp_with_test_input, CLONE_CHILD_already_there) ASSERT_EQ(evt->get_thread_info()->m_pid, p1_t1_pid); } -TEST_F(sinsp_with_test_input, CLONE_CHILD_tid_collision) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_tid_collision) { add_default_init_thread(); open_inspector(); sinsp_threadinfo* tinfo = NULL; @@ -470,8 +493,7 @@ TEST_F(sinsp_with_test_input, CLONE_CHILD_tid_collision) ASSERT_EQ(evt->get_thread_info()->m_pid, new_pid); } -TEST_F(sinsp_with_test_input, CLONE_CHILD_new_main_thread) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_new_main_thread) { add_default_init_thread(); open_inspector(); sinsp_evt* evt = NULL; @@ -494,8 +516,7 @@ TEST_F(sinsp_with_test_input, CLONE_CHILD_new_main_thread) ASSERT_EQ(p1_t1_tinfo, evt->get_thread_info()); } -TEST_F(sinsp_with_test_input, CLONE_CHILD_flag_CLONE_PARENT) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_flag_CLONE_PARENT) { add_default_init_thread(); open_inspector(); @@ -520,15 +541,14 @@ TEST_F(sinsp_with_test_input, CLONE_CHILD_flag_CLONE_PARENT) * shouldn't need this flag to detect the real parent, so we omit it here * and see what happens. */ - generate_clone_x_event(0, p2_t1_tid, p2_t1_pid, p2_t1_ptid); // omitted PPM_CL_CLONE_PARENT + generate_clone_x_event(0, p2_t1_tid, p2_t1_pid, p2_t1_ptid); // omitted PPM_CL_CLONE_PARENT ASSERT_THREAD_INFO_PIDS(p2_t1_tid, p2_t1_pid, p2_t1_ptid) ASSERT_THREAD_CHILDREN(INIT_TID, 2, 2, p1_t1_tid, p2_t1_tid) ASSERT_THREAD_INFO_FLAG(p2_t1_tid, PPM_CL_CLONE_PARENT, false); } -TEST_F(sinsp_with_test_input, CLONE_CHILD_flag_CLONE_THREAD) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_flag_CLONE_THREAD) { add_default_init_thread(); open_inspector(); @@ -557,8 +577,7 @@ TEST_F(sinsp_with_test_input, CLONE_CHILD_flag_CLONE_THREAD) ASSERT_THREAD_INFO_FLAG(p1_t2_tid, PPM_CL_CLONE_FILES, true); } -TEST_F(sinsp_with_test_input, CLONE_CHILD_check_event_tinfo) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_check_event_tinfo) { add_default_init_thread(); open_inspector(); @@ -596,8 +615,7 @@ TEST_F(sinsp_with_test_input, CLONE_CHILD_check_event_tinfo) } /* Here we are using the child clone exit event to reconstruct the tree */ -TEST_F(sinsp_with_test_input, CLONE_CHILD_missing_both_clone_events_create_secondary_threads) -{ +TEST_F(sinsp_with_test_input, CLONE_CHILD_missing_both_clone_events_create_secondary_threads) { /* The schema is: * - init * - p1_t1 (we miss this thread info) diff --git a/userspace/libsinsp/test/parsers/parse_connect.cpp b/userspace/libsinsp/test/parsers/parse_connect.cpp index e6633e9598..43bdf49525 100644 --- a/userspace/libsinsp/test/parsers/parse_connect.cpp +++ b/userspace/libsinsp/test/parsers/parse_connect.cpp @@ -23,8 +23,7 @@ limitations under the License. // Note: // 1. We don't save the type of the unix socket: datagram or stream // 2. Do we want to keep the tuple in this way `9c758d0f->9c758d0a /tmp/stream.sock`? -TEST_F(sinsp_with_test_input, CONNECT_parse_unix_socket) -{ +TEST_F(sinsp_with_test_input, CONNECT_parse_unix_socket) { add_default_init_thread(); open_inspector(); @@ -34,8 +33,13 @@ TEST_F(sinsp_with_test_input, CONNECT_parse_unix_socket) // We need the enter event because we store it and we use it in the exit one. // We only store it, we don't create a fdinfo, if the enter event is missing // we don't parse the exit one. - auto evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SOCKET_SOCKET_E, 3, (uint32_t)PPM_AF_UNIX, - (uint32_t)SOCK_STREAM, (uint32_t)0); + auto evt = add_event_advance_ts(increasing_ts(), + INIT_TID, + PPME_SOCKET_SOCKET_E, + 3, + (uint32_t)PPM_AF_UNIX, + (uint32_t)SOCK_STREAM, + (uint32_t)0); auto fdinfo = evt->get_fd_info(); ASSERT_FALSE(fdinfo); @@ -64,9 +68,15 @@ TEST_F(sinsp_with_test_input, CONNECT_parse_unix_socket) ASSERT_EQ(fdinfo->m_name, ""); // We don't need the enter event! - std::vector socktuple = test_utils::pack_unix_socktuple(0x9c758d0f, 0x9c758d0a, "/tmp/stream.sock"); - evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SOCKET_CONNECT_X, 3, return_value, - scap_const_sized_buffer{socktuple.data(), socktuple.size()}, client_fd); + std::vector socktuple = + test_utils::pack_unix_socktuple(0x9c758d0f, 0x9c758d0a, "/tmp/stream.sock"); + evt = add_event_advance_ts(increasing_ts(), + INIT_TID, + PPME_SOCKET_CONNECT_X, + 3, + return_value, + scap_const_sized_buffer{socktuple.data(), socktuple.size()}, + client_fd); /* FDINFO associated with the event */ fdinfo = evt->get_fd_info(); @@ -102,18 +112,23 @@ TEST_F(sinsp_with_test_input, CONNECT_parse_unix_socket) ASSERT_EQ(fdinfo->m_name_raw, ""); } -TEST_F(sinsp_with_test_input, BIND_parse_unix_socket) -{ +TEST_F(sinsp_with_test_input, BIND_parse_unix_socket) { add_default_init_thread(); open_inspector(); int64_t return_value = 0; std::string unix_path = "/tmp/python_unix_udp_sockets_example"; sockaddr_un u_sockaddr = test_utils::fill_sockaddr_un(unix_path.c_str()); - std::vector server_sockaddr = test_utils::pack_sockaddr(reinterpret_cast(&u_sockaddr)); - auto evt = add_event_advance_ts(increasing_ts(), INIT_TID, PPME_SOCKET_BIND_X, 2, return_value, - scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); - + std::vector server_sockaddr = + test_utils::pack_sockaddr(reinterpret_cast(&u_sockaddr)); + auto evt = add_event_advance_ts( + increasing_ts(), + INIT_TID, + PPME_SOCKET_BIND_X, + 2, + return_value, + scap_const_sized_buffer{server_sockaddr.data(), server_sockaddr.size()}); + // we want to check that `get_param_value_str` returns the correct unix socket path ASSERT_EQ(evt->get_param_value_str("addr"), unix_path); } diff --git a/userspace/libsinsp/test/parsers/parse_execve.cpp b/userspace/libsinsp/test/parsers/parse_execve.cpp index c913317a5b..b2cb22cdb4 100644 --- a/userspace/libsinsp/test/parsers/parse_execve.cpp +++ b/userspace/libsinsp/test/parsers/parse_execve.cpp @@ -20,8 +20,7 @@ limitations under the License. /*=============================== EXECVE ===========================*/ -TEST_F(sinsp_with_test_input, EXECVE_from_a_not_leader_thread) -{ +TEST_F(sinsp_with_test_input, EXECVE_from_a_not_leader_thread) { /* Instantiate the default tree */ DEFAULT_TREE @@ -36,8 +35,7 @@ TEST_F(sinsp_with_test_input, EXECVE_from_a_not_leader_thread) ASSERT_MISSING_THREAD_INFO(p2_t3_tid, true); } -TEST_F(sinsp_with_test_input, EXECVE_from_a_leader_thread) -{ +TEST_F(sinsp_with_test_input, EXECVE_from_a_leader_thread) { /* Instantiate the default tree */ DEFAULT_TREE @@ -52,8 +50,7 @@ TEST_F(sinsp_with_test_input, EXECVE_from_a_leader_thread) ASSERT_MISSING_THREAD_INFO(p2_t3_tid, true); } -TEST_F(sinsp_with_test_input, EXECVE_from_a_not_leader_thread_with_a_child) -{ +TEST_F(sinsp_with_test_input, EXECVE_from_a_not_leader_thread_with_a_child) { /* Instantiate the default tree */ DEFAULT_TREE @@ -82,8 +79,7 @@ TEST_F(sinsp_with_test_input, EXECVE_from_a_not_leader_thread_with_a_child) ASSERT_THREAD_CHILDREN(p2_t1_tid, 2, 2, p3_t1_tid, p7_t1_tid); } -TEST_F(sinsp_with_test_input, EXECVE_resurrect_thread) -{ +TEST_F(sinsp_with_test_input, EXECVE_resurrect_thread) { /* Instantiate the default tree */ DEFAULT_TREE @@ -114,8 +110,7 @@ TEST_F(sinsp_with_test_input, EXECVE_resurrect_thread) ASSERT_MISSING_THREAD_INFO(p2_t3_tid, true); } -TEST_F(sinsp_with_test_input, EXECVE_missing_process_execve_repair) -{ +TEST_F(sinsp_with_test_input, EXECVE_missing_process_execve_repair) { add_default_init_thread(); open_inspector(); @@ -138,12 +133,18 @@ TEST_F(sinsp_with_test_input, EXECVE_missing_process_execve_repair) ASSERT_THREAD_CHILDREN(INIT_TID, 1, 1, p1_t1_tid); } -TEST_F(sinsp_with_test_input, EXECVE_exepath_with_trusted_exepath) -{ +TEST_F(sinsp_with_test_input, EXECVE_exepath_with_trusted_exepath) { DEFAULT_TREE /* Now we call an execve on p6_t1 */ - generate_execve_enter_and_exit_event(0, p6_t1_tid, p6_t1_tid, p6_t1_pid, p6_t1_ptid, "/good-exe", "good-exe", "/usr/bin/bad-exe"); + generate_execve_enter_and_exit_event(0, + p6_t1_tid, + p6_t1_tid, + p6_t1_pid, + p6_t1_ptid, + "/good-exe", + "good-exe", + "/usr/bin/bad-exe"); auto p6_t1_tinfo = m_inspector.get_thread_ref(p6_t1_tid, false).get(); ASSERT_TRUE(p6_t1_tinfo); @@ -158,7 +159,14 @@ TEST_F(sinsp_with_test_input, EXECVE_exepath_with_trusted_exepath) int64_t p7_t1_vtid = 20; int64_t p7_t1_vpid = 20; - generate_clone_x_event(0, p7_t1_tid, p7_t1_pid, p7_t1_ptid, PPM_CL_CHILD_IN_PIDNS, p7_t1_vtid, p7_t1_vpid, "new-comm"); + generate_clone_x_event(0, + p7_t1_tid, + p7_t1_pid, + p7_t1_ptid, + PPM_CL_CHILD_IN_PIDNS, + p7_t1_vtid, + p7_t1_vpid, + "new-comm"); auto p7_t1_tinfo = m_inspector.get_thread_ref(p7_t1_tid, false).get(); ASSERT_TRUE(p7_t1_tinfo); @@ -167,8 +175,7 @@ TEST_F(sinsp_with_test_input, EXECVE_exepath_with_trusted_exepath) ASSERT_EQ(p7_t1_tinfo->get_comm(), "new-comm"); } -TEST_F(sinsp_with_test_input, EXECVE_exepath_without_trusted_exepath) -{ +TEST_F(sinsp_with_test_input, EXECVE_exepath_without_trusted_exepath) { DEFAULT_TREE /* Now we call an old event version of execve on p6_t1 */ @@ -185,12 +192,43 @@ TEST_F(sinsp_with_test_input, EXECVE_exepath_without_trusted_exepath) add_event_advance_ts(increasing_ts(), old_tid, PPME_SYSCALL_EXECVE_19_E, 1, pathname.c_str()); - add_event_advance_ts(increasing_ts(), new_tid, PPME_SYSCALL_EXECVE_19_X, 27, retval, pathname.c_str(), empty_bytebuf, new_tid, pid, ppid, "", not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_32, not_relevant_32, not_relevant_32, comm.c_str(), empty_bytebuf, empty_bytebuf, not_relevant_32, not_relevant_64, not_relevant_32, not_relevant_32, not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_32); + add_event_advance_ts(increasing_ts(), + new_tid, + PPME_SYSCALL_EXECVE_19_X, + 27, + retval, + pathname.c_str(), + empty_bytebuf, + new_tid, + pid, + ppid, + "", + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_32, + not_relevant_32, + not_relevant_32, + comm.c_str(), + empty_bytebuf, + empty_bytebuf, + not_relevant_32, + not_relevant_64, + not_relevant_32, + not_relevant_32, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_32); auto p6_t1_tinfo = m_inspector.get_thread_ref(p6_t1_tid, false).get(); ASSERT_TRUE(p6_t1_tinfo); - /* In the old event version we will use the pathname to reconstruct the exepath through our userspace logic */ + /* In the old event version we will use the pathname to reconstruct the exepath through our + * userspace logic */ ASSERT_EQ(p6_t1_tinfo->get_exepath(), pathname.c_str()); ASSERT_EQ(p6_t1_tinfo->get_comm(), comm.c_str()); @@ -201,7 +239,14 @@ TEST_F(sinsp_with_test_input, EXECVE_exepath_without_trusted_exepath) int64_t p7_t1_vtid = 20; int64_t p7_t1_vpid = 20; - generate_clone_x_event(0, p7_t1_tid, p7_t1_pid, p7_t1_ptid, PPM_CL_CHILD_IN_PIDNS, p7_t1_vtid, p7_t1_vpid, "new-comm"); + generate_clone_x_event(0, + p7_t1_tid, + p7_t1_pid, + p7_t1_ptid, + PPM_CL_CHILD_IN_PIDNS, + p7_t1_vtid, + p7_t1_vpid, + "new-comm"); auto p7_t1_tinfo = m_inspector.get_thread_ref(p7_t1_tid, false).get(); ASSERT_TRUE(p7_t1_tinfo); diff --git a/userspace/libsinsp/test/parsers/parse_prctl.cpp b/userspace/libsinsp/test/parsers/parse_prctl.cpp index c38f926eac..8f0a331064 100644 --- a/userspace/libsinsp/test/parsers/parse_prctl.cpp +++ b/userspace/libsinsp/test/parsers/parse_prctl.cpp @@ -20,8 +20,7 @@ limitations under the License. /*=============================== PRCTL EXIT EVENT ===========================*/ -TEST_F(sinsp_with_test_input, PRCTL_failed) -{ +TEST_F(sinsp_with_test_input, PRCTL_failed) { /* Instantiate the default tree */ DEFAULT_TREE @@ -31,8 +30,14 @@ TEST_F(sinsp_with_test_input, PRCTL_failed) ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, false, 3, 3); /* Let's imagine a prctl is called on `p2_t2` but it fails */ - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)-1, - PPM_PR_SET_CHILD_SUBREAPER, "", (int64_t)1); + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)-1, + PPM_PR_SET_CHILD_SUBREAPER, + "", + (int64_t)1); /* p2_t2_pid shouldn't be a reaper */ ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, false, 3, 3); @@ -40,8 +45,14 @@ TEST_F(sinsp_with_test_input, PRCTL_failed) /* FAILED PPM_PR_GET_CHILD_SUBREAPER */ /* Same thing for a failed prctl get */ - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)-1, - PPM_PR_GET_CHILD_SUBREAPER, "", (int64_t)1); + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)-1, + PPM_PR_GET_CHILD_SUBREAPER, + "", + (int64_t)1); /* p2_t2_pid shouldn't be a reaper */ ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, false, 3, 3); @@ -49,12 +60,18 @@ TEST_F(sinsp_with_test_input, PRCTL_failed) /* INVALID THREAD INFO */ /* this time the prctl call is successful but we call it from an invalid thread. - * Our logic will generate an invalid thread info, but this shouldn't have a valid tginfo so nothing should - * happen. + * Our logic will generate an invalid thread info, but this shouldn't have a valid tginfo so + * nothing should happen. */ int64_t invalid_tid = 61004; - add_event_advance_ts(increasing_ts(), invalid_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)0, - PPM_PR_GET_CHILD_SUBREAPER, "", (int64_t)1); + add_event_advance_ts(increasing_ts(), + invalid_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)0, + PPM_PR_GET_CHILD_SUBREAPER, + "", + (int64_t)1); sinsp_threadinfo* invalid_tid_tinfo = m_inspector.get_thread_ref(invalid_tid, false).get(); ASSERT_TRUE(invalid_tid_tinfo); @@ -63,12 +80,17 @@ TEST_F(sinsp_with_test_input, PRCTL_failed) /* Unhandled prctl option */ /* Nothing should happen */ - add_event_advance_ts(increasing_ts(), invalid_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)0, PPM_PR_SET_NAME, "", - (int64_t)1); + add_event_advance_ts(increasing_ts(), + invalid_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)0, + PPM_PR_SET_NAME, + "", + (int64_t)1); } -TEST_F(sinsp_with_test_input, PRCTL_set_child_subreaper) -{ +TEST_F(sinsp_with_test_input, PRCTL_set_child_subreaper) { /* Instantiate the default tree */ DEFAULT_TREE @@ -80,8 +102,14 @@ TEST_F(sinsp_with_test_input, PRCTL_set_child_subreaper) /* Let's imagine a prctl is called on `p2_t2`. Parameter 4 could * be anything greater than 1. */ - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)0, - PPM_PR_SET_CHILD_SUBREAPER, "", (int64_t)80); + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)0, + PPM_PR_SET_CHILD_SUBREAPER, + "", + (int64_t)80); ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, true, 3, 3); @@ -90,15 +118,20 @@ TEST_F(sinsp_with_test_input, PRCTL_set_child_subreaper) /* Let's imagine `p2_t3` unset its group with a prctl call. * Please note that the reaper status is shared between all the thread group */ - add_event_advance_ts(increasing_ts(), p2_t3_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)0, - PPM_PR_SET_CHILD_SUBREAPER, "", (int64_t)0); + add_event_advance_ts(increasing_ts(), + p2_t3_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)0, + PPM_PR_SET_CHILD_SUBREAPER, + "", + (int64_t)0); /* p2_t2 group should have reaper==false */ ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, false, 3, 3); } -TEST_F(sinsp_with_test_input, PRCTL_get_child_subreaper) -{ +TEST_F(sinsp_with_test_input, PRCTL_get_child_subreaper) { /* Instantiate the default tree */ DEFAULT_TREE @@ -108,16 +141,28 @@ TEST_F(sinsp_with_test_input, PRCTL_get_child_subreaper) ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, false, 3, 3); /* Let's imagine a prctl is called on `p2_t2` */ - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)0, - PPM_PR_GET_CHILD_SUBREAPER, "", (int64_t)1); + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)0, + PPM_PR_GET_CHILD_SUBREAPER, + "", + (int64_t)1); ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, true, 3, 3); /* UNSET CHILD_SUBREAPER */ /* Let's imagine `p2_t3` unset its group with a prctl call */ - add_event_advance_ts(increasing_ts(), p2_t3_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)0, - PPM_PR_GET_CHILD_SUBREAPER, "", (int64_t)0); + add_event_advance_ts(increasing_ts(), + p2_t3_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)0, + PPM_PR_GET_CHILD_SUBREAPER, + "", + (int64_t)0); /* p2_t2 group should have reaper==false */ ASSERT_THREAD_GROUP_INFO(p2_t2_pid, 3, false, 3, 3); diff --git a/userspace/libsinsp/test/parsers/parse_proc_exit.cpp b/userspace/libsinsp/test/parsers/parse_proc_exit.cpp index 4d4145ed7a..14d0f3f4c5 100644 --- a/userspace/libsinsp/test/parsers/parse_proc_exit.cpp +++ b/userspace/libsinsp/test/parsers/parse_proc_exit.cpp @@ -20,8 +20,7 @@ limitations under the License. /*=============================== PROC EXIT EVENT ===========================*/ -TEST_F(sinsp_with_test_input, PROC_EXIT_not_existent_thread) -{ +TEST_F(sinsp_with_test_input, PROC_EXIT_not_existent_thread) { DEFAULT_TREE /* Before this proc exit init had 5 children */ @@ -33,13 +32,13 @@ TEST_F(sinsp_with_test_input, PROC_EXIT_not_existent_thread) int64_t unknown_tid = 50000; auto evt = generate_proc_exit_event(unknown_tid, INIT_TID); - /* The thread info associated with the event should be null and INIT should have the same number of children */ + /* The thread info associated with the event should be null and INIT should have the same number + * of children */ ASSERT_FALSE(evt->get_thread_info()); ASSERT_THREAD_CHILDREN(INIT_TID, 5, 5); } -TEST_F(sinsp_with_test_input, PROC_EXIT_no_children) -{ +TEST_F(sinsp_with_test_input, PROC_EXIT_no_children) { DEFAULT_TREE /* Before this proc exit init had 5 children */ @@ -64,8 +63,7 @@ TEST_F(sinsp_with_test_input, PROC_EXIT_no_children) ASSERT_EQ(m_inspector.get_tid_to_remove(), p5_t1_tid); } -TEST_F(sinsp_with_test_input, PROC_EXIT_reaper_0) -{ +TEST_F(sinsp_with_test_input, PROC_EXIT_reaper_0) { DEFAULT_TREE /* we call the proc_exit with a reaper equal to 0 @@ -89,8 +87,7 @@ TEST_F(sinsp_with_test_input, PROC_EXIT_reaper_0) ASSERT_EQ(m_inspector.get_tid_to_remove(), p5_t2_tid); } -TEST_F(sinsp_with_test_input, PROC_EXIT_negative_reaper) -{ +TEST_F(sinsp_with_test_input, PROC_EXIT_negative_reaper) { DEFAULT_TREE /* we call the proc_exit with a reaper equal to -1 @@ -112,8 +109,7 @@ TEST_F(sinsp_with_test_input, PROC_EXIT_negative_reaper) ASSERT_EQ(m_inspector.get_tid_to_remove(), p5_t2_tid); } -TEST_F(sinsp_with_test_input, PROC_EXIT_already_dead_thread) -{ +TEST_F(sinsp_with_test_input, PROC_EXIT_already_dead_thread) { DEFAULT_TREE /* This should never happen a run-time but just to check it */ @@ -146,8 +142,7 @@ TEST_F(sinsp_with_test_input, PROC_EXIT_already_dead_thread) ASSERT_EQ(m_inspector.get_tid_to_remove(), p5_t2_tid); } -TEST_F(sinsp_with_test_input, PROC_EXIT_positive_reaper) -{ +TEST_F(sinsp_with_test_input, PROC_EXIT_positive_reaper) { DEFAULT_TREE /* we call the proc_exit with a reaper equal to -1 @@ -169,8 +164,7 @@ TEST_F(sinsp_with_test_input, PROC_EXIT_positive_reaper) ASSERT_EQ(m_inspector.get_tid_to_remove(), p5_t2_tid); } -TEST_F(sinsp_with_test_input, PROC_EXIT_old_event_version) -{ +TEST_F(sinsp_with_test_input, PROC_EXIT_old_event_version) { DEFAULT_TREE /* This version of proc_exit event doesn't have the reaper info */ diff --git a/userspace/libsinsp/test/parsers/parse_setregid.cpp b/userspace/libsinsp/test/parsers/parse_setregid.cpp index e83524ca5f..e281b17f3d 100644 --- a/userspace/libsinsp/test/parsers/parse_setregid.cpp +++ b/userspace/libsinsp/test/parsers/parse_setregid.cpp @@ -19,25 +19,34 @@ limitations under the License. #include "driver/ppm_events_public.h" #include -TEST_F(sinsp_with_test_input, SETREGID_failure) -{ +TEST_F(sinsp_with_test_input, SETREGID_failure) { /* Instantiate the default tree */ DEFAULT_TREE - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_SETREGID_X, 3, (uint64_t)1, (uint32_t)0, (uint32_t)0); - + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_SETREGID_X, + 3, + (uint64_t)1, + (uint32_t)0, + (uint32_t)0); sinsp_threadinfo* ti = m_inspector.get_thread_ref(p2_t2_tid, false).get(); ASSERT_TRUE(ti); ASSERT_TRUE(ti->m_user.gid() == 0); } -TEST_F(sinsp_with_test_input, SETREGID_success) -{ +TEST_F(sinsp_with_test_input, SETREGID_success) { /* Instantiate the default tree */ DEFAULT_TREE - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_SETREGID_X, 3, (uint64_t)0, (uint32_t)1337, (uint32_t)1337); + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_SETREGID_X, + 3, + (uint64_t)0, + (uint32_t)1337, + (uint32_t)1337); sinsp_threadinfo* ti = m_inspector.get_thread_ref(p2_t2_tid, false).get(); ASSERT_TRUE(ti); diff --git a/userspace/libsinsp/test/parsers/parse_setreuid.cpp b/userspace/libsinsp/test/parsers/parse_setreuid.cpp index e428b96df6..1dc2a4d3a6 100644 --- a/userspace/libsinsp/test/parsers/parse_setreuid.cpp +++ b/userspace/libsinsp/test/parsers/parse_setreuid.cpp @@ -19,25 +19,34 @@ limitations under the License. #include "driver/ppm_events_public.h" #include -TEST_F(sinsp_with_test_input, SETREUID_failure) -{ +TEST_F(sinsp_with_test_input, SETREUID_failure) { /* Instantiate the default tree */ DEFAULT_TREE - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_SETREUID_X, 3, (uint64_t)1, (uint32_t)0, (uint32_t)0); - + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_SETREUID_X, + 3, + (uint64_t)1, + (uint32_t)0, + (uint32_t)0); sinsp_threadinfo* ti = m_inspector.get_thread_ref(p2_t2_tid, false).get(); ASSERT_TRUE(ti); ASSERT_TRUE(ti->m_user.uid() == 0); } -TEST_F(sinsp_with_test_input, SETREUID_success) -{ +TEST_F(sinsp_with_test_input, SETREUID_success) { /* Instantiate the default tree */ DEFAULT_TREE - add_event_advance_ts(increasing_ts(), p2_t2_tid, PPME_SYSCALL_SETREUID_X, 3, (uint64_t)0, (uint32_t)1337, (uint32_t)1337); + add_event_advance_ts(increasing_ts(), + p2_t2_tid, + PPME_SYSCALL_SETREUID_X, + 3, + (uint64_t)0, + (uint32_t)1337, + (uint32_t)1337); sinsp_threadinfo* ti = m_inspector.get_thread_ref(p2_t2_tid, false).get(); ASSERT_TRUE(ti); diff --git a/userspace/libsinsp/test/plugin_manager.ut.cpp b/userspace/libsinsp/test/plugin_manager.ut.cpp index 86352783ef..e271c83a11 100644 --- a/userspace/libsinsp/test/plugin_manager.ut.cpp +++ b/userspace/libsinsp/test/plugin_manager.ut.cpp @@ -20,15 +20,13 @@ limitations under the License. #include #include -class mock_sinsp_plugin: public sinsp_plugin -{ +class mock_sinsp_plugin : public sinsp_plugin { public: - inline mock_sinsp_plugin( - plugin_caps_t caps, - const std::string& name, - uint32_t id, - const std::string& source): sinsp_plugin(nullptr, nullptr, nullptr) - { + inline mock_sinsp_plugin(plugin_caps_t caps, + const std::string& name, + uint32_t id, + const std::string& source): + sinsp_plugin(nullptr, nullptr, nullptr) { m_caps = caps; m_name = name; m_id = id; @@ -36,8 +34,7 @@ class mock_sinsp_plugin: public sinsp_plugin } }; -TEST(sinsp_plugin_manager, add_and_queries) -{ +TEST(sinsp_plugin_manager, add_and_queries) { std::vector sources; sinsp_plugin_manager m(sources); @@ -61,8 +58,8 @@ TEST(sinsp_plugin_manager, add_and_queries) m.add(p5); auto p6 = std::make_shared(CAP_SOURCING, "plugin6", 0, ""); m.add(p6); - - ASSERT_EQ(m.plugins().size(), (std::size_t) 6); + + ASSERT_EQ(m.plugins().size(), (std::size_t)6); ASSERT_EQ(m.plugins()[0], p1); ASSERT_EQ(m.plugins()[1], p2); ASSERT_EQ(m.plugins()[2], p3); @@ -76,7 +73,7 @@ TEST(sinsp_plugin_manager, add_and_queries) ASSERT_EQ(m.plugin_by_id(3), nullptr); ASSERT_EQ(m.plugin_by_id(4), p4); - ASSERT_EQ(sources.size(), (std::size_t) 3); + ASSERT_EQ(sources.size(), (std::size_t)3); ASSERT_EQ(sources[0], "some_source"); ASSERT_EQ(sources[1], "source1"); ASSERT_EQ(sources[2], "source2"); @@ -87,23 +84,22 @@ TEST(sinsp_plugin_manager, add_and_queries) ASSERT_EQ(found, false); ASSERT_EQ(res, sinsp_no_event_source_idx); res = m.source_idx_by_plugin_id(1, found); - ASSERT_EQ(res, (std::size_t) 1); + ASSERT_EQ(res, (std::size_t)1); ASSERT_EQ(found, true); res = m.source_idx_by_plugin_id(2, found); - ASSERT_EQ(res, (std::size_t) 2); + ASSERT_EQ(res, (std::size_t)2); ASSERT_EQ(found, true); res = m.source_idx_by_plugin_id(3, found); ASSERT_EQ(res, sinsp_no_event_source_idx); ASSERT_EQ(found, false); res = m.source_idx_by_plugin_id(4, found); - ASSERT_EQ(res, (std::size_t) 1); + ASSERT_EQ(res, (std::size_t)1); ASSERT_EQ(found, true); } // note(jasondellaluce): this is a design chocie, but we may drop this // constraint in the future -TEST(sinsp_plugin_manager, add_conflicts) -{ +TEST(sinsp_plugin_manager, add_conflicts) { std::vector sources; sinsp_plugin_manager m(sources); @@ -124,5 +120,5 @@ TEST(sinsp_plugin_manager, add_conflicts) // adding with same source (should be ok, but should not produce duplicates) p2 = std::make_shared(CAP_SOURCING, "plugin2", 2, "source1"); EXPECT_NO_THROW(m.add(p2)); - ASSERT_EQ(sources.size(), (std::size_t) 1); + ASSERT_EQ(sources.size(), (std::size_t)1); } diff --git a/userspace/libsinsp/test/plugins.ut.cpp b/userspace/libsinsp/test/plugins.ut.cpp index 8d95c52131..f802590942 100644 --- a/userspace/libsinsp/test/plugins.ut.cpp +++ b/userspace/libsinsp/test/plugins.ut.cpp @@ -24,46 +24,37 @@ limitations under the License. #include "test_utils.h" #include "plugins/test_plugins.h" -static std::shared_ptr register_plugin_api( - sinsp* i, - plugin_api& api, - const std::string& initcfg = "") -{ +static std::shared_ptr register_plugin_api(sinsp* i, + plugin_api& api, + const std::string& initcfg = "") { std::string err; auto pl = i->register_plugin(&api); - if (!pl->init(initcfg, err)) - { + if(!pl->init(initcfg, err)) { throw sinsp_exception(err); } return pl; } -static std::shared_ptr register_plugin( - sinsp* i, - std::function constructor, - const std::string& initcfg = "") -{ +static std::shared_ptr register_plugin(sinsp* i, + std::function constructor, + const std::string& initcfg = "") { plugin_api api; constructor(api); return register_plugin_api(i, api, initcfg); } -static void add_plugin_filterchecks( - sinsp* i, - std::shared_ptr p, - const std::string& src, - filter_check_list& fl) -{ - if (p->caps() & CAP_EXTRACTION - && sinsp_plugin::is_source_compatible(p->extract_event_sources(), src)) - { +static void add_plugin_filterchecks(sinsp* i, + std::shared_ptr p, + const std::string& src, + filter_check_list& fl) { + if(p->caps() & CAP_EXTRACTION && + sinsp_plugin::is_source_compatible(p->extract_event_sources(), src)) { fl.add_filter_check(i->new_generic_filtercheck()); fl.add_filter_check(sinsp_plugin::new_filtercheck(p)); } } -TEST(plugins, broken_source_capability) -{ +TEST(plugins, broken_source_capability) { plugin_api api; { @@ -72,13 +63,13 @@ TEST(plugins, broken_source_capability) // The example plugin has id 999 so `!= 0`. For this reason, // the event source name should be different from "syscall" - api.get_id = [](){ return (uint32_t)999; }; - api.get_event_source = [](){ return sinsp_syscall_event_source_name; }; + api.get_id = []() { return (uint32_t)999; }; + api.get_event_source = []() { return sinsp_syscall_event_source_name; }; ASSERT_ANY_THROW(register_plugin_api(&inspector, api)); // `get_event_source` is implemented so also `get_id` should be implemented api.get_id = NULL; - api.get_event_source = [](){ return sinsp_syscall_event_source_name; }; + api.get_event_source = []() { return sinsp_syscall_event_source_name; }; ASSERT_ANY_THROW(register_plugin_api(&inspector, api)); // Now both methods are NULL so we are ok! @@ -106,8 +97,7 @@ TEST(plugins, broken_source_capability) } } -TEST(plugins, broken_extract_capability) -{ +TEST(plugins, broken_extract_capability) { plugin_api api; get_plugin_api_sample_plugin_extract(api); sinsp inspector; @@ -122,8 +112,7 @@ TEST(plugins, broken_extract_capability) ASSERT_ANY_THROW(register_plugin_api(&inspector, api)); } -TEST(plugins, broken_parsing_capability) -{ +TEST(plugins, broken_parsing_capability) { plugin_api api; get_plugin_api_sample_syscall_parse(api); sinsp inspector; @@ -133,8 +122,7 @@ TEST(plugins, broken_parsing_capability) ASSERT_ANY_THROW(register_plugin_api(&inspector, api)); } -TEST(plugins, broken_async_capability) -{ +TEST(plugins, broken_async_capability) { plugin_api api; get_plugin_api_sample_syscall_async(api); sinsp inspector; @@ -152,8 +140,7 @@ TEST(plugins, broken_async_capability) // scenario: a plugin with field extraction capability compatible with the // "syscall" event source should be able to extract filter values from // regular syscall events produced by any scap engine. -TEST_F(sinsp_with_test_input, plugin_syscall_extract) -{ +TEST_F(sinsp_with_test_input, plugin_syscall_extract) { size_t syscall_source_idx = 0; std::string syscall_source_name = sinsp_syscall_event_source_name; @@ -173,8 +160,23 @@ TEST_F(sinsp_with_test_input, plugin_syscall_extract) open_inspector(); // should extract legit values for non-ignored event codes - add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); - auto evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, (uint64_t)6, (uint64_t)3, "/tmp/the_file", PPM_O_RDWR, 0, 5, (uint64_t)123); + add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); + auto evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + (uint64_t)6, + (uint64_t)3, + "/tmp/the_file", + PPM_O_RDWR, + 0, + 5, + (uint64_t)123); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx); ASSERT_EQ(std::string(evt->get_source_name()), syscall_source_name); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_OPEN_X); @@ -185,7 +187,7 @@ TEST_F(sinsp_with_test_input, plugin_syscall_extract) ASSERT_EQ(get_field_as_string(evt, "sample.tick", pl_flist), "false"); // Check rhs filter checks support on plugins - + // Check on strings ASSERT_EQ(get_field_as_string(evt, "sample.proc_name", pl_flist), "init"); ASSERT_TRUE(eval_filter(evt, "(sample.proc_name = init)", pl_flist)); @@ -204,11 +206,20 @@ TEST_F(sinsp_with_test_input, plugin_syscall_extract) ASSERT_FALSE(eval_filter(evt, "(toupper(sample.proc_name) = init)", pl_flist)); ASSERT_TRUE(eval_filter(evt, "(toupper(sample.proc_name) = INIT)", pl_flist)); ASSERT_TRUE(eval_filter(evt, "(tolower(toupper(sample.proc_name)) = init)", pl_flist)); - ASSERT_TRUE(eval_filter(evt, "(tolower(toupper(sample.proc_name)) = tolower(toupper(sample.proc_name)))", pl_flist)); - ASSERT_TRUE(eval_filter(evt, "(toupper(sample.proc_name) = toupper(sample.proc_name))", pl_flist)); + ASSERT_TRUE( + eval_filter(evt, + "(tolower(toupper(sample.proc_name)) = tolower(toupper(sample.proc_name)))", + pl_flist)); + ASSERT_TRUE( + eval_filter(evt, "(toupper(sample.proc_name) = toupper(sample.proc_name))", pl_flist)); // Here `sample.is_open` should be false - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_INOTIFY_INIT1_X, 2, (int64_t)12, (uint16_t)32); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_INOTIFY_INIT1_X, + 2, + (int64_t)12, + (uint16_t)32); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx); ASSERT_EQ(std::string(evt->get_source_name()), syscall_source_name); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_INOTIFY_INIT1_X); @@ -220,7 +231,14 @@ TEST_F(sinsp_with_test_input, plugin_syscall_extract) // should extract NULL for ignored event codes // `PPME_SYSCALL_OPEN_BY_HANDLE_AT_X` is an ignored event, see plugin_get_extract_event_types - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, 4, (uint64_t)4, (uint64_t)5, PPM_O_RDWR, "/tmp/the_file.txt"); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + 4, + (uint64_t)4, + (uint64_t)5, + PPM_O_RDWR, + "/tmp/the_file.txt"); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx); ASSERT_EQ(std::string(evt->get_source_name()), syscall_source_name); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_OPEN_BY_HANDLE_AT_X); @@ -234,7 +252,12 @@ TEST_F(sinsp_with_test_input, plugin_syscall_extract) const char data[2048] = "hello world"; /* There are no added plugins with id `1` */ uint32_t unknwon_plugin_id = 1; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_PLUGINEVENT_E, 2, unknwon_plugin_id, scap_const_sized_buffer{&data, strlen(data) + 1}); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_PLUGINEVENT_E, + 2, + unknwon_plugin_id, + scap_const_sized_buffer{&data, strlen(data) + 1}); ASSERT_EQ(evt->get_source_idx(), sinsp_no_event_source_idx); ASSERT_EQ(evt->get_source_name(), sinsp_no_event_source_name); ASSERT_EQ(evt->get_type(), PPME_PLUGINEVENT_E); @@ -247,7 +270,12 @@ TEST_F(sinsp_with_test_input, plugin_syscall_extract) // should extract NULL for non-compatible event sources /* This source plugin generate events with a source that we cannot extract with our plugin */ uint32_t source_plugin_id = 999; - evt = add_event_advance_ts(increasing_ts(), 1, PPME_PLUGINEVENT_E, 2, source_plugin_id, scap_const_sized_buffer{&data, strlen(data) + 1}); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_PLUGINEVENT_E, + 2, + source_plugin_id, + scap_const_sized_buffer{&data, strlen(data) + 1}); ASSERT_EQ(evt->get_source_idx(), 1); ASSERT_EQ(std::string(evt->get_source_name()), std::string("sample")); ASSERT_EQ(evt->get_type(), PPME_PLUGINEVENT_E); @@ -261,8 +289,7 @@ TEST_F(sinsp_with_test_input, plugin_syscall_extract) // scenario: an event sourcing plugin should produce events of "syscall" // event source and we should be able to extract filter values implemented // by both libsinsp and another plugin with field extraction capability -TEST_F(sinsp_with_test_input, plugin_syscall_source) -{ +TEST_F(sinsp_with_test_input, plugin_syscall_source) { size_t syscall_source_idx = 0; std::string syscall_source_name = sinsp_syscall_event_source_name; @@ -285,7 +312,7 @@ TEST_F(sinsp_with_test_input, plugin_syscall_source) ASSERT_NE(evt, nullptr); ASSERT_EQ(evt->get_type(), PPME_SYSCALL_OPEN_X); ASSERT_EQ(evt->get_source_idx(), syscall_source_idx); - ASSERT_EQ(evt->get_tid(), (uint64_t) 1); + ASSERT_EQ(evt->get_tid(), (uint64_t)1); ASSERT_EQ(std::string(evt->get_source_name()), syscall_source_name); ASSERT_EQ(get_field_as_string(evt, "fd.name", filterlist), "/tmp/the_file"); ASSERT_EQ(get_field_as_string(evt, "fd.directory", filterlist), "/tmp"); @@ -297,18 +324,16 @@ TEST_F(sinsp_with_test_input, plugin_syscall_source) // We check that the plugin don't produce other events but just 1 size_t metaevt_count = 0; - evt = next_event(); // expecting a few or zero metaevts and then EOF - while (evt != nullptr && metaevt_count++ < 100) - { - ASSERT_TRUE(libsinsp::events::is_metaevent((ppm_event_code) evt->get_type())); + evt = next_event(); // expecting a few or zero metaevts and then EOF + while(evt != nullptr && metaevt_count++ < 100) { + ASSERT_TRUE(libsinsp::events::is_metaevent((ppm_event_code)evt->get_type())); evt = next_event(); } } // scenario: a plugin with field extraction capability compatible with the // event source of another plugin should extract values from its events -TEST_F(sinsp_with_test_input, plugin_custom_source) -{ +TEST_F(sinsp_with_test_input, plugin_custom_source) { sinsp_filter_check_list filterlist; auto src_pl = register_plugin(&m_inspector, get_plugin_api_sample_plugin_source); auto ext_pl = register_plugin(&m_inspector, get_plugin_api_sample_plugin_extract); @@ -325,71 +350,75 @@ TEST_F(sinsp_with_test_input, plugin_custom_source) ASSERT_NE(evt, nullptr); ASSERT_EQ(evt->get_type(), PPME_PLUGINEVENT_E); ASSERT_EQ(evt->get_source_idx(), 1); - ASSERT_EQ(evt->get_tid(), (uint64_t) -1); + ASSERT_EQ(evt->get_tid(), (uint64_t)-1); ASSERT_EQ(std::string(evt->get_source_name()), src_pl->event_source()); ASSERT_FALSE(field_has_value(evt, "fd.name", filterlist)); ASSERT_EQ(get_field_as_string(evt, "evt.pluginname", filterlist), src_pl->name()); ASSERT_EQ(get_field_as_string(evt, "sample.hello", filterlist), "hello world"); - ASSERT_EQ(next_event(), nullptr); // EOF is expected + ASSERT_EQ(next_event(), nullptr); // EOF is expected } -TEST(sinsp_plugin, plugin_extract_compatibility) -{ +TEST(sinsp_plugin, plugin_extract_compatibility) { std::string tmp; sinsp i; plugin_api api; get_plugin_api_sample_plugin_extract(api); // compatible event sources specified, event types not specified - api.get_name = [](){ return "p1"; }; + api.get_name = []() { return "p1"; }; auto p = i.register_plugin(&api); p->init("", tmp); ASSERT_EQ(p->extract_event_sources().size(), 1); ASSERT_TRUE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), "sample")); - ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), sinsp_syscall_event_source_name)); + ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), + sinsp_syscall_event_source_name)); ASSERT_EQ(p->extract_event_codes().size(), 1); - /* The plugin doesn't declare a list of event types and for this reason, it can extract only from pluginevent_e */ + /* The plugin doesn't declare a list of event types and for this reason, it can extract only + * from pluginevent_e */ ASSERT_TRUE(p->extract_event_codes().contains(PPME_PLUGINEVENT_E)); ASSERT_FALSE(p->extract_event_codes().contains(PPME_SYSCALL_OPEN_E)); // compatible event sources specified, event types specified (config-altered) - api.get_name = [](){ return "p1-2"; }; + api.get_name = []() { return "p1-2"; }; p = i.register_plugin(&api); - ASSERT_ANY_THROW(p->extract_event_codes()); // can't be called before init + ASSERT_ANY_THROW(p->extract_event_codes()); // can't be called before init p->init("322,402", tmp); ASSERT_EQ(p->extract_event_sources().size(), 1); ASSERT_TRUE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), "sample")); - ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), sinsp_syscall_event_source_name)); + ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), + sinsp_syscall_event_source_name)); ASSERT_EQ(p->extract_event_codes().size(), 2); ASSERT_TRUE(p->extract_event_codes().contains(PPME_PLUGINEVENT_E)); ASSERT_TRUE(p->extract_event_codes().contains(PPME_ASYNCEVENT_E)); ASSERT_FALSE(p->extract_event_codes().contains(PPME_SYSCALL_OPEN_E)); // compatible event sources specified, event types specified - api.get_name = [](){ return "p2"; }; + api.get_name = []() { return "p2"; }; api.get_extract_event_types = [](uint32_t* n, ss_plugin_t* s) { - static uint16_t ret[] = { PPME_SYSCALL_OPEN_E }; - *n = sizeof(ret) / sizeof(uint16_t); - return &ret[0]; + static uint16_t ret[] = {PPME_SYSCALL_OPEN_E}; + *n = sizeof(ret) / sizeof(uint16_t); + return &ret[0]; }; p = i.register_plugin(&api); p->init("", tmp); ASSERT_EQ(p->extract_event_sources().size(), 1); ASSERT_TRUE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), "sample")); - ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), sinsp_syscall_event_source_name)); + ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), + sinsp_syscall_event_source_name)); ASSERT_EQ(p->extract_event_codes().size(), 1); ASSERT_FALSE(p->extract_event_codes().contains(PPME_PLUGINEVENT_E)); ASSERT_TRUE(p->extract_event_codes().contains(PPME_SYSCALL_OPEN_E)); // compatible event sources not specified, event types not specified - api.get_name = [](){ return "p3"; }; + api.get_name = []() { return "p3"; }; api.get_extract_event_sources = NULL; api.get_extract_event_types = NULL; p = i.register_plugin(&api); p->init("", tmp); ASSERT_EQ(p->extract_event_sources().size(), 0); ASSERT_TRUE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), "sample")); - ASSERT_TRUE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), sinsp_syscall_event_source_name)); + ASSERT_TRUE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), + sinsp_syscall_event_source_name)); ASSERT_TRUE(p->extract_event_codes().contains(PPME_PLUGINEVENT_E)); ASSERT_TRUE(p->extract_event_codes().contains(PPME_SYSCALL_OPEN_E)); @@ -397,7 +426,7 @@ TEST(sinsp_plugin, plugin_extract_compatibility) // event sourcing capability is detected with specific event source plugin_api src_api; get_plugin_api_sample_plugin_source(src_api); - api.get_name = [](){ return "p4"; }; + api.get_name = []() { return "p4"; }; api.get_id = src_api.get_id; api.get_event_source = src_api.get_event_source; api.open = src_api.open; @@ -407,7 +436,8 @@ TEST(sinsp_plugin, plugin_extract_compatibility) p->init("", tmp); ASSERT_EQ(p->extract_event_sources().size(), 1); ASSERT_TRUE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), "sample")); - ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), sinsp_syscall_event_source_name)); + ASSERT_FALSE(sinsp_plugin::is_source_compatible(p->extract_event_sources(), + sinsp_syscall_event_source_name)); ASSERT_EQ(p->extract_event_codes().size(), 1); ASSERT_TRUE(p->extract_event_codes().contains(PPME_PLUGINEVENT_E)); ASSERT_FALSE(p->extract_event_codes().contains(PPME_SYSCALL_OPEN_E)); @@ -419,8 +449,7 @@ TEST(sinsp_plugin, plugin_extract_compatibility) // any scap engine. The first is responsible of attaching an extra field to // the sinsp thread table (a counter), and the latter extracts a field based // on the value of the additional table's field. -TEST_F(sinsp_with_test_input, plugin_syscall_parse) -{ +TEST_F(sinsp_with_test_input, plugin_syscall_parse) { // note: the "parsing" plugin will need to be loaded before the "extraction" // one, otherwise the latter will not be able to access the addional // plugin-defined field. Here we are also testing the loading order guarantees. @@ -433,34 +462,76 @@ TEST_F(sinsp_with_test_input, plugin_syscall_parse) open_inspector(); // should extract and parse regularly for non-ignored event codes - auto evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + auto evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); ASSERT_EQ(get_field_as_string(evt, "sample.open_count", pl_flist), "1"); ASSERT_EQ(get_field_as_string(evt, "sample.evt_count", pl_flist), "1"); ASSERT_EQ(get_field_as_string(evt, "sample.tick", pl_flist), "false"); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (uint64_t)3, "/tmp/the_file", PPM_O_RDWR, 0, 5, (uint64_t)123); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)3, + "/tmp/the_file", + PPM_O_RDWR, + 0, + 5, + (uint64_t)123); ASSERT_EQ(get_field_as_string(evt, "sample.open_count", pl_flist), "2"); ASSERT_EQ(get_field_as_string(evt, "sample.evt_count", pl_flist), "1"); ASSERT_EQ(get_field_as_string(evt, "sample.tick", pl_flist), "false"); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_INOTIFY_INIT1_X, 2, (int64_t)12, (uint16_t)32); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_INOTIFY_INIT1_X, + 2, + (int64_t)12, + (uint16_t)32); ASSERT_EQ(get_field_as_string(evt, "sample.open_count", pl_flist), "2"); // the parsing plugin filters-out this kind of event, so there should be no counter for it ASSERT_EQ(get_field_as_string(evt, "sample.evt_count", pl_flist), "0"); ASSERT_EQ(get_field_as_string(evt, "sample.tick", pl_flist), "false"); - // should extract NULL for ignored event codes, but should still parse it (because the parsing plugin does not ignore it) - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, 4, (uint64_t)4, (uint64_t)5, PPM_O_RDWR, "/tmp/the_file.txt"); + // should extract NULL for ignored event codes, but should still parse it (because the parsing + // plugin does not ignore it) + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + 4, + (uint64_t)4, + (uint64_t)5, + PPM_O_RDWR, + "/tmp/the_file.txt"); ASSERT_FALSE(field_has_value(evt, "sample.open_count", pl_flist)); ASSERT_FALSE(field_has_value(evt, "sample.evt_count", pl_flist)); ASSERT_FALSE(field_has_value(evt, "sample.tick", pl_flist)); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_INOTIFY_INIT1_X, 2, (int64_t)12, (uint16_t)32); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_INOTIFY_INIT1_X, + 2, + (int64_t)12, + (uint16_t)32); ASSERT_EQ(get_field_as_string(evt, "sample.open_count", pl_flist), "3"); ASSERT_EQ(get_field_as_string(evt, "sample.evt_count", pl_flist), "0"); ASSERT_EQ(get_field_as_string(evt, "sample.tick", pl_flist), "false"); - evt = add_event_advance_ts(increasing_ts(), 1, PPME_SYSCALL_OPEN_X, 6, (uint64_t)4, "/tmp/the_file", PPM_O_RDWR, 0, 5, (uint64_t)123); + evt = add_event_advance_ts(increasing_ts(), + 1, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)4, + "/tmp/the_file", + PPM_O_RDWR, + 0, + 5, + (uint64_t)123); ASSERT_EQ(get_field_as_string(evt, "sample.open_count", pl_flist), "4"); // this is the second time we see this event type ASSERT_EQ(get_field_as_string(evt, "sample.evt_count", pl_flist), "2"); @@ -473,10 +544,9 @@ TEST_F(sinsp_with_test_input, plugin_syscall_parse) // the only events received are the ones coming from the async plugin. // note: emscripten has trouble with the nodriver engine and async events #if !defined(__EMSCRIPTEN__) -TEST_F(sinsp_with_test_input, plugin_syscall_async) -{ +TEST_F(sinsp_with_test_input, plugin_syscall_async) { uint64_t max_count = 10; - uint64_t period_ns = 1000000; // 1ms + uint64_t period_ns = 1000000; // 1ms /* async plugin config */ std::string async_pl_cfg = std::to_string(max_count) + ":" + std::to_string(period_ns); std::string srcname = sinsp_syscall_event_source_name; @@ -487,7 +557,8 @@ TEST_F(sinsp_with_test_input, plugin_syscall_async) add_plugin_filterchecks(&m_inspector, ext_pl, srcname, filterlist); // check that the async event name is an accepted evt.type value - std::unique_ptr chk(filterlist.new_filter_check_from_fldname("evt.type", &m_inspector, false)); + std::unique_ptr chk( + filterlist.new_filter_check_from_fldname("evt.type", &m_inspector, false)); ASSERT_GT(chk->parse_field_name("evt.type", true, false), 0); ASSERT_NO_THROW(chk->add_filter_value("openat", strlen("openat") + 1, 0)); ASSERT_NO_THROW(chk->add_filter_value("sampleticker", strlen("sampleticker") + 1, 1)); @@ -496,18 +567,16 @@ TEST_F(sinsp_with_test_input, plugin_syscall_async) // we will not use the test scap engine here, but open the no-driver instead uint64_t count = 0; uint64_t cycles = 0; - uint64_t max_cycles = max_count * 8; // avoid infinite loops - sinsp_evt *evt = NULL; + uint64_t max_cycles = max_count * 8; // avoid infinite loops + sinsp_evt* evt = NULL; int32_t rc = SCAP_SUCCESS; uint64_t last_ts = 0; m_inspector.open_nodriver(); - while (rc == SCAP_SUCCESS && cycles < max_cycles && count < max_count) - { + while(rc == SCAP_SUCCESS && cycles < max_cycles && count < max_count) { cycles++; rc = m_inspector.next(&evt); /* The no driver engine sends only `PPME_SCAPEVENT_X` events */ - if (rc == SCAP_TIMEOUT || evt->get_type() == PPME_SCAPEVENT_X) - { + if(rc == SCAP_TIMEOUT || evt->get_type() == PPME_SCAPEVENT_X) { // wait a bit so that the plugin can fire the async event std::this_thread::sleep_for(std::chrono::nanoseconds(period_ns)); rc = SCAP_SUCCESS; @@ -517,13 +586,14 @@ TEST_F(sinsp_with_test_input, plugin_syscall_async) ASSERT_NE(evt, nullptr); ASSERT_EQ(evt->get_type(), PPME_ASYNCEVENT_E); ASSERT_EQ(evt->get_tid(), 1); - ASSERT_EQ(evt->get_source_idx(), 0); // "syscall" source + ASSERT_EQ(evt->get_source_idx(), 0); // "syscall" source ASSERT_EQ(std::string(evt->get_source_name()), srcname); - if (cycles > 1) - { + if(cycles > 1) { ASSERT_GE(evt->get_ts(), last_ts); } - ASSERT_FALSE(field_has_value(evt, "evt.pluginname", filterlist)); // not available for "syscall" async events + ASSERT_FALSE(field_has_value(evt, + "evt.pluginname", + filterlist)); // not available for "syscall" async events ASSERT_FALSE(field_has_value(evt, "evt.plugininfo", filterlist)); ASSERT_EQ(get_field_as_string(evt, "evt.is_async", filterlist), "true"); ASSERT_EQ(get_field_as_string(evt, "evt.asynctype", filterlist), "sampleticker"); @@ -534,15 +604,14 @@ TEST_F(sinsp_with_test_input, plugin_syscall_async) m_inspector.close(); ASSERT_EQ(count, max_count); } -#endif // !defined(__EMSCRIPTEN__) +#endif // !defined(__EMSCRIPTEN__) // Scenario we load a plugin that parses any event and plays with the // thread table, by stressing all the operations supported. After that, we // also play with the plugin's table from the inspector C++ interface. // Basically, we are verifying that the sinsp <-> plugin tables access // is bidirectional and consistent. -TEST_F(sinsp_with_test_input, plugin_tables) -{ +TEST_F(sinsp_with_test_input, plugin_tables) { auto& reg = m_inspector.get_table_registry(); add_default_init_thread(); @@ -557,7 +626,7 @@ TEST_F(sinsp_with_test_input, plugin_tables) register_plugin(&m_inspector, get_plugin_api_sample_syscall_tables); ASSERT_EQ(reg->tables().size(), 2); ASSERT_NE(reg->tables().find("plugin_sample"), reg->tables().end()); - ASSERT_ANY_THROW(reg->get_table("plugin_sample")); // wrong key type + ASSERT_ANY_THROW(reg->get_table("plugin_sample")); // wrong key type ASSERT_NE(reg->get_table("plugin_sample"), nullptr); // get the plugin table and check its fields and info @@ -579,7 +648,8 @@ TEST_F(sinsp_with_test_input, plugin_tables) // add a new field in the plugin table const auto& dfield = table->dynamic_fields()->add_field("str_val"); - ASSERT_NE(table->dynamic_fields()->fields().find("str_val"), table->dynamic_fields()->fields().end()); + ASSERT_NE(table->dynamic_fields()->fields().find("str_val"), + table->dynamic_fields()->fields().end()); ASSERT_EQ(dfield, table->dynamic_fields()->fields().find("str_val")->second); ASSERT_EQ(dfield.readonly(), false); ASSERT_EQ(dfield.valid(), true); @@ -593,9 +663,15 @@ TEST_F(sinsp_with_test_input, plugin_tables) const char* asyncname = "sampleasync"; const char* sample_plugin_evtdata = "hello world"; uint64_t max_iterations = 10000; - for (uint64_t i = 0; i < max_iterations; i++) - { - auto evt = add_event_advance_ts(increasing_ts(), 1, PPME_ASYNCEVENT_E, 3, (uint32_t) 0, asyncname, scap_const_sized_buffer{sample_plugin_evtdata, strlen(sample_plugin_evtdata) + 1}); + for(uint64_t i = 0; i < max_iterations; i++) { + auto evt = add_event_advance_ts( + increasing_ts(), + 1, + PPME_ASYNCEVENT_E, + 3, + (uint32_t)0, + asyncname, + scap_const_sized_buffer{sample_plugin_evtdata, strlen(sample_plugin_evtdata) + 1}); ASSERT_EQ(evt->get_type(), PPME_ASYNCEVENT_E); ASSERT_EQ(evt->get_source_idx(), 0); } @@ -604,8 +680,7 @@ TEST_F(sinsp_with_test_input, plugin_tables) auto sfieldacc = sfield->second.new_accessor(); auto dfieldacc = dfield.new_accessor(); - for (uint64_t i = 0; i < max_iterations; i++) - { + for(uint64_t i = 0; i < max_iterations; i++) { ASSERT_EQ(table->entries_count(), i); // get non-existing entry @@ -621,7 +696,7 @@ TEST_F(sinsp_with_test_input, plugin_tables) ASSERT_EQ(table->entries_count(), i + 1); // read and write from newly-created thread (existing field) - uint64_t tmpu64 = (uint64_t) -1; + uint64_t tmpu64 = (uint64_t)-1; t->get_dynamic_field(sfieldacc, tmpu64); ASSERT_EQ(tmpu64, 0); tmpu64 = 5; @@ -642,8 +717,7 @@ TEST_F(sinsp_with_test_input, plugin_tables) } // full iteration - auto it = [&](libsinsp::state::table_entry& e) -> bool - { + auto it = [&](libsinsp::state::table_entry& e) -> bool { uint64_t tmpu64; std::string tmpstr; e.get_dynamic_field(sfieldacc, tmpu64); @@ -655,16 +729,12 @@ TEST_F(sinsp_with_test_input, plugin_tables) ASSERT_TRUE(table->foreach_entry(it)); // iteration with break-out - ASSERT_FALSE(table->foreach_entry([&](libsinsp::state::table_entry& e) -> bool - { - return false; - })); + ASSERT_FALSE( + table->foreach_entry([&](libsinsp::state::table_entry& e) -> bool { return false; })); // iteration with error - ASSERT_ANY_THROW(table->foreach_entry([&](libsinsp::state::table_entry& e) -> bool - { - throw sinsp_exception("some error"); - })); + ASSERT_ANY_THROW(table->foreach_entry( + [&](libsinsp::state::table_entry& e) -> bool { throw sinsp_exception("some error"); })); // erasing an unknown thread ASSERT_EQ(table->erase_entry(max_iterations), false); @@ -679,8 +749,7 @@ TEST_F(sinsp_with_test_input, plugin_tables) ASSERT_EQ(table->entries_count(), 0); } -TEST_F(sinsp_with_test_input, plugin_subtables) -{ +TEST_F(sinsp_with_test_input, plugin_subtables) { const constexpr auto num_entries_from_plugin = 1024; auto& reg = m_inspector.get_table_registry(); @@ -737,11 +806,16 @@ TEST_F(sinsp_with_test_input, plugin_subtables) open_inspector(); // step #0: the plugin should populate the fdtable - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); ASSERT_EQ(subtable->entries_count(), num_entries_from_plugin); - auto itt = [&](libsinsp::state::table_entry& e) -> bool - { + auto itt = [&](libsinsp::state::table_entry& e) -> bool { int64_t tmp; std::string tmpstr; e.get_static_field(sfieldacc, tmp); @@ -753,16 +827,27 @@ TEST_F(sinsp_with_test_input, plugin_subtables) ASSERT_TRUE(subtable->foreach_entry(itt)); // step #1: the plugin should remove one entry from the fdtable - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); ASSERT_EQ(subtable->entries_count(), num_entries_from_plugin - 1); // step #2: the plugin should cleae the fdtable - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); ASSERT_EQ(subtable->entries_count(), 0); } -TEST_F(sinsp_with_test_input, plugin_subtables_array) -{ +TEST_F(sinsp_with_test_input, plugin_subtables_array) { const constexpr auto num_entries_from_plugin = 10; auto& reg = m_inspector.get_table_registry(); @@ -793,8 +878,9 @@ TEST_F(sinsp_with_test_input, plugin_subtables_array) // obtain a pointer to the subtable (check typing too) auto subtable_acc = field->second.new_accessor(); - auto subtable = dynamic_cast>*>( - entry->get_static_field(subtable_acc)); + auto subtable = + dynamic_cast>*>( + entry->get_static_field(subtable_acc)); ASSERT_NE(subtable, nullptr); ASSERT_EQ(subtable->name(), "env"); ASSERT_EQ(subtable->entries_count(), 0); @@ -815,11 +901,16 @@ TEST_F(sinsp_with_test_input, plugin_subtables_array) open_inspector(); // step #0: the plugin should populate the fdtable - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); ASSERT_EQ(subtable->entries_count(), num_entries_from_plugin); - auto itt = [&](libsinsp::state::table_entry& e) -> bool - { + auto itt = [&](libsinsp::state::table_entry& e) -> bool { std::string tmpstr; e.get_dynamic_field(dfieldacc, tmpstr); EXPECT_EQ(tmpstr, "hello"); @@ -828,11 +919,23 @@ TEST_F(sinsp_with_test_input, plugin_subtables_array) ASSERT_TRUE(subtable->foreach_entry(itt)); // step #1: the plugin should remove one entry from the fdtable - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); ASSERT_EQ(subtable->entries_count(), num_entries_from_plugin - 1); // step #2: the plugin should cleae the fdtable - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); ASSERT_EQ(subtable->entries_count(), 0); } @@ -841,16 +944,16 @@ TEST_F(sinsp_with_test_input, plugin_subtables_array) // We use a callback attached to the logger to assert the message. // When the inspector goes out of scope, // the plugin is automatically destroyed. -TEST(sinsp_plugin, plugin_logging) -{ +TEST(sinsp_plugin, plugin_logging) { { std::string tmp; sinsp i; plugin_api api; get_plugin_api_sample_plugin_extract(api); - // the plugin is logging with a NULL component, so we expect the component to fallback to the plugin name - api.get_name = [](){ return "plugin_name"; }; + // the plugin is logging with a NULL component, so we expect the component to fallback to + // the plugin name + api.get_name = []() { return "plugin_name"; }; libsinsp_logger()->add_callback_log([](std::string&& str, sinsp_logger::severity sev) { std::string expected = "plugin_name: initializing plugin..."; @@ -872,14 +975,13 @@ TEST(sinsp_plugin, plugin_logging) // Scenario: we provide the plugin with a new configuration, // expecting it to log when it's notified. -TEST(sinsp_plugin, plugin_set_config) -{ +TEST(sinsp_plugin, plugin_set_config) { std::string tmp; sinsp i; plugin_api api; get_plugin_api_sample_plugin_extract(api); - api.get_name = [](){ return "plugin_name"; }; + api.get_name = []() { return "plugin_name"; }; auto p = i.register_plugin(&api); p->init("", tmp); @@ -896,8 +998,7 @@ TEST(sinsp_plugin, plugin_set_config) #ifdef __linux__ -TEST_F(sinsp_with_test_input, plugin_metrics) -{ +TEST_F(sinsp_with_test_input, plugin_metrics) { uint32_t test_metrics_flags = (METRICS_V2_PLUGINS); libs::metrics::libs_metrics_collector libs_metrics_collector(&m_inspector, test_metrics_flags); @@ -913,9 +1014,14 @@ TEST_F(sinsp_with_test_input, plugin_metrics) ASSERT_EQ(metrics_snapshot.size(), 2); int events = 256; - for (int i = 0; i < events; i++) - { - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + for(int i = 0; i < events; i++) { + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); } libs_metrics_collector.snapshot(); @@ -932,8 +1038,7 @@ TEST_F(sinsp_with_test_input, plugin_metrics) #if defined(ENABLE_THREAD_POOL) && !defined(__EMSCRIPTEN__) -TEST_F(sinsp_with_test_input, plugin_routines) -{ +TEST_F(sinsp_with_test_input, plugin_routines) { auto p = register_plugin(&m_inspector, get_plugin_api_sample_routines); open_inspector(); @@ -946,29 +1051,56 @@ TEST_F(sinsp_with_test_input, plugin_routines) ASSERT_EQ(routines_num, 1); // step #1: the plugin subscribes another routine - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); routines_num = tp->routines_num(); ASSERT_EQ(routines_num, 2); // step #2: the plugin unsubscribes the previous routine - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); routines_num = tp->routines_num(); ASSERT_EQ(routines_num, 1); // step #3: the plugin subscribes another routine - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); routines_num = tp->routines_num(); ASSERT_EQ(routines_num, 2); // step #4: the plugin sets a flag that causes the previous routine to be unsubscibed - add_event_advance_ts(increasing_ts(), 0, PPME_SYSCALL_OPEN_E, 3, "/tmp/the_file", PPM_O_RDWR, 0); - std::this_thread::sleep_for(std::chrono::nanoseconds(1000)); //wait for a bit to let routine finish + add_event_advance_ts(increasing_ts(), + 0, + PPME_SYSCALL_OPEN_E, + 3, + "/tmp/the_file", + PPM_O_RDWR, + 0); + std::this_thread::sleep_for( + std::chrono::nanoseconds(1000)); // wait for a bit to let routine finish routines_num = tp->routines_num(); ASSERT_EQ(routines_num, 1); - // step: #5: the plugin doesn't unsubscribe the last routine, but the thread pool shuould unsubscribe it on capture close + // step: #5: the plugin doesn't unsubscribe the last routine, but the thread pool shuould + // unsubscribe it on capture close m_inspector.close(); - std::this_thread::sleep_for(std::chrono::nanoseconds(100)); //wait for a bit to let routine finish + std::this_thread::sleep_for( + std::chrono::nanoseconds(100)); // wait for a bit to let routine finish routines_num = tp->routines_num(); ASSERT_EQ(routines_num, 0); } diff --git a/userspace/libsinsp/test/plugins/metrics.cpp b/userspace/libsinsp/test/plugins/metrics.cpp index 4c853d0401..6979b0212c 100644 --- a/userspace/libsinsp/test/plugins/metrics.cpp +++ b/userspace/libsinsp/test/plugins/metrics.cpp @@ -26,114 +26,102 @@ limitations under the License. namespace { -struct plugin_state -{ - std::string lasterr; - ss_plugin_metric metrics[2]; - uint64_t count = 0; +struct plugin_state { + std::string lasterr; + ss_plugin_metric metrics[2]; + uint64_t count = 0; }; -const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ - return "0.1.0"; +const char* plugin_get_version() { + return "0.1.0"; } -const char* plugin_get_name() -{ - return "sample_metrics"; +const char* plugin_get_name() { + return "sample_metrics"; } -const char* plugin_get_description() -{ - return "some desc"; +const char* plugin_get_description() { + return "some desc"; } -const char* plugin_get_contact() -{ - return "some contact"; +const char* plugin_get_contact() { + return "some contact"; } -const char* plugin_get_parse_event_sources() -{ - return "[\"syscall\"]"; +const char* plugin_get_parse_event_sources() { + return "[\"syscall\"]"; } -uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - static uint16_t types[] = { - PPME_SYSCALL_OPEN_E, - //PPME_SYSCALL_OPEN_X, - }; - *num_types = sizeof(types) / sizeof(uint16_t); - return &types[0]; +uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) { + static uint16_t types[] = { + PPME_SYSCALL_OPEN_E, + // PPME_SYSCALL_OPEN_X, + }; + *num_types = sizeof(types) / sizeof(uint16_t); + return &types[0]; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - *rc = SS_PLUGIN_SUCCESS; - auto ret = new plugin_state(); +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + *rc = SS_PLUGIN_SUCCESS; + auto ret = new plugin_state(); - ret->metrics[0].type = SS_PLUGIN_METRIC_TYPE_NON_MONOTONIC; - ret->metrics[0].value_type = SS_PLUGIN_METRIC_VALUE_TYPE_U64; - ret->metrics[0].value.u64 = 1234; - ret->metrics[0].name = "dummy_metric"; + ret->metrics[0].type = SS_PLUGIN_METRIC_TYPE_NON_MONOTONIC; + ret->metrics[0].value_type = SS_PLUGIN_METRIC_VALUE_TYPE_U64; + ret->metrics[0].value.u64 = 1234; + ret->metrics[0].name = "dummy_metric"; - ret->metrics[1].type = SS_PLUGIN_METRIC_TYPE_MONOTONIC; - ret->metrics[1].value_type = SS_PLUGIN_METRIC_VALUE_TYPE_U64; - ret->metrics[1].value.u64 = 0; - ret->metrics[1].name = "evt_count"; + ret->metrics[1].type = SS_PLUGIN_METRIC_TYPE_MONOTONIC; + ret->metrics[1].value_type = SS_PLUGIN_METRIC_VALUE_TYPE_U64; + ret->metrics[1].value.u64 = 0; + ret->metrics[1].name = "evt_count"; - return ret; + return ret; } -void plugin_destroy(ss_plugin_t* s) -{ - delete reinterpret_cast(s); +void plugin_destroy(ss_plugin_t* s) { + delete reinterpret_cast(s); } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_event_parse_input* in) -{ - auto ps = reinterpret_cast(s); - ps->count++; - ps->metrics[1].value.u64 = ps->count; +ss_plugin_rc plugin_parse_event(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_event_parse_input* in) { + auto ps = reinterpret_cast(s); + ps->count++; + ps->metrics[1].value.u64 = ps->count; - return SS_PLUGIN_SUCCESS; + return SS_PLUGIN_SUCCESS; } -ss_plugin_metric* plugin_get_metrics(ss_plugin_t *s, uint32_t *num_metrics) -{ - auto ps = reinterpret_cast(s); +ss_plugin_metric* plugin_get_metrics(ss_plugin_t* s, uint32_t* num_metrics) { + auto ps = reinterpret_cast(s); - *num_metrics = sizeof(ps->metrics) / sizeof(ss_plugin_metric); + *num_metrics = sizeof(ps->metrics) / sizeof(ss_plugin_metric); - return ps->metrics; + return ps->metrics; } -} // anonymous namespace - -void get_plugin_api_sample_metrics(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); - out.get_required_api_version = plugin_get_required_api_version; - out.get_version = plugin_get_version; - out.get_description = plugin_get_description; - out.get_contact = plugin_get_contact; - out.get_name = plugin_get_name; - out.get_last_error = plugin_get_last_error; - out.init = plugin_init; - out.destroy = plugin_destroy; - out.get_parse_event_sources = plugin_get_parse_event_sources; - out.get_parse_event_types = plugin_get_parse_event_types; - out.parse_event = plugin_parse_event; - out.get_metrics = plugin_get_metrics; +} // anonymous namespace + +void get_plugin_api_sample_metrics(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); + out.get_required_api_version = plugin_get_required_api_version; + out.get_version = plugin_get_version; + out.get_description = plugin_get_description; + out.get_contact = plugin_get_contact; + out.get_name = plugin_get_name; + out.get_last_error = plugin_get_last_error; + out.init = plugin_init; + out.destroy = plugin_destroy; + out.get_parse_event_sources = plugin_get_parse_event_sources; + out.get_parse_event_types = plugin_get_parse_event_types; + out.parse_event = plugin_parse_event; + out.get_metrics = plugin_get_metrics; } diff --git a/userspace/libsinsp/test/plugins/plugin_extract.cpp b/userspace/libsinsp/test/plugins/plugin_extract.cpp index 9099f37c4e..911092e24c 100644 --- a/userspace/libsinsp/test/plugins/plugin_extract.cpp +++ b/userspace/libsinsp/test/plugins/plugin_extract.cpp @@ -32,151 +32,131 @@ namespace { * - Is compatible with the "sample" event source only * - Extracts a simple field containing the string inside the events' payload */ -struct plugin_state -{ - std::string lasterr; - std::string strstorage; - const char* strptr; - std::vector event_types; - ss_plugin_owner_t* owner; - ss_plugin_log_fn_t log; +struct plugin_state { + std::string lasterr; + std::string strstorage; + const char* strptr; + std::vector event_types; + ss_plugin_owner_t* owner; + ss_plugin_log_fn_t log; }; -const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ - return "0.1.0"; +const char* plugin_get_version() { + return "0.1.0"; } -const char* plugin_get_name() -{ - return "sample_plugin_extract"; +const char* plugin_get_name() { + return "sample_plugin_extract"; } -const char* plugin_get_description() -{ - return "some desc"; +const char* plugin_get_description() { + return "some desc"; } -const char* plugin_get_contact() -{ - return "some contact"; +const char* plugin_get_contact() { + return "some contact"; } -const char* plugin_get_fields() -{ - return - "[" \ - "{\"type\": \"string\", \"name\": \"sample.hello\", \"desc\": \"A constant hello world string\"}" \ - "]"; +const char* plugin_get_fields() { + return "[" + "{\"type\": \"string\", \"name\": \"sample.hello\", \"desc\": \"A constant hello world " + "string\"}" + "]"; } -const char* plugin_get_extract_event_sources() -{ - return "[\"sample\"]"; +const char* plugin_get_extract_event_sources() { + return "[\"sample\"]"; } -uint16_t* plugin_get_extract_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - auto ps = reinterpret_cast(s); - if (!ps->event_types.empty()) - { - *num_types = (uint32_t) ps->event_types.size(); - return ps->event_types.data(); - } - - static uint16_t *types = {}; - *num_types = 0; - return types; +uint16_t* plugin_get_extract_event_types(uint32_t* num_types, ss_plugin_t* s) { + auto ps = reinterpret_cast(s); + if(!ps->event_types.empty()) { + *num_types = (uint32_t)ps->event_types.size(); + return ps->event_types.data(); + } + + static uint16_t* types = {}; + *num_types = 0; + return types; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - auto ret = new plugin_state(); - - //save logger and owner in the state - ret->log = in->log_fn; - ret->owner = in->owner; - - ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); - - // init config may indicate the comma-separated, event-types to filter - std::string cfg = in->config; - if (!cfg.empty()) - { - if (cfg.back() != ',') - { - cfg += ","; - } - std::string val; - std::stringstream test(cfg); - while(std::getline(test, val, ',')) - { - auto v = std::atoi(val.c_str()); - if (v == 0) - { - ret->lasterr = "invalid init config string: " + cfg; - return ret; - } - ret->event_types.push_back((uint16_t) v); - } - } - - *rc = SS_PLUGIN_SUCCESS; - return ret; +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + auto ret = new plugin_state(); + + // save logger and owner in the state + ret->log = in->log_fn; + ret->owner = in->owner; + + ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); + + // init config may indicate the comma-separated, event-types to filter + std::string cfg = in->config; + if(!cfg.empty()) { + if(cfg.back() != ',') { + cfg += ","; + } + std::string val; + std::stringstream test(cfg); + while(std::getline(test, val, ',')) { + auto v = std::atoi(val.c_str()); + if(v == 0) { + ret->lasterr = "invalid init config string: " + cfg; + return ret; + } + ret->event_types.push_back((uint16_t)v); + } + } + + *rc = SS_PLUGIN_SUCCESS; + return ret; } -void plugin_destroy(ss_plugin_t* s) -{ - auto ps = reinterpret_cast(s); - ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); +void plugin_destroy(ss_plugin_t* s) { + auto ps = reinterpret_cast(s); + ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); - delete ps; + delete ps; } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_rc plugin_extract_fields(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_field_extract_input* in) -{ - auto ps = reinterpret_cast(s); - for (uint32_t i = 0; i < in->num_fields; i++) - { - switch(in->fields[i].field_id) - { - case 0: // test.hello - ps->strstorage = "hello world"; - ps->strptr = ps->strstorage.c_str(); - in->fields[i].res.str = &ps->strptr; - in->fields[i].res_len = 1; - break; - default: - in->fields[i].res_len = 0; - return SS_PLUGIN_FAILURE; - } - } - return SS_PLUGIN_SUCCESS; +ss_plugin_rc plugin_extract_fields(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_field_extract_input* in) { + auto ps = reinterpret_cast(s); + for(uint32_t i = 0; i < in->num_fields; i++) { + switch(in->fields[i].field_id) { + case 0: // test.hello + ps->strstorage = "hello world"; + ps->strptr = ps->strstorage.c_str(); + in->fields[i].res.str = &ps->strptr; + in->fields[i].res_len = 1; + break; + default: + in->fields[i].res_len = 0; + return SS_PLUGIN_FAILURE; + } + } + return SS_PLUGIN_SUCCESS; } -ss_plugin_rc plugin_set_config(ss_plugin_t *s, const ss_plugin_set_config_input* i) -{ - auto ps = reinterpret_cast(s); - ps->log(ps->owner, NULL, "new config!", SS_PLUGIN_LOG_SEV_INFO); +ss_plugin_rc plugin_set_config(ss_plugin_t* s, const ss_plugin_set_config_input* i) { + auto ps = reinterpret_cast(s); + ps->log(ps->owner, NULL, "new config!", SS_PLUGIN_LOG_SEV_INFO); - return SS_PLUGIN_SUCCESS; + return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_plugin_extract(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); +void get_plugin_api_sample_plugin_extract(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; out.get_description = plugin_get_description; @@ -185,9 +165,9 @@ void get_plugin_api_sample_plugin_extract(plugin_api& out) out.get_last_error = plugin_get_last_error; out.init = plugin_init; out.destroy = plugin_destroy; - out.get_fields = plugin_get_fields; - out.get_extract_event_sources = plugin_get_extract_event_sources; - out.get_extract_event_types = plugin_get_extract_event_types; - out.extract_fields = plugin_extract_fields; - out.set_config = plugin_set_config; + out.get_fields = plugin_get_fields; + out.get_extract_event_sources = plugin_get_extract_event_sources; + out.get_extract_event_types = plugin_get_extract_event_types; + out.extract_fields = plugin_extract_fields; + out.set_config = plugin_set_config; } diff --git a/userspace/libsinsp/test/plugins/plugin_source.cpp b/userspace/libsinsp/test/plugins/plugin_source.cpp index 6115ace32f..85182c93cb 100644 --- a/userspace/libsinsp/test/plugins/plugin_source.cpp +++ b/userspace/libsinsp/test/plugins/plugin_source.cpp @@ -34,149 +34,138 @@ static constexpr const char* s_evt_data = "hello world"; * - Implements a specific event source "sample" * - Sources plugin events containing a sample string */ -struct plugin_state -{ - std::string lasterr; - ss_plugin_owner_t* owner; - ss_plugin_log_fn_t log; +struct plugin_state { + std::string lasterr; + ss_plugin_owner_t* owner; + ss_plugin_log_fn_t log; }; -struct instance_state -{ - uint64_t count; - uint8_t evt_buf[2048]; - ss_plugin_event* evt; +struct instance_state { + uint64_t count; + uint8_t evt_buf[2048]; + ss_plugin_event* evt; }; -const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ - return "0.1.0"; +const char* plugin_get_version() { + return "0.1.0"; } -const char* plugin_get_name() -{ - return "sample_plugin_source"; +const char* plugin_get_name() { + return "sample_plugin_source"; } -const char* plugin_get_description() -{ - return "some desc"; +const char* plugin_get_description() { + return "some desc"; } -const char* plugin_get_contact() -{ - return "some contact"; +const char* plugin_get_contact() { + return "some contact"; } -uint32_t plugin_get_id() -{ +uint32_t plugin_get_id() { return 999; } -const char* plugin_get_event_source() -{ +const char* plugin_get_event_source() { return "sample"; } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - auto ret = new plugin_state(); +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + auto ret = new plugin_state(); - //save logger and owner in the state - ret->log = in->log_fn; - ret->owner = in->owner; + // save logger and owner in the state + ret->log = in->log_fn; + ret->owner = in->owner; - ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); + ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); - *rc = SS_PLUGIN_SUCCESS; - return ret; + *rc = SS_PLUGIN_SUCCESS; + return ret; } -void plugin_destroy(ss_plugin_t* s) -{ - auto ps = reinterpret_cast(s); - ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); +void plugin_destroy(ss_plugin_t* s) { + auto ps = reinterpret_cast(s); + ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); - delete ps; + delete ps; } -ss_instance_t* plugin_open(ss_plugin_t* s, const char* params, ss_plugin_rc* rc) -{ - auto ret = new instance_state(); - ret->evt = (ss_plugin_event*) &ret->evt_buf; - ret->count = 10000; - auto count = atoi(params); - if (count > 0) - { - ret->count = (uint64_t) count; - } - - *rc = SS_PLUGIN_SUCCESS; - return ret; +ss_instance_t* plugin_open(ss_plugin_t* s, const char* params, ss_plugin_rc* rc) { + auto ret = new instance_state(); + ret->evt = (ss_plugin_event*)&ret->evt_buf; + ret->count = 10000; + auto count = atoi(params); + if(count > 0) { + ret->count = (uint64_t)count; + } + + *rc = SS_PLUGIN_SUCCESS; + return ret; } -void plugin_close(ss_plugin_t* s, ss_instance_t* i) -{ - delete ((instance_state *) i); +void plugin_close(ss_plugin_t* s, ss_instance_t* i) { + delete((instance_state*)i); } -ss_plugin_rc plugin_next_batch(ss_plugin_t* s, ss_instance_t* i, uint32_t *nevts, ss_plugin_event ***evts) -{ - instance_state *istate = (instance_state *) i; +ss_plugin_rc plugin_next_batch(ss_plugin_t* s, + ss_instance_t* i, + uint32_t* nevts, + ss_plugin_event*** evts) { + instance_state* istate = (instance_state*)i; - if (istate->count == 0) - { - *nevts = 0; - return SS_PLUGIN_EOF; - } + if(istate->count == 0) { + *nevts = 0; + return SS_PLUGIN_EOF; + } - *nevts = 1; - *evts = &istate->evt; + *nevts = 1; + *evts = &istate->evt; - char error[SCAP_LASTERR_SIZE]; + char error[SCAP_LASTERR_SIZE]; - int32_t encode_res = scap_event_encode_params(scap_sized_buffer{istate->evt, sizeof(istate->evt_buf)}, - nullptr, error, PPME_PLUGINEVENT_E, 2, - plugin_get_id(), scap_sized_buffer{(void*) s_evt_data, strlen(s_evt_data) + 1}); + int32_t encode_res = + scap_event_encode_params(scap_sized_buffer{istate->evt, sizeof(istate->evt_buf)}, + nullptr, + error, + PPME_PLUGINEVENT_E, + 2, + plugin_get_id(), + scap_sized_buffer{(void*)s_evt_data, strlen(s_evt_data) + 1}); - if (encode_res == SCAP_FAILURE) - { - return SS_PLUGIN_FAILURE; - } + if(encode_res == SCAP_FAILURE) { + return SS_PLUGIN_FAILURE; + } - istate->evt->tid = -1; - istate->evt->ts = UINT64_MAX; + istate->evt->tid = -1; + istate->evt->ts = UINT64_MAX; - istate->count--; - return SS_PLUGIN_SUCCESS; + istate->count--; + return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_plugin_source(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); +void get_plugin_api_sample_plugin_source(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; out.get_description = plugin_get_description; out.get_contact = plugin_get_contact; out.get_name = plugin_get_name; - out.get_id = plugin_get_id; - out.get_event_source = plugin_get_event_source; + out.get_id = plugin_get_id; + out.get_event_source = plugin_get_event_source; out.get_last_error = plugin_get_last_error; out.init = plugin_init; out.destroy = plugin_destroy; - out.open = plugin_open; - out.close = plugin_close; - out.next_batch = plugin_next_batch; + out.open = plugin_open; + out.close = plugin_close; + out.next_batch = plugin_next_batch; } diff --git a/userspace/libsinsp/test/plugins/routines.cpp b/userspace/libsinsp/test/plugins/routines.cpp index 5a52480894..180487a09a 100644 --- a/userspace/libsinsp/test/plugins/routines.cpp +++ b/userspace/libsinsp/test/plugins/routines.cpp @@ -22,147 +22,135 @@ limitations under the License. #include #include -struct plugin_state -{ - std::string lasterr; - ss_plugin_owner_t *owner; - ss_plugin_routine_vtable routine_vtable; - - uint8_t step = 1; - std::atomic flag = true; - ss_plugin_routine_t *routine; +struct plugin_state { + std::string lasterr; + ss_plugin_owner_t* owner; + ss_plugin_routine_vtable routine_vtable; + + uint8_t step = 1; + std::atomic flag = true; + ss_plugin_routine_t* routine; }; -static const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +static const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -static const char* plugin_get_version() -{ - return "0.1.0"; +static const char* plugin_get_version() { + return "0.1.0"; } -static const char* plugin_get_name() -{ - return "sample_routines"; +static const char* plugin_get_name() { + return "sample_routines"; } -static const char* plugin_get_description() -{ - return "some desc"; +static const char* plugin_get_description() { + return "some desc"; } -static const char* plugin_get_contact() -{ - return "some contact"; +static const char* plugin_get_contact() { + return "some contact"; } -static const char* plugin_get_parse_event_sources() -{ - return "[\"syscall\"]"; +static const char* plugin_get_parse_event_sources() { + return "[\"syscall\"]"; } -static uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - static uint16_t types[] = { - PPME_SYSCALL_OPEN_E, - }; - *num_types = sizeof(types) / sizeof(uint16_t); - return &types[0]; +static uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) { + static uint16_t types[] = { + PPME_SYSCALL_OPEN_E, + }; + *num_types = sizeof(types) / sizeof(uint16_t); + return &types[0]; } -static ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - *rc = SS_PLUGIN_SUCCESS; - plugin_state *ret = new plugin_state(); +static ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + *rc = SS_PLUGIN_SUCCESS; + plugin_state* ret = new plugin_state(); - ret->owner = in->owner; - - return ret; -} - -static void plugin_destroy(ss_plugin_t* s) -{ - delete ((plugin_state *) s); -} + ret->owner = in->owner; -static const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); + return ret; } -static ss_plugin_bool test_routine(ss_plugin_t *s, ss_plugin_routine_state_t *i) -{ - bool flag = *(bool*)i; - - //this routine keeps running while flag is true - return flag; +static void plugin_destroy(ss_plugin_t* s) { + delete((plugin_state*)s); } -static ss_plugin_bool do_nothing(ss_plugin_t *s, ss_plugin_routine_state_t *i) -{ - //this routine always keeps running - return true; +static const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -static ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_event_parse_input* in) -{ - plugin_state *ps = (plugin_state *) s; +static ss_plugin_bool test_routine(ss_plugin_t* s, ss_plugin_routine_state_t* i) { + bool flag = *(bool*)i; - switch (ps->step) - { - case 1: - ps->routine = ps->routine_vtable.subscribe(ps->owner, do_nothing, (ss_plugin_routine_state_t*)&ps->flag); - break; - case 2: - ps->routine_vtable.unsubscribe(ps->owner, ps->routine); - break; - case 3: - ps->routine = ps->routine_vtable.subscribe(ps->owner, test_routine, (ss_plugin_routine_state_t*)&ps->flag); - break; - case 4: - ps->flag = false; - break; - default: - break; - } + // this routine keeps running while flag is true + return flag; +} - ps->step++; +static ss_plugin_bool do_nothing(ss_plugin_t* s, ss_plugin_routine_state_t* i) { + // this routine always keeps running + return true; +} - return SS_PLUGIN_SUCCESS; +static ss_plugin_rc plugin_parse_event(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_event_parse_input* in) { + plugin_state* ps = (plugin_state*)s; + + switch(ps->step) { + case 1: + ps->routine = ps->routine_vtable.subscribe(ps->owner, + do_nothing, + (ss_plugin_routine_state_t*)&ps->flag); + break; + case 2: + ps->routine_vtable.unsubscribe(ps->owner, ps->routine); + break; + case 3: + ps->routine = ps->routine_vtable.subscribe(ps->owner, + test_routine, + (ss_plugin_routine_state_t*)&ps->flag); + break; + case 4: + ps->flag = false; + break; + default: + break; + } + + ps->step++; + + return SS_PLUGIN_SUCCESS; } -static ss_plugin_rc plugin_capture_open(ss_plugin_t* s, const ss_plugin_capture_listen_input* i) -{ - plugin_state *ps = (plugin_state *) s; - ps->routine_vtable.subscribe = i->routine->subscribe; - ps->routine_vtable.unsubscribe = i->routine->unsubscribe; +static ss_plugin_rc plugin_capture_open(ss_plugin_t* s, const ss_plugin_capture_listen_input* i) { + plugin_state* ps = (plugin_state*)s; + ps->routine_vtable.subscribe = i->routine->subscribe; + ps->routine_vtable.unsubscribe = i->routine->unsubscribe; - ps->routine_vtable.subscribe(ps->owner, do_nothing, (ss_plugin_routine_state_t*)&ps->flag); + ps->routine_vtable.subscribe(ps->owner, do_nothing, (ss_plugin_routine_state_t*)&ps->flag); - return SS_PLUGIN_SUCCESS; + return SS_PLUGIN_SUCCESS; } -static ss_plugin_rc plugin_capture_close(ss_plugin_t* s, const ss_plugin_capture_listen_input* i) -{ - return SS_PLUGIN_SUCCESS; +static ss_plugin_rc plugin_capture_close(ss_plugin_t* s, const ss_plugin_capture_listen_input* i) { + return SS_PLUGIN_SUCCESS; } -void get_plugin_api_sample_routines(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); - out.get_required_api_version = plugin_get_required_api_version; - out.get_version = plugin_get_version; - out.get_description = plugin_get_description; - out.get_contact = plugin_get_contact; - out.get_name = plugin_get_name; - out.get_last_error = plugin_get_last_error; - out.init = plugin_init; - out.destroy = plugin_destroy; - out.get_parse_event_sources = plugin_get_parse_event_sources; - out.get_parse_event_types = plugin_get_parse_event_types; - out.parse_event = plugin_parse_event; - out.capture_open = plugin_capture_open; - out.capture_close = plugin_capture_close; -} \ No newline at end of file +void get_plugin_api_sample_routines(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); + out.get_required_api_version = plugin_get_required_api_version; + out.get_version = plugin_get_version; + out.get_description = plugin_get_description; + out.get_contact = plugin_get_contact; + out.get_name = plugin_get_name; + out.get_last_error = plugin_get_last_error; + out.init = plugin_init; + out.destroy = plugin_destroy; + out.get_parse_event_sources = plugin_get_parse_event_sources; + out.get_parse_event_types = plugin_get_parse_event_types; + out.parse_event = plugin_parse_event; + out.capture_open = plugin_capture_open; + out.capture_close = plugin_capture_close; +} diff --git a/userspace/libsinsp/test/plugins/sample_table.h b/userspace/libsinsp/test/plugins/sample_table.h index a172b89774..b7fe8bca19 100644 --- a/userspace/libsinsp/test/plugins/sample_table.h +++ b/userspace/libsinsp/test/plugins/sample_table.h @@ -29,285 +29,267 @@ limitations under the License. /** * @brief A simple plugin-implemented table with u64 keys used for test purposes. */ -class sample_table -{ +class sample_table { public: - class entry - { - public: - virtual ~entry() - { - // note: makes sure that release_table_entry is invoked consistently - if (refcount > 0) - { - fprintf(stderr, "sample_table: table entry deleted with non-zero refcount %ld\n", refcount); - exit(1); - } - for (auto &p : data) - { - delete p; - } - } - private: - std::vector data; - std::vector strings; - uint64_t refcount; - - friend class sample_table; - }; - - sample_table(const std::string& n, std::string& err): - name(n), lasterr(err), strings(), entries(), fields() { } - virtual ~sample_table() = default; - sample_table(sample_table&&) = default; - sample_table(const sample_table& s) = default; - - static const char* get_name(ss_plugin_table_t* _t) - { - auto t = static_cast(_t); - return t->name.c_str(); - } - - static uint64_t get_size(ss_plugin_table_t* _t) - { - auto t = static_cast(_t); - return t->entries.size(); - } - - static const ss_plugin_table_fieldinfo* list_fields(ss_plugin_table_t* _t, uint32_t* nfields) - { - auto t = static_cast(_t); - *nfields = (uint32_t) t->fields.size(); - return t->fields.data(); - } - - static ss_plugin_table_field_t* get_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type) - { - auto t = static_cast(_t); - for (size_t i = 0; i < t->fields.size(); i++) - { - if (strcmp(t->fields[i].name, name) == 0) - { - // note: shifted by 1 so that we never return 0 (interpreted as NULL) - return (ss_plugin_table_field_t*) (i + 1); - } - } - t->lasterr = "unknown field with name: " + std::string(name); - return nullptr; - } - - static ss_plugin_table_field_t* add_field(ss_plugin_table_t* _t, const char* name, ss_plugin_state_type data_type) - { - auto t = static_cast(_t); - for (size_t i = 0; i < t->fields.size(); i++) - { - const auto& f = t->fields[i]; - if (strcmp(f.name, name) == 0) - { - if (f.field_type != data_type) - { - t->lasterr = "field defined with incompatible types: " + std::string(name); - return NULL; - } - // note: shifted by 1 so that we never return 0 (interpreted as NULL) - return (ss_plugin_table_field_t*) (i + 1); - } - } - - ss_plugin_table_fieldinfo f; - t->strings.push_back(name); - f.field_type = data_type; - f.read_only = false; - t->fields.push_back(f); - for (size_t i = 0; i < t->fields.size(); i++) - { - // note: previous string pointers may have been changed so we - // we need to set all of them again - t->fields[i].name = t->strings[i].c_str(); - } - - // note: shifted by 1 so that we never return 0 (interpreted as NULL) - return (ss_plugin_table_field_t*) (t->fields.size()); - } - - static ss_plugin_table_entry_t *get_entry(ss_plugin_table_t *_t, const ss_plugin_state_data *key) - { - auto t = static_cast(_t); - auto it = t->entries.find(key->u64); - if (it != t->entries.end()) - { - it->second.refcount++; - return static_cast(&it->second); - } - t->lasterr = "unknown entry at key: " + std::to_string(key->u64); - return nullptr; - } - - static ss_plugin_rc read_entry_field(ss_plugin_table_t *_t, ss_plugin_table_entry_t *_e, const ss_plugin_table_field_t *_f, ss_plugin_state_data *out) - { - auto t = static_cast(_t); - auto e = static_cast(_e); - auto f = size_t (_f) - 1; - while (e->data.size() <= f) - { - e->data.push_back(new ss_plugin_state_data()); - e->strings.emplace_back(); - } - if (t->fields[f].field_type == SS_PLUGIN_ST_STRING) - { - out->str = e->strings[f].c_str(); - } - else - { - memcpy(out, e->data[f], sizeof(ss_plugin_state_data)); - } - return SS_PLUGIN_SUCCESS; - } - - static void release_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e) - { - auto e = static_cast(_e); - e->refcount--; - } - - static ss_plugin_bool iterate_entries(ss_plugin_table_t* _t, ss_plugin_table_iterator_func_t it, ss_plugin_table_iterator_state_t* s) - { - auto t = static_cast(_t); - for (auto& [k, e]: t->entries) - { - if (it(s, static_cast(&e)) != 1) - { - return 0; - } - } - return 1; - } - - static ss_plugin_rc clear(ss_plugin_table_t *_t) - { - auto t = static_cast(_t); - t->entries.clear(); - return SS_PLUGIN_SUCCESS; - } - - static ss_plugin_rc erase_entry(ss_plugin_table_t *_t, const ss_plugin_state_data *key) - { - auto t = static_cast(_t); - auto it = t->entries.find(key->u64); - if (it != t->entries.end()) - { - t->entries.erase(key->u64); - return SS_PLUGIN_SUCCESS;; - } - t->lasterr = "unknown entry at key: " + std::to_string(key->u64); - return SS_PLUGIN_FAILURE; - } - - static ss_plugin_table_entry_t *create_entry(ss_plugin_table_t *t) - { - auto e = new sample_table::entry(); - e->refcount = 1; - return static_cast(e); - } - - static void destroy_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e) - { - auto e = static_cast(_e); - e->refcount = 0; - delete e; - } - - static ss_plugin_table_entry_t *add_entry(ss_plugin_table_t *_t, const ss_plugin_state_data *key, ss_plugin_table_entry_t *_e) - { - auto t = static_cast(_t); - auto e = static_cast(_e); - e->refcount = 0; - t->entries.insert({ key->u64, *e }); - delete e; - t->entries[key->u64].refcount = 1; - return static_cast(&t->entries[key->u64]); - } - - static ss_plugin_rc write_entry_field(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e, const ss_plugin_table_field_t* _f, const ss_plugin_state_data* in) - { - auto t = static_cast(_t); - auto e = static_cast(_e); - auto f = size_t (_f) - 1; - while (e->data.size() <= f) - { - e->data.push_back(new ss_plugin_state_data()); - e->strings.emplace_back(); - } - if (t->fields[f].field_type == SS_PLUGIN_ST_STRING) - { - e->strings[f] = in->str; - } - else - { - memcpy(e->data[f], in, sizeof(ss_plugin_state_data)); - } - return SS_PLUGIN_SUCCESS; - } - - struct deleter_t - { - void operator()(ss_plugin_table_input* t) - { - delete static_cast(t->table); - delete t; - } - }; - - using ptr_t = std::unique_ptr; - - static ptr_t create(const std::string& name, std::string& lasterr) - { - auto t = new sample_table(name, lasterr); - ptr_t ret(new ss_plugin_table_input()); - ret->name = t->name.c_str(); - ret->table = t; - ret->key_type = ss_plugin_state_type::SS_PLUGIN_ST_UINT64; - ret->reader_ext = &t->reader_vtable; - ret->writer_ext = &t->writer_vtable; - ret->fields_ext = &t->fields_vtable; - ret->fields_ext->list_table_fields = list_fields; - ret->fields_ext->get_table_field = get_field; - ret->fields_ext->add_table_field = add_field; - ret->fields.list_table_fields = ret->fields_ext->list_table_fields; - ret->fields.get_table_field = ret->fields_ext->get_table_field; - ret->fields.add_table_field = ret->fields_ext->add_table_field; - ret->reader_ext->get_table_name = get_name; - ret->reader_ext->get_table_size = get_size; - ret->reader_ext->get_table_entry = get_entry; - ret->reader_ext->read_entry_field = read_entry_field; - ret->reader_ext->release_table_entry = release_table_entry; - ret->reader_ext->iterate_entries = iterate_entries; - ret->reader.get_table_name = ret->reader_ext->get_table_name; - ret->reader.get_table_size = ret->reader_ext->get_table_size; - ret->reader.get_table_entry = ret->reader_ext->get_table_entry; - ret->reader.read_entry_field = ret->reader_ext->read_entry_field; - ret->writer_ext->clear_table = clear; - ret->writer_ext->erase_table_entry = erase_entry; - ret->writer_ext->create_table_entry = create_entry; - ret->writer_ext->destroy_table_entry = destroy_entry; - ret->writer_ext->add_table_entry = add_entry; - ret->writer_ext->write_entry_field = write_entry_field; - ret->writer.clear_table = ret->writer_ext->clear_table; - ret->writer.erase_table_entry = ret->writer_ext->erase_table_entry; - ret->writer.create_table_entry = ret->writer_ext->create_table_entry; - ret->writer.destroy_table_entry = ret->writer_ext->destroy_table_entry; - ret->writer.add_table_entry = ret->writer_ext->add_table_entry; - ret->writer.write_entry_field = ret->writer_ext->write_entry_field; - return ret; - } + class entry { + public: + virtual ~entry() { + // note: makes sure that release_table_entry is invoked consistently + if(refcount > 0) { + fprintf(stderr, + "sample_table: table entry deleted with non-zero refcount %ld\n", + refcount); + exit(1); + } + for(auto& p : data) { + delete p; + } + } + + private: + std::vector data; + std::vector strings; + uint64_t refcount; + + friend class sample_table; + }; + + sample_table(const std::string& n, std::string& err): + name(n), + lasterr(err), + strings(), + entries(), + fields() {} + virtual ~sample_table() = default; + sample_table(sample_table&&) = default; + sample_table(const sample_table& s) = default; + + static const char* get_name(ss_plugin_table_t* _t) { + auto t = static_cast(_t); + return t->name.c_str(); + } + + static uint64_t get_size(ss_plugin_table_t* _t) { + auto t = static_cast(_t); + return t->entries.size(); + } + + static const ss_plugin_table_fieldinfo* list_fields(ss_plugin_table_t* _t, uint32_t* nfields) { + auto t = static_cast(_t); + *nfields = (uint32_t)t->fields.size(); + return t->fields.data(); + } + + static ss_plugin_table_field_t* get_field(ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type) { + auto t = static_cast(_t); + for(size_t i = 0; i < t->fields.size(); i++) { + if(strcmp(t->fields[i].name, name) == 0) { + // note: shifted by 1 so that we never return 0 (interpreted as NULL) + return (ss_plugin_table_field_t*)(i + 1); + } + } + t->lasterr = "unknown field with name: " + std::string(name); + return nullptr; + } + + static ss_plugin_table_field_t* add_field(ss_plugin_table_t* _t, + const char* name, + ss_plugin_state_type data_type) { + auto t = static_cast(_t); + for(size_t i = 0; i < t->fields.size(); i++) { + const auto& f = t->fields[i]; + if(strcmp(f.name, name) == 0) { + if(f.field_type != data_type) { + t->lasterr = "field defined with incompatible types: " + std::string(name); + return NULL; + } + // note: shifted by 1 so that we never return 0 (interpreted as NULL) + return (ss_plugin_table_field_t*)(i + 1); + } + } + + ss_plugin_table_fieldinfo f; + t->strings.push_back(name); + f.field_type = data_type; + f.read_only = false; + t->fields.push_back(f); + for(size_t i = 0; i < t->fields.size(); i++) { + // note: previous string pointers may have been changed so we + // we need to set all of them again + t->fields[i].name = t->strings[i].c_str(); + } + + // note: shifted by 1 so that we never return 0 (interpreted as NULL) + return (ss_plugin_table_field_t*)(t->fields.size()); + } + + static ss_plugin_table_entry_t* get_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key) { + auto t = static_cast(_t); + auto it = t->entries.find(key->u64); + if(it != t->entries.end()) { + it->second.refcount++; + return static_cast(&it->second); + } + t->lasterr = "unknown entry at key: " + std::to_string(key->u64); + return nullptr; + } + + static ss_plugin_rc read_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* _e, + const ss_plugin_table_field_t* _f, + ss_plugin_state_data* out) { + auto t = static_cast(_t); + auto e = static_cast(_e); + auto f = size_t(_f) - 1; + while(e->data.size() <= f) { + e->data.push_back(new ss_plugin_state_data()); + e->strings.emplace_back(); + } + if(t->fields[f].field_type == SS_PLUGIN_ST_STRING) { + out->str = e->strings[f].c_str(); + } else { + memcpy(out, e->data[f], sizeof(ss_plugin_state_data)); + } + return SS_PLUGIN_SUCCESS; + } + + static void release_table_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e) { + auto e = static_cast(_e); + e->refcount--; + } + + static ss_plugin_bool iterate_entries(ss_plugin_table_t* _t, + ss_plugin_table_iterator_func_t it, + ss_plugin_table_iterator_state_t* s) { + auto t = static_cast(_t); + for(auto& [k, e] : t->entries) { + if(it(s, static_cast(&e)) != 1) { + return 0; + } + } + return 1; + } + + static ss_plugin_rc clear(ss_plugin_table_t* _t) { + auto t = static_cast(_t); + t->entries.clear(); + return SS_PLUGIN_SUCCESS; + } + + static ss_plugin_rc erase_entry(ss_plugin_table_t* _t, const ss_plugin_state_data* key) { + auto t = static_cast(_t); + auto it = t->entries.find(key->u64); + if(it != t->entries.end()) { + t->entries.erase(key->u64); + return SS_PLUGIN_SUCCESS; + ; + } + t->lasterr = "unknown entry at key: " + std::to_string(key->u64); + return SS_PLUGIN_FAILURE; + } + + static ss_plugin_table_entry_t* create_entry(ss_plugin_table_t* t) { + auto e = new sample_table::entry(); + e->refcount = 1; + return static_cast(e); + } + + static void destroy_entry(ss_plugin_table_t* _t, ss_plugin_table_entry_t* _e) { + auto e = static_cast(_e); + e->refcount = 0; + delete e; + } + + static ss_plugin_table_entry_t* add_entry(ss_plugin_table_t* _t, + const ss_plugin_state_data* key, + ss_plugin_table_entry_t* _e) { + auto t = static_cast(_t); + auto e = static_cast(_e); + e->refcount = 0; + t->entries.insert({key->u64, *e}); + delete e; + t->entries[key->u64].refcount = 1; + return static_cast(&t->entries[key->u64]); + } + + static ss_plugin_rc write_entry_field(ss_plugin_table_t* _t, + ss_plugin_table_entry_t* _e, + const ss_plugin_table_field_t* _f, + const ss_plugin_state_data* in) { + auto t = static_cast(_t); + auto e = static_cast(_e); + auto f = size_t(_f) - 1; + while(e->data.size() <= f) { + e->data.push_back(new ss_plugin_state_data()); + e->strings.emplace_back(); + } + if(t->fields[f].field_type == SS_PLUGIN_ST_STRING) { + e->strings[f] = in->str; + } else { + memcpy(e->data[f], in, sizeof(ss_plugin_state_data)); + } + return SS_PLUGIN_SUCCESS; + } + + struct deleter_t { + void operator()(ss_plugin_table_input* t) { + delete static_cast(t->table); + delete t; + } + }; + + using ptr_t = std::unique_ptr; + + static ptr_t create(const std::string& name, std::string& lasterr) { + auto t = new sample_table(name, lasterr); + ptr_t ret(new ss_plugin_table_input()); + ret->name = t->name.c_str(); + ret->table = t; + ret->key_type = ss_plugin_state_type::SS_PLUGIN_ST_UINT64; + ret->reader_ext = &t->reader_vtable; + ret->writer_ext = &t->writer_vtable; + ret->fields_ext = &t->fields_vtable; + ret->fields_ext->list_table_fields = list_fields; + ret->fields_ext->get_table_field = get_field; + ret->fields_ext->add_table_field = add_field; + ret->fields.list_table_fields = ret->fields_ext->list_table_fields; + ret->fields.get_table_field = ret->fields_ext->get_table_field; + ret->fields.add_table_field = ret->fields_ext->add_table_field; + ret->reader_ext->get_table_name = get_name; + ret->reader_ext->get_table_size = get_size; + ret->reader_ext->get_table_entry = get_entry; + ret->reader_ext->read_entry_field = read_entry_field; + ret->reader_ext->release_table_entry = release_table_entry; + ret->reader_ext->iterate_entries = iterate_entries; + ret->reader.get_table_name = ret->reader_ext->get_table_name; + ret->reader.get_table_size = ret->reader_ext->get_table_size; + ret->reader.get_table_entry = ret->reader_ext->get_table_entry; + ret->reader.read_entry_field = ret->reader_ext->read_entry_field; + ret->writer_ext->clear_table = clear; + ret->writer_ext->erase_table_entry = erase_entry; + ret->writer_ext->create_table_entry = create_entry; + ret->writer_ext->destroy_table_entry = destroy_entry; + ret->writer_ext->add_table_entry = add_entry; + ret->writer_ext->write_entry_field = write_entry_field; + ret->writer.clear_table = ret->writer_ext->clear_table; + ret->writer.erase_table_entry = ret->writer_ext->erase_table_entry; + ret->writer.create_table_entry = ret->writer_ext->create_table_entry; + ret->writer.destroy_table_entry = ret->writer_ext->destroy_table_entry; + ret->writer.add_table_entry = ret->writer_ext->add_table_entry; + ret->writer.write_entry_field = ret->writer_ext->write_entry_field; + return ret; + } private: - std::string name; - std::string& lasterr; - std::vector strings; - std::unordered_map entries; - std::vector fields; - ss_plugin_table_reader_vtable_ext reader_vtable; - ss_plugin_table_writer_vtable_ext writer_vtable; - ss_plugin_table_fields_vtable_ext fields_vtable; + std::string name; + std::string& lasterr; + std::vector strings; + std::unordered_map entries; + std::vector fields; + ss_plugin_table_reader_vtable_ext reader_vtable; + ss_plugin_table_writer_vtable_ext writer_vtable; + ss_plugin_table_fields_vtable_ext fields_vtable; }; diff --git a/userspace/libsinsp/test/plugins/syscall_async.cpp b/userspace/libsinsp/test/plugins/syscall_async.cpp index 44b2b180ea..b247b12ac7 100644 --- a/userspace/libsinsp/test/plugins/syscall_async.cpp +++ b/userspace/libsinsp/test/plugins/syscall_async.cpp @@ -35,171 +35,163 @@ namespace { * - Defines only one async event name * - Sends an async event periodically given the configured time period */ -struct plugin_state -{ - std::string lasterr; - uint64_t async_period; - uint64_t async_maxevts; - std::thread async_thread; - std::atomic async_thread_run; - uint8_t async_evt_buf[2048]; - ss_plugin_event* async_evt; - ss_plugin_owner_t* owner; - ss_plugin_log_fn_t log; +struct plugin_state { + std::string lasterr; + uint64_t async_period; + uint64_t async_maxevts; + std::thread async_thread; + std::atomic async_thread_run; + uint8_t async_evt_buf[2048]; + ss_plugin_event* async_evt; + ss_plugin_owner_t* owner; + ss_plugin_log_fn_t log; }; -const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ - return "0.1.0"; +const char* plugin_get_version() { + return "0.1.0"; } -const char* plugin_get_name() -{ - return "sample_syscall_async"; +const char* plugin_get_name() { + return "sample_syscall_async"; } -const char* plugin_get_description() -{ - return "some desc"; +const char* plugin_get_description() { + return "some desc"; } -const char* plugin_get_contact() -{ - return "some contact"; +const char* plugin_get_contact() { + return "some contact"; } -const char* plugin_get_async_event_sources() -{ - return "[\"syscall\"]"; +const char* plugin_get_async_event_sources() { + return "[\"syscall\"]"; } -const char* plugin_get_async_events() -{ - return "[\"sampleticker\"]"; +const char* plugin_get_async_events() { + return "[\"sampleticker\"]"; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - *rc = SS_PLUGIN_SUCCESS; - auto ret = new plugin_state(); - - //save logger and owner in the state - ret->log = in->log_fn; - ret->owner = in->owner; - - ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); - - ret->async_evt = (ss_plugin_event*) &ret->async_evt_buf; - ret->async_thread_run = false; - if (2 != sscanf(in->config, "%ld:%ld", &ret->async_maxevts, &ret->async_period)) - { - ret->async_period = 1000000; - ret->async_maxevts = 100; - } - return ret; +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + *rc = SS_PLUGIN_SUCCESS; + auto ret = new plugin_state(); + + // save logger and owner in the state + ret->log = in->log_fn; + ret->owner = in->owner; + + ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); + + ret->async_evt = (ss_plugin_event*)&ret->async_evt_buf; + ret->async_thread_run = false; + if(2 != sscanf(in->config, "%ld:%ld", &ret->async_maxevts, &ret->async_period)) { + ret->async_period = 1000000; + ret->async_maxevts = 100; + } + return ret; } -void plugin_destroy(ss_plugin_t* s) -{ - auto ps = reinterpret_cast(s); - ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); - - // stop the async thread if it's running - if (ps->async_thread_run) - { - ps->async_thread_run = false; - if (ps->async_thread.joinable()) - { - ps->async_thread.join(); - } - } - - delete ps; +void plugin_destroy(ss_plugin_t* s) { + auto ps = reinterpret_cast(s); + ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); + + // stop the async thread if it's running + if(ps->async_thread_run) { + ps->async_thread_run = false; + if(ps->async_thread.joinable()) { + ps->async_thread.join(); + } + } + + delete ps; } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_rc plugin_set_async_event_handler(ss_plugin_t* s, ss_plugin_owner_t* owner, const ss_plugin_async_event_handler_t handler) -{ - auto ps = reinterpret_cast(s); - - // stop the async thread if it's running - if (ps->async_thread_run) - { - ps->async_thread_run = false; - if (ps->async_thread.joinable()) - { - ps->async_thread.join(); - } - } - - // launch the async thread with the handler, if one is provided - if (handler) - { - ps->async_thread_run = true; - ps->async_thread = std::thread([ps, owner, handler]() - { - char err[PLUGIN_MAX_ERRLEN]; - const char* name = "sampleticker"; - const char* data = "sample ticker notification"; - for (uint64_t i = 0; i < ps->async_maxevts && ps->async_thread_run; i++) - { - // attempt sending an event that is not in the allowed name list - scap_event_encode_params(scap_sized_buffer{ps->async_evt, sizeof(ps->async_evt_buf)}, nullptr, err, - PPME_ASYNCEVENT_E, 3, 0, "unsupportedname", scap_const_sized_buffer{data, strlen(data) + 1}); - ps->async_evt->tid = 1; - - if (SS_PLUGIN_SUCCESS == handler(owner, ps->async_evt, err)) - { - printf("sample_syscall_async: unexpected success in sending unsupported asynchronous event from plugin\n"); - exit(1); - } - - // send an event in the allowed name list - // note: we set a tid=1 to test that async events can have - // either an empty (-1) or a non-empty tid value - scap_event_encode_params(scap_sized_buffer{ps->async_evt, sizeof(ps->async_evt_buf)}, nullptr, err, - PPME_ASYNCEVENT_E, 3, 0, name, scap_const_sized_buffer{data, strlen(data) + 1}); - ps->async_evt->tid = 1; - - if (SS_PLUGIN_SUCCESS != handler(owner, ps->async_evt, err)) - { - printf("sample_syscall_async: unexpected failure in sending asynchronous event from plugin: %s\n", err); - exit(1); - } +ss_plugin_rc plugin_set_async_event_handler(ss_plugin_t* s, + ss_plugin_owner_t* owner, + const ss_plugin_async_event_handler_t handler) { + auto ps = reinterpret_cast(s); + + // stop the async thread if it's running + if(ps->async_thread_run) { + ps->async_thread_run = false; + if(ps->async_thread.joinable()) { + ps->async_thread.join(); + } + } + + // launch the async thread with the handler, if one is provided + if(handler) { + ps->async_thread_run = true; + ps->async_thread = std::thread([ps, owner, handler]() { + char err[PLUGIN_MAX_ERRLEN]; + const char* name = "sampleticker"; + const char* data = "sample ticker notification"; + for(uint64_t i = 0; i < ps->async_maxevts && ps->async_thread_run; i++) { + // attempt sending an event that is not in the allowed name list + scap_event_encode_params( + scap_sized_buffer{ps->async_evt, sizeof(ps->async_evt_buf)}, + nullptr, + err, + PPME_ASYNCEVENT_E, + 3, + 0, + "unsupportedname", + scap_const_sized_buffer{data, strlen(data) + 1}); + ps->async_evt->tid = 1; + + if(SS_PLUGIN_SUCCESS == handler(owner, ps->async_evt, err)) { + printf("sample_syscall_async: unexpected success in sending unsupported " + "asynchronous event from plugin\n"); + exit(1); + } + + // send an event in the allowed name list + // note: we set a tid=1 to test that async events can have + // either an empty (-1) or a non-empty tid value + scap_event_encode_params( + scap_sized_buffer{ps->async_evt, sizeof(ps->async_evt_buf)}, + nullptr, + err, + PPME_ASYNCEVENT_E, + 3, + 0, + name, + scap_const_sized_buffer{data, strlen(data) + 1}); + ps->async_evt->tid = 1; + + if(SS_PLUGIN_SUCCESS != handler(owner, ps->async_evt, err)) { + printf("sample_syscall_async: unexpected failure in sending asynchronous event " + "from plugin: %s\n", + err); + exit(1); + } // sleep for a period - if(i < 2) - { + if(i < 2) { // sleep for 1ms std::this_thread::sleep_for(std::chrono::nanoseconds(ps->async_period)); - } - else - { + } else { // sleep for 1s - std::this_thread::sleep_for(std::chrono::nanoseconds(ps->async_period*1000)); + std::this_thread::sleep_for(std::chrono::nanoseconds(ps->async_period * 1000)); } + } + }); + } - } - }); - } - - return SS_PLUGIN_SUCCESS; + return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_syscall_async(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); +void get_plugin_api_sample_syscall_async(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; out.get_description = plugin_get_description; @@ -208,7 +200,7 @@ void get_plugin_api_sample_syscall_async(plugin_api& out) out.get_last_error = plugin_get_last_error; out.init = plugin_init; out.destroy = plugin_destroy; - out.get_async_event_sources = plugin_get_async_event_sources; - out.get_async_events = plugin_get_async_events; - out.set_async_event_handler = plugin_set_async_event_handler; + out.get_async_event_sources = plugin_get_async_event_sources; + out.get_async_events = plugin_get_async_events; + out.set_async_event_handler = plugin_set_async_event_handler; } diff --git a/userspace/libsinsp/test/plugins/syscall_extract.cpp b/userspace/libsinsp/test/plugins/syscall_extract.cpp index f7a2cc0c2d..03f57f8cda 100644 --- a/userspace/libsinsp/test/plugins/syscall_extract.cpp +++ b/userspace/libsinsp/test/plugins/syscall_extract.cpp @@ -34,68 +34,53 @@ namespace { * - Optionally accesses a field defined at runtime by another plugin on the thread table * - Optionally accesses a table defined at runtime by another plugin */ -struct plugin_state -{ - std::string lasterr; - uint64_t u64storage; - std::string strstorage; - const char* strptrstorage; - ss_plugin_table_t* thread_table; - ss_plugin_table_field_t* thread_comm_field; - ss_plugin_table_field_t* thread_opencount_field; - ss_plugin_table_t* evtcount_table; - ss_plugin_table_field_t* evtcount_count_field; - ss_plugin_owner_t* owner; - ss_plugin_log_fn_t log; +struct plugin_state { + std::string lasterr; + uint64_t u64storage; + std::string strstorage; + const char* strptrstorage; + ss_plugin_table_t* thread_table; + ss_plugin_table_field_t* thread_comm_field; + ss_plugin_table_field_t* thread_opencount_field; + ss_plugin_table_t* evtcount_table; + ss_plugin_table_field_t* evtcount_count_field; + ss_plugin_owner_t* owner; + ss_plugin_log_fn_t log; }; -inline bool evt_type_is_open(uint16_t type) -{ - return type == PPME_SYSCALL_OPEN_E - || type == PPME_SYSCALL_OPEN_X - || type == PPME_SYSCALL_OPENAT_E - || type == PPME_SYSCALL_OPENAT_X - || type == PPME_SYSCALL_OPENAT_2_E - || type == PPME_SYSCALL_OPENAT_2_X - || type == PPME_SYSCALL_OPENAT2_E - || type == PPME_SYSCALL_OPENAT2_X - || type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_E - || type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X - ; +inline bool evt_type_is_open(uint16_t type) { + return type == PPME_SYSCALL_OPEN_E || type == PPME_SYSCALL_OPEN_X || + type == PPME_SYSCALL_OPENAT_E || type == PPME_SYSCALL_OPENAT_X || + type == PPME_SYSCALL_OPENAT_2_E || type == PPME_SYSCALL_OPENAT_2_X || + type == PPME_SYSCALL_OPENAT2_E || type == PPME_SYSCALL_OPENAT2_X || + type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_E || type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X; } -inline const char* get_async_event_name(const ss_plugin_event* e) -{ - return (const char*) ((uint8_t*) e + sizeof(ss_plugin_event) + 4+4+4+4); +inline const char* get_async_event_name(const ss_plugin_event* e) { + return (const char*)((uint8_t*)e + sizeof(ss_plugin_event) + 4 + 4 + 4 + 4); } -const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ - return "0.1.0"; +const char* plugin_get_version() { + return "0.1.0"; } -const char* plugin_get_name() -{ - return "sample_syscall_extract"; +const char* plugin_get_name() { + return "sample_syscall_extract"; } -const char* plugin_get_description() -{ - return "some desc"; +const char* plugin_get_description() { + return "some desc"; } -const char* plugin_get_contact() -{ - return "some contact"; +const char* plugin_get_contact() { + return "some contact"; } -const char* plugin_get_fields() -{ +const char* plugin_get_fields() { return R"( [ { @@ -126,268 +111,266 @@ const char* plugin_get_fields() ])"; } -const char* plugin_get_extract_event_sources() -{ - return "[\"syscall\"]"; +const char* plugin_get_extract_event_sources() { + return "[\"syscall\"]"; } -uint16_t* plugin_get_extract_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - static uint16_t types[] = { - PPME_SYSCALL_OPEN_E, - PPME_SYSCALL_OPEN_X, - PPME_SYSCALL_OPENAT_E, - PPME_SYSCALL_OPENAT_X, - PPME_SYSCALL_OPENAT_2_E, - PPME_SYSCALL_OPENAT_2_X, - PPME_SYSCALL_OPENAT2_E, - PPME_SYSCALL_OPENAT2_X, - // note: filtered for testing purposes - // PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, - // PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, - // note: non-filtered for testing purposes - PPME_SYSCALL_INOTIFY_INIT1_E, - PPME_SYSCALL_INOTIFY_INIT1_X, - PPME_ASYNCEVENT_E, // used for catching async events - PPME_SYSCALL_GETCWD_X, // general purpose, used for other unit tests - }; - *num_types = sizeof(types) / sizeof(uint16_t); - return &types[0]; +uint16_t* plugin_get_extract_event_types(uint32_t* num_types, ss_plugin_t* s) { + static uint16_t types[] = { + PPME_SYSCALL_OPEN_E, + PPME_SYSCALL_OPEN_X, + PPME_SYSCALL_OPENAT_E, + PPME_SYSCALL_OPENAT_X, + PPME_SYSCALL_OPENAT_2_E, + PPME_SYSCALL_OPENAT_2_X, + PPME_SYSCALL_OPENAT2_E, + PPME_SYSCALL_OPENAT2_X, + // note: filtered for testing purposes + // PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, + // PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + // note: non-filtered for testing purposes + PPME_SYSCALL_INOTIFY_INIT1_E, + PPME_SYSCALL_INOTIFY_INIT1_X, + PPME_ASYNCEVENT_E, // used for catching async events + PPME_SYSCALL_GETCWD_X, // general purpose, used for other unit tests + }; + *num_types = sizeof(types) / sizeof(uint16_t); + return &types[0]; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - *rc = SS_PLUGIN_SUCCESS; - auto ret = new plugin_state(); +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + *rc = SS_PLUGIN_SUCCESS; + auto ret = new plugin_state(); - //save logger and owner in the state - ret->log = in->log_fn; - ret->owner = in->owner; + // save logger and owner in the state + ret->log = in->log_fn; + ret->owner = in->owner; - ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); + ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); // we have the extraction capability so the `in->tables` field should be != NULL - if (!in || !in->tables) - { - *rc = SS_PLUGIN_FAILURE; - ret->lasterr = "invalid config input"; - return ret; - } - - // get accessor for thread table - ret->thread_table = in->tables->get_table( - in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); - if (!ret->thread_table) - { - *rc = SS_PLUGIN_FAILURE; - auto err = in->get_owner_last_error(in->owner); - ret->lasterr = err ? err : "can't access thread table"; - return ret; - } - - // get accessor for proc name in thread table entries - ret->thread_comm_field = in->tables->fields.get_table_field( - ret->thread_table, "comm", ss_plugin_state_type::SS_PLUGIN_ST_STRING); - if (!ret->thread_comm_field) - { - *rc = SS_PLUGIN_FAILURE; - auto err = in->get_owner_last_error(in->owner); - ret->lasterr = err ? err : "can't access proc name in thread table"; - return ret; - } - - // get a field defined from another plugin (sample_syscall_parse) in the sinsp thread table. - // we don't check for errors: if the field is not available, we'll simply - // extract the related field as NULL. - ret->thread_opencount_field = in->tables->fields.get_table_field( - ret->thread_table, "open_evt_count", ss_plugin_state_type::SS_PLUGIN_ST_UINT64); - /* The result will depend on how the plugin is used in the test */ - if (!ret->thread_opencount_field) - { - printf("OK(syscall_extract) - as expected field 'open_evt_count' is not available in the thread table. The plugin field 'sample.open_count' will not be available\n"); - } - else - { - printf("OK(syscall_extract) - as expected field 'open_evt_count' is available in the thread table. The plugin field 'sample.open_count' will be available\n"); + if(!in || !in->tables) { + *rc = SS_PLUGIN_FAILURE; + ret->lasterr = "invalid config input"; + return ret; } - // we try to access a table (and one of its fields) defined and owned by - // another plugin - ret->evtcount_table = in->tables->get_table( - in->owner, "event_counters", ss_plugin_state_type::SS_PLUGIN_ST_UINT64); - /* The result will depend on how the plugin is used in the test */ - if (ret->evtcount_table) - { - ret->evtcount_count_field = in->tables->fields.get_table_field( - ret->evtcount_table, "count", ss_plugin_state_type::SS_PLUGIN_ST_UINT64); - } - - if (!ret->evtcount_table || !ret->evtcount_count_field) - { - printf("OK(syscall_extract) - as expected 'event_counters' table is not available. The plugin field 'sample.evt_count' will not be available\n"); - } - else - { - printf("OK(syscall_extract) - as expected 'event_counters' table is available. The plugin field 'sample.evt_count' will be available\n"); + // get accessor for thread table + ret->thread_table = + in->tables->get_table(in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); + if(!ret->thread_table) { + *rc = SS_PLUGIN_FAILURE; + auto err = in->get_owner_last_error(in->owner); + ret->lasterr = err ? err : "can't access thread table"; + return ret; + } + + // get accessor for proc name in thread table entries + ret->thread_comm_field = + in->tables->fields.get_table_field(ret->thread_table, + "comm", + ss_plugin_state_type::SS_PLUGIN_ST_STRING); + if(!ret->thread_comm_field) { + *rc = SS_PLUGIN_FAILURE; + auto err = in->get_owner_last_error(in->owner); + ret->lasterr = err ? err : "can't access proc name in thread table"; + return ret; + } + + // get a field defined from another plugin (sample_syscall_parse) in the sinsp thread table. + // we don't check for errors: if the field is not available, we'll simply + // extract the related field as NULL. + ret->thread_opencount_field = + in->tables->fields.get_table_field(ret->thread_table, + "open_evt_count", + ss_plugin_state_type::SS_PLUGIN_ST_UINT64); + /* The result will depend on how the plugin is used in the test */ + if(!ret->thread_opencount_field) { + printf("OK(syscall_extract) - as expected field 'open_evt_count' is not available in the " + "thread table. The plugin field 'sample.open_count' will not be available\n"); + } else { + printf("OK(syscall_extract) - as expected field 'open_evt_count' is available in the " + "thread table. The plugin field 'sample.open_count' will be available\n"); } - return ret; + + // we try to access a table (and one of its fields) defined and owned by + // another plugin + ret->evtcount_table = in->tables->get_table(in->owner, + "event_counters", + ss_plugin_state_type::SS_PLUGIN_ST_UINT64); + /* The result will depend on how the plugin is used in the test */ + if(ret->evtcount_table) { + ret->evtcount_count_field = + in->tables->fields.get_table_field(ret->evtcount_table, + "count", + ss_plugin_state_type::SS_PLUGIN_ST_UINT64); + } + + if(!ret->evtcount_table || !ret->evtcount_count_field) { + printf("OK(syscall_extract) - as expected 'event_counters' table is not available. The " + "plugin field 'sample.evt_count' will not be available\n"); + } else { + printf("OK(syscall_extract) - as expected 'event_counters' table is available. The plugin " + "field 'sample.evt_count' will be available\n"); + } + return ret; } -void plugin_destroy(ss_plugin_t* s) -{ - auto ps = reinterpret_cast(s); - ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); +void plugin_destroy(ss_plugin_t* s) { + auto ps = reinterpret_cast(s); + ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); - delete ps; + delete ps; } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_rc plugin_extract_fields(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_field_extract_input* in) -{ - ss_plugin_rc rc; - ss_plugin_state_data tmp; - ss_plugin_table_entry_t* thread = NULL; - ss_plugin_table_entry_t* evtcount = NULL; - auto ps = reinterpret_cast(s); - for (uint32_t i = 0; i < in->num_fields; i++) - { - switch(in->fields[i].field_id) - { - case 0: // sample.is_open - ps->u64storage = evt_type_is_open(ev->evt->type); - in->fields[i].res.u64 = &ps->u64storage; - in->fields[i].res_len = 1; - break; - case 1: // sample.open_count - /* This is a new field defined in the sinsp thread table */ - if (!ps->thread_opencount_field) - { - in->fields[i].res_len = 0; - return SS_PLUGIN_FAILURE; - } - tmp.s64 = ev->evt->tid; - thread = in->table_reader.get_table_entry(ps->thread_table, &tmp); - if (!thread) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't get thread with tid=" + std::to_string(ev->evt->tid)); - return SS_PLUGIN_FAILURE; - } - rc = in->table_reader.read_entry_field(ps->thread_table, thread, ps->thread_opencount_field, &tmp); - if (rc != SS_PLUGIN_SUCCESS) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't read ope counter from thread with tid=" + std::to_string(ev->evt->tid)); - in->table_reader_ext->release_table_entry(ps->thread_table, thread); - return SS_PLUGIN_FAILURE; - } - ps->u64storage = tmp.u64; - in->fields[i].res.u64 = &ps->u64storage; - in->fields[i].res_len = 1; - in->table_reader_ext->release_table_entry(ps->thread_table, thread); - break; - case 2: // sample.evt_count - if (!ps->evtcount_table || !ps->evtcount_count_field) - { - in->fields[i].res_len = 0; - return SS_PLUGIN_FAILURE; - } - - // testing that error reporting works as expected - tmp.s64 = 9999; - evtcount = in->table_reader.get_table_entry(ps->evtcount_table, &tmp); - if (evtcount) - { - printf("sample_syscall_extract: unexpected success in getting unknown table entry from another plugin\n"); - exit(1); - } - else - { - auto err = in->get_owner_last_error(in->owner); - if (err == NULL || strlen(err) == 0) - { - printf("sample_syscall_extract: unexpected empty error in getting unknown table entry from another plugin\n"); - exit(1); - } - } - - tmp.s64 = ev->evt->type; - evtcount = in->table_reader.get_table_entry(ps->evtcount_table, &tmp); - if (!evtcount) - { - // stubbing the counter to 0 if no entry exists - ps->u64storage = 0; - in->fields[i].res.u64 = &ps->u64storage; - in->fields[i].res_len = 1; - return SS_PLUGIN_SUCCESS; - } - rc = in->table_reader.read_entry_field(ps->evtcount_table, evtcount, ps->evtcount_count_field, &tmp); - if (rc != SS_PLUGIN_SUCCESS) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't read event counter for type=" + std::to_string(ev->evt->type)); - in->table_reader_ext->release_table_entry(ps->evtcount_table, evtcount); - return SS_PLUGIN_FAILURE; - } - ps->u64storage = tmp.u64; - in->fields[i].res.u64 = &ps->u64storage; - in->fields[i].res_len = 1; - in->table_reader_ext->release_table_entry(ps->evtcount_table, evtcount); - break; - case 3: // sample.proc_name - tmp.s64 = ev->evt->tid; - thread = in->table_reader.get_table_entry(ps->thread_table, &tmp); - if (!thread) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't get thread with tid=" + std::to_string(ev->evt->tid)); - return SS_PLUGIN_FAILURE; - } - rc = in->table_reader.read_entry_field(ps->thread_table, thread, ps->thread_comm_field, &tmp); - if (rc != SS_PLUGIN_SUCCESS) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't read proc name from thread with tid=" + std::to_string(ev->evt->tid)); - in->table_reader_ext->release_table_entry(ps->thread_table, thread); - return SS_PLUGIN_FAILURE; - } - ps->strstorage = std::string(tmp.str); - ps->strptrstorage = ps->strstorage.c_str(); - in->fields[i].res.str = &ps->strptrstorage; - in->fields[i].res_len = 1; - in->table_reader_ext->release_table_entry(ps->thread_table, thread); - break; - case 4: // sample.tick - if (ev->evt->type == PPME_ASYNCEVENT_E - && strcmp("sampleticker", get_async_event_name(ev->evt)) == 0) - { - ps->strstorage = "true"; - } - else - { - ps->strstorage = "false"; - } - ps->strptrstorage = ps->strstorage.c_str(); - in->fields[i].res.str = &ps->strptrstorage; - in->fields[i].res_len = 1; - break; - default: - in->fields[i].res_len = 0; - return SS_PLUGIN_FAILURE; - } - } - return SS_PLUGIN_SUCCESS; +ss_plugin_rc plugin_extract_fields(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_field_extract_input* in) { + ss_plugin_rc rc; + ss_plugin_state_data tmp; + ss_plugin_table_entry_t* thread = NULL; + ss_plugin_table_entry_t* evtcount = NULL; + auto ps = reinterpret_cast(s); + for(uint32_t i = 0; i < in->num_fields; i++) { + switch(in->fields[i].field_id) { + case 0: // sample.is_open + ps->u64storage = evt_type_is_open(ev->evt->type); + in->fields[i].res.u64 = &ps->u64storage; + in->fields[i].res_len = 1; + break; + case 1: // sample.open_count + /* This is a new field defined in the sinsp thread table */ + if(!ps->thread_opencount_field) { + in->fields[i].res_len = 0; + return SS_PLUGIN_FAILURE; + } + tmp.s64 = ev->evt->tid; + thread = in->table_reader.get_table_entry(ps->thread_table, &tmp); + if(!thread) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = + err ? err : ("can't get thread with tid=" + std::to_string(ev->evt->tid)); + return SS_PLUGIN_FAILURE; + } + rc = in->table_reader.read_entry_field(ps->thread_table, + thread, + ps->thread_opencount_field, + &tmp); + if(rc != SS_PLUGIN_SUCCESS) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = err ? err + : ("can't read ope counter from thread with tid=" + + std::to_string(ev->evt->tid)); + in->table_reader_ext->release_table_entry(ps->thread_table, thread); + return SS_PLUGIN_FAILURE; + } + ps->u64storage = tmp.u64; + in->fields[i].res.u64 = &ps->u64storage; + in->fields[i].res_len = 1; + in->table_reader_ext->release_table_entry(ps->thread_table, thread); + break; + case 2: // sample.evt_count + if(!ps->evtcount_table || !ps->evtcount_count_field) { + in->fields[i].res_len = 0; + return SS_PLUGIN_FAILURE; + } + + // testing that error reporting works as expected + tmp.s64 = 9999; + evtcount = in->table_reader.get_table_entry(ps->evtcount_table, &tmp); + if(evtcount) { + printf("sample_syscall_extract: unexpected success in getting unknown table entry " + "from another plugin\n"); + exit(1); + } else { + auto err = in->get_owner_last_error(in->owner); + if(err == NULL || strlen(err) == 0) { + printf("sample_syscall_extract: unexpected empty error in getting unknown " + "table entry from another plugin\n"); + exit(1); + } + } + + tmp.s64 = ev->evt->type; + evtcount = in->table_reader.get_table_entry(ps->evtcount_table, &tmp); + if(!evtcount) { + // stubbing the counter to 0 if no entry exists + ps->u64storage = 0; + in->fields[i].res.u64 = &ps->u64storage; + in->fields[i].res_len = 1; + return SS_PLUGIN_SUCCESS; + } + rc = in->table_reader.read_entry_field(ps->evtcount_table, + evtcount, + ps->evtcount_count_field, + &tmp); + if(rc != SS_PLUGIN_SUCCESS) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = err ? err + : ("can't read event counter for type=" + + std::to_string(ev->evt->type)); + in->table_reader_ext->release_table_entry(ps->evtcount_table, evtcount); + return SS_PLUGIN_FAILURE; + } + ps->u64storage = tmp.u64; + in->fields[i].res.u64 = &ps->u64storage; + in->fields[i].res_len = 1; + in->table_reader_ext->release_table_entry(ps->evtcount_table, evtcount); + break; + case 3: // sample.proc_name + tmp.s64 = ev->evt->tid; + thread = in->table_reader.get_table_entry(ps->thread_table, &tmp); + if(!thread) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = + err ? err : ("can't get thread with tid=" + std::to_string(ev->evt->tid)); + return SS_PLUGIN_FAILURE; + } + rc = in->table_reader.read_entry_field(ps->thread_table, + thread, + ps->thread_comm_field, + &tmp); + if(rc != SS_PLUGIN_SUCCESS) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = err ? err + : ("can't read proc name from thread with tid=" + + std::to_string(ev->evt->tid)); + in->table_reader_ext->release_table_entry(ps->thread_table, thread); + return SS_PLUGIN_FAILURE; + } + ps->strstorage = std::string(tmp.str); + ps->strptrstorage = ps->strstorage.c_str(); + in->fields[i].res.str = &ps->strptrstorage; + in->fields[i].res_len = 1; + in->table_reader_ext->release_table_entry(ps->thread_table, thread); + break; + case 4: // sample.tick + if(ev->evt->type == PPME_ASYNCEVENT_E && + strcmp("sampleticker", get_async_event_name(ev->evt)) == 0) { + ps->strstorage = "true"; + } else { + ps->strstorage = "false"; + } + ps->strptrstorage = ps->strstorage.c_str(); + in->fields[i].res.str = &ps->strptrstorage; + in->fields[i].res_len = 1; + break; + default: + in->fields[i].res_len = 0; + return SS_PLUGIN_FAILURE; + } + } + return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_syscall_extract(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); +void get_plugin_api_sample_syscall_extract(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; out.get_description = plugin_get_description; @@ -396,8 +379,8 @@ void get_plugin_api_sample_syscall_extract(plugin_api& out) out.get_last_error = plugin_get_last_error; out.init = plugin_init; out.destroy = plugin_destroy; - out.get_fields = plugin_get_fields; - out.get_extract_event_sources = plugin_get_extract_event_sources; - out.get_extract_event_types = plugin_get_extract_event_types; - out.extract_fields = plugin_extract_fields; + out.get_fields = plugin_get_fields; + out.get_extract_event_sources = plugin_get_extract_event_sources; + out.get_extract_event_types = plugin_get_extract_event_types; + out.extract_fields = plugin_extract_fields; } diff --git a/userspace/libsinsp/test/plugins/syscall_parse.cpp b/userspace/libsinsp/test/plugins/syscall_parse.cpp index 783a14ce9d..311d6c1771 100644 --- a/userspace/libsinsp/test/plugins/syscall_parse.cpp +++ b/userspace/libsinsp/test/plugins/syscall_parse.cpp @@ -35,233 +35,228 @@ namespace { * - Owns and defines a new table that has one entry for each event type, * with a field representing a counter for all events of that type across all threads. */ -struct plugin_state -{ - std::string lasterr; - ss_plugin_table_t* thread_table; - ss_plugin_table_field_t* thread_opencount_field; - sample_table::ptr_t event_count_table; - ss_plugin_table_field_t* event_count_table_count_field; - ss_plugin_owner_t* owner; - ss_plugin_log_fn_t log; +struct plugin_state { + std::string lasterr; + ss_plugin_table_t* thread_table; + ss_plugin_table_field_t* thread_opencount_field; + sample_table::ptr_t event_count_table; + ss_plugin_table_field_t* event_count_table_count_field; + ss_plugin_owner_t* owner; + ss_plugin_log_fn_t log; }; -inline bool evt_type_is_open(uint16_t type) -{ - return type == PPME_SYSCALL_OPEN_E - || type == PPME_SYSCALL_OPEN_X - || type == PPME_SYSCALL_OPENAT_E - || type == PPME_SYSCALL_OPENAT_X - || type == PPME_SYSCALL_OPENAT_2_E - || type == PPME_SYSCALL_OPENAT_2_X - || type == PPME_SYSCALL_OPENAT2_E - || type == PPME_SYSCALL_OPENAT2_X - || type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_E - || type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X - ; +inline bool evt_type_is_open(uint16_t type) { + return type == PPME_SYSCALL_OPEN_E || type == PPME_SYSCALL_OPEN_X || + type == PPME_SYSCALL_OPENAT_E || type == PPME_SYSCALL_OPENAT_X || + type == PPME_SYSCALL_OPENAT_2_E || type == PPME_SYSCALL_OPENAT_2_X || + type == PPME_SYSCALL_OPENAT2_E || type == PPME_SYSCALL_OPENAT2_X || + type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_E || type == PPME_SYSCALL_OPEN_BY_HANDLE_AT_X; } -const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ - return "0.1.0"; +const char* plugin_get_version() { + return "0.1.0"; } -const char* plugin_get_name() -{ - return "sample_syscall_parse"; +const char* plugin_get_name() { + return "sample_syscall_parse"; } -const char* plugin_get_description() -{ - return "some desc"; +const char* plugin_get_description() { + return "some desc"; } -const char* plugin_get_contact() -{ - return "some contact"; +const char* plugin_get_contact() { + return "some contact"; } -const char* plugin_get_parse_event_sources() -{ - return "[\"syscall\"]"; +const char* plugin_get_parse_event_sources() { + return "[\"syscall\"]"; } -uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - static uint16_t types[] = { - PPME_SYSCALL_OPEN_E, - PPME_SYSCALL_OPEN_X, - PPME_SYSCALL_OPENAT_E, - PPME_SYSCALL_OPENAT_X, - PPME_SYSCALL_OPENAT_2_E, - PPME_SYSCALL_OPENAT_2_X, - PPME_SYSCALL_OPENAT2_E, - PPME_SYSCALL_OPENAT2_X, - PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, - PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, - }; - *num_types = sizeof(types) / sizeof(uint16_t); - return &types[0]; +uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) { + static uint16_t types[] = { + PPME_SYSCALL_OPEN_E, + PPME_SYSCALL_OPEN_X, + PPME_SYSCALL_OPENAT_E, + PPME_SYSCALL_OPENAT_X, + PPME_SYSCALL_OPENAT_2_E, + PPME_SYSCALL_OPENAT_2_X, + PPME_SYSCALL_OPENAT2_E, + PPME_SYSCALL_OPENAT2_X, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + }; + *num_types = sizeof(types) / sizeof(uint16_t); + return &types[0]; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - *rc = SS_PLUGIN_SUCCESS; - auto ret = new plugin_state(); - - //save logger and owner in the state - ret->log = in->log_fn; - ret->owner = in->owner; - - ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); - - if (!in || !in->tables) - { - *rc = SS_PLUGIN_FAILURE; - ret->lasterr = "invalid config input"; - return ret; - } - - // get accessor for thread table - ret->thread_table = in->tables->get_table( - in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); - if (!ret->thread_table) - { - *rc = SS_PLUGIN_FAILURE; - auto err = in->get_owner_last_error(in->owner); - ret->lasterr = err ? err : "can't access thread table"; - return ret; - } - - // define a new field in thread table entries - ret->thread_opencount_field = in->tables->fields.add_table_field( - ret->thread_table, "open_evt_count", ss_plugin_state_type::SS_PLUGIN_ST_UINT64); - if (!ret->thread_opencount_field) - { - *rc = SS_PLUGIN_FAILURE; - auto err = in->get_owner_last_error(in->owner); - ret->lasterr = err ? err : "can't add open counter in thread table"; - return ret; - } - - // define a new table that keeps a counter for all events. The table's key - // is the event code as for the libscap specific - ret->event_count_table = sample_table::create("event_counters", ret->lasterr); - ret->event_count_table_count_field = ret->event_count_table->fields.add_table_field( - ret->event_count_table->table, "count", - ss_plugin_state_type::SS_PLUGIN_ST_UINT64); - if (!ret->event_count_table_count_field) - { - *rc = SS_PLUGIN_FAILURE; - ret->lasterr = "can't define event counter fields (count)"; - return ret; - } - - if (SS_PLUGIN_SUCCESS != in->tables->add_table(in->owner, ret->event_count_table.get())) - { - *rc = SS_PLUGIN_FAILURE; - auto err = in->get_owner_last_error(in->owner); - ret->lasterr = err ? err : "can't add event counter table"; - return ret; - } - return ret; +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + *rc = SS_PLUGIN_SUCCESS; + auto ret = new plugin_state(); + + // save logger and owner in the state + ret->log = in->log_fn; + ret->owner = in->owner; + + ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); + + if(!in || !in->tables) { + *rc = SS_PLUGIN_FAILURE; + ret->lasterr = "invalid config input"; + return ret; + } + + // get accessor for thread table + ret->thread_table = + in->tables->get_table(in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); + if(!ret->thread_table) { + *rc = SS_PLUGIN_FAILURE; + auto err = in->get_owner_last_error(in->owner); + ret->lasterr = err ? err : "can't access thread table"; + return ret; + } + + // define a new field in thread table entries + ret->thread_opencount_field = + in->tables->fields.add_table_field(ret->thread_table, + "open_evt_count", + ss_plugin_state_type::SS_PLUGIN_ST_UINT64); + if(!ret->thread_opencount_field) { + *rc = SS_PLUGIN_FAILURE; + auto err = in->get_owner_last_error(in->owner); + ret->lasterr = err ? err : "can't add open counter in thread table"; + return ret; + } + + // define a new table that keeps a counter for all events. The table's key + // is the event code as for the libscap specific + ret->event_count_table = sample_table::create("event_counters", ret->lasterr); + ret->event_count_table_count_field = ret->event_count_table->fields.add_table_field( + ret->event_count_table->table, + "count", + ss_plugin_state_type::SS_PLUGIN_ST_UINT64); + if(!ret->event_count_table_count_field) { + *rc = SS_PLUGIN_FAILURE; + ret->lasterr = "can't define event counter fields (count)"; + return ret; + } + + if(SS_PLUGIN_SUCCESS != in->tables->add_table(in->owner, ret->event_count_table.get())) { + *rc = SS_PLUGIN_FAILURE; + auto err = in->get_owner_last_error(in->owner); + ret->lasterr = err ? err : "can't add event counter table"; + return ret; + } + return ret; } -void plugin_destroy(ss_plugin_t* s) -{ - auto ps = reinterpret_cast(s); - ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); +void plugin_destroy(ss_plugin_t* s) { + auto ps = reinterpret_cast(s); + ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); - delete ps; + delete ps; } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } // parses events and keeps a count for each thread about the syscalls of the open family -ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_event_parse_input* in) -{ - ss_plugin_state_data tmp; - auto ps = reinterpret_cast(s); - - // update event counters - tmp.u64 = ev->evt->type; - auto evtcounter = ps->event_count_table->reader.get_table_entry(ps->event_count_table->table, &tmp); - if (!evtcounter) - { - auto newentry = ps->event_count_table->writer.create_table_entry(ps->event_count_table->table); - tmp.u64 = ev->evt->type; - evtcounter = ps->event_count_table->writer.add_table_entry(ps->event_count_table->table, &tmp, newentry); - if (!evtcounter) - { - ps->lasterr = "can't allocate event counter in table"; - return SS_PLUGIN_FAILURE; - } - } - if (SS_PLUGIN_SUCCESS != ps->event_count_table->reader.read_entry_field( - ps->event_count_table->table, evtcounter, ps->event_count_table_count_field, &tmp)) - { - ps->lasterr = "can't read event counter in table"; - ps->event_count_table->reader_ext->release_table_entry(ps->event_count_table->table, evtcounter); - return SS_PLUGIN_FAILURE; - } - tmp.u64++; - if (SS_PLUGIN_SUCCESS != ps->event_count_table->writer.write_entry_field( - ps->event_count_table->table, evtcounter, ps->event_count_table_count_field, &tmp)) - { - ps->lasterr = "can't write event counter in table"; - ps->event_count_table->reader_ext->release_table_entry(ps->event_count_table->table, evtcounter); - return SS_PLUGIN_FAILURE; - } - ps->event_count_table->reader_ext->release_table_entry(ps->event_count_table->table, evtcounter); - - // update counter for current thread - if (evt_type_is_open(ev->evt->type)) - { - tmp.s64 = ev->evt->tid; - auto thread = in->table_reader.get_table_entry(ps->thread_table, &tmp); - if (!thread) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't get thread with tid=" + std::to_string(ev->evt->tid)); - return SS_PLUGIN_FAILURE; - } - - if (SS_PLUGIN_SUCCESS != in->table_reader.read_entry_field(ps->thread_table, thread, ps->thread_opencount_field, &tmp)) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't read open counter from thread with tid=" + std::to_string(ev->evt->tid)); - in->table_reader_ext->release_table_entry(ps->thread_table, thread); - return SS_PLUGIN_FAILURE; - } - - // increase counter and write it back in the current thread's info - tmp.u64++; - if (SS_PLUGIN_SUCCESS != in->table_writer.write_entry_field(ps->thread_table, thread, ps->thread_opencount_field, &tmp)) - { - auto err = in->get_owner_last_error(in->owner); - ps->lasterr = err ? err : ("can't write open counter to thread with tid=" + std::to_string(ev->evt->tid)); - in->table_reader_ext->release_table_entry(ps->thread_table, thread); - return SS_PLUGIN_FAILURE; - } - in->table_reader_ext->release_table_entry(ps->thread_table, thread); - } - - return SS_PLUGIN_SUCCESS; +ss_plugin_rc plugin_parse_event(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_event_parse_input* in) { + ss_plugin_state_data tmp; + auto ps = reinterpret_cast(s); + + // update event counters + tmp.u64 = ev->evt->type; + auto evtcounter = + ps->event_count_table->reader.get_table_entry(ps->event_count_table->table, &tmp); + if(!evtcounter) { + auto newentry = + ps->event_count_table->writer.create_table_entry(ps->event_count_table->table); + tmp.u64 = ev->evt->type; + evtcounter = ps->event_count_table->writer.add_table_entry(ps->event_count_table->table, + &tmp, + newentry); + if(!evtcounter) { + ps->lasterr = "can't allocate event counter in table"; + return SS_PLUGIN_FAILURE; + } + } + if(SS_PLUGIN_SUCCESS != + ps->event_count_table->reader.read_entry_field(ps->event_count_table->table, + evtcounter, + ps->event_count_table_count_field, + &tmp)) { + ps->lasterr = "can't read event counter in table"; + ps->event_count_table->reader_ext->release_table_entry(ps->event_count_table->table, + evtcounter); + return SS_PLUGIN_FAILURE; + } + tmp.u64++; + if(SS_PLUGIN_SUCCESS != + ps->event_count_table->writer.write_entry_field(ps->event_count_table->table, + evtcounter, + ps->event_count_table_count_field, + &tmp)) { + ps->lasterr = "can't write event counter in table"; + ps->event_count_table->reader_ext->release_table_entry(ps->event_count_table->table, + evtcounter); + return SS_PLUGIN_FAILURE; + } + ps->event_count_table->reader_ext->release_table_entry(ps->event_count_table->table, + evtcounter); + + // update counter for current thread + if(evt_type_is_open(ev->evt->type)) { + tmp.s64 = ev->evt->tid; + auto thread = in->table_reader.get_table_entry(ps->thread_table, &tmp); + if(!thread) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = err ? err : ("can't get thread with tid=" + std::to_string(ev->evt->tid)); + return SS_PLUGIN_FAILURE; + } + + if(SS_PLUGIN_SUCCESS != in->table_reader.read_entry_field(ps->thread_table, + thread, + ps->thread_opencount_field, + &tmp)) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = err ? err + : ("can't read open counter from thread with tid=" + + std::to_string(ev->evt->tid)); + in->table_reader_ext->release_table_entry(ps->thread_table, thread); + return SS_PLUGIN_FAILURE; + } + + // increase counter and write it back in the current thread's info + tmp.u64++; + if(SS_PLUGIN_SUCCESS != in->table_writer.write_entry_field(ps->thread_table, + thread, + ps->thread_opencount_field, + &tmp)) { + auto err = in->get_owner_last_error(in->owner); + ps->lasterr = err ? err + : ("can't write open counter to thread with tid=" + + std::to_string(ev->evt->tid)); + in->table_reader_ext->release_table_entry(ps->thread_table, thread); + return SS_PLUGIN_FAILURE; + } + in->table_reader_ext->release_table_entry(ps->thread_table, thread); + } + + return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_syscall_parse(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); +void get_plugin_api_sample_syscall_parse(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; out.get_description = plugin_get_description; @@ -270,7 +265,7 @@ void get_plugin_api_sample_syscall_parse(plugin_api& out) out.get_last_error = plugin_get_last_error; out.init = plugin_init; out.destroy = plugin_destroy; - out.get_parse_event_sources = plugin_get_parse_event_sources; - out.get_parse_event_types = plugin_get_parse_event_types; - out.parse_event = plugin_parse_event; + out.get_parse_event_sources = plugin_get_parse_event_sources; + out.get_parse_event_types = plugin_get_parse_event_types; + out.parse_event = plugin_parse_event; } diff --git a/userspace/libsinsp/test/plugins/syscall_source.cpp b/userspace/libsinsp/test/plugins/syscall_source.cpp index 5f08e361e1..faa3c74590 100644 --- a/userspace/libsinsp/test/plugins/syscall_source.cpp +++ b/userspace/libsinsp/test/plugins/syscall_source.cpp @@ -32,128 +32,123 @@ namespace { * - Does not implement a specific event source, thus can create any syscall event * - Sources events of type PPME_SYSCALL_OPEN_X */ -struct plugin_state -{ - std::string lasterr; - ss_plugin_owner_t* owner; - ss_plugin_log_fn_t log; +struct plugin_state { + std::string lasterr; + ss_plugin_owner_t* owner; + ss_plugin_log_fn_t log; }; -struct instance_state -{ - uint64_t count; - uint8_t evt_buf[2048]; - ss_plugin_event* evt; +struct instance_state { + uint64_t count; + uint8_t evt_buf[2048]; + ss_plugin_event* evt; }; -const char* plugin_get_required_api_version() -{ - return PLUGIN_API_VERSION_STR; +const char* plugin_get_required_api_version() { + return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ - return "0.1.0"; +const char* plugin_get_version() { + return "0.1.0"; } -const char* plugin_get_name() -{ - return "sample_syscall_source"; +const char* plugin_get_name() { + return "sample_syscall_source"; } -const char* plugin_get_description() -{ - return "some desc"; +const char* plugin_get_description() { + return "some desc"; } -const char* plugin_get_contact() -{ - return "some contact"; +const char* plugin_get_contact() { + return "some contact"; } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ - auto ret = new plugin_state(); +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { + auto ret = new plugin_state(); - //save logger and owner in the state - ret->log = in->log_fn; - ret->owner = in->owner; + // save logger and owner in the state + ret->log = in->log_fn; + ret->owner = in->owner; - ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); + ret->log(ret->owner, NULL, "initializing plugin...", SS_PLUGIN_LOG_SEV_INFO); - *rc = SS_PLUGIN_SUCCESS; - return ret; + *rc = SS_PLUGIN_SUCCESS; + return ret; } -void plugin_destroy(ss_plugin_t* s) -{ - auto ps = reinterpret_cast(s); - ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); +void plugin_destroy(ss_plugin_t* s) { + auto ps = reinterpret_cast(s); + ps->log(ps->owner, NULL, "destroying plugin...", SS_PLUGIN_LOG_SEV_INFO); - delete ps; + delete ps; } -ss_instance_t* plugin_open(ss_plugin_t* s, const char* params, ss_plugin_rc* rc) -{ - auto ret = new instance_state(); - ret->evt = (ss_plugin_event*) &ret->evt_buf; - ret->count = 10000; - auto count = atoi(params); - if (count > 0) - { - ret->count = (uint64_t) count; - } - - *rc = SS_PLUGIN_SUCCESS; - return ret; +ss_instance_t* plugin_open(ss_plugin_t* s, const char* params, ss_plugin_rc* rc) { + auto ret = new instance_state(); + ret->evt = (ss_plugin_event*)&ret->evt_buf; + ret->count = 10000; + auto count = atoi(params); + if(count > 0) { + ret->count = (uint64_t)count; + } + + *rc = SS_PLUGIN_SUCCESS; + return ret; } -void plugin_close(ss_plugin_t* s, ss_instance_t* i) -{ - delete ((instance_state *) i); +void plugin_close(ss_plugin_t* s, ss_instance_t* i) { + delete((instance_state*)i); } -ss_plugin_rc plugin_next_batch(ss_plugin_t* s, ss_instance_t* i, uint32_t *nevts, ss_plugin_event ***evts) -{ - instance_state *istate = (instance_state *) i; - - if (istate->count == 0) - { - *nevts = 0; - return SS_PLUGIN_EOF; - } - - *nevts = 1; - *evts = &istate->evt; - - char error[SCAP_LASTERR_SIZE]; - - int32_t encode_res = scap_event_encode_params(scap_sized_buffer{istate->evt, sizeof(istate->evt_buf)}, - nullptr, error, PPME_SYSCALL_OPEN_X, 6, - (uint64_t) 3, "/tmp/the_file", ((1 << 0) | (1 << 1)), 0, 5, (uint64_t) 123); - - if (encode_res == SCAP_FAILURE) - { - return SS_PLUGIN_FAILURE; - } - - istate->evt->tid = 1; - istate->evt->ts = UINT64_MAX; - - istate->count--; - return SS_PLUGIN_SUCCESS; +ss_plugin_rc plugin_next_batch(ss_plugin_t* s, + ss_instance_t* i, + uint32_t* nevts, + ss_plugin_event*** evts) { + instance_state* istate = (instance_state*)i; + + if(istate->count == 0) { + *nevts = 0; + return SS_PLUGIN_EOF; + } + + *nevts = 1; + *evts = &istate->evt; + + char error[SCAP_LASTERR_SIZE]; + + int32_t encode_res = + scap_event_encode_params(scap_sized_buffer{istate->evt, sizeof(istate->evt_buf)}, + nullptr, + error, + PPME_SYSCALL_OPEN_X, + 6, + (uint64_t)3, + "/tmp/the_file", + ((1 << 0) | (1 << 1)), + 0, + 5, + (uint64_t)123); + + if(encode_res == SCAP_FAILURE) { + return SS_PLUGIN_FAILURE; + } + + istate->evt->tid = 1; + istate->evt->ts = UINT64_MAX; + + istate->count--; + return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_syscall_source(plugin_api& out) -{ - memset(&out, 0, sizeof(plugin_api)); +void get_plugin_api_sample_syscall_source(plugin_api& out) { + memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; out.get_description = plugin_get_description; @@ -162,7 +157,7 @@ void get_plugin_api_sample_syscall_source(plugin_api& out) out.get_last_error = plugin_get_last_error; out.init = plugin_init; out.destroy = plugin_destroy; - out.open = plugin_open; - out.close = plugin_close; - out.next_batch = plugin_next_batch; + out.open = plugin_open; + out.close = plugin_close; + out.next_batch = plugin_next_batch; } diff --git a/userspace/libsinsp/test/plugins/syscall_subtables.cpp b/userspace/libsinsp/test/plugins/syscall_subtables.cpp index 8c0e5fae3e..16b235a026 100644 --- a/userspace/libsinsp/test/plugins/syscall_subtables.cpp +++ b/userspace/libsinsp/test/plugins/syscall_subtables.cpp @@ -26,8 +26,7 @@ limitations under the License. namespace { -struct plugin_state -{ +struct plugin_state { std::string lasterr; ss_plugin_table_t* thread_table; @@ -40,70 +39,61 @@ struct plugin_state uint8_t step = 0; }; -const char* plugin_get_required_api_version() -{ +const char* plugin_get_required_api_version() { return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ +const char* plugin_get_version() { return "0.1.0"; } -const char* plugin_get_name() -{ +const char* plugin_get_name() { return "sample_subtables"; } -const char* plugin_get_description() -{ +const char* plugin_get_description() { return "some desc"; } -const char* plugin_get_contact() -{ +const char* plugin_get_contact() { return "some contact"; } -const char* plugin_get_parse_event_sources() -{ +const char* plugin_get_parse_event_sources() { return "[\"syscall\"]"; } -uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - static uint16_t types[] = { PPME_SYSCALL_OPEN_E }; - *num_types = sizeof(types) / sizeof(uint16_t); - return &types[0]; +uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) { + static uint16_t types[] = {PPME_SYSCALL_OPEN_E}; + *num_types = sizeof(types) / sizeof(uint16_t); + return &types[0]; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { *rc = SS_PLUGIN_SUCCESS; auto ret = new plugin_state(); - if (!in || !in->tables) - { + if(!in || !in->tables) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "invalid config input"; return ret; } // get an accessor to the threads table - ret->thread_table = in->tables->get_table( - in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); - if (!ret->thread_table) - { + ret->thread_table = + in->tables->get_table(in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); + if(!ret->thread_table) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't access thread table"; return ret; } // get an accessor to the file descriptor tables owned by each thread info - ret->table_field_fdtable = in->tables->fields.get_table_field( - ret->thread_table, "file_descriptors", ss_plugin_state_type::SS_PLUGIN_ST_TABLE); - if (!ret->table_field_fdtable) - { + ret->table_field_fdtable = + in->tables->fields.get_table_field(ret->thread_table, + "file_descriptors", + ss_plugin_state_type::SS_PLUGIN_ST_TABLE); + if(!ret->table_field_fdtable) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't get fdtable field in thread table"; return ret; @@ -112,8 +102,7 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) // create a new thread info -- the purpose is just to access its file // descriptor table and obtain accessors for fields of that sub-table auto entry = in->tables->writer_ext->create_table_entry(ret->thread_table); - if (!entry) - { + if(!entry) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't create subtable entry (init-time)"; return ret; @@ -121,39 +110,44 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) // read pointer to file descriptor table owned by the new thread info ss_plugin_state_data data; - *rc = in->tables->reader_ext->read_entry_field(ret->thread_table, entry, ret->table_field_fdtable, &data); - if (*rc != SS_PLUGIN_SUCCESS) - { + *rc = in->tables->reader_ext->read_entry_field(ret->thread_table, + entry, + ret->table_field_fdtable, + &data); + if(*rc != SS_PLUGIN_SUCCESS) { ret->lasterr = "can't read sub-table table entry field (init-time)"; return ret; } auto fdtable = data.table; // obtain accessor to one of the fields of file descriptor tables (name) - ret->table_field_fdtable_name = in->tables->fields_ext->get_table_field( - fdtable, "name", ss_plugin_state_type::SS_PLUGIN_ST_STRING); - if (!ret->table_field_fdtable_name) - { + ret->table_field_fdtable_name = + in->tables->fields_ext->get_table_field(fdtable, + "name", + ss_plugin_state_type::SS_PLUGIN_ST_STRING); + if(!ret->table_field_fdtable_name) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't get sub-table 'name' field"; return ret; } // obtain accessor to one of the fields of file descriptor tables (pid) - ret->table_field_fdtable_pid = in->tables->fields_ext->get_table_field( - fdtable, "pid", ss_plugin_state_type::SS_PLUGIN_ST_INT64); - if (!ret->table_field_fdtable_pid) - { + ret->table_field_fdtable_pid = + in->tables->fields_ext->get_table_field(fdtable, + "pid", + ss_plugin_state_type::SS_PLUGIN_ST_INT64); + if(!ret->table_field_fdtable_pid) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't get sub-table pid field"; return ret; } // add a new fields to file descriptors table - ret->table_field_fdtable_custom = in->tables->fields_ext->add_table_field( - fdtable, "custom", ss_plugin_state_type::SS_PLUGIN_ST_STRING); - if (!ret->table_field_fdtable_custom) - { + ret->table_field_fdtable_custom = + in->tables->fields_ext->add_table_field(fdtable, + "custom", + ss_plugin_state_type::SS_PLUGIN_ST_STRING); + if(!ret->table_field_fdtable_custom) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't add sub-table custom field"; return ret; @@ -165,18 +159,17 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) return ret; } -void plugin_destroy(ss_plugin_t* s) -{ +void plugin_destroy(ss_plugin_t* s) { delete reinterpret_cast(s); } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_event_parse_input* in) -{ +ss_plugin_rc plugin_parse_event(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_event_parse_input* in) { auto ps = reinterpret_cast(s); ss_plugin_state_data key; ss_plugin_state_data out; @@ -187,53 +180,54 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, key.s64 = 0; entry = in->table_reader_ext->get_table_entry(ps->thread_table, &key); - if (!entry) - { + if(!entry) { ps->lasterr = "can't get table entry"; return SS_PLUGIN_FAILURE; } - auto res = in->table_reader_ext->read_entry_field(ps->thread_table, entry, ps->table_field_fdtable, &out); - if (res != SS_PLUGIN_SUCCESS) - { + auto res = in->table_reader_ext->read_entry_field(ps->thread_table, + entry, + ps->table_field_fdtable, + &out); + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't read table entry field"; return SS_PLUGIN_FAILURE; } fdtable = out.table; - //add entries to the fdtable - if(ps->step == 0) - { + // add entries to the fdtable + if(ps->step == 0) { int max_iterations = 1024; - for (int i = 0; i < max_iterations; i++) - { + for(int i = 0; i < max_iterations; i++) { auto nentry = in->table_writer_ext->create_table_entry(fdtable); - if (!nentry) - { + if(!nentry) { ps->lasterr = "can't create subtable entry"; return SS_PLUGIN_FAILURE; } key.s64 = i; nentry = in->table_writer_ext->add_table_entry(fdtable, &key, nentry); - if (!nentry) - { + if(!nentry) { ps->lasterr = "can't add subtable entry"; return SS_PLUGIN_FAILURE; } data.s64 = 123; - auto res = in->table_writer_ext->write_entry_field(fdtable, nentry, ps->table_field_fdtable_pid, &data); - if (res != SS_PLUGIN_SUCCESS) - { + auto res = in->table_writer_ext->write_entry_field(fdtable, + nentry, + ps->table_field_fdtable_pid, + &data); + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't write subtable entry field"; return SS_PLUGIN_FAILURE; } data.str = "world"; - res = in->table_writer_ext->write_entry_field(fdtable, nentry, ps->table_field_fdtable_custom, &data); - if (res != SS_PLUGIN_SUCCESS) - { + res = in->table_writer_ext->write_entry_field(fdtable, + nentry, + ps->table_field_fdtable_custom, + &data); + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't write subtable entry custom field"; return SS_PLUGIN_FAILURE; } @@ -246,13 +240,11 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, return SS_PLUGIN_SUCCESS; } - //remove one entry from the fdtable - if(ps->step == 1) - { + // remove one entry from the fdtable + if(ps->step == 1) { key.s64 = 0; auto res = in->table_writer_ext->erase_table_entry(fdtable, &key); - if (res != SS_PLUGIN_SUCCESS) - { + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't erase subtable entry"; return SS_PLUGIN_FAILURE; } @@ -262,12 +254,10 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, return SS_PLUGIN_SUCCESS; } - //clear the fdtable - if(ps->step == 2) - { + // clear the fdtable + if(ps->step == 2) { auto res = in->table_writer_ext->clear_table(fdtable); - if (res != SS_PLUGIN_SUCCESS) - { + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't clear subtable"; return SS_PLUGIN_FAILURE; } @@ -281,10 +271,9 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_syscall_subtables(plugin_api& out) -{ +void get_plugin_api_sample_syscall_subtables(plugin_api& out) { memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; diff --git a/userspace/libsinsp/test/plugins/syscall_subtables_array.cpp b/userspace/libsinsp/test/plugins/syscall_subtables_array.cpp index fc411fac7a..44daca24ee 100644 --- a/userspace/libsinsp/test/plugins/syscall_subtables_array.cpp +++ b/userspace/libsinsp/test/plugins/syscall_subtables_array.cpp @@ -26,8 +26,7 @@ limitations under the License. namespace { -struct plugin_state -{ +struct plugin_state { std::string lasterr; ss_plugin_table_t* thread_table; @@ -37,70 +36,61 @@ struct plugin_state uint8_t step = 0; }; -const char* plugin_get_required_api_version() -{ +const char* plugin_get_required_api_version() { return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ +const char* plugin_get_version() { return "0.1.0"; } -const char* plugin_get_name() -{ +const char* plugin_get_name() { return "sample_subtables_array"; } -const char* plugin_get_description() -{ +const char* plugin_get_description() { return "some desc"; } -const char* plugin_get_contact() -{ +const char* plugin_get_contact() { return "some contact"; } -const char* plugin_get_parse_event_sources() -{ +const char* plugin_get_parse_event_sources() { return "[\"syscall\"]"; } -uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - static uint16_t types[] = { PPME_SYSCALL_OPEN_E }; - *num_types = sizeof(types) / sizeof(uint16_t); - return &types[0]; +uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) { + static uint16_t types[] = {PPME_SYSCALL_OPEN_E}; + *num_types = sizeof(types) / sizeof(uint16_t); + return &types[0]; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { *rc = SS_PLUGIN_SUCCESS; auto ret = new plugin_state(); - if (!in || !in->tables) - { + if(!in || !in->tables) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "invalid config input"; return ret; } // get an accessor to the threads table - ret->thread_table = in->tables->get_table( - in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); - if (!ret->thread_table) - { + ret->thread_table = + in->tables->get_table(in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); + if(!ret->thread_table) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't access thread table"; return ret; } // get an accessor to the file descriptor tables owned by each thread info - ret->table_field_envtable = in->tables->fields.get_table_field( - ret->thread_table, "env", ss_plugin_state_type::SS_PLUGIN_ST_TABLE); - if (!ret->table_field_envtable) - { + ret->table_field_envtable = + in->tables->fields.get_table_field(ret->thread_table, + "env", + ss_plugin_state_type::SS_PLUGIN_ST_TABLE); + if(!ret->table_field_envtable) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't get envtable field in thread table"; return ret; @@ -109,8 +99,7 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) // create a new thread info -- the purpose is just to access its file // descriptor table and obtain accessors for fields of that sub-table auto entry = in->tables->writer_ext->create_table_entry(ret->thread_table); - if (!entry) - { + if(!entry) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't create subtable entry (init-time)"; return ret; @@ -118,19 +107,22 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) // read pointer to file descriptor table owned by the new thread info ss_plugin_state_data data; - *rc = in->tables->reader_ext->read_entry_field(ret->thread_table, entry, ret->table_field_envtable, &data); - if (*rc != SS_PLUGIN_SUCCESS) - { + *rc = in->tables->reader_ext->read_entry_field(ret->thread_table, + entry, + ret->table_field_envtable, + &data); + if(*rc != SS_PLUGIN_SUCCESS) { ret->lasterr = "can't read sub-table table entry field (init-time)"; return ret; } auto envtable = data.table; // obtain accessor to one of the fields of file descriptor tables (name) - ret->table_field_envtable_value = in->tables->fields_ext->get_table_field( - envtable, "value", ss_plugin_state_type::SS_PLUGIN_ST_STRING); - if (!ret->table_field_envtable_value) - { + ret->table_field_envtable_value = + in->tables->fields_ext->get_table_field(envtable, + "value", + ss_plugin_state_type::SS_PLUGIN_ST_STRING); + if(!ret->table_field_envtable_value) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't get sub-table 'value' field"; return ret; @@ -142,18 +134,17 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) return ret; } -void plugin_destroy(ss_plugin_t* s) -{ +void plugin_destroy(ss_plugin_t* s) { delete reinterpret_cast(s); } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } -ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_event_parse_input* in) -{ +ss_plugin_rc plugin_parse_event(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_event_parse_input* in) { auto ps = reinterpret_cast(s); ss_plugin_state_data key; ss_plugin_state_data out; @@ -161,63 +152,66 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, key.s64 = 0; ss_plugin_table_entry_t* tinfo = in->table_reader_ext->get_table_entry(ps->thread_table, &key); - if (!tinfo) - { + if(!tinfo) { ps->lasterr = "can't get table entry"; return SS_PLUGIN_FAILURE; } - auto res = in->table_reader_ext->read_entry_field(ps->thread_table, tinfo, ps->table_field_envtable, &out); - if (res != SS_PLUGIN_SUCCESS) - { + auto res = in->table_reader_ext->read_entry_field(ps->thread_table, + tinfo, + ps->table_field_envtable, + &out); + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't read table entry field"; return SS_PLUGIN_FAILURE; } ss_plugin_table_t* envtable = out.table; - //add entries to the envtable - if(ps->step == 0) - { + // add entries to the envtable + if(ps->step == 0) { int max_iterations = 10; - for (int i = 0; i < max_iterations; i++) - { + for(int i = 0; i < max_iterations; i++) { auto nentry = in->table_writer_ext->create_table_entry(envtable); - if (!nentry) - { + if(!nentry) { ps->lasterr = "can't create subtable entry"; printf("ERR %s\n", ps->lasterr.c_str()); return SS_PLUGIN_FAILURE; } key.s64 = i; nentry = in->table_writer_ext->add_table_entry(envtable, &key, nentry); - if (!nentry) - { + if(!nentry) { ps->lasterr = "can't add subtable entry"; printf("ERR %s\n", ps->lasterr.c_str()); return SS_PLUGIN_FAILURE; } data.str = "hello"; - res = in->table_reader_ext->read_entry_field(envtable, nentry, ps->table_field_envtable_value, &data); - if (res != SS_PLUGIN_SUCCESS) - { - ps->lasterr = "can't read subtable entry value field: " + std::string(in->get_owner_last_error(in->owner)); + res = in->table_reader_ext->read_entry_field(envtable, + nentry, + ps->table_field_envtable_value, + &data); + if(res != SS_PLUGIN_SUCCESS) { + ps->lasterr = "can't read subtable entry value field: " + + std::string(in->get_owner_last_error(in->owner)); printf("ERR %s\n", ps->lasterr.c_str()); return SS_PLUGIN_FAILURE; } - if (strcmp(data.str, "") != 0) - { - ps->lasterr = "wrong string read from subtable entry value field: " + std::string(data.str); + if(strcmp(data.str, "") != 0) { + ps->lasterr = "wrong string read from subtable entry value field: " + + std::string(data.str); printf("ERR %s\n", ps->lasterr.c_str()); return SS_PLUGIN_FAILURE; } data.str = "hello"; - res = in->table_writer_ext->write_entry_field(envtable, nentry, ps->table_field_envtable_value, &data); - if (res != SS_PLUGIN_SUCCESS) - { - ps->lasterr = "can't write subtable entry value field: " + std::string(in->get_owner_last_error(in->owner)); + res = in->table_writer_ext->write_entry_field(envtable, + nentry, + ps->table_field_envtable_value, + &data); + if(res != SS_PLUGIN_SUCCESS) { + ps->lasterr = "can't write subtable entry value field: " + + std::string(in->get_owner_last_error(in->owner)); printf("ERR %s\n", ps->lasterr.c_str()); return SS_PLUGIN_FAILURE; } @@ -231,12 +225,10 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, } // remove one entry from the envtable - if(ps->step == 1) - { + if(ps->step == 1) { key.s64 = 0; auto res = in->table_writer_ext->erase_table_entry(envtable, &key); - if (res != SS_PLUGIN_SUCCESS) - { + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't erase subtable entry"; printf("ERR %s\n", ps->lasterr.c_str()); return SS_PLUGIN_FAILURE; @@ -248,11 +240,9 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, } // clear the envtable - if(ps->step == 2) - { + if(ps->step == 2) { auto res = in->table_writer_ext->clear_table(envtable); - if (res != SS_PLUGIN_SUCCESS) - { + if(res != SS_PLUGIN_SUCCESS) { ps->lasterr = "can't clear subtable"; printf("ERR %s\n", ps->lasterr.c_str()); return SS_PLUGIN_FAILURE; @@ -266,10 +256,9 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, return SS_PLUGIN_SUCCESS; } -} // anonynous namespace +} // namespace -void get_plugin_api_sample_syscall_subtables_array(plugin_api& out) -{ +void get_plugin_api_sample_syscall_subtables_array(plugin_api& out) { memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; diff --git a/userspace/libsinsp/test/plugins/syscall_tables.cpp b/userspace/libsinsp/test/plugins/syscall_tables.cpp index b3c959966b..6fa59bd1ae 100644 --- a/userspace/libsinsp/test/plugins/syscall_tables.cpp +++ b/userspace/libsinsp/test/plugins/syscall_tables.cpp @@ -30,8 +30,7 @@ namespace { * Example of plugin that accesses the thread table and that exposes its own * sta table. The goal is to test all the methods of the table API. */ -struct plugin_state -{ +struct plugin_state { std::string lasterr; ss_plugin_table_t* thread_table; ss_plugin_table_field_t* thread_static_field; @@ -41,60 +40,50 @@ struct plugin_state ss_plugin_table_field_t* internal_dynamic_field; }; -const char* plugin_get_required_api_version() -{ +const char* plugin_get_required_api_version() { return PLUGIN_API_VERSION_STR; } -const char* plugin_get_version() -{ +const char* plugin_get_version() { return "0.1.0"; } -const char* plugin_get_name() -{ +const char* plugin_get_name() { return "sample_tables"; } -const char* plugin_get_description() -{ +const char* plugin_get_description() { return "some desc"; } -const char* plugin_get_contact() -{ +const char* plugin_get_contact() { return "some contact"; } -const char* plugin_get_parse_event_sources() -{ +const char* plugin_get_parse_event_sources() { return "[\"syscall\"]"; } -uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) -{ - static uint16_t *types = {}; +uint16_t* plugin_get_parse_event_types(uint32_t* num_types, ss_plugin_t* s) { + static uint16_t* types = {}; *num_types = 0; return types; } -ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) -{ +ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) { *rc = SS_PLUGIN_SUCCESS; auto ret = new plugin_state(); - if (!in || !in->tables) - { + if(!in || !in->tables) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "invalid config input"; return ret; } // get accessor for thread table - ret->thread_table = in->tables->get_table( - in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); - if (!ret->thread_table) - { + ret->thread_table = + in->tables->get_table(in->owner, "threads", ss_plugin_state_type::SS_PLUGIN_ST_INT64); + if(!ret->thread_table) { *rc = SS_PLUGIN_FAILURE; auto err = in->get_owner_last_error(in->owner); ret->lasterr = err ? err : "can't access thread table"; @@ -103,10 +92,11 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) // get an existing field from thread table entries // todo(jasondellaluce): add tests for fields of other types as well - ret->thread_static_field = in->tables->fields.get_table_field( - ret->thread_table, "comm", ss_plugin_state_type::SS_PLUGIN_ST_STRING); - if (!ret->thread_static_field) - { + ret->thread_static_field = + in->tables->fields.get_table_field(ret->thread_table, + "comm", + ss_plugin_state_type::SS_PLUGIN_ST_STRING); + if(!ret->thread_static_field) { *rc = SS_PLUGIN_FAILURE; auto err = in->get_owner_last_error(in->owner); ret->lasterr = err ? err : "can't get static field in thread table"; @@ -115,19 +105,21 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) // define a new field in thread table entries // todo(jasondellaluce): add tests for fields of other types as well - ret->thread_dynamic_field = in->tables->fields.add_table_field( - ret->thread_table, "some_new_dynamic_field", ss_plugin_state_type::SS_PLUGIN_ST_UINT64); - if (!ret->thread_dynamic_field) - { + ret->thread_dynamic_field = + in->tables->fields.add_table_field(ret->thread_table, + "some_new_dynamic_field", + ss_plugin_state_type::SS_PLUGIN_ST_UINT64); + if(!ret->thread_dynamic_field) { *rc = SS_PLUGIN_FAILURE; auto err = in->get_owner_last_error(in->owner); ret->lasterr = err ? err : "can't add dynamic field in thread table"; return ret; } - ret->thread_dynamic_field_str = in->tables->fields.add_table_field( - ret->thread_table, "some_new_dynamic_field_str", ss_plugin_state_type::SS_PLUGIN_ST_STRING); - if (!ret->thread_dynamic_field_str) - { + ret->thread_dynamic_field_str = + in->tables->fields.add_table_field(ret->thread_table, + "some_new_dynamic_field_str", + ss_plugin_state_type::SS_PLUGIN_ST_STRING); + if(!ret->thread_dynamic_field_str) { *rc = SS_PLUGIN_FAILURE; auto err = in->get_owner_last_error(in->owner); ret->lasterr = err ? err : "can't add dynamic field in thread table"; @@ -137,18 +129,17 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) // define a new table that keeps a counter for all events. // todo(jasondellaluce): add tests for fields of other types as well ret->internal_table = sample_table::create("plugin_sample", ret->lasterr); - ret->internal_dynamic_field = ret->internal_table->fields.add_table_field( - ret->internal_table->table, "u64_val", - ss_plugin_state_type::SS_PLUGIN_ST_UINT64); - if (!ret->internal_dynamic_field) - { + ret->internal_dynamic_field = + ret->internal_table->fields.add_table_field(ret->internal_table->table, + "u64_val", + ss_plugin_state_type::SS_PLUGIN_ST_UINT64); + if(!ret->internal_dynamic_field) { *rc = SS_PLUGIN_FAILURE; ret->lasterr = "can't define internal table field"; return ret; } - if (SS_PLUGIN_SUCCESS != in->tables->add_table(in->owner, ret->internal_table.get())) - { + if(SS_PLUGIN_SUCCESS != in->tables->add_table(in->owner, ret->internal_table.get())) { *rc = SS_PLUGIN_FAILURE; auto err = in->get_owner_last_error(in->owner); ret->lasterr = err ? err : "can't add internal table"; @@ -157,19 +148,18 @@ ss_plugin_t* plugin_init(const ss_plugin_init_input* in, ss_plugin_rc* rc) return ret; } -void plugin_destroy(ss_plugin_t* s) -{ +void plugin_destroy(ss_plugin_t* s) { delete reinterpret_cast(s); } -const char* plugin_get_last_error(ss_plugin_t* s) -{ - return ((plugin_state *) s)->lasterr.c_str(); +const char* plugin_get_last_error(ss_plugin_t* s) { + return ((plugin_state*)s)->lasterr.c_str(); } // parses events and keeps a count for each thread about the syscalls of the open family -ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, const ss_plugin_event_parse_input* in) -{ +ss_plugin_rc plugin_parse_event(ss_plugin_t* s, + const ss_plugin_event_input* ev, + const ss_plugin_event_parse_input* in) { static int64_t s_new_thread_tid = 999999; int step = 0; ss_plugin_state_data tmp; @@ -179,9 +169,11 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, // get table name step++; { - if (strcmp("threads", in->table_reader_ext->get_table_name(ps->thread_table))) - { - fprintf(stderr, "table_reader.get_table_name (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(strcmp("threads", in->table_reader_ext->get_table_name(ps->thread_table))) { + fprintf(stderr, + "table_reader.get_table_name (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } } @@ -190,9 +182,12 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, step++; { auto size = in->table_reader_ext->get_table_size(ps->thread_table); - if (size != 1) - { - fprintf(stderr, "table_reader.get_table_size (%d) failure: (%lu) %s\n", step, size, in->get_owner_last_error(in->owner)); + if(size != 1) { + fprintf(stderr, + "table_reader.get_table_size (%d) failure: (%lu) %s\n", + step, + size, + in->get_owner_last_error(in->owner)); exit(1); } } @@ -202,18 +197,24 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, { tmp.s64 = 1; thread = in->table_reader_ext->get_table_entry(ps->thread_table, &tmp); - if (!thread) - { - fprintf(stderr, "table_reader.get_table_entry (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(!thread) { + fprintf(stderr, + "table_reader.get_table_entry (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_static_field, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_static_field, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } - if (strcmp("init", tmp.str)) - { + if(strcmp("init", tmp.str)) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } @@ -222,29 +223,42 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, // read-write dynamic field from existing thread step++; { - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_dynamic_field, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } - if (tmp.u64 != 0) - { + if(tmp.u64 != 0) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } tmp.u64 = 5; - if (SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, thread, ps->thread_dynamic_field, &tmp)) - { - fprintf(stderr, "table_reader.write_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_dynamic_field, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (tmp.u64 != 5) - { + if(SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field, + &tmp)) { + fprintf(stderr, + "table_reader.write_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(tmp.u64 != 5) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } @@ -253,29 +267,43 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, // read-write dynamic field (str) from existing thread step++; { - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_dynamic_field_str, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field_str, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } - if (strcmp("", tmp.str)) - { + if(strcmp("", tmp.str)) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } tmp.str = "hello"; - if (SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, thread, ps->thread_dynamic_field_str, &tmp)) - { - fprintf(stderr, "table_reader.write_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_dynamic_field_str, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (strcmp("hello", tmp.str)) - { + if(SS_PLUGIN_SUCCESS != + in->table_writer_ext->write_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field_str, + &tmp)) { + fprintf(stderr, + "table_reader.write_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field_str, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(strcmp("hello", tmp.str)) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } @@ -287,8 +315,7 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, in->table_reader_ext->release_table_entry(ps->thread_table, thread); tmp.s64 = s_new_thread_tid; thread = in->table_reader_ext->get_table_entry(ps->thread_table, &tmp); - if (thread) - { + if(thread) { fprintf(stderr, "table_reader.get_table_entry (%d) inconsistency\n", step); exit(1); } @@ -298,9 +325,11 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, step++; { thread = in->table_writer_ext->create_table_entry(ps->thread_table); - if (!thread) - { - fprintf(stderr, "table_reader.create_table_entry (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(!thread) { + fprintf(stderr, + "table_reader.create_table_entry (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } in->table_writer_ext->destroy_table_entry(ps->thread_table, thread); @@ -310,22 +339,28 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, step++; { thread = in->table_writer_ext->create_table_entry(ps->thread_table); - if (!thread) - { - fprintf(stderr, "table_reader.create_table_entry (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(!thread) { + fprintf(stderr, + "table_reader.create_table_entry (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } tmp.s64 = s_new_thread_tid; thread = in->table_writer_ext->add_table_entry(ps->thread_table, &tmp, thread); - if (!thread) - { - fprintf(stderr, "table_reader.add_table_entry (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(!thread) { + fprintf(stderr, + "table_reader.add_table_entry (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } auto size = in->table_reader_ext->get_table_size(ps->thread_table); - if (size != 2) - { - fprintf(stderr, "table_reader.get_table_size (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(size != 2) { + fprintf(stderr, + "table_reader.get_table_size (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } in->table_reader_ext->release_table_entry(ps->thread_table, thread); @@ -336,9 +371,11 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, { tmp.s64 = s_new_thread_tid; thread = in->table_reader_ext->get_table_entry(ps->thread_table, &tmp); - if (!thread) - { - fprintf(stderr, "table_reader.get_table_entry (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(!thread) { + fprintf(stderr, + "table_reader.get_table_entry (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } } @@ -346,29 +383,42 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, // read and write from newly-created thread (static field) step++; { - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_static_field, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_static_field, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } - if (strcmp("", tmp.str)) - { + if(strcmp("", tmp.str)) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } tmp.str = "hello"; - if (SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, thread, ps->thread_static_field, &tmp)) - { - fprintf(stderr, "table_reader.write_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_static_field, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (strcmp("hello", tmp.str)) - { + if(SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, + thread, + ps->thread_static_field, + &tmp)) { + fprintf(stderr, + "table_reader.write_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_static_field, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(strcmp("hello", tmp.str)) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } @@ -377,29 +427,42 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, // read and write from newly-created thread (dynamic field) step++; { - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_dynamic_field, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } - if (tmp.u64 != 0) - { + if(tmp.u64 != 0) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } tmp.u64 = 5; - if (SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, thread, ps->thread_dynamic_field, &tmp)) - { - fprintf(stderr, "table_reader.write_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, thread, ps->thread_dynamic_field, &tmp)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); - exit(1); - } - if (tmp.u64 != 5) - { + if(SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field, + &tmp)) { + fprintf(stderr, + "table_reader.write_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(SS_PLUGIN_SUCCESS != in->table_reader_ext->read_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field, + &tmp)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); + exit(1); + } + if(tmp.u64 != 5) { fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", step); exit(1); } @@ -411,8 +474,7 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, step++; { tmp.s64 = 10; - if (SS_PLUGIN_SUCCESS == in->table_writer_ext->erase_table_entry(ps->thread_table, &tmp)) - { + if(SS_PLUGIN_SUCCESS == in->table_writer_ext->erase_table_entry(ps->thread_table, &tmp)) { fprintf(stderr, "table_reader.erase_table_entry (%d) inconsistency\n", step); exit(1); } @@ -421,11 +483,10 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, // loop over all threads, we expect to only find two (init, and our new one) step++; { - struct iterate_entries_state - { + struct iterate_entries_state { int* step = nullptr; uint64_t count = 0; - const ss_plugin_event_parse_input *in = nullptr; + const ss_plugin_event_parse_input* in = nullptr; plugin_state* ps = nullptr; }; @@ -434,56 +495,68 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, its1.in = in; its1.ps = ps; its1.step = &step; - auto it1 = [](ss_plugin_table_iterator_state_t* s, ss_plugin_table_entry_t* e) -> ss_plugin_bool - { - auto st = (iterate_entries_state*) s; + auto it1 = [](ss_plugin_table_iterator_state_t* s, + ss_plugin_table_entry_t* e) -> ss_plugin_bool { + auto st = (iterate_entries_state*)s; st->count++; ss_plugin_state_data val; - if (SS_PLUGIN_SUCCESS != st->in->table_reader_ext->read_entry_field(st->ps->thread_table, e, st->ps->thread_static_field, &val)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", (*st->step), st->in->get_owner_last_error(st->in->owner)); + if(SS_PLUGIN_SUCCESS != + st->in->table_reader_ext->read_entry_field(st->ps->thread_table, + e, + st->ps->thread_static_field, + &val)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + (*st->step), + st->in->get_owner_last_error(st->in->owner)); exit(1); } - if (strcmp(val.str, "init") == 0 || strcmp(val.str, "hello") == 0) - { - if (SS_PLUGIN_SUCCESS != st->in->table_reader_ext->read_entry_field(st->ps->thread_table, e, st->ps->thread_dynamic_field, &val)) - { - fprintf(stderr, "table_reader.read_entry_field (%d) failure: %s\n", (*st->step), st->in->get_owner_last_error(st->in->owner)); + if(strcmp(val.str, "init") == 0 || strcmp(val.str, "hello") == 0) { + if(SS_PLUGIN_SUCCESS != + st->in->table_reader_ext->read_entry_field(st->ps->thread_table, + e, + st->ps->thread_dynamic_field, + &val)) { + fprintf(stderr, + "table_reader.read_entry_field (%d) failure: %s\n", + (*st->step), + st->in->get_owner_last_error(st->in->owner)); exit(1); } - if (val.u64 != 5) - { - fprintf(stderr, "table_reader.read_entry_field (%d) inconsistency\n", (*st->step)); + if(val.u64 != 5) { + fprintf(stderr, + "table_reader.read_entry_field (%d) inconsistency\n", + (*st->step)); exit(1); } - } - else - { - fprintf(stderr, "table_reader.read_entry_field (%d) unexpected value: %s\n", (*st->step), val.str); + } else { + fprintf(stderr, + "table_reader.read_entry_field (%d) unexpected value: %s\n", + (*st->step), + val.str); exit(1); } return 1; }; - if (in->table_reader_ext->iterate_entries(ps->thread_table, it1, (ss_plugin_table_iterator_state_t*) &its1) != 1) - { + if(in->table_reader_ext->iterate_entries(ps->thread_table, + it1, + (ss_plugin_table_iterator_state_t*)&its1) != 1) { fprintf(stderr, "table_reader.iterate_entries (%d) unexpected break-out\n", step); exit(1); } - if (its1.count != 2) - { + if(its1.count != 2) { fprintf(stderr, "table_reader.iterate_entries (%d) unexpected count result\n", step); exit(1); } // iteration with break-out - auto it2 = [](ss_plugin_table_iterator_state_t* s, ss_plugin_table_entry_t* e) -> ss_plugin_bool - { - return false; - }; - if (in->table_reader_ext->iterate_entries(ps->thread_table, it2, (ss_plugin_table_iterator_state_t*) &its1) != 0) - { + auto it2 = [](ss_plugin_table_iterator_state_t* s, + ss_plugin_table_entry_t* e) -> ss_plugin_bool { return false; }; + if(in->table_reader_ext->iterate_entries(ps->thread_table, + it2, + (ss_plugin_table_iterator_state_t*)&its1) != 0) { fprintf(stderr, "table_reader.iterate_entries (%d) break-out was expected\n", step); exit(1); } @@ -493,8 +566,7 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, step++; { tmp.s64 = s_new_thread_tid; - if (SS_PLUGIN_SUCCESS != in->table_writer_ext->erase_table_entry(ps->thread_table, &tmp)) - { + if(SS_PLUGIN_SUCCESS != in->table_writer_ext->erase_table_entry(ps->thread_table, &tmp)) { fprintf(stderr, "table_reader.erase_table_entry (%d) inconsistency\n", step); exit(1); } @@ -505,21 +577,34 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, { tmp.s64 = 1; thread = in->table_reader_ext->get_table_entry(ps->thread_table, &tmp); - if (!thread) - { - fprintf(stderr, "table_reader.get_table_entry (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(!thread) { + fprintf(stderr, + "table_reader.get_table_entry (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } tmp.u64 = 0; - if (SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, thread, ps->thread_dynamic_field, &tmp)) - { - fprintf(stderr, "table_reader.write_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field, + &tmp)) { + fprintf(stderr, + "table_reader.write_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } tmp.str = ""; - if (SS_PLUGIN_SUCCESS != in->table_writer_ext->write_entry_field(ps->thread_table, thread, ps->thread_dynamic_field_str, &tmp)) - { - fprintf(stderr, "table_reader.write_entry_field (%d) failure: %s\n", step, in->get_owner_last_error(in->owner)); + if(SS_PLUGIN_SUCCESS != + in->table_writer_ext->write_entry_field(ps->thread_table, + thread, + ps->thread_dynamic_field_str, + &tmp)) { + fprintf(stderr, + "table_reader.write_entry_field (%d) failure: %s\n", + step, + in->get_owner_last_error(in->owner)); exit(1); } @@ -529,10 +614,9 @@ ss_plugin_rc plugin_parse_event(ss_plugin_t *s, const ss_plugin_event_input *ev, return SS_PLUGIN_SUCCESS; } -} // anonymous namespace +} // anonymous namespace -void get_plugin_api_sample_syscall_tables(plugin_api& out) -{ +void get_plugin_api_sample_syscall_tables(plugin_api& out) { memset(&out, 0, sizeof(plugin_api)); out.get_required_api_version = plugin_get_required_api_version; out.get_version = plugin_get_version; diff --git a/userspace/libsinsp/test/ppm_api_version.ut.cpp b/userspace/libsinsp/test/ppm_api_version.ut.cpp index 54959f4700..bcac760735 100644 --- a/userspace/libsinsp/test/ppm_api_version.ut.cpp +++ b/userspace/libsinsp/test/ppm_api_version.ut.cpp @@ -19,14 +19,12 @@ limitations under the License. #include #include -TEST(api_version, unpack) -{ +TEST(api_version, unpack) { uint64_t ver1_2_3 = (1ULL << 44) | (2ULL << 24) | 3; ASSERT_EQ(ver1_2_3, PPM_API_VERSION(1, 2, 3)); } -TEST(api_version, pack) -{ +TEST(api_version, pack) { uint64_t ver1_2_3 = (1ULL << 44) | (2ULL << 24) | 3; EXPECT_EQ(1u, PPM_API_VERSION_MAJOR(ver1_2_3)); EXPECT_EQ(2u, PPM_API_VERSION_MINOR(ver1_2_3)); diff --git a/userspace/libsinsp/test/prefix_search.ut.cpp b/userspace/libsinsp/test/prefix_search.ut.cpp index e9285b1e34..1bb16de5bb 100644 --- a/userspace/libsinsp/test/prefix_search.ut.cpp +++ b/userspace/libsinsp/test/prefix_search.ut.cpp @@ -22,8 +22,7 @@ limitations under the License. using namespace std; -TEST(prefix_search_test, basic) -{ +TEST(prefix_search_test, basic) { path_prefix_search tree; tree.add_search_path("/var/run"); @@ -52,8 +51,7 @@ TEST(prefix_search_test, basic) ASSERT_FALSE(found); } -TEST(prefix_search_test, as_string) -{ +TEST(prefix_search_test, as_string) { path_prefix_search tree; tree.add_search_path("/var/run"); @@ -69,7 +67,7 @@ TEST(prefix_search_test, as_string) // Note: /var/run/dmesg is not included because /var/run is // already added and is a prefix of /var/run/dmesg. - const char *expected = R"STR(root -> + const char* expected = R"STR(root -> etc -> lib -> opt -> @@ -84,11 +82,10 @@ TEST(prefix_search_test, as_string) run -> )STR"; - ASSERT_STREQ(treerep.c_str(), expected); + ASSERT_STREQ(treerep.c_str(), expected); } -TEST(prefix_search_test, glob) -{ +TEST(prefix_search_test, glob) { path_prefix_search tree; tree.add_search_path("/opt/*/subdir"); @@ -111,8 +108,7 @@ TEST(prefix_search_test, glob) ASSERT_TRUE(found); } -TEST(prefix_search_test, subpaths) -{ +TEST(prefix_search_test, subpaths) { path_prefix_search tree; tree.add_search_path("/var/log/messages"); @@ -165,8 +161,7 @@ TEST(prefix_search_test, subpaths) ASSERT_TRUE(treerep.find("var") == string::npos); } -TEST(prefix_search_test, root_dir_match) -{ +TEST(prefix_search_test, root_dir_match) { path_prefix_search tree; tree.add_search_path("/"); @@ -183,8 +178,7 @@ TEST(prefix_search_test, root_dir_match) ASSERT_TRUE(found); } -TEST(prefix_search_test, maps) -{ +TEST(prefix_search_test, maps) { path_prefix_map tree; uint32_t val; const uint32_t* match; @@ -238,8 +232,7 @@ TEST(prefix_search_test, maps) ASSERT_TRUE(*match == 5); } -TEST(prefix_search_test, root_dir_maps) -{ +TEST(prefix_search_test, root_dir_maps) { path_prefix_map tree; uint32_t val; const uint32_t* match; @@ -269,8 +262,7 @@ TEST(prefix_search_test, root_dir_maps) ASSERT_TRUE(*match == 2); } -TEST(prefix_search_test, container_images) -{ +TEST(prefix_search_test, container_images) { path_prefix_map tree; uint32_t val; const uint32_t* match; diff --git a/userspace/libsinsp/test/procfs_utils.ut.cpp b/userspace/libsinsp/test/procfs_utils.ut.cpp index 98f03b40b9..43323ae777 100644 --- a/userspace/libsinsp/test/procfs_utils.ut.cpp +++ b/userspace/libsinsp/test/procfs_utils.ut.cpp @@ -22,17 +22,14 @@ limitations under the License. using namespace libsinsp::procfs_utils; -TEST(procfs_utils_test, get_userns_uid) -{ +TEST(procfs_utils_test, get_userns_uid) { std::string uidmap = " 0 1000 0\n 1 1000000 1000\n"; std::stringstream s(uidmap); ASSERT_EQ(get_userns_root_uid(s), 1000); } - -TEST(procfs_utils_test, get_userns_uid_root) -{ +TEST(procfs_utils_test, get_userns_uid_root) { std::string uidmap = " 0 0 0\n"; std::stringstream s(uidmap); diff --git a/userspace/libsinsp/test/public_sinsp_API/event_related.cpp b/userspace/libsinsp/test/public_sinsp_API/event_related.cpp index f4b9a68717..08fe6ac8a3 100644 --- a/userspace/libsinsp/test/public_sinsp_API/event_related.cpp +++ b/userspace/libsinsp/test/public_sinsp_API/event_related.cpp @@ -2,8 +2,7 @@ #include /* Check the `is_unused_event` API works correctly */ -TEST(events, check_unused_events) -{ +TEST(events, check_unused_events) { /* `PPME_SYSCALL_EXECVE_8_E` has the `EF_OLD_VERSION` flag */ ASSERT_EQ(libsinsp::events::is_unused_event(PPME_SYSCALL_EXECVE_8_E), false); @@ -15,8 +14,7 @@ TEST(events, check_unused_events) } /* Check the `is_old_version_event` API works correctly */ -TEST(events, check_old_version_events) -{ +TEST(events, check_old_version_events) { /* `PPME_SYSCALL_EXECVE_8_E` has only the `EF_OLD_VERSION` flag */ ASSERT_EQ(libsinsp::events::is_old_version_event(PPME_SYSCALL_EXECVE_14_E), true); @@ -25,8 +23,7 @@ TEST(events, check_old_version_events) } /* Check if the events category is correct */ -TEST(events, check_events_category) -{ +TEST(events, check_events_category) { /* Assert that the API works good */ ASSERT_EQ(libsinsp::events::is_syscall_event(PPME_SYSCALL_EXECVE_8_E), true); ASSERT_EQ(libsinsp::events::is_syscall_event(PPME_SCHEDSWITCH_6_X), false); @@ -42,4 +39,4 @@ TEST(events, check_events_category) ASSERT_EQ(libsinsp::events::is_plugin_event(PPME_PLUGINEVENT_E), true); ASSERT_EQ(libsinsp::events::is_plugin_event(PPME_SYSCALL_CLONE_20_E), false); -} \ No newline at end of file +} diff --git a/userspace/libsinsp/test/public_sinsp_API/events_set.cpp b/userspace/libsinsp/test/public_sinsp_API/events_set.cpp index e1414e0446..451ba94e9f 100644 --- a/userspace/libsinsp/test/public_sinsp_API/events_set.cpp +++ b/userspace/libsinsp/test/public_sinsp_API/events_set.cpp @@ -20,8 +20,7 @@ limitations under the License. #include #include "../test_utils.h" -TEST(events_set, check_size) -{ +TEST(events_set, check_size) { auto sc_set = libsinsp::events::set(); ASSERT_EQ(sc_set.size(), 0); ASSERT_TRUE(sc_set.empty()); @@ -43,8 +42,7 @@ TEST(events_set, check_size) ASSERT_TRUE(sc_set.empty()); } -TEST(events_set, check_equal) -{ +TEST(events_set, check_equal) { auto sc_set = libsinsp::events::set(); sc_set.insert(PPM_SC_ACCEPT); sc_set.insert(PPM_SC_ACCEPT4); @@ -66,11 +64,10 @@ TEST(events_set, check_equal) ASSERT_TRUE(other_set.equals(libsinsp::events::set())); } -TEST(events_set, set_check_merge) -{ - auto merge_vec = std::vector{1,2,3,4,5}; - auto intersect_vector = std::vector{1,2,3,4,5}; - auto difference_vector = std::vector{1,2,3,4,5}; +TEST(events_set, set_check_merge) { + auto merge_vec = std::vector{1, 2, 3, 4, 5}; + auto intersect_vector = std::vector{1, 2, 3, 4, 5}; + auto difference_vector = std::vector{1, 2, 3, 4, 5}; auto sc_set_1 = libsinsp::events::set(); sc_set_1.insert((ppm_sc_code)1); @@ -83,14 +80,13 @@ TEST(events_set, set_check_merge) sc_set_2.insert((ppm_sc_code)5); auto sc_set_merge = sc_set_1.merge(sc_set_2); - for (auto val : merge_vec) { + for(auto val : merge_vec) { ASSERT_EQ(sc_set_merge.data()[val], 1); } } -TEST(events_set, set_check_intersect) -{ - auto int_vec = std::vector{1,4}; +TEST(events_set, set_check_intersect) { + auto int_vec = std::vector{1, 4}; auto sc_set_1 = libsinsp::events::set(); sc_set_1.insert((ppm_sc_code)1); @@ -103,14 +99,13 @@ TEST(events_set, set_check_intersect) sc_set_2.insert((ppm_sc_code)5); auto sc_set_int = sc_set_1.intersect(sc_set_2); - for (auto val : int_vec) { + for(auto val : int_vec) { ASSERT_EQ(sc_set_int.data()[val], 1); } } -TEST(events_set, set_check_diff) -{ - auto diff_vec = std::vector{2,3}; +TEST(events_set, set_check_diff) { + auto diff_vec = std::vector{2, 3}; auto sc_set_1 = libsinsp::events::set(); sc_set_1.insert((ppm_sc_code)1); @@ -123,43 +118,58 @@ TEST(events_set, set_check_diff) sc_set_2.insert((ppm_sc_code)4); auto sc_set_diff = sc_set_1.diff(sc_set_2); - for (auto val : diff_vec) { + for(auto val : diff_vec) { ASSERT_TRUE(sc_set_diff.contains((ppm_sc_code)val)); } } -TEST(events_set, names_to_event_set) -{ - auto event_set = libsinsp::events::names_to_event_set(std::unordered_set{"openat","execveat"}); - libsinsp::events::set event_set_truth = {PPME_SYSCALL_OPENAT_E, PPME_SYSCALL_OPENAT_X, - PPME_SYSCALL_OPENAT_2_E, PPME_SYSCALL_OPENAT_2_X, PPME_SYSCALL_EXECVEAT_E, PPME_SYSCALL_EXECVEAT_X}; +TEST(events_set, names_to_event_set) { + auto event_set = libsinsp::events::names_to_event_set( + std::unordered_set{"openat", "execveat"}); + libsinsp::events::set event_set_truth = {PPME_SYSCALL_OPENAT_E, + PPME_SYSCALL_OPENAT_X, + PPME_SYSCALL_OPENAT_2_E, + PPME_SYSCALL_OPENAT_2_X, + PPME_SYSCALL_EXECVEAT_E, + PPME_SYSCALL_EXECVEAT_X}; ASSERT_PPM_EVENT_CODES_EQ(event_set_truth, event_set); - ASSERT_EQ(event_set.size(), 6); // enter/exit events for each event name, special case "openat" has 4 PPME instead of 2 + ASSERT_EQ(event_set.size(), 6); // enter/exit events for each event name, special case "openat" + // has 4 PPME instead of 2 // generic event case - event_set = libsinsp::events::names_to_event_set(std::unordered_set{"openat","execveat","syncfs"}); - event_set_truth = {PPME_SYSCALL_OPENAT_E, PPME_SYSCALL_OPENAT_X, PPME_SYSCALL_OPENAT_2_E, PPME_SYSCALL_OPENAT_2_X, - PPME_SYSCALL_EXECVEAT_E, PPME_SYSCALL_EXECVEAT_X, PPME_GENERIC_E, PPME_GENERIC_X}; + event_set = libsinsp::events::names_to_event_set( + std::unordered_set{"openat", "execveat", "syncfs"}); + event_set_truth = {PPME_SYSCALL_OPENAT_E, + PPME_SYSCALL_OPENAT_X, + PPME_SYSCALL_OPENAT_2_E, + PPME_SYSCALL_OPENAT_2_X, + PPME_SYSCALL_EXECVEAT_E, + PPME_SYSCALL_EXECVEAT_X, + PPME_GENERIC_E, + PPME_GENERIC_X}; ASSERT_PPM_EVENT_CODES_EQ(event_set_truth, event_set); - ASSERT_EQ(event_set.size(), 8); // enter/exit events for each event name, special case "openat" has 4 PPME instead of 2 + ASSERT_EQ(event_set.size(), 8); // enter/exit events for each event name, special case "openat" + // has 4 PPME instead of 2 } // Tests that no generic ppm sc is mapped to an event too // basically, avoid that someone added a new event mapping a once-generic syscall, // and forgot to update libscap/linux/scap_ppm_sc.c::g_events_to_sc_map. -TEST(events_set, generic_no_events) -{ - auto generic_ev_set_truth = libsinsp::events::set({PPME_GENERIC_E, PPME_GENERIC_X}); +TEST(events_set, generic_no_events) { + auto generic_ev_set_truth = + libsinsp::events::set({PPME_GENERIC_E, PPME_GENERIC_X}); auto generic_sc_set = libsinsp::events::event_set_to_sc_set(generic_ev_set_truth); auto final_ev_set = libsinsp::events::sc_set_to_event_set(generic_sc_set); ASSERT_PPM_EVENT_CODES_EQ(final_ev_set, generic_ev_set_truth); } -TEST(events_set, non_syscalls_events) -{ - auto ev_set_truth = libsinsp::events::set({PPME_SYSCALL_POLL_E, PPME_SYSCALL_POLL_X, - PPME_SIGNALDELIVER_E, PPME_SIGNALDELIVER_X, - PPME_PROCINFO_E, PPME_PROCINFO_X}); +TEST(events_set, non_syscalls_events) { + auto ev_set_truth = libsinsp::events::set({PPME_SYSCALL_POLL_E, + PPME_SYSCALL_POLL_X, + PPME_SIGNALDELIVER_E, + PPME_SIGNALDELIVER_X, + PPME_PROCINFO_E, + PPME_PROCINFO_X}); auto sc_set = libsinsp::events::event_set_to_sc_set(ev_set_truth); auto final_ev_set = libsinsp::events::sc_set_to_event_set(sc_set); @@ -174,99 +184,147 @@ TEST(events_set, non_syscalls_events) ASSERT_FALSE(final_ev_set.contains(PPME_PROCINFO_X)); } -TEST(events_set, event_set_to_names_generic_events) -{ - static libsinsp::events::set generic_event_set = {PPME_GENERIC_E, PPME_GENERIC_X}; +TEST(events_set, event_set_to_names_generic_events) { + static libsinsp::events::set generic_event_set = {PPME_GENERIC_E, + PPME_GENERIC_X}; auto names = libsinsp::events::event_set_to_names(generic_event_set); /* Negative assertions. */ - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"execve"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"accept"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"mprotect"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"mmap"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"container"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"procexit"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"umount2"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"eventfd2"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"syscall"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"init_module"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"execve"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"accept"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"mprotect"}).empty()); + ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set{"mmap"}).empty()); + ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set{"container"}) + .empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"procexit"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"umount2"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"eventfd2"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"syscall"}).empty()); + ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set{"init_module"}) + .empty()); /* Random checks for some generic sc events. */ - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"syncfs"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"perf_event_open"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"timer_create"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"lsetxattr"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"getsid"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"sethostname"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"readlinkat"}).empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"syncfs"}).empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"perf_event_open"}) + .empty()); + ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set{"timer_create"}) + .empty()); + ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set{"lsetxattr"}) + .empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"getsid"}).empty()); + ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set{"sethostname"}) + .empty()); + ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set{"readlinkat"}) + .empty()); /* Solely check for some conservative lower bound to roughly ensure * we are getting a whole bunch of generic sc events. * At the time of writing we have about 234 generic sc syscalls as defined * by not having a dedicated PPME_SYSCALL_* or PPME_SOCKET_* definition. - */ + */ ASSERT_GT(names.size(), 180); } -TEST(events_set, event_set_to_names_no_generic_events1) -{ - static std::set names_truth = {"kill", "dup", "umount", "eventfd", "procexit", "container"}; - auto names_unordered = libsinsp::events::event_set_to_names(libsinsp::events::set{PPME_SYSCALL_KILL_E, PPME_SYSCALL_KILL_X, - PPME_SYSCALL_DUP_1_E, PPME_SYSCALL_DUP_1_X, PPME_SYSCALL_UMOUNT_E, PPME_SYSCALL_UMOUNT_X, PPME_SYSCALL_EVENTFD_E, PPME_SYSCALL_EVENTFD_X, PPME_PROCEXIT_E, PPME_CONTAINER_E}); +TEST(events_set, event_set_to_names_no_generic_events1) { + static std::set names_truth = + {"kill", "dup", "umount", "eventfd", "procexit", "container"}; + auto names_unordered = libsinsp::events::event_set_to_names( + libsinsp::events::set{PPME_SYSCALL_KILL_E, + PPME_SYSCALL_KILL_X, + PPME_SYSCALL_DUP_1_E, + PPME_SYSCALL_DUP_1_X, + PPME_SYSCALL_UMOUNT_E, + PPME_SYSCALL_UMOUNT_X, + PPME_SYSCALL_EVENTFD_E, + PPME_SYSCALL_EVENTFD_X, + PPME_PROCEXIT_E, + PPME_CONTAINER_E}); auto names = test_utils::unordered_set_to_ordered(names_unordered); ASSERT_NAMES_EQ(names_truth, names); - ASSERT_TRUE(unordered_set_intersection(names_unordered, std::unordered_set {"syncfs"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names_unordered, std::unordered_set {"eventfd2"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names_unordered, std::unordered_set {"container"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names_unordered, std::unordered_set {"eventfd"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names_unordered, std::unordered_set{"syncfs"}) + .empty()); + ASSERT_TRUE( + unordered_set_intersection(names_unordered, std::unordered_set{"eventfd2"}) + .empty()); + ASSERT_FALSE(unordered_set_intersection(names_unordered, + std::unordered_set{"container"}) + .empty()); + ASSERT_FALSE( + unordered_set_intersection(names_unordered, std::unordered_set{"eventfd"}) + .empty()); } -TEST(events_set, event_set_to_names_no_generic_events2) -{ +TEST(events_set, event_set_to_names_no_generic_events2) { auto names = libsinsp::events::event_set_to_names(libsinsp::events::all_event_set(), false); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"execve"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"accept"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"mprotect"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"mmap"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"container"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"procexit"}).empty()); - ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set {"init_module"}).empty()); - - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"syncfs"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"perf_event_open"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"timer_create"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"lsetxattr"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"getsid"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"sethostname"}).empty()); - ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set {"readlinkat"}).empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"execve"}).empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"accept"}).empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"mprotect"}).empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"mmap"}).empty()); + ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set{"container"}) + .empty()); + ASSERT_FALSE( + unordered_set_intersection(names, std::unordered_set{"procexit"}).empty()); + ASSERT_FALSE(unordered_set_intersection(names, std::unordered_set{"init_module"}) + .empty()); + + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"syncfs"}).empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"perf_event_open"}) + .empty()); + ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set{"timer_create"}) + .empty()); + ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set{"lsetxattr"}) + .empty()); + ASSERT_TRUE( + unordered_set_intersection(names, std::unordered_set{"getsid"}).empty()); + ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set{"sethostname"}) + .empty()); + ASSERT_TRUE(unordered_set_intersection(names, std::unordered_set{"readlinkat"}) + .empty()); } -TEST(events_set, sc_set_to_event_set) -{ +TEST(events_set, sc_set_to_event_set) { libsinsp::events::set sc_set = { - PPM_SC_KILL, - PPM_SC_SENDTO, - PPM_SC_SETRESUID, // note: corner case PPM_SC_SETRESUID32 would fail - PPM_SC_ALARM, + PPM_SC_KILL, + PPM_SC_SENDTO, + PPM_SC_SETRESUID, // note: corner case PPM_SC_SETRESUID32 would fail + PPM_SC_ALARM, }; libsinsp::events::set event_set_truth = { - PPME_SYSCALL_KILL_E, - PPME_SYSCALL_KILL_X, - PPME_SOCKET_SENDTO_E, - PPME_SOCKET_SENDTO_X, - PPME_SYSCALL_SETRESUID_E, - PPME_SYSCALL_SETRESUID_X, - PPME_GENERIC_E, - PPME_GENERIC_X, + PPME_SYSCALL_KILL_E, + PPME_SYSCALL_KILL_X, + PPME_SOCKET_SENDTO_E, + PPME_SOCKET_SENDTO_X, + PPME_SYSCALL_SETRESUID_E, + PPME_SYSCALL_SETRESUID_X, + PPME_GENERIC_E, + PPME_GENERIC_X, }; auto event_set = libsinsp::events::sc_set_to_event_set(sc_set); ASSERT_PPM_EVENT_CODES_EQ(event_set_truth, event_set); } -TEST(events_set, all_non_generic_sc_event_set) -{ - auto event_set = libsinsp::events::all_event_set().filter([&](ppm_event_code e) { return libsinsp::events::is_syscall_event(e); })\ - .diff(libsinsp::events::set{PPME_GENERIC_E, PPME_GENERIC_X}); +TEST(events_set, all_non_generic_sc_event_set) { + auto event_set = + libsinsp::events::all_event_set() + .filter([&](ppm_event_code e) { return libsinsp::events::is_syscall_event(e); }) + .diff(libsinsp::events::set{PPME_GENERIC_E, PPME_GENERIC_X}); /* No generic sc events expected. */ ASSERT_FALSE(event_set.contains(PPME_GENERIC_E)); ASSERT_FALSE(event_set.contains(PPME_GENERIC_X)); @@ -277,9 +335,9 @@ TEST(events_set, all_non_generic_sc_event_set) ASSERT_FALSE(event_set.contains(PPME_PROCEXIT_X)); } -TEST(events_set, all_non_sc_event_set) -{ - auto event_set = libsinsp::events::all_event_set().filter([&](ppm_event_code e) { return !libsinsp::events::is_syscall_event(e); }); +TEST(events_set, all_non_sc_event_set) { + auto event_set = libsinsp::events::all_event_set().filter( + [&](ppm_event_code e) { return !libsinsp::events::is_syscall_event(e); }); /* No sc events at all expected. */ ASSERT_FALSE(event_set.contains(PPME_GENERIC_E)); ASSERT_FALSE(event_set.contains(PPME_GENERIC_X)); diff --git a/userspace/libsinsp/test/public_sinsp_API/interesting_syscalls.cpp b/userspace/libsinsp/test/public_sinsp_API/interesting_syscalls.cpp index 561cd679cb..b6541f3aa6 100644 --- a/userspace/libsinsp/test/public_sinsp_API/interesting_syscalls.cpp +++ b/userspace/libsinsp/test/public_sinsp_API/interesting_syscalls.cpp @@ -20,8 +20,7 @@ limitations under the License. #include #include "../test_utils.h" -TEST(interesting_syscalls, io_sc_set) -{ +TEST(interesting_syscalls, io_sc_set) { libsinsp::events::set io_sc_set_truth; io_sc_set_truth.insert(PPM_SC_READ); @@ -47,8 +46,7 @@ TEST(interesting_syscalls, io_sc_set) ASSERT_PPM_SC_CODES_EQ(io_sc_set_truth, io_sc_set); } -TEST(interesting_syscalls, all_sc_set) -{ +TEST(interesting_syscalls, all_sc_set) { auto sc_set = libsinsp::events::all_sc_set(); /* @@ -59,99 +57,124 @@ TEST(interesting_syscalls, all_sc_set) ASSERT_TRUE(sc_set.size() <= PPM_SC_MAX); } -TEST(interesting_syscalls, sc_set_to_event_names) -{ +TEST(interesting_syscalls, sc_set_to_event_names) { // "syncfs" is a generic event / syscall static std::set names_truth = {"kill", "read", "syncfs", "procexit", "switch"}; - static libsinsp::events::set sc_set = {PPM_SC_KILL, PPM_SC_READ, PPM_SC_SYNCFS, PPM_SC_SCHED_PROCESS_EXIT, PPM_SC_SCHED_SWITCH}; - auto names = test_utils::unordered_set_to_ordered(libsinsp::events::sc_set_to_event_names(sc_set)); + static libsinsp::events::set sc_set = {PPM_SC_KILL, + PPM_SC_READ, + PPM_SC_SYNCFS, + PPM_SC_SCHED_PROCESS_EXIT, + PPM_SC_SCHED_SWITCH}; + auto names = + test_utils::unordered_set_to_ordered(libsinsp::events::sc_set_to_event_names(sc_set)); ASSERT_NAMES_EQ(names_truth, names); } -TEST(interesting_syscalls, event_names_to_sc_set) -{ - static libsinsp::events::set sc_set_truth = { - PPM_SC_KILL, - PPM_SC_READ, - PPM_SC_SYNCFS, - PPM_SC_ACCEPT, - PPM_SC_ACCEPT4, - PPM_SC_EXECVE, - PPM_SC_SETRESUID, - PPM_SC_SETRESUID32, - PPM_SC_EVENTFD, - PPM_SC_EVENTFD2, - PPM_SC_UMOUNT, - PPM_SC_UMOUNT2, - PPM_SC_PIPE, - PPM_SC_PIPE2, - PPM_SC_SIGNALFD, - PPM_SC_SIGNALFD4 - }; +TEST(interesting_syscalls, event_names_to_sc_set) { + static libsinsp::events::set sc_set_truth = {PPM_SC_KILL, + PPM_SC_READ, + PPM_SC_SYNCFS, + PPM_SC_ACCEPT, + PPM_SC_ACCEPT4, + PPM_SC_EXECVE, + PPM_SC_SETRESUID, + PPM_SC_SETRESUID32, + PPM_SC_EVENTFD, + PPM_SC_EVENTFD2, + PPM_SC_UMOUNT, + PPM_SC_UMOUNT2, + PPM_SC_PIPE, + PPM_SC_PIPE2, + PPM_SC_SIGNALFD, + PPM_SC_SIGNALFD4}; auto sc_set = libsinsp::events::event_names_to_sc_set(std::unordered_set{ - "kill", - "read", - "syncfs", - "accept", - "accept4", - "execve", - "setresuid", - "eventfd", - "eventfd2", - "umount", - "umount2", - "pipe", - "pipe2", - "signalfd", - "signalfd4", + "kill", + "read", + "syncfs", + "accept", + "accept4", + "execve", + "setresuid", + "eventfd", + "eventfd2", + "umount", + "umount2", + "pipe", + "pipe2", + "signalfd", + "signalfd4", }); ASSERT_PPM_SC_CODES_EQ(sc_set_truth, sc_set); } -/* This test asserts the behavior of `event_names_to_sc_set` API when corner cases like `accept/accept4` are involved */ -TEST(interesting_syscalls, names_sc_set_names_corner_cases) -{ - /* INCONSISTENCY: `event_names_to_sc_set` is converting event names to ppm_sc, but this was not its original scope, the original scope was to convert sc_names -> to sc_set */ - std::unordered_set event_names{"accept", "execve", "syncfs", "eventfd", "umount", "pipe", "signalfd", "umount2", "procexit"}; +/* This test asserts the behavior of `event_names_to_sc_set` API when corner cases like + * `accept/accept4` are involved */ +TEST(interesting_syscalls, names_sc_set_names_corner_cases) { + /* INCONSISTENCY: `event_names_to_sc_set` is converting event names to ppm_sc, but this was not + * its original scope, the original scope was to convert sc_names -> to sc_set */ + std::unordered_set event_names{"accept", + "execve", + "syncfs", + "eventfd", + "umount", + "pipe", + "signalfd", + "umount2", + "procexit"}; auto sc_set = libsinsp::events::event_names_to_sc_set(event_names); - libsinsp::events::set expected_sc_set{PPM_SC_ACCEPT, PPM_SC_ACCEPT4, PPM_SC_EXECVE, PPM_SC_SYNCFS, PPM_SC_EVENTFD, PPM_SC_UMOUNT, PPM_SC_PIPE, PPM_SC_SIGNALFD, PPM_SC_UMOUNT2, PPM_SC_SCHED_PROCESS_EXIT}; + libsinsp::events::set expected_sc_set{PPM_SC_ACCEPT, + PPM_SC_ACCEPT4, + PPM_SC_EXECVE, + PPM_SC_SYNCFS, + PPM_SC_EVENTFD, + PPM_SC_UMOUNT, + PPM_SC_PIPE, + PPM_SC_SIGNALFD, + PPM_SC_UMOUNT2, + PPM_SC_SCHED_PROCESS_EXIT}; ASSERT_PPM_SC_CODES_EQ(sc_set, expected_sc_set); /* Please note that here we are converting sc_set to sc_names not event_names! */ - auto sc_names = libsinsp::events::sc_set_to_event_names(sc_set); - static std::unordered_set expected_sc_names = {"accept", "accept4", "execve", "syncfs", "eventfd", "umount", "pipe", "signalfd", "umount2", "procexit"}; + auto sc_names = libsinsp::events::sc_set_to_event_names(sc_set); + static std::unordered_set expected_sc_names = {"accept", + "accept4", + "execve", + "syncfs", + "eventfd", + "umount", + "pipe", + "signalfd", + "umount2", + "procexit"}; ASSERT_NAMES_EQ(expected_sc_names, sc_names); } -TEST(interesting_syscalls, event_set_to_sc_set) -{ +TEST(interesting_syscalls, event_set_to_sc_set) { libsinsp::events::set sc_set_truth = { - PPM_SC_KILL, - PPM_SC_SENDTO, + PPM_SC_KILL, + PPM_SC_SENDTO, }; libsinsp::events::set event_set = { - PPME_SYSCALL_KILL_E, - PPME_SYSCALL_KILL_X, - PPME_SOCKET_SENDTO_E, - PPME_SOCKET_SENDTO_X, + PPME_SYSCALL_KILL_E, + PPME_SYSCALL_KILL_X, + PPME_SOCKET_SENDTO_E, + PPME_SOCKET_SENDTO_X, }; auto sc_set = libsinsp::events::event_set_to_sc_set(event_set); ASSERT_PPM_SC_CODES_EQ(sc_set_truth, sc_set); } -TEST(interesting_syscalls, event_set_to_sc_set_generic_events) -{ - +TEST(interesting_syscalls, event_set_to_sc_set_generic_events) { libsinsp::events::set event_set = { - PPME_SYSCALL_KILL_E, - PPME_SYSCALL_KILL_X, - PPME_SOCKET_SENDTO_E, - PPME_SOCKET_SENDTO_X, - PPME_GENERIC_E, - PPME_GENERIC_X, + PPME_SYSCALL_KILL_E, + PPME_SYSCALL_KILL_X, + PPME_SOCKET_SENDTO_E, + PPME_SOCKET_SENDTO_X, + PPME_GENERIC_E, + PPME_GENERIC_X, }; auto sc_set = libsinsp::events::event_set_to_sc_set(event_set); @@ -165,58 +188,67 @@ TEST(interesting_syscalls, event_set_to_sc_set_generic_events) ASSERT_TRUE(sc_set.contains(PPM_SC_READLINKAT)); } -TEST(filter_ppm_codes, check_sinsp_repair_state_sc_set) -{ - libsinsp::events::set truth; - libsinsp::events::set input_sc_set; - libsinsp::events::set sc_set; - - truth = libsinsp::events::event_names_to_sc_set({ - "capset", "chdir", "chroot", "clone", "clone3", "execve", "execveat", "fchdir", "fork", "procexit", - "setgid", "setgid32", "setpgid", "setresgid", "setresgid32", "setresuid", "setresuid32", "setsid", - "setuid", "setuid32", "vfork", "prctl"}); - input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "execveat"}); - sc_set = sinsp_repair_state_sc_set(input_sc_set); - ASSERT_PPM_SC_CODES_EQ(truth, sc_set); - - truth = libsinsp::events::event_names_to_sc_set({ - "accept", "accept4", "bind", "capset", "chdir", "chroot", "clone", "clone3", "close", "connect", - "execve", "execveat", "fchdir", "fork", "getsockopt", "procexit", "setgid", "setgid32", "setpgid", "setresgid", "setresgid32", - "setresuid", "setresuid32", "setsid", "setuid", "setuid32", "socket", "vfork", "prctl"}); - input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "execveat", "connect", "accept", "accept4"}); - sc_set = sinsp_repair_state_sc_set(input_sc_set); - ASSERT_PPM_SC_CODES_EQ(truth, sc_set); - - truth = libsinsp::events::event_names_to_sc_set({ - "capset", "chdir", "chroot", "clone", "clone3", "close", "connect", "execve", "execveat", - "fchdir", "fork", "getsockopt", "procexit", "setgid", "setgid32", "setpgid", "setresgid", "setresgid32", - "setresuid", "setresuid32", "setsid", "setuid", "setuid32", "socket", "vfork", "prctl"}); - input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "execveat", "connect"}); - sc_set = sinsp_repair_state_sc_set(input_sc_set); - ASSERT_PPM_SC_CODES_EQ(truth, sc_set); - - truth = libsinsp::events::event_names_to_sc_set({ - "accept", "accept4", "bind", "capset", "chdir", "chroot", "clone", "clone3", "close", "execve", - "execveat", "fchdir", "fork", "getsockopt", "procexit", "setgid", "setgid32", "setpgid", "setresgid", "setresgid32", - "setresuid", "setresuid32", "setsid", "setuid", "setuid32", "socket", "vfork", "prctl"}); - input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "accept", "accept4"}); - sc_set = sinsp_repair_state_sc_set(input_sc_set); - ASSERT_PPM_SC_CODES_EQ(truth, sc_set); - - truth = libsinsp::events::event_names_to_sc_set({ - "capset", "chdir", "chroot", "clone", "clone3", "execve", "execveat", "fchdir", "fork", "procexit", - "setgid", "setgid32", "setpgid", "setresgid", "setresgid32", "setresuid", "setresuid32", "setsid", - "setuid", "setuid32", "vfork", "prctl"}); - input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "execveat"}); - sc_set = sinsp_repair_state_sc_set(input_sc_set); - ASSERT_PPM_SC_CODES_EQ(truth, sc_set); - - truth = libsinsp::events::event_names_to_sc_set({ - "capset", "chdir", "chroot", "clone", "clone3", "close", "execve", "execveat", "fchdir", "fork", - "open", "openat", "openat2", "procexit", "setgid", "setgid32", "setpgid", "setresgid", "setresgid32", - "setresuid", "setresuid32", "setsid", "setuid", "setuid32", "vfork", "prctl"}); - input_sc_set = libsinsp::events::event_names_to_sc_set({"open", "openat", "openat2"}); - sc_set = sinsp_repair_state_sc_set(input_sc_set); - ASSERT_PPM_SC_CODES_EQ(truth, sc_set); - +TEST(filter_ppm_codes, check_sinsp_repair_state_sc_set) { + libsinsp::events::set truth; + libsinsp::events::set input_sc_set; + libsinsp::events::set sc_set; + + truth = libsinsp::events::event_names_to_sc_set( + {"capset", "chdir", "chroot", "clone", "clone3", "execve", + "execveat", "fchdir", "fork", "procexit", "setgid", "setgid32", + "setpgid", "setresgid", "setresgid32", "setresuid", "setresuid32", "setsid", + "setuid", "setuid32", "vfork", "prctl"}); + input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "execveat"}); + sc_set = sinsp_repair_state_sc_set(input_sc_set); + ASSERT_PPM_SC_CODES_EQ(truth, sc_set); + + truth = libsinsp::events::event_names_to_sc_set( + {"accept", "accept4", "bind", "capset", "chdir", "chroot", + "clone", "clone3", "close", "connect", "execve", "execveat", + "fchdir", "fork", "getsockopt", "procexit", "setgid", "setgid32", + "setpgid", "setresgid", "setresgid32", "setresuid", "setresuid32", "setsid", + "setuid", "setuid32", "socket", "vfork", "prctl"}); + input_sc_set = libsinsp::events::event_names_to_sc_set( + {"execve", "execveat", "connect", "accept", "accept4"}); + sc_set = sinsp_repair_state_sc_set(input_sc_set); + ASSERT_PPM_SC_CODES_EQ(truth, sc_set); + + truth = libsinsp::events::event_names_to_sc_set( + {"capset", "chdir", "chroot", "clone", "clone3", "close", + "connect", "execve", "execveat", "fchdir", "fork", "getsockopt", + "procexit", "setgid", "setgid32", "setpgid", "setresgid", "setresgid32", + "setresuid", "setresuid32", "setsid", "setuid", "setuid32", "socket", + "vfork", "prctl"}); + input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "execveat", "connect"}); + sc_set = sinsp_repair_state_sc_set(input_sc_set); + ASSERT_PPM_SC_CODES_EQ(truth, sc_set); + + truth = libsinsp::events::event_names_to_sc_set( + {"accept", "accept4", "bind", "capset", "chdir", "chroot", + "clone", "clone3", "close", "execve", "execveat", "fchdir", + "fork", "getsockopt", "procexit", "setgid", "setgid32", "setpgid", + "setresgid", "setresgid32", "setresuid", "setresuid32", "setsid", "setuid", + "setuid32", "socket", "vfork", "prctl"}); + input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "accept", "accept4"}); + sc_set = sinsp_repair_state_sc_set(input_sc_set); + ASSERT_PPM_SC_CODES_EQ(truth, sc_set); + + truth = libsinsp::events::event_names_to_sc_set( + {"capset", "chdir", "chroot", "clone", "clone3", "execve", + "execveat", "fchdir", "fork", "procexit", "setgid", "setgid32", + "setpgid", "setresgid", "setresgid32", "setresuid", "setresuid32", "setsid", + "setuid", "setuid32", "vfork", "prctl"}); + input_sc_set = libsinsp::events::event_names_to_sc_set({"execve", "execveat"}); + sc_set = sinsp_repair_state_sc_set(input_sc_set); + ASSERT_PPM_SC_CODES_EQ(truth, sc_set); + + truth = libsinsp::events::event_names_to_sc_set( + {"capset", "chdir", "chroot", "clone", "clone3", "close", + "execve", "execveat", "fchdir", "fork", "open", "openat", + "openat2", "procexit", "setgid", "setgid32", "setpgid", "setresgid", + "setresgid32", "setresuid", "setresuid32", "setsid", "setuid", "setuid32", + "vfork", "prctl"}); + input_sc_set = libsinsp::events::event_names_to_sc_set({"open", "openat", "openat2"}); + sc_set = sinsp_repair_state_sc_set(input_sc_set); + ASSERT_PPM_SC_CODES_EQ(truth, sc_set); } diff --git a/userspace/libsinsp/test/public_sinsp_API/ppm_sc_codes.cpp b/userspace/libsinsp/test/public_sinsp_API/ppm_sc_codes.cpp index 6a78fe02b5..9a05c4a13f 100644 --- a/userspace/libsinsp/test/public_sinsp_API/ppm_sc_codes.cpp +++ b/userspace/libsinsp/test/public_sinsp_API/ppm_sc_codes.cpp @@ -30,287 +30,242 @@ static libsinsp::events::set sinsp_generic_syscalls_set; * otherwise some of the following checks will fail. */ const libsinsp::events::set expected_sinsp_state_event_set = { - PPME_SOCKET_ACCEPT_E, - PPME_SOCKET_ACCEPT_X, - PPME_SOCKET_ACCEPT_5_E, - PPME_SOCKET_ACCEPT_5_X, - PPME_SOCKET_ACCEPT4_E, - PPME_SOCKET_ACCEPT4_X, - PPME_SOCKET_ACCEPT4_5_E, - PPME_SOCKET_ACCEPT4_5_X, - PPME_SOCKET_BIND_E, - PPME_SOCKET_BIND_X, - PPME_SYSCALL_CAPSET_E, - PPME_SYSCALL_CAPSET_X, - PPME_SYSCALL_CHDIR_E, - PPME_SYSCALL_CHDIR_X, - PPME_SYSCALL_CHROOT_E, - PPME_SYSCALL_CHROOT_X, - PPME_SYSCALL_CLONE3_E, - PPME_SYSCALL_CLONE3_X, - PPME_SYSCALL_CLONE_11_E, - PPME_SYSCALL_CLONE_11_X, - PPME_SYSCALL_CLONE_16_E, - PPME_SYSCALL_CLONE_16_X, - PPME_SYSCALL_CLONE_17_E, - PPME_SYSCALL_CLONE_17_X, - PPME_SYSCALL_CLONE_20_E, - PPME_SYSCALL_CLONE_20_X, - PPME_SYSCALL_CLOSE_E, - PPME_SYSCALL_CLOSE_X, - PPME_SOCKET_CONNECT_E, - PPME_SOCKET_CONNECT_X, - PPME_SYSCALL_CREAT_E, - PPME_SYSCALL_CREAT_X, - PPME_SYSCALL_DUP_E, - PPME_SYSCALL_DUP_X, - PPME_SYSCALL_DUP_1_E, - PPME_SYSCALL_DUP_1_X, - PPME_SYSCALL_DUP2_E, - PPME_SYSCALL_DUP2_X, - PPME_SYSCALL_DUP3_E, - PPME_SYSCALL_DUP3_X, - PPME_SYSCALL_EVENTFD_E, - PPME_SYSCALL_EVENTFD_X, - PPME_SYSCALL_EXECVE_8_E, - PPME_SYSCALL_EXECVE_8_X, - PPME_SYSCALL_EXECVE_13_E, - PPME_SYSCALL_EXECVE_13_X, - PPME_SYSCALL_EXECVE_14_E, - PPME_SYSCALL_EXECVE_14_X, - PPME_SYSCALL_EXECVE_15_E, - PPME_SYSCALL_EXECVE_15_X, - PPME_SYSCALL_EXECVE_16_E, - PPME_SYSCALL_EXECVE_16_X, - PPME_SYSCALL_EXECVE_17_E, - PPME_SYSCALL_EXECVE_17_X, - PPME_SYSCALL_EXECVE_18_E, - PPME_SYSCALL_EXECVE_18_X, - PPME_SYSCALL_EXECVE_19_E, - PPME_SYSCALL_EXECVE_19_X, - PPME_SYSCALL_EXECVEAT_E, - PPME_SYSCALL_EXECVEAT_X, - PPME_SYSCALL_FCHDIR_E, - PPME_SYSCALL_FCHDIR_X, - PPME_SYSCALL_FCNTL_E, - PPME_SYSCALL_FCNTL_X, - PPME_SYSCALL_FORK_E, - PPME_SYSCALL_FORK_X, - PPME_SYSCALL_FORK_17_E, - PPME_SYSCALL_FORK_17_X, - PPME_SYSCALL_FORK_20_E, - PPME_SYSCALL_FORK_20_X, - PPME_SYSCALL_INOTIFY_INIT_E, - PPME_SYSCALL_INOTIFY_INIT_X, - PPME_SYSCALL_IO_URING_SETUP_E, - PPME_SYSCALL_IO_URING_SETUP_X, - PPME_SYSCALL_MOUNT_E, - PPME_SYSCALL_MOUNT_X, - PPME_SYSCALL_OPEN_E, - PPME_SYSCALL_OPEN_X, - PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, - PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, - PPME_SYSCALL_OPENAT_E, - PPME_SYSCALL_OPENAT_X, - PPME_SYSCALL_OPENAT_2_E, - PPME_SYSCALL_OPENAT_2_X, - PPME_SYSCALL_OPENAT2_E, - PPME_SYSCALL_OPENAT2_X, - PPME_SYSCALL_PIPE_E, - PPME_SYSCALL_PIPE_X, - PPME_SYSCALL_PRLIMIT_E, - PPME_SYSCALL_PRLIMIT_X, - PPME_SOCKET_RECVFROM_E, - PPME_SOCKET_RECVFROM_X, - PPME_SOCKET_RECVMSG_E, - PPME_SOCKET_RECVMSG_X, - PPME_SOCKET_GETSOCKOPT_E, - PPME_SOCKET_GETSOCKOPT_X, - PPME_SOCKET_SENDMSG_E, - PPME_SOCKET_SENDMSG_X, - PPME_SOCKET_SENDTO_E, - PPME_SOCKET_SENDTO_X, - PPME_SYSCALL_SETGID_E, - PPME_SYSCALL_SETGID_X, - PPME_SYSCALL_SETPGID_E, - PPME_SYSCALL_SETPGID_X, - PPME_SYSCALL_SETRESGID_E, - PPME_SYSCALL_SETRESGID_X, - PPME_SYSCALL_SETRESUID_E, - PPME_SYSCALL_SETRESUID_X, - PPME_SYSCALL_SETRLIMIT_E, - PPME_SYSCALL_SETRLIMIT_X, - PPME_SYSCALL_SETSID_E, - PPME_SYSCALL_SETSID_X, - PPME_SYSCALL_SETUID_E, - PPME_SYSCALL_SETUID_X, - PPME_SOCKET_SHUTDOWN_E, - PPME_SOCKET_SHUTDOWN_X, - PPME_SYSCALL_SIGNALFD_E, - PPME_SYSCALL_SIGNALFD_X, - PPME_SOCKET_SOCKET_E, - PPME_SOCKET_SOCKET_X, - PPME_SOCKET_SOCKETPAIR_E, - PPME_SOCKET_SOCKETPAIR_X, - PPME_SYSCALL_TIMERFD_CREATE_E, - PPME_SYSCALL_TIMERFD_CREATE_X, - PPME_SYSCALL_UMOUNT_E, - PPME_SYSCALL_UMOUNT_X, - PPME_SYSCALL_USERFAULTFD_E, - PPME_SYSCALL_USERFAULTFD_X, - PPME_SYSCALL_VFORK_E, - PPME_SYSCALL_VFORK_X, - PPME_SYSCALL_VFORK_17_E, - PPME_SYSCALL_VFORK_17_X, - PPME_SYSCALL_VFORK_20_E, - PPME_SYSCALL_VFORK_20_X, - PPME_SYSCALL_EPOLL_CREATE_E, - PPME_SYSCALL_EPOLL_CREATE_X, - PPME_SYSCALL_EPOLL_CREATE1_E, - PPME_SYSCALL_EPOLL_CREATE1_X, - PPME_PROCEXIT_E, - PPME_PROCEXIT_1_E, - PPME_DROP_E, - PPME_DROP_X, - PPME_SCAPEVENT_E, - PPME_CONTAINER_E, - PPME_PROCINFO_E, - PPME_CPU_HOTPLUG_E, - PPME_K8S_E, - PPME_TRACER_E, - PPME_TRACER_X, - PPME_MESOS_E, - PPME_CONTAINER_JSON_E, - PPME_NOTIFICATION_E, - PPME_INFRASTRUCTURE_EVENT_E, - PPME_CONTAINER_JSON_2_E, - PPME_USER_ADDED_E, - PPME_USER_DELETED_E, - PPME_GROUP_ADDED_E, - PPME_GROUP_DELETED_E, - PPME_GROUP_DELETED_E, - PPME_SYSCALL_UMOUNT_1_E, - PPME_SYSCALL_UMOUNT_1_X, - PPME_SOCKET_ACCEPT4_6_E, - PPME_SOCKET_ACCEPT4_6_X, - PPME_SYSCALL_UMOUNT2_E, - PPME_SYSCALL_UMOUNT2_X, - PPME_SYSCALL_PIPE2_E, - PPME_SYSCALL_PIPE2_X, - PPME_SYSCALL_INOTIFY_INIT1_E, - PPME_SYSCALL_INOTIFY_INIT1_X, - PPME_SYSCALL_EVENTFD2_E, - PPME_SYSCALL_EVENTFD2_X, - PPME_SYSCALL_SIGNALFD4_E, - PPME_SYSCALL_SIGNALFD4_X, - PPME_SYSCALL_PRCTL_E, - PPME_SYSCALL_PRCTL_X, - PPME_ASYNCEVENT_E, - PPME_SYSCALL_MEMFD_CREATE_E, - PPME_SYSCALL_MEMFD_CREATE_X, - PPME_SYSCALL_PIDFD_GETFD_E, - PPME_SYSCALL_PIDFD_GETFD_X, - PPME_SYSCALL_PIDFD_OPEN_E, - PPME_SYSCALL_PIDFD_OPEN_X, - PPME_SYSCALL_SETREUID_E, - PPME_SYSCALL_SETREUID_X, - PPME_SYSCALL_SETREGID_E, - PPME_SYSCALL_SETREGID_X -}; + PPME_SOCKET_ACCEPT_E, + PPME_SOCKET_ACCEPT_X, + PPME_SOCKET_ACCEPT_5_E, + PPME_SOCKET_ACCEPT_5_X, + PPME_SOCKET_ACCEPT4_E, + PPME_SOCKET_ACCEPT4_X, + PPME_SOCKET_ACCEPT4_5_E, + PPME_SOCKET_ACCEPT4_5_X, + PPME_SOCKET_BIND_E, + PPME_SOCKET_BIND_X, + PPME_SYSCALL_CAPSET_E, + PPME_SYSCALL_CAPSET_X, + PPME_SYSCALL_CHDIR_E, + PPME_SYSCALL_CHDIR_X, + PPME_SYSCALL_CHROOT_E, + PPME_SYSCALL_CHROOT_X, + PPME_SYSCALL_CLONE3_E, + PPME_SYSCALL_CLONE3_X, + PPME_SYSCALL_CLONE_11_E, + PPME_SYSCALL_CLONE_11_X, + PPME_SYSCALL_CLONE_16_E, + PPME_SYSCALL_CLONE_16_X, + PPME_SYSCALL_CLONE_17_E, + PPME_SYSCALL_CLONE_17_X, + PPME_SYSCALL_CLONE_20_E, + PPME_SYSCALL_CLONE_20_X, + PPME_SYSCALL_CLOSE_E, + PPME_SYSCALL_CLOSE_X, + PPME_SOCKET_CONNECT_E, + PPME_SOCKET_CONNECT_X, + PPME_SYSCALL_CREAT_E, + PPME_SYSCALL_CREAT_X, + PPME_SYSCALL_DUP_E, + PPME_SYSCALL_DUP_X, + PPME_SYSCALL_DUP_1_E, + PPME_SYSCALL_DUP_1_X, + PPME_SYSCALL_DUP2_E, + PPME_SYSCALL_DUP2_X, + PPME_SYSCALL_DUP3_E, + PPME_SYSCALL_DUP3_X, + PPME_SYSCALL_EVENTFD_E, + PPME_SYSCALL_EVENTFD_X, + PPME_SYSCALL_EXECVE_8_E, + PPME_SYSCALL_EXECVE_8_X, + PPME_SYSCALL_EXECVE_13_E, + PPME_SYSCALL_EXECVE_13_X, + PPME_SYSCALL_EXECVE_14_E, + PPME_SYSCALL_EXECVE_14_X, + PPME_SYSCALL_EXECVE_15_E, + PPME_SYSCALL_EXECVE_15_X, + PPME_SYSCALL_EXECVE_16_E, + PPME_SYSCALL_EXECVE_16_X, + PPME_SYSCALL_EXECVE_17_E, + PPME_SYSCALL_EXECVE_17_X, + PPME_SYSCALL_EXECVE_18_E, + PPME_SYSCALL_EXECVE_18_X, + PPME_SYSCALL_EXECVE_19_E, + PPME_SYSCALL_EXECVE_19_X, + PPME_SYSCALL_EXECVEAT_E, + PPME_SYSCALL_EXECVEAT_X, + PPME_SYSCALL_FCHDIR_E, + PPME_SYSCALL_FCHDIR_X, + PPME_SYSCALL_FCNTL_E, + PPME_SYSCALL_FCNTL_X, + PPME_SYSCALL_FORK_E, + PPME_SYSCALL_FORK_X, + PPME_SYSCALL_FORK_17_E, + PPME_SYSCALL_FORK_17_X, + PPME_SYSCALL_FORK_20_E, + PPME_SYSCALL_FORK_20_X, + PPME_SYSCALL_INOTIFY_INIT_E, + PPME_SYSCALL_INOTIFY_INIT_X, + PPME_SYSCALL_IO_URING_SETUP_E, + PPME_SYSCALL_IO_URING_SETUP_X, + PPME_SYSCALL_MOUNT_E, + PPME_SYSCALL_MOUNT_X, + PPME_SYSCALL_OPEN_E, + PPME_SYSCALL_OPEN_X, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_E, + PPME_SYSCALL_OPEN_BY_HANDLE_AT_X, + PPME_SYSCALL_OPENAT_E, + PPME_SYSCALL_OPENAT_X, + PPME_SYSCALL_OPENAT_2_E, + PPME_SYSCALL_OPENAT_2_X, + PPME_SYSCALL_OPENAT2_E, + PPME_SYSCALL_OPENAT2_X, + PPME_SYSCALL_PIPE_E, + PPME_SYSCALL_PIPE_X, + PPME_SYSCALL_PRLIMIT_E, + PPME_SYSCALL_PRLIMIT_X, + PPME_SOCKET_RECVFROM_E, + PPME_SOCKET_RECVFROM_X, + PPME_SOCKET_RECVMSG_E, + PPME_SOCKET_RECVMSG_X, + PPME_SOCKET_GETSOCKOPT_E, + PPME_SOCKET_GETSOCKOPT_X, + PPME_SOCKET_SENDMSG_E, + PPME_SOCKET_SENDMSG_X, + PPME_SOCKET_SENDTO_E, + PPME_SOCKET_SENDTO_X, + PPME_SYSCALL_SETGID_E, + PPME_SYSCALL_SETGID_X, + PPME_SYSCALL_SETPGID_E, + PPME_SYSCALL_SETPGID_X, + PPME_SYSCALL_SETRESGID_E, + PPME_SYSCALL_SETRESGID_X, + PPME_SYSCALL_SETRESUID_E, + PPME_SYSCALL_SETRESUID_X, + PPME_SYSCALL_SETRLIMIT_E, + PPME_SYSCALL_SETRLIMIT_X, + PPME_SYSCALL_SETSID_E, + PPME_SYSCALL_SETSID_X, + PPME_SYSCALL_SETUID_E, + PPME_SYSCALL_SETUID_X, + PPME_SOCKET_SHUTDOWN_E, + PPME_SOCKET_SHUTDOWN_X, + PPME_SYSCALL_SIGNALFD_E, + PPME_SYSCALL_SIGNALFD_X, + PPME_SOCKET_SOCKET_E, + PPME_SOCKET_SOCKET_X, + PPME_SOCKET_SOCKETPAIR_E, + PPME_SOCKET_SOCKETPAIR_X, + PPME_SYSCALL_TIMERFD_CREATE_E, + PPME_SYSCALL_TIMERFD_CREATE_X, + PPME_SYSCALL_UMOUNT_E, + PPME_SYSCALL_UMOUNT_X, + PPME_SYSCALL_USERFAULTFD_E, + PPME_SYSCALL_USERFAULTFD_X, + PPME_SYSCALL_VFORK_E, + PPME_SYSCALL_VFORK_X, + PPME_SYSCALL_VFORK_17_E, + PPME_SYSCALL_VFORK_17_X, + PPME_SYSCALL_VFORK_20_E, + PPME_SYSCALL_VFORK_20_X, + PPME_SYSCALL_EPOLL_CREATE_E, + PPME_SYSCALL_EPOLL_CREATE_X, + PPME_SYSCALL_EPOLL_CREATE1_E, + PPME_SYSCALL_EPOLL_CREATE1_X, + PPME_PROCEXIT_E, + PPME_PROCEXIT_1_E, + PPME_DROP_E, + PPME_DROP_X, + PPME_SCAPEVENT_E, + PPME_CONTAINER_E, + PPME_PROCINFO_E, + PPME_CPU_HOTPLUG_E, + PPME_K8S_E, + PPME_TRACER_E, + PPME_TRACER_X, + PPME_MESOS_E, + PPME_CONTAINER_JSON_E, + PPME_NOTIFICATION_E, + PPME_INFRASTRUCTURE_EVENT_E, + PPME_CONTAINER_JSON_2_E, + PPME_USER_ADDED_E, + PPME_USER_DELETED_E, + PPME_GROUP_ADDED_E, + PPME_GROUP_DELETED_E, + PPME_GROUP_DELETED_E, + PPME_SYSCALL_UMOUNT_1_E, + PPME_SYSCALL_UMOUNT_1_X, + PPME_SOCKET_ACCEPT4_6_E, + PPME_SOCKET_ACCEPT4_6_X, + PPME_SYSCALL_UMOUNT2_E, + PPME_SYSCALL_UMOUNT2_X, + PPME_SYSCALL_PIPE2_E, + PPME_SYSCALL_PIPE2_X, + PPME_SYSCALL_INOTIFY_INIT1_E, + PPME_SYSCALL_INOTIFY_INIT1_X, + PPME_SYSCALL_EVENTFD2_E, + PPME_SYSCALL_EVENTFD2_X, + PPME_SYSCALL_SIGNALFD4_E, + PPME_SYSCALL_SIGNALFD4_X, + PPME_SYSCALL_PRCTL_E, + PPME_SYSCALL_PRCTL_X, + PPME_ASYNCEVENT_E, + PPME_SYSCALL_MEMFD_CREATE_E, + PPME_SYSCALL_MEMFD_CREATE_X, + PPME_SYSCALL_PIDFD_GETFD_E, + PPME_SYSCALL_PIDFD_GETFD_X, + PPME_SYSCALL_PIDFD_OPEN_E, + PPME_SYSCALL_PIDFD_OPEN_X, + PPME_SYSCALL_SETREUID_E, + PPME_SYSCALL_SETREUID_X, + PPME_SYSCALL_SETREGID_E, + PPME_SYSCALL_SETREGID_X}; const libsinsp::events::set expected_sinsp_state_sc_set = { - PPM_SC_ACCEPT, - PPM_SC_ACCEPT4, - PPM_SC_BIND, - PPM_SC_CAPSET, - PPM_SC_CHDIR, - PPM_SC_CHROOT, - PPM_SC_CLONE, - PPM_SC_CLONE3, - PPM_SC_CLOSE, - PPM_SC_CONNECT, - PPM_SC_CREAT, - PPM_SC_DUP, - PPM_SC_DUP2, - PPM_SC_DUP3, - PPM_SC_EVENTFD, - PPM_SC_EVENTFD2, - PPM_SC_EXECVE, - PPM_SC_EXECVEAT, - PPM_SC_FCHDIR, - PPM_SC_FCNTL, - PPM_SC_FCNTL64, - PPM_SC_FORK, - PPM_SC_INOTIFY_INIT, - PPM_SC_INOTIFY_INIT1, - PPM_SC_IO_URING_SETUP, - PPM_SC_MOUNT, - PPM_SC_OPEN, - PPM_SC_OPEN_BY_HANDLE_AT, - PPM_SC_OPENAT, - PPM_SC_OPENAT2, - PPM_SC_PIPE, - PPM_SC_PIPE2, - PPM_SC_PRLIMIT64, - PPM_SC_RECVFROM, - PPM_SC_RECVMSG, - PPM_SC_GETSOCKOPT, - PPM_SC_SENDMSG, - PPM_SC_SENDTO, - PPM_SC_SETGID, - PPM_SC_SETGID32, - PPM_SC_SETPGID, - PPM_SC_SETRESGID, - PPM_SC_SETRESGID32, - PPM_SC_SETRESUID, - PPM_SC_SETRESUID32, - PPM_SC_SETRLIMIT, - PPM_SC_SETSID, - PPM_SC_SETUID, - PPM_SC_SETUID32, - PPM_SC_SHUTDOWN, - PPM_SC_SIGNALFD, - PPM_SC_SIGNALFD4, - PPM_SC_SOCKET, - PPM_SC_SOCKETPAIR, - PPM_SC_TIMERFD_CREATE, - PPM_SC_UMOUNT, - PPM_SC_UMOUNT2, - PPM_SC_USERFAULTFD, - PPM_SC_VFORK, - PPM_SC_EPOLL_CREATE, - PPM_SC_EPOLL_CREATE1, - PPM_SC_SCHED_PROCESS_EXIT, - PPM_SC_PRCTL, - PPM_SC_MEMFD_CREATE, - PPM_SC_PIDFD_OPEN, - PPM_SC_PIDFD_GETFD, - PPM_SC_SETREUID, - PPM_SC_SETREGID, + PPM_SC_ACCEPT, PPM_SC_ACCEPT4, + PPM_SC_BIND, PPM_SC_CAPSET, + PPM_SC_CHDIR, PPM_SC_CHROOT, + PPM_SC_CLONE, PPM_SC_CLONE3, + PPM_SC_CLOSE, PPM_SC_CONNECT, + PPM_SC_CREAT, PPM_SC_DUP, + PPM_SC_DUP2, PPM_SC_DUP3, + PPM_SC_EVENTFD, PPM_SC_EVENTFD2, + PPM_SC_EXECVE, PPM_SC_EXECVEAT, + PPM_SC_FCHDIR, PPM_SC_FCNTL, + PPM_SC_FCNTL64, PPM_SC_FORK, + PPM_SC_INOTIFY_INIT, PPM_SC_INOTIFY_INIT1, + PPM_SC_IO_URING_SETUP, PPM_SC_MOUNT, + PPM_SC_OPEN, PPM_SC_OPEN_BY_HANDLE_AT, + PPM_SC_OPENAT, PPM_SC_OPENAT2, + PPM_SC_PIPE, PPM_SC_PIPE2, + PPM_SC_PRLIMIT64, PPM_SC_RECVFROM, + PPM_SC_RECVMSG, PPM_SC_GETSOCKOPT, + PPM_SC_SENDMSG, PPM_SC_SENDTO, + PPM_SC_SETGID, PPM_SC_SETGID32, + PPM_SC_SETPGID, PPM_SC_SETRESGID, + PPM_SC_SETRESGID32, PPM_SC_SETRESUID, + PPM_SC_SETRESUID32, PPM_SC_SETRLIMIT, + PPM_SC_SETSID, PPM_SC_SETUID, + PPM_SC_SETUID32, PPM_SC_SHUTDOWN, + PPM_SC_SIGNALFD, PPM_SC_SIGNALFD4, + PPM_SC_SOCKET, PPM_SC_SOCKETPAIR, + PPM_SC_TIMERFD_CREATE, PPM_SC_UMOUNT, + PPM_SC_UMOUNT2, PPM_SC_USERFAULTFD, + PPM_SC_VFORK, PPM_SC_EPOLL_CREATE, + PPM_SC_EPOLL_CREATE1, PPM_SC_SCHED_PROCESS_EXIT, + PPM_SC_PRCTL, PPM_SC_MEMFD_CREATE, + PPM_SC_PIDFD_OPEN, PPM_SC_PIDFD_GETFD, + PPM_SC_SETREUID, PPM_SC_SETREGID, }; const libsinsp::events::set expected_unknown_event_set = { - PPME_PROCEXIT_X, - PPME_SCHEDSWITCH_1_X, - PPME_SCHEDSWITCH_6_X, - PPME_PROCEXIT_1_X, - PPME_PLUGINEVENT_X, - PPME_USER_ADDED_X, - PPME_USER_DELETED_X, - PPME_GROUP_ADDED_X, - PPME_GROUP_DELETED_X, - PPME_CONTAINER_JSON_2_X, - PPME_PAGE_FAULT_X, - PPME_INFRASTRUCTURE_EVENT_X, - PPME_NOTIFICATION_X, - PPME_CONTAINER_JSON_X, - PPME_MESOS_X, - PPME_K8S_X, - PPME_CPU_HOTPLUG_X, - PPME_PROCINFO_X, - PPME_SIGNALDELIVER_X, - PPME_CONTAINER_X, - PPME_ASYNCEVENT_X, + PPME_PROCEXIT_X, PPME_SCHEDSWITCH_1_X, + PPME_SCHEDSWITCH_6_X, PPME_PROCEXIT_1_X, + PPME_PLUGINEVENT_X, PPME_USER_ADDED_X, + PPME_USER_DELETED_X, PPME_GROUP_ADDED_X, + PPME_GROUP_DELETED_X, PPME_CONTAINER_JSON_2_X, + PPME_PAGE_FAULT_X, PPME_INFRASTRUCTURE_EVENT_X, + PPME_NOTIFICATION_X, PPME_CONTAINER_JSON_X, + PPME_MESOS_X, PPME_K8S_X, + PPME_CPU_HOTPLUG_X, PPME_PROCINFO_X, + PPME_SIGNALDELIVER_X, PPME_CONTAINER_X, + PPME_ASYNCEVENT_X, }; /// todo(@Andreagit97): here we miss static sets for io, proc, net groups @@ -318,8 +273,7 @@ const libsinsp::events::set expected_unknown_event_set = { /*=============================== Events related ===============================*/ /* Check the `info` API works correctly */ -TEST(ppm_sc_API, check_event_info) -{ +TEST(ppm_sc_API, check_event_info) { { auto event_info_pointer = libsinsp::events::info(PPME_GENERIC_E); ASSERT_STREQ(event_info_pointer->name, "syscall"); @@ -340,8 +294,7 @@ TEST(ppm_sc_API, check_event_info) } /* Check the `is_generic` API works correctly */ -TEST(ppm_sc_API, check_generic_events) -{ +TEST(ppm_sc_API, check_generic_events) { ASSERT_EQ(libsinsp::events::is_generic(ppm_event_code::PPME_GENERIC_E), true); ASSERT_EQ(libsinsp::events::is_generic(ppm_event_code::PPME_GENERIC_X), true); ASSERT_EQ(libsinsp::events::is_generic(ppm_event_code::PPME_SYSCALL_CLONE3_X), false); @@ -349,16 +302,18 @@ TEST(ppm_sc_API, check_generic_events) } /* Check the `is_skip_parse_reset_event` API works correctly */ -TEST(ppm_sc_API, check_skip_parse_reset_events) -{ +TEST(ppm_sc_API, check_skip_parse_reset_events) { ASSERT_EQ(libsinsp::events::is_skip_parse_reset_event(ppm_event_code::PPME_PROCINFO_E), true); - ASSERT_EQ(libsinsp::events::is_skip_parse_reset_event(ppm_event_code::PPME_SYSCALL_GETDENTS_E), false); - ASSERT_EQ(libsinsp::events::is_skip_parse_reset_event(ppm_event_code::PPME_PLUGINEVENT_E), false); + ASSERT_EQ(libsinsp::events::is_skip_parse_reset_event(ppm_event_code::PPME_SYSCALL_GETDENTS_E), + false); + ASSERT_EQ(libsinsp::events::is_skip_parse_reset_event(ppm_event_code::PPME_PLUGINEVENT_E), + false); } /*=============================== Events related ===============================*/ -/*=============================== PPME set related (sinsp_events.cpp) ===============================*/ +/*=============================== PPME set related (sinsp_events.cpp) + * ===============================*/ /* The schema here is: * - All event set @@ -380,45 +335,51 @@ TEST(ppm_sc_API, check_skip_parse_reset_events) * - (NGEN) -> event set -> (NGEN) NGEN = not generic event names */ -TEST(ppm_sc_API, generic_syscalls_set) -{ +TEST(ppm_sc_API, generic_syscalls_set) { libsinsp::events::set generic_enter_event{PPME_GENERIC_E}; libsinsp::events::set generic_exit_event{PPME_GENERIC_X}; std::vector generic_syscalls_enter(PPM_SC_MAX, 0); std::vector generic_syscalls_exit(PPM_SC_MAX, 0); - ASSERT_EQ(scap_get_ppm_sc_from_events(generic_enter_event.data(), generic_syscalls_enter.data()), SCAP_SUCCESS); - ASSERT_EQ(scap_get_ppm_sc_from_events(generic_exit_event.data(), generic_syscalls_exit.data()), SCAP_SUCCESS); + ASSERT_EQ( + scap_get_ppm_sc_from_events(generic_enter_event.data(), generic_syscalls_enter.data()), + SCAP_SUCCESS); + ASSERT_EQ(scap_get_ppm_sc_from_events(generic_exit_event.data(), generic_syscalls_exit.data()), + SCAP_SUCCESS); ASSERT_EQ(generic_syscalls_enter, generic_syscalls_exit); // Load generic syscalls in the sinsp_generic_syscalls_set - for(uint32_t ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if (generic_syscalls_enter[ppm_sc]) - { + for(uint32_t ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(generic_syscalls_enter[ppm_sc]) { sinsp_generic_syscalls_set.insert((ppm_sc_code)ppm_sc); } } } -TEST(ppm_sc_API, all_event_set) -{ +TEST(ppm_sc_API, all_event_set) { /* Here we want to return also unused events like `PPME_SCHEDSWITCH_6_X` */ const auto all_events = libsinsp::events::all_event_set(); ASSERT_EQ(all_events.size(), PPM_EVENT_MAX); - for(int i = 0; i < PPM_EVENT_MAX; i++) - { - ASSERT_TRUE(all_events.contains((ppm_event_code)i)) << "\n- The event '" << scap_get_event_info_table()[i].name << "' is not present inside the all event set" << std::endl; + for(int i = 0; i < PPM_EVENT_MAX; i++) { + ASSERT_TRUE(all_events.contains((ppm_event_code)i)) + << "\n- The event '" << scap_get_event_info_table()[i].name + << "' is not present inside the all event set" << std::endl; } } -TEST(ppm_sc_API, all_event_names) -{ +TEST(ppm_sc_API, all_event_names) { /* Here we want all events' names also the ones associated with generic events, so the syscalls - * names, but we don't want the "syscall" event name associated with `GENERIC_E`/`GENERIC_X` events extracted from the event table. + * names, but we don't want the "syscall" event name associated with `GENERIC_E`/`GENERIC_X` + * events extracted from the event table. */ - auto events_names = test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(libsinsp::events::all_event_set())); - /* `NA*` events were now removed so we don't want them again, all other syscall names have no events associated so they shouldn't be in this set */ - std::set some_not_desired_names{"syscall", "ugetrlimit", "fcntl64", "sendfile64", "setresuid32", "setresgid32", "setuid32", "setgid32", "getuid32", "geteuid32", "getgid32", "getegid32", "getresuid32", "getresgid32", "NA1", "NA2", "NA3", "NA4", "NA5", "NA6"}; + auto events_names = test_utils::unordered_set_to_ordered( + libsinsp::events::event_set_to_names(libsinsp::events::all_event_set())); + /* `NA*` events were now removed so we don't want them again, all other syscall names have no + * events associated so they shouldn't be in this set */ + std::set some_not_desired_names{ + "syscall", "ugetrlimit", "fcntl64", "sendfile64", "setresuid32", + "setresgid32", "setuid32", "setgid32", "getuid32", "geteuid32", + "getgid32", "getegid32", "getresuid32", "getresgid32", "NA1", + "NA2", "NA3", "NA4", "NA5", "NA6"}; ASSERT_NOT_CONTAINS(events_names, some_not_desired_names); /* We count old version events to be sure about the final number of names we should expect */ @@ -426,10 +387,8 @@ TEST(ppm_sc_API, all_event_names) std::set all_expected_events_names = {}; /* We skip `syscall` name associated with `GENERIC_E`/`GENERIC_X` */ - for(int evt = 2; evt < PPM_EVENT_MAX; evt++) - { - if(libsinsp::events::is_old_version_event((ppm_event_code)evt)) - { + for(int evt = 2; evt < PPM_EVENT_MAX; evt++) { + if(libsinsp::events::is_old_version_event((ppm_event_code)evt)) { old_versions_events++; } all_expected_events_names.insert(scap_get_event_info_table()[evt].name); @@ -437,43 +396,43 @@ TEST(ppm_sc_API, all_event_names) libsinsp::events::set generic_events{PPME_GENERIC_E, PPME_GENERIC_X}; std::vector generic_syscalls(PPM_SC_MAX, 0); - ASSERT_EQ(scap_get_ppm_sc_from_events(generic_events.data(), generic_syscalls.data()), SCAP_SUCCESS); - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if(generic_syscalls[ppm_sc]) - { + ASSERT_EQ(scap_get_ppm_sc_from_events(generic_events.data(), generic_syscalls.data()), + SCAP_SUCCESS); + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(generic_syscalls[ppm_sc]) { all_expected_events_names.insert(scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)); } } ASSERT_NAMES_EQ(events_names, all_expected_events_names); - /* To obtain the right size of the event names we need to divide by 2 the total number of events. - * Events are almost all paired, and when they are not paired dividing by 2 we remove the `NA` entries. - * Since we consider the `NA` a valid name we need to add it to the set, so `+1` - * We don't want the name "syscall" associated with `PPME_GENERIC_E` and `PPME_GENERIC_E`, so `-1`. `-1` and not `-2` because we have already divided by 2. - * We need to remove all the old version events because their names are just a replica of current events ones. `/2` because we have already divided by 2. - * Finally we need to add the GENERIC names. + /* To obtain the right size of the event names we need to divide by 2 the total number of + * events. Events are almost all paired, and when they are not paired dividing by 2 we remove + * the `NA` entries. Since we consider the `NA` a valid name we need to add it to the set, so + * `+1` We don't want the name "syscall" associated with `PPME_GENERIC_E` and `PPME_GENERIC_E`, + * so `-1`. `-1` and not `-2` because we have already divided by 2. We need to remove all the + * old version events because their names are just a replica of current events ones. `/2` + * because we have already divided by 2. Finally we need to add the GENERIC names. */ - ASSERT_EQ(events_names.size(), (PPM_EVENT_MAX / 2) + 1 - 1 - old_versions_events / 2 + GENERIC_SYSCALLS_NUM); + ASSERT_EQ(events_names.size(), + (PPM_EVENT_MAX / 2) + 1 - 1 - old_versions_events / 2 + GENERIC_SYSCALLS_NUM); } -TEST(ppm_sc_API, sinsp_state_event_set) -{ - ASSERT_PPM_EVENT_CODES_EQ(libsinsp::events::sinsp_state_event_set(), expected_sinsp_state_event_set); +TEST(ppm_sc_API, sinsp_state_event_set) { + ASSERT_PPM_EVENT_CODES_EQ(libsinsp::events::sinsp_state_event_set(), + expected_sinsp_state_event_set); } -TEST(ppm_sc_API, all_generic_events_names) -{ +TEST(ppm_sc_API, all_generic_events_names) { libsinsp::events::set generic_events{PPME_GENERIC_E, PPME_GENERIC_X}; - std::set generic_events_names = test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(generic_events)); + std::set generic_events_names = test_utils::unordered_set_to_ordered( + libsinsp::events::event_set_to_names(generic_events)); std::vector generic_syscalls(PPM_SC_MAX, 0); - ASSERT_EQ(scap_get_ppm_sc_from_events(generic_events.data(), generic_syscalls.data()), SCAP_SUCCESS); + ASSERT_EQ(scap_get_ppm_sc_from_events(generic_events.data(), generic_syscalls.data()), + SCAP_SUCCESS); std::set expected_generic_event_names; - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if(generic_syscalls[ppm_sc]) - { + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(generic_syscalls[ppm_sc]) { expected_generic_event_names.insert(scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)); } } @@ -482,19 +441,17 @@ TEST(ppm_sc_API, all_generic_events_names) ASSERT_EQ(generic_events_names.size(), GENERIC_SYSCALLS_NUM); } -TEST(ppm_sc_API, all_generic_ppm_sc) -{ +TEST(ppm_sc_API, all_generic_ppm_sc) { libsinsp::events::set generic_events{PPME_GENERIC_E, PPME_GENERIC_X}; auto generic_ppm_sc = libsinsp::events::event_set_to_sc_set(generic_events); std::vector generic_syscalls(PPM_SC_MAX, 0); - ASSERT_EQ(scap_get_ppm_sc_from_events(generic_events.data(), generic_syscalls.data()), SCAP_SUCCESS); + ASSERT_EQ(scap_get_ppm_sc_from_events(generic_events.data(), generic_syscalls.data()), + SCAP_SUCCESS); libsinsp::events::set expected_generic_ppm_sc; - for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if(generic_syscalls[ppm_sc]) - { + for(int ppm_sc = 0; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(generic_syscalls[ppm_sc]) { expected_generic_ppm_sc.insert((ppm_sc_code)ppm_sc); } } @@ -503,8 +460,7 @@ TEST(ppm_sc_API, all_generic_ppm_sc) ASSERT_EQ(generic_ppm_sc.size(), GENERIC_SYSCALLS_NUM); } -TEST(ppm_sc_API, generic_e_generic_x_comparison) -{ +TEST(ppm_sc_API, generic_e_generic_x_comparison) { /* These 2 sets should be equal */ const auto generic_e_event_names = libsinsp::events::event_set_to_names({PPME_GENERIC_E}); const auto generic_x_event_names = libsinsp::events::event_set_to_names({PPME_GENERIC_X}); @@ -519,8 +475,7 @@ TEST(ppm_sc_API, generic_e_generic_x_comparison) ASSERT_PPM_EVENT_CODES_EQ(generic_e_set, generic_x_set); } -TEST(ppm_sc_API, unknown_events) -{ +TEST(ppm_sc_API, unknown_events) { std::unordered_set unknown_event_names{"NA"}; const auto unknown_event_set = libsinsp::events::names_to_event_set(unknown_event_names); ASSERT_PPM_EVENT_CODES_EQ(unknown_event_set, expected_unknown_event_set); @@ -537,8 +492,7 @@ TEST(ppm_sc_API, unknown_events) ASSERT_TRUE(libsinsp::events::sc_set_to_event_set(empty_sc_set).empty()); } -TEST(ppm_sc_API, event_empty_sets) -{ +TEST(ppm_sc_API, event_empty_sets) { std::unordered_set empty_string_set; const auto empty_event_set = libsinsp::events::names_to_event_set(empty_string_set); const auto empty_sc_set = libsinsp::events::event_set_to_sc_set(empty_event_set); @@ -551,8 +505,7 @@ TEST(ppm_sc_API, event_empty_sets) ASSERT_TRUE(libsinsp::events::event_set_to_sc_set(meta_event).empty()); } -TEST(ppm_sc_API, AES_names_AES) -{ +TEST(ppm_sc_API, AES_names_AES) { const auto all_events = libsinsp::events::all_event_set(); const auto all_events_names = libsinsp::events::event_set_to_names(all_events); /* Convert again to codes */ @@ -560,69 +513,87 @@ TEST(ppm_sc_API, AES_names_AES) } /* Information Loss */ -TEST(ppm_sc_API, AES_sc_set_AES) -{ +TEST(ppm_sc_API, AES_sc_set_AES) { const auto all_events = libsinsp::events::all_event_set(); auto all_ppm_sc = libsinsp::events::event_set_to_sc_set(all_events); ASSERT_PPM_SC_CODES_EQ(all_ppm_sc, libsinsp::events::all_sc_set()); - /* We cannot recover events not related to tracepoints or syscalls like meta events or unused ones */ + /* We cannot recover events not related to tracepoints or syscalls like meta events or unused + * ones */ const auto partial_events = libsinsp::events::sc_set_to_event_set(all_ppm_sc); - for(int i = 0; i < PPM_EVENT_MAX; i++) - { + for(int i = 0; i < PPM_EVENT_MAX; i++) { if(libsinsp::events::is_unused_event((ppm_event_code)i) || libsinsp::events::is_plugin_event((ppm_event_code)i) || libsinsp::events::is_unknown_event((ppm_event_code)i) || - libsinsp::events::is_metaevent((ppm_event_code)i)) - { + libsinsp::events::is_metaevent((ppm_event_code)i)) { continue; } - ASSERT_TRUE(partial_events.contains((ppm_event_code)i)) << "\n- The event '" << scap_get_event_info_table()[i].name << "' is not present inside the event set" << std::endl; + ASSERT_TRUE(partial_events.contains((ppm_event_code)i)) + << "\n- The event '" << scap_get_event_info_table()[i].name + << "' is not present inside the event set" << std::endl; } ASSERT_EQ(partial_events.size(), SYSCALL_EVENTS_NUM + TRACEPOINT_EVENTS_NUM); } /* Information Enrichment */ -TEST(ppm_sc_API, SES_names_SES) -{ - const libsinsp::events::set shared_events{PPME_GENERIC_E, PPME_SYSCALL_CLONE_11_E, PPME_CONTAINER_JSON_2_E, PPME_PLUGINEVENT_E, PPME_SYSCALL_CLOSE_X, PPME_SCAPEVENT_E, PPME_PROCEXIT_1_X}; +TEST(ppm_sc_API, SES_names_SES) { + const libsinsp::events::set shared_events{PPME_GENERIC_E, + PPME_SYSCALL_CLONE_11_E, + PPME_CONTAINER_JSON_2_E, + PPME_PLUGINEVENT_E, + PPME_SYSCALL_CLOSE_X, + PPME_SCAPEVENT_E, + PPME_PROCEXIT_1_X}; const auto shared_events_names = libsinsp::events::event_set_to_names(shared_events); - std::set some_desired_event_names{"alarm", "clone", "container", "pluginevent", "close", "scapevent", "NA"}; // PPME_PROCEXIT_1_X is UNKNOWN + std::set some_desired_event_names{"alarm", + "clone", + "container", + "pluginevent", + "close", + "scapevent", + "NA"}; // PPME_PROCEXIT_1_X is UNKNOWN ASSERT_CONTAINS(shared_events_names, some_desired_event_names); - /* size = all generic names + 6 names written above (alarm is generic one so already included in the generic names) */ + /* size = all generic names + 6 names written above (alarm is generic one so already included in + * the generic names) */ ASSERT_EQ(shared_events_names.size(), GENERIC_SYSCALLS_NUM + 6); /* Convert again to codes, here we recover also enter/exit and old version */ libsinsp::events::set expected_shared_events{ - PPME_GENERIC_E, - PPME_GENERIC_X, - PPME_SYSCALL_CLONE_11_E, - PPME_SYSCALL_CLONE_11_X, - PPME_SYSCALL_CLONE_16_E, - PPME_SYSCALL_CLONE_16_X, - PPME_SYSCALL_CLONE_17_E, - PPME_SYSCALL_CLONE_17_X, - PPME_SYSCALL_CLONE_20_E, - PPME_SYSCALL_CLONE_20_X, - PPME_CONTAINER_E, // CONTAINER_X is unknown - PPME_CONTAINER_JSON_E, - PPME_CONTAINER_JSON_2_E, - PPME_PLUGINEVENT_E, - PPME_SYSCALL_CLOSE_E, - PPME_SYSCALL_CLOSE_X, - PPME_SCAPEVENT_E, - PPME_SCAPEVENT_X}; + PPME_GENERIC_E, + PPME_GENERIC_X, + PPME_SYSCALL_CLONE_11_E, + PPME_SYSCALL_CLONE_11_X, + PPME_SYSCALL_CLONE_16_E, + PPME_SYSCALL_CLONE_16_X, + PPME_SYSCALL_CLONE_17_E, + PPME_SYSCALL_CLONE_17_X, + PPME_SYSCALL_CLONE_20_E, + PPME_SYSCALL_CLONE_20_X, + PPME_CONTAINER_E, // CONTAINER_X is unknown + PPME_CONTAINER_JSON_E, + PPME_CONTAINER_JSON_2_E, + PPME_PLUGINEVENT_E, + PPME_SYSCALL_CLOSE_E, + PPME_SYSCALL_CLOSE_X, + PPME_SCAPEVENT_E, + PPME_SCAPEVENT_X}; /* We need to add all events associated with `NA` */ expected_shared_events = expected_shared_events.merge(expected_unknown_event_set); - ASSERT_PPM_EVENT_CODES_EQ(expected_shared_events, libsinsp::events::names_to_event_set(shared_events_names)); + ASSERT_PPM_EVENT_CODES_EQ(expected_shared_events, + libsinsp::events::names_to_event_set(shared_events_names)); } /* Information Loss */ -TEST(ppm_sc_API, SES_sc_set_SES) -{ - const libsinsp::events::set shared_events{PPME_GENERIC_E, PPME_SYSCALL_CLONE_11_E, PPME_CONTAINER_JSON_2_X, PPME_PLUGINEVENT_E, PPME_SYSCALL_CLOSE_X, PPME_SCAPEVENT_E, PPME_PAGE_FAULT_E}; +TEST(ppm_sc_API, SES_sc_set_SES) { + const libsinsp::events::set shared_events{PPME_GENERIC_E, + PPME_SYSCALL_CLONE_11_E, + PPME_CONTAINER_JSON_2_X, + PPME_PLUGINEVENT_E, + PPME_SYSCALL_CLOSE_X, + PPME_SCAPEVENT_E, + PPME_PAGE_FAULT_E}; auto shared_ppm_sc = libsinsp::events::event_set_to_sc_set(shared_events); @@ -635,57 +606,63 @@ TEST(ppm_sc_API, SES_sc_set_SES) auto shared_events_again = libsinsp::events::sc_set_to_event_set(shared_ppm_sc); - /* Convert again to codes, here we recover enter/exit and old versions but we cannot recover not syscall/tracepoints events */ + /* Convert again to codes, here we recover enter/exit and old versions but we cannot recover not + * syscall/tracepoints events */ libsinsp::events::set expected_shared_events{ - PPME_GENERIC_E, - PPME_GENERIC_X, - PPME_PAGE_FAULT_E, // not PAGE_FAULT_X because it is UNKNOWN - PPME_SYSCALL_CLONE_11_E, - PPME_SYSCALL_CLONE_11_X, - PPME_SYSCALL_CLONE_16_E, - PPME_SYSCALL_CLONE_16_X, - PPME_SYSCALL_CLONE_17_E, - PPME_SYSCALL_CLONE_17_X, - PPME_SYSCALL_CLONE_20_E, - PPME_SYSCALL_CLONE_20_X, - PPME_SYSCALL_CLOSE_E, - PPME_SYSCALL_CLOSE_X, + PPME_GENERIC_E, + PPME_GENERIC_X, + PPME_PAGE_FAULT_E, // not PAGE_FAULT_X because it is UNKNOWN + PPME_SYSCALL_CLONE_11_E, + PPME_SYSCALL_CLONE_11_X, + PPME_SYSCALL_CLONE_16_E, + PPME_SYSCALL_CLONE_16_X, + PPME_SYSCALL_CLONE_17_E, + PPME_SYSCALL_CLONE_17_X, + PPME_SYSCALL_CLONE_20_E, + PPME_SYSCALL_CLONE_20_X, + PPME_SYSCALL_CLOSE_E, + PPME_SYSCALL_CLOSE_X, }; ASSERT_PPM_EVENT_CODES_EQ(expected_shared_events, shared_events_again); } /* Information Enrichment */ -TEST(ppm_sc_API, NGES_names_NGES) -{ +TEST(ppm_sc_API, NGES_names_NGES) { /* This test is useful to assert that conversion without generics works well */ - const libsinsp::events::set not_generic_events{PPME_SYSCALL_CLONE_11_E, PPME_CONTAINER_JSON_2_E, PPME_PLUGINEVENT_E, PPME_SYSCALL_CLOSE_X}; + const libsinsp::events::set not_generic_events{PPME_SYSCALL_CLONE_11_E, + PPME_CONTAINER_JSON_2_E, + PPME_PLUGINEVENT_E, + PPME_SYSCALL_CLOSE_X}; const auto not_generic_events_names = libsinsp::events::event_set_to_names(not_generic_events); std::set some_desired_event_names{"clone", "container", "pluginevent", "close"}; - ASSERT_NAMES_EQ(test_utils::unordered_set_to_ordered(not_generic_events_names), some_desired_event_names); + ASSERT_NAMES_EQ(test_utils::unordered_set_to_ordered(not_generic_events_names), + some_desired_event_names); /* Convert again to codes, here we recover also enter/exit and old version */ - libsinsp::events::set expected_not_generic_events{ - PPME_SYSCALL_CLONE_11_E, - PPME_SYSCALL_CLONE_11_X, - PPME_SYSCALL_CLONE_16_E, - PPME_SYSCALL_CLONE_16_X, - PPME_SYSCALL_CLONE_17_E, - PPME_SYSCALL_CLONE_17_X, - PPME_SYSCALL_CLONE_20_E, - PPME_SYSCALL_CLONE_20_X, - PPME_CONTAINER_E, - PPME_CONTAINER_JSON_E, - PPME_CONTAINER_JSON_2_E, - PPME_PLUGINEVENT_E, - PPME_SYSCALL_CLOSE_E, - PPME_SYSCALL_CLOSE_X}; - - ASSERT_PPM_EVENT_CODES_EQ(expected_not_generic_events, libsinsp::events::names_to_event_set(not_generic_events_names)); + libsinsp::events::set expected_not_generic_events{PPME_SYSCALL_CLONE_11_E, + PPME_SYSCALL_CLONE_11_X, + PPME_SYSCALL_CLONE_16_E, + PPME_SYSCALL_CLONE_16_X, + PPME_SYSCALL_CLONE_17_E, + PPME_SYSCALL_CLONE_17_X, + PPME_SYSCALL_CLONE_20_E, + PPME_SYSCALL_CLONE_20_X, + PPME_CONTAINER_E, + PPME_CONTAINER_JSON_E, + PPME_CONTAINER_JSON_2_E, + PPME_PLUGINEVENT_E, + PPME_SYSCALL_CLOSE_E, + PPME_SYSCALL_CLOSE_X}; + + ASSERT_PPM_EVENT_CODES_EQ(expected_not_generic_events, + libsinsp::events::names_to_event_set(not_generic_events_names)); } /* Information Loss */ -TEST(ppm_sc_API, NGES_sc_set_NGES) -{ - const libsinsp::events::set not_generic_events{PPME_SYSCALL_CLONE_11_E, PPME_CONTAINER_JSON_2_X, PPME_PLUGINEVENT_E, PPME_SYSCALL_CLOSE_X}; +TEST(ppm_sc_API, NGES_sc_set_NGES) { + const libsinsp::events::set not_generic_events{PPME_SYSCALL_CLONE_11_E, + PPME_CONTAINER_JSON_2_X, + PPME_PLUGINEVENT_E, + PPME_SYSCALL_CLOSE_X}; auto not_generic_ppm_sc = libsinsp::events::event_set_to_sc_set(not_generic_events); @@ -695,79 +672,84 @@ TEST(ppm_sc_API, NGES_sc_set_NGES) auto not_generic_events_again = libsinsp::events::sc_set_to_event_set(not_generic_ppm_sc); - /* Convert again to codes, here we recover enter/exit and old versions but we cannot recover not syscall/tracepoints events */ + /* Convert again to codes, here we recover enter/exit and old versions but we cannot recover not + * syscall/tracepoints events */ libsinsp::events::set expected_not_generic_events{ - PPME_SYSCALL_CLONE_11_E, - PPME_SYSCALL_CLONE_11_X, - PPME_SYSCALL_CLONE_16_E, - PPME_SYSCALL_CLONE_16_X, - PPME_SYSCALL_CLONE_17_E, - PPME_SYSCALL_CLONE_17_X, - PPME_SYSCALL_CLONE_20_E, - PPME_SYSCALL_CLONE_20_X, - PPME_SYSCALL_CLOSE_E, - PPME_SYSCALL_CLOSE_X, + PPME_SYSCALL_CLONE_11_E, + PPME_SYSCALL_CLONE_11_X, + PPME_SYSCALL_CLONE_16_E, + PPME_SYSCALL_CLONE_16_X, + PPME_SYSCALL_CLONE_17_E, + PPME_SYSCALL_CLONE_17_X, + PPME_SYSCALL_CLONE_20_E, + PPME_SYSCALL_CLONE_20_X, + PPME_SYSCALL_CLOSE_E, + PPME_SYSCALL_CLOSE_X, }; ASSERT_PPM_EVENT_CODES_EQ(expected_not_generic_events, not_generic_events_again); } -TEST(ppm_sc_API, AEN_event_set_AEN) -{ - const auto all_events_names = libsinsp::events::event_set_to_names(libsinsp::events::all_event_set()); +TEST(ppm_sc_API, AEN_event_set_AEN) { + const auto all_events_names = + libsinsp::events::event_set_to_names(libsinsp::events::all_event_set()); const auto all_events = libsinsp::events::names_to_event_set(all_events_names); ASSERT_EQ(all_events.size(), PPM_EVENT_MAX); - const auto all_events_names_again = test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(all_events)); + const auto all_events_names_again = + test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(all_events)); ASSERT_NAMES_EQ(test_utils::unordered_set_to_ordered(all_events_names), all_events_names_again); } /* Information Enrichment */ -TEST(ppm_sc_API, SEN_event_set_SEN) -{ +TEST(ppm_sc_API, SEN_event_set_SEN) { /* `not-exists` and `Read` should not be considered */ - std::unordered_set shared_events_names{"syncfs", "clone", "switch", "not-exists", "Read"}; // Note the capital letter in 'Read' + std::unordered_set shared_events_names{ + "syncfs", + "clone", + "switch", + "not-exists", + "Read"}; // Note the capital letter in 'Read' const auto shared_events = libsinsp::events::names_to_event_set(shared_events_names); - libsinsp::events::set expected_shared_events{ - PPME_GENERIC_E, - PPME_GENERIC_X, - PPME_SYSCALL_CLONE_11_E, - PPME_SYSCALL_CLONE_11_X, - PPME_SYSCALL_CLONE_16_E, - PPME_SYSCALL_CLONE_16_X, - PPME_SYSCALL_CLONE_17_E, - PPME_SYSCALL_CLONE_17_X, - PPME_SYSCALL_CLONE_20_E, - PPME_SYSCALL_CLONE_20_X, - PPME_SCHEDSWITCH_1_E, - PPME_SCHEDSWITCH_6_E}; + libsinsp::events::set expected_shared_events{PPME_GENERIC_E, + PPME_GENERIC_X, + PPME_SYSCALL_CLONE_11_E, + PPME_SYSCALL_CLONE_11_X, + PPME_SYSCALL_CLONE_16_E, + PPME_SYSCALL_CLONE_16_X, + PPME_SYSCALL_CLONE_17_E, + PPME_SYSCALL_CLONE_17_X, + PPME_SYSCALL_CLONE_20_E, + PPME_SYSCALL_CLONE_20_X, + PPME_SCHEDSWITCH_1_E, + PPME_SCHEDSWITCH_6_E}; ASSERT_PPM_EVENT_CODES_EQ(expected_shared_events, shared_events); std::set some_desired_names{"syncfs", "clone", "switch"}; - auto shared_events_names_again = test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(shared_events)); + auto shared_events_names_again = test_utils::unordered_set_to_ordered( + libsinsp::events::event_set_to_names(shared_events)); /* Here we cannot recover just "syncfs" but we recover all generic syscalls names */ ASSERT_CONTAINS(shared_events_names_again, some_desired_names); ASSERT_EQ(shared_events_names_again.size(), GENERIC_SYSCALLS_NUM + 2); } -TEST(ppm_sc_API, NGEN_event_set_NGEN) -{ +TEST(ppm_sc_API, NGEN_event_set_NGEN) { std::unordered_set not_generic_events_names{"brk", "fcntl"}; const auto not_generic_events = libsinsp::events::names_to_event_set(not_generic_events_names); - libsinsp::events::set expected_not_generic_events{ - PPME_SYSCALL_FCNTL_E, - PPME_SYSCALL_FCNTL_X, - PPME_SYSCALL_BRK_4_E, - PPME_SYSCALL_BRK_4_X, - PPME_SYSCALL_BRK_1_E, - PPME_SYSCALL_BRK_1_X}; + libsinsp::events::set expected_not_generic_events{PPME_SYSCALL_FCNTL_E, + PPME_SYSCALL_FCNTL_X, + PPME_SYSCALL_BRK_4_E, + PPME_SYSCALL_BRK_4_X, + PPME_SYSCALL_BRK_1_E, + PPME_SYSCALL_BRK_1_X}; ASSERT_PPM_EVENT_CODES_EQ(expected_not_generic_events, not_generic_events); - const auto not_generic_events_names_again = test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(not_generic_events)); - ASSERT_NAMES_EQ(test_utils::unordered_set_to_ordered(not_generic_events_names), not_generic_events_names_again); + const auto not_generic_events_names_again = test_utils::unordered_set_to_ordered( + libsinsp::events::event_set_to_names(not_generic_events)); + ASSERT_NAMES_EQ(test_utils::unordered_set_to_ordered(not_generic_events_names), + not_generic_events_names_again); } /// todo(@Andreagit97) remove duplicated -TEST(ppm_sc_API, from_event_names_to_event_names_with_information_loss) -{ +TEST(ppm_sc_API, from_event_names_to_event_names_with_information_loss) { std::unordered_set event_names{"openat", "execveat", "syncfs"}; /* Converting event names associated with generic events causes information loss! @@ -786,19 +768,24 @@ TEST(ppm_sc_API, from_event_names_to_event_names_with_information_loss) ASSERT_EQ(event_codes.size(), 8); /* Converting again event set to names */ - auto event_names_with_all_generics = test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(event_codes)); + auto event_names_with_all_generics = + test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names(event_codes)); /* Expected set */ - auto expected_events_names = test_utils::unordered_set_to_ordered(libsinsp::events::event_set_to_names({PPME_GENERIC_E, PPME_GENERIC_X})); + auto expected_events_names = test_utils::unordered_set_to_ordered( + libsinsp::events::event_set_to_names({PPME_GENERIC_E, PPME_GENERIC_X})); expected_events_names.insert("openat"); expected_events_names.insert("execveat"); ASSERT_NAMES_EQ(event_names_with_all_generics, expected_events_names); } /// todo(@Andreagit97) remove duplicated -TEST(ppm_sc_API, event_set_to_names_misc) -{ - auto event_codes = libsinsp::events::set{PPME_GENERIC_E, PPME_GENERIC_X, PPME_SYSCALL_OPEN_E, PPME_SYSCALL_OPENAT_X, PPME_SYSCALL_OPENAT_2_E}; +TEST(ppm_sc_API, event_set_to_names_misc) { + auto event_codes = libsinsp::events::set{PPME_GENERIC_E, + PPME_GENERIC_X, + PPME_SYSCALL_OPEN_E, + PPME_SYSCALL_OPENAT_X, + PPME_SYSCALL_OPENAT_2_E}; const auto event_names = libsinsp::events::event_set_to_names(event_codes); std::set some_desired_event_names = {"open", "openat"}; ASSERT_CONTAINS(event_names, some_desired_event_names); @@ -810,9 +797,11 @@ TEST(ppm_sc_API, event_set_to_names_misc) ASSERT_PPM_EVENT_CODES_EQ(event_codes, event_codes_again); } -/*=============================== PPME set related (sinsp_events.cpp) ===============================*/ +/*=============================== PPME set related (sinsp_events.cpp) + * ===============================*/ -/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) ===============================*/ +/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) + * ===============================*/ /* The schema here is: * - All sc set @@ -826,29 +815,30 @@ TEST(ppm_sc_API, event_set_to_names_misc) * - NET sc set todo(@Andreagit97) * - PROC sc set todo(@Andreagit97) * - SYS sc set todo(@Andreagit97) - * - (ASS) -> names -> (ASS) ASS = all sc set (this test is not so meaningful the mapping is 1:1) + * - (ASS) -> names -> (ASS) ASS = all sc set (this test is not so meaningful the mapping is + * 1:1) * - (ASS) -> event set -> (ASS) - * - (SSS) -> event set -> (SSS) SSS = shared sc set (some syscall associated with generic events + not generic syscalls) + * - (SSS) -> event set -> (SSS) SSS = shared sc set (some syscall associated with generic + * events + not generic syscalls) * - (NGSS) -> event set -> (NGSS) NGSS = not generic sc set * - (SSN) -> sc set -> (SSN) SSN = shared sc names */ -TEST(ppm_sc_API, all_sc_set) -{ +TEST(ppm_sc_API, all_sc_set) { auto all_sc = libsinsp::events::all_sc_set(); - /* In all_sc we don't have `PPM_SC_UNKNOWN` and the code `382` that corresponds to old/wrong code */ + /* In all_sc we don't have `PPM_SC_UNKNOWN` and the code `382` that corresponds to old/wrong + * code */ ASSERT_EQ(all_sc.size(), PPM_SC_MAX - 2); } -TEST(ppm_sc_API, all_sc_names) -{ - auto sc_names = test_utils::unordered_set_to_ordered(libsinsp::events::sc_set_to_sc_names(libsinsp::events::all_sc_set())); +TEST(ppm_sc_API, all_sc_names) { + auto sc_names = test_utils::unordered_set_to_ordered( + libsinsp::events::sc_set_to_sc_names(libsinsp::events::all_sc_set())); std::set expected_sc_names; - /* In all_sc we don't have `PPM_SC_UNKNOWN` so we don't have to retrieve the "unknown" name, we start the for loop from 1 */ - for(int ppm_sc = 1; ppm_sc < PPM_SC_MAX; ppm_sc++) - { - if(std::string("").compare(scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)) == 0) - { + /* In all_sc we don't have `PPM_SC_UNKNOWN` so we don't have to retrieve the "unknown" name, we + * start the for loop from 1 */ + for(int ppm_sc = 1; ppm_sc < PPM_SC_MAX; ppm_sc++) { + if(std::string("").compare(scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)) == 0) { continue; } expected_sc_names.insert(scap_get_ppm_sc_name((ppm_sc_code)ppm_sc)); @@ -856,25 +846,26 @@ TEST(ppm_sc_API, all_sc_names) ASSERT_NAMES_EQ(sc_names, expected_sc_names); } -TEST(ppm_sc_API, sinsp_state_sc_set) -{ +TEST(ppm_sc_API, sinsp_state_sc_set) { ASSERT_PPM_SC_CODES_EQ(expected_sinsp_state_sc_set, libsinsp::events::sinsp_state_sc_set()); } -TEST(ppm_sc_API, enforce_sinsp_state_sc_set) -{ +TEST(ppm_sc_API, enforce_sinsp_state_sc_set) { auto expected_final_state_set = libsinsp::events::enforce_simple_sc_set(); expected_final_state_set.insert(PPM_SC_UNKNOWN); expected_final_state_set.insert(PPM_SC__NEWSELECT); expected_final_state_set.insert(PPM_SC_PAGE_FAULT_KERNEL); expected_final_state_set.insert(PPM_SC_SCHED_SWITCH); - ASSERT_PPM_SC_CODES_EQ(expected_final_state_set, libsinsp::events::enforce_simple_sc_set({PPM_SC_UNKNOWN, PPM_SC__NEWSELECT, PPM_SC_PAGE_FAULT_KERNEL, PPM_SC_SCHED_SWITCH})); + ASSERT_PPM_SC_CODES_EQ(expected_final_state_set, + libsinsp::events::enforce_simple_sc_set({PPM_SC_UNKNOWN, + PPM_SC__NEWSELECT, + PPM_SC_PAGE_FAULT_KERNEL, + PPM_SC_SCHED_SWITCH})); ASSERT_CONTAINS(expected_final_state_set, libsinsp::events::sinsp_state_sc_set()); } -TEST(ppm_sc_API, sc_empty_sets) -{ +TEST(ppm_sc_API, sc_empty_sets) { std::unordered_set empty_string_set; const auto empty_sc_set = libsinsp::events::sc_names_to_sc_set(empty_string_set); const auto empty_event_set = libsinsp::events::sc_set_to_event_set(empty_sc_set); @@ -884,45 +875,42 @@ TEST(ppm_sc_API, sc_empty_sets) ASSERT_TRUE(empty_sc_names.empty()); } -TEST(ppm_sc_API, sc_unknown) -{ +TEST(ppm_sc_API, sc_unknown) { libsinsp::events::set unknown_sc{PPM_SC_UNKNOWN}; ASSERT_TRUE(libsinsp::events::sc_set_to_event_set(unknown_sc).empty()); - ASSERT_NAMES_EQ(libsinsp::events::sc_set_to_sc_names(unknown_sc), std::unordered_set{"unknown"}); + ASSERT_NAMES_EQ(libsinsp::events::sc_set_to_sc_names(unknown_sc), + std::unordered_set{"unknown"}); } -TEST(ppm_sc_API, ASS_sc_names_ASS) -{ +TEST(ppm_sc_API, ASS_sc_names_ASS) { const auto all_sc = libsinsp::events::all_sc_set(); const auto all_sc_names = libsinsp::events::sc_set_to_sc_names(all_sc); const auto all_sc_again = libsinsp::events::sc_names_to_sc_set(all_sc_names); ASSERT_PPM_SC_CODES_EQ(all_sc, all_sc_again); } -TEST(ppm_sc_API, ASS_event_names_ASS) -{ +TEST(ppm_sc_API, ASS_event_names_ASS) { const auto all_sc = libsinsp::events::all_sc_set(); const auto all_event_names = libsinsp::events::sc_set_to_event_names(all_sc); const auto all_sc_again = libsinsp::events::event_names_to_sc_set(all_event_names); ASSERT_PPM_SC_CODES_EQ(all_sc, all_sc_again); } -TEST(ppm_sc_API, ASS_event_set_ASS) -{ +TEST(ppm_sc_API, ASS_event_set_ASS) { const auto all_sc = libsinsp::events::all_sc_set(); const auto all_events = libsinsp::events::sc_set_to_event_set(all_sc); - for(int i = 0; i < PPM_EVENT_MAX; i++) - { + for(int i = 0; i < PPM_EVENT_MAX; i++) { if(libsinsp::events::is_unused_event((ppm_event_code)i) || libsinsp::events::is_plugin_event((ppm_event_code)i) || libsinsp::events::is_unknown_event((ppm_event_code)i) || - libsinsp::events::is_metaevent((ppm_event_code)i)) - { + libsinsp::events::is_metaevent((ppm_event_code)i)) { continue; } - ASSERT_TRUE(all_events.contains((ppm_event_code)i)) << "\n- The event '" << scap_get_event_info_table()[i].name << "' is not present inside the event set" << std::endl; + ASSERT_TRUE(all_events.contains((ppm_event_code)i)) + << "\n- The event '" << scap_get_event_info_table()[i].name + << "' is not present inside the event set" << std::endl; } ASSERT_EQ(all_events.size(), SYSCALL_EVENTS_NUM + TRACEPOINT_EVENTS_NUM); @@ -931,20 +919,21 @@ TEST(ppm_sc_API, ASS_event_set_ASS) } /* Information Loss */ -TEST(ppm_sc_API, SSS_event_set_SSS) -{ - const libsinsp::events::set shared_sc_set{PPM_SC_UNKNOWN, PPM_SC_SYSLOG, PPM_SC_ACCEPT4, PPM_SC_PAGE_FAULT_KERNEL}; +TEST(ppm_sc_API, SSS_event_set_SSS) { + const libsinsp::events::set shared_sc_set{PPM_SC_UNKNOWN, + PPM_SC_SYSLOG, + PPM_SC_ACCEPT4, + PPM_SC_PAGE_FAULT_KERNEL}; const auto shared_event_set = libsinsp::events::sc_set_to_event_set(shared_sc_set); - const libsinsp::events::set expected_shared_event_set{ - PPME_GENERIC_E, - PPME_GENERIC_X, - PPME_SOCKET_ACCEPT4_6_E, - PPME_SOCKET_ACCEPT4_6_X, - PPME_SOCKET_ACCEPT4_5_E, - PPME_SOCKET_ACCEPT4_5_X, - PPME_SOCKET_ACCEPT4_E, - PPME_SOCKET_ACCEPT4_X, - PPME_PAGE_FAULT_E}; + const libsinsp::events::set expected_shared_event_set{PPME_GENERIC_E, + PPME_GENERIC_X, + PPME_SOCKET_ACCEPT4_6_E, + PPME_SOCKET_ACCEPT4_6_X, + PPME_SOCKET_ACCEPT4_5_E, + PPME_SOCKET_ACCEPT4_5_X, + PPME_SOCKET_ACCEPT4_E, + PPME_SOCKET_ACCEPT4_X, + PPME_PAGE_FAULT_E}; ASSERT_PPM_EVENT_CODES_EQ(shared_event_set, expected_shared_event_set); /* Converting again we are not able to understand that the initial syscall was `PPM_SC_SYSLOG`. @@ -957,35 +946,46 @@ TEST(ppm_sc_API, SSS_event_set_SSS) ASSERT_TRUE(shared_sc_set_again.contains(PPM_SC_PAGE_FAULT_KERNEL)); ASSERT_TRUE(shared_sc_set_again.contains(PPM_SC_PAGE_FAULT_USER)); ASSERT_FALSE(shared_sc_set_again.contains(PPM_SC_UNKNOWN)); - /* +3 because we have to add `PPM_SC_ACCEPT4` `PPM_SC_PAGE_FAULT_KERNEL` `PPM_SC_PAGE_FAULT_USER` */ + /* +3 because we have to add `PPM_SC_ACCEPT4` `PPM_SC_PAGE_FAULT_KERNEL` + * `PPM_SC_PAGE_FAULT_USER` */ ASSERT_EQ(shared_sc_set_again.size(), GENERIC_SYSCALLS_NUM + 3); } /* Information Loss */ -TEST(ppm_sc_API, NGSS_event_set_NGSS) -{ - const libsinsp::events::set not_generic_sc_set{PPM_SC_UNKNOWN, PPM_SC_PIPE2, PPM_SC_EVENTFD2, PPM_SC_BRK}; +TEST(ppm_sc_API, NGSS_event_set_NGSS) { + const libsinsp::events::set not_generic_sc_set{PPM_SC_UNKNOWN, + PPM_SC_PIPE2, + PPM_SC_EVENTFD2, + PPM_SC_BRK}; const auto not_generic_event_set = libsinsp::events::sc_set_to_event_set(not_generic_sc_set); const libsinsp::events::set expected_not_generic_event_set{ - PPME_SYSCALL_PIPE2_E, - PPME_SYSCALL_PIPE2_X, - PPME_SYSCALL_EVENTFD2_E, - PPME_SYSCALL_EVENTFD2_X, - PPME_SYSCALL_BRK_1_E, - PPME_SYSCALL_BRK_1_X, - PPME_SYSCALL_BRK_4_E, - PPME_SYSCALL_BRK_4_X}; + PPME_SYSCALL_PIPE2_E, + PPME_SYSCALL_PIPE2_X, + PPME_SYSCALL_EVENTFD2_E, + PPME_SYSCALL_EVENTFD2_X, + PPME_SYSCALL_BRK_1_E, + PPME_SYSCALL_BRK_1_X, + PPME_SYSCALL_BRK_4_E, + PPME_SYSCALL_BRK_4_X}; ASSERT_PPM_EVENT_CODES_EQ(expected_not_generic_event_set, not_generic_event_set); /* We lose also the `PPM_SC_UNKNOWN` */ - const auto not_generic_sc_set_again = libsinsp::events::event_set_to_sc_set(not_generic_event_set); + const auto not_generic_sc_set_again = + libsinsp::events::event_set_to_sc_set(not_generic_event_set); ASSERT_CONTAINS(not_generic_sc_set, not_generic_sc_set_again); ASSERT_EQ(not_generic_sc_set_again.size(), 3); } -TEST(ppm_sc_API, SSN_sc_set_SSN) -{ - auto sc_set = libsinsp::events::sc_names_to_sc_set(std::unordered_set{"open", "openat", "alarm", "****!!!!!", "NOT-SC", "", "unknown", "sched_process_exit"}); +TEST(ppm_sc_API, SSN_sc_set_SSN) { + auto sc_set = libsinsp::events::sc_names_to_sc_set( + std::unordered_set{"open", + "openat", + "alarm", + "****!!!!!", + "NOT-SC", + "", + "unknown", + "sched_process_exit"}); ASSERT_TRUE(sc_set.contains(PPM_SC_OPEN)); ASSERT_TRUE(sc_set.contains(PPM_SC_OPENAT)); ASSERT_TRUE(sc_set.contains(PPM_SC_ALARM)); @@ -993,12 +993,17 @@ TEST(ppm_sc_API, SSN_sc_set_SSN) ASSERT_TRUE(sc_set.contains(PPM_SC_SCHED_PROCESS_EXIT)); ASSERT_EQ(sc_set.size(), 5); - std::unordered_set expected_sc_names{"open", "openat", "alarm", "unknown", "sched_process_exit"}; + std::unordered_set expected_sc_names{"open", + "openat", + "alarm", + "unknown", + "sched_process_exit"}; auto sc_names_again = libsinsp::events::sc_set_to_sc_names(sc_set); ASSERT_NAMES_EQ(expected_sc_names, sc_names_again); } -/// todo(@Andreagit97) Here we miss all tests on `io_sc_set` and others... Not sure we want all those helpers, if yes we need to create -/// sets here in tests so we can assert against them +/// todo(@Andreagit97) Here we miss all tests on `io_sc_set` and others... Not sure we want all +/// those helpers, if yes we need to create sets here in tests so we can assert against them -/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) ===============================*/ +/*=============================== PPM_SC set related (sinsp_events_ppm_sc.cpp) + * ===============================*/ diff --git a/userspace/libsinsp/test/public_sinsp_API/sinsp_logger.cpp b/userspace/libsinsp/test/public_sinsp_API/sinsp_logger.cpp index 191e9bdc97..0f2db41482 100644 --- a/userspace/libsinsp/test/public_sinsp_API/sinsp_logger.cpp +++ b/userspace/libsinsp/test/public_sinsp_API/sinsp_logger.cpp @@ -27,8 +27,7 @@ limitations under the License. #include #include -namespace -{ +namespace { /** Default size for read buffers, must be <= the size of a pipe. */ const size_t BUFFER_SIZE = 4096; @@ -36,13 +35,11 @@ const size_t BUFFER_SIZE = 4096; /** The default log message content. */ const std::string DEFAULT_MESSAGE = "hello, world"; -class sinsp_logger_test : public testing::Test -{ +class sinsp_logger_test : public testing::Test { public: sinsp_logger_test() {} - void SetUp() - { + void SetUp() { libsinsp_logger()->reset(); s_cb_output.clear(); } @@ -59,8 +56,7 @@ class sinsp_logger_test : public testing::Test * @param[in] substr The substring for which to search. * @param[out] count The number of times substr was found in target. */ - void count_substrings(const std::string& target, const std::string& substr, size_t& count) - { + void count_substrings(const std::string& target, const std::string& substr, size_t& count) { size_t position = target.find(substr); count = 0; @@ -70,8 +66,7 @@ class sinsp_logger_test : public testing::Test ++count; - while ((position = target.find(substr, position + 1)) != std::string::npos) - { + while((position = target.find(substr, position + 1)) != std::string::npos) { ++count; } } @@ -82,8 +77,7 @@ class sinsp_logger_test : public testing::Test * @param[in] filename The name of the file to read. * @param[out] out The content of the file. */ - void read_file(const std::string& filename, std::string& out) - { + void read_file(const std::string& filename, std::string& out) { test_helpers::scoped_file_descriptor fd(open(filename.c_str(), O_RDONLY)); ASSERT_TRUE(fd.is_valid()); @@ -100,8 +94,7 @@ class sinsp_logger_test : public testing::Test * @param[in] fd The file descriptor from which to read. * @param[out] str The content read from the given fd */ - void nb_read_fd(const int fd, std::string& str) - { + void nb_read_fd(const int fd, std::string& str) { char buffer[BUFFER_SIZE] = {}; set_nonblocking(fd); @@ -131,8 +124,7 @@ class sinsp_logger_test : public testing::Test std::string& std_err, std::string& file_out, const sinsp_logger::severity severity = sinsp_logger::SEV_INFO, - const std::string& log_filename = "") - { + const std::string& log_filename = "") { test_helpers::scoped_pipe stdout_pipe; test_helpers::scoped_pipe stderr_pipe; @@ -144,7 +136,7 @@ class sinsp_logger_test : public testing::Test ASSERT_TRUE(pid >= 0); - if (pid == 0) // child + if(pid == 0) // child { ASSERT_TRUE(dup2(stdout_pipe.write_end().get_fd(), STDOUT_FILENO) >= 0); ASSERT_TRUE(dup2(stderr_pipe.write_end().get_fd(), STDERR_FILENO) >= 0); @@ -155,8 +147,7 @@ class sinsp_logger_test : public testing::Test libsinsp_logger()->log(message, severity); _exit(0); - } - else // parent + } else // parent { int status = 0; @@ -173,8 +164,7 @@ class sinsp_logger_test : public testing::Test nb_read_fd(stderr_pipe.read_end().get_fd(), std_err); stderr_pipe.read_end().close(); - if (log_filename != "") - { + if(log_filename != "") { read_file(log_filename.c_str(), file_out); } } @@ -188,8 +178,7 @@ class sinsp_logger_test : public testing::Test * @param[in] str The log message * @param[in] sev The log severity */ - static void log_callback_fn(std::string&& str, const sinsp_logger::severity sev) - { + static void log_callback_fn(std::string&& str, const sinsp_logger::severity sev) { s_cb_output = std::move(str); } @@ -206,8 +195,7 @@ class sinsp_logger_test : public testing::Test * * @param[in] fd The file descriptor to be placed in non-blocking mode. */ - void set_nonblocking(const int fd) - { + void set_nonblocking(const int fd) { int flags = fcntl(fd, F_GETFL); ASSERT_TRUE(flags >= 0); @@ -225,15 +213,13 @@ std::string sinsp_logger_test::s_cb_output; } // end namespace -TEST_F(sinsp_logger_test, constructor) -{ +TEST_F(sinsp_logger_test, constructor) { ASSERT_FALSE(libsinsp_logger()->has_output()); ASSERT_EQ(libsinsp_logger()->get_severity(), sinsp_logger::SEV_INFO); ASSERT_EQ(libsinsp_logger()->get_log_output_type(), sinsp_logger::OT_NONE); } -TEST_F(sinsp_logger_test, output_type) -{ +TEST_F(sinsp_logger_test, output_type) { ASSERT_FALSE(libsinsp_logger()->has_output()); libsinsp_logger()->add_stdout_log(); libsinsp_logger()->add_stderr_log(); @@ -247,15 +233,18 @@ TEST_F(sinsp_logger_test, output_type) libsinsp_logger()->add_file_log("./xyazd"); close(fd); - ASSERT_EQ(libsinsp_logger()->get_log_output_type(), (sinsp_logger::OT_STDOUT | sinsp_logger::OT_STDERR | sinsp_logger::OT_FILE | sinsp_logger::OT_CALLBACK | sinsp_logger::OT_NOTS | sinsp_logger::OT_ENCODE_SEV)); + ASSERT_EQ(libsinsp_logger()->get_log_output_type(), + (sinsp_logger::OT_STDOUT | sinsp_logger::OT_STDERR | sinsp_logger::OT_FILE | + sinsp_logger::OT_CALLBACK | sinsp_logger::OT_NOTS | sinsp_logger::OT_ENCODE_SEV)); libsinsp_logger()->remove_callback_log(); - ASSERT_EQ(libsinsp_logger()->get_log_output_type(), (sinsp_logger::OT_STDOUT | sinsp_logger::OT_STDERR | sinsp_logger::OT_FILE | sinsp_logger::OT_NOTS | sinsp_logger::OT_ENCODE_SEV)); + ASSERT_EQ(libsinsp_logger()->get_log_output_type(), + (sinsp_logger::OT_STDOUT | sinsp_logger::OT_STDERR | sinsp_logger::OT_FILE | + sinsp_logger::OT_NOTS | sinsp_logger::OT_ENCODE_SEV)); ASSERT_TRUE(libsinsp_logger()->has_output()); } -TEST_F(sinsp_logger_test, get_set_severity) -{ +TEST_F(sinsp_logger_test, get_set_severity) { libsinsp_logger()->set_severity(sinsp_logger::SEV_FATAL); ASSERT_EQ(libsinsp_logger()->get_severity(), sinsp_logger::SEV_FATAL); ASSERT_TRUE(libsinsp_logger()->is_enabled(sinsp_logger::SEV_FATAL)); @@ -266,8 +255,7 @@ TEST_F(sinsp_logger_test, get_set_severity) ASSERT_TRUE(libsinsp_logger()->is_enabled(sinsp_logger::SEV_ERROR)); } -TEST_F(sinsp_logger_test, initial_state) -{ +TEST_F(sinsp_logger_test, initial_state) { ASSERT_EQ(libsinsp_logger()->get_log_output_type(), sinsp_logger::OT_NONE); ASSERT_EQ(libsinsp_logger()->get_severity(), sinsp_logger::SEV_INFO); } @@ -277,13 +265,11 @@ TEST_F(sinsp_logger_test, initial_state) * With no enabled log sinks, calls to the logging API should produce no * output. */ -TEST_F(sinsp_logger_test, log_no_output) -{ +TEST_F(sinsp_logger_test, log_no_output) { std::string out; std::string err; std::string file; - generate_log(DEFAULT_MESSAGE, out, err, file, sinsp_logger::SEV_FATAL); ASSERT_EQ(out, ""); @@ -295,8 +281,7 @@ TEST_F(sinsp_logger_test, log_no_output) * Ensure that if the logger's severity is higher than the logged message's * severity, that the message is not emitted to the log sink. */ -TEST_F(sinsp_logger_test, low_severity_not_logged) -{ +TEST_F(sinsp_logger_test, low_severity_not_logged) { std::string out; std::string err; std::string file; @@ -318,8 +303,7 @@ TEST_F(sinsp_logger_test, low_severity_not_logged) * With stdout logging sink enabled, emitted logs should be written only to * standard output. */ -TEST_F(sinsp_logger_test, log_standard_output) -{ +TEST_F(sinsp_logger_test, log_standard_output) { std::string out; std::string err; std::string file; @@ -339,8 +323,7 @@ TEST_F(sinsp_logger_test, log_standard_output) * enabled), emitted logs should be written only to standard output, and those * logs contain the encoded severity before the timestamp */ -TEST_F(sinsp_logger_test, log_standard_output_severity) -{ +TEST_F(sinsp_logger_test, log_standard_output_severity) { std::string out; std::string err; std::string file; @@ -368,8 +351,7 @@ TEST_F(sinsp_logger_test, log_standard_output_severity) * enabled), emitted logs should be written only to standard output, and those * logs do not contain the timestamp. */ -TEST_F(sinsp_logger_test, log_standard_output_nots) -{ +TEST_F(sinsp_logger_test, log_standard_output_nots) { std::string out; std::string err; std::string file; @@ -394,8 +376,7 @@ TEST_F(sinsp_logger_test, log_standard_output_nots) * With stderr logging sink enabled, emitted logs should be written only to * standard error. */ -TEST_F(sinsp_logger_test, log_standard_error) -{ +TEST_F(sinsp_logger_test, log_standard_error) { std::string out; std::string err; std::string file; @@ -414,8 +395,7 @@ TEST_F(sinsp_logger_test, log_standard_error) * With file logging sink enabled, emitted logs should be written only to the * file. */ -TEST_F(sinsp_logger_test, log_file) -{ +TEST_F(sinsp_logger_test, log_file) { const std::string filename = "/tmp/ut.out"; // FIXME std::string out; std::string err; @@ -435,8 +415,7 @@ TEST_F(sinsp_logger_test, log_file) * With a callback logging sink enabled, emitted logs should be written only to * the callback. */ -TEST_F(sinsp_logger_test, log_callback) -{ +TEST_F(sinsp_logger_test, log_callback) { libsinsp_logger()->add_callback_log(log_callback_fn); ASSERT_EQ(libsinsp_logger()->get_log_output_type(), sinsp_logger::OT_CALLBACK); @@ -445,8 +424,7 @@ TEST_F(sinsp_logger_test, log_callback) ASSERT_NE(get_callback_output().find(DEFAULT_MESSAGE), std::string::npos); } -TEST_F(sinsp_logger_test, log_stderr_multithreaded) -{ +TEST_F(sinsp_logger_test, log_stderr_multithreaded) { const size_t NUM_THREADS = 5; const std::string message = "123456789"; // 9 characters const size_t NUM_LOGS = 80; @@ -474,34 +452,29 @@ TEST_F(sinsp_logger_test, log_stderr_multithreaded) // Create NUM_THREADS threads, each of which will write NUM_LOGS // instances of the message. - for (size_t i = 0; i < NUM_THREADS; ++i) - { - threads[i] = std::thread( - [message]() - { - for (size_t i = 0; i < NUM_LOGS; ++i) - { - const std::string new_str = + for(size_t i = 0; i < NUM_THREADS; ++i) { + threads[i] = std::thread([message]() { + for(size_t i = 0; i < NUM_LOGS; ++i) { + const std::string new_str = libsinsp_logger()->format_and_return(sinsp_logger::SEV_FATAL, - "%s", - message.c_str()); - - // Make sure that multiple threads aren't - // writing to the same underlying buffer - ASSERT_EQ(message, new_str); - - // Normally we wouldn't want to do something - // like this, but hopefully this will result - // in more thread interleaving between the - // threads. - std::this_thread::yield(); - } - }); + "%s", + message.c_str()); + + // Make sure that multiple threads aren't + // writing to the same underlying buffer + ASSERT_EQ(message, new_str); + + // Normally we wouldn't want to do something + // like this, but hopefully this will result + // in more thread interleaving between the + // threads. + std::this_thread::yield(); + } + }); } // Wait for all the threads to finish - for (size_t i = 0; i < NUM_THREADS; ++i) - { + for(size_t i = 0; i < NUM_THREADS; ++i) { threads[i].join(); } diff --git a/userspace/libsinsp/test/scap_files/cycledumper/cycledumper.cpp b/userspace/libsinsp/test/scap_files/cycledumper/cycledumper.cpp index 810cd37efa..eb181fbaaf 100644 --- a/userspace/libsinsp/test/scap_files/cycledumper/cycledumper.cpp +++ b/userspace/libsinsp/test/scap_files/cycledumper/cycledumper.cpp @@ -23,9 +23,9 @@ limitations under the License. #include #include -TEST(scap_file, filter) -{ - std::filesystem::path tmp_scap_file_path = std::filesystem::temp_directory_path() / "tmp.XYZXXZZZZ.scap"; +TEST(scap_file, filter) { + std::filesystem::path tmp_scap_file_path = + std::filesystem::temp_directory_path() / "tmp.XYZXXZZZZ.scap"; std::string tmp_scap_file_name = tmp_scap_file_path.string(); // Dump a filtered scap-file @@ -34,16 +34,20 @@ TEST(scap_file, filter) inspector.set_filter("proc.name=ifplugd"); inspector.open_savefile(LIBSINSP_TEST_SCAP_FILES_DIR "/sample.scap"); - auto dumper = std::make_unique(&inspector, tmp_scap_file_name, 0, 0, 0, 0, true); + auto dumper = std::make_unique(&inspector, + tmp_scap_file_name, + 0, + 0, + 0, + 0, + true); int32_t res; sinsp_evt* evt; - do - { + do { res = inspector.next(&evt); EXPECT_NE(res, SCAP_FAILURE); - if(res != SCAP_EOF) - { + if(res != SCAP_EOF) { dumper->dump(evt); } } while(res != SCAP_EOF); @@ -64,24 +68,33 @@ TEST(scap_file, filter) int n_opens = 0; int n_closes = 0; -void open_cb() { n_opens += 1; } +void open_cb() { + n_opens += 1; +} -void close_cb() { n_closes += 1; } +void close_cb() { + n_closes += 1; +} -TEST(scap_file, cycledumper_num_events) -{ +TEST(scap_file, cycledumper_num_events) { int events_per_capture = 100; n_opens = 0; n_closes = 0; - std::filesystem::path tmp_scap_file_path = std::filesystem::temp_directory_path() / "tmp.XYZXXZZZZ.scap"; + std::filesystem::path tmp_scap_file_path = + std::filesystem::temp_directory_path() / "tmp.XYZXXZZZZ.scap"; std::string tmp_scap_file_name = tmp_scap_file_path.string(); { sinsp inspector; inspector.open_savefile(LIBSINSP_TEST_SCAP_FILES_DIR "/sample.scap"); - auto dumper = std::make_unique(&inspector, tmp_scap_file_name, 0, 0, 0, - events_per_capture, true); + auto dumper = std::make_unique(&inspector, + tmp_scap_file_name, + 0, + 0, + 0, + events_per_capture, + true); std::vector> open_cbs = {std::bind(&open_cb)}; std::vector> close_cbs = {std::bind(&close_cb)}; @@ -90,12 +103,10 @@ TEST(scap_file, cycledumper_num_events) int32_t res; sinsp_evt* evt; - do - { + do { res = inspector.next(&evt); EXPECT_NE(res, SCAP_FAILURE); - if(res != SCAP_EOF) - { + if(res != SCAP_EOF) { dumper->dump(evt); } } while(res != SCAP_EOF); @@ -105,24 +116,29 @@ TEST(scap_file, cycledumper_num_events) } ASSERT_EQ(n_opens, 5); - ASSERT_EQ(n_closes, 6); // a autodump_stop is called before starting. + ASSERT_EQ(n_closes, 6); // a autodump_stop is called before starting. std::filesystem::remove(tmp_scap_file_path); } -TEST(scap_file, cycledumper_seconds) -{ +TEST(scap_file, cycledumper_seconds) { int seconds_per_capture = 1; n_opens = 0; n_closes = 0; - std::filesystem::path tmp_scap_file_path = std::filesystem::temp_directory_path() / "tmp.XYZXXZZZZ.scap"; + std::filesystem::path tmp_scap_file_path = + std::filesystem::temp_directory_path() / "tmp.XYZXXZZZZ.scap"; std::string tmp_scap_file_name = tmp_scap_file_path.string(); { sinsp inspector; inspector.open_savefile(LIBSINSP_TEST_SCAP_FILES_DIR "/sample.scap"); - auto dumper = std::make_unique(&inspector, tmp_scap_file_name, 0, - seconds_per_capture, 0, 0, true); + auto dumper = std::make_unique(&inspector, + tmp_scap_file_name, + 0, + seconds_per_capture, + 0, + 0, + true); std::vector> open_cbs = {std::bind(&open_cb)}; std::vector> close_cbs = {std::bind(&close_cb)}; @@ -131,12 +147,10 @@ TEST(scap_file, cycledumper_seconds) int32_t res; sinsp_evt* evt; - do - { + do { res = inspector.next(&evt); EXPECT_NE(res, SCAP_FAILURE); - if(res != SCAP_EOF) - { + if(res != SCAP_EOF) { dumper->dump(evt); } } while(res != SCAP_EOF); @@ -146,6 +160,6 @@ TEST(scap_file, cycledumper_seconds) } ASSERT_EQ(n_opens, 1); - ASSERT_EQ(n_closes, 2); // a autodump_stop is called before starting. + ASSERT_EQ(n_closes, 2); // a autodump_stop is called before starting. std::filesystem::remove(tmp_scap_file_path); } diff --git a/userspace/libsinsp/test/scap_files/kexec_arm64/kexec_arm64.cpp b/userspace/libsinsp/test/scap_files/kexec_arm64/kexec_arm64.cpp index ff32954c33..e55e0241b6 100644 --- a/userspace/libsinsp/test/scap_files/kexec_arm64/kexec_arm64.cpp +++ b/userspace/libsinsp/test/scap_files/kexec_arm64/kexec_arm64.cpp @@ -20,8 +20,7 @@ limitations under the License. #include #include -TEST(scap_file_kexec_arm64, tail_lineage) -{ +TEST(scap_file_kexec_arm64, tail_lineage) { std::string path = LIBSINSP_TEST_SCAP_FILES_DIR + std::string("kexec_arm64.scap"); sinsp m_inspector; m_inspector.open_savefile(path); @@ -36,23 +35,22 @@ TEST(scap_file_kexec_arm64, tail_lineage) /* Search the tail execve event */ int64_t tid_tail = 141546; - auto evt = scap_file_test_helpers::capture_search_evt_by_type_and_tid(&m_inspector, PPME_SYSCALL_EXECVE_19_X, - tid_tail); + auto evt = scap_file_test_helpers::capture_search_evt_by_type_and_tid(&m_inspector, + PPME_SYSCALL_EXECVE_19_X, + tid_tail); std::vector traverse_parents; - sinsp_threadinfo::visitor_func_t visitor = [&traverse_parents](sinsp_threadinfo* pt) - { + sinsp_threadinfo::visitor_func_t visitor = [&traverse_parents](sinsp_threadinfo* pt) { /* we stop when we reach the init parent */ traverse_parents.push_back(pt->m_tid); - if(pt->m_tid == INIT_TID) - { + if(pt->m_tid == INIT_TID) { return false; } return true; }; - /* In this captures all runc threads are already dead when we call tail so the expected lineage is the - * following: + /* In this captures all runc threads are already dead when we call tail so the expected lineage + * is the following: * * (num_event: 274503) * v [tail] tid: 141546, pid: 141546, ptid 141446, vtid: 21, vpid: 21, reaper: 0 @@ -70,8 +68,11 @@ TEST(scap_file_kexec_arm64, tail_lineage) int64_t tid_containerd_shim2 = 112962; int64_t tid_systemd2 = 1; - std::vector expected_traverse_parents_after_execve = {tid_sh, tid_containerd_shim1, tid_systemd1, - tid_containerd_shim2, tid_systemd2}; + std::vector expected_traverse_parents_after_execve = {tid_sh, + tid_containerd_shim1, + tid_systemd1, + tid_containerd_shim2, + tid_systemd2}; traverse_parents.clear(); ASSERT_TRUE(evt->get_thread_info()); evt->get_thread_info()->traverse_parent_state(visitor); @@ -84,8 +85,7 @@ TEST(scap_file_kexec_arm64, tail_lineage) ASSERT_TRUE(containerd_shim1_tinfo->m_tginfo->is_reaper()); } -TEST(scap_file_kexec_arm64, final_thread_table_dim) -{ +TEST(scap_file_kexec_arm64, final_thread_table_dim) { std::string path = LIBSINSP_TEST_SCAP_FILES_DIR + std::string("kexec_arm64.scap"); sinsp m_inspector; m_inspector.open_savefile(path); diff --git a/userspace/libsinsp/test/scap_files/kexec_x86/kexec_x86.cpp b/userspace/libsinsp/test/scap_files/kexec_x86/kexec_x86.cpp index 987db95460..05231ec0d5 100644 --- a/userspace/libsinsp/test/scap_files/kexec_x86/kexec_x86.cpp +++ b/userspace/libsinsp/test/scap_files/kexec_x86/kexec_x86.cpp @@ -20,8 +20,7 @@ limitations under the License. #include #include -TEST(scap_file_kexec_x86, tail_lineage) -{ +TEST(scap_file_kexec_x86, tail_lineage) { std::string path = LIBSINSP_TEST_SCAP_FILES_DIR + std::string("kexec_x86.scap"); sinsp m_inspector; m_inspector.open_savefile(path); @@ -36,16 +35,15 @@ TEST(scap_file_kexec_x86, tail_lineage) /* Search the tail execve event */ int64_t tid_tail = 107370; - auto evt = scap_file_test_helpers::capture_search_evt_by_type_and_tid(&m_inspector, PPME_SYSCALL_EXECVE_19_X, - tid_tail); + auto evt = scap_file_test_helpers::capture_search_evt_by_type_and_tid(&m_inspector, + PPME_SYSCALL_EXECVE_19_X, + tid_tail); std::vector traverse_parents; - sinsp_threadinfo::visitor_func_t visitor = [&traverse_parents](sinsp_threadinfo* pt) - { + sinsp_threadinfo::visitor_func_t visitor = [&traverse_parents](sinsp_threadinfo* pt) { /* we stop when we reach the init parent */ traverse_parents.push_back(pt->m_tid); - if(pt->m_tid == INIT_TID) - { + if(pt->m_tid == INIT_TID) { return false; } return true; @@ -59,10 +57,10 @@ TEST(scap_file_kexec_x86, tail_lineage) * v [tail] tid: 107370, pid: 107370, ptid 107364, vtid: 19, vpid: 19, reaper: 0 * v [sh] tid: 107364, pid: 107364, ptid: 107357, vtid: 13, vpid: 13, reaper: 0 * v {runc} tid: 107357, pid: 107354, ptid: 107204, vtid: 2019, vpid: 2016, reaper: 0 - * v {containerd-shim} tid: 107204, pid: 107196, ptid: 100562, vtid: 1951, vpid: 1943, reaper: 0, - * v [systemd] tid: 100562, pid: 100562, ptid: 100542, vtid: 1, vpid: 1, reaper: 1, - * v [containerd-shim] tid: 100542, pid: 100542, ptid: 1, vtid: 100542, vpid: 100542, reaper: 0 - * v [systemd] tid: 1, pid: 1, ptid: 0, vtid: 1, vpid: 1, reaper: 1 + * v {containerd-shim} tid: 107204, pid: 107196, ptid: 100562, vtid: 1951, vpid: 1943, reaper: + * 0, v [systemd] tid: 100562, pid: 100562, ptid: 100542, vtid: 1, vpid: 1, reaper: 1, v + * [containerd-shim] tid: 100542, pid: 100542, ptid: 1, vtid: 100542, vpid: 100542, reaper: 0 v + * [systemd] tid: 1, pid: 1, ptid: 0, vtid: 1, vpid: 1, reaper: 1 */ /* This is the process lineage we expect */ @@ -73,8 +71,12 @@ TEST(scap_file_kexec_x86, tail_lineage) int64_t tid_containerd_shim2 = 100542; int64_t tid_systemd2 = 1; - std::vector expected_traverse_parents_after_execve = { - tid_sh, tid_runc, tid_containerd_shim1, tid_systemd1, tid_containerd_shim2, tid_systemd2}; + std::vector expected_traverse_parents_after_execve = {tid_sh, + tid_runc, + tid_containerd_shim1, + tid_systemd1, + tid_containerd_shim2, + tid_systemd2}; traverse_parents.clear(); ASSERT_TRUE(evt->get_thread_info()); evt->get_thread_info()->traverse_parent_state(visitor); @@ -97,8 +99,11 @@ TEST(scap_file_kexec_x86, tail_lineage) * v [systemd] tid: 1, pid: 1, ptid: 0, vtid: 1, vpid: 1, reaper: 1 */ - std::vector expected_traverse_parents_after_remove = {tid_sh, tid_containerd_shim1, tid_systemd1, - tid_containerd_shim2, tid_systemd2}; + std::vector expected_traverse_parents_after_remove = {tid_sh, + tid_containerd_shim1, + tid_systemd1, + tid_containerd_shim2, + tid_systemd2}; traverse_parents.clear(); ASSERT_TRUE(evt->get_thread_info()); evt->get_thread_info()->traverse_parent_state(visitor); @@ -111,8 +116,7 @@ TEST(scap_file_kexec_x86, tail_lineage) ASSERT_TRUE(containerd_shim1_tinfo->m_tginfo->is_reaper()); } -TEST(scap_file_kexec_x86, final_thread_table_dim) -{ +TEST(scap_file_kexec_x86, final_thread_table_dim) { std::string path = LIBSINSP_TEST_SCAP_FILES_DIR + std::string("kexec_x86.scap"); sinsp m_inspector; m_inspector.open_savefile(path); diff --git a/userspace/libsinsp/test/sinsp_metrics.ut.cpp b/userspace/libsinsp/test/sinsp_metrics.ut.cpp index f5bea53b4c..392adb08d2 100644 --- a/userspace/libsinsp/test/sinsp_metrics.ut.cpp +++ b/userspace/libsinsp/test/sinsp_metrics.ut.cpp @@ -21,14 +21,14 @@ limitations under the License. #include "sinsp_with_test_input.h" #include -TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_prometheus) -{ +TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_prometheus) { DEFAULT_TREE auto evt = generate_random_event(p2_t1_tid); ASSERT_EQ(get_field_as_string(evt, "proc.nthreads"), "3"); /* Snapshot current metrics and get the updated metrics_snapshot buffer */ - uint32_t test_metrics_flags = (METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | METRICS_V2_RESOURCE_UTILIZATION | METRICS_V2_STATE_COUNTERS); + uint32_t test_metrics_flags = (METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | + METRICS_V2_RESOURCE_UTILIZATION | METRICS_V2_STATE_COUNTERS); libs::metrics::libs_metrics_collector libs_metrics_collector(&m_inspector, test_metrics_flags); libs::metrics::prometheus_metrics_converter prometheus_metrics_converter; @@ -41,224 +41,308 @@ TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_prometheus) std::string prometheus_text_substring; std::string metrics_names_all_str_post_unit_conversion_pre_prometheus_text_conversion; - for (auto& metric: metrics_snapshot) - { + for(auto& metric : metrics_snapshot) { prometheus_metrics_converter.convert_metric_to_unit_convention(metric); - if (!metrics_names_all_str_post_unit_conversion_pre_prometheus_text_conversion.empty()) - { + if(!metrics_names_all_str_post_unit_conversion_pre_prometheus_text_conversion.empty()) { metrics_names_all_str_post_unit_conversion_pre_prometheus_text_conversion += " "; } metrics_names_all_str_post_unit_conversion_pre_prometheus_text_conversion += metric.name; - // Since unit testing is very limited here just also print it for manual inspection if needed - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "testns", "falco"); + // Since unit testing is very limited here just also print it for manual inspection if + // needed + prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, + "testns", + "falco"); std::cerr << prometheus_text; - if (strncmp(metric.name, "n_missing_container_images", strlen(metric.name)) == 0) - { + if(strncmp(metric.name, "n_missing_container_images", strlen(metric.name)) == 0) { // This resembles the Falco client use case - // Falco output_rule metrics prepends either `falco.` or `scap.` to a single metric, see https://falco.org/docs/metrics/ - // Use same strings for `prometheus_subsystem`, but instead of `.` we use `_` delimiter to conform with Prometheus naming conventions + append the unit - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "testns", "falco", {{"example_key1", "example1"},{"example_key2", "example2"}}); - prometheus_text_substring = R"(# HELP testns_falco_n_missing_container_images_total https://falco.org/docs/metrics/ + // Falco output_rule metrics prepends either `falco.` or `scap.` to a single metric, see + // https://falco.org/docs/metrics/ Use same strings for `prometheus_subsystem`, but + // instead of `.` we use `_` delimiter to conform with Prometheus naming conventions + + // append the unit + prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus( + metric, + "testns", + "falco", + {{"example_key1", "example1"}, {"example_key2", "example2"}}); + prometheus_text_substring = + R"(# HELP testns_falco_n_missing_container_images_total https://falco.org/docs/metrics/ # TYPE testns_falco_n_missing_container_images_total gauge testns_falco_n_missing_container_images_total{example_key1="example1",example_key2="example2"} 0 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; // Test only one const_labels - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "testns", "falco", {{"example_key1", "example1"}}); - prometheus_text_substring = R"(# HELP testns_falco_n_missing_container_images_total https://falco.org/docs/metrics/ + prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus( + metric, + "testns", + "falco", + {{"example_key1", "example1"}}); + prometheus_text_substring = + R"(# HELP testns_falco_n_missing_container_images_total https://falco.org/docs/metrics/ # TYPE testns_falco_n_missing_container_images_total gauge testns_falco_n_missing_container_images_total{example_key1="example1"} 0 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; // Test no const_labels - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "testns", "falco"); - prometheus_text_substring = R"(# HELP testns_falco_n_missing_container_images_total https://falco.org/docs/metrics/ + prometheus_text = + prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, + "testns", + "falco"); + prometheus_text_substring = + R"(# HELP testns_falco_n_missing_container_images_total https://falco.org/docs/metrics/ # TYPE testns_falco_n_missing_container_images_total gauge testns_falco_n_missing_container_images_total 0 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; // Test no prometheus_subsytem - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "testns"); - prometheus_text_substring = R"(# HELP testns_n_missing_container_images_total https://falco.org/docs/metrics/ + prometheus_text = + prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, + "testns"); + prometheus_text_substring = + R"(# HELP testns_n_missing_container_images_total https://falco.org/docs/metrics/ # TYPE testns_n_missing_container_images_total gauge testns_n_missing_container_images_total 0 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; // Test no prometheus_namespace - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric); - prometheus_text_substring = R"(# HELP n_missing_container_images_total https://falco.org/docs/metrics/ + prometheus_text = + prometheus_metrics_converter.convert_metric_to_text_prometheus(metric); + prometheus_text_substring = + R"(# HELP n_missing_container_images_total https://falco.org/docs/metrics/ # TYPE n_missing_container_images_total gauge n_missing_container_images_total 0 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; // Test no prometheus_namespace, but prometheus_subsytem - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "", "falco"); - prometheus_text_substring = R"(# HELP falco_n_missing_container_images_total https://falco.org/docs/metrics/ + prometheus_text = + prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, + "", + "falco"); + prometheus_text_substring = + R"(# HELP falco_n_missing_container_images_total https://falco.org/docs/metrics/ # TYPE falco_n_missing_container_images_total gauge falco_n_missing_container_images_total 0 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; - } else if (strncmp(metric.name, "memory_rss_bytes", strlen(metric.name)) == 0) - { - // Test that libs native metric unit suffix was removed and replaced by the Prometheus specific unit suffix naming convention - // todo adjust once base units are implemented - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "testns", "falco"); - prometheus_text_substring = R"(# HELP testns_falco_memory_rss_bytes https://falco.org/docs/metrics/ + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; + } else if(strncmp(metric.name, "memory_rss_bytes", strlen(metric.name)) == 0) { + // Test that libs native metric unit suffix was removed and replaced by the Prometheus + // specific unit suffix naming convention todo adjust once base units are implemented + prometheus_text = + prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, + "testns", + "falco"); + prometheus_text_substring = + R"(# HELP testns_falco_memory_rss_bytes https://falco.org/docs/metrics/ # TYPE testns_falco_memory_rss_bytes gauge testns_falco_memory_rss_bytes )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; } } - ASSERT_EQ(metrics_names_all_str_post_unit_conversion_pre_prometheus_text_conversion, - "cpu_usage_ratio memory_rss_bytes memory_vsz_bytes memory_pss_bytes container_memory_used_bytes host_cpu_usage_ratio host_memory_used_bytes host_procs_running host_open_fds n_threads n_fds n_noncached_fd_lookups n_cached_fd_lookups n_failed_fd_lookups n_added_fds n_removed_fds n_stored_evts n_store_evts_drops n_retrieved_evts n_retrieve_evts_drops n_noncached_thread_lookups n_cached_thread_lookups n_failed_thread_lookups n_added_threads n_removed_threads n_drops_full_threadtable n_missing_container_images n_containers"); - - // Test global wrapper base metrics plus test invalid characters sanitization for the metric and label names (pseudo metrics) - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus("56kernel_release-:!", "", "", {{"0kernel_release__", "6.6.7-200.fc39.x86_64"}, {"", "empty_key_name"}}); + ASSERT_EQ( + metrics_names_all_str_post_unit_conversion_pre_prometheus_text_conversion, + "cpu_usage_ratio memory_rss_bytes memory_vsz_bytes memory_pss_bytes " + "container_memory_used_bytes host_cpu_usage_ratio host_memory_used_bytes " + "host_procs_running host_open_fds n_threads n_fds n_noncached_fd_lookups " + "n_cached_fd_lookups n_failed_fd_lookups n_added_fds n_removed_fds n_stored_evts " + "n_store_evts_drops n_retrieved_evts n_retrieve_evts_drops n_noncached_thread_lookups " + "n_cached_thread_lookups n_failed_thread_lookups n_added_threads n_removed_threads " + "n_drops_full_threadtable n_missing_container_images n_containers"); + + // Test global wrapper base metrics plus test invalid characters sanitization for the metric and + // label names (pseudo metrics) + prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus( + "56kernel_release-:!", + "", + "", + {{"0kernel_release__", "6.6.7-200.fc39.x86_64"}, {"", "empty_key_name"}}); prometheus_text_substring = R"(# HELP _56kernel_release_:_info https://falco.org/docs/metrics/ # TYPE _56kernel_release_:_info gauge _56kernel_release_:_info{_0kernel_release_="6.6.7-200.fc39.x86_64"} 1 )"; - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus("", "", "", {{"0kernel_release__", "6.6.7-200.fc39.x86_64"}, {"", "empty_key_name"}}); - prometheus_text_substring = R"(# HELP _info https://falco.org/docs/metrics/ + prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus( + "", + "", + "", + {{"0kernel_release__", "6.6.7-200.fc39.x86_64"}, {"", "empty_key_name"}}); + prometheus_text_substring = R"(# HELP _info https://falco.org/docs/metrics/ # TYPE _info gauge _info{_0kernel_release_="6.6.7-200.fc39.x86_64"} 1 )"; std::cerr << prometheus_text; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; // Another round of fake metric tests since we do not fetch real scap metrics, for example. std::vector fake_metrics_snapshot; - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("sys_enter.run_cnt", - METRICS_V2_LIBBPF_STATS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - 76435525241UL)); - - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("sys_enter.run_time_ns", - METRICS_V2_LIBBPF_STATS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_TIME_NS_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - 16269369826392UL)); - - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("sys_enter.avg_time_ns", - METRICS_V2_LIBBPF_STATS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_TIME_NS, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - 203UL)); - - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("n_drops", - METRICS_V2_KERNEL_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - 674200UL)); - - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("n_drops_buffer_total", - METRICS_V2_KERNEL_COUNTERS, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - 5000UL)); + fake_metrics_snapshot.emplace_back( + libs::metrics::libsinsp_metrics::new_metric("sys_enter.run_cnt", + METRICS_V2_LIBBPF_STATS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + 76435525241UL)); + + fake_metrics_snapshot.emplace_back( + libs::metrics::libsinsp_metrics::new_metric("sys_enter.run_time_ns", + METRICS_V2_LIBBPF_STATS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_TIME_NS_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + 16269369826392UL)); + + fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric( + "sys_enter.avg_time_ns", + METRICS_V2_LIBBPF_STATS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_TIME_NS, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + 203UL)); + + fake_metrics_snapshot.emplace_back( + libs::metrics::libsinsp_metrics::new_metric("n_drops", + METRICS_V2_KERNEL_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + 674200UL)); + + fake_metrics_snapshot.emplace_back( + libs::metrics::libsinsp_metrics::new_metric("n_drops_buffer_total", + METRICS_V2_KERNEL_COUNTERS, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + 5000UL)); // Simulate some derived metrics; critical for example for Falco consumer use cases - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("duration_sec", - METRICS_V2_MISC, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_TIME_S_COUNT, - METRIC_VALUE_METRIC_TYPE_MONOTONIC, - 144UL)); - - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("evt_rate_sec", - METRICS_V2_MISC, - METRIC_VALUE_TYPE_D, - METRIC_VALUE_UNIT_TIME_S, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - 126065.4)); - - // Timestamps while they always go up should still be regarded as gauge from a Prometheus perspective - // https://www.robustperception.io/are-increasing-timestamps-counters-or-gauges/ - fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric("host_boot_ts", - METRICS_V2_MISC, - METRIC_VALUE_TYPE_U64, - METRIC_VALUE_UNIT_TIME_TIMESTAMP_NS, - METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, - 1708753667000000000UL)); - - for (auto& metric: fake_metrics_snapshot) - { + fake_metrics_snapshot.emplace_back( + libs::metrics::libsinsp_metrics::new_metric("duration_sec", + METRICS_V2_MISC, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_TIME_S_COUNT, + METRIC_VALUE_METRIC_TYPE_MONOTONIC, + 144UL)); + + fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric( + "evt_rate_sec", + METRICS_V2_MISC, + METRIC_VALUE_TYPE_D, + METRIC_VALUE_UNIT_TIME_S, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + 126065.4)); + + // Timestamps while they always go up should still be regarded as gauge from a Prometheus + // perspective https://www.robustperception.io/are-increasing-timestamps-counters-or-gauges/ + fake_metrics_snapshot.emplace_back(libs::metrics::libsinsp_metrics::new_metric( + "host_boot_ts", + METRICS_V2_MISC, + METRIC_VALUE_TYPE_U64, + METRIC_VALUE_UNIT_TIME_TIMESTAMP_NS, + METRIC_VALUE_METRIC_TYPE_NON_MONOTONIC_CURRENT, + 1708753667000000000UL)); + + for(auto& metric : fake_metrics_snapshot) { prometheus_metrics_converter.convert_metric_to_unit_convention(metric); - prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, "testns", "falco"); + prometheus_text = prometheus_metrics_converter.convert_metric_to_text_prometheus(metric, + "testns", + "falco"); std::cerr << prometheus_text; - if (strncmp(metric.name, "sys_enter.run_cnt", strlen(metric.name)) == 0) - { - prometheus_text_substring = R"(# HELP testns_falco_sys_enter_run_cnt_total https://falco.org/docs/metrics/ + if(strncmp(metric.name, "sys_enter.run_cnt", strlen(metric.name)) == 0) { + prometheus_text_substring = + R"(# HELP testns_falco_sys_enter_run_cnt_total https://falco.org/docs/metrics/ # TYPE testns_falco_sys_enter_run_cnt_total counter testns_falco_sys_enter_run_cnt_total 76435525241 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; - } else if (strncmp(metric.name, "sys_enter.run_time_ns", strlen(metric.name)) == 0) - { - prometheus_text_substring = R"(# HELP testns_falco_sys_enter_run_time_nanoseconds_total https://falco.org/docs/metrics/ + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; + } else if(strncmp(metric.name, "sys_enter.run_time_ns", strlen(metric.name)) == 0) { + prometheus_text_substring = + R"(# HELP testns_falco_sys_enter_run_time_nanoseconds_total https://falco.org/docs/metrics/ # TYPE testns_falco_sys_enter_run_time_nanoseconds_total counter testns_falco_sys_enter_run_time_nanoseconds_total 16269369826392 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; - } else if (strncmp(metric.name, "sys_enter.avg_time_ns", strlen(metric.name)) == 0) - { - prometheus_text_substring = R"(# HELP testns_falco_sys_enter_avg_time_nanoseconds https://falco.org/docs/metrics/ + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; + } else if(strncmp(metric.name, "sys_enter.avg_time_ns", strlen(metric.name)) == 0) { + prometheus_text_substring = + R"(# HELP testns_falco_sys_enter_avg_time_nanoseconds https://falco.org/docs/metrics/ # TYPE testns_falco_sys_enter_avg_time_nanoseconds gauge testns_falco_sys_enter_avg_time_nanoseconds 203 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; - } else if (strncmp(metric.name, "n_drops_buffer_total", strlen(metric.name)) == 0 && strlen(metric.name) == 20) // avoid clash with "n_drops" metric name + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; + } else if(strncmp(metric.name, "n_drops_buffer_total", strlen(metric.name)) == 0 && + strlen(metric.name) == 20) // avoid clash with "n_drops" metric name { - prometheus_text_substring = R"(# HELP testns_falco_n_drops_buffer_total https://falco.org/docs/metrics/ + prometheus_text_substring = + R"(# HELP testns_falco_n_drops_buffer_total https://falco.org/docs/metrics/ # TYPE testns_falco_n_drops_buffer_total counter testns_falco_n_drops_buffer_total 5000 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; - } else if (strncmp(metric.name, "duration_sec", strlen(metric.name)) == 0) - { - prometheus_text_substring = R"(# HELP testns_falco_duration_seconds_total https://falco.org/docs/metrics/ + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; + } else if(strncmp(metric.name, "duration_sec", strlen(metric.name)) == 0) { + prometheus_text_substring = + R"(# HELP testns_falco_duration_seconds_total https://falco.org/docs/metrics/ # TYPE testns_falco_duration_seconds_total counter testns_falco_duration_seconds_total 144 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; - } else if (strncmp(metric.name, "evt_rate_sec", strlen(metric.name)) == 0) - { - prometheus_text_substring = R"(# HELP testns_falco_evt_rate_seconds https://falco.org/docs/metrics/ + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; + } else if(strncmp(metric.name, "evt_rate_sec", strlen(metric.name)) == 0) { + prometheus_text_substring = + R"(# HELP testns_falco_evt_rate_seconds https://falco.org/docs/metrics/ # TYPE testns_falco_evt_rate_seconds gauge testns_falco_evt_rate_seconds 126065.400000 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; - } else if (strncmp(metric.name, "host_boot_ts", strlen(metric.name)) == 0) - { - prometheus_text_substring = R"(# HELP testns_falco_host_boot_timestamp_nanoseconds https://falco.org/docs/metrics/ + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; + } else if(strncmp(metric.name, "host_boot_ts", strlen(metric.name)) == 0) { + prometheus_text_substring = + R"(# HELP testns_falco_host_boot_timestamp_nanoseconds https://falco.org/docs/metrics/ # TYPE testns_falco_host_boot_timestamp_nanoseconds gauge testns_falco_host_boot_timestamp_nanoseconds 1708753667000000000 )"; - ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) << "Substring not found in prometheus_text got\n" << prometheus_text; + ASSERT_TRUE(prometheus_text.find(prometheus_text_substring) != std::string::npos) + << "Substring not found in prometheus_text got\n" + << prometheus_text; } } - } -TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_output_rule) -{ +TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_output_rule) { DEFAULT_TREE auto evt = generate_random_event(p2_t1_tid); ASSERT_EQ(get_field_as_string(evt, "proc.nthreads"), "3"); /* Snapshot current metrics and get the updated metrics_snapshot buffer */ - uint32_t test_metrics_flags = (METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | METRICS_V2_RESOURCE_UTILIZATION | METRICS_V2_STATE_COUNTERS); + uint32_t test_metrics_flags = (METRICS_V2_KERNEL_COUNTERS | METRICS_V2_LIBBPF_STATS | + METRICS_V2_RESOURCE_UTILIZATION | METRICS_V2_STATE_COUNTERS); libs::metrics::libs_metrics_collector libs_metrics_collector(&m_inspector, test_metrics_flags); libs::metrics::output_rule_metrics_converter output_rule_metrics_converter; @@ -270,53 +354,62 @@ TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_output_rule) metrics_snapshot = libs_metrics_collector.get_metrics(); ASSERT_EQ(metrics_snapshot.size(), 28); - /* These names should always be available, note that we currently can't check for the merged scap stats metrics here */ - std::unordered_set minimal_metrics_names = {"cpu_usage_perc", "memory_rss_kb", "host_open_fds", \ - "n_threads", "n_fds", "n_added_fds", "n_added_threads", "n_removed_threads", "n_containers"}; - - for(const auto& metric_name : minimal_metrics_names) - { + /* These names should always be available, note that we currently can't check for the merged + * scap stats metrics here */ + std::unordered_set minimal_metrics_names = {"cpu_usage_perc", + "memory_rss_kb", + "host_open_fds", + "n_threads", + "n_fds", + "n_added_fds", + "n_added_threads", + "n_removed_threads", + "n_containers"}; + + for(const auto& metric_name : minimal_metrics_names) { size_t i = 0; - for (const auto& metric: metrics_snapshot) - { - if(metric_name == metric.name) - { + for(const auto& metric : metrics_snapshot) { + if(metric_name == metric.name) { break; } i++; } - if(i == metrics_snapshot.size()) - { + if(i == metrics_snapshot.size()) { FAIL() << "unable to find stat '" << metric_name << "' in metrics_snapshot buffer"; } } /* Assert successful memory unit changes and sanity check some values to be greater than 0 */ - const std::vector metrics_names_memory = {"memory_rss_mb", "memory_vsz_mb", "memory_pss_mb", "container_memory_used_mb", "host_memory_used_mb"}; - const std::vector metrics_names_values_gt = {"n_threads", "n_fds", "n_added_threads"}; + const std::vector metrics_names_memory = {"memory_rss_mb", + "memory_vsz_mb", + "memory_pss_mb", + "container_memory_used_mb", + "host_memory_used_mb"}; + const std::vector metrics_names_values_gt = {"n_threads", + "n_fds", + "n_added_threads"}; int success_memory_cnt = 0; int success_values_cnt = 0; - for (auto& metric: metrics_snapshot) - { - // This resembles the Falco client use case and would be called if `convert_memory_to_mb` is set to true + for(auto& metric : metrics_snapshot) { + // This resembles the Falco client use case and would be called if `convert_memory_to_mb` is + // set to true output_rule_metrics_converter.convert_metric_to_unit_convention(metric); - if (std::find(metrics_names_memory.begin(), metrics_names_memory.end(), metric.name) != metrics_names_memory.end()) - { + if(std::find(metrics_names_memory.begin(), metrics_names_memory.end(), metric.name) != + metrics_names_memory.end()) { ASSERT_EQ(metric.unit, METRIC_VALUE_UNIT_MEMORY_MEGABYTES); ASSERT_EQ(metric.type, METRIC_VALUE_TYPE_D); - if (strncmp(metric.name, "host_memory_used_mb", strlen(metric.name)) == 0 || strncmp(metric.name, "memory_rss_mb", strlen(metric.name)) == 0) - { + if(strncmp(metric.name, "host_memory_used_mb", strlen(metric.name)) == 0 || + strncmp(metric.name, "memory_rss_mb", strlen(metric.name)) == 0) { ASSERT_GT(metric.value.d, 0); // Just making sure we don't get a high value due to an unitialized variables ASSERT_LT(metric.value.d, 1000000); success_memory_cnt++; - } else - { + } else { success_memory_cnt++; } } - if (std::find(metrics_names_values_gt.begin(), metrics_names_values_gt.end(), metric.name) != metrics_names_values_gt.end()) - { + if(std::find(metrics_names_values_gt.begin(), metrics_names_values_gt.end(), metric.name) != + metrics_names_values_gt.end()) { ASSERT_GT(metric.value.u64, 0); // Just making sure we don't get a high value due to an uninitialized variables ASSERT_LT(metric.value.u64, 106721347371); @@ -341,8 +434,9 @@ TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_output_rule) /* Some sanity checks for selective flags */ test_metrics_flags = 0; - test_metrics_flags |= METRICS_V2_KERNEL_COUNTERS; // 20, but can't test it here it's 0 - test_metrics_flags |= METRICS_V2_LIBBPF_STATS; // 21 (x86_64 machine), but can't test it here it's 0 + test_metrics_flags |= METRICS_V2_KERNEL_COUNTERS; // 20, but can't test it here it's 0 + test_metrics_flags |= + METRICS_V2_LIBBPF_STATS; // 21 (x86_64 machine), but can't test it here it's 0 libs::metrics::libs_metrics_collector libs_metrics_collector4(&m_inspector, test_metrics_flags); libs_metrics_collector4.snapshot(); metrics_snapshot = libs_metrics_collector4.get_metrics(); @@ -369,14 +463,19 @@ TEST_F(sinsp_with_test_input, sinsp_libs_metrics_collector_output_rule) ASSERT_EQ(metrics_snapshot.size(), 28); } -TEST(sinsp_libs_metrics, sinsp_libs_metrics_convert_units) -{ +TEST(sinsp_libs_metrics, sinsp_libs_metrics_convert_units) { /* Test public libs::metrics::convert_memory method */ - double converted_memory = libs::metrics::convert_memory(METRIC_VALUE_UNIT_MEMORY_BYTES, METRIC_VALUE_UNIT_MEMORY_MEGABYTES, (uint64_t)52428800); + double converted_memory = libs::metrics::convert_memory(METRIC_VALUE_UNIT_MEMORY_BYTES, + METRIC_VALUE_UNIT_MEMORY_MEGABYTES, + (uint64_t)52428800); ASSERT_EQ(converted_memory, 50); - converted_memory = libs::metrics::convert_memory(METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, METRIC_VALUE_UNIT_MEMORY_MEGABYTES, (uint64_t)51200); + converted_memory = libs::metrics::convert_memory(METRIC_VALUE_UNIT_MEMORY_KIBIBYTES, + METRIC_VALUE_UNIT_MEMORY_MEGABYTES, + (uint64_t)51200); ASSERT_EQ(converted_memory, 50); - converted_memory = libs::metrics::convert_memory(METRIC_VALUE_UNIT_MEMORY_MEGABYTES, METRIC_VALUE_UNIT_MEMORY_MEGABYTES, (uint64_t)50); + converted_memory = libs::metrics::convert_memory(METRIC_VALUE_UNIT_MEMORY_MEGABYTES, + METRIC_VALUE_UNIT_MEMORY_MEGABYTES, + (uint64_t)50); ASSERT_EQ(converted_memory, 50); } diff --git a/userspace/libsinsp/test/sinsp_utils.ut.cpp b/userspace/libsinsp/test/sinsp_utils.ut.cpp index 8779e0b0fe..a2dff2117a 100644 --- a/userspace/libsinsp/test/sinsp_utils.ut.cpp +++ b/userspace/libsinsp/test/sinsp_utils.ut.cpp @@ -20,8 +20,7 @@ limitations under the License. #include #include -TEST(sinsp_utils_test, concatenate_paths) -{ +TEST(sinsp_utils_test, concatenate_paths) { // Some tests were motivated by this resource: // https://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap04.html#tag_04_11 @@ -54,7 +53,8 @@ TEST(sinsp_utils_test, concatenate_paths) path1 = "a"; path2 = "../"; res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("a..", res); // since the helper does not add any "/" between path1 and path2, we end up with this. + EXPECT_EQ("a..", res); // since the helper does not add any "/" between path1 and path2, we end + // up with this. path1 = "a/"; path2 = "../"; @@ -69,22 +69,24 @@ TEST(sinsp_utils_test, concatenate_paths) path1 = "foo/"; path2 = "..//a"; res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("a", res); // path2 has been sanitized, plus we moved up a folder because of ".." + EXPECT_EQ("a", res); // path2 has been sanitized, plus we moved up a folder because of ".." path1 = "/foo/"; path2 = "..//a"; res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("/a", res); // path2 has been sanitized, plus we moved up a folder because of ".." + EXPECT_EQ("/a", res); // path2 has been sanitized, plus we moved up a folder because of ".." path1 = "heolo"; path2 = "w////////////..//////.////////r.|"; res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("r.|", res); // since the helper does not add any "/" between path1 and path2, we end up with this. + EXPECT_EQ("r.|", res); // since the helper does not add any "/" between path1 and path2, we end + // up with this. path1 = "heolo"; - path2 = "w/////////////..//"; // heolow/////////////..// > heolow/..// -> / + path2 = "w/////////////..//"; // heolow/////////////..// > heolow/..// -> / res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("", res); // since the helper does not add any "/" between path1 and path2, we end up with this, ie a folder up from "heolow/" + EXPECT_EQ("", res); // since the helper does not add any "/" between path1 and path2, we end up + // with this, ie a folder up from "heolow/" path1 = ""; path2 = "./"; @@ -144,17 +146,20 @@ TEST(sinsp_utils_test, concatenate_paths) path1 = "./app"; path2 = "custom/term"; res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("./appcustom/term", res); // since path1 is not '/' terminated, we expect a string concat without further path fields + EXPECT_EQ("./appcustom/term", res); // since path1 is not '/' terminated, we expect a string + // concat without further path fields path1 = "/app"; path2 = "custom/term"; res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("/appcustom/term", res); // since path1 is not '/' terminated, we expect a string concat without further path fields + EXPECT_EQ("/appcustom/term", res); // since path1 is not '/' terminated, we expect a string + // concat without further path fields path1 = "app"; path2 = "custom/term"; res = sinsp_utils::concatenate_paths(path1, path2); - EXPECT_EQ("appcustom/term", res); // since path1 is not '/' terminated, we expect a string concat without further path fields + EXPECT_EQ("appcustom/term", res); // since path1 is not '/' terminated, we expect a string + // concat without further path fields path1 = "app/"; path2 = "custom/term"; @@ -199,8 +204,7 @@ TEST(sinsp_utils_test, concatenate_paths) EXPECT_EQ("/root/c:/hello/world", res); */ } -TEST(sinsp_utils_test, sinsp_split) -{ +TEST(sinsp_utils_test, sinsp_split) { const char *in = "hello\0world\0"; size_t len = 11; std::vector split = sinsp_split({in, len}, '\0'); @@ -236,18 +240,18 @@ TEST(sinsp_utils_test, sinsp_split) split = sinsp_split(str, ','); EXPECT_EQ(split.size(), 0); - str = "A"; + str = "A"; split = sinsp_split(str, ','); EXPECT_EQ(split.size(), 1); EXPECT_EQ(split[0], "A"); - str = ","; + str = ","; split = sinsp_split(str, ','); EXPECT_EQ(split.size(), 2); EXPECT_EQ(split[0], ""); EXPECT_EQ(split[1], ""); - str = ",,"; + str = ",,"; split = sinsp_split(str, ','); EXPECT_EQ(split.size(), 3); EXPECT_EQ(split[0], ""); @@ -265,5 +269,4 @@ TEST(sinsp_utils_test, sinsp_split) EXPECT_EQ(split.size(), 2); EXPECT_EQ(split[0], ""); EXPECT_EQ(split[1], "B"); - } diff --git a/userspace/libsinsp/test/sinsp_with_test_input.cpp b/userspace/libsinsp/test/sinsp_with_test_input.cpp index e06781eb21..c5431994c3 100644 --- a/userspace/libsinsp/test/sinsp_with_test_input.cpp +++ b/userspace/libsinsp/test/sinsp_with_test_input.cpp @@ -18,23 +18,19 @@ limitations under the License. #include "sinsp_with_test_input.h" -sinsp_with_test_input::sinsp_with_test_input() -{ +sinsp_with_test_input::sinsp_with_test_input() { m_test_data.event_count = 0; m_test_data.events = nullptr; m_test_data.thread_count = 0; m_test_data.threads = nullptr; } -sinsp_with_test_input::~sinsp_with_test_input() -{ - for (auto& el : m_events) - { +sinsp_with_test_input::~sinsp_with_test_input() { + for(auto& el : m_events) { free(el); } - for (auto& el : m_async_events) - { + for(auto& el : m_async_events) { free(el); } @@ -45,8 +41,11 @@ void sinsp_with_test_input::open_inspector(sinsp_mode_t mode) { m_inspector.open_test_input(&m_test_data, mode); } -scap_evt* sinsp_with_test_input::_add_event(uint64_t ts, uint64_t tid, ppm_event_code event_type, uint32_t n, ...) -{ +scap_evt* sinsp_with_test_input::_add_event(uint64_t ts, + uint64_t tid, + ppm_event_code event_type, + uint32_t n, + ...) { va_list args; va_start(args, n); scap_evt* ret = add_event_v(ts, tid, event_type, n, args); @@ -55,10 +54,9 @@ scap_evt* sinsp_with_test_input::_add_event(uint64_t ts, uint64_t tid, ppm_event return ret; } -sinsp_evt* sinsp_with_test_input::advance_ts_get_event(uint64_t ts) -{ - for (sinsp_evt* evt = next_event(); evt != nullptr; evt = next_event()) { - if (evt->get_ts() == ts) { +sinsp_evt* sinsp_with_test_input::advance_ts_get_event(uint64_t ts) { + for(sinsp_evt* evt = next_event(); evt != nullptr; evt = next_event()) { + if(evt->get_ts() == ts) { return evt; } } @@ -67,8 +65,11 @@ sinsp_evt* sinsp_with_test_input::advance_ts_get_event(uint64_t ts) } // adds an event and advances the inspector to the new timestamp -sinsp_evt* sinsp_with_test_input::_add_event_advance_ts(uint64_t ts, uint64_t tid, ppm_event_code event_type, uint32_t n, ...) -{ +sinsp_evt* sinsp_with_test_input::_add_event_advance_ts(uint64_t ts, + uint64_t tid, + ppm_event_code event_type, + uint32_t n, + ...) { va_list args; va_start(args, n); sinsp_evt* ret = add_event_advance_ts_v(ts, tid, event_type, n, args); @@ -77,20 +78,28 @@ sinsp_evt* sinsp_with_test_input::_add_event_advance_ts(uint64_t ts, uint64_t ti return ret; } -sinsp_evt* sinsp_with_test_input::add_event_advance_ts_v(uint64_t ts, uint64_t tid, ppm_event_code event_type, uint32_t n, va_list args) -{ +sinsp_evt* sinsp_with_test_input::add_event_advance_ts_v(uint64_t ts, + uint64_t tid, + ppm_event_code event_type, + uint32_t n, + va_list args) { add_event_v(ts, tid, event_type, n, args); sinsp_evt* evt = advance_ts_get_event(ts); - if (evt != nullptr) { + if(evt != nullptr) { return evt; } - throw std::runtime_error("could not retrieve last event or internal error (event vector size: " + std::to_string(m_events.size()) + std::string(")")); + throw std::runtime_error( + "could not retrieve last event or internal error (event vector size: " + + std::to_string(m_events.size()) + std::string(")")); } // Generates and allocates a new event. -scap_evt* sinsp_with_test_input::create_event_v(uint64_t ts, uint64_t tid, ppm_event_code event_type, uint32_t n, va_list args) -{ +scap_evt* sinsp_with_test_input::create_event_v(uint64_t ts, + uint64_t tid, + ppm_event_code event_type, + uint32_t n, + va_list args) { struct scap_sized_buffer event_buf = {NULL, 0}; size_t event_size = 0; char error[SCAP_LASTERR_SIZE] = {'\0'}; @@ -129,10 +138,15 @@ scap_evt* sinsp_with_test_input::create_event_v(uint64_t ts, uint64_t tid, ppm_e return event; } -scap_evt* sinsp_with_test_input::add_event_v(uint64_t ts, uint64_t tid, ppm_event_code event_type, uint32_t n, va_list args) -{ - if (ts < m_last_recorded_timestamp) { - throw std::runtime_error("the test framework does not currently support out of order events with decreasing timestamps"); +scap_evt* sinsp_with_test_input::add_event_v(uint64_t ts, + uint64_t tid, + ppm_event_code event_type, + uint32_t n, + va_list args) { + if(ts < m_last_recorded_timestamp) { + throw std::runtime_error( + "the test framework does not currently support out of order events with decreasing " + "timestamps"); } scap_evt* event = create_event_v(ts, tid, event_type, n, args); @@ -146,8 +160,11 @@ scap_evt* sinsp_with_test_input::add_event_v(uint64_t ts, uint64_t tid, ppm_even return event; } -scap_evt* sinsp_with_test_input::add_async_event(uint64_t ts, uint64_t tid, ppm_event_code event_type, uint32_t n, ...) -{ +scap_evt* sinsp_with_test_input::add_async_event(uint64_t ts, + uint64_t tid, + ppm_event_code event_type, + uint32_t n, + ...) { va_list args; va_start(args, n); scap_evt* ret = add_async_event_v(ts, tid, event_type, n, args); @@ -156,8 +173,11 @@ scap_evt* sinsp_with_test_input::add_async_event(uint64_t ts, uint64_t tid, ppm_ return ret; } -scap_evt* sinsp_with_test_input::add_async_event_v(uint64_t ts, uint64_t tid, ppm_event_code event_type, uint32_t n, va_list args) -{ +scap_evt* sinsp_with_test_input::add_async_event_v(uint64_t ts, + uint64_t tid, + ppm_event_code event_type, + uint32_t n, + va_list args) { scap_evt* scap_event = create_event_v(ts, tid, event_type, n, args); m_async_events.push_back(scap_event); @@ -172,19 +192,23 @@ scap_evt* sinsp_with_test_input::add_async_event_v(uint64_t ts, uint64_t tid, pp //=============================== PROCESS GENERATION =========================== -// Allowed event types: PPME_SYSCALL_CLONE_20_X, PPME_SYSCALL_FORK_20_X, PPME_SYSCALL_VFORK_20_X, PPME_SYSCALL_CLONE3_X -sinsp_evt* sinsp_with_test_input::generate_clone_x_event(int64_t retval, int64_t tid, int64_t pid, int64_t ppid, uint32_t flags, - int64_t vtid, int64_t vpid, - const std::string& name, const std::vector& cgroup_vec, - ppm_event_code event_type) -{ - if(vtid == DEFAULT_VALUE) - { +// Allowed event types: PPME_SYSCALL_CLONE_20_X, PPME_SYSCALL_FORK_20_X, PPME_SYSCALL_VFORK_20_X, +// PPME_SYSCALL_CLONE3_X +sinsp_evt* sinsp_with_test_input::generate_clone_x_event(int64_t retval, + int64_t tid, + int64_t pid, + int64_t ppid, + uint32_t flags, + int64_t vtid, + int64_t vpid, + const std::string& name, + const std::vector& cgroup_vec, + ppm_event_code event_type) { + if(vtid == DEFAULT_VALUE) { vtid = tid; } - if(vpid == DEFAULT_VALUE) - { + if(vpid == DEFAULT_VALUE) { vpid = pid; } @@ -197,112 +221,164 @@ sinsp_evt* sinsp_with_test_input::generate_clone_x_event(int64_t retval, int64_t std::string cgroupsv = test_utils::to_null_delimited(cgroup_vec); // If the cgroup vector is not empty overwrite it - if(!cgroup_vec.empty()) - { + if(!cgroup_vec.empty()) { cgroup_byte_buf = scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}; } - return add_event_advance_ts(increasing_ts(), tid, event_type, 20, retval, name.c_str(), empty_bytebuf, - tid, pid, ppid, "", not_relevant_64, not_relevant_64, not_relevant_64, - not_relevant_32, not_relevant_32, not_relevant_32, name.c_str(), - cgroup_byte_buf, flags, not_relevant_32, not_relevant_32, vtid, vpid); -} - -sinsp_evt* sinsp_with_test_input::generate_execve_enter_and_exit_event(int64_t retval, int64_t old_tid, int64_t new_tid, int64_t pid, - int64_t ppid, const std::string& pathname, - const std::string& comm, - const std::string& resolved_kernel_path, - const std::vector& cgroup_vec) -{ + return add_event_advance_ts(increasing_ts(), + tid, + event_type, + 20, + retval, + name.c_str(), + empty_bytebuf, + tid, + pid, + ppid, + "", + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_32, + not_relevant_32, + not_relevant_32, + name.c_str(), + cgroup_byte_buf, + flags, + not_relevant_32, + not_relevant_32, + vtid, + vpid); +} + +sinsp_evt* sinsp_with_test_input::generate_execve_enter_and_exit_event( + int64_t retval, + int64_t old_tid, + int64_t new_tid, + int64_t pid, + int64_t ppid, + const std::string& pathname, + const std::string& comm, + const std::string& resolved_kernel_path, + const std::vector& cgroup_vec) { // Scaffolding needed to call the PPME_SYSCALL_EXECVE_19_X uint64_t not_relevant_64 = 0; uint32_t not_relevant_32 = 0; - scap_const_sized_buffer empty_bytebuf = { /*.buf =*/nullptr, /*.size =*/0 }; + scap_const_sized_buffer empty_bytebuf = {/*.buf =*/nullptr, /*.size =*/0}; scap_const_sized_buffer cgroup_byte_buf = empty_bytebuf; std::string cgroupsv = test_utils::to_null_delimited(cgroup_vec); // If the cgroup vector is not empty overwrite it - if(!cgroup_vec.empty()) - { + if(!cgroup_vec.empty()) { cgroup_byte_buf = scap_const_sized_buffer{cgroupsv.data(), cgroupsv.size()}; } add_event_advance_ts(increasing_ts(), old_tid, PPME_SYSCALL_EXECVE_19_E, 1, pathname.c_str()); // we have an `old_tid` and a `new_tid` because if a secondary thread calls the execve // the thread leader will take control so the `tid` between enter and exit event will change - return add_event_advance_ts( - increasing_ts(), new_tid, PPME_SYSCALL_EXECVE_19_X, 28, retval, pathname.c_str(), empty_bytebuf, - new_tid, pid, ppid, "", not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_32, - not_relevant_32, not_relevant_32, comm.c_str(), cgroup_byte_buf, empty_bytebuf, not_relevant_32, - not_relevant_64, not_relevant_32, not_relevant_32, not_relevant_64, not_relevant_64, - not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_64, not_relevant_32, - resolved_kernel_path.c_str()); -} - -void sinsp_with_test_input::remove_thread(int64_t tid_to_remove, int64_t reaper_tid) -{ + return add_event_advance_ts(increasing_ts(), + new_tid, + PPME_SYSCALL_EXECVE_19_X, + 28, + retval, + pathname.c_str(), + empty_bytebuf, + new_tid, + pid, + ppid, + "", + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_32, + not_relevant_32, + not_relevant_32, + comm.c_str(), + cgroup_byte_buf, + empty_bytebuf, + not_relevant_32, + not_relevant_64, + not_relevant_32, + not_relevant_32, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_64, + not_relevant_32, + resolved_kernel_path.c_str()); +} + +void sinsp_with_test_input::remove_thread(int64_t tid_to_remove, int64_t reaper_tid) { generate_proc_exit_event(tid_to_remove, reaper_tid); // Generate a random event on init to trigger the removal after proc exit generate_random_event(); } -sinsp_evt* sinsp_with_test_input::generate_proc_exit_event(int64_t tid_to_remove, int64_t reaper_tid) -{ +sinsp_evt* sinsp_with_test_input::generate_proc_exit_event(int64_t tid_to_remove, + int64_t reaper_tid) { // Scaffolding needed to call the PPME_PROCEXIT_1_E int64_t not_relevant_64 = 0; uint8_t not_relevant_8 = 0; - return add_event_advance_ts(increasing_ts(), tid_to_remove, PPME_PROCEXIT_1_E, 5, not_relevant_64, not_relevant_64, not_relevant_8, not_relevant_8, reaper_tid); + return add_event_advance_ts(increasing_ts(), + tid_to_remove, + PPME_PROCEXIT_1_E, + 5, + not_relevant_64, + not_relevant_64, + not_relevant_8, + not_relevant_8, + reaper_tid); } -sinsp_evt* sinsp_with_test_input::generate_random_event(int64_t tid_caller) -{ +sinsp_evt* sinsp_with_test_input::generate_random_event(int64_t tid_caller) { // Generate a random failed event. Useful when we want to trigger some actions on an event // and we don't care about the event chosen. return add_event_advance_ts(increasing_ts(), tid_caller, PPME_SYSCALL_GETCWD_E, 0); } -sinsp_evt* sinsp_with_test_input::generate_getcwd_failed_entry_event(int64_t tid_caller) -{ +sinsp_evt* sinsp_with_test_input::generate_getcwd_failed_entry_event(int64_t tid_caller) { int64_t err = -1; std::string path = "/test/dir"; - return add_event_advance_ts(increasing_ts(), tid_caller, PPME_SYSCALL_GETCWD_X, 2, err, path.c_str()); + return add_event_advance_ts(increasing_ts(), + tid_caller, + PPME_SYSCALL_GETCWD_X, + 2, + err, + path.c_str()); } //=============================== PROCESS GENERATION =========================== -void sinsp_with_test_input::add_thread(const scap_threadinfo& tinfo, const std::vector& fdinfos) -{ +void sinsp_with_test_input::add_thread(const scap_threadinfo& tinfo, + const std::vector& fdinfos) { m_threads.push_back(tinfo); m_test_data.threads = m_threads.data(); m_test_data.thread_count = m_threads.size(); m_fdinfos.push_back(fdinfos); - scap_test_fdinfo_data fdinfo_descriptor = { - /*.fdinfos =*/ m_fdinfos.back().data(), - /*.fdinfo_count =*/ m_fdinfos.back().size() - }; + scap_test_fdinfo_data fdinfo_descriptor = {/*.fdinfos =*/m_fdinfos.back().data(), + /*.fdinfo_count =*/m_fdinfos.back().size()}; m_test_fdinfo_data.push_back(fdinfo_descriptor); m_test_data.fdinfo_data = m_test_fdinfo_data.data(); } -void sinsp_with_test_input::set_threadinfo_last_access_time(int64_t tid, uint64_t access_time_ns) -{ +void sinsp_with_test_input::set_threadinfo_last_access_time(int64_t tid, uint64_t access_time_ns) { auto tinfo = m_inspector.get_thread_ref(tid, false).get(); - if(tinfo != nullptr) - { + if(tinfo != nullptr) { tinfo->m_lastaccess_ts = access_time_ns; - } - else - { - throw sinsp_exception("There is no thread info associated with tid: " + std::to_string(tid)); + } else { + throw sinsp_exception("There is no thread info associated with tid: " + + std::to_string(tid)); } } // Remove all threads with `tinfo->m_lastaccess_ts` minor than `m_lastevent_ts - thread_timeout` -void sinsp_with_test_input::remove_inactive_threads(uint64_t m_lastevent_ts, uint64_t thread_timeout) -{ +void sinsp_with_test_input::remove_inactive_threads(uint64_t m_lastevent_ts, + uint64_t thread_timeout) { // We need to set these 2 variables to enable the remove_inactive_logic m_inspector.m_thread_manager->set_last_flush_time_ns(1); m_inspector.m_threads_purging_scan_time_ns = 2; @@ -313,19 +389,41 @@ void sinsp_with_test_input::remove_inactive_threads(uint64_t m_lastevent_ts, uin } // static -scap_threadinfo sinsp_with_test_input::create_threadinfo( - uint64_t tid, uint64_t pid, uint64_t ptid, uint64_t vpgid, int64_t vtid, int64_t vpid, - const std::string& comm, const std::string& exe, const std::string& exepath, - uint64_t clone_ts, uint32_t uid, uint32_t gid, - const std::vector& args, uint64_t sid, - const std::vector& env, const std::string& cwd, - int64_t fdlimit, uint32_t flags, bool exe_writable, - uint64_t cap_permitted, uint64_t cap_inheritable, uint64_t cap_effective, - uint32_t vmsize_kb, uint32_t vmrss_kb, uint32_t vmswap_kb, uint64_t pfmajor, uint64_t pfminor, - const std::vector& cgroups, const std::string& root, - int filtered_out, uint32_t tty, uint32_t loginuid, bool exe_upper_layer, bool exe_lower_layer, - bool exe_from_memfd) -{ +scap_threadinfo sinsp_with_test_input::create_threadinfo(uint64_t tid, + uint64_t pid, + uint64_t ptid, + uint64_t vpgid, + int64_t vtid, + int64_t vpid, + const std::string& comm, + const std::string& exe, + const std::string& exepath, + uint64_t clone_ts, + uint32_t uid, + uint32_t gid, + const std::vector& args, + uint64_t sid, + const std::vector& env, + const std::string& cwd, + int64_t fdlimit, + uint32_t flags, + bool exe_writable, + uint64_t cap_permitted, + uint64_t cap_inheritable, + uint64_t cap_effective, + uint32_t vmsize_kb, + uint32_t vmrss_kb, + uint32_t vmswap_kb, + uint64_t pfmajor, + uint64_t pfminor, + const std::vector& cgroups, + const std::string& root, + int filtered_out, + uint32_t tty, + uint32_t loginuid, + bool exe_upper_layer, + bool exe_lower_layer, + bool exe_from_memfd) { scap_threadinfo tinfo = {}; tinfo.tid = tid; @@ -357,20 +455,17 @@ scap_threadinfo sinsp_with_test_input::create_threadinfo( tinfo.exe_from_memfd = exe_from_memfd; std::string argsv; - if (!args.empty()) - { + if(!args.empty()) { argsv = test_utils::to_null_delimited(args); } std::string envv; - if (!env.empty()) - { + if(!env.empty()) { envv = test_utils::to_null_delimited(env); } std::string cgroupsv; - if (!cgroups.empty()) - { + if(!cgroups.empty()) { cgroupsv = test_utils::to_null_delimited(cgroups); } @@ -389,10 +484,24 @@ scap_threadinfo sinsp_with_test_input::create_threadinfo( return tinfo; } -void sinsp_with_test_input::add_default_init_thread() -{ - std::vector env = { "TEST_ENV_PARENT_LINEAGE=secret", "HOME=/home/user/parent" }; - scap_threadinfo tinfo = create_threadinfo(1, 1, 0, 1, 1, 1, "init", "/sbin/init", "/sbin/init", increasing_ts(), 0, 0, {}, 0, env, "/root/"); +void sinsp_with_test_input::add_default_init_thread() { + std::vector env = {"TEST_ENV_PARENT_LINEAGE=secret", "HOME=/home/user/parent"}; + scap_threadinfo tinfo = create_threadinfo(1, + 1, + 0, + 1, + 1, + 1, + "init", + "/sbin/init", + "/sbin/init", + increasing_ts(), + 0, + 0, + {}, + 0, + env, + "/root/"); std::vector fdinfos; scap_fdinfo fdinfo; @@ -410,101 +519,120 @@ void sinsp_with_test_input::add_default_init_thread() add_thread(tinfo, fdinfos); } -void sinsp_with_test_input::add_simple_thread(int64_t tid, int64_t pid, int64_t ptid, const std::string& comm) -{ - scap_threadinfo tinfo = create_threadinfo(tid, pid, ptid, tid, tid, pid, comm, "/sbin/init", "/sbin/init", increasing_ts(), 0, 0, {}, 0, {}, "/root/"); +void sinsp_with_test_input::add_simple_thread(int64_t tid, + int64_t pid, + int64_t ptid, + const std::string& comm) { + scap_threadinfo tinfo = create_threadinfo(tid, + pid, + ptid, + tid, + tid, + pid, + comm, + "/sbin/init", + "/sbin/init", + increasing_ts(), + 0, + 0, + {}, + 0, + {}, + "/root/"); add_thread(tinfo, {}); } -uint64_t sinsp_with_test_input::increasing_ts() -{ +uint64_t sinsp_with_test_input::increasing_ts() { uint64_t ret = m_test_timestamp; - m_test_timestamp += 10000000; // 10 msec increment + m_test_timestamp += 10000000; // 10 msec increment return ret; } // Return true if `field_name` exists in the filtercheck list. // The field value could also be NULL, but in this method, we are not interested in the value. -bool sinsp_with_test_input::field_exists(sinsp_evt* evt, std::string_view field_name) -{ +bool sinsp_with_test_input::field_exists(sinsp_evt* evt, std::string_view field_name) { return field_exists(evt, field_name, m_default_filterlist); } -bool sinsp_with_test_input::field_exists(sinsp_evt* evt, std::string_view field_name, filter_check_list& flist) -{ - if (evt == nullptr) { +bool sinsp_with_test_input::field_exists(sinsp_evt* evt, + std::string_view field_name, + filter_check_list& flist) { + if(evt == nullptr) { throw sinsp_exception("The event class is NULL"); } auto new_fl = flist.new_filter_check_from_fldname(field_name, &m_inspector, false); - if(new_fl != nullptr) - { + if(new_fl != nullptr) { // if we can create a filter check it means that the field exists return true; - } - else - { + } else { return false; } } // Return true if `field_name` value is not NULL for this event. -bool sinsp_with_test_input::field_has_value(sinsp_evt* evt, std::string_view field_name) -{ +bool sinsp_with_test_input::field_has_value(sinsp_evt* evt, std::string_view field_name) { return field_has_value(evt, field_name, m_default_filterlist); } -bool sinsp_with_test_input::field_has_value(sinsp_evt* evt, std::string_view field_name, filter_check_list& flist) -{ - if (evt == nullptr) { +bool sinsp_with_test_input::field_has_value(sinsp_evt* evt, + std::string_view field_name, + filter_check_list& flist) { + if(evt == nullptr) { throw sinsp_exception("The event class is NULL"); } - std::unique_ptr chk(flist.new_filter_check_from_fldname(field_name, &m_inspector, false)); - if(chk == nullptr) - { + std::unique_ptr chk( + flist.new_filter_check_from_fldname(field_name, &m_inspector, false)); + if(chk == nullptr) { throw sinsp_exception("The field " + std::string(field_name) + " is not a valid field."); } - // we created a filter check starting from the field name so if we arrive here we will find it for sure + // we created a filter check starting from the field name so if we arrive here we will find it + // for sure chk->parse_field_name(field_name, true, false); std::vector values; return chk->extract(evt, values); } -std::string sinsp_with_test_input::get_field_as_string(sinsp_evt* evt, std::string_view field_name) -{ +std::string sinsp_with_test_input::get_field_as_string(sinsp_evt* evt, + std::string_view field_name) { return get_field_as_string(evt, field_name, m_default_filterlist); } -std::string sinsp_with_test_input::get_field_as_string(sinsp_evt* evt, std::string_view field_name, filter_check_list& flist) -{ - if (evt == nullptr) { +std::string sinsp_with_test_input::get_field_as_string(sinsp_evt* evt, + std::string_view field_name, + filter_check_list& flist) { + if(evt == nullptr) { throw sinsp_exception("The event class is NULL"); } - std::unique_ptr chk(flist.new_filter_check_from_fldname(field_name, &m_inspector, false)); - if(chk == nullptr) - { + std::unique_ptr chk( + flist.new_filter_check_from_fldname(field_name, &m_inspector, false)); + if(chk == nullptr) { throw sinsp_exception("The field " + std::string(field_name) + " is not a valid field."); } - // we created a filter check starting from the field name so if we arrive here we will find it for sure + // we created a filter check starting from the field name so if we arrive here we will find it + // for sure chk->parse_field_name(field_name, true, false); const char* result = chk->tostring(evt); - if (result == nullptr) { + if(result == nullptr) { throw sinsp_exception("The field " + std::string(field_name) + " is NULL"); } return result; } -bool sinsp_with_test_input::eval_filter(sinsp_evt* evt, std::string_view filter_str, std::shared_ptr cachef) -{ +bool sinsp_with_test_input::eval_filter(sinsp_evt* evt, + std::string_view filter_str, + std::shared_ptr cachef) { return eval_filter(evt, filter_str, m_default_filterlist, cachef); } -bool sinsp_with_test_input::eval_filter(sinsp_evt* evt, std::string_view filter_str, filter_check_list &flist, std::shared_ptr cachef) -{ +bool sinsp_with_test_input::eval_filter(sinsp_evt* evt, + std::string_view filter_str, + filter_check_list& flist, + std::shared_ptr cachef) { auto factory = std::make_shared(&m_inspector, flist); sinsp_filter_compiler compiler(factory, std::string(filter_str), cachef); @@ -513,35 +641,31 @@ bool sinsp_with_test_input::eval_filter(sinsp_evt* evt, std::string_view filter_ return filter->run(evt); } -bool sinsp_with_test_input::eval_filter(sinsp_evt* evt, std::string_view filter_str, std::shared_ptr filterf, std::shared_ptr cachef) -{ +bool sinsp_with_test_input::eval_filter(sinsp_evt* evt, + std::string_view filter_str, + std::shared_ptr filterf, + std::shared_ptr cachef) { sinsp_filter_compiler compiler(filterf, std::string(filter_str), cachef); auto filter = compiler.compile(); return filter->run(evt); } -bool sinsp_with_test_input::filter_compiles(std::string_view filter_str) -{ +bool sinsp_with_test_input::filter_compiles(std::string_view filter_str) { return filter_compiles(filter_str, m_default_filterlist); } -bool sinsp_with_test_input::filter_compiles(std::string_view filter_str, filter_check_list &flist) -{ +bool sinsp_with_test_input::filter_compiles(std::string_view filter_str, filter_check_list& flist) { auto factory = std::make_shared(&m_inspector, flist); sinsp_filter_compiler compiler(factory, std::string(filter_str)); - try - { + try { auto f = compiler.compile(); return true; - } - catch(const sinsp_exception& e) - { + } catch(const sinsp_exception& e) { return false; } } -sinsp_evt* sinsp_with_test_input::next_event() -{ +sinsp_evt* sinsp_with_test_input::next_event() { sinsp_evt* evt; auto result = m_inspector.next(&evt); return result == SCAP_SUCCESS ? evt : nullptr; diff --git a/userspace/libsinsp/test/sinsp_with_test_input.h b/userspace/libsinsp/test/sinsp_with_test_input.h index fad9551355..4d9efb99c4 100644 --- a/userspace/libsinsp/test/sinsp_with_test_input.h +++ b/userspace/libsinsp/test/sinsp_with_test_input.h @@ -34,8 +34,7 @@ limitations under the License. #define INIT_PID INIT_TID #define INIT_PTID 0 -class sinsp_with_test_input : public ::testing::Test -{ +class sinsp_with_test_input : public ::testing::Test { protected: sinsp_with_test_input(); ~sinsp_with_test_input(); @@ -44,128 +43,150 @@ class sinsp_with_test_input : public ::testing::Test void open_inspector(sinsp_mode_t mode = SINSP_MODE_TEST); - template - void _check_event_params(const char *filename, int lineno, ppm_event_code event_type, uint32_t n, Ts && ... inputs) - { + template + void _check_event_params(const char* filename, + int lineno, + ppm_event_code event_type, + uint32_t n, + Ts&&... inputs) { uint32_t i = 0; std::string prefix = std::string(filename) + ":" + std::to_string(lineno) + " | "; // This check is mostly needed to avoid the unused warning when n is 0 // and therefore the lambda below would never run, leaving us with event_type unused. - if (event_type < 0 || event_type > PPM_EVENT_MAX) - { - throw std::runtime_error(prefix+"wrong event type: " + std::to_string(event_type)); + if(event_type < 0 || event_type > PPM_EVENT_MAX) { + throw std::runtime_error(prefix + "wrong event type: " + std::to_string(event_type)); } - ([&] - { - const struct ppm_event_info *event_info = &scap_get_event_info_table()[event_type]; - const struct ppm_param_info *pi = &event_info->params[i]; - switch(pi->type) - { - case PT_INT8: - case PT_UINT8: - case PT_FLAGS8: - case PT_SIGTYPE: - case PT_L4PROTO: - case PT_SOCKFAMILY: - case PT_ENUMFLAGS8: - if (sizeof(inputs) != 1) - { - throw std::runtime_error(prefix+"wrong sized argument " + - std::to_string(i) + " passed; expected: 1B, received: " + - std::to_string(sizeof(inputs)) + "B"); - } - break; - - case PT_INT16: - case PT_UINT16: - case PT_SYSCALLID: - case PT_PORT: - case PT_FLAGS16: - case PT_ENUMFLAGS16: - if (sizeof(inputs) != 2) - { - throw std::runtime_error(prefix+"wrong sized argument " + - std::to_string(i) + " passed; expected: 2B, received: " + - std::to_string(sizeof(inputs)) + "B"); - } - break; - - case PT_INT32: - case PT_UINT32: - case PT_BOOL: - case PT_IPV4ADDR: - case PT_UID: - case PT_GID: - case PT_FLAGS32: - case PT_SIGSET: - case PT_MODE: - case PT_ENUMFLAGS32: - if (sizeof(inputs) != 4) - { - throw std::runtime_error(prefix+"wrong sized argument " + - std::to_string(i) + " passed; expected: 4B, received: " + - std::to_string(sizeof(inputs)) + "B"); - } - break; - - case PT_INT64: - case PT_UINT64: - case PT_ERRNO: - case PT_FD: - case PT_PID: - case PT_RELTIME: - case PT_ABSTIME: - case PT_DOUBLE: - if (sizeof(inputs) != 8) - { - throw std::runtime_error(prefix+"wrong sized argument " + - std::to_string(i) + " passed; expected: 8B, received: " + - std::to_string(sizeof(inputs)) + "B"); - } - break; - default: - // we only assert integer-like arguments that are the most common failures. - break; - } - i++; - } (), ...); - if (i != n) - { - throw std::runtime_error(prefix+"wrong number of arguments: specified " + - std::to_string(n) + " but passed: " + std::to_string(i)); + ( + [&] { + const struct ppm_event_info* event_info = + &scap_get_event_info_table()[event_type]; + const struct ppm_param_info* pi = &event_info->params[i]; + switch(pi->type) { + case PT_INT8: + case PT_UINT8: + case PT_FLAGS8: + case PT_SIGTYPE: + case PT_L4PROTO: + case PT_SOCKFAMILY: + case PT_ENUMFLAGS8: + if(sizeof(inputs) != 1) { + throw std::runtime_error(prefix + "wrong sized argument " + + std::to_string(i) + + " passed; expected: 1B, received: " + + std::to_string(sizeof(inputs)) + "B"); + } + break; + + case PT_INT16: + case PT_UINT16: + case PT_SYSCALLID: + case PT_PORT: + case PT_FLAGS16: + case PT_ENUMFLAGS16: + if(sizeof(inputs) != 2) { + throw std::runtime_error(prefix + "wrong sized argument " + + std::to_string(i) + + " passed; expected: 2B, received: " + + std::to_string(sizeof(inputs)) + "B"); + } + break; + + case PT_INT32: + case PT_UINT32: + case PT_BOOL: + case PT_IPV4ADDR: + case PT_UID: + case PT_GID: + case PT_FLAGS32: + case PT_SIGSET: + case PT_MODE: + case PT_ENUMFLAGS32: + if(sizeof(inputs) != 4) { + throw std::runtime_error(prefix + "wrong sized argument " + + std::to_string(i) + + " passed; expected: 4B, received: " + + std::to_string(sizeof(inputs)) + "B"); + } + break; + + case PT_INT64: + case PT_UINT64: + case PT_ERRNO: + case PT_FD: + case PT_PID: + case PT_RELTIME: + case PT_ABSTIME: + case PT_DOUBLE: + if(sizeof(inputs) != 8) { + throw std::runtime_error(prefix + "wrong sized argument " + + std::to_string(i) + + " passed; expected: 8B, received: " + + std::to_string(sizeof(inputs)) + "B"); + } + break; + default: + // we only assert integer-like arguments that are the most common failures. + break; + } + i++; + }(), + ...); + if(i != n) { + throw std::runtime_error(prefix + "wrong number of arguments: specified " + + std::to_string(n) + " but passed: " + std::to_string(i)); } } -#define add_event(ts, tid, code, n, ...) \ - _add_event(ts, tid, code, n, ##__VA_ARGS__); \ - _check_event_params(__FILE__, __LINE__, code, n, ##__VA_ARGS__) +#define add_event(ts, tid, code, n, ...) \ + _add_event(ts, tid, code, n, ##__VA_ARGS__); \ + _check_event_params(__FILE__, __LINE__, code, n, ##__VA_ARGS__) scap_evt* _add_event(uint64_t ts, uint64_t tid, ppm_event_code, uint32_t n, ...); sinsp_evt* advance_ts_get_event(uint64_t ts); -#define add_event_advance_ts(ts, tid, code, n, ...) \ - _add_event_advance_ts(ts, tid, code, n, ##__VA_ARGS__); \ - _check_event_params(__FILE__, __LINE__, code, n, ##__VA_ARGS__) +#define add_event_advance_ts(ts, tid, code, n, ...) \ + _add_event_advance_ts(ts, tid, code, n, ##__VA_ARGS__); \ + _check_event_params(__FILE__, __LINE__, code, n, ##__VA_ARGS__) sinsp_evt* _add_event_advance_ts(uint64_t ts, uint64_t tid, ppm_event_code, uint32_t n, ...); - sinsp_evt* add_event_advance_ts_v(uint64_t ts, uint64_t tid, ppm_event_code, uint32_t n, va_list args); + sinsp_evt* add_event_advance_ts_v(uint64_t ts, + uint64_t tid, + ppm_event_code, + uint32_t n, + va_list args); scap_evt* create_event_v(uint64_t ts, uint64_t tid, ppm_event_code, uint32_t n, va_list args); scap_evt* add_event_v(uint64_t ts, uint64_t tid, ppm_event_code, uint32_t n, va_list args); scap_evt* add_async_event(uint64_t ts, uint64_t tid, ppm_event_code, uint32_t n, ...); - scap_evt* add_async_event_v(uint64_t ts, uint64_t tid, ppm_event_code, uint32_t n, va_list args); + scap_evt* add_async_event_v(uint64_t ts, + uint64_t tid, + ppm_event_code, + uint32_t n, + va_list args); //=============================== PROCESS GENERATION =========================== - // Allowed event types: PPME_SYSCALL_CLONE_20_X, PPME_SYSCALL_FORK_20_X, PPME_SYSCALL_VFORK_20_X, PPME_SYSCALL_CLONE3_X - sinsp_evt* generate_clone_x_event(int64_t retval, int64_t tid, int64_t pid, int64_t ppid, uint32_t flags = 0, - int64_t vtid = DEFAULT_VALUE, int64_t vpid = DEFAULT_VALUE, - const std::string& name = "bash", const std::vector& cgroup_vec = {}, - ppm_event_code event_type = PPME_SYSCALL_CLONE_20_X); - sinsp_evt* generate_execve_enter_and_exit_event(int64_t retval, int64_t old_tid, int64_t new_tid, int64_t pid, - int64_t ppid, const std::string& pathname = "/bin/test-exe", - const std::string& comm = "test-exe", - const std::string& resolved_kernel_path = "/bin/test-exe", - const std::vector& cgroup_vec = {}); + // Allowed event types: PPME_SYSCALL_CLONE_20_X, PPME_SYSCALL_FORK_20_X, + // PPME_SYSCALL_VFORK_20_X, PPME_SYSCALL_CLONE3_X + sinsp_evt* generate_clone_x_event(int64_t retval, + int64_t tid, + int64_t pid, + int64_t ppid, + uint32_t flags = 0, + int64_t vtid = DEFAULT_VALUE, + int64_t vpid = DEFAULT_VALUE, + const std::string& name = "bash", + const std::vector& cgroup_vec = {}, + ppm_event_code event_type = PPME_SYSCALL_CLONE_20_X); + sinsp_evt* generate_execve_enter_and_exit_event( + int64_t retval, + int64_t old_tid, + int64_t new_tid, + int64_t pid, + int64_t ppid, + const std::string& pathname = "/bin/test-exe", + const std::string& comm = "test-exe", + const std::string& resolved_kernel_path = "/bin/test-exe", + const std::vector& cgroup_vec = {}); void remove_thread(int64_t tid_to_remove, int64_t reaper_tid); sinsp_evt* generate_proc_exit_event(int64_t tid_to_remove, int64_t reaper_tid); sinsp_evt* generate_random_event(int64_t tid_caller = INIT_TID); @@ -177,20 +198,47 @@ class sinsp_with_test_input : public ::testing::Test void set_threadinfo_last_access_time(int64_t tid, uint64_t access_time_ns); void remove_inactive_threads(uint64_t m_lastevent_ts, uint64_t thread_timeout); - static scap_threadinfo create_threadinfo( - uint64_t tid, uint64_t pid, uint64_t ptid, uint64_t vpgid, int64_t vtid, int64_t vpid, - const std::string& comm, const std::string& exe, const std::string& exepath, - uint64_t clone_ts, uint32_t uid, uint32_t gid, - const std::vector& args, uint64_t sid, const std::vector& env, - const std::string& cwd, - int64_t fdlimit = 0x100000, uint32_t flags = 0, bool exe_writable = true, - uint64_t cap_permitted = 0x1ffffffffff, uint64_t cap_inheritable = 0, uint64_t cap_effective = 0x1ffffffffff, - uint32_t vmsize_kb = 10000, uint32_t vmrss_kb = 100, uint32_t vmswap_kb = 0, uint64_t pfmajor = 222, uint64_t pfminor = 22, - const std::vector& cgroups = {}, const std::string& root = "/", - int filtered_out = 0, uint32_t tty = 0, uint32_t loginuid = UINT32_MAX, bool exe_upper_layer = false, bool exe_lower_layer = false, bool exe_from_memfd = false); + static scap_threadinfo create_threadinfo(uint64_t tid, + uint64_t pid, + uint64_t ptid, + uint64_t vpgid, + int64_t vtid, + int64_t vpid, + const std::string& comm, + const std::string& exe, + const std::string& exepath, + uint64_t clone_ts, + uint32_t uid, + uint32_t gid, + const std::vector& args, + uint64_t sid, + const std::vector& env, + const std::string& cwd, + int64_t fdlimit = 0x100000, + uint32_t flags = 0, + bool exe_writable = true, + uint64_t cap_permitted = 0x1ffffffffff, + uint64_t cap_inheritable = 0, + uint64_t cap_effective = 0x1ffffffffff, + uint32_t vmsize_kb = 10000, + uint32_t vmrss_kb = 100, + uint32_t vmswap_kb = 0, + uint64_t pfmajor = 222, + uint64_t pfminor = 22, + const std::vector& cgroups = {}, + const std::string& root = "/", + int filtered_out = 0, + uint32_t tty = 0, + uint32_t loginuid = UINT32_MAX, + bool exe_upper_layer = false, + bool exe_lower_layer = false, + bool exe_from_memfd = false); void add_default_init_thread(); - void add_simple_thread(int64_t tid, int64_t pid, int64_t ptid, const std::string& comm = "random"); + void add_simple_thread(int64_t tid, + int64_t pid, + int64_t ptid, + const std::string& comm = "random"); uint64_t increasing_ts(); bool field_exists(sinsp_evt*, std::string_view field_name); @@ -199,9 +247,17 @@ class sinsp_with_test_input : public ::testing::Test bool field_has_value(sinsp_evt*, std::string_view field_name, filter_check_list&); std::string get_field_as_string(sinsp_evt*, std::string_view field_name); std::string get_field_as_string(sinsp_evt*, std::string_view field_name, filter_check_list&); - bool eval_filter(sinsp_evt* evt, std::string_view filter_str, std::shared_ptr cachef = nullptr); - bool eval_filter(sinsp_evt* evt, std::string_view filter_str, filter_check_list&, std::shared_ptr cachef = nullptr); - bool eval_filter(sinsp_evt* evt, std::string_view filter_str, std::shared_ptr filterf, std::shared_ptr cachef = nullptr); + bool eval_filter(sinsp_evt* evt, + std::string_view filter_str, + std::shared_ptr cachef = nullptr); + bool eval_filter(sinsp_evt* evt, + std::string_view filter_str, + filter_check_list&, + std::shared_ptr cachef = nullptr); + bool eval_filter(sinsp_evt* evt, + std::string_view filter_str, + std::shared_ptr filterf, + std::shared_ptr cachef = nullptr); bool filter_compiles(std::string_view filter_str); bool filter_compiles(std::string_view filter_str, filter_check_list&); diff --git a/userspace/libsinsp/test/state.ut.cpp b/userspace/libsinsp/test/state.ut.cpp index 8d1fdc6d0f..bb91a6a436 100644 --- a/userspace/libsinsp/test/state.ut.cpp +++ b/userspace/libsinsp/test/state.ut.cpp @@ -22,452 +22,427 @@ limitations under the License. #include #include -TEST(typeinfo, basic_tests) -{ - struct some_unknown_type { }; - ASSERT_ANY_THROW(libsinsp::state::typeinfo::of()); - ASSERT_EQ(libsinsp::state::typeinfo::of().size(), sizeof(std::string)); - ASSERT_EQ(libsinsp::state::typeinfo::of(), libsinsp::state::typeinfo::of()); +TEST(typeinfo, basic_tests) { + struct some_unknown_type {}; + ASSERT_ANY_THROW(libsinsp::state::typeinfo::of()); + ASSERT_EQ(libsinsp::state::typeinfo::of().size(), sizeof(std::string)); + ASSERT_EQ(libsinsp::state::typeinfo::of(), + libsinsp::state::typeinfo::of()); } -TEST(static_struct, defs_and_access) -{ - struct err_multidef_struct: public libsinsp::state::static_struct - { - libsinsp::state::static_struct::field_infos static_fields() const override - { - libsinsp::state::static_struct::field_infos ret; - define_static_field(ret, this, m_num, "num"); - define_static_field(ret, this, m_num, "num"); - return ret; - } - - uint32_t m_num{0}; - }; - - class sample_struct: public libsinsp::state::static_struct - { - public: - libsinsp::state::static_struct::field_infos static_fields() const override - { - libsinsp::state::static_struct::field_infos ret; - define_static_field(ret, this, m_num, "num"); - define_static_field(ret, this, m_str, "str", true); - return ret; - } - - uint32_t get_num() const { return m_num; } - void set_num(uint32_t v) { m_num = v; } - const std::string& get_str() const { return m_str; } - void set_str(const std::string& v) { m_str = v; } - - private: - uint32_t m_num{0}; - std::string m_str; - }; - - struct sample_struct2: public libsinsp::state::static_struct - { - public: - libsinsp::state::static_struct::field_infos static_fields() const override - { - libsinsp::state::static_struct::field_infos ret; - define_static_field(ret, this, m_num, "num"); - return ret; - } - - uint32_t m_num{0}; - }; - - // test errors - ASSERT_ANY_THROW(err_multidef_struct().static_fields()); - - sample_struct s; - const auto& fields = s.static_fields(); - - // check field definitions - auto field_num = fields.find("num"); - auto field_str = fields.find("str"); - ASSERT_EQ(fields.size(), 2); - ASSERT_EQ(fields, sample_struct().static_fields()); - - ASSERT_NE(field_num, fields.end()); - ASSERT_EQ(field_num->second.name(), "num"); - ASSERT_EQ(field_num->second.readonly(), false); - ASSERT_EQ(field_num->second.info(), libsinsp::state::typeinfo::of()); - - ASSERT_NE(field_str, fields.end()); - ASSERT_EQ(field_str->second.name(), "str"); - ASSERT_EQ(field_str->second.readonly(), true); - ASSERT_EQ(field_str->second.info(), libsinsp::state::typeinfo::of()); - - // check field access - auto acc_num = field_num->second.new_accessor(); - auto acc_str = field_str->second.new_accessor(); - ASSERT_ANY_THROW(field_num->second.new_accessor()); - ASSERT_ANY_THROW(field_str->second.new_accessor()); - - ASSERT_EQ(s.get_num(), 0); - ASSERT_EQ(s.get_static_field(acc_num), 0); - s.set_num(5); - ASSERT_EQ(s.get_num(), 5); - uint32_t u32tmp = 0; - s.get_static_field(acc_num, u32tmp); - ASSERT_EQ(u32tmp, 5); - s.set_static_field(acc_num, (uint32_t) 6); - ASSERT_EQ(s.get_num(), 6); - ASSERT_EQ(s.get_static_field(acc_num), 6); - - std::string str = ""; - ASSERT_EQ(s.get_str(), str); - ASSERT_EQ(s.get_static_field(acc_str), str); - str = "hello"; - s.set_str("hello"); - ASSERT_EQ(s.get_str(), str); - s.get_static_field(acc_str, str); - ASSERT_EQ(str, "hello"); - ASSERT_ANY_THROW(s.set_static_field(acc_str, "hello")); // readonly - - const char* cstr = "sample"; - s.set_str(""); - s.get_static_field(acc_str, cstr); - ASSERT_EQ(strcmp(cstr, ""), 0); - s.set_str("hello"); - s.get_static_field(acc_str, cstr); - ASSERT_EQ(strcmp(cstr, "hello"), 0); - ASSERT_EQ(cstr, s.get_str().c_str()); - ASSERT_ANY_THROW(s.set_static_field(acc_str, cstr)); // readonly - - - // illegal access from an accessor created from different definition list - // note: this should supposedly be checked for and throw an exception, - // but for now we have no elegant way to do it efficiently. - // todo(jasondellaluce): find a good way to check for this - sample_struct2 s2; - auto acc_num2 = s2.static_fields().find("num")->second.new_accessor(); - ASSERT_NO_THROW(s.get_static_field(acc_num2)); +TEST(static_struct, defs_and_access) { + struct err_multidef_struct : public libsinsp::state::static_struct { + libsinsp::state::static_struct::field_infos static_fields() const override { + libsinsp::state::static_struct::field_infos ret; + define_static_field(ret, this, m_num, "num"); + define_static_field(ret, this, m_num, "num"); + return ret; + } + + uint32_t m_num{0}; + }; + + class sample_struct : public libsinsp::state::static_struct { + public: + libsinsp::state::static_struct::field_infos static_fields() const override { + libsinsp::state::static_struct::field_infos ret; + define_static_field(ret, this, m_num, "num"); + define_static_field(ret, this, m_str, "str", true); + return ret; + } + + uint32_t get_num() const { return m_num; } + void set_num(uint32_t v) { m_num = v; } + const std::string& get_str() const { return m_str; } + void set_str(const std::string& v) { m_str = v; } + + private: + uint32_t m_num{0}; + std::string m_str; + }; + + struct sample_struct2 : public libsinsp::state::static_struct { + public: + libsinsp::state::static_struct::field_infos static_fields() const override { + libsinsp::state::static_struct::field_infos ret; + define_static_field(ret, this, m_num, "num"); + return ret; + } + + uint32_t m_num{0}; + }; + + // test errors + ASSERT_ANY_THROW(err_multidef_struct().static_fields()); + + sample_struct s; + const auto& fields = s.static_fields(); + + // check field definitions + auto field_num = fields.find("num"); + auto field_str = fields.find("str"); + ASSERT_EQ(fields.size(), 2); + ASSERT_EQ(fields, sample_struct().static_fields()); + + ASSERT_NE(field_num, fields.end()); + ASSERT_EQ(field_num->second.name(), "num"); + ASSERT_EQ(field_num->second.readonly(), false); + ASSERT_EQ(field_num->second.info(), libsinsp::state::typeinfo::of()); + + ASSERT_NE(field_str, fields.end()); + ASSERT_EQ(field_str->second.name(), "str"); + ASSERT_EQ(field_str->second.readonly(), true); + ASSERT_EQ(field_str->second.info(), libsinsp::state::typeinfo::of()); + + // check field access + auto acc_num = field_num->second.new_accessor(); + auto acc_str = field_str->second.new_accessor(); + ASSERT_ANY_THROW(field_num->second.new_accessor()); + ASSERT_ANY_THROW(field_str->second.new_accessor()); + + ASSERT_EQ(s.get_num(), 0); + ASSERT_EQ(s.get_static_field(acc_num), 0); + s.set_num(5); + ASSERT_EQ(s.get_num(), 5); + uint32_t u32tmp = 0; + s.get_static_field(acc_num, u32tmp); + ASSERT_EQ(u32tmp, 5); + s.set_static_field(acc_num, (uint32_t)6); + ASSERT_EQ(s.get_num(), 6); + ASSERT_EQ(s.get_static_field(acc_num), 6); + + std::string str = ""; + ASSERT_EQ(s.get_str(), str); + ASSERT_EQ(s.get_static_field(acc_str), str); + str = "hello"; + s.set_str("hello"); + ASSERT_EQ(s.get_str(), str); + s.get_static_field(acc_str, str); + ASSERT_EQ(str, "hello"); + ASSERT_ANY_THROW(s.set_static_field(acc_str, "hello")); // readonly + + const char* cstr = "sample"; + s.set_str(""); + s.get_static_field(acc_str, cstr); + ASSERT_EQ(strcmp(cstr, ""), 0); + s.set_str("hello"); + s.get_static_field(acc_str, cstr); + ASSERT_EQ(strcmp(cstr, "hello"), 0); + ASSERT_EQ(cstr, s.get_str().c_str()); + ASSERT_ANY_THROW(s.set_static_field(acc_str, cstr)); // readonly + + // illegal access from an accessor created from different definition list + // note: this should supposedly be checked for and throw an exception, + // but for now we have no elegant way to do it efficiently. + // todo(jasondellaluce): find a good way to check for this + sample_struct2 s2; + auto acc_num2 = s2.static_fields().find("num")->second.new_accessor(); + ASSERT_NO_THROW(s.get_static_field(acc_num2)); } -TEST(dynamic_struct, defs_and_access) -{ - auto fields = std::make_shared(); - - struct sample_struct: public libsinsp::state::dynamic_struct - { - public: - sample_struct(const std::shared_ptr& i): dynamic_struct(i) { } - }; - - // struct construction and setting fields definition - sample_struct s(fields); - ASSERT_ANY_THROW(s.set_dynamic_fields(nullptr)); - ASSERT_ANY_THROW(s.set_dynamic_fields(std::make_shared())); - // The double paranthesis fixes - // Error C2063 'std::shared_ptr' : not a function C - // on the Windows compiler. - // This should be quirk of the Windows compiler. - ASSERT_NO_THROW((sample_struct(std::shared_ptr()))); - ASSERT_NO_THROW(sample_struct(nullptr)); - auto s2 = sample_struct(nullptr); - s2.set_dynamic_fields(fields); - ASSERT_NO_THROW(s2.set_dynamic_fields(fields)); - - // check field definitions - ASSERT_EQ(fields->fields().size(), 0); - ASSERT_EQ(fields, s.dynamic_fields()); - - // adding new fields - auto field_num = fields->add_field("num"); - ASSERT_EQ(fields->fields().size(), 1); - ASSERT_EQ(field_num, fields->fields().find("num")->second); - ASSERT_EQ(field_num.name(), "num"); - ASSERT_EQ(field_num.info(), libsinsp::state::typeinfo::of()); - ASSERT_EQ(field_num, fields->add_field("num")); - ASSERT_ANY_THROW(fields->add_field("num")); - - auto field_str = fields->add_field("str"); - ASSERT_EQ(fields->fields().size(), 2); - ASSERT_EQ(field_str, fields->fields().find("str")->second); - ASSERT_EQ(field_str.name(), "str"); - ASSERT_EQ(field_str.info(), libsinsp::state::typeinfo::of()); - ASSERT_EQ(field_str, fields->add_field("str")); - ASSERT_ANY_THROW(fields->add_field("str")); - - // check field access - auto acc_num = field_num.new_accessor(); - auto acc_str = field_str.new_accessor(); - ASSERT_ANY_THROW(field_num.new_accessor()); - ASSERT_ANY_THROW(field_str.new_accessor()); - - uint64_t tmp; - s.get_dynamic_field(acc_num, tmp); - ASSERT_EQ(tmp, 0); - s.set_dynamic_field(acc_num, (uint64_t) 6); - s.get_dynamic_field(acc_num, tmp); - ASSERT_EQ(tmp, 6); - - std::string tmpstr; - s.get_dynamic_field(acc_str, tmpstr); - ASSERT_EQ(tmpstr, std::string("")); - s.set_dynamic_field(acc_str, std::string("hello")); - s.get_dynamic_field(acc_str, tmpstr); - ASSERT_EQ(tmpstr, std::string("hello")); - - s.set_dynamic_field(acc_str, std::string("")); - const char* ctmpstr = "sample"; - s.get_dynamic_field(acc_str, ctmpstr); - ASSERT_EQ(strcmp(ctmpstr, ""), 0); - ctmpstr = "hello"; - s.set_dynamic_field(acc_str, ctmpstr); - ctmpstr = ""; - s.get_dynamic_field(acc_str, ctmpstr); - ASSERT_EQ(strcmp(ctmpstr, "hello"), 0); - - // illegal access from an accessor created from different definition list - auto fields2 = std::make_shared(); - auto field_num2 = fields2->add_field("num"); - auto acc_num2 = field_num2.new_accessor(); - ASSERT_ANY_THROW(s.get_dynamic_field(acc_num2, tmp)); +TEST(dynamic_struct, defs_and_access) { + auto fields = std::make_shared(); + + struct sample_struct : public libsinsp::state::dynamic_struct { + public: + sample_struct(const std::shared_ptr& i): dynamic_struct(i) {} + }; + + // struct construction and setting fields definition + sample_struct s(fields); + ASSERT_ANY_THROW(s.set_dynamic_fields(nullptr)); + ASSERT_ANY_THROW( + s.set_dynamic_fields(std::make_shared())); + // The double paranthesis fixes + // Error C2063 'std::shared_ptr' : not a function + // C on the Windows compiler. This should be quirk of the Windows compiler. + ASSERT_NO_THROW( + (sample_struct(std::shared_ptr()))); + ASSERT_NO_THROW(sample_struct(nullptr)); + auto s2 = sample_struct(nullptr); + s2.set_dynamic_fields(fields); + ASSERT_NO_THROW(s2.set_dynamic_fields(fields)); + + // check field definitions + ASSERT_EQ(fields->fields().size(), 0); + ASSERT_EQ(fields, s.dynamic_fields()); + + // adding new fields + auto field_num = fields->add_field("num"); + ASSERT_EQ(fields->fields().size(), 1); + ASSERT_EQ(field_num, fields->fields().find("num")->second); + ASSERT_EQ(field_num.name(), "num"); + ASSERT_EQ(field_num.info(), libsinsp::state::typeinfo::of()); + ASSERT_EQ(field_num, fields->add_field("num")); + ASSERT_ANY_THROW(fields->add_field("num")); + + auto field_str = fields->add_field("str"); + ASSERT_EQ(fields->fields().size(), 2); + ASSERT_EQ(field_str, fields->fields().find("str")->second); + ASSERT_EQ(field_str.name(), "str"); + ASSERT_EQ(field_str.info(), libsinsp::state::typeinfo::of()); + ASSERT_EQ(field_str, fields->add_field("str")); + ASSERT_ANY_THROW(fields->add_field("str")); + + // check field access + auto acc_num = field_num.new_accessor(); + auto acc_str = field_str.new_accessor(); + ASSERT_ANY_THROW(field_num.new_accessor()); + ASSERT_ANY_THROW(field_str.new_accessor()); + + uint64_t tmp; + s.get_dynamic_field(acc_num, tmp); + ASSERT_EQ(tmp, 0); + s.set_dynamic_field(acc_num, (uint64_t)6); + s.get_dynamic_field(acc_num, tmp); + ASSERT_EQ(tmp, 6); + + std::string tmpstr; + s.get_dynamic_field(acc_str, tmpstr); + ASSERT_EQ(tmpstr, std::string("")); + s.set_dynamic_field(acc_str, std::string("hello")); + s.get_dynamic_field(acc_str, tmpstr); + ASSERT_EQ(tmpstr, std::string("hello")); + + s.set_dynamic_field(acc_str, std::string("")); + const char* ctmpstr = "sample"; + s.get_dynamic_field(acc_str, ctmpstr); + ASSERT_EQ(strcmp(ctmpstr, ""), 0); + ctmpstr = "hello"; + s.set_dynamic_field(acc_str, ctmpstr); + ctmpstr = ""; + s.get_dynamic_field(acc_str, ctmpstr); + ASSERT_EQ(strcmp(ctmpstr, "hello"), 0); + + // illegal access from an accessor created from different definition list + auto fields2 = std::make_shared(); + auto field_num2 = fields2->add_field("num"); + auto acc_num2 = field_num2.new_accessor(); + ASSERT_ANY_THROW(s.get_dynamic_field(acc_num2, tmp)); } -TEST(dynamic_struct, mem_ownership) -{ - struct sample_struct: public libsinsp::state::dynamic_struct - { - sample_struct(const std::shared_ptr& i): dynamic_struct(i) { } - }; - - std::string tmpstr1, tmpstr2; - auto defs1 = std::make_shared(); - - // construct two entries, test safety checks - sample_struct s1(nullptr); - ASSERT_NO_THROW(s1.set_dynamic_fields(nullptr)); - ASSERT_NO_THROW(s1.set_dynamic_fields(defs1)); - sample_struct s2(defs1); - ASSERT_ANY_THROW(s1.set_dynamic_fields(nullptr)); - ASSERT_NO_THROW(s1.set_dynamic_fields(defs1)); - ASSERT_ANY_THROW(s1.set_dynamic_fields(std::make_shared())); - - // define a string dynamic field - auto field_str = defs1->add_field("str"); - auto field_str_acc = field_str.new_accessor(); - - // write same value in both structs, ensure they have two distinct copies - s1.set_dynamic_field(field_str_acc, std::string("hello")); - s1.get_dynamic_field(field_str_acc, tmpstr1); - ASSERT_EQ(tmpstr1, std::string("hello")); - s2.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_EQ(tmpstr2, std::string("")); // s2 should not be influenced - s2.set_dynamic_field(field_str_acc, std::string("hello2")); - s2.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_EQ(tmpstr2, tmpstr1 + "2"); - s1.get_dynamic_field(field_str_acc, tmpstr1); // s1 should not be influenced - ASSERT_EQ(tmpstr2, tmpstr1 + "2"); - - // deep copy and memory ownership (constructor) - sample_struct s3(s1); - ASSERT_EQ(s1.dynamic_fields().get(), s3.dynamic_fields().get()); - s1.get_dynamic_field(field_str_acc, tmpstr1); - s3.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_EQ(tmpstr1, tmpstr2); - s3.set_dynamic_field(field_str_acc, std::string("hello3")); - s1.get_dynamic_field(field_str_acc, tmpstr1); // should still be "hello" as before - s3.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_NE(tmpstr1, tmpstr2); - - // deep copy and memory ownership (assignment) - sample_struct s4(std::make_shared()); - s4 = s1; - ASSERT_EQ(s1.dynamic_fields().get(), s4.dynamic_fields().get()); - s1.get_dynamic_field(field_str_acc, tmpstr1); - s4.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_EQ(tmpstr1, tmpstr2); - s4.set_dynamic_field(field_str_acc, std::string("hello4")); - s1.get_dynamic_field(field_str_acc, tmpstr1); // should still be "hello" as before - s4.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_NE(tmpstr1, tmpstr2); - - // deep copy and memory ownership (assignment, null initial definitions) - sample_struct s5(nullptr); - s5 = s1; - ASSERT_EQ(s1.dynamic_fields().get(), s5.dynamic_fields().get()); - s1.get_dynamic_field(field_str_acc, tmpstr1); - s5.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_EQ(tmpstr1, tmpstr2); - s5.set_dynamic_field(field_str_acc, std::string("hello4")); - s1.get_dynamic_field(field_str_acc, tmpstr1); // should still be "hello" as before - s5.get_dynamic_field(field_str_acc, tmpstr2); - ASSERT_NE(tmpstr1, tmpstr2); +TEST(dynamic_struct, mem_ownership) { + struct sample_struct : public libsinsp::state::dynamic_struct { + sample_struct(const std::shared_ptr& i): dynamic_struct(i) {} + }; + + std::string tmpstr1, tmpstr2; + auto defs1 = std::make_shared(); + + // construct two entries, test safety checks + sample_struct s1(nullptr); + ASSERT_NO_THROW(s1.set_dynamic_fields(nullptr)); + ASSERT_NO_THROW(s1.set_dynamic_fields(defs1)); + sample_struct s2(defs1); + ASSERT_ANY_THROW(s1.set_dynamic_fields(nullptr)); + ASSERT_NO_THROW(s1.set_dynamic_fields(defs1)); + ASSERT_ANY_THROW(s1.set_dynamic_fields( + std::make_shared())); + + // define a string dynamic field + auto field_str = defs1->add_field("str"); + auto field_str_acc = field_str.new_accessor(); + + // write same value in both structs, ensure they have two distinct copies + s1.set_dynamic_field(field_str_acc, std::string("hello")); + s1.get_dynamic_field(field_str_acc, tmpstr1); + ASSERT_EQ(tmpstr1, std::string("hello")); + s2.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_EQ(tmpstr2, std::string("")); // s2 should not be influenced + s2.set_dynamic_field(field_str_acc, std::string("hello2")); + s2.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_EQ(tmpstr2, tmpstr1 + "2"); + s1.get_dynamic_field(field_str_acc, tmpstr1); // s1 should not be influenced + ASSERT_EQ(tmpstr2, tmpstr1 + "2"); + + // deep copy and memory ownership (constructor) + sample_struct s3(s1); + ASSERT_EQ(s1.dynamic_fields().get(), s3.dynamic_fields().get()); + s1.get_dynamic_field(field_str_acc, tmpstr1); + s3.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_EQ(tmpstr1, tmpstr2); + s3.set_dynamic_field(field_str_acc, std::string("hello3")); + s1.get_dynamic_field(field_str_acc, tmpstr1); // should still be "hello" as before + s3.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_NE(tmpstr1, tmpstr2); + + // deep copy and memory ownership (assignment) + sample_struct s4(std::make_shared()); + s4 = s1; + ASSERT_EQ(s1.dynamic_fields().get(), s4.dynamic_fields().get()); + s1.get_dynamic_field(field_str_acc, tmpstr1); + s4.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_EQ(tmpstr1, tmpstr2); + s4.set_dynamic_field(field_str_acc, std::string("hello4")); + s1.get_dynamic_field(field_str_acc, tmpstr1); // should still be "hello" as before + s4.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_NE(tmpstr1, tmpstr2); + + // deep copy and memory ownership (assignment, null initial definitions) + sample_struct s5(nullptr); + s5 = s1; + ASSERT_EQ(s1.dynamic_fields().get(), s5.dynamic_fields().get()); + s1.get_dynamic_field(field_str_acc, tmpstr1); + s5.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_EQ(tmpstr1, tmpstr2); + s5.set_dynamic_field(field_str_acc, std::string("hello4")); + s1.get_dynamic_field(field_str_acc, tmpstr1); // should still be "hello" as before + s5.get_dynamic_field(field_str_acc, tmpstr2); + ASSERT_NE(tmpstr1, tmpstr2); } -TEST(table_registry, defs_and_access) -{ - class sample_table: public libsinsp::state::table - { - public: - sample_table(): table("sample") { } - - size_t entries_count() const override - { - return m_entries.size(); - } - - void clear_entries() override - { - m_entries.clear(); - } - - std::unique_ptr new_entry() const override - { - return std::unique_ptr( - new libsinsp::state::table_entry(dynamic_fields())); - } - - bool foreach_entry(std::function pred) override - { - for (const auto& e : m_entries) - { - if (!pred(*e.second)) - { - return false; - } - } - return true; - } - - std::shared_ptr get_entry(const uint64_t& key) override - { - const auto& it = m_entries.find(key); - if (it == m_entries.end()) - { - return nullptr; - } - return it->second; - } - - std::shared_ptr add_entry(const uint64_t& key, std::unique_ptr entry) override - { - m_entries[key] = std::move(entry); - return m_entries[key]; - } - - bool erase_entry(const uint64_t& key) override - { - return m_entries.erase(key) != 0; - } - - private: - std::unordered_map> m_entries; - }; - - libsinsp::state::table_registry r; - ASSERT_EQ(r.tables().size(), 0); - ASSERT_EQ(r.get_table("sample"), nullptr); - ASSERT_ANY_THROW(r.add_table(nullptr)); - - sample_table t; - r.add_table(&t); - ASSERT_EQ(r.tables().size(), 1); - ASSERT_EQ(r.tables().find("sample")->second, &t); - ASSERT_EQ(r.get_table("sample"), &t); - ASSERT_ANY_THROW(r.add_table(&t)); // double registration - ASSERT_ANY_THROW(r.get_table("sample")); // bad key type +TEST(table_registry, defs_and_access) { + class sample_table : public libsinsp::state::table { + public: + sample_table(): table("sample") {} + + size_t entries_count() const override { return m_entries.size(); } + + void clear_entries() override { m_entries.clear(); } + + std::unique_ptr new_entry() const override { + return std::unique_ptr( + new libsinsp::state::table_entry(dynamic_fields())); + } + + bool foreach_entry(std::function pred) override { + for(const auto& e : m_entries) { + if(!pred(*e.second)) { + return false; + } + } + return true; + } + + std::shared_ptr get_entry(const uint64_t& key) override { + const auto& it = m_entries.find(key); + if(it == m_entries.end()) { + return nullptr; + } + return it->second; + } + + std::shared_ptr add_entry( + const uint64_t& key, + std::unique_ptr entry) override { + m_entries[key] = std::move(entry); + return m_entries[key]; + } + + bool erase_entry(const uint64_t& key) override { return m_entries.erase(key) != 0; } + + private: + std::unordered_map> m_entries; + }; + + libsinsp::state::table_registry r; + ASSERT_EQ(r.tables().size(), 0); + ASSERT_EQ(r.get_table("sample"), nullptr); + ASSERT_ANY_THROW(r.add_table(nullptr)); + + sample_table t; + r.add_table(&t); + ASSERT_EQ(r.tables().size(), 1); + ASSERT_EQ(r.tables().find("sample")->second, &t); + ASSERT_EQ(r.get_table("sample"), &t); + ASSERT_ANY_THROW(r.add_table(&t)); // double registration + ASSERT_ANY_THROW(r.get_table("sample")); // bad key type } -TEST(thread_manager, table_access) -{ - // note: used for regression checks, keep this updated as we make - // new fields available - static const int s_threadinfo_static_fields_count = 28; - - sinsp inspector; - auto table = static_cast*>(inspector.m_thread_manager.get()); - - // empty table state and info - ASSERT_EQ(table->name(), "threads"); - ASSERT_EQ(table->key_info(), libsinsp::state::typeinfo::of()); - ASSERT_EQ(*table->static_fields(), sinsp_threadinfo().static_fields()); - ASSERT_NE(table->dynamic_fields(), nullptr); - ASSERT_EQ(table->dynamic_fields()->fields().size(), 0); - ASSERT_EQ(table->entries_count(), 0); - ASSERT_EQ(table->get_entry(999), nullptr); - ASSERT_EQ(table->erase_entry(999), false); - - // create and add a thread - auto newt = table->new_entry(); - auto newtinfo = dynamic_cast(newt.get()); - auto tid_acc = newt->static_fields().at("tid").new_accessor(); - auto comm_acc = newt->static_fields().at("comm").new_accessor(); - auto fdtable_acc = newt->static_fields().at("file_descriptors").new_accessor(); - ASSERT_NE(newtinfo, nullptr); - ASSERT_EQ(newt->dynamic_fields(), table->dynamic_fields()); - ASSERT_EQ(newt->static_fields(), *table->static_fields()); - ASSERT_EQ(newt->static_fields().size(), s_threadinfo_static_fields_count); - newtinfo->m_tid = 999; - newtinfo->m_comm = "test"; - ASSERT_EQ(newt->get_static_field(tid_acc), (int64_t) 999); - ASSERT_EQ(newt->get_static_field(comm_acc), "test"); - ASSERT_NE(newt->get_static_field(fdtable_acc), nullptr); - ASSERT_EQ(newt->get_static_field(fdtable_acc)->name(), "file_descriptors"); - ASSERT_NO_THROW(table->add_entry(999, std::move(newt))); - ASSERT_EQ(table->entries_count(), 1); - auto addedt = table->get_entry(999); - ASSERT_NE(addedt, nullptr); - ASSERT_EQ(addedt->get_static_field(tid_acc), (int64_t) 999); - ASSERT_EQ(addedt->get_static_field(comm_acc), "test"); - ASSERT_NE(addedt->get_static_field(fdtable_acc), nullptr); - ASSERT_EQ(addedt->get_static_field(fdtable_acc)->name(), "file_descriptors"); - - // add a dynamic field to table - std::string tmpstr; - auto dynf_acc = table->dynamic_fields()->add_field("some_new_field").new_accessor(); - ASSERT_EQ(table->dynamic_fields()->fields().size(), 1); - ASSERT_EQ(addedt->dynamic_fields()->fields().size(), 1); - addedt->get_dynamic_field(dynf_acc, tmpstr); - ASSERT_EQ(tmpstr, ""); - addedt->set_dynamic_field(dynf_acc, std::string("hello")); - addedt->get_dynamic_field(dynf_acc, tmpstr); - ASSERT_EQ(tmpstr, "hello"); - - // add another thread - newt = table->new_entry(); - newt->set_static_field(tid_acc, (int64_t) 1000); - ASSERT_NO_THROW(table->add_entry(1000, std::move(newt))); - addedt = table->get_entry(1000); - ASSERT_EQ(addedt->get_static_field(tid_acc), (int64_t) 1000); - addedt->get_dynamic_field(dynf_acc, tmpstr); - ASSERT_EQ(tmpstr, ""); - addedt->set_dynamic_field(dynf_acc, std::string("world")); - addedt->get_dynamic_field(dynf_acc, tmpstr); - ASSERT_EQ(tmpstr, "world"); - - // loop over entries - int count = 0; - table->foreach_entry([&count, tid_acc](libsinsp::state::table_entry &e) { - auto tid = e.get_static_field(tid_acc); - if (tid == 999 || tid == 1000) - { - count++; - } - return true; - }); - ASSERT_EQ(count, 2); - - // remove and clear entries - ASSERT_EQ(table->entries_count(), 2); - ASSERT_EQ(table->erase_entry(1000), true); - ASSERT_EQ(table->entries_count(), 1); - table->clear_entries(); - ASSERT_EQ(table->entries_count(), 0); +TEST(thread_manager, table_access) { + // note: used for regression checks, keep this updated as we make + // new fields available + static const int s_threadinfo_static_fields_count = 28; + + sinsp inspector; + auto table = static_cast*>(inspector.m_thread_manager.get()); + + // empty table state and info + ASSERT_EQ(table->name(), "threads"); + ASSERT_EQ(table->key_info(), libsinsp::state::typeinfo::of()); + ASSERT_EQ(*table->static_fields(), sinsp_threadinfo().static_fields()); + ASSERT_NE(table->dynamic_fields(), nullptr); + ASSERT_EQ(table->dynamic_fields()->fields().size(), 0); + ASSERT_EQ(table->entries_count(), 0); + ASSERT_EQ(table->get_entry(999), nullptr); + ASSERT_EQ(table->erase_entry(999), false); + + // create and add a thread + auto newt = table->new_entry(); + auto newtinfo = dynamic_cast(newt.get()); + auto tid_acc = newt->static_fields().at("tid").new_accessor(); + auto comm_acc = newt->static_fields().at("comm").new_accessor(); + auto fdtable_acc = newt->static_fields() + .at("file_descriptors") + .new_accessor(); + ASSERT_NE(newtinfo, nullptr); + ASSERT_EQ(newt->dynamic_fields(), table->dynamic_fields()); + ASSERT_EQ(newt->static_fields(), *table->static_fields()); + ASSERT_EQ(newt->static_fields().size(), s_threadinfo_static_fields_count); + newtinfo->m_tid = 999; + newtinfo->m_comm = "test"; + ASSERT_EQ(newt->get_static_field(tid_acc), (int64_t)999); + ASSERT_EQ(newt->get_static_field(comm_acc), "test"); + ASSERT_NE(newt->get_static_field(fdtable_acc), nullptr); + ASSERT_EQ(newt->get_static_field(fdtable_acc)->name(), "file_descriptors"); + ASSERT_NO_THROW(table->add_entry(999, std::move(newt))); + ASSERT_EQ(table->entries_count(), 1); + auto addedt = table->get_entry(999); + ASSERT_NE(addedt, nullptr); + ASSERT_EQ(addedt->get_static_field(tid_acc), (int64_t)999); + ASSERT_EQ(addedt->get_static_field(comm_acc), "test"); + ASSERT_NE(addedt->get_static_field(fdtable_acc), nullptr); + ASSERT_EQ(addedt->get_static_field(fdtable_acc)->name(), "file_descriptors"); + + // add a dynamic field to table + std::string tmpstr; + auto dynf_acc = table->dynamic_fields() + ->add_field("some_new_field") + .new_accessor(); + ASSERT_EQ(table->dynamic_fields()->fields().size(), 1); + ASSERT_EQ(addedt->dynamic_fields()->fields().size(), 1); + addedt->get_dynamic_field(dynf_acc, tmpstr); + ASSERT_EQ(tmpstr, ""); + addedt->set_dynamic_field(dynf_acc, std::string("hello")); + addedt->get_dynamic_field(dynf_acc, tmpstr); + ASSERT_EQ(tmpstr, "hello"); + + // add another thread + newt = table->new_entry(); + newt->set_static_field(tid_acc, (int64_t)1000); + ASSERT_NO_THROW(table->add_entry(1000, std::move(newt))); + addedt = table->get_entry(1000); + ASSERT_EQ(addedt->get_static_field(tid_acc), (int64_t)1000); + addedt->get_dynamic_field(dynf_acc, tmpstr); + ASSERT_EQ(tmpstr, ""); + addedt->set_dynamic_field(dynf_acc, std::string("world")); + addedt->get_dynamic_field(dynf_acc, tmpstr); + ASSERT_EQ(tmpstr, "world"); + + // loop over entries + int count = 0; + table->foreach_entry([&count, tid_acc](libsinsp::state::table_entry& e) { + auto tid = e.get_static_field(tid_acc); + if(tid == 999 || tid == 1000) { + count++; + } + return true; + }); + ASSERT_EQ(count, 2); + + // remove and clear entries + ASSERT_EQ(table->entries_count(), 2); + ASSERT_EQ(table->erase_entry(1000), true); + ASSERT_EQ(table->entries_count(), 1); + table->clear_entries(); + ASSERT_EQ(table->entries_count(), 0); } -TEST(thread_manager, fdtable_access) -{ - // note: used for regression checks, keep this updated as we make new fields available - static const int s_fdinfo_static_fields_count = 32; +TEST(thread_manager, fdtable_access) { + // note: used for regression checks, keep this updated as we make new fields available + static const int s_fdinfo_static_fields_count = 32; - sinsp inspector; + sinsp inspector; auto& reg = inspector.get_table_registry(); ASSERT_EQ(reg->tables().size(), 1); @@ -488,7 +463,7 @@ TEST(thread_manager, fdtable_access) ASSERT_EQ(table->entries_count(), 0); - //add two new entries to the thread table + // add two new entries to the thread table ASSERT_NE(table->add_entry(0, table->new_entry()), nullptr); auto entry = table->get_entry(0); ASSERT_NE(entry, nullptr); @@ -499,7 +474,7 @@ TEST(thread_manager, fdtable_access) ASSERT_NE(entry2, nullptr); ASSERT_EQ(table->entries_count(), 2); - //getting the fd tables from the newly created threads + // getting the fd tables from the newly created threads auto subtable_acc = field->second.new_accessor(); auto subtable = dynamic_cast(entry->get_static_field(subtable_acc)); auto subtable2 = dynamic_cast(entry2->get_static_field(subtable_acc)); @@ -513,7 +488,7 @@ TEST(thread_manager, fdtable_access) ASSERT_EQ(subtable->static_fields()->size(), s_fdinfo_static_fields_count); ASSERT_EQ(subtable->dynamic_fields()->fields().size(), 0); - //getting an existing field + // getting an existing field auto sfield = subtable->static_fields()->find("pid"); ASSERT_NE(sfield, subtable->static_fields()->end()); ASSERT_EQ(sfield->second.readonly(), false); @@ -521,7 +496,7 @@ TEST(thread_manager, fdtable_access) ASSERT_EQ(sfield->second.name(), "pid"); ASSERT_EQ(sfield->second.info(), libsinsp::state::typeinfo::of()); - //adding a new dynamic field + // adding a new dynamic field const auto& dfield = subtable->dynamic_fields()->add_field("str_val"); ASSERT_EQ(dfield, subtable->dynamic_fields()->fields().find("str_val")->second); ASSERT_EQ(dfield.readonly(), false); @@ -530,21 +505,22 @@ TEST(thread_manager, fdtable_access) ASSERT_EQ(dfield.name(), "str_val"); ASSERT_EQ(dfield.info(), libsinsp::state::typeinfo::of()); - //checking if the new field has been added + // checking if the new field has been added ASSERT_EQ(subtable->dynamic_fields()->fields().size(), 1); - ASSERT_NE(subtable->dynamic_fields()->fields().find("str_val"), subtable->dynamic_fields()->fields().end()); + ASSERT_NE(subtable->dynamic_fields()->fields().find("str_val"), + subtable->dynamic_fields()->fields().end()); - //checking if the new field has been added to the other subtable + // checking if the new field has been added to the other subtable ASSERT_EQ(subtable2->dynamic_fields()->fields().size(), 1); - ASSERT_NE(subtable2->dynamic_fields()->fields().find("str_val"), subtable2->dynamic_fields()->fields().end()); + ASSERT_NE(subtable2->dynamic_fields()->fields().find("str_val"), + subtable2->dynamic_fields()->fields().end()); auto sfieldacc = sfield->second.new_accessor(); auto dfieldacc = dfield.new_accessor(); // adding new entries to the subtable - uint64_t max_iterations = 4096; // note: configured max entries in fd tables - for (uint64_t i = 0; i < max_iterations; i++) - { + uint64_t max_iterations = 4096; // note: configured max entries in fd tables + for(uint64_t i = 0; i < max_iterations; i++) { ASSERT_EQ(subtable->entries_count(), i); // get non-existing entry @@ -578,8 +554,7 @@ TEST(thread_manager, fdtable_access) } // full iteration - auto it = [&](libsinsp::state::table_entry& e) -> bool - { + auto it = [&](libsinsp::state::table_entry& e) -> bool { int64_t tmp; std::string tmpstr; e.get_static_field(sfieldacc, tmp); @@ -591,16 +566,12 @@ TEST(thread_manager, fdtable_access) ASSERT_TRUE(subtable->foreach_entry(it)); // iteration with break-out - ASSERT_FALSE(subtable->foreach_entry([&](libsinsp::state::table_entry& e) -> bool - { - return false; - })); + ASSERT_FALSE(subtable->foreach_entry( + [&](libsinsp::state::table_entry& e) -> bool { return false; })); // iteration with error - ASSERT_ANY_THROW(subtable->foreach_entry([&](libsinsp::state::table_entry& e) -> bool - { - throw sinsp_exception("some error"); - })); + ASSERT_ANY_THROW(subtable->foreach_entry( + [&](libsinsp::state::table_entry& e) -> bool { throw sinsp_exception("some error"); })); // erasing an unknown fd ASSERT_EQ(subtable->erase_entry(max_iterations), false); @@ -615,9 +586,8 @@ TEST(thread_manager, fdtable_access) ASSERT_EQ(subtable->entries_count(), 0); } -TEST(thread_manager, env_vars_access) -{ - sinsp inspector; +TEST(thread_manager, env_vars_access) { + sinsp inspector; auto& reg = inspector.get_table_registry(); ASSERT_EQ(reg->tables().size(), 1); @@ -638,15 +608,17 @@ TEST(thread_manager, env_vars_access) ASSERT_EQ(table->entries_count(), 0); - //add two new entries to the thread table + // add two new entries to the thread table ASSERT_NE(table->add_entry(1, table->new_entry()), nullptr); auto entry = table->get_entry(1); ASSERT_NE(entry, nullptr); ASSERT_EQ(table->entries_count(), 1); - //getting the fd tables from the newly created threads + // getting the fd tables from the newly created threads auto subtable_acc = field->second.new_accessor(); - auto subtable = dynamic_cast>*>(entry->get_static_field(subtable_acc)); + auto subtable = + dynamic_cast>*>( + entry->get_static_field(subtable_acc)); ASSERT_NE(subtable, nullptr); EXPECT_EQ(subtable->name(), "env"); EXPECT_EQ(subtable->entries_count(), 0); @@ -654,7 +626,7 @@ TEST(thread_manager, env_vars_access) EXPECT_EQ(subtable->static_fields()->size(), 0); EXPECT_EQ(subtable->dynamic_fields()->fields().size(), 1); - //getting an existing field + // getting an existing field auto sfield = subtable->dynamic_fields()->fields().find("value"); ASSERT_NE(sfield, subtable->dynamic_fields()->fields().end()); EXPECT_EQ(sfield->second.readonly(), false); @@ -666,8 +638,7 @@ TEST(thread_manager, env_vars_access) // adding new entries to the subtable uint64_t max_iterations = 10; - for (uint64_t i = 0; i < max_iterations; i++) - { + for(uint64_t i = 0; i < max_iterations; i++) { ASSERT_EQ(subtable->entries_count(), i); // get non-existing entry @@ -691,8 +662,7 @@ TEST(thread_manager, env_vars_access) } // full iteration - auto it = [&](libsinsp::state::table_entry& e) -> bool - { + auto it = [&](libsinsp::state::table_entry& e) -> bool { std::string tmpstr = "test"; e.get_dynamic_field(fieldacc, tmpstr); EXPECT_EQ(tmpstr, "hello"); @@ -701,16 +671,12 @@ TEST(thread_manager, env_vars_access) ASSERT_TRUE(subtable->foreach_entry(it)); // iteration with break-out - ASSERT_FALSE(subtable->foreach_entry([&](libsinsp::state::table_entry& e) -> bool - { - return false; - })); + ASSERT_FALSE(subtable->foreach_entry( + [&](libsinsp::state::table_entry& e) -> bool { return false; })); // iteration with error - ASSERT_ANY_THROW(subtable->foreach_entry([&](libsinsp::state::table_entry& e) -> bool - { - throw sinsp_exception("some error"); - })); + ASSERT_ANY_THROW(subtable->foreach_entry( + [&](libsinsp::state::table_entry& e) -> bool { throw sinsp_exception("some error"); })); // erasing an unknown fd ASSERT_EQ(subtable->erase_entry(max_iterations), false); @@ -720,18 +686,17 @@ TEST(thread_manager, env_vars_access) ASSERT_EQ(subtable->erase_entry(0), true); ASSERT_EQ(subtable->entries_count(), max_iterations - 1); - // check that changes are reflected in thread's table - auto tinfo = inspector.m_thread_manager->get_thread_ref(1); - ASSERT_NE(tinfo, nullptr); + // check that changes are reflected in thread's table + auto tinfo = inspector.m_thread_manager->get_thread_ref(1); + ASSERT_NE(tinfo, nullptr); - ASSERT_EQ(tinfo->m_env.size(), max_iterations - 1); - for (const auto & v : tinfo->m_env) - { - EXPECT_EQ(v, "hello"); - } + ASSERT_EQ(tinfo->m_env.size(), max_iterations - 1); + for(const auto& v : tinfo->m_env) { + EXPECT_EQ(v, "hello"); + } // clear all ASSERT_NO_THROW(subtable->clear_entries()); EXPECT_EQ(subtable->entries_count(), 0); - EXPECT_EQ(tinfo->m_env.size(), 0); + EXPECT_EQ(tinfo->m_env.size(), 0); } diff --git a/userspace/libsinsp/test/string_visitor.ut.cpp b/userspace/libsinsp/test/string_visitor.ut.cpp index 2eb5ef7901..9eefe6675e 100644 --- a/userspace/libsinsp/test/string_visitor.ut.cpp +++ b/userspace/libsinsp/test/string_visitor.ut.cpp @@ -25,15 +25,12 @@ using namespace std; using namespace libsinsp::filter; using namespace libsinsp::filter::ast; -class string_visitor_test : public testing::Test -{ +class string_visitor_test : public testing::Test { protected: - // In and out are different to test minor things like // consistent spacing between fields and values, top-level // parentheses, etc. - void unidirectional(const std::string& in, const std::string& out) - { + void unidirectional(const std::string& in, const std::string& out) { parser parser(in); std::unique_ptr e(parser.parse()); @@ -41,107 +38,96 @@ class string_visitor_test : public testing::Test ASSERT_STREQ(as_string(e.get()).c_str(), out.c_str()); } - void bidirectional(const std::string &filter) - { + void bidirectional(const std::string& filter) { std::unique_ptr e1(parser(filter).parse()); std::unique_ptr e2(parser(as_string(e1.get())).parse()); ASSERT_TRUE(e1->is_equal(e2.get())); } std::string complex_filter = - "(" - " (evt.type = open or evt.type = openat)" - " and evt.is_open_write = true" - " and fd.typechar = f" - " and fd.num >= 0" - ")" - "and (" - " fd.filename in (" - " .bashrc, .bash_profile, .bash_history, .bash_login," - " .bash_logout, .inputrc, .profile, .cshrc, .login, .logout," - " .history, .tcshrc, .cshdirs, .zshenv, .zprofile, .zshrc," - " .zlogin, .zlogout" - " )" - " or fd.name in (/etc/profile, /etc/bashrc, /etc/csh.cshrc, /etc/csh.login)" - " or fd.directory in (/etc/zsh)" - ")" - "and not proc.name in (ash, bash, csh, ksh, sh, tcsh, zsh, dash)" - "and not (" - " proc.name = exe" - " and (proc.cmdline contains \"/var/lib/docker\" or proc.cmdline contains '/var/run/docker')" - " and proc.pname in (dockerd, docker, dockerd-current, docker-current)" - ")"; - + "(" + " (evt.type = open or evt.type = openat)" + " and evt.is_open_write = true" + " and fd.typechar = f" + " and fd.num >= 0" + ")" + "and (" + " fd.filename in (" + " .bashrc, .bash_profile, .bash_history, .bash_login," + " .bash_logout, .inputrc, .profile, .cshrc, .login, .logout," + " .history, .tcshrc, .cshdirs, .zshenv, .zprofile, .zshrc," + " .zlogin, .zlogout" + " )" + " or fd.name in (/etc/profile, /etc/bashrc, /etc/csh.cshrc, /etc/csh.login)" + " or fd.directory in (/etc/zsh)" + ")" + "and not proc.name in (ash, bash, csh, ksh, sh, tcsh, zsh, dash)" + "and not (" + " proc.name = exe" + " and (proc.cmdline contains \"/var/lib/docker\" or proc.cmdline contains " + "'/var/run/docker')" + " and proc.pname in (dockerd, docker, dockerd-current, docker-current)" + ")"; }; -TEST_F(string_visitor_test, and_expr) -{ +TEST_F(string_visitor_test, and_expr) { std::string in = "proc.name=nginx and fd.name=/etc/passwd"; std::string out = "(proc.name = nginx and fd.name = /etc/passwd)"; unidirectional(in, out); } -TEST_F(string_visitor_test, and_expr_bidirectional) -{ +TEST_F(string_visitor_test, and_expr_bidirectional) { std::string in = "proc.name=nginx and fd.name=/etc/passwd"; bidirectional(in); } -TEST_F(string_visitor_test, or_expr) -{ +TEST_F(string_visitor_test, or_expr) { std::string in = "proc.name=nginx or fd.name=/etc/passwd"; std::string out = "(proc.name = nginx or fd.name = /etc/passwd)"; unidirectional(in, out); } -TEST_F(string_visitor_test, or_expr_bidirectional) -{ +TEST_F(string_visitor_test, or_expr_bidirectional) { std::string in = "proc.name=nginx or fd.name=/etc/passwd"; bidirectional(in); } -TEST_F(string_visitor_test, not_expr) -{ +TEST_F(string_visitor_test, not_expr) { std::string in = "not proc.name=nginx"; std::string out = "not proc.name = nginx"; unidirectional(in, out); } -TEST_F(string_visitor_test, not_expr_bidirectional) -{ +TEST_F(string_visitor_test, not_expr_bidirectional) { std::string in = "not proc.name=nginx"; bidirectional(in); } -TEST_F(string_visitor_test, list_expr) -{ +TEST_F(string_visitor_test, list_expr) { std::string in = "proc.name in (nginx, apache)"; unidirectional(in, in); } -TEST_F(string_visitor_test, list_expr_bidirectional) -{ +TEST_F(string_visitor_test, list_expr_bidirectional) { std::string in = "proc.name in (nginx, apache)"; bidirectional(in); } -TEST_F(string_visitor_test, list_expr_escaped) -{ +TEST_F(string_visitor_test, list_expr_escaped) { std::string in = "proc.name in (\"some proc\", apache)"; unidirectional(in, in); } -TEST_F(string_visitor_test, list_expr_escaped_bidirectional) -{ +TEST_F(string_visitor_test, list_expr_escaped_bidirectional) { std::string in = "proc.name in (\"some proc\", apache)"; bidirectional(in); @@ -149,151 +135,139 @@ TEST_F(string_visitor_test, list_expr_escaped_bidirectional) // No unidirectional version of this test--the single quoted string // ends up being escaped with double quotes. -TEST_F(string_visitor_test, list_expr_escaped_bidirectional_single_quote) -{ +TEST_F(string_visitor_test, list_expr_escaped_bidirectional_single_quote) { std::string in = "proc.name in ('some proc', apache)"; bidirectional(in); } -TEST_F(string_visitor_test, check_args) -{ +TEST_F(string_visitor_test, check_args) { std::string in = "proc.aname[1] != nginx"; unidirectional(in, in); } -TEST_F(string_visitor_test, check_args_bidirectional) -{ +TEST_F(string_visitor_test, check_args_bidirectional) { std::string in = "proc.aname[1] != nginx"; bidirectional(in); } -TEST_F(string_visitor_test, check_args_escaped) -{ +TEST_F(string_visitor_test, check_args_escaped) { std::string in = "proc.aname[\"some proc\"] != nginx"; unidirectional(in, in); } -TEST_F(string_visitor_test, check_args_escaped_bidirectional) -{ +TEST_F(string_visitor_test, check_args_escaped_bidirectional) { std::string in = "proc.aname[\"some proc\"] != nginx"; bidirectional(in); } -TEST_F(string_visitor_test, binary_check) -{ +TEST_F(string_visitor_test, binary_check) { std::string in = "proc.name=nginx"; std::string out = "proc.name = nginx"; unidirectional(in, out); } -TEST_F(string_visitor_test, binary_check_bidirectional) -{ +TEST_F(string_visitor_test, binary_check_bidirectional) { std::string in = "proc.name=nginx"; bidirectional(in); } -TEST_F(string_visitor_test, binary_check_escaped) -{ +TEST_F(string_visitor_test, binary_check_escaped) { std::string in = "proc.name=\"some proc\""; std::string out = "proc.name = \"some proc\""; unidirectional(in, out); } -TEST_F(string_visitor_test, binary_check_escaped_bidirectional) -{ +TEST_F(string_visitor_test, binary_check_escaped_bidirectional) { std::string in = "proc.name=\"some proc\""; bidirectional(in); } -TEST_F(string_visitor_test, binary_check_escaped_single_quote) -{ +TEST_F(string_visitor_test, binary_check_escaped_single_quote) { std::string in = "proc.name='some proc'"; std::string out = "proc.name = \"some proc\""; unidirectional(in, out); } -TEST_F(string_visitor_test, binary_check_escaped_nested_quotes) -{ +TEST_F(string_visitor_test, binary_check_escaped_nested_quotes) { std::string in = "proc.name=\"some 'proc'\""; std::string out = "proc.name = \"some 'proc'\""; unidirectional(in, out); } -TEST_F(string_visitor_test, unary_check) -{ +TEST_F(string_visitor_test, unary_check) { std::string in = "proc.name exists"; unidirectional(in, in); } -TEST_F(string_visitor_test, unary_check_bidirectional) -{ +TEST_F(string_visitor_test, unary_check_bidirectional) { std::string in = "proc.name exists"; bidirectional(in); } -TEST_F(string_visitor_test, unary_check_arg) -{ +TEST_F(string_visitor_test, unary_check_arg) { std::string in = "proc.aname[1] exists"; unidirectional(in, in); } -TEST_F(string_visitor_test, unary_check_arg_bidirectional) -{ +TEST_F(string_visitor_test, unary_check_arg_bidirectional) { std::string in = "proc.aname[1] exists"; bidirectional(in); } -TEST_F(string_visitor_test, unary_check_arg_escaped) -{ +TEST_F(string_visitor_test, unary_check_arg_escaped) { std::string in = "proc.aname[\"some proc\"] exists"; unidirectional(in, in); } -TEST_F(string_visitor_test, unary_check_arg_escaped_bidirectional) -{ +TEST_F(string_visitor_test, unary_check_arg_escaped_bidirectional) { std::string in = "proc.aname[\"some proc\"] exists"; bidirectional(in); } -TEST_F(string_visitor_test, macro_reference) -{ +TEST_F(string_visitor_test, macro_reference) { std::string in = "(some_macro and proc.name = nginx)"; unidirectional(in, in); } -TEST_F(string_visitor_test, macro_reference_bidirectional) -{ +TEST_F(string_visitor_test, macro_reference_bidirectional) { std::string in = "some_macro and proc.name = nginx"; bidirectional(in); } -TEST_F(string_visitor_test, complex) -{ - std::string out = "(((evt.type = open or evt.type = openat) and evt.is_open_write = true and fd.typechar = f and fd.num >= 0) and (fd.filename in (.bashrc, .bash_profile, .bash_history, .bash_login, .bash_logout, .inputrc, .profile, .cshrc, .login, .logout, .history, .tcshrc, .cshdirs, .zshenv, .zprofile, .zshrc, .zlogin, .zlogout) or fd.name in (/etc/profile, /etc/bashrc, /etc/csh.cshrc, /etc/csh.login) or fd.directory in (/etc/zsh)) and not proc.name in (ash, bash, csh, ksh, sh, tcsh, zsh, dash) and not (proc.name = exe and (proc.cmdline contains /var/lib/docker or proc.cmdline contains /var/run/docker) and proc.pname in (dockerd, docker, dockerd-current, docker-current)))"; +TEST_F(string_visitor_test, complex) { + std::string out = + "(((evt.type = open or evt.type = openat) and evt.is_open_write = true and fd.typechar " + "= f and fd.num >= 0) and (fd.filename in (.bashrc, .bash_profile, .bash_history, " + ".bash_login, .bash_logout, .inputrc, .profile, .cshrc, .login, .logout, .history, " + ".tcshrc, .cshdirs, .zshenv, .zprofile, .zshrc, .zlogin, .zlogout) or fd.name in " + "(/etc/profile, /etc/bashrc, /etc/csh.cshrc, /etc/csh.login) or fd.directory in " + "(/etc/zsh)) and not proc.name in (ash, bash, csh, ksh, sh, tcsh, zsh, dash) and not " + "(proc.name = exe and (proc.cmdline contains /var/lib/docker or proc.cmdline contains " + "/var/run/docker) and proc.pname in (dockerd, docker, dockerd-current, " + "docker-current)))"; unidirectional(complex_filter, out); } -TEST_F(string_visitor_test, complex_bidirectional) -{ +TEST_F(string_visitor_test, complex_bidirectional) { bidirectional(complex_filter); } diff --git a/userspace/libsinsp/test/test_utils.cpp b/userspace/libsinsp/test/test_utils.cpp index b329766912..e6f9949c48 100644 --- a/userspace/libsinsp/test/test_utils.cpp +++ b/userspace/libsinsp/test/test_utils.cpp @@ -22,7 +22,7 @@ limitations under the License. #if !defined(_WIN32) #include -#endif //_WIN32 +#endif //_WIN32 #include #include @@ -32,8 +32,7 @@ limitations under the License. namespace test_utils { #if !defined(_WIN32) -sockaddr_in fill_sockaddr_in(int32_t ipv4_port, const char* ipv4_string) -{ +sockaddr_in fill_sockaddr_in(int32_t ipv4_port, const char *ipv4_string) { sockaddr_in sockaddr; memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sin_family = AF_INET; @@ -42,8 +41,7 @@ sockaddr_in fill_sockaddr_in(int32_t ipv4_port, const char* ipv4_string) return sockaddr; } -sockaddr_in6 fill_sockaddr_in6(int32_t ipv6_port, const char* ipv6_string) -{ +sockaddr_in6 fill_sockaddr_in6(int32_t ipv6_port, const char *ipv6_string) { sockaddr_in6 sockaddr; memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sin6_family = AF_INET6; @@ -52,21 +50,19 @@ sockaddr_in6 fill_sockaddr_in6(int32_t ipv6_port, const char* ipv6_string) return sockaddr; } -struct sockaddr_un fill_sockaddr_un(const char* unix_path) -{ +struct sockaddr_un fill_sockaddr_un(const char *unix_path) { struct sockaddr_un sockaddr; memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sun_family = AF_UNIX; strlcpy(sockaddr.sun_path, unix_path, UNIX_PATH_MAX); return sockaddr; } -#endif //_WIN32 +#endif //_WIN32 -std::string to_null_delimited(const std::vector list) -{ +std::string to_null_delimited(const std::vector list) { std::string res; - for (std::string item : list) { + for(std::string item : list) { res += item; res.push_back('\0'); } @@ -75,37 +71,33 @@ std::string to_null_delimited(const std::vector list) } template -std::set unordered_set_to_ordered(std::unordered_set unordered_set) -{ +std::set unordered_set_to_ordered(std::unordered_set unordered_set) { std::set s; - for(const auto& val : unordered_set) - { + for(const auto &val : unordered_set) { s.insert(val); } return s; } template std::set unordered_set_to_ordered(std::unordered_set unordered_set); -template std::set unordered_set_to_ordered(std::unordered_set unordered_set); +template std::set unordered_set_to_ordered( + std::unordered_set unordered_set); -void print_bytes(uint8_t *buf, size_t size) -{ - for(size_t i = 0; i < size; i++) - { - if (i % 16 == 0) { +void print_bytes(uint8_t *buf, size_t size) { + for(size_t i = 0; i < size; i++) { + if(i % 16 == 0) { printf("%03lx | ", i); } printf("%02x ", buf[i]); - if (i % 16 == 0xf) { + if(i % 16 == 0xf) { printf("\n"); } } printf("\n"); } -std::string describe_string(const char* nullable_string) -{ +std::string describe_string(const char *nullable_string) { std::string description; - if (nullable_string == nullptr) { + if(nullable_string == nullptr) { description.append("literal NULL"); } else { description.append("\""); @@ -116,10 +108,9 @@ std::string describe_string(const char* nullable_string) return description; } -inline void vecbuf_append(std::vector &dest, void* src, size_t size) -{ - uint8_t *src_bytes = reinterpret_cast(src); - for (size_t i = 0; i < size; i++) { +inline void vecbuf_append(std::vector &dest, void *src, size_t size) { + uint8_t *src_bytes = reinterpret_cast(src); + for(size_t i = 0; i < size; i++) { uint8_t byte; memcpy(&byte, src_bytes + i, 1); dest.push_back(byte); @@ -127,119 +118,89 @@ inline void vecbuf_append(std::vector &dest, void* src, size_t size) } #if !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(__APPLE__) -std::vector pack_addr(sockaddr *sa) -{ +std::vector pack_addr(sockaddr *sa) { std::vector res; - switch(sa->sa_family) - { - case AF_INET: - { - sockaddr_in *sa_in = (sockaddr_in *)sa; - vecbuf_append(res, &sa_in->sin_addr.s_addr, sizeof(sa_in->sin_addr.s_addr)); - } - break; - - case AF_INET6: - { - sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; - vecbuf_append(res, &sa_in6->sin6_addr, 2 * sizeof(uint64_t)); - } - break; - - case AF_UNIX: - { - sockaddr_un *sa_un = (sockaddr_un *)sa; - std::string path = std::string(sa_un->sun_path); - path = path.substr(0, UNIX_PATH_MAX); - path.push_back('\0'); - res.insert(res.end(), path.begin(), path.end()); - } - break; + switch(sa->sa_family) { + case AF_INET: { + sockaddr_in *sa_in = (sockaddr_in *)sa; + vecbuf_append(res, &sa_in->sin_addr.s_addr, sizeof(sa_in->sin_addr.s_addr)); + } break; + + case AF_INET6: { + sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; + vecbuf_append(res, &sa_in6->sin6_addr, 2 * sizeof(uint64_t)); + } break; + + case AF_UNIX: { + sockaddr_un *sa_un = (sockaddr_un *)sa; + std::string path = std::string(sa_un->sun_path); + path = path.substr(0, UNIX_PATH_MAX); + path.push_back('\0'); + res.insert(res.end(), path.begin(), path.end()); + } break; } return res; } -uint16_t get_port(sockaddr *sa) -{ - switch(sa->sa_family) - { - case AF_INET: - { - sockaddr_in *sa_in = (sockaddr_in *)sa; - return ntohs(sa_in->sin_port); - } - break; - - case AF_INET6: - { - sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; - return ntohs(sa_in6->sin6_port); - } - break; - +uint16_t get_port(sockaddr *sa) { + switch(sa->sa_family) { + case AF_INET: { + sockaddr_in *sa_in = (sockaddr_in *)sa; + return ntohs(sa_in->sin_port); + } break; + + case AF_INET6: { + sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; + return ntohs(sa_in6->sin6_port); + } break; } return 0; } -std::vector pack_addr_port(sockaddr *sa) -{ +std::vector pack_addr_port(sockaddr *sa) { std::vector res; uint16_t dport = get_port(sa); - switch(sa->sa_family) - { - case AF_INET: - case AF_INET6: - { - auto addr = pack_addr(sa); - res.insert(res.end(), addr.begin(), addr.end()); - vecbuf_append(res, &dport, sizeof(uint16_t)); - } - break; - - case AF_UNIX: - { - return pack_addr(sa); - } - break; + switch(sa->sa_family) { + case AF_INET: + case AF_INET6: { + auto addr = pack_addr(sa); + res.insert(res.end(), addr.begin(), addr.end()); + vecbuf_append(res, &dport, sizeof(uint16_t)); + } break; + + case AF_UNIX: { + return pack_addr(sa); + } break; } return res; } -uint8_t get_sock_family(sockaddr *sa) -{ +uint8_t get_sock_family(sockaddr *sa) { uint8_t sock_family = 0; - switch(sa->sa_family) - { - case AF_INET: - { - sockaddr_in *sa_in = (sockaddr_in *)sa; - sock_family = socket_family_to_scap(sa_in->sin_family); - } - break; - - case AF_INET6: - { - sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; - sock_family = socket_family_to_scap(sa_in6->sin6_family); - } - break; - - case AF_UNIX: - { - sockaddr_un *sa_un = (sockaddr_un *)sa; - sock_family = socket_family_to_scap(sa_un->sun_family); - } - break; + switch(sa->sa_family) { + case AF_INET: { + sockaddr_in *sa_in = (sockaddr_in *)sa; + sock_family = socket_family_to_scap(sa_in->sin_family); + } break; + + case AF_INET6: { + sockaddr_in6 *sa_in6 = (sockaddr_in6 *)sa; + sock_family = socket_family_to_scap(sa_in6->sin6_family); + } break; + + case AF_UNIX: { + sockaddr_un *sa_un = (sockaddr_un *)sa; + sock_family = socket_family_to_scap(sa_un->sun_family); + } break; } return sock_family; } -std::vector pack_sockaddr(sockaddr *sa) -{ +std::vector pack_sockaddr(sockaddr *sa) { std::vector res; res.push_back(get_sock_family(sa)); auto addr_port = pack_addr_port(sa); @@ -248,8 +209,7 @@ std::vector pack_sockaddr(sockaddr *sa) return res; } -std::vector pack_socktuple(sockaddr *src, sockaddr *dest) -{ +std::vector pack_socktuple(sockaddr *src, sockaddr *dest) { std::vector res; res.push_back(get_sock_family(src)); @@ -262,30 +222,29 @@ std::vector pack_socktuple(sockaddr *src, sockaddr *dest) return res; } -std::vector pack_unix_socktuple(uint64_t scr_pointer, uint64_t dst_pointer, std::string unix_path) -{ +std::vector pack_unix_socktuple(uint64_t scr_pointer, + uint64_t dst_pointer, + std::string unix_path) { std::vector res; // Assert family. res.push_back(PPM_AF_UNIX); - // Scr pointer - for (size_t i = 0; i < sizeof(scr_pointer); ++i) - { - res.push_back(scr_pointer & 0xFF); - scr_pointer >>= 8; + // Scr pointer + for(size_t i = 0; i < sizeof(scr_pointer); ++i) { + res.push_back(scr_pointer & 0xFF); + scr_pointer >>= 8; } - // Dest pointer - for (size_t i = 0; i < sizeof(dst_pointer); ++i) - { - res.push_back(dst_pointer & 0xFF); - dst_pointer >>= 8; + // Dest pointer + for(size_t i = 0; i < sizeof(dst_pointer); ++i) { + res.push_back(dst_pointer & 0xFF); + dst_pointer >>= 8; } res.insert(res.end(), unix_path.begin(), unix_path.end()); return res; } -#endif //_WIN32 __EMSCRIPTEN__ +#endif //_WIN32 __EMSCRIPTEN__ -} // namespace test_utils +} // namespace test_utils diff --git a/userspace/libsinsp/test/test_utils.h b/userspace/libsinsp/test/test_utils.h index 8b77d46e93..fc2569c931 100644 --- a/userspace/libsinsp/test/test_utils.h +++ b/userspace/libsinsp/test/test_utils.h @@ -24,7 +24,7 @@ limitations under the License. #include #if !defined(_WIN32) #include -#endif //_WIN32 +#endif //_WIN32 #include #define DEFAULT_IPV4_CLIENT_STRING "172.40.111.222" @@ -47,18 +47,19 @@ limitations under the License. #else #if !defined(_WIN32) #include -# endif //_WIN32 +#endif //_WIN32 #ifndef UNIX_PATH_MAX #define UNIX_PATH_MAX 108 #endif #endif -#define ASSERT_NAMES_EQ(a, b) \ - { \ - auto a1 = a; \ - auto b1 = b; \ - EXPECT_EQ(a1.size(), b1.size()); \ - ASSERT_EQ(std::set(a1.begin(), a1.end()), std::set(b1.begin(), b1.end())); \ +#define ASSERT_NAMES_EQ(a, b) \ + { \ + auto a1 = a; \ + auto b1 = b; \ + EXPECT_EQ(a1.size(), b1.size()); \ + ASSERT_EQ(std::set(a1.begin(), a1.end()), \ + std::set(b1.begin(), b1.end())); \ } // `merge` requires cpp17... @@ -67,8 +68,7 @@ limitations under the License. auto a1 = a; \ auto b1 = b; \ uint32_t prev_size = a1.size(); \ - for(const auto& val : b1) \ - { \ + for(const auto& val : b1) { \ a1.insert(val); \ } \ ASSERT_EQ(prev_size, a1.size()); \ @@ -80,35 +80,36 @@ limitations under the License. auto a1 = a; \ auto b1 = b; \ uint32_t prev_size = a1.size(); \ - for(const auto& val : b1) \ - { \ + for(const auto& val : b1) { \ a1.insert(val); \ } \ ASSERT_EQ(prev_size + b1.size(), a1.size()); \ } -#define ASSERT_PPM_EVENT_CODES_EQ(a, b) \ - { \ - auto a1 = a; \ - auto b1 = b; \ - EXPECT_EQ(a1.size(), b1.size()); \ - ASSERT_EQ(libsinsp::events::set(a1.begin(), a1.end()), libsinsp::events::set(b1.begin(), b1.end())); \ - ASSERT_TRUE(a1.equals(b1)); \ +#define ASSERT_PPM_EVENT_CODES_EQ(a, b) \ + { \ + auto a1 = a; \ + auto b1 = b; \ + EXPECT_EQ(a1.size(), b1.size()); \ + ASSERT_EQ(libsinsp::events::set(a1.begin(), a1.end()), \ + libsinsp::events::set(b1.begin(), b1.end())); \ + ASSERT_TRUE(a1.equals(b1)); \ } -#define ASSERT_PPM_SC_CODES_EQ(a, b) \ - { \ - auto a1 = a; \ - auto b1 = b; \ - EXPECT_EQ(a1.size(), b1.size()); \ - ASSERT_EQ(libsinsp::events::set(a1.begin(), a1.end()), libsinsp::events::set(b1.begin(), b1.end())); \ - ASSERT_TRUE(a1.equals(b1)); \ +#define ASSERT_PPM_SC_CODES_EQ(a, b) \ + { \ + auto a1 = a; \ + auto b1 = b; \ + EXPECT_EQ(a1.size(), b1.size()); \ + ASSERT_EQ(libsinsp::events::set(a1.begin(), a1.end()), \ + libsinsp::events::set(b1.begin(), b1.end())); \ + ASSERT_TRUE(a1.equals(b1)); \ } namespace test_utils { -// transform a list of strings into a single string where each element is delimited by a null (0) byte. -// the last element will also be null-terminated unless the input list is empty. +// transform a list of strings into a single string where each element is delimited by a null (0) +// byte. the last element will also be null-terminated unless the input list is empty. std::string to_null_delimited(std::vector list); // This helper is used to convert an unordered set into an ordered set. @@ -119,13 +120,15 @@ std::set unordered_set_to_ordered(std::unordered_set unordered_set); struct sockaddr_in fill_sockaddr_in(int32_t ipv4_port, const char* ipv4_string); struct sockaddr_in6 fill_sockaddr_in6(int32_t ipv6_port, const char* ipv6_string); struct sockaddr_un fill_sockaddr_un(const char* unix_path); -std::vector pack_sockaddr(sockaddr *sa); -std::vector pack_socktuple(sockaddr *src, sockaddr *dest); -std::vector pack_unix_socktuple(uint64_t scr_pointer, uint64_t dst_pointer, std::string unix_path); -#endif //_WIN32 +std::vector pack_sockaddr(sockaddr* sa); +std::vector pack_socktuple(sockaddr* src, sockaddr* dest); +std::vector pack_unix_socktuple(uint64_t scr_pointer, + uint64_t dst_pointer, + std::string unix_path); +#endif //_WIN32 -void print_bytes(uint8_t *buf, size_t size); +void print_bytes(uint8_t* buf, size_t size); std::string describe_string(const char* nullable_string); -} // namespace test_utils +} // namespace test_utils diff --git a/userspace/libsinsp/test/thread_pool.ut.cpp b/userspace/libsinsp/test/thread_pool.ut.cpp index e0c78ee076..55fc3dd599 100644 --- a/userspace/libsinsp/test/thread_pool.ut.cpp +++ b/userspace/libsinsp/test/thread_pool.ut.cpp @@ -20,65 +20,55 @@ limitations under the License. #include #if defined(ENABLE_THREAD_POOL) && !defined(__EMSCRIPTEN__) -TEST_F(sinsp_with_test_input, thread_pool) -{ - open_inspector(); +TEST_F(sinsp_with_test_input, thread_pool) { + open_inspector(); - auto tp = m_inspector.get_thread_pool(); - - ASSERT_NE(tp, nullptr); - ASSERT_EQ(tp->routines_num(), 0); + auto tp = m_inspector.get_thread_pool(); - // subscribe a routine that keeps running until unsubscribed - auto r = tp->subscribe([] - { - return true; - }); + ASSERT_NE(tp, nullptr); + ASSERT_EQ(tp->routines_num(), 0); - // check if the routine has been subscribed - ASSERT_NE(r, 0); - ASSERT_EQ(tp->routines_num(), 1); + // subscribe a routine that keeps running until unsubscribed + auto r = tp->subscribe([] { return true; }); - // check if the routine has been unsubscribed - auto res = tp->unsubscribe(r); - ASSERT_EQ(tp->routines_num(), 0); - ASSERT_EQ(res, true); + // check if the routine has been subscribed + ASSERT_NE(r, 0); + ASSERT_EQ(tp->routines_num(), 1); - // unsuccessful unsubscribe - res = tp->unsubscribe(0); - ASSERT_EQ(res, false); + // check if the routine has been unsubscribed + auto res = tp->unsubscribe(r); + ASSERT_EQ(tp->routines_num(), 0); + ASSERT_EQ(res, true); - // subscribe a routine that keeps running until a condition is met (returns false) - std::atomic count = 0; - std::atomic routine_exited = false; - r = tp->subscribe([&count, &routine_exited] - { - if(count >= 1024) - { - routine_exited = true; - return false; - } - count++; - return true; - }); - ASSERT_EQ(tp->routines_num(), 1); + // unsuccessful unsubscribe + res = tp->unsubscribe(0); + ASSERT_EQ(res, false); - // the routine above keeps increasing a counter, until the counter reaches 1024 - // we wait for the routine to exit, then we check if it has been unsubscribed - while(!routine_exited) - { - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } - ASSERT_EQ(count, 1024); - ASSERT_EQ(tp->routines_num(), 0); + // subscribe a routine that keeps running until a condition is met (returns false) + std::atomic count = 0; + std::atomic routine_exited = false; + r = tp->subscribe([&count, &routine_exited] { + if(count >= 1024) { + routine_exited = true; + return false; + } + count++; + return true; + }); + ASSERT_EQ(tp->routines_num(), 1); - // all the remaining routines should be unsubscribed when the inspector is closed - r = tp->subscribe([] - { - return true; - }); - ASSERT_EQ(tp->routines_num(), 1); - m_inspector.close(); - ASSERT_EQ(tp->routines_num(), 0); + // the routine above keeps increasing a counter, until the counter reaches 1024 + // we wait for the routine to exit, then we check if it has been unsubscribed + while(!routine_exited) { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } + ASSERT_EQ(count, 1024); + ASSERT_EQ(tp->routines_num(), 0); + + // all the remaining routines should be unsubscribed when the inspector is closed + r = tp->subscribe([] { return true; }); + ASSERT_EQ(tp->routines_num(), 1); + m_inspector.close(); + ASSERT_EQ(tp->routines_num(), 0); } -#endif \ No newline at end of file +#endif diff --git a/userspace/libsinsp/test/thread_table.ut.cpp b/userspace/libsinsp/test/thread_table.ut.cpp index 34181ae107..810e8a4889 100644 --- a/userspace/libsinsp/test/thread_table.ut.cpp +++ b/userspace/libsinsp/test/thread_table.ut.cpp @@ -20,8 +20,7 @@ limitations under the License. /* These are a sort of e2e for the sinsp state, they assert some flows in sinsp */ -TEST_F(sinsp_with_test_input, THRD_TABLE_check_default_tree) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_check_default_tree) { /* This test allow us to trust the DEFAULT TREE in other tests */ /* Instantiate the default tree */ @@ -58,8 +57,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_check_default_tree) ASSERT_THREAD_CHILDREN(p5_t2_tid, 1, 1, p6_t1_tid); } -TEST_F(sinsp_with_test_input, THRD_TABLE_missing_init_in_proc) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_missing_init_in_proc) { int64_t p1_t1_tid = 2; int64_t p1_t1_pid = 2; int64_t p1_t1_ptid = INIT_TID; @@ -76,8 +74,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_missing_init_in_proc) ASSERT_EQ(p1_t1_tinfo->m_ptid, 0); } -TEST_F(sinsp_with_test_input, THRD_TABLE_check_init_process_creation) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_check_init_process_creation) { /* Right now we have only the init process here */ add_default_init_thread(); open_inspector(); @@ -97,8 +94,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_check_init_process_creation) ASSERT_EQ(tinfo->m_tginfo->get_thread_list().front().lock().get(), tinfo); } -TEST_F(sinsp_with_test_input, THRD_TABLE_create_thread_dependencies_after_proc_scan) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_create_thread_dependencies_after_proc_scan) { /* - init * - p1_t1 * - p2_t1 @@ -180,8 +176,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_create_thread_dependencies_after_proc_s ASSERT_THREAD_INFO_PIDS(init_t3_tid, init_t3_pid, init_t3_ptid); } -TEST_F(sinsp_with_test_input, THRD_TABLE_remove_inactive_threads) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_remove_inactive_threads) { DEFAULT_TREE set_threadinfo_last_access_time(INIT_TID, 70); @@ -205,8 +200,8 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_remove_inactive_threads) set_threadinfo_last_access_time(p2_t1_tid, 20); set_threadinfo_last_access_time(p2_t3_tid, 20); - /* p2_t1 shouldn't be removed from the table since it is a leader thread and we still have some threads in that - * group while p2_t3 should be removed. + /* p2_t1 shouldn't be removed from the table since it is a leader thread and we still have some + * threads in that group while p2_t3 should be removed. */ remove_inactive_threads(80, 20); ASSERT_EQ(DEFAULT_TREE_NUM_PROCS - 1, m_inspector.m_thread_manager->get_thread_count()); @@ -214,8 +209,14 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_remove_inactive_threads) /* Calling PRCTL on an unknown thread should generate an invalid thread */ int64_t unknown_tid = 61103; - add_event_advance_ts(increasing_ts(), unknown_tid, PPME_SYSCALL_PRCTL_X, 4, (int64_t)0, - PPM_PR_GET_CHILD_SUBREAPER, "", (int64_t)0); + add_event_advance_ts(increasing_ts(), + unknown_tid, + PPME_SYSCALL_PRCTL_X, + 4, + (int64_t)0, + PPM_PR_GET_CHILD_SUBREAPER, + "", + (int64_t)0); auto unknown_tinfo = m_inspector.get_thread_ref(unknown_tid, false).get(); ASSERT_TRUE(unknown_tinfo); @@ -232,18 +233,15 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_remove_inactive_threads) ASSERT_EQ(DEFAULT_TREE_NUM_PROCS - 1, m_inspector.m_thread_manager->get_thread_count()); } -TEST_F(sinsp_with_test_input, THRD_TABLE_traverse_default_tree) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_traverse_default_tree) { /* Instantiate the default tree */ DEFAULT_TREE std::vector traverse_parents; - sinsp_threadinfo::visitor_func_t visitor = [&traverse_parents](sinsp_threadinfo* pt) - { + sinsp_threadinfo::visitor_func_t visitor = [&traverse_parents](sinsp_threadinfo* pt) { /* we stop when we reach the init parent */ traverse_parents.push_back(pt->m_tid); - if(pt->m_tid == INIT_TID) - { + if(pt->m_tid == INIT_TID) { return false; } return true; @@ -267,7 +265,10 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_traverse_default_tree) tinfo = m_inspector.get_thread_ref(p5_t2_tid, false).get(); ASSERT_TRUE(tinfo); - std::vector expected_p5_traverse_parents = {p5_t2_ptid, p4_t2_ptid, p3_t1_ptid, p2_t1_ptid}; + std::vector expected_p5_traverse_parents = {p5_t2_ptid, + p4_t2_ptid, + p3_t1_ptid, + p2_t1_ptid}; traverse_parents.clear(); tinfo->traverse_parent_state(visitor); @@ -334,8 +335,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_traverse_default_tree) /*=============================== p6_t1 traverse ===========================*/ } -TEST_F(sinsp_with_test_input, THRD_TABLE_remove_thread_group_main_thread_first) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_remove_thread_group_main_thread_first) { DEFAULT_TREE /* We remove the main thread, but it is only marked as dead */ @@ -350,8 +350,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_remove_thread_group_main_thread_first) ASSERT_MISSING_THREAD_INFO(p5_t2_tid, true) } -TEST_F(sinsp_with_test_input, THRD_TABLE_remove_thread_group_secondary_thread_first) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_remove_thread_group_secondary_thread_first) { DEFAULT_TREE /* We remove the secondary thread */ @@ -365,8 +364,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_remove_thread_group_secondary_thread_fi ASSERT_MISSING_THREAD_INFO(p5_t2_tid, true) } -TEST_F(sinsp_with_test_input, THRD_TABLE_manage_proc_exit_event_lost) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_manage_proc_exit_event_lost) { DEFAULT_TREE /* Let's imagine we miss the exit event on p5_t2. At a certain point @@ -380,8 +378,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_manage_proc_exit_event_lost) ASSERT_MISSING_THREAD_INFO(p5_t2_tid, true); } -TEST_F(sinsp_with_test_input, THRD_TABLE_ignore_not_existent_reaper) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_ignore_not_existent_reaper) { DEFAULT_TREE /* not existent reaper, our userspace logic should be able @@ -403,8 +400,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_ignore_not_existent_reaper) ASSERT_TRUE(unknonw_repaer_tinfo->is_invalid()); } -TEST_F(sinsp_with_test_input, THRD_TABLE_reparenting_in_the_default_tree) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_reparenting_in_the_default_tree) { DEFAULT_TREE /* p5_t1 has no children, when p5_t2 dies p5_t1 receives p6_t1 as child */ @@ -428,8 +424,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_reparenting_in_the_default_tree) ASSERT_THREAD_GROUP_INFO(p2_t1_pid, 3, true, 3, 3); } -TEST_F(sinsp_with_test_input, THRD_TABLE_max_table_size) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_max_table_size) { m_inspector.m_thread_manager->set_max_thread_table_size(10000); add_default_init_thread(); @@ -442,8 +437,8 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_max_table_size) /* Here we want to check that creating a number of threads grater * than m_max_thread_table_size doesn't cause a crash. */ - for(uint32_t i = 1; i < (m_inspector.m_thread_manager->get_max_thread_table_size() + 1000); i++) - { + for(uint32_t i = 1; i < (m_inspector.m_thread_manager->get_max_thread_table_size() + 1000); + i++) { /* we change only the tid */ generate_clone_x_event(0, pid + i, pid, INIT_TID, PPM_CL_CLONE_THREAD); } @@ -456,8 +451,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_max_table_size) ASSERT_THREAD_GROUP_INFO(pid, thread_group_size, false, thread_group_size, thread_group_size); } -TEST_F(sinsp_with_test_input, THRD_TABLE_many_threads_in_a_group) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_many_threads_in_a_group) { add_default_init_thread(); open_inspector(); @@ -466,8 +460,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_many_threads_in_a_group) generate_clone_x_event(0, pid, pid, INIT_TID); /* put HUGE_THREAD_NUMBER threads into the group */ - for(auto i = 1; i < HUGE_THREAD_NUMBER; i++) - { + for(auto i = 1; i < HUGE_THREAD_NUMBER; i++) { generate_clone_x_event(0, pid + i, pid, INIT_TID); } @@ -475,12 +468,12 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_many_threads_in_a_group) ASSERT_THREAD_GROUP_INFO(pid, thread_group_size, false, thread_group_size, thread_group_size); /* Only `DEFAULT_DEAD_THREADS_THRESHOLD - 1` removal, we need another one */ - for(auto i = 0; i < (DEFAULT_DEAD_THREADS_THRESHOLD - 1); i++) - { + for(auto i = 0; i < (DEFAULT_DEAD_THREADS_THRESHOLD - 1); i++) { remove_thread(pid + i, 0); } - /* we have DEFAULT_DEAD_THREADS_THRESHOLD-1 dead threads so we don't try to clean the expired ones */ + /* we have DEFAULT_DEAD_THREADS_THRESHOLD-1 dead threads so we don't try to clean the expired + * ones */ int64_t alive_threads = thread_group_size - (DEFAULT_DEAD_THREADS_THRESHOLD - 1); /* Please note that the main thread is not expired so `alive_threads+1` */ ASSERT_THREAD_GROUP_INFO(20, alive_threads, false, thread_group_size, alive_threads + 1); @@ -501,8 +494,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_many_threads_in_a_group) ASSERT_THREAD_GROUP_INFO(20, alive_threads, false, thread_group_size, alive_threads + 1); /* remove all threads in the group */ - for(int i = 0; i <= HUGE_THREAD_NUMBER; i++) - { + for(int i = 0; i <= HUGE_THREAD_NUMBER; i++) { remove_thread(pid + i, 0); } @@ -512,8 +504,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_many_threads_in_a_group) ASSERT_EQ(m_inspector.m_thread_manager->get_thread_count(), 1); } -TEST_F(sinsp_with_test_input, THRD_TABLE_add_and_remove_many_threads_in_a_group) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_add_and_remove_many_threads_in_a_group) { add_default_init_thread(); open_inspector(); @@ -522,8 +513,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_add_and_remove_many_threads_in_a_group) generate_clone_x_event(0, pid, pid, INIT_TID); /* put HUGE_THREAD_NUMBER threads into the group and remove them immediately after */ - for(auto i = 1; i < HUGE_THREAD_NUMBER; i++) - { + for(auto i = 1; i < HUGE_THREAD_NUMBER; i++) { generate_clone_x_event(0, pid + i, pid, INIT_TID); remove_thread(pid + i, 0); } @@ -537,10 +527,11 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_add_and_remove_many_threads_in_a_group) * - `-DEFAULT_DEAD_THREADS_THRESHOLD` is the first time we call the logic. To compensate * this we will do `called_logic++` at the end. */ - int called_logic = - (HUGE_THREAD_NUMBER - DEFAULT_DEAD_THREADS_THRESHOLD - 1) / (DEFAULT_DEAD_THREADS_THRESHOLD - 1); + int called_logic = (HUGE_THREAD_NUMBER - DEFAULT_DEAD_THREADS_THRESHOLD - 1) / + (DEFAULT_DEAD_THREADS_THRESHOLD - 1); called_logic++; - int remaining_threads = HUGE_THREAD_NUMBER - (called_logic * (DEFAULT_DEAD_THREADS_THRESHOLD - 1)); + int remaining_threads = + HUGE_THREAD_NUMBER - (called_logic * (DEFAULT_DEAD_THREADS_THRESHOLD - 1)); /* we should have only the main thread alive */ ASSERT_THREAD_GROUP_INFO(20, 1, false, remaining_threads, 1); @@ -549,22 +540,19 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_add_and_remove_many_threads_in_a_group) ASSERT_EQ(m_inspector.m_thread_manager->get_thread_count(), 2); } -TEST_F(sinsp_with_test_input, THRD_TABLE_many_children) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_many_children) { add_default_init_thread(); open_inspector(); int64_t tid = 20; - for(auto i = 0; i < HUGE_THREAD_NUMBER; i++) - { + for(auto i = 0; i < HUGE_THREAD_NUMBER; i++) { generate_clone_x_event(0, tid + i, tid + i, INIT_TID); } ASSERT_THREAD_CHILDREN(INIT_TID, HUGE_THREAD_NUMBER, HUGE_THREAD_NUMBER); /* Only `DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1` removal, we need another one */ - for(auto i = 0; i < (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1); i++) - { + for(auto i = 0; i < (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1); i++) { remove_thread(tid + i, 0); } @@ -586,8 +574,7 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_many_children) ASSERT_THREAD_CHILDREN(INIT_TID, alive_children + 2, alive_children); /* remove all threads */ - for(int i = 0; i <= HUGE_THREAD_NUMBER; i++) - { + for(int i = 0; i <= HUGE_THREAD_NUMBER; i++) { remove_thread(tid + i, 0); } @@ -599,32 +586,32 @@ TEST_F(sinsp_with_test_input, THRD_TABLE_many_children) * - `-DEFAULT_EXPIRED_CHILDREN_THRESHOLD` is the first time we call the logic. To compensate * this we will do `called_logic++` at the end. */ - int called_logic = - (HUGE_THREAD_NUMBER - DEFAULT_EXPIRED_CHILDREN_THRESHOLD) / (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1); + int called_logic = (HUGE_THREAD_NUMBER - DEFAULT_EXPIRED_CHILDREN_THRESHOLD) / + (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1); called_logic++; - int remaining_threads = HUGE_THREAD_NUMBER - (called_logic * (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1)); + int remaining_threads = + HUGE_THREAD_NUMBER - (called_logic * (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1)); ASSERT_THREAD_CHILDREN(INIT_TID, remaining_threads, 0); /* Only init process */ ASSERT_EQ(m_inspector.m_thread_manager->get_thread_count(), 1); } -TEST_F(sinsp_with_test_input, THRD_TABLE_add_and_remove_many_children) -{ +TEST_F(sinsp_with_test_input, THRD_TABLE_add_and_remove_many_children) { add_default_init_thread(); open_inspector(); int64_t tid = 20; - for(auto i = 0; i < HUGE_THREAD_NUMBER; i++) - { + for(auto i = 0; i < HUGE_THREAD_NUMBER; i++) { generate_clone_x_event(0, tid + i, tid + i, INIT_TID); remove_thread(tid + i, 0); } - int called_logic = - (HUGE_THREAD_NUMBER - DEFAULT_EXPIRED_CHILDREN_THRESHOLD) / (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1); + int called_logic = (HUGE_THREAD_NUMBER - DEFAULT_EXPIRED_CHILDREN_THRESHOLD) / + (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1); called_logic++; - int remaining_threads = HUGE_THREAD_NUMBER - (called_logic * (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1)); + int remaining_threads = + HUGE_THREAD_NUMBER - (called_logic * (DEFAULT_EXPIRED_CHILDREN_THRESHOLD - 1)); ASSERT_THREAD_CHILDREN(INIT_TID, remaining_threads, 0); /* Only init process */ diff --git a/userspace/libsinsp/test/token_bucket.ut.cpp b/userspace/libsinsp/test/token_bucket.ut.cpp index 94ee1c882e..b5d4df3817 100644 --- a/userspace/libsinsp/test/token_bucket.ut.cpp +++ b/userspace/libsinsp/test/token_bucket.ut.cpp @@ -3,8 +3,7 @@ #include // token bucket default ctor -TEST(token_bucket, constructor) -{ +TEST(token_bucket, constructor) { auto tb = std::make_shared(); EXPECT_EQ(tb->get_tokens(), 1); @@ -15,12 +14,10 @@ TEST(token_bucket, constructor) tb->init(1.0, max, now); EXPECT_EQ(tb->get_last_seen(), now); EXPECT_EQ(tb->get_tokens(), max); - } // token bucket ctor with custom timer -TEST(token_bucket, constructor_custom_timer) -{ +TEST(token_bucket, constructor_custom_timer) { auto t = []() -> uint64_t { return 22; }; auto tb = std::make_shared(t); @@ -29,8 +26,7 @@ TEST(token_bucket, constructor_custom_timer) } // token bucket with 2 tokens/sec rate, max 10 tokens -TEST(token_bucket, two_token_per_sec_ten_max) -{ +TEST(token_bucket, two_token_per_sec_ten_max) { auto tb = std::make_shared(); tb->init(2.0, 10, 1); @@ -42,26 +38,25 @@ TEST(token_bucket, two_token_per_sec_ten_max) EXPECT_TRUE(claimed); } - // claiming all the 7 remaining tokens - { + // claiming all the 7 remaining tokens + { bool claimed = tb->claim(7, 2000000001); EXPECT_EQ(tb->get_last_seen(), 2000000001); EXPECT_EQ(tb->get_tokens(), 0.0); EXPECT_TRUE(claimed); } - // claiming 1 token more than the 2 available fails + // claiming 1 token more than the 2 available fails { bool claimed = tb->claim(3, 3000000001); - EXPECT_EQ(tb->get_last_seen(),3000000001); + EXPECT_EQ(tb->get_last_seen(), 3000000001); EXPECT_EQ(tb->get_tokens(), 2.0); EXPECT_FALSE(claimed); } } // token bucket default initialization -TEST(token_bucket, default_init) -{ +TEST(token_bucket, default_init) { token_bucket tb; EXPECT_EQ(tb.get_tokens(), 1); } diff --git a/userspace/libsinsp/test/user.ut.cpp b/userspace/libsinsp/test/user.ut.cpp index c5a06153a8..00f9ee02a4 100644 --- a/userspace/libsinsp/test/user.ut.cpp +++ b/userspace/libsinsp/test/user.ut.cpp @@ -26,14 +26,12 @@ limitations under the License. using namespace libsinsp; -class usergroup_manager_test : public sinsp_with_test_input -{ +class usergroup_manager_test : public sinsp_with_test_input { // for gtest filtering convenience, // add something when needed }; -TEST_F(usergroup_manager_test, add_rm) -{ +TEST_F(usergroup_manager_test, add_rm) { std::string container_id{""}; sinsp_usergroup_manager mgr(&m_inspector); @@ -83,8 +81,7 @@ TEST_F(usergroup_manager_test, add_rm) // note(jasondellaluce): emscripten has issues with getpwuid #if !defined(__EMSCRIPTEN__) -TEST_F(usergroup_manager_test, system_lookup) -{ +TEST_F(usergroup_manager_test, system_lookup) { std::string container_id{""}; sinsp_usergroup_manager mgr(&m_inspector); @@ -120,14 +117,13 @@ TEST_F(usergroup_manager_test, system_lookup) } #endif -TEST_F(usergroup_manager_test, add_no_import_users) -{ +TEST_F(usergroup_manager_test, add_no_import_users) { std::string container_id{""}; sinsp_usergroup_manager mgr(&m_inspector); mgr.m_import_users = false; - auto *added_usr = mgr.add_user(container_id, -1, 37, 15, "test", "/test", "/bin/test"); + auto* added_usr = mgr.add_user(container_id, -1, 37, 15, "test", "/test", "/bin/test"); ASSERT_NE(added_usr, nullptr); ASSERT_EQ(added_usr->uid, 37); ASSERT_EQ(added_usr->gid, 15); @@ -138,7 +134,7 @@ TEST_F(usergroup_manager_test, add_no_import_users) auto* user = mgr.get_user(container_id, 37); ASSERT_EQ(user, nullptr); - auto *added_grp = mgr.add_group(container_id, -1, 15, "foo"); + auto* added_grp = mgr.add_group(container_id, -1, 15, "foo"); ASSERT_NE(added_grp, nullptr); ASSERT_EQ(added_grp->gid, 15); ASSERT_STREQ(added_grp->name, ""); @@ -149,12 +145,10 @@ TEST_F(usergroup_manager_test, add_no_import_users) // note(jasondellaluce): emscripten has issues with fgetpwent // note(therealbobo): macos doesn't define fgetpwent -#if (defined(HAVE_PWD_H) && defined(HAVE_GRP_H)) && !defined(__EMSCRIPTEN__) && !defined(__APPLE__) -class usergroup_manager_host_root_test : public sinsp_with_test_input -{ +#if(defined(HAVE_PWD_H) && defined(HAVE_GRP_H)) && !defined(__EMSCRIPTEN__) && !defined(__APPLE__) +class usergroup_manager_host_root_test : public sinsp_with_test_input { protected: - void SetUp() override - { + void SetUp() override { char pwd_buf[SCAP_MAX_PATH_SIZE]; auto pwd = getcwd(pwd_buf, SCAP_MAX_PATH_SIZE); ASSERT_NE(pwd, nullptr); @@ -179,8 +173,7 @@ class usergroup_manager_host_root_test : public sinsp_with_test_input } } - void TearDown() override - { + void TearDown() override { unlink((m_host_root + "/etc/passwd").c_str()); unlink((m_host_root + "/etc/group").c_str()); rmdir((m_host_root + "/etc").c_str()); @@ -190,8 +183,7 @@ class usergroup_manager_host_root_test : public sinsp_with_test_input std::string m_host_root; }; -TEST_F(usergroup_manager_host_root_test, host_root_lookup) -{ +TEST_F(usergroup_manager_host_root_test, host_root_lookup) { std::string container_id{""}; sinsp_usergroup_manager mgr(&m_inspector); @@ -212,9 +204,8 @@ TEST_F(usergroup_manager_host_root_test, host_root_lookup) ASSERT_STREQ(group->name, "toor"); } -TEST_F(usergroup_manager_host_root_test, nss_user_lookup) -{ - std::string container_id; // empty container_id means host +TEST_F(usergroup_manager_host_root_test, nss_user_lookup) { + std::string container_id; // empty container_id means host sinsp_usergroup_manager mgr(&m_inspector); mgr.add_user(container_id, -1, 0, 0, {}, {}, {}); diff --git a/userspace/libsinsp/thread_group_info.h b/userspace/libsinsp/thread_group_info.h index a397d96343..5f2b154d48 100644 --- a/userspace/libsinsp/thread_group_info.h +++ b/userspace/libsinsp/thread_group_info.h @@ -31,35 +31,35 @@ class sinsp_threadinfo; #define DEFAULT_DEAD_THREADS_THRESHOLD 11 /* New struct that keep information regarding the thread group */ -struct thread_group_info -{ +struct thread_group_info { public: - thread_group_info(int64_t group_pid, bool reaper, std::weak_ptr current_thread): - m_pid(group_pid), m_reaper(reaper) - { - if(current_thread.expired()) - { + thread_group_info(int64_t group_pid, + bool reaper, + std::weak_ptr current_thread): + m_pid(group_pid), + m_reaper(reaper) { + if(current_thread.expired()) { throw sinsp_exception("we cannot create a thread group info from an expired thread"); } - /* When we create the thread group info the count is 1, because we only have the creator thread */ + /* When we create the thread group info the count is 1, because we only have the creator + * thread */ m_alive_count = 1; m_threads.push_front(current_thread); }; inline void increment_thread_count() { m_alive_count++; } - inline void decrement_thread_count() - { + inline void decrement_thread_count() { m_alive_count--; /* Clean expired threads if necessary. * Please note that this is an approximation, `m_threads.size() - m_alive_count` are not the * real expired threads, they are just the ones marked as dead. For example the main thread - * of the group is marked as dead but it will be never expired until the thread group exists. + * of the group is marked as dead but it will be never expired until the thread group + * exists. */ - if((m_threads.size() - m_alive_count) >= DEFAULT_DEAD_THREADS_THRESHOLD) - { + if((m_threads.size() - m_alive_count) >= DEFAULT_DEAD_THREADS_THRESHOLD) { clean_expired_threads(); } } @@ -72,33 +72,28 @@ struct thread_group_info inline int64_t get_tgroup_pid() const { return m_pid; } - inline const std::list>& get_thread_list() const { return m_threads; } + inline const std::list>& get_thread_list() const { + return m_threads; + } - inline void add_thread_to_group(const std::shared_ptr& thread, bool main) - { + inline void add_thread_to_group(const std::shared_ptr& thread, bool main) { /* The main thread should always be the first element of the list, if present. * In this way we can efficiently obtain the main thread. */ - if(main) - { + if(main) { m_threads.push_front(thread); - } - else - { + } else { m_threads.push_back(thread); } /* we are adding a thread so we increment the count */ increment_thread_count(); } - inline void clean_expired_threads() - { + inline void clean_expired_threads() { auto thread = m_threads.begin(); - while(thread != m_threads.end()) - { + while(thread != m_threads.end()) { /* This child is expired */ - if(thread->expired()) - { + if(thread->expired()) { /* `erase` returns the pointer to the next child * no need for manual increment. */ diff --git a/userspace/libsinsp/thread_pool.h b/userspace/libsinsp/thread_pool.h index 1921e892f1..bbfd2455fc 100644 --- a/userspace/libsinsp/thread_pool.h +++ b/userspace/libsinsp/thread_pool.h @@ -22,8 +22,7 @@ limitations under the License. #include #include -class thread_pool -{ +class thread_pool { public: using routine_id_t = uintptr_t; @@ -32,30 +31,30 @@ class thread_pool virtual ~thread_pool() = default; /*! - * \brief Subscribes a routine to the thread pool. - * - * \param func The routine to be subscribed, represented by a function returning a bool value. - * Returning false causes the routine to be unsubscribed from the thread pool. - * - * \return An handle representing a specific routine. - * This can later be used to unsubscribe the routine. - */ + * \brief Subscribes a routine to the thread pool. + * + * \param func The routine to be subscribed, represented by a function returning a bool value. + * Returning false causes the routine to be unsubscribed from the thread pool. + * + * \return An handle representing a specific routine. + * This can later be used to unsubscribe the routine. + */ virtual routine_id_t subscribe(const std::function& func) = 0; /*! - * \brief Unsubscribes a routine from the thread pool. - * - * \param id A routine handle. - */ + * \brief Unsubscribes a routine from the thread pool. + * + * \param id A routine handle. + */ virtual bool unsubscribe(routine_id_t id) = 0; /*! - * \brief Unsubscribes all the subscribed routines and waits for the running ones to finish. - */ + * \brief Unsubscribes all the subscribed routines and waits for the running ones to finish. + */ virtual void purge() = 0; /*! - * \return The count of currently subscribed routines. - */ + * \return The count of currently subscribed routines. + */ virtual size_t routines_num() = 0; -}; \ No newline at end of file +}; diff --git a/userspace/libsinsp/thread_pool_bs.cpp b/userspace/libsinsp/thread_pool_bs.cpp index 429f221099..a7ee88bb2f 100644 --- a/userspace/libsinsp/thread_pool_bs.cpp +++ b/userspace/libsinsp/thread_pool_bs.cpp @@ -20,77 +20,63 @@ limitations under the License. #include -void thread_pool_bs::default_bs_tp_deleter::operator()(BS::thread_pool* __ptr) const -{ +void thread_pool_bs::default_bs_tp_deleter::operator()(BS::thread_pool* __ptr) const { std::default_delete{}(__ptr); } -thread_pool_bs::thread_pool_bs(size_t num_workers): m_pool(nullptr), m_routines() -{ - if (num_workers == 0) - { +thread_pool_bs::thread_pool_bs(size_t num_workers): m_pool(nullptr), m_routines() { + if(num_workers == 0) { m_pool = std::unique_ptr(new BS::thread_pool()); - } - else - { - m_pool = std::unique_ptr(new BS::thread_pool(num_workers)); + } else { + m_pool = std::unique_ptr( + new BS::thread_pool(num_workers)); } } -thread_pool_bs::routine_id_t thread_pool_bs::subscribe(const std::function& func) -{ +thread_pool_bs::routine_id_t thread_pool_bs::subscribe(const std::function& func) { m_routines.push_back(std::make_shared>(func)); auto& new_routine = m_routines.back(); run_routine(new_routine); - + return reinterpret_cast(new_routine.get()); } -bool thread_pool_bs::unsubscribe(thread_pool_bs::routine_id_t id) -{ +bool thread_pool_bs::unsubscribe(thread_pool_bs::routine_id_t id) { bool removed = false; - m_routines.remove_if([id, &removed](const std::shared_ptr>& v) - { - if(v.get() == reinterpret_cast*>(id)) - { - removed = true; - return true; - } + m_routines.remove_if([id, &removed](const std::shared_ptr>& v) { + if(v.get() == reinterpret_cast*>(id)) { + removed = true; + return true; + } - return false; - }); + return false; + }); return removed; } -void thread_pool_bs::purge() -{ +void thread_pool_bs::purge() { m_routines.clear(); m_pool->purge(); m_pool->wait(); } -size_t thread_pool_bs::routines_num() -{ +size_t thread_pool_bs::routines_num() { return m_routines.size(); } -void thread_pool_bs::run_routine(std::shared_ptr> routine) -{ - m_pool->detach_task([this, routine] - { - if (routine.use_count() <= 1) - { - return; - } - - if(!((*routine) && (*routine)())) - { - m_routines.remove(routine); - return; - } - - run_routine(routine); - }); -} \ No newline at end of file +void thread_pool_bs::run_routine(std::shared_ptr> routine) { + m_pool->detach_task([this, routine] { + if(routine.use_count() <= 1) { + return; + } + + if(!((*routine) && (*routine)())) { + m_routines.remove(routine); + return; + } + + run_routine(routine); + }); +} diff --git a/userspace/libsinsp/thread_pool_bs.h b/userspace/libsinsp/thread_pool_bs.h index 1b9d82afb9..065d0b5abf 100644 --- a/userspace/libsinsp/thread_pool_bs.h +++ b/userspace/libsinsp/thread_pool_bs.h @@ -19,32 +19,30 @@ limitations under the License. #include namespace BS { - class thread_pool; +class thread_pool; }; -class thread_pool_bs : public thread_pool -{ +class thread_pool_bs : public thread_pool { public: thread_pool_bs(size_t num_workers = 0); - virtual ~thread_pool_bs() - { - purge(); - } + virtual ~thread_pool_bs() { purge(); } thread_pool::routine_id_t subscribe(const std::function& func); bool unsubscribe(thread_pool::routine_id_t id); - void purge(); + void purge(); size_t routines_num(); private: - struct default_bs_tp_deleter { void operator()(BS::thread_pool* __ptr) const; }; + struct default_bs_tp_deleter { + void operator()(BS::thread_pool* __ptr) const; + }; void run_routine(std::shared_ptr> id); std::unique_ptr m_pool; std::list>> m_routines; -}; \ No newline at end of file +}; diff --git a/userspace/libsinsp/threadinfo.cpp b/userspace/libsinsp/threadinfo.cpp index 837930aa6d..66b6737aa0 100644 --- a/userspace/libsinsp/threadinfo.cpp +++ b/userspace/libsinsp/threadinfo.cpp @@ -32,8 +32,7 @@ constexpr static const char* s_thread_table_name = "threads"; extern sinsp_evttables g_infotables; -static void copy_ipv6_address(uint32_t* dest, uint32_t* src) -{ +static void copy_ipv6_address(uint32_t* dest, uint32_t* src) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; @@ -44,19 +43,19 @@ static void copy_ipv6_address(uint32_t* dest, uint32_t* src) // sinsp_threadinfo implementation /////////////////////////////////////////////////////////////////////////////// -sinsp_threadinfo::sinsp_threadinfo(sinsp* inspector, const std::shared_ptr& dyn_fields): - table_entry(dyn_fields), - m_cgroups(new cgroups_t), - m_inspector(inspector), - m_fdtable(inspector), - m_args_table_adapter("args", m_args), - m_env_table_adapter("env", m_env) -{ +sinsp_threadinfo::sinsp_threadinfo( + sinsp* inspector, + const std::shared_ptr& dyn_fields): + table_entry(dyn_fields), + m_cgroups(new cgroups_t), + m_inspector(inspector), + m_fdtable(inspector), + m_args_table_adapter("args", m_args), + m_env_table_adapter("env", m_env) { init(); } -libsinsp::state::static_struct::field_infos sinsp_threadinfo::static_fields() const -{ +libsinsp::state::static_struct::field_infos sinsp_threadinfo::static_fields() const { libsinsp::state::static_struct::field_infos ret; // todo(jasondellaluce): support missing fields that are vectors, maps, or sub-tables define_static_field(ret, this, m_tid, "tid"); @@ -111,14 +110,13 @@ libsinsp::state::static_struct::field_infos sinsp_threadinfo::static_fields() co return ret; } -void sinsp_threadinfo::init() -{ - m_pid = (uint64_t) - 1LL; - m_sid = (uint64_t) - 1LL; - m_ptid = (uint64_t) - 1LL; - m_vpgid = (uint64_t) - 1LL; +void sinsp_threadinfo::init() { + m_pid = (uint64_t)-1LL; + m_sid = (uint64_t)-1LL; + m_ptid = (uint64_t)-1LL; + m_vpgid = (uint64_t)-1LL; set_lastevent_data_validity(false); - m_reaper_tid = - 1; + m_reaper_tid = -1; m_not_expired_children = 0; m_lastevent_type = -1; m_lastevent_ts = 0; @@ -161,22 +159,18 @@ void sinsp_threadinfo::init() m_exe_from_memfd = false; } -sinsp_threadinfo::~sinsp_threadinfo() -{ - if(m_lastevent_data) - { +sinsp_threadinfo::~sinsp_threadinfo() { + if(m_lastevent_data) { free(m_lastevent_data); } } -void sinsp_threadinfo::fix_sockets_coming_from_proc() -{ +void sinsp_threadinfo::fix_sockets_coming_from_proc() { m_fdtable.loop([this](int64_t fd, sinsp_fdinfo& fdi) { - if(fdi.m_type == SCAP_FD_IPV4_SOCK) - { - if(m_inspector->m_thread_manager->m_server_ports.find(fdi.m_sockinfo.m_ipv4info.m_fields.m_sport) != - m_inspector->m_thread_manager->m_server_ports.end()) - { + if(fdi.m_type == SCAP_FD_IPV4_SOCK) { + if(m_inspector->m_thread_manager->m_server_ports.find( + fdi.m_sockinfo.m_ipv4info.m_fields.m_sport) != + m_inspector->m_thread_manager->m_server_ports.end()) { uint32_t tip; uint16_t tport; @@ -185,15 +179,16 @@ void sinsp_threadinfo::fix_sockets_coming_from_proc() fdi.m_sockinfo.m_ipv4info.m_fields.m_sip = fdi.m_sockinfo.m_ipv4info.m_fields.m_dip; fdi.m_sockinfo.m_ipv4info.m_fields.m_dip = tip; - fdi.m_sockinfo.m_ipv4info.m_fields.m_sport = fdi.m_sockinfo.m_ipv4info.m_fields.m_dport; + fdi.m_sockinfo.m_ipv4info.m_fields.m_sport = + fdi.m_sockinfo.m_ipv4info.m_fields.m_dport; fdi.m_sockinfo.m_ipv4info.m_fields.m_dport = tport; - fdi.m_name = ipv4tuple_to_string(&fdi.m_sockinfo.m_ipv4info, m_inspector->is_hostname_and_port_resolution_enabled()); + fdi.m_name = + ipv4tuple_to_string(&fdi.m_sockinfo.m_ipv4info, + m_inspector->is_hostname_and_port_resolution_enabled()); fdi.set_role_server(); - } - else - { + } else { fdi.set_role_client(); } } @@ -208,8 +203,7 @@ void sinsp_threadinfo::fix_sockets_coming_from_proc() #define MAX_PROG_HASH_LEN 1024 -void sinsp_threadinfo::compute_program_hash() -{ +void sinsp_threadinfo::compute_program_hash() { auto curr_hash = std::hash()(m_exe); hash_combine(curr_hash, m_container_id); auto rem_len = MAX_PROG_HASH_LEN - (m_exe.size() + m_container_id.size()); @@ -222,10 +216,8 @@ void sinsp_threadinfo::compute_program_hash() // // The program hash includes the arguments as well // - for (auto arg = m_args.begin(); arg != m_args.end() && rem_len > 0; ++arg) - { - if (arg->size() >= rem_len) - { + for(auto arg = m_args.begin(); arg != m_args.end() && rem_len > 0; ++arg) { + if(arg->size() >= rem_len) { auto partial_str = arg->substr(0, rem_len); hash_combine(curr_hash, partial_str); break; @@ -240,28 +232,22 @@ void sinsp_threadinfo::compute_program_hash() // For some specific processes (essentially the scripting languages) // we include the arguments in the scripts hash as well // - if(m_comm.size() == 4) - { + if(m_comm.size() == 4) { uint32_t ncomm; memcpy(&ncomm, m_comm.c_str(), 4); - if(ncomm == STR_AS_NUM_JAVA || ncomm == STR_AS_NUM_RUBY || - ncomm == STR_AS_NUM_PERL || ncomm == STR_AS_NUM_NODE) - { + if(ncomm == STR_AS_NUM_JAVA || ncomm == STR_AS_NUM_RUBY || ncomm == STR_AS_NUM_PERL || + ncomm == STR_AS_NUM_NODE) { m_program_hash_scripts = m_program_hash; } - } - else if(m_comm.size() >= 6) - { - if(m_comm.substr(0, 6) == "python") - { + } else if(m_comm.size() >= 6) { + if(m_comm.substr(0, 6) == "python") { m_program_hash_scripts = m_program_hash; } } } -void sinsp_threadinfo::add_fd_from_scap(scap_fdinfo *fdi) -{ +void sinsp_threadinfo::add_fd_from_scap(scap_fdinfo* fdi) { auto newfdi = m_inspector->build_fdinfo(); bool do_add = true; @@ -272,41 +258,44 @@ void sinsp_threadinfo::add_fd_from_scap(scap_fdinfo *fdi) newfdi->m_ino = fdi->ino; newfdi->m_fd = fdi->fd; - switch(newfdi->m_type) - { + switch(newfdi->m_type) { case SCAP_FD_IPV4_SOCK: newfdi->m_sockinfo.m_ipv4info.m_fields.m_sip = fdi->info.ipv4info.sip; newfdi->m_sockinfo.m_ipv4info.m_fields.m_dip = fdi->info.ipv4info.dip; newfdi->m_sockinfo.m_ipv4info.m_fields.m_sport = fdi->info.ipv4info.sport; newfdi->m_sockinfo.m_ipv4info.m_fields.m_dport = fdi->info.ipv4info.dport; newfdi->m_sockinfo.m_ipv4info.m_fields.m_l4proto = fdi->info.ipv4info.l4proto; - if(fdi->info.ipv4info.l4proto == SCAP_L4_TCP) - { + if(fdi->info.ipv4info.l4proto == SCAP_L4_TCP) { newfdi->m_flags |= sinsp_fdinfo::FLAGS_SOCKET_CONNECTED; } m_inspector->get_ifaddr_list().update_fd(*newfdi); - newfdi->m_name = ipv4tuple_to_string(&newfdi->m_sockinfo.m_ipv4info, m_inspector->is_hostname_and_port_resolution_enabled()); + newfdi->m_name = + ipv4tuple_to_string(&newfdi->m_sockinfo.m_ipv4info, + m_inspector->is_hostname_and_port_resolution_enabled()); break; case SCAP_FD_IPV4_SERVSOCK: newfdi->m_sockinfo.m_ipv4serverinfo.m_ip = fdi->info.ipv4serverinfo.ip; newfdi->m_sockinfo.m_ipv4serverinfo.m_port = fdi->info.ipv4serverinfo.port; newfdi->m_sockinfo.m_ipv4serverinfo.m_l4proto = fdi->info.ipv4serverinfo.l4proto; - newfdi->m_name = ipv4serveraddr_to_string(&newfdi->m_sockinfo.m_ipv4serverinfo, m_inspector->is_hostname_and_port_resolution_enabled()); + newfdi->m_name = + ipv4serveraddr_to_string(&newfdi->m_sockinfo.m_ipv4serverinfo, + m_inspector->is_hostname_and_port_resolution_enabled()); // // We keep note of all the host bound server ports. // We'll need them later when patching connections direction. // - m_inspector->m_thread_manager->m_server_ports.insert(newfdi->m_sockinfo.m_ipv4serverinfo.m_port); + m_inspector->m_thread_manager->m_server_ports.insert( + newfdi->m_sockinfo.m_ipv4serverinfo.m_port); break; case SCAP_FD_IPV6_SOCK: if(sinsp_utils::is_ipv4_mapped_ipv6((uint8_t*)&fdi->info.ipv6info.sip) && - sinsp_utils::is_ipv4_mapped_ipv6((uint8_t*)&fdi->info.ipv6info.dip)) - { + sinsp_utils::is_ipv4_mapped_ipv6((uint8_t*)&fdi->info.ipv6info.dip)) { // - // This is an IPv4-mapped IPv6 addresses (http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses). - // Convert it into the IPv4 representation. + // This is an IPv4-mapped IPv6 addresses + // (http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses). Convert it into the + // IPv4 representation. // newfdi->m_type = SCAP_FD_IPV4_SOCK; newfdi->m_sockinfo.m_ipv4info.m_fields.m_sip = fdi->info.ipv6info.sip[3]; @@ -314,50 +303,53 @@ void sinsp_threadinfo::add_fd_from_scap(scap_fdinfo *fdi) newfdi->m_sockinfo.m_ipv4info.m_fields.m_sport = fdi->info.ipv6info.sport; newfdi->m_sockinfo.m_ipv4info.m_fields.m_dport = fdi->info.ipv6info.dport; newfdi->m_sockinfo.m_ipv4info.m_fields.m_l4proto = fdi->info.ipv6info.l4proto; - if(fdi->info.ipv6info.l4proto == SCAP_L4_TCP) - { + if(fdi->info.ipv6info.l4proto == SCAP_L4_TCP) { newfdi->m_flags |= sinsp_fdinfo::FLAGS_SOCKET_CONNECTED; } m_inspector->get_ifaddr_list().update_fd(*newfdi); - newfdi->m_name = ipv4tuple_to_string(&newfdi->m_sockinfo.m_ipv4info, m_inspector->is_hostname_and_port_resolution_enabled()); - } - else - { - copy_ipv6_address(newfdi->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b, fdi->info.ipv6info.sip); - copy_ipv6_address(newfdi->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b, fdi->info.ipv6info.dip); + newfdi->m_name = + ipv4tuple_to_string(&newfdi->m_sockinfo.m_ipv4info, + m_inspector->is_hostname_and_port_resolution_enabled()); + } else { + copy_ipv6_address(newfdi->m_sockinfo.m_ipv6info.m_fields.m_sip.m_b, + fdi->info.ipv6info.sip); + copy_ipv6_address(newfdi->m_sockinfo.m_ipv6info.m_fields.m_dip.m_b, + fdi->info.ipv6info.dip); newfdi->m_sockinfo.m_ipv6info.m_fields.m_sport = fdi->info.ipv6info.sport; newfdi->m_sockinfo.m_ipv6info.m_fields.m_dport = fdi->info.ipv6info.dport; newfdi->m_sockinfo.m_ipv6info.m_fields.m_l4proto = fdi->info.ipv6info.l4proto; - if(fdi->info.ipv6info.l4proto == SCAP_L4_TCP) - { + if(fdi->info.ipv6info.l4proto == SCAP_L4_TCP) { newfdi->m_flags |= sinsp_fdinfo::FLAGS_SOCKET_CONNECTED; } - newfdi->m_name = ipv6tuple_to_string(&newfdi->m_sockinfo.m_ipv6info, m_inspector->is_hostname_and_port_resolution_enabled()); + newfdi->m_name = + ipv6tuple_to_string(&newfdi->m_sockinfo.m_ipv6info, + m_inspector->is_hostname_and_port_resolution_enabled()); } break; case SCAP_FD_IPV6_SERVSOCK: - copy_ipv6_address(newfdi->m_sockinfo.m_ipv6serverinfo.m_ip.m_b, fdi->info.ipv6serverinfo.ip); + copy_ipv6_address(newfdi->m_sockinfo.m_ipv6serverinfo.m_ip.m_b, + fdi->info.ipv6serverinfo.ip); newfdi->m_sockinfo.m_ipv6serverinfo.m_port = fdi->info.ipv6serverinfo.port; newfdi->m_sockinfo.m_ipv6serverinfo.m_l4proto = fdi->info.ipv6serverinfo.l4proto; - newfdi->m_name = ipv6serveraddr_to_string(&newfdi->m_sockinfo.m_ipv6serverinfo, m_inspector->is_hostname_and_port_resolution_enabled()); + newfdi->m_name = + ipv6serveraddr_to_string(&newfdi->m_sockinfo.m_ipv6serverinfo, + m_inspector->is_hostname_and_port_resolution_enabled()); // // We keep note of all the host bound server ports. // We'll need them later when patching connections direction. // - m_inspector->m_thread_manager->m_server_ports.insert(newfdi->m_sockinfo.m_ipv6serverinfo.m_port); + m_inspector->m_thread_manager->m_server_ports.insert( + newfdi->m_sockinfo.m_ipv6serverinfo.m_port); break; case SCAP_FD_UNIX_SOCK: newfdi->m_sockinfo.m_unixinfo.m_fields.m_source = fdi->info.unix_socket_info.source; newfdi->m_sockinfo.m_unixinfo.m_fields.m_dest = fdi->info.unix_socket_info.destination; newfdi->m_name = fdi->info.unix_socket_info.fname; - if(newfdi->m_name.empty()) - { + if(newfdi->m_name.empty()) { newfdi->set_role_client(); - } - else - { + } else { newfdi->set_role_server(); } break; @@ -390,18 +382,15 @@ void sinsp_threadinfo::add_fd_from_scap(scap_fdinfo *fdi) break; } - // // Add the FD to the table // - if(!do_add) - { + if(!do_add) { return; } auto addedfdi = m_fdtable.add(fdi->fd, std::move(newfdi)); - if(m_inspector->m_filter != nullptr && m_inspector->is_capture()) - { + if(m_inspector->m_filter != nullptr && m_inspector->is_capture()) { // in case the inspector is configured with an internal filter, we can // filter-out thread infos (and their fd infos) to not dump them in // captures unless actually used. Here, we simulate an internal event @@ -433,14 +422,11 @@ void sinsp_threadinfo::add_fd_from_scap(scap_fdinfo *fdi) int64_t tlefd = tevt.get_tinfo()->m_lastevent_fd; tevt.get_tinfo()->m_lastevent_fd = fdi->fd; - if(m_inspector->m_filter->run(&tevt)) - { + if(m_inspector->m_filter->run(&tevt)) { // we mark the thread info as non-filterable due to one event // using one of its file descriptor has passed the filter m_filtered_out = false; - } - else - { + } else { // we can't say if the thread info for this fd is filterable or not, // but we can mark the given file descriptor as filterable. This flag // will prevent the fd info from being written in captures. @@ -452,8 +438,7 @@ void sinsp_threadinfo::add_fd_from_scap(scap_fdinfo *fdi) } } -void sinsp_threadinfo::init(scap_threadinfo* pi) -{ +void sinsp_threadinfo::init(scap_threadinfo* pi) { init(); m_tid = pi->tid; @@ -476,13 +461,13 @@ void sinsp_threadinfo::init(scap_threadinfo* pi) m_not_expired_children = 0; set_args(pi->args, pi->args_len); - if(is_main_thread()) - { + if(is_main_thread()) { set_env(pi->env, pi->env_len); update_cwd({pi->cwd}); } m_flags |= pi->flags; - m_flags |= PPM_CL_ACTIVE; // Assume that all the threads coming from /proc are real, active threads + m_flags |= PPM_CL_ACTIVE; // Assume that all the threads coming from /proc are real, active + // threads m_fdtable.clear(); m_fdtable.set_tid(m_tid); m_fdlimit = pi->fdlimit; @@ -513,36 +498,33 @@ void sinsp_threadinfo::init(scap_threadinfo* pi) set_cgroups(pi->cgroups.path, pi->cgroups.len); m_root = pi->root; ASSERT(m_inspector); - m_inspector->m_container_manager.resolve_container(this, m_inspector->is_live() || m_inspector->is_syscall_plugin()); + m_inspector->m_container_manager.resolve_container( + this, + m_inspector->is_live() || m_inspector->is_syscall_plugin()); set_group(pi->gid); set_user(pi->uid); set_loginuser((uint32_t)pi->loginuid); } -void sinsp_threadinfo::set_user(uint32_t uid) -{ - scap_userinfo *user = m_inspector->m_usergroup_manager.get_user(m_container_id, uid); - if (!user) - { +void sinsp_threadinfo::set_user(uint32_t uid) { + scap_userinfo* user = m_inspector->m_usergroup_manager.get_user(m_container_id, uid); + if(!user) { auto notify = m_inspector->is_live() || m_inspector->is_syscall_plugin(); - user = m_inspector->m_usergroup_manager.add_user(m_container_id, m_pid, uid, m_group.gid(), {}, {}, {}, notify); + user = m_inspector->m_usergroup_manager + .add_user(m_container_id, m_pid, uid, m_group.gid(), {}, {}, {}, notify); } - if (user) - { + if(user) { m_user.set_uid(user->uid); m_user.set_gid(m_group.gid()); - if (m_inspector->is_user_details_enabled()) - { + if(m_inspector->is_user_details_enabled()) { m_user.set_name(user->name, strnlen(user->name, MAX_CREDENTIALS_STR_LEN)); m_user.set_homedir(user->homedir, strnlen(user->homedir, MAX_CREDENTIALS_STR_LEN)); m_user.set_shell(user->shell, strnlen(user->shell, MAX_CREDENTIALS_STR_LEN)); } - } - else - { + } else { // No need to set name/homedir/shell, the default values from // sinsp_userinfo are going to be used. m_user.set_uid(uid); @@ -550,25 +532,19 @@ void sinsp_threadinfo::set_user(uint32_t uid) } } -void sinsp_threadinfo::set_group(uint32_t gid) -{ - scap_groupinfo *group = m_inspector->m_usergroup_manager.get_group(m_container_id, gid); - if (!group) - { +void sinsp_threadinfo::set_group(uint32_t gid) { + scap_groupinfo* group = m_inspector->m_usergroup_manager.get_group(m_container_id, gid); + if(!group) { auto notify = m_inspector->is_live() || m_inspector->is_syscall_plugin(); group = m_inspector->m_usergroup_manager.add_group(m_container_id, m_pid, gid, {}, notify); } - if (group) - { + if(group) { m_group.set_gid(group->gid); - if (m_inspector->is_user_details_enabled()) - { + if(m_inspector->is_user_details_enabled()) { m_group.set_name(group->name, strnlen(group->name, MAX_CREDENTIALS_STR_LEN)); } - } - else - { + } else { // No need to set name/homedir/shell, the default values from // sinsp_userinfo are going to be used. m_group.set_gid(gid); @@ -576,24 +552,22 @@ void sinsp_threadinfo::set_group(uint32_t gid) m_user.set_gid(m_group.gid()); } -void sinsp_threadinfo::set_loginuser(uint32_t loginuid) -{ - scap_userinfo *login_user = m_inspector->m_usergroup_manager.get_user(m_container_id, loginuid); +void sinsp_threadinfo::set_loginuser(uint32_t loginuid) { + scap_userinfo* login_user = m_inspector->m_usergroup_manager.get_user(m_container_id, loginuid); - if (login_user) - { + if(login_user) { m_loginuser.set_uid(login_user->uid); m_loginuser.set_gid(m_group.gid()); - if (m_inspector->is_user_details_enabled()) - { - m_loginuser.set_name(login_user->name, strnlen(login_user->name, MAX_CREDENTIALS_STR_LEN)); - m_loginuser.set_homedir(login_user->homedir, strnlen(login_user->homedir, MAX_CREDENTIALS_STR_LEN)); - m_loginuser.set_shell(login_user->shell, strnlen(login_user->shell, MAX_CREDENTIALS_STR_LEN)); + if(m_inspector->is_user_details_enabled()) { + m_loginuser.set_name(login_user->name, + strnlen(login_user->name, MAX_CREDENTIALS_STR_LEN)); + m_loginuser.set_homedir(login_user->homedir, + strnlen(login_user->homedir, MAX_CREDENTIALS_STR_LEN)); + m_loginuser.set_shell(login_user->shell, + strnlen(login_user->shell, MAX_CREDENTIALS_STR_LEN)); } - } - else - { + } else { // No need to set name/homedir/shell, the default values from // sinsp_userinfo are going to be used. m_loginuser.set_uid(loginuid); @@ -601,10 +575,8 @@ void sinsp_threadinfo::set_loginuser(uint32_t loginuid) } } -sinsp_threadinfo::cgroups_t& sinsp_threadinfo::cgroups() const -{ - if(m_cgroups) - { +sinsp_threadinfo::cgroups_t& sinsp_threadinfo::cgroups() const { + if(m_cgroups) { return *m_cgroups; } @@ -612,53 +584,51 @@ sinsp_threadinfo::cgroups_t& sinsp_threadinfo::cgroups() const return empty; } -std::string sinsp_threadinfo::get_comm() const -{ +std::string sinsp_threadinfo::get_comm() const { return m_comm; } -std::string sinsp_threadinfo::get_exe() const -{ +std::string sinsp_threadinfo::get_exe() const { return m_exe; } -std::string sinsp_threadinfo::get_exepath() const -{ +std::string sinsp_threadinfo::get_exepath() const { return m_exepath; } -void sinsp_threadinfo::set_args(const char* args, size_t len) -{ - if (len > 0 && args[len - 1] == '\0') - { +void sinsp_threadinfo::set_args(const char* args, size_t len) { + if(len > 0 && args[len - 1] == '\0') { len--; } set_args(sinsp_split({args, len}, '\0')); } -void sinsp_threadinfo::set_args(const std::vector& args) -{ +void sinsp_threadinfo::set_args(const std::vector& args) { m_args = args; } -void sinsp_threadinfo::set_env(const char* env, size_t len) -{ - if (len == SCAP_MAX_ENV_SIZE && m_inspector->large_envs_enabled()) - { +void sinsp_threadinfo::set_env(const char* env, size_t len) { + if(len == SCAP_MAX_ENV_SIZE && m_inspector->large_envs_enabled()) { // the environment is possibly truncated, try to read from /proc // this may fail for short-lived processes - if (set_env_from_proc()) - { - libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, "Large environment for process %lu [%s], loaded from /proc", m_pid, m_comm.c_str()); + if(set_env_from_proc()) { + libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, + "Large environment for process %lu [%s], loaded from /proc", + m_pid, + m_comm.c_str()); return; } else { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "Failed to load environment for process %lu [%s] from /proc, using first %d bytes", m_pid, m_comm.c_str(), SCAP_MAX_ENV_SIZE); + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "Failed to load environment for process %lu [%s] from /proc, " + "using first %d bytes", + m_pid, + m_comm.c_str(), + SCAP_MAX_ENV_SIZE); } } - if (len > 0 && env[len - 1] == '\0') - { + if(len > 0 && env[len - 1] == '\0') { len--; } @@ -666,21 +636,20 @@ void sinsp_threadinfo::set_env(const char* env, size_t len) } bool sinsp_threadinfo::set_env_from_proc() { - std::string environ_path = std::string(scap_get_host_root()) + "/proc/" + std::to_string(m_pid) + "/environ"; + std::string environ_path = + std::string(scap_get_host_root()) + "/proc/" + std::to_string(m_pid) + "/environ"; std::ifstream environment(environ_path); - if (!environment) - { + if(!environment) { // failed to read the environment from /proc, work with what we have return false; } m_env.clear(); - while (environment) { + while(environment) { std::string env; getline(environment, env, '\0'); - if (!env.empty()) - { + if(!env.empty()) { m_env.emplace_back(env); } } @@ -688,21 +657,14 @@ bool sinsp_threadinfo::set_env_from_proc() { return true; } -const std::vector& sinsp_threadinfo::get_env() -{ - if(is_main_thread()) - { +const std::vector& sinsp_threadinfo::get_env() { + if(is_main_thread()) { return m_env; - } - else - { + } else { auto mtinfo = get_main_thread(); - if(mtinfo != nullptr) - { + if(mtinfo != nullptr) { return mtinfo->get_env(); - } - else - { + } else { // it should never happen but provide a safe fallback just in case // except during sinsp::scap_open() (see sinsp::get_thread()). return m_env; @@ -711,17 +673,14 @@ const std::vector& sinsp_threadinfo::get_env() } // Return value string for the exact environment variable name given -std::string sinsp_threadinfo::get_env(const std::string& name) -{ +std::string sinsp_threadinfo::get_env(const std::string& name) { size_t nlen = name.length(); - for(const auto& env_var : get_env()) - { + for(const auto& env_var : get_env()) { if((env_var.length() > (nlen + 1)) && (env_var[nlen] == '=') && - !env_var.compare(0, nlen, name)) - { + !env_var.compare(0, nlen, name)) { // Stripping spaces, not sure if we really should or need to size_t first = env_var.find_first_not_of(' ', nlen + 1); - if (first == std::string::npos) + if(first == std::string::npos) return ""; size_t last = env_var.find_last_not_of(' '); @@ -732,18 +691,15 @@ std::string sinsp_threadinfo::get_env(const std::string& name) return ""; } -std::string sinsp_threadinfo::concatenate_all_env() -{ +std::string sinsp_threadinfo::concatenate_all_env() { const auto& all_env = get_env(); - if(all_env.size() == 0) - { + if(all_env.size() == 0) { return ""; } // Here we have at least one env so we can pop the last character at the end of the loop. std::string concatenate_env; - for(const auto& env_var : all_env) - { + for(const auto& env_var : all_env) { concatenate_env += env_var; concatenate_env += ' '; } @@ -751,25 +707,20 @@ std::string sinsp_threadinfo::concatenate_all_env() return concatenate_env; } -void sinsp_threadinfo::set_cgroups(const char* cgroups, size_t len) -{ - if (len > 0 && cgroups[len - 1] == '\0') - { +void sinsp_threadinfo::set_cgroups(const char* cgroups, size_t len) { + if(len > 0 && cgroups[len - 1] == '\0') { len--; } set_cgroups(sinsp_split({cgroups, len}, '\0')); } -void sinsp_threadinfo::set_cgroups(const std::vector& cgroups) -{ +void sinsp_threadinfo::set_cgroups(const std::vector& cgroups) { auto tmp_cgroups = std::make_unique(); - for(const auto &def : cgroups) - { + for(const auto& def : cgroups) { std::string::size_type eq_pos = def.find("="); - if (eq_pos == std::string::npos) - { + if(eq_pos == std::string::npos) { return; } @@ -777,21 +728,15 @@ void sinsp_threadinfo::set_cgroups(const std::vector& cgroups) std::string cgroup = def.substr(eq_pos + 1); size_t pos = subsys.find("_cgroup"); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { subsys.erase(pos, sizeof("_cgroup") - 1); } - if(subsys == "perf") - { + if(subsys == "perf") { subsys = "perf_event"; - } - else if(subsys == "mem") - { + } else if(subsys == "mem") { subsys = "memory"; - } - else if(subsys == "io") - { + } else if(subsys == "io") { // blkio has been renamed just `io` // in kernel space: // https://github.com/torvalds/linux/commit/c165b3e3c7bb68c2ed55a5ac2623f030d01d9567 @@ -804,16 +749,13 @@ void sinsp_threadinfo::set_cgroups(const std::vector& cgroups) m_cgroups.swap(tmp_cgroups); } -sinsp_threadinfo* sinsp_threadinfo::get_parent_thread() -{ +sinsp_threadinfo* sinsp_threadinfo::get_parent_thread() { return m_inspector->get_thread_ref(m_ptid, false).get(); } -sinsp_fdinfo* sinsp_threadinfo::add_fd(int64_t fd, std::unique_ptr fdinfo) -{ +sinsp_fdinfo* sinsp_threadinfo::add_fd(int64_t fd, std::unique_ptr fdinfo) { sinsp_fdtable* fd_table_ptr = get_fd_table(); - if(fd_table_ptr == NULL) - { + if(fd_table_ptr == NULL) { ASSERT(false); return NULL; } @@ -827,22 +769,18 @@ sinsp_fdinfo* sinsp_threadinfo::add_fd(int64_t fd, std::unique_ptr return res; } -void sinsp_threadinfo::remove_fd(int64_t fd) -{ +void sinsp_threadinfo::remove_fd(int64_t fd) { sinsp_fdtable* fd_table_ptr = get_fd_table(); - if(fd_table_ptr == NULL) - { + if(fd_table_ptr == NULL) { ASSERT(false); return; } fd_table_ptr->erase(fd); } -bool sinsp_threadinfo::loop_fds(sinsp_fdtable::fdtable_const_visitor_t visitor) -{ +bool sinsp_threadinfo::loop_fds(sinsp_fdtable::fdtable_const_visitor_t visitor) { sinsp_fdtable* fdt = get_fd_table(); - if(fdt == NULL) - { + if(fdt == NULL) { ASSERT(false); return false; } @@ -850,30 +788,23 @@ bool sinsp_threadinfo::loop_fds(sinsp_fdtable::fdtable_const_visitor_t visitor) return fdt->const_loop(visitor); } -bool sinsp_threadinfo::is_bound_to_port(uint16_t number) const -{ +bool sinsp_threadinfo::is_bound_to_port(uint16_t number) const { const sinsp_fdtable* fdt = get_fd_table(); - if(fdt == NULL) - { + if(fdt == NULL) { ASSERT(false); return false; } bool ret = false; fdt->const_loop([&](int64_t fd, const sinsp_fdinfo& fdi) { - if(fdi.m_type == SCAP_FD_IPV4_SOCK) - { - if(fdi.m_sockinfo.m_ipv4info.m_fields.m_dport == number) - { + if(fdi.m_type == SCAP_FD_IPV4_SOCK) { + if(fdi.m_sockinfo.m_ipv4info.m_fields.m_dport == number) { // set result and break out of the loop ret = true; return false; } - } - else if(fdi.m_type == SCAP_FD_IPV4_SERVSOCK) - { - if(fdi.m_sockinfo.m_ipv4serverinfo.m_port == number) - { + } else if(fdi.m_type == SCAP_FD_IPV4_SERVSOCK) { + if(fdi.m_sockinfo.m_ipv4serverinfo.m_port == number) { // set result and break out of the loop ret = true; return false; @@ -885,21 +816,17 @@ bool sinsp_threadinfo::is_bound_to_port(uint16_t number) const return ret; } -bool sinsp_threadinfo::uses_client_port(uint16_t number) const -{ +bool sinsp_threadinfo::uses_client_port(uint16_t number) const { const sinsp_fdtable* fdt = get_fd_table(); - if(fdt == NULL) - { + if(fdt == NULL) { ASSERT(false); return false; } bool ret = false; fdt->const_loop([&](int64_t fd, const sinsp_fdinfo& fdi) { - if(fdi.m_type == SCAP_FD_IPV4_SOCK) - { - if(fdi.m_sockinfo.m_ipv4info.m_fields.m_sport == number) - { + if(fdi.m_type == SCAP_FD_IPV4_SOCK) { + if(fdi.m_sockinfo.m_ipv4info.m_fields.m_sport == number) { // set result and break out of the loop ret = true; return false; @@ -911,25 +838,19 @@ bool sinsp_threadinfo::uses_client_port(uint16_t number) const return ret; } -bool sinsp_threadinfo::is_lastevent_data_valid() const -{ - return (m_lastevent_cpuid != (uint16_t) - 1); +bool sinsp_threadinfo::is_lastevent_data_valid() const { + return (m_lastevent_cpuid != (uint16_t)-1); } -sinsp_threadinfo* sinsp_threadinfo::get_cwd_root() -{ - if(!(m_flags & PPM_CL_CLONE_FS)) - { +sinsp_threadinfo* sinsp_threadinfo::get_cwd_root() { + if(!(m_flags & PPM_CL_CLONE_FS)) { return this; - } - else - { + } else { return get_main_thread(); } } -std::string sinsp_threadinfo::get_cwd() -{ +std::string sinsp_threadinfo::get_cwd() { // Ideally we should use get_cwd_root() // but scap does not read CLONE_FS from /proc // Also glibc and muslc use always @@ -937,106 +858,79 @@ std::string sinsp_threadinfo::get_cwd() // get_main_thread() for now sinsp_threadinfo* tinfo = get_main_thread(); - if(tinfo) - { + if(tinfo) { return tinfo->m_cwd; - } - else - { - ///todo(@Andreagit97) not sure we want to return "./" it seems like a valid path + } else { + /// todo(@Andreagit97) not sure we want to return "./" it seems like a valid path return "./"; } } -void sinsp_threadinfo::update_cwd(std::string_view cwd) -{ +void sinsp_threadinfo::update_cwd(std::string_view cwd) { sinsp_threadinfo* tinfo = get_main_thread(); - if (tinfo == nullptr) - { + if(tinfo == nullptr) { return; } tinfo->m_cwd = sinsp_utils::concatenate_paths(m_cwd, cwd); - if(tinfo->m_cwd.empty() || tinfo->m_cwd.back() != '/') - { + if(tinfo->m_cwd.empty() || tinfo->m_cwd.back() != '/') { tinfo->m_cwd += '/'; } } -uint64_t sinsp_threadinfo::get_fd_usage_pct() -{ +uint64_t sinsp_threadinfo::get_fd_usage_pct() { int64_t fdlimit = get_fd_limit(); - if(fdlimit > 0) - { + if(fdlimit > 0) { uint64_t fd_opencount = get_fd_opencount(); - ASSERT(fd_opencount <= (uint64_t) fdlimit); - if(fd_opencount <= (uint64_t) fdlimit) - { + ASSERT(fd_opencount <= (uint64_t)fdlimit); + if(fd_opencount <= (uint64_t)fdlimit) { return (fd_opencount * 100) / fdlimit; - } - else - { + } else { return 100; } - } - else - { + } else { return 0; } } -double sinsp_threadinfo::get_fd_usage_pct_d() -{ +double sinsp_threadinfo::get_fd_usage_pct_d() { int64_t fdlimit = get_fd_limit(); - if(fdlimit > 0) - { + if(fdlimit > 0) { uint64_t fd_opencount = get_fd_opencount(); - ASSERT(fd_opencount <= (uint64_t) fdlimit); - if(fd_opencount <= (uint64_t) fdlimit) - { + ASSERT(fd_opencount <= (uint64_t)fdlimit); + if(fd_opencount <= (uint64_t)fdlimit) { return ((double)fd_opencount * 100) / fdlimit; - } - else - { + } else { return 100; } - } - else - { + } else { return 0; } } -uint64_t sinsp_threadinfo::get_fd_opencount() const -{ +uint64_t sinsp_threadinfo::get_fd_opencount() const { auto main_thread = get_main_thread(); - if(main_thread == nullptr) - { + if(main_thread == nullptr) { return 0; } return main_thread->get_fdtable().size(); } -uint64_t sinsp_threadinfo::get_fd_limit() -{ +uint64_t sinsp_threadinfo::get_fd_limit() { auto main_thread = get_main_thread(); - if(main_thread == nullptr) - { + if(main_thread == nullptr) { return 0; } return main_thread->m_fdlimit; } -const std::string& sinsp_threadinfo::get_cgroup(const std::string& subsys) const -{ +const std::string& sinsp_threadinfo::get_cgroup(const std::string& subsys) const { static const std::string notfound = "/"; - for(const auto& it : cgroups()) - { - if(it.first == subsys) - { + for(const auto& it : cgroups()) { + if(it.first == subsys) { return it.second; } } @@ -1044,12 +938,9 @@ const std::string& sinsp_threadinfo::get_cgroup(const std::string& subsys) const return notfound; } -bool sinsp_threadinfo::get_cgroup(const std::string& subsys, std::string& cgroup) const -{ - for(const auto& it : cgroups()) - { - if(it.first == subsys) - { +bool sinsp_threadinfo::get_cgroup(const std::string& subsys, std::string& cgroup) const { + for(const auto& it : cgroups()) { + if(it.first == subsys) { cgroup = it.second; return true; } @@ -1058,22 +949,19 @@ bool sinsp_threadinfo::get_cgroup(const std::string& subsys, std::string& cgroup return false; } -void sinsp_threadinfo::traverse_parent_state(visitor_func_t &visitor) -{ +void sinsp_threadinfo::traverse_parent_state(visitor_func_t& visitor) { // Use two pointers starting at this, traversing the parent // state, at different rates. If they ever equal each other // before slow is NULL there's a loop. - sinsp_threadinfo *slow=this->get_parent_thread(), *fast=slow; + sinsp_threadinfo *slow = this->get_parent_thread(), *fast = slow; // Move fast to its parent fast = (fast ? fast->get_parent_thread() : fast); // The slow pointer must be valid and not have a tid of -1. - while(slow && slow->m_tid != -1) - { - if(!visitor(slow)) - { + while(slow && slow->m_tid != -1) { + if(!visitor(slow)) { break; } @@ -1082,23 +970,21 @@ void sinsp_threadinfo::traverse_parent_state(visitor_func_t &visitor) // advance fast 2 steps, checking to see if we meet // slow after each step. - for (uint32_t i = 0; i < 2; i++) { + for(uint32_t i = 0; i < 2; i++) { fast = (fast ? fast->get_parent_thread() : fast); // If not at the end but fast == slow or if // slow points to itself, there's a loop in // the thread state. - if(slow && (slow == fast || - slow->m_tid == slow->m_ptid)) - { + if(slow && (slow == fast || slow->m_tid == slow->m_ptid)) { // Note we only log a loop once for a given main thread, to avoid flooding logs. - if(!m_parent_loop_detected) - { - libsinsp_logger()->log(std::string("Loop in parent thread state detected for pid ") + - std::to_string(m_pid) + - ". stopped at tid= " + std::to_string(slow->m_tid) + - " ptid=" + std::to_string(slow->m_ptid), - sinsp_logger::SEV_WARNING); + if(!m_parent_loop_detected) { + libsinsp_logger()->log( + std::string("Loop in parent thread state detected for pid ") + + std::to_string(m_pid) + + ". stopped at tid= " + std::to_string(slow->m_tid) + + " ptid=" + std::to_string(slow->m_ptid), + sinsp_logger::SEV_WARNING); m_parent_loop_detected = true; } return; @@ -1110,34 +996,26 @@ void sinsp_threadinfo::traverse_parent_state(visitor_func_t &visitor) /* We should never call this method if we don't have children to reparent * if we want to save some clock cycles */ -void sinsp_threadinfo::assign_children_to_reaper(sinsp_threadinfo* reaper) -{ +void sinsp_threadinfo::assign_children_to_reaper(sinsp_threadinfo* reaper) { /* We have no children to reparent. */ - if(m_children.size() == 0) - { + if(m_children.size() == 0) { return; } - if(reaper == this) - { + if(reaper == this) { throw sinsp_exception("the current process is reaper of itself, this should never happen!"); } auto child = m_children.begin(); - while(child != m_children.end()) - { + while(child != m_children.end()) { /* If the child is not expired we move it to the reaper * and we change its `ptid`. */ - if(!child->expired()) - { - if(reaper == nullptr) - { + if(!child->expired()) { + if(reaper == nullptr) { /* we set `0` as the parent for all children */ child->lock()->m_ptid = 0; - } - else - { + } else { /* Add the child to the reaper list */ reaper->add_child(child->lock()); } @@ -1151,30 +1029,25 @@ void sinsp_threadinfo::assign_children_to_reaper(sinsp_threadinfo* reaper) m_not_expired_children = 0; } -void sinsp_threadinfo::populate_cmdline(std::string &cmdline, const sinsp_threadinfo *tinfo) -{ +void sinsp_threadinfo::populate_cmdline(std::string& cmdline, const sinsp_threadinfo* tinfo) { cmdline = tinfo->get_comm(); - for (const auto& arg : tinfo->m_args) - { + for(const auto& arg : tinfo->m_args) { cmdline += " "; cmdline += arg; } } -bool sinsp_threadinfo::is_health_probe() const -{ +bool sinsp_threadinfo::is_health_probe() const { return (m_category == sinsp_threadinfo::CAT_HEALTHCHECK || - m_category == sinsp_threadinfo::CAT_LIVENESS_PROBE || + m_category == sinsp_threadinfo::CAT_LIVENESS_PROBE || m_category == sinsp_threadinfo::CAT_READINESS_PROBE); } -std::string sinsp_threadinfo::get_path_for_dir_fd(int64_t dir_fd) -{ +std::string sinsp_threadinfo::get_path_for_dir_fd(int64_t dir_fd) { sinsp_fdinfo* dir_fdinfo = get_fd(dir_fd); - if (!dir_fdinfo || dir_fdinfo->m_name.empty()) - { -#ifndef _WIN32 // we will have to implement this for Windows + if(!dir_fdinfo || dir_fdinfo->m_name.empty()) { +#ifndef _WIN32 // we will have to implement this for Windows // Sad day; we don't have the directory in the tinfo's fd cache. // Must manually look it up so we can resolve filenames correctly. char proc_path[PATH_MAX]; @@ -1188,10 +1061,9 @@ std::string sinsp_threadinfo::get_path_for_dir_fd(int64_t dir_fd) (long long)dir_fd); ret = readlink(proc_path, dirfd_path, sizeof(dirfd_path) - 1); - if (ret < 0) - { + if(ret < 0) { libsinsp_logger()->log("Unable to determine path for file descriptor.", - sinsp_logger::SEV_INFO); + sinsp_logger::SEV_INFO); return ""; } dirfd_path[ret] = '\0'; @@ -1200,60 +1072,48 @@ std::string sinsp_threadinfo::get_path_for_dir_fd(int64_t dir_fd) rel_path_base.append("/"); libsinsp_logger()->log(std::string("Translating to ") + rel_path_base); return rel_path_base; -#endif // _WIN32 +#endif // _WIN32 } return dir_fdinfo->m_name; } -size_t sinsp_threadinfo::args_len() const -{ +size_t sinsp_threadinfo::args_len() const { return strvec_len(m_args); } -size_t sinsp_threadinfo::env_len() const -{ +size_t sinsp_threadinfo::env_len() const { return strvec_len(m_env); } -void sinsp_threadinfo::args_to_iovec(struct iovec **iov, int *iovcnt, - std::string &rem) const -{ - return strvec_to_iovec(m_args, - iov, iovcnt, - rem); +void sinsp_threadinfo::args_to_iovec(struct iovec** iov, int* iovcnt, std::string& rem) const { + return strvec_to_iovec(m_args, iov, iovcnt, rem); } -void sinsp_threadinfo::env_to_iovec(struct iovec **iov, int *iovcnt, - std::string &rem) const -{ - return strvec_to_iovec(m_env, - iov, iovcnt, - rem); +void sinsp_threadinfo::env_to_iovec(struct iovec** iov, int* iovcnt, std::string& rem) const { + return strvec_to_iovec(m_env, iov, iovcnt, rem); } // Set the provided iovec to the string in str, if it will fit. If it // won't, copy the portion that will fit to rem and set the iovec to // rem. Updates alen with the new total length and possibly sets rem // to any truncated string. -void sinsp_threadinfo::add_to_iovec(const std::string &str, - const bool include_trailing_null, - struct iovec &iov, - uint32_t &alen, - std::string &rem) const -{ +void sinsp_threadinfo::add_to_iovec(const std::string& str, + const bool include_trailing_null, + struct iovec& iov, + uint32_t& alen, + std::string& rem) const { uint32_t len = str.size() + (include_trailing_null ? 1 : 0); - const char *buf = str.c_str(); + const char* buf = str.c_str(); - if(len > alen) - { + if(len > alen) { // The entire string won't fit. Use rem to hold a // truncated copy - rem = str.substr(0, alen-1); + rem = str.substr(0, alen - 1); buf = rem.c_str(); len = alen; } - iov.iov_base = (void *) buf; + iov.iov_base = (void*)buf; iov.iov_len = len; alen -= len; @@ -1261,46 +1121,41 @@ void sinsp_threadinfo::add_to_iovec(const std::string &str, // iov will be allocated and must be freed. rem is used to hold a // possibly truncated final argument. -void sinsp_threadinfo::cgroups_to_iovec(struct iovec **iov, int *iovcnt, - std::string &rem, const cgroups_t& cgroups) const -{ +void sinsp_threadinfo::cgroups_to_iovec(struct iovec** iov, + int* iovcnt, + std::string& rem, + const cgroups_t& cgroups) const { uint32_t alen = SCAP_MAX_ARGS_SIZE; static const std::string eq = "="; // We allocate an iovec big enough to hold all the cgroups and // intermediate '=' signs. Based on alen, we might not use all // of the iovec. - *iov = (struct iovec *) malloc((3 * cgroups.size()) * sizeof(struct iovec)); - if(iov == NULL) - { + *iov = (struct iovec*)malloc((3 * cgroups.size()) * sizeof(struct iovec)); + if(iov == NULL) { throw sinsp_exception("memory allocation error in sinsp_threadinfo::cgroups_to_iovec."); } *iovcnt = 0; - for(auto it = cgroups.begin(); it != cgroups.end() && alen > 0; ++it) - { + for(auto it = cgroups.begin(); it != cgroups.end() && alen > 0; ++it) { add_to_iovec(it->first, false, (*iov)[(*iovcnt)++], alen, rem); - if(alen > 0) - { + if(alen > 0) { add_to_iovec(eq, false, (*iov)[(*iovcnt)++], alen, rem); } - if(alen > 0) - { + if(alen > 0) { add_to_iovec(it->second, true, (*iov)[(*iovcnt)++], alen, rem); } } } -size_t sinsp_threadinfo::strvec_len(const std::vector &strs) const -{ +size_t sinsp_threadinfo::strvec_len(const std::vector& strs) const { size_t totlen = 0; - for(auto &str : strs) - { + for(auto& str : strs) { totlen += str.size(); - totlen++; // Trailing NULL + totlen++; // Trailing NULL } return totlen; @@ -1308,36 +1163,32 @@ size_t sinsp_threadinfo::strvec_len(const std::vector &strs) const // iov will be allocated and must be freed. rem is used to hold a // possibly truncated final argument. -void sinsp_threadinfo::strvec_to_iovec(const std::vector &strs, - struct iovec **iov, int *iovcnt, - std::string &rem) const -{ +void sinsp_threadinfo::strvec_to_iovec(const std::vector& strs, + struct iovec** iov, + int* iovcnt, + std::string& rem) const { uint32_t alen = SCAP_MAX_ARGS_SIZE; // We allocate an iovec big enough to hold all the entries in // strs. Based on alen, we might not use all of the iovec. - *iov = (struct iovec *) malloc(strs.size() * sizeof(struct iovec)); - if(iov == NULL) - { + *iov = (struct iovec*)malloc(strs.size() * sizeof(struct iovec)); + if(iov == NULL) { throw sinsp_exception("memory allocation error in sinsp_threadinfo::strvec_to_iovec."); } *iovcnt = 0; - for(auto it = strs.begin(); it != strs.end() && alen > 0; ++it) - { + for(auto it = strs.begin(); it != strs.end() && alen > 0; ++it) { add_to_iovec(*it, true, (*iov)[(*iovcnt)++], alen, rem); } } -static void fd_to_scap(scap_fdinfo *dst, sinsp_fdinfo* src) -{ +static void fd_to_scap(scap_fdinfo* dst, sinsp_fdinfo* src) { dst->type = src->m_type; dst->ino = src->m_ino; dst->fd = src->m_fd; - switch(dst->type) - { + switch(dst->type) { case SCAP_FD_IPV4_SOCK: dst->info.ipv4info.sip = src->m_sockinfo.m_ipv4info.m_fields.m_sip; dst->info.ipv4info.dip = src->m_sockinfo.m_ipv4info.m_fields.m_dip; @@ -1365,11 +1216,15 @@ static void fd_to_scap(scap_fdinfo *dst, sinsp_fdinfo* src) case SCAP_FD_UNIX_SOCK: dst->info.unix_socket_info.source = src->m_sockinfo.m_unixinfo.m_fields.m_source; dst->info.unix_socket_info.destination = src->m_sockinfo.m_unixinfo.m_fields.m_dest; - strlcpy(dst->info.unix_socket_info.fname, src->m_name.c_str(), sizeof(dst->info.unix_socket_info.fname)); + strlcpy(dst->info.unix_socket_info.fname, + src->m_name.c_str(), + sizeof(dst->info.unix_socket_info.fname)); break; case SCAP_FD_FILE_V2: dst->info.regularinfo.open_flags = src->m_openflags; - strlcpy(dst->info.regularinfo.fname, src->m_name.c_str(), sizeof(dst->info.regularinfo.fname)); + strlcpy(dst->info.regularinfo.fname, + src->m_name.c_str(), + sizeof(dst->info.regularinfo.fname)); dst->info.regularinfo.dev = src->m_dev; dst->info.regularinfo.mount_id = src->m_mount_id; break; @@ -1401,25 +1256,20 @@ static const auto s_threadinfo_static_fields = sinsp_threadinfo().static_fields( /////////////////////////////////////////////////////////////////////////////// // sinsp_thread_manager implementation /////////////////////////////////////////////////////////////////////////////// -sinsp_thread_manager::sinsp_thread_manager(sinsp* inspector) - : table(s_thread_table_name, &s_threadinfo_static_fields), - m_max_thread_table_size(m_thread_table_default_size), - m_fdtable_dyn_fields(std::make_shared()) -{ +sinsp_thread_manager::sinsp_thread_manager(sinsp* inspector): + table(s_thread_table_name, &s_threadinfo_static_fields), + m_max_thread_table_size(m_thread_table_default_size), + m_fdtable_dyn_fields(std::make_shared()) { m_inspector = inspector; - if (m_inspector != nullptr) - { + if(m_inspector != nullptr) { m_sinsp_stats_v2 = m_inspector->get_sinsp_stats_v2(); - } - else - { + } else { m_sinsp_stats_v2 = nullptr; } clear(); } -void sinsp_thread_manager::clear() -{ +void sinsp_thread_manager::clear() { m_threadtable.clear(); m_thread_groups.clear(); m_last_tid = 0; @@ -1427,54 +1277,48 @@ void sinsp_thread_manager::clear() } /* This is called on the table after the `/proc` scan */ -void sinsp_thread_manager::create_thread_dependencies(const std::shared_ptr& tinfo) -{ +void sinsp_thread_manager::create_thread_dependencies( + const std::shared_ptr& tinfo) { /* This should never happen */ - if(tinfo == nullptr) - { - throw sinsp_exception("There is a NULL pointer in the thread table, this should never happen"); + if(tinfo == nullptr) { + throw sinsp_exception( + "There is a NULL pointer in the thread table, this should never happen"); } /* For invalid threads we do nothing. * They won't have a valid parent or a valid thread group. * We use them just to see which tid calls a syscall. */ - if(tinfo->is_invalid()) - { + if(tinfo->is_invalid()) { return; } /* This is a defensive check, it should never happen * a thread that calls this method should never have a thread group info */ - if(tinfo->m_tginfo != nullptr) - { + if(tinfo->m_tginfo != nullptr) { return; } bool reaper = false; - /* reaper should be true if we are an init process for the init namespace or for an inner namespace */ - if(tinfo->m_pid == 1 || tinfo->m_vpid == 1) - { + /* reaper should be true if we are an init process for the init namespace or for an inner + * namespace */ + if(tinfo->m_pid == 1 || tinfo->m_vpid == 1) { reaper = true; } /* Create the thread group info for the thread. */ auto tginfo = m_inspector->m_thread_manager->get_thread_group_info(tinfo->m_pid); - if(tginfo == nullptr) - { + if(tginfo == nullptr) { tginfo = std::make_shared(tinfo->m_pid, reaper, tinfo); m_inspector->m_thread_manager->set_thread_group_info(tinfo->m_pid, tginfo); - } - else - { + } else { tginfo->add_thread_to_group(tinfo, tinfo->is_main_thread()); } tinfo->m_tginfo = tginfo; /* init group has no parent */ - if(tinfo->m_pid == 1) - { + if(tinfo->m_pid == 1) { return; } @@ -1487,8 +1331,7 @@ void sinsp_thread_manager::create_thread_dependencies(const std::shared_ptrget_thread_ref(tinfo->m_ptid, false); - if(parent_thread == nullptr || parent_thread->is_invalid()) - { + if(parent_thread == nullptr || parent_thread->is_invalid()) { /* If we have a valid parent we assign the new child to it otherwise we set ptid = 0. */ tinfo->m_ptid = 0; return; @@ -1496,14 +1339,12 @@ void sinsp_thread_manager::create_thread_dependencies(const std::shared_ptradd_child(tinfo); } -std::unique_ptr sinsp_thread_manager::new_threadinfo() const -{ +std::unique_ptr sinsp_thread_manager::new_threadinfo() const { auto tinfo = new sinsp_threadinfo(m_inspector, dynamic_fields()); return std::unique_ptr(tinfo); } -std::unique_ptr sinsp_thread_manager::new_fdinfo() const -{ +std::unique_ptr sinsp_thread_manager::new_fdinfo() const { return sinsp_fdtable(m_inspector).new_fdinfo(); } @@ -1512,21 +1353,21 @@ std::unique_ptr sinsp_thread_manager::new_fdinfo() const * 2. We are doing a proc scan with a callback or without. (`from_scap_proctable==true`) * 3. We are trying to obtain thread info from /proc through `get_thread_ref` */ -const std::shared_ptr& sinsp_thread_manager::add_thread(std::unique_ptr threadinfo, bool from_scap_proctable) -{ - +const std::shared_ptr& sinsp_thread_manager::add_thread( + std::unique_ptr threadinfo, + bool from_scap_proctable) { /* We have no more space */ - if(m_threadtable.size() >= m_max_thread_table_size - && threadinfo->m_pid != m_inspector->m_self_pid - ) - { - if (m_sinsp_stats_v2 != nullptr) - { + if(m_threadtable.size() >= m_max_thread_table_size && + threadinfo->m_pid != m_inspector->m_self_pid) { + if(m_sinsp_stats_v2 != nullptr) { // rate limit messages to avoid spamming the logs - if (m_sinsp_stats_v2->m_n_drops_full_threadtable % m_max_thread_table_size == 0) - { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "Thread table full, dropping tid %lu (pid %lu, comm \"%s\")", - threadinfo->m_tid, threadinfo->m_pid, threadinfo->m_comm.c_str()); + if(m_sinsp_stats_v2->m_n_drops_full_threadtable % m_max_thread_table_size == 0) { + libsinsp_logger()->format( + sinsp_logger::SEV_INFO, + "Thread table full, dropping tid %lu (pid %lu, comm \"%s\")", + threadinfo->m_tid, + threadinfo->m_pid, + threadinfo->m_comm.c_str()); } m_sinsp_stats_v2->m_n_drops_full_threadtable++; } @@ -1536,24 +1377,21 @@ const std::shared_ptr& sinsp_thread_manager::add_thread(std::u auto tinfo_shared_ptr = std::shared_ptr(std::move(threadinfo)); - if(!from_scap_proctable) - { + if(!from_scap_proctable) { create_thread_dependencies(tinfo_shared_ptr); } - if (tinfo_shared_ptr->dynamic_fields() != dynamic_fields()) - { + if(tinfo_shared_ptr->dynamic_fields() != dynamic_fields()) { throw sinsp_exception("adding entry with incompatible dynamic defs to thread table"); } - if (tinfo_shared_ptr->get_fdtable().dynamic_fields() != m_fdtable_dyn_fields) - { - throw sinsp_exception("adding entry with incompatible dynamic defs to of file descriptor sub-table"); + if(tinfo_shared_ptr->get_fdtable().dynamic_fields() != m_fdtable_dyn_fields) { + throw sinsp_exception( + "adding entry with incompatible dynamic defs to of file descriptor sub-table"); } tinfo_shared_ptr->compute_program_hash(); - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_added_threads++; } @@ -1568,25 +1406,19 @@ const std::shared_ptr& sinsp_thread_manager::add_thread(std::u * child_subreaper for its children (like a service manager) * 3. give them to the init process (PID 1) in our pid namespace */ -sinsp_threadinfo* sinsp_thread_manager::find_new_reaper(sinsp_threadinfo* tinfo) -{ - if(tinfo == nullptr) - { +sinsp_threadinfo* sinsp_thread_manager::find_new_reaper(sinsp_threadinfo* tinfo) { + if(tinfo == nullptr) { throw sinsp_exception("cannot call find_new_reaper() on a null tinfo"); } /* First we check in our thread group for alive threads */ - if(tinfo->m_tginfo != nullptr && tinfo->m_tginfo->get_thread_count() > 0) - { - for(const auto& thread_weak : tinfo->m_tginfo->get_thread_list()) - { - if(thread_weak.expired()) - { + if(tinfo->m_tginfo != nullptr && tinfo->m_tginfo->get_thread_count() > 0) { + for(const auto& thread_weak : tinfo->m_tginfo->get_thread_list()) { + if(thread_weak.expired()) { continue; } auto thread = thread_weak.lock().get(); - if(!thread->is_dead() && thread != tinfo) - { + if(!thread->is_dead() && thread != tinfo) { return thread; } } @@ -1606,12 +1438,10 @@ sinsp_threadinfo* sinsp_thread_manager::find_new_reaper(sinsp_threadinfo* tinfo) uint16_t prev_set_size = 1; auto parent_tinfo = tinfo->get_parent_thread(); - while(parent_tinfo != nullptr) - { + while(parent_tinfo != nullptr) { prev_set_size = loop_detection_set.size(); loop_detection_set.insert(parent_tinfo->m_tid); - if(loop_detection_set.size() == prev_set_size) - { + if(loop_detection_set.size() == prev_set_size) { /* loop detected */ ASSERT(false); break; @@ -1624,24 +1454,18 @@ sinsp_threadinfo* sinsp_thread_manager::find_new_reaper(sinsp_threadinfo* tinfo) * namespace level so it's possible that the parent is in a different namespace causing * a container escape! We are not able to detect it with the actual info. */ - if(parent_tinfo->is_in_pid_namespace() != tinfo->is_in_pid_namespace()) - { + if(parent_tinfo->is_in_pid_namespace() != tinfo->is_in_pid_namespace()) { break; } - if(parent_tinfo->m_tginfo != nullptr && - parent_tinfo->m_tginfo->is_reaper() && - parent_tinfo->m_tginfo->get_thread_count() > 0) - { - for(const auto& thread_weak : parent_tinfo->m_tginfo->get_thread_list()) - { - if(thread_weak.expired()) - { + if(parent_tinfo->m_tginfo != nullptr && parent_tinfo->m_tginfo->is_reaper() && + parent_tinfo->m_tginfo->get_thread_count() > 0) { + for(const auto& thread_weak : parent_tinfo->m_tginfo->get_thread_list()) { + if(thread_weak.expired()) { continue; } auto thread = thread_weak.lock().get(); - if(!thread->is_dead()) - { + if(!thread->is_dead()) { return thread; } } @@ -1652,22 +1476,19 @@ sinsp_threadinfo* sinsp_thread_manager::find_new_reaper(sinsp_threadinfo* tinfo) return nullptr; } -void sinsp_thread_manager::remove_main_thread_fdtable(sinsp_threadinfo* main_thread) -{ - ///todo(@Andreagit97): all this logic is useful only if we have a `m_fd_listener` - ///we could avoid it if not present. +void sinsp_thread_manager::remove_main_thread_fdtable(sinsp_threadinfo* main_thread) { + /// todo(@Andreagit97): all this logic is useful only if we have a `m_fd_listener` + /// we could avoid it if not present. /* Please note that the main thread is not always here, it is possible * that for some reason we lose it! */ - if(main_thread == nullptr) - { + if(main_thread == nullptr) { return; } sinsp_fdtable* fd_table_ptr = main_thread->get_fd_table(); - if(fd_table_ptr == nullptr) - { + if(fd_table_ptr == nullptr) { return; } @@ -1692,16 +1513,13 @@ void sinsp_thread_manager::remove_main_thread_fdtable(sinsp_threadinfo* main_thr }); } -void sinsp_thread_manager::remove_thread(int64_t tid) -{ +void sinsp_thread_manager::remove_thread(int64_t tid) { auto thread_to_remove = m_threadtable.get_ref(tid); /* This should never happen but just to be sure. */ - if(thread_to_remove == nullptr) - { + if(thread_to_remove == nullptr) { // Extra m_inspector nullptr check - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_failed_thread_lookups++; } return; @@ -1711,8 +1529,7 @@ void sinsp_thread_manager::remove_thread(int64_t tid) * All threads should have a m_tginfo apart from the invalid ones * which don't have a group or children. */ - if(thread_to_remove->is_invalid() || thread_to_remove->m_tginfo == nullptr) - { + if(thread_to_remove->is_invalid() || thread_to_remove->m_tginfo == nullptr) { thread_to_remove->remove_child_from_parent(); m_threadtable.erase(tid); m_last_tid = -1; @@ -1722,8 +1539,7 @@ void sinsp_thread_manager::remove_thread(int64_t tid) /* [Mark the thread as dead] * If didn't lose the PROC_EXIT event we have already done it */ - if(!thread_to_remove->is_dead()) - { + if(!thread_to_remove->is_dead()) { /* we should decrement only if the thread is alive */ thread_to_remove->m_tginfo->decrement_thread_count(); thread_to_remove->set_dead(); @@ -1734,12 +1550,12 @@ void sinsp_thread_manager::remove_thread(int64_t tid) * 1. We have no children so we have nothing to reparent. * 2. We receive a PROC_EXIT event for this thread, with reaper info: * - Reaper 0 means that the kernel didn't find any children for this thread, - * probably we are not correctly aligned with it. In this case, we will use our userspace logic - * to find a reaper. + * probably we are not correctly aligned with it. In this case, we will use our userspace + * logic to find a reaper. * - Reaper -1 means that we cannot find the correct reaper info in the kernel due * to BPF verifier limits. In this case, we will use our userspace logic to find a reaper. - * - Reaper > 0 means the kernel sent us a valid reaper we will use it if present in our thread table. - * If not present we will use our userspace logic. + * - Reaper > 0 means the kernel sent us a valid reaper we will use it if present in our + * thread table. If not present we will use our userspace logic. * 3. We receive an old version of the PROC_EXIT event without reaper info. In this case, * we use our userspace logic. * 4. We lost the PROC_EXIT event, so we are here because the purging logic called us. Also @@ -1748,29 +1564,25 @@ void sinsp_thread_manager::remove_thread(int64_t tid) * So excluding the case in which the kernel sent us a valid reaper we always fallback to * our userspace logic. */ - if(thread_to_remove->m_children.size()) - { - sinsp_threadinfo *reaper_tinfo = nullptr; + if(thread_to_remove->m_children.size()) { + sinsp_threadinfo* reaper_tinfo = nullptr; - if(thread_to_remove->m_reaper_tid > 0) - { + if(thread_to_remove->m_reaper_tid > 0) { /* The kernel sent us a valid reaper * We should have the reaper thread in the table, but if we don't have * it, we try to create it from /proc */ - reaper_tinfo = m_inspector->get_thread_ref(thread_to_remove->m_reaper_tid , true).get(); + reaper_tinfo = m_inspector->get_thread_ref(thread_to_remove->m_reaper_tid, true).get(); } - if(reaper_tinfo == nullptr || reaper_tinfo->is_invalid()) - { + if(reaper_tinfo == nullptr || reaper_tinfo->is_invalid()) { /* Fallback case: - * We search for a reaper in best effort traversing our table - */ + * We search for a reaper in best effort traversing our table + */ reaper_tinfo = find_new_reaper(thread_to_remove.get()); } - if(reaper_tinfo != nullptr) - { + if(reaper_tinfo != nullptr) { /* We update the reaper tid if necessary. */ thread_to_remove->m_reaper_tid = reaper_tinfo->m_tid; @@ -1780,11 +1592,11 @@ void sinsp_thread_manager::remove_thread(int64_t tid) * the thread group as a reaper: * - init process of a namespace. * - process that called prctl on itself. - * Please note that in the kernel init processes are not marked with `is_child_subreaper` - * but here we don't make distinctions we mark reapers and sub reapers with the same flag. + * Please note that in the kernel init processes are not marked with + * `is_child_subreaper` but here we don't make distinctions we mark reapers and sub + * reapers with the same flag. */ - if(reaper_tinfo->m_pid != thread_to_remove->m_pid && reaper_tinfo->m_tginfo) - { + if(reaper_tinfo->m_pid != thread_to_remove->m_pid && reaper_tinfo->m_tginfo) { reaper_tinfo->m_tginfo->set_reaper(true); } } @@ -1794,8 +1606,7 @@ void sinsp_thread_manager::remove_thread(int64_t tid) /* [Remove main thread] * We remove the main thread if there are no other threads in the group */ - if((thread_to_remove->m_tginfo->get_thread_count() == 0)) - { + if((thread_to_remove->m_tginfo->get_thread_count() == 0)) { remove_main_thread_fdtable(thread_to_remove->get_main_thread()); /* we remove the main thread and the thread group */ @@ -1812,8 +1623,7 @@ void sinsp_thread_manager::remove_thread(int64_t tid) * If we are the main thread and it's time to be removed, we are removed * in the previous `if`. */ - if(!thread_to_remove->is_main_thread()) - { + if(!thread_to_remove->is_main_thread()) { thread_to_remove->remove_child_from_parent(); m_threadtable.erase(tid); } @@ -1822,39 +1632,33 @@ void sinsp_thread_manager::remove_thread(int64_t tid) * the cache just to be sure. */ m_last_tid = -1; - if (m_sinsp_stats_v2 != nullptr) - { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_removed_threads++; } } -void sinsp_thread_manager::fix_sockets_coming_from_proc() -{ - m_threadtable.loop([&] (sinsp_threadinfo& tinfo) { +void sinsp_thread_manager::fix_sockets_coming_from_proc() { + m_threadtable.loop([&](sinsp_threadinfo& tinfo) { tinfo.fix_sockets_coming_from_proc(); return true; }); } -void sinsp_thread_manager::clear_thread_pointers(sinsp_threadinfo& tinfo) -{ +void sinsp_thread_manager::clear_thread_pointers(sinsp_threadinfo& tinfo) { sinsp_fdtable* fdt = tinfo.get_fd_table(); - if(fdt != NULL) - { + if(fdt != NULL) { fdt->reset_cache(); } } -void sinsp_thread_manager::reset_child_dependencies() -{ - m_threadtable.loop([&] (sinsp_threadinfo& tinfo) { +void sinsp_thread_manager::reset_child_dependencies() { + m_threadtable.loop([&](sinsp_threadinfo& tinfo) { tinfo.clean_expired_children(); /* Little optimization: only the main thread cleans the thread group from expired threads. - * Downside: if the main thread is not present in the thread group because we lost it we don't - * clean the thread group from expired threads. + * Downside: if the main thread is not present in the thread group because we lost it we + * don't clean the thread group from expired threads. */ - if(tinfo.is_main_thread() && tinfo.m_tginfo != nullptr) - { + if(tinfo.is_main_thread() && tinfo.m_tginfo != nullptr) { tinfo.m_tginfo->clean_expired_threads(); } clear_thread_pointers(tinfo); @@ -1862,18 +1666,15 @@ void sinsp_thread_manager::reset_child_dependencies() }); } -void sinsp_thread_manager::create_thread_dependencies_after_proc_scan() -{ +void sinsp_thread_manager::create_thread_dependencies_after_proc_scan() { m_threadtable.const_loop_shared_pointer([&](const std::shared_ptr& tinfo) { create_thread_dependencies(tinfo); return true; }); } -void sinsp_thread_manager::free_dump_fdinfos(std::vector* fdinfos_to_free) -{ - for(uint32_t j = 0; j < fdinfos_to_free->size(); j++) - { +void sinsp_thread_manager::free_dump_fdinfos(std::vector* fdinfos_to_free) { + for(uint32_t j = 0; j < fdinfos_to_free->size(); j++) { free(fdinfos_to_free->at(j)); } @@ -1882,8 +1683,7 @@ void sinsp_thread_manager::free_dump_fdinfos(std::vector* fdinfos_ // NOTE: This does *not* populate any array-based fields (comm, exe, // exepath, args, env, cwd, cgroups, root) -void sinsp_thread_manager::thread_to_scap(sinsp_threadinfo& tinfo, scap_threadinfo* sctinfo) -{ +void sinsp_thread_manager::thread_to_scap(sinsp_threadinfo& tinfo, scap_threadinfo* sctinfo) { // // Fill in the thread data // @@ -1897,7 +1697,7 @@ void sinsp_thread_manager::thread_to_scap(sinsp_threadinfo& tinfo, scap_threadi sctinfo->sid = tinfo.m_sid; sctinfo->vpgid = tinfo.m_vpgid; - sctinfo->flags = tinfo.m_flags ; + sctinfo->flags = tinfo.m_flags; sctinfo->fdlimit = tinfo.m_fdlimit; sctinfo->uid = tinfo.m_user.uid(); sctinfo->gid = tinfo.m_group.gid(); @@ -1913,27 +1713,23 @@ void sinsp_thread_manager::thread_to_scap(sinsp_threadinfo& tinfo, scap_threadi sctinfo->filtered_out = tinfo.m_filtered_out; } -void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) -{ - if(m_threadtable.size() == 0) - { +void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) { + if(m_threadtable.size() == 0) { return; } - scap_dumper_t *proclist_dumper = scap_write_proclist_begin(); - if(proclist_dumper == nullptr) - { - throw sinsp_exception("Failed to create proclist dumper"); + scap_dumper_t* proclist_dumper = scap_write_proclist_begin(); + if(proclist_dumper == nullptr) { + throw sinsp_exception("Failed to create proclist dumper"); } uint32_t totlen = 0; - m_threadtable.loop([&] (sinsp_threadinfo& tinfo) { - if(tinfo.m_filtered_out) - { + m_threadtable.loop([&](sinsp_threadinfo& tinfo) { + if(tinfo.m_filtered_out) { return true; } - scap_threadinfo sctinfo {}; + scap_threadinfo sctinfo{}; struct iovec *args_iov, *envs_iov, *cgroups_iov; int argscnt, envscnt, cgroupscnt; std::string argsrem, envsrem, cgroupsrem; @@ -1947,16 +1743,20 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) tinfo.env_to_iovec(&envs_iov, &envscnt, envsrem); tinfo.cgroups_to_iovec(&cgroups_iov, &cgroupscnt, cgroupsrem, cg); - if(scap_write_proclist_entry_bufs(proclist_dumper, &sctinfo, &entrylen, - tinfo.m_comm.c_str(), - tinfo.m_exe.c_str(), - tinfo.m_exepath.c_str(), - args_iov, argscnt, - envs_iov, envscnt, - (tinfo.get_cwd() == "" ? "/" : tinfo.get_cwd().c_str()), - cgroups_iov, cgroupscnt, - tinfo.m_root.c_str()) != SCAP_SUCCESS) - { + if(scap_write_proclist_entry_bufs(proclist_dumper, + &sctinfo, + &entrylen, + tinfo.m_comm.c_str(), + tinfo.m_exe.c_str(), + tinfo.m_exepath.c_str(), + args_iov, + argscnt, + envs_iov, + envscnt, + (tinfo.get_cwd() == "" ? "/" : tinfo.get_cwd().c_str()), + cgroups_iov, + cgroupscnt, + tinfo.m_root.c_str()) != SCAP_SUCCESS) { sinsp_exception exc(scap_dump_getlasterr(proclist_dumper)); scap_dump_close(proclist_dumper); throw exc; @@ -1971,8 +1771,7 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) return true; }); - if(scap_write_proclist_end(dumper, proclist_dumper, totlen) != SCAP_SUCCESS) - { + if(scap_write_proclist_end(dumper, proclist_dumper, totlen) != SCAP_SUCCESS) { throw sinsp_exception(scap_dump_getlasterr(dumper)); } @@ -1980,13 +1779,12 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) // Dump the FDs // - m_threadtable.loop([&] (sinsp_threadinfo& tinfo) { - if(tinfo.m_filtered_out) - { + m_threadtable.loop([&](sinsp_threadinfo& tinfo) { + if(tinfo.m_filtered_out) { return true; } - scap_threadinfo sctinfo {}; + scap_threadinfo sctinfo{}; memset(&sctinfo, 0, sizeof(scap_threadinfo)); @@ -1995,14 +1793,12 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) // shallow copy is safe thread_to_scap(tinfo, &sctinfo); - if(tinfo.is_main_thread()) - { + if(tinfo.is_main_thread()) { // // Add the FDs // sinsp_fdtable* fd_table_ptr = tinfo.get_fd_table(); - if(fd_table_ptr == NULL) - { + if(fd_table_ptr == NULL) { return false; } @@ -2012,8 +1808,7 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) // Allocate the scap fd info // scap_fdinfo* scfdinfo = (scap_fdinfo*)malloc(sizeof(scap_fdinfo)); - if(scfdinfo == NULL) - { + if(scfdinfo == NULL) { scap_fd_free_proc_fd_table(&sctinfo); should_exit = true; return false; @@ -2027,8 +1822,7 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) // // Add the new fd to the scap table. // - if(scap_fd_add(&sctinfo, scfdinfo) != SCAP_SUCCESS) - { + if(scap_fd_add(&sctinfo, scfdinfo) != SCAP_SUCCESS) { scap_fd_free_proc_fd_table(&sctinfo); throw sinsp_exception("Failed to add fd to hash table"); } @@ -2036,8 +1830,7 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) return true; }); - if (should_exit) - { + if(should_exit) { return false; } } @@ -2045,9 +1838,11 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) // // Dump the thread to disk // - if(scap_write_proc_fds(dumper, &sctinfo) != SCAP_SUCCESS) - { - throw sinsp_exception("error calling scap_write_proc_fds in sinsp_thread_manager::dump_threads_to_file (" + std::string(scap_dump_getlasterr(dumper)) + ")"); + if(scap_write_proc_fds(dumper, &sctinfo) != SCAP_SUCCESS) { + throw sinsp_exception( + "error calling scap_write_proc_fds in " + "sinsp_thread_manager::dump_threads_to_file (" + + std::string(scap_dump_getlasterr(dumper)) + ")"); } scap_fd_free_proc_fd_table(&sctinfo); @@ -2055,115 +1850,109 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) }); } -const threadinfo_map_t::ptr_t& sinsp_thread_manager::get_thread_ref(int64_t tid, bool query_os_if_not_found, bool lookup_only, bool main_thread) -{ - const auto& sinsp_proc = find_thread(tid, lookup_only); - - if(!sinsp_proc && query_os_if_not_found && - (m_threadtable.size() < m_max_thread_table_size || tid == m_inspector->m_self_pid)) - { - // Certain code paths can lead to this point from scap_open() (incomplete example: - // scap_proc_scan_proc_dir() -> resolve_container() -> get_env()). Adding a - // defensive check here to protect both, callers of get_env and get_thread. - if (!m_inspector->get_scap_handle()) - { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "%s: Unable to complete for tid=%" - PRIu64 ": sinsp::scap_t* is uninitialized", __func__, tid); - return m_nullptr_tinfo_ret; - } +const threadinfo_map_t::ptr_t& sinsp_thread_manager::get_thread_ref(int64_t tid, + bool query_os_if_not_found, + bool lookup_only, + bool main_thread) { + const auto& sinsp_proc = find_thread(tid, lookup_only); + + if(!sinsp_proc && query_os_if_not_found && + (m_threadtable.size() < m_max_thread_table_size || tid == m_inspector->m_self_pid)) { + // Certain code paths can lead to this point from scap_open() (incomplete example: + // scap_proc_scan_proc_dir() -> resolve_container() -> get_env()). Adding a + // defensive check here to protect both, callers of get_env and get_thread. + if(!m_inspector->get_scap_handle()) { + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "%s: Unable to complete for tid=%" PRIu64 + ": sinsp::scap_t* is uninitialized", + __func__, + tid); + return m_nullptr_tinfo_ret; + } - scap_threadinfo scap_proc {}; - bool have_scap_proc = false; + scap_threadinfo scap_proc{}; + bool have_scap_proc = false; - // leaving scap_proc uninitialized could lead to undefined behaviour. - // to be safe we should initialized to zero. - memset(&scap_proc, 0, sizeof(scap_threadinfo)); + // leaving scap_proc uninitialized could lead to undefined behaviour. + // to be safe we should initialized to zero. + memset(&scap_proc, 0, sizeof(scap_threadinfo)); - scap_proc.tid = -1; - scap_proc.pid = -1; - scap_proc.ptid = -1; + scap_proc.tid = -1; + scap_proc.pid = -1; + scap_proc.ptid = -1; // unfortunately, sinsp owns the threade factory - auto newti = m_inspector->build_threadinfo(); - - m_n_proc_lookups++; - - if(main_thread) - { - m_n_main_thread_lookups++; - } - - if(m_n_proc_lookups == m_max_n_proc_lookups) - { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "Reached max process lookup number, duration=%" PRIu64 "ms", - m_n_proc_lookups_duration_ns / 1000000); - } - - if(m_max_n_proc_lookups < 0 || - m_n_proc_lookups <= m_max_n_proc_lookups) - { - bool scan_sockets = false; - - if(m_max_n_proc_socket_lookups < 0 || - m_n_proc_lookups <= m_max_n_proc_socket_lookups) - { - scan_sockets = true; - if(m_n_proc_lookups == m_max_n_proc_socket_lookups) - { - libsinsp_logger()->format(sinsp_logger::SEV_INFO, "Reached max socket lookup number, tid=%" PRIu64 ", duration=%" PRIu64 "ms", - tid, m_n_proc_lookups_duration_ns / 1000000); - } - } - - uint64_t ts = sinsp_utils::get_current_time_ns(); - if(scap_proc_get(m_inspector->get_scap_platform(), tid, &scap_proc, scan_sockets) == SCAP_SUCCESS) - { - have_scap_proc = true; - } - m_n_proc_lookups_duration_ns += sinsp_utils::get_current_time_ns() - ts; - } - - if(have_scap_proc) - { - newti->init(&scap_proc); - } - else - { - // - // Add a fake entry to avoid a continuous lookup - // - newti->m_tid = tid; - newti->m_pid = -1; - newti->m_ptid = -1; - newti->m_reaper_tid = -1; - newti->m_not_expired_children = 0; - newti->m_comm = ""; - newti->m_exe = ""; - newti->m_user.set_uid(0xffffffff); - newti->m_group.set_gid(0xffffffff); - newti->m_loginuser.set_uid(0xffffffff); - } - - // - // Done. Add the new thread to the list. - // - add_thread(std::move(newti), false); - return find_thread(tid, lookup_only); - } - - return sinsp_proc; + auto newti = m_inspector->build_threadinfo(); + + m_n_proc_lookups++; + + if(main_thread) { + m_n_main_thread_lookups++; + } + + if(m_n_proc_lookups == m_max_n_proc_lookups) { + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "Reached max process lookup number, duration=%" PRIu64 "ms", + m_n_proc_lookups_duration_ns / 1000000); + } + + if(m_max_n_proc_lookups < 0 || m_n_proc_lookups <= m_max_n_proc_lookups) { + bool scan_sockets = false; + + if(m_max_n_proc_socket_lookups < 0 || m_n_proc_lookups <= m_max_n_proc_socket_lookups) { + scan_sockets = true; + if(m_n_proc_lookups == m_max_n_proc_socket_lookups) { + libsinsp_logger()->format(sinsp_logger::SEV_INFO, + "Reached max socket lookup number, tid=%" PRIu64 + ", duration=%" PRIu64 "ms", + tid, + m_n_proc_lookups_duration_ns / 1000000); + } + } + + uint64_t ts = sinsp_utils::get_current_time_ns(); + if(scap_proc_get(m_inspector->get_scap_platform(), tid, &scap_proc, scan_sockets) == + SCAP_SUCCESS) { + have_scap_proc = true; + } + m_n_proc_lookups_duration_ns += sinsp_utils::get_current_time_ns() - ts; + } + + if(have_scap_proc) { + newti->init(&scap_proc); + } else { + // + // Add a fake entry to avoid a continuous lookup + // + newti->m_tid = tid; + newti->m_pid = -1; + newti->m_ptid = -1; + newti->m_reaper_tid = -1; + newti->m_not_expired_children = 0; + newti->m_comm = ""; + newti->m_exe = ""; + newti->m_user.set_uid(0xffffffff); + newti->m_group.set_gid(0xffffffff); + newti->m_loginuser.set_uid(0xffffffff); + } + + // + // Done. Add the new thread to the list. + // + add_thread(std::move(newti), false); + return find_thread(tid, lookup_only); + } + + return sinsp_proc; } /* `lookup_only==true` means that we don't fill the `m_last_tinfo` field */ -const threadinfo_map_t::ptr_t& sinsp_thread_manager::find_thread(int64_t tid, bool lookup_only) -{ +const threadinfo_map_t::ptr_t& sinsp_thread_manager::find_thread(int64_t tid, bool lookup_only) { // // Try looking up in our simple cache // - if(tid == m_last_tid && m_last_tinfo) - { - if (m_sinsp_stats_v2 != nullptr) - { + if(tid == m_last_tid && m_last_tinfo) { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_cached_thread_lookups++; } // This allows us to avoid performing an actual timestamp lookup @@ -2177,25 +1966,19 @@ const threadinfo_map_t::ptr_t& sinsp_thread_manager::find_thread(int64_t tid, bo // const auto& thr = m_threadtable.get_ref(tid); - if(thr) - { - if (m_sinsp_stats_v2 != nullptr) - { + if(thr) { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_noncached_thread_lookups++; } - if(!lookup_only) - { + if(!lookup_only) { m_last_tinfo.reset(); m_last_tid = tid; m_last_tinfo = thr; thr->m_lastaccess_ts = m_inspector->get_lastevent_ts(); } return thr; - } - else - { - if (m_sinsp_stats_v2 != nullptr) - { + } else { + if(m_sinsp_stats_v2 != nullptr) { m_sinsp_stats_v2->m_n_failed_thread_lookups++; } @@ -2203,29 +1986,23 @@ const threadinfo_map_t::ptr_t& sinsp_thread_manager::find_thread(int64_t tid, bo } } -void sinsp_thread_manager::set_max_thread_table_size(uint32_t value) -{ - m_max_thread_table_size = value; +void sinsp_thread_manager::set_max_thread_table_size(uint32_t value) { + m_max_thread_table_size = value; } -std::unique_ptr sinsp_thread_manager::new_entry() const -{ +std::unique_ptr sinsp_thread_manager::new_entry() const { return m_inspector->build_threadinfo(); } -void sinsp_thread_manager::set_tinfo_shared_dynamic_fields(sinsp_threadinfo& tinfo) const -{ - if (tinfo.dynamic_fields() == nullptr) - { +void sinsp_thread_manager::set_tinfo_shared_dynamic_fields(sinsp_threadinfo& tinfo) const { + if(tinfo.dynamic_fields() == nullptr) { tinfo.set_dynamic_fields(dynamic_fields()); } tinfo.get_fdtable().set_dynamic_fields(m_fdtable_dyn_fields); } -void sinsp_thread_manager::set_fdinfo_shared_dynamic_fields(sinsp_fdinfo& fdinfo) const -{ - if (fdinfo.dynamic_fields() == nullptr) - { +void sinsp_thread_manager::set_fdinfo_shared_dynamic_fields(sinsp_fdinfo& fdinfo) const { + if(fdinfo.dynamic_fields() == nullptr) { fdinfo.set_dynamic_fields(m_fdtable_dyn_fields); } } diff --git a/userspace/libsinsp/threadinfo.h b/userspace/libsinsp/threadinfo.h index b9fc2e30ee..6540bc2d59 100644 --- a/userspace/libsinsp/threadinfo.h +++ b/userspace/libsinsp/threadinfo.h @@ -22,8 +22,8 @@ limitations under the License. #ifdef _WIN32 struct iovec { - void *iov_base; /* Starting address */ - size_t iov_len; /* Number of bytes to transfer */ + void* iov_base; /* Starting address */ + size_t iov_len; /* Number of bytes to transfer */ }; #else #include @@ -37,8 +37,7 @@ struct iovec { #include #include -struct erase_fd_params -{ +struct erase_fd_params { bool m_remove_from_table; int64_t m_fd; sinsp_threadinfo* m_tinfo; @@ -61,11 +60,9 @@ struct erase_fd_params \note sinsp_threadinfo is also used to keep process state. For the sinsp library, a process is just a thread with TID=PID. */ -class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry -{ +class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry { public: - class sinsp_userinfo - { + class sinsp_userinfo { public: sinsp_userinfo() { m_uid = 0xffffffff; @@ -74,22 +71,16 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry uint32_t uid() const { return m_uid; } uint32_t gid() const { return m_gid; } std::string name() const { - if (m_name.empty()) - { + if(m_name.empty()) { return (m_uid == 0) ? "root" : ""; - } - else - { + } else { return m_name; } }; std::string homedir() const { - if (m_homedir.empty()) - { + if(m_homedir.empty()) { return (m_uid == 0) ? "/root" : ""; - } - else - { + } else { return m_homedir; } }; @@ -97,48 +88,41 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry void set_uid(uint32_t uid) { m_uid = uid; }; void set_gid(uint32_t gid) { m_gid = gid; }; - void set_name(char *name, size_t length) { m_name.assign(name, length); }; - void set_homedir(char *homedir, size_t length) { m_homedir.assign(homedir, length); }; - void set_shell(char *shell, size_t length) { m_shell.assign(shell, length); }; + void set_name(char* name, size_t length) { m_name.assign(name, length); }; + void set_homedir(char* homedir, size_t length) { m_homedir.assign(homedir, length); }; + void set_shell(char* shell, size_t length) { m_shell.assign(shell, length); }; private: - uint32_t m_uid; ///< User ID - uint32_t m_gid; ///< Group ID - std::string m_name; ///< Username - std::string m_homedir; ///< Home directory - std::string m_shell; ///< Shell program + uint32_t m_uid; ///< User ID + uint32_t m_gid; ///< Group ID + std::string m_name; ///< Username + std::string m_homedir; ///< Home directory + std::string m_shell; ///< Shell program }; - - class sinsp_groupinfo - { + class sinsp_groupinfo { public: - sinsp_groupinfo() { - m_gid = 0xffffffff; - } + sinsp_groupinfo() { m_gid = 0xffffffff; } uint32_t gid() const { return m_gid; }; std::string name() const { - if (m_name.empty()) - { + if(m_name.empty()) { return (m_gid == 0) ? "root" : ""; - } - else - { + } else { return m_name; } }; void set_gid(uint32_t gid) { m_gid = gid; }; - void set_name(char *name, size_t length) { m_name.assign(name, length); }; + void set_name(char* name, size_t length) { m_name.assign(name, length); }; + private: - uint32_t m_gid; ///< Group ID - std::string m_name; ///< Group name + uint32_t m_gid; ///< Group ID + std::string m_name; ///< Group name }; - - sinsp_threadinfo( - sinsp *inspector = nullptr, - const std::shared_ptr& dyn_fields = nullptr); + sinsp_threadinfo(sinsp* inspector = nullptr, + const std::shared_ptr& + dyn_fields = nullptr); virtual ~sinsp_threadinfo(); libsinsp::state::static_struct::field_infos static_fields() const override; @@ -163,10 +147,7 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry */ std::string get_cwd(); - inline void set_cwd(const std::string& v) - { - m_cwd = v; - } + inline void set_cwd(const std::string& v) { m_cwd = v; } /*! \brief Return the values of all environment variables for the process @@ -181,23 +162,22 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry std::string get_env(const std::string& name); /*! - \brief Return concatenated environment variables with the format of "ENV_NAME=value ENV_NAME1=value1" ... + \brief Return concatenated environment variables with the format of "ENV_NAME=value + ENV_NAME1=value1" ... */ std::string concatenate_all_env(); /*! \brief Return true if this is a process' main thread. */ - inline bool is_main_thread() const - { + inline bool is_main_thread() const { return (m_tid == m_pid) || m_flags & PPM_CL_IS_MAIN_THREAD; } /*! \brief Return true if this thread belongs to a pid namespace. */ - inline bool is_in_pid_namespace() const - { + inline bool is_in_pid_namespace() const { // m_tid should be always valid because we read it from the scap event header return (m_flags & PPM_CL_CHILD_IN_PIDNS || (m_tid != m_vtid && m_vtid >= 0)); } @@ -206,45 +186,33 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry \brief Return true if the thread is invalid. Sometimes we create some invalid thread info, if we are not able to scan proc. */ - inline bool is_invalid() const - { - return m_tid < 0 || m_pid < 0 || m_ptid < 0; - } + inline bool is_invalid() const { return m_tid < 0 || m_pid < 0 || m_ptid < 0; } /*! \brief Return true if the thread is dead. */ - inline bool is_dead() const - { - return m_flags & PPM_CL_CLOSED; - } + inline bool is_dead() const { return m_flags & PPM_CL_CLOSED; } /*! \brief Mark thread as dead. */ - inline void set_dead() - { - m_flags |= PPM_CL_CLOSED; - } + inline void set_dead() { m_flags |= PPM_CL_CLOSED; } /*! \brief In some corner cases is possible that a dead main thread could become again alive. For example, when an execve is performed by a secondary thread and the main thread is already dead */ - inline void resurrect_thread() - { + inline void resurrect_thread() { /* If the thread is not dead we do nothing. * It should never happen */ - if(!is_dead()) - { + if(!is_dead()) { return; } m_flags &= ~PPM_CL_CLOSED; - if(!m_tginfo) - { + if(!m_tginfo) { return; } /* we increment again the threadcount since we @@ -254,27 +222,21 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry } /*! - \brief Return the number of alive threads in the thread group, including the thread leader. + \brief Return the number of alive threads in the thread group, including the thread leader. */ - inline uint64_t get_num_threads() const - { - return m_tginfo ? m_tginfo->get_thread_count() : 0; - } + inline uint64_t get_num_threads() const { return m_tginfo ? m_tginfo->get_thread_count() : 0; } /*! - \brief Return the number of alive threads in the thread group, excluding the thread leader. + \brief Return the number of alive threads in the thread group, excluding the thread leader. */ - inline uint64_t get_num_not_leader_threads() const - { - if(!m_tginfo) - { + inline uint64_t get_num_not_leader_threads() const { + if(!m_tginfo) { return 0; } auto main_thread = get_main_thread(); - if(main_thread != nullptr && !main_thread->is_dead()) - { - return m_tginfo->get_thread_count()-1; + if(main_thread != nullptr && !main_thread->is_dead()) { + return m_tginfo->get_thread_count() - 1; } /* we don't have the main thread in the group or it is dead */ return m_tginfo->get_thread_count(); @@ -284,43 +246,32 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry \brief returns true if there is a loop detected in the thread parent state. Needs traverse_parent_state() to have been called first. */ - inline bool parent_loop_detected() const - { - return m_parent_loop_detected; - } + inline bool parent_loop_detected() const { return m_parent_loop_detected; } - inline void set_parent_loop_detected(bool v) - { - m_parent_loop_detected = v; - } + inline void set_parent_loop_detected(bool v) { m_parent_loop_detected = v; } /*! \brief Get the main thread of the process containing this thread. */ - inline sinsp_threadinfo* get_main_thread() - { - if(is_main_thread()) - { + inline sinsp_threadinfo* get_main_thread() { + if(is_main_thread()) { return this; } // This is possible when we have invalid threads - if(m_tginfo == nullptr) - { + if(m_tginfo == nullptr) { return nullptr; } // If we have the main thread in the group, it is always the first one auto possible_main = m_tginfo->get_first_thread(); - if(possible_main == nullptr || !possible_main->is_main_thread()) - { + if(possible_main == nullptr || !possible_main->is_main_thread()) { return nullptr; } return possible_main; } - inline const sinsp_threadinfo* get_main_thread() const - { + inline const sinsp_threadinfo* get_main_thread() const { return const_cast(this)->get_main_thread(); } @@ -337,20 +288,16 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry \return Pointer to the FD information, or NULL if the given FD doesn't exist */ - inline sinsp_fdinfo* get_fd(int64_t fd) - { - if(fd < 0) - { + inline sinsp_fdinfo* get_fd(int64_t fd) { + if(fd < 0) { return NULL; } sinsp_fdtable* fdt = get_fd_table(); - if(fdt) - { - sinsp_fdinfo *fdinfo = fdt->find(fd); - if(fdinfo) - { + if(fdt) { + sinsp_fdinfo* fdinfo = fdt->find(fd); + if(fdinfo) { // Its current name is now its old // name. The name might change as a // result of parsing. @@ -415,13 +362,12 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry // function for each node. If the function returns false, the // traversal stops. // - typedef std::function visitor_func_t; - void traverse_parent_state(visitor_func_t &visitor); + typedef std::function visitor_func_t; + void traverse_parent_state(visitor_func_t& visitor); void assign_children_to_reaper(sinsp_threadinfo* reaper); - inline void add_child(const std::shared_ptr& child) - { + inline void add_child(const std::shared_ptr& child) { m_children.push_front(child); /* Set current thread as parent */ child->m_ptid = m_tid; @@ -430,31 +376,26 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry } /* We call it immediately before removing the thread from the thread table. */ - inline void remove_child_from_parent() - { + inline void remove_child_from_parent() { auto parent = get_parent_thread(); - if(parent == nullptr) - { + if(parent == nullptr) { return; } parent->m_not_expired_children--; /* Clean expired children if necessary. */ - if((parent->m_children.size() - parent->m_not_expired_children) >= DEFAULT_EXPIRED_CHILDREN_THRESHOLD) - { + if((parent->m_children.size() - parent->m_not_expired_children) >= + DEFAULT_EXPIRED_CHILDREN_THRESHOLD) { parent->clean_expired_children(); } } - inline void clean_expired_children() - { + inline void clean_expired_children() { auto child = m_children.begin(); - while(child != m_children.end()) - { + while(child != m_children.end()) { /* This child is expired */ - if(child->expired()) - { + if(child->expired()) { /* `erase` returns the pointer to the next child * no need for manual increment. */ @@ -465,7 +406,7 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry } } - static void populate_cmdline(std::string &cmdline, const sinsp_threadinfo *tinfo); + static void populate_cmdline(std::string& cmdline, const sinsp_threadinfo* tinfo); // Return true if this thread is a part of a healthcheck, // readiness probe, or liveness probe. @@ -488,52 +429,60 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry // // Core state // - int64_t m_tid; ///< The id of this thread - int64_t m_pid; ///< The id of the process containing this thread. In single thread threads, this is equal to tid. - int64_t m_ptid; ///< The id of the process that started this thread. - int64_t m_reaper_tid; ///< The id of the reaper for this thread - int64_t m_sid; ///< The session id of the process containing this thread. - std::string m_comm; ///< Command name (e.g. "top") - std::string m_exe; ///< argv[0] (e.g. "sshd: user@pts/4") - std::string m_exepath; ///< full executable path + int64_t m_tid; ///< The id of this thread + int64_t m_pid; ///< The id of the process containing this thread. In single thread threads, + ///< this is equal to tid. + int64_t m_ptid; ///< The id of the process that started this thread. + int64_t m_reaper_tid; ///< The id of the reaper for this thread + int64_t m_sid; ///< The session id of the process containing this thread. + std::string m_comm; ///< Command name (e.g. "top") + std::string m_exe; ///< argv[0] (e.g. "sshd: user@pts/4") + std::string m_exepath; ///< full executable path bool m_exe_writable; - bool m_exe_upper_layer; ///< True if the executable file belongs to upper layer in overlayfs - bool m_exe_lower_layer; ///< True if the executable file belongs to lower layer in overlayfs - bool m_exe_from_memfd; ///< True if the executable is stored in fileless memory referenced by memfd - std::vector m_args; ///< Command line arguments (e.g. "-d1") - std::vector m_env; ///< Environment variables - std::unique_ptr m_cgroups; ///< subsystem-cgroup pairs - std::string m_container_id; ///< heuristic-based container id - uint32_t m_flags; ///< The thread flags. See the PPM_CL_* declarations in ppm_events_public.h. + bool m_exe_upper_layer; ///< True if the executable file belongs to upper layer in overlayfs + bool m_exe_lower_layer; ///< True if the executable file belongs to lower layer in overlayfs + bool m_exe_from_memfd; ///< True if the executable is stored in fileless memory referenced by + ///< memfd + std::vector m_args; ///< Command line arguments (e.g. "-d1") + std::vector m_env; ///< Environment variables + std::unique_ptr m_cgroups; ///< subsystem-cgroup pairs + std::string m_container_id; ///< heuristic-based container id + uint32_t m_flags; ///< The thread flags. See the PPM_CL_* declarations in ppm_events_public.h. int64_t m_fdlimit; ///< The maximum number of FDs this thread can open - sinsp_userinfo m_user; ///< user infos - sinsp_userinfo m_loginuser; ///< loginuser infos (auid) - sinsp_groupinfo m_group; ///< group infos - uint64_t m_cap_permitted; ///< permitted capabilities - uint64_t m_cap_effective; ///< effective capabilities - uint64_t m_cap_inheritable; ///< inheritable capabilities - uint64_t m_exe_ino; ///< executable inode ino - uint64_t m_exe_ino_ctime; ///< executable inode ctime (last status change time) - uint64_t m_exe_ino_mtime; ///< executable inode mtime (last modification time) - uint64_t m_exe_ino_ctime_duration_clone_ts; ///< duration in ns between executable inode ctime (last status change time) and clone_ts - uint64_t m_exe_ino_ctime_duration_pidns_start; ///< duration in ns between pidns start ts and executable inode ctime (last status change time) if pidns start predates ctime - uint32_t m_vmsize_kb; ///< total virtual memory (as kb). - uint32_t m_vmrss_kb; ///< resident non-swapped memory (as kb). - uint32_t m_vmswap_kb; ///< swapped memory (as kb). - uint64_t m_pfmajor; ///< number of major page faults since start. - uint64_t m_pfminor; ///< number of minor page faults since start. - int64_t m_vtid; ///< The virtual id of this thread. - int64_t m_vpid; ///< The virtual id of the process containing this thread. In single thread threads, this is equal to vtid. - int64_t m_vpgid; // The virtual process group id, as seen from its pid namespace - uint64_t m_pidns_init_start_ts; /// m_tginfo; std::list> m_children; uint64_t m_not_expired_children; - bool m_filtered_out; ///< True if this thread is filtered out by the inspector filter from saving to a capture + bool m_filtered_out; ///< True if this thread is filtered out by the inspector filter from + ///< saving to a capture // In some cases, a threadinfo has a category that identifies // why it was run. Descriptions: @@ -556,24 +505,25 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry // // State for multi-event processing // - int64_t m_lastevent_fd; ///< The FD os the last event used by this thread. - uint64_t m_lastevent_ts; ///< timestamp of the last event for this thread. - uint64_t m_prevevent_ts; ///< timestamp of the event before the last for this thread. - uint64_t m_lastaccess_ts; ///< The last time this thread was looked up. Used when cleaning up the table. - uint64_t m_clone_ts; ///< When the clone that started this process happened. - uint64_t m_lastexec_ts; ///< The last time exec was called + int64_t m_lastevent_fd; ///< The FD os the last event used by this thread. + uint64_t m_lastevent_ts; ///< timestamp of the last event for this thread. + uint64_t m_prevevent_ts; ///< timestamp of the event before the last for this thread. + uint64_t m_lastaccess_ts; ///< The last time this thread was looked up. Used when cleaning up + ///< the table. + uint64_t m_clone_ts; ///< When the clone that started this process happened. + uint64_t m_lastexec_ts; ///< The last time exec was called size_t args_len() const; size_t env_len() const; - void args_to_iovec(struct iovec **iov, int *iovcnt, - std::string &rem) const; + void args_to_iovec(struct iovec** iov, int* iovcnt, std::string& rem) const; - void env_to_iovec(struct iovec **iov, int *iovcnt, - std::string &rem) const; + void env_to_iovec(struct iovec** iov, int* iovcnt, std::string& rem) const; - void cgroups_to_iovec(struct iovec **iov, int *iovcnt, - std::string &rem, const cgroups_t& cgroups) const; + void cgroups_to_iovec(struct iovec** iov, + int* iovcnt, + std::string& rem, + const cgroups_t& cgroups) const; // // State for filtering @@ -584,14 +534,12 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry // // Global state // - sinsp *m_inspector; + sinsp* m_inspector; struct hasher { - size_t operator()(sinsp_threadinfo* tinfo) const - { + size_t operator()(sinsp_threadinfo* tinfo) const { auto main_thread = tinfo->get_main_thread(); - if(main_thread == nullptr) - { + if(main_thread == nullptr) { return 0; } return main_thread->m_program_hash; @@ -599,12 +547,10 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry }; struct comparer { - size_t operator()(sinsp_threadinfo* lhs, sinsp_threadinfo* rhs) const - { + size_t operator()(sinsp_threadinfo* lhs, sinsp_threadinfo* rhs) const { auto lhs_main_thread = lhs->get_main_thread(); auto rhs_main_thread = rhs->get_main_thread(); - if(lhs_main_thread == nullptr || rhs_main_thread == nullptr) - { + if(lhs_main_thread == nullptr || rhs_main_thread == nullptr) { return 0; } return lhs_main_thread->m_program_hash == rhs_main_thread->m_program_hash; @@ -614,21 +560,16 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry /* Note that `fd_table` should be shared with the main thread only if `PPM_CL_CLONE_FILES` * is specified. Today we always specify `PPM_CL_CLONE_FILES` for all threads. */ - inline sinsp_fdtable* get_fd_table() - { - if(!(m_flags & PPM_CL_CLONE_FILES)) - { + inline sinsp_fdtable* get_fd_table() { + if(!(m_flags & PPM_CL_CLONE_FILES)) { return &m_fdtable; - } - else - { + } else { sinsp_threadinfo* root = get_main_thread(); return (root == nullptr) ? nullptr : &(root->get_fdtable()); } } - inline const sinsp_fdtable* get_fd_table() const - { + inline const sinsp_fdtable* get_fd_table() const { return const_cast(this)->get_fd_table(); } @@ -637,7 +578,7 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry void init(scap_threadinfo* pi); void fix_sockets_coming_from_proc(); sinsp_fdinfo* add_fd(int64_t fd, std::unique_ptr fdinfo); - void add_fd_from_scap(scap_fdinfo *fdinfo); + void add_fd_from_scap(scap_fdinfo* fdinfo); void remove_fd(int64_t fd); void update_cwd(std::string_view cwd); void set_args(const char* args, size_t len); @@ -646,96 +587,61 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry void set_cgroups(const char* cgroups, size_t len); void set_cgroups(const std::vector& cgroups); bool is_lastevent_data_valid() const; - inline void set_lastevent_data_validity(bool isvalid) - { - if(isvalid) - { + inline void set_lastevent_data_validity(bool isvalid) { + if(isvalid) { m_lastevent_cpuid = (uint16_t)1; - } - else - { - m_lastevent_cpuid = (uint16_t) - 1; + } else { + m_lastevent_cpuid = (uint16_t)-1; } } void compute_program_hash(); - inline const uint8_t* get_last_event_data() const - { - return m_lastevent_data; - } + inline const uint8_t* get_last_event_data() const { return m_lastevent_data; } - inline uint8_t* get_last_event_data() - { - return m_lastevent_data; - } + inline uint8_t* get_last_event_data() { return m_lastevent_data; } - inline void set_last_event_data(uint8_t* v) - { - m_lastevent_data = v; - } + inline void set_last_event_data(uint8_t* v) { m_lastevent_data = v; } - inline const sinsp_fdtable& get_fdtable() const - { - return m_fdtable; - } + inline const sinsp_fdtable& get_fdtable() const { return m_fdtable; } - inline sinsp_fdtable& get_fdtable() - { - return m_fdtable; - } + inline sinsp_fdtable& get_fdtable() { return m_fdtable; } - inline uint16_t get_lastevent_type() const - { - return m_lastevent_type; - } + inline uint16_t get_lastevent_type() const { return m_lastevent_type; } - inline void set_lastevent_type(uint16_t v) - { - m_lastevent_type = v; - } - - inline uint16_t get_lastevent_cpuid() const - { - return m_lastevent_cpuid; - } + inline void set_lastevent_type(uint16_t v) { m_lastevent_type = v; } - inline void set_lastevent_cpuid(uint16_t v) - { - m_lastevent_cpuid = v; - } + inline uint16_t get_lastevent_cpuid() const { return m_lastevent_cpuid; } - inline const sinsp_evt::category& get_lastevent_category() const - { - return m_lastevent_category; - } + inline void set_lastevent_cpuid(uint16_t v) { m_lastevent_cpuid = v; } - inline sinsp_evt::category& get_lastevent_category() - { + inline const sinsp_evt::category& get_lastevent_category() const { return m_lastevent_category; } + inline sinsp_evt::category& get_lastevent_category() { return m_lastevent_category; } private: sinsp_threadinfo* get_cwd_root(); bool set_env_from_proc(); - size_t strvec_len(const std::vector &strs) const; - void strvec_to_iovec(const std::vector &strs, - struct iovec **iov, int *iovcnt, - std::string &rem) const; - - void add_to_iovec(const std::string &str, - const bool include_trailing_null, - struct iovec &iov, - uint32_t &alen, - std::string &rem) const; + size_t strvec_len(const std::vector& strs) const; + void strvec_to_iovec(const std::vector& strs, + struct iovec** iov, + int* iovcnt, + std::string& rem) const; + + void add_to_iovec(const std::string& str, + const bool include_trailing_null, + struct iovec& iov, + uint32_t& alen, + std::string& rem) const; // // Parameters that can't be accessed directly because they could be in the // parent thread info // - sinsp_fdtable m_fdtable; // The fd table of this thread - std::string m_cwd; // current working directory - uint8_t* m_lastevent_data; // Used by some event parsers to store the last enter event + sinsp_fdtable m_fdtable; // The fd table of this thread + std::string m_cwd; // current working directory + uint8_t* m_lastevent_data; // Used by some event parsers to store the last enter event uint16_t m_lastevent_type; uint16_t m_lastevent_cpuid; @@ -747,101 +653,77 @@ class SINSP_PUBLIC sinsp_threadinfo : public libsinsp::state::table_entry /*@}*/ -class threadinfo_map_t -{ +class threadinfo_map_t { public: - typedef std::function&)> const_shared_ptr_visitor_t; + typedef std::function&)> + const_shared_ptr_visitor_t; typedef std::function const_visitor_t; typedef std::function visitor_t; typedef std::shared_ptr ptr_t; - inline const ptr_t& put(const ptr_t& tinfo) - { + inline const ptr_t& put(const ptr_t& tinfo) { m_threads[tinfo->m_tid] = tinfo; return m_threads[tinfo->m_tid]; } - inline sinsp_threadinfo* get(uint64_t tid) - { + inline sinsp_threadinfo* get(uint64_t tid) { auto it = m_threads.find(tid); - if (it == m_threads.end()) - { - return nullptr; + if(it == m_threads.end()) { + return nullptr; } return it->second.get(); } - inline const ptr_t& get_ref(uint64_t tid) - { + inline const ptr_t& get_ref(uint64_t tid) { auto it = m_threads.find(tid); - if (it == m_threads.end()) - { + if(it == m_threads.end()) { return m_nullptr_ret; } return it->second; } - inline void erase(uint64_t tid) - { - m_threads.erase(tid); - } + inline void erase(uint64_t tid) { m_threads.erase(tid); } - inline void clear() - { - m_threads.clear(); - } + inline void clear() { m_threads.clear(); } - bool const_loop_shared_pointer(const_shared_ptr_visitor_t callback) - { - for (auto& it : m_threads) - { - if (!callback(it.second)) - { + bool const_loop_shared_pointer(const_shared_ptr_visitor_t callback) { + for(auto& it : m_threads) { + if(!callback(it.second)) { return false; } } return true; } - bool const_loop(const_visitor_t callback) const - { - for (const auto& it : m_threads) - { - if (!callback(*it.second)) - { + bool const_loop(const_visitor_t callback) const { + for(const auto& it : m_threads) { + if(!callback(*it.second)) { return false; } } return true; } - bool loop(visitor_t callback) - { - for (auto& it : m_threads) - { - if (!callback(*it.second)) - { + bool loop(visitor_t callback) { + for(auto& it : m_threads) { + if(!callback(*it.second)) { return false; } } return true; } - inline size_t size() const - { - return m_threads.size(); - } + inline size_t size() const { return m_threads.size(); } protected: std::unordered_map m_threads; - const ptr_t m_nullptr_ret; // needed for returning a reference + const ptr_t m_nullptr_ret; // needed for returning a reference }; /////////////////////////////////////////////////////////////////////////////// // This class manages the thread table /////////////////////////////////////////////////////////////////////////////// -class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table -{ +class SINSP_PUBLIC sinsp_thread_manager : public libsinsp::state::table { public: sinsp_thread_manager(sinsp* inspector); void clear(); @@ -853,7 +735,8 @@ class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table void set_tinfo_shared_dynamic_fields(sinsp_threadinfo& tinfo) const; void set_fdinfo_shared_dynamic_fields(sinsp_fdinfo& fdinfo) const; - const threadinfo_map_t::ptr_t& add_thread(std::unique_ptr threadinfo, bool from_scap_proctable); + const threadinfo_map_t::ptr_t& add_thread(std::unique_ptr threadinfo, + bool from_scap_proctable); sinsp_threadinfo* find_new_reaper(sinsp_threadinfo*); void remove_thread(int64_t tid); // Returns true if the table is actually scanned @@ -864,47 +747,43 @@ class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table void reset_child_dependencies(); void create_thread_dependencies_after_proc_scan(); /*! - \brief Look up a thread given its tid and return its information, - and optionally go dig into proc if the thread is not in the thread table. + \brief Look up a thread given its tid and return its information, + and optionally go dig into proc if the thread is not in the thread table. - \param tid the ID of the thread. In case of multi-thread processes, - this corresponds to the PID. - \param query_os_if_not_found if true, the library will search for this - thread's information in proc, use the result to create a new thread - entry, and return the new entry. + \param tid the ID of the thread. In case of multi-thread processes, + this corresponds to the PID. + \param query_os_if_not_found if true, the library will search for this + thread's information in proc, use the result to create a new thread + entry, and return the new entry. - \return the \ref sinsp_threadinfo object containing full thread information - and state. + \return the \ref sinsp_threadinfo object containing full thread information + and state. - \note if you are interested in a process' information, just give this - function with the PID of the process. + \note if you are interested in a process' information, just give this + function with the PID of the process. - @throws a sinsp_exception containing the error string is thrown in case - of failure. - */ + @throws a sinsp_exception containing the error string is thrown in case + of failure. + */ - const threadinfo_map_t::ptr_t& get_thread_ref(int64_t tid, bool query_os_if_not_found = false, bool lookup_only = true, bool main_thread=false); + const threadinfo_map_t::ptr_t& get_thread_ref(int64_t tid, + bool query_os_if_not_found = false, + bool lookup_only = true, + bool main_thread = false); // - // Note: lookup_only should be used when the query for the thread is made - // not as a consequence of an event for that thread arriving, but - // just for lookup reason. In that case, m_lastaccess_ts is not updated - // and m_last_tinfo is not set. - // - const threadinfo_map_t::ptr_t& find_thread(int64_t tid, bool lookup_only); - + // Note: lookup_only should be used when the query for the thread is made + // not as a consequence of an event for that thread arriving, but + // just for lookup reason. In that case, m_lastaccess_ts is not updated + // and m_last_tinfo is not set. + // + const threadinfo_map_t::ptr_t& find_thread(int64_t tid, bool lookup_only); void dump_threads_to_file(scap_dumper_t* dumper); - uint32_t get_thread_count() - { - return (uint32_t)m_threadtable.size(); - } + uint32_t get_thread_count() { return (uint32_t)m_threadtable.size(); } - threadinfo_map_t* get_threads() - { - return &m_threadtable; - } + threadinfo_map_t* get_threads() { return &m_threadtable; } std::set m_server_ports; @@ -913,44 +792,39 @@ class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table int32_t get_m_n_proc_lookups() const { return m_n_proc_lookups; } int32_t get_m_n_main_thread_lookups() const { return m_n_main_thread_lookups; } uint64_t get_m_n_proc_lookups_duration_ns() const { return m_n_proc_lookups_duration_ns; } - void reset_thread_counters() { m_n_proc_lookups = 0; m_n_main_thread_lookups = 0; m_n_proc_lookups_duration_ns = 0; } + void reset_thread_counters() { + m_n_proc_lookups = 0; + m_n_main_thread_lookups = 0; + m_n_proc_lookups_duration_ns = 0; + } void set_m_max_n_proc_lookups(int32_t val) { m_max_n_proc_lookups = val; } void set_m_max_n_proc_socket_lookups(int32_t val) { m_max_n_proc_socket_lookups = val; } // ---- libsinsp::state::table implementation ---- - size_t entries_count() const override - { - return m_threadtable.size(); - } + size_t entries_count() const override { return m_threadtable.size(); } - void clear_entries() override - { - m_threadtable.clear(); - } + void clear_entries() override { m_threadtable.clear(); } std::unique_ptr new_entry() const override; - bool foreach_entry(std::function pred) override - { - return m_threadtable.loop([&pred](sinsp_threadinfo& e){ return pred(e); }); + bool foreach_entry(std::function pred) override { + return m_threadtable.loop([&pred](sinsp_threadinfo& e) { return pred(e); }); } - std::shared_ptr get_entry(const int64_t& key) override - { + std::shared_ptr get_entry(const int64_t& key) override { return find_thread(key, false); } - std::shared_ptr add_entry(const int64_t& key, std::unique_ptr entry) override - { - if (!entry) - { + std::shared_ptr add_entry( + const int64_t& key, + std::unique_ptr entry) override { + if(!entry) { throw sinsp_exception("null entry added to thread table"); } auto tinfo = dynamic_cast(entry.get()); - if (!tinfo) - { + if(!tinfo) { throw sinsp_exception("unknown entry type added to thread table"); } entry.release(); @@ -958,38 +832,33 @@ class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table return add_thread(std::unique_ptr(tinfo), false); } - bool erase_entry(const int64_t& key) override - { + bool erase_entry(const int64_t& key) override { // todo(jasondellaluce): should we trigger the whole removal logic, // or should we just erase the table entry? // todo(jasondellaluce): should we make m_tid_to_remove a list, in case // we have more than one thread removed in a given event loop iteration? - if(m_threadtable.get(key)) - { + if(m_threadtable.get(key)) { this->remove_thread(key); return true; } return false; } - inline const std::shared_ptr& get_thread_group_info(int64_t pid) const - { + inline const std::shared_ptr& get_thread_group_info(int64_t pid) const { auto tgroup = m_thread_groups.find(pid); - if(tgroup != m_thread_groups.end()) - { + if(tgroup != m_thread_groups.end()) { return tgroup->second; } return m_nullptr_tginfo_ret; } - inline void set_thread_group_info(int64_t pid, const std::shared_ptr& tginfo) - { + inline void set_thread_group_info(int64_t pid, + const std::shared_ptr& tginfo) { /* It should be impossible to have a pid conflict... * Right now we manage it but we could also remove it. */ auto ret = m_thread_groups.insert({pid, tginfo}); - if(!ret.second) - { + if(!ret.second) { m_thread_groups.erase(ret.first); m_thread_groups.insert({pid, tginfo}); } @@ -999,20 +868,11 @@ class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table void thread_to_scap(sinsp_threadinfo& tinfo, scap_threadinfo* sctinfo); - inline uint64_t get_last_flush_time_ns() const - { - return m_last_flush_time_ns; - } + inline uint64_t get_last_flush_time_ns() const { return m_last_flush_time_ns; } - inline void set_last_flush_time_ns(uint64_t v) - { - m_last_flush_time_ns = v; - } + inline void set_last_flush_time_ns(uint64_t v) { m_last_flush_time_ns = v; } - inline uint32_t get_max_thread_table_size() const - { - return m_max_thread_table_size; - } + inline uint32_t get_max_thread_table_size() const { return m_max_thread_table_size; } private: inline void clear_thread_pointers(sinsp_threadinfo& threadinfo); @@ -1021,7 +881,8 @@ class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table sinsp* m_inspector; std::shared_ptr m_sinsp_stats_v2; - /* the key is the pid of the group, and the value is a shared pointer to the thread_group_info */ + /* the key is the pid of the group, and the value is a shared pointer to the thread_group_info + */ std::unordered_map> m_thread_groups; threadinfo_map_t m_threadtable; int64_t m_last_tid; @@ -1038,6 +899,8 @@ class SINSP_PUBLIC sinsp_thread_manager: public libsinsp::state::table int32_t m_max_n_proc_socket_lookups = -1; std::shared_ptr m_fdtable_dyn_fields; - const std::shared_ptr m_nullptr_tinfo_ret; // needed for returning a reference - const std::shared_ptr m_nullptr_tginfo_ret; // needed for returning a reference + const std::shared_ptr + m_nullptr_tinfo_ret; // needed for returning a reference + const std::shared_ptr + m_nullptr_tginfo_ret; // needed for returning a reference }; diff --git a/userspace/libsinsp/token_bucket.cpp b/userspace/libsinsp/token_bucket.cpp index a043b25fd5..9965831852 100644 --- a/userspace/libsinsp/token_bucket.cpp +++ b/userspace/libsinsp/token_bucket.cpp @@ -24,32 +24,25 @@ limitations under the License. #include #include -token_bucket::token_bucket(): - token_bucket(sinsp_utils::get_current_time_ns) -{ -} +token_bucket::token_bucket(): token_bucket(sinsp_utils::get_current_time_ns) {} -token_bucket::token_bucket(std::function timer) -{ +token_bucket::token_bucket(std::function timer) { m_timer = timer; init(1, 1); } -void token_bucket::init(double rate, double max_tokens, uint64_t now) -{ +void token_bucket::init(double rate, double max_tokens, uint64_t now) { m_rate = rate; m_max_tokens = max_tokens; m_tokens = max_tokens; m_last_seen = now == 0 ? m_timer() : now; } -bool token_bucket::claim() -{ +bool token_bucket::claim() { return claim(1, m_timer()); } -bool token_bucket::claim(double tokens, uint64_t now) -{ +bool token_bucket::claim(double tokens, uint64_t now) { double tokens_gained = m_rate * ((now - m_last_seen) / (1000000000.0)); m_last_seen = now; @@ -58,16 +51,14 @@ bool token_bucket::claim(double tokens, uint64_t now) // // Cap at max_tokens // - if(m_tokens > m_max_tokens) - { + if(m_tokens > m_max_tokens) { m_tokens = m_max_tokens; } // // If m_tokens is < tokens, can't claim. // - if(m_tokens < tokens) - { + if(m_tokens < tokens) { return false; } @@ -76,12 +67,10 @@ bool token_bucket::claim(double tokens, uint64_t now) return true; } -double token_bucket::get_tokens() -{ +double token_bucket::get_tokens() { return m_tokens; } -uint64_t token_bucket::get_last_seen() -{ +uint64_t token_bucket::get_last_seen() { return m_last_seen; } diff --git a/userspace/libsinsp/token_bucket.h b/userspace/libsinsp/token_bucket.h index fcdfed6b1c..1c6d2ac59c 100644 --- a/userspace/libsinsp/token_bucket.h +++ b/userspace/libsinsp/token_bucket.h @@ -23,8 +23,7 @@ limitations under the License. // A simple token bucket that accumulates tokens at a fixed rate and allows // for limited bursting in the form of "banked" tokens. -class token_bucket -{ +class token_bucket { public: token_bucket(); token_bucket(std::function timer); diff --git a/userspace/libsinsp/tuples.cpp b/userspace/libsinsp/tuples.cpp index 0a99e15295..651971b35c 100644 --- a/userspace/libsinsp/tuples.cpp +++ b/userspace/libsinsp/tuples.cpp @@ -30,100 +30,81 @@ static_assert(sizeof(ipv6addr) == 16); // is_pod check split into is_standard_layout && is_trivial to be C++20 future proof static_assert(std::is_standard_layout::value && std::is_trivial::value); -ipv6addr ipv6addr::empty_address ("0::");//= {0x00000000, 0x00000000, 0x00000000, 0x00000000}; +ipv6addr ipv6addr::empty_address("0::"); //= {0x00000000, 0x00000000, 0x00000000, 0x00000000}; -ipv6addr::ipv6addr(const std::string &str_addr) -{ - if(inet_pton(AF_INET6, str_addr.c_str(), m_b) != 1) - { +ipv6addr::ipv6addr(const std::string &str_addr) { + if(inet_pton(AF_INET6, str_addr.c_str(), m_b) != 1) { throw sinsp_exception("unrecognized IPv6 address " + str_addr); } } -bool ipv6addr::operator==(const ipv6addr &other) const -{ - return (m_b[0] == other.m_b[0] && - m_b[1] == other.m_b[1] && - m_b[2] == other.m_b[2] && - m_b[3] == other.m_b[3]); +bool ipv6addr::operator==(const ipv6addr &other) const { + return (m_b[0] == other.m_b[0] && m_b[1] == other.m_b[1] && m_b[2] == other.m_b[2] && + m_b[3] == other.m_b[3]); } -bool ipv6addr::operator!=(const ipv6addr &other) const -{ +bool ipv6addr::operator!=(const ipv6addr &other) const { return !operator==(other); } -bool ipv6addr::operator<(const ipv6addr &other) const -{ - for(int i = 0; i < 4; i++) - { - if(m_b[i] < other.m_b[i]) return true; - else if(other.m_b[i] < m_b[i]) return false; +bool ipv6addr::operator<(const ipv6addr &other) const { + for(int i = 0; i < 4; i++) { + if(m_b[i] < other.m_b[i]) + return true; + else if(other.m_b[i] < m_b[i]) + return false; } return false; } -bool ipv6addr::in_subnet(const ipv6addr &other) const -{ +bool ipv6addr::in_subnet(const ipv6addr &other) const { // They're in the same subnet if the first 64 bits match // (Assumes convention of first 48 bits for network, next 16 // bits for subnet). - return (m_b[0] == other.m_b[0] && - m_b[1] == other.m_b[1]); + return (m_b[0] == other.m_b[0] && m_b[1] == other.m_b[1]); } -void ipv6net::init(const std::string &str) -{ +void ipv6net::init(const std::string &str) { std::stringstream ss(str); std::string ip, mask; getline(ss, ip, '/'); getline(ss, mask); - if(inet_pton(AF_INET6, ip.c_str(), m_addr.m_b) != 1) - { + if(inet_pton(AF_INET6, ip.c_str(), m_addr.m_b) != 1) { throw sinsp_exception("unrecognized IPv6 address " + std::string(str)); } uint32_t prefix_len = sinsp_numparser::parseu8(mask); - if (prefix_len == 0 || prefix_len > 128) - { + if(prefix_len == 0 || prefix_len > 128) { throw sinsp_exception("invalid v6 netmask " + mask); } m_mask_len_bytes = prefix_len / 8; m_mask_tail_bits = 8 - (prefix_len % 8); - if (m_mask_tail_bits == 8) - { + if(m_mask_tail_bits == 8) { --m_mask_len_bytes; m_mask_tail_bits = 0; } } -ipv6net::ipv6net(const std::string &str) -{ - if(strchr(str.c_str(), '/') != nullptr) - { +ipv6net::ipv6net(const std::string &str) { + if(strchr(str.c_str(), '/') != nullptr) { init(str); - } - else - { + } else { throw sinsp_exception("invalid v6 netmask: " + str); } } -bool ipv6net::in_cidr(const ipv6addr &other) const -{ - auto this_bytes = (const uint8_t*)(&m_addr.m_b); - auto other_bytes = (const uint8_t*)(&other.m_b); +bool ipv6net::in_cidr(const ipv6addr &other) const { + auto this_bytes = (const uint8_t *)(&m_addr.m_b); + auto other_bytes = (const uint8_t *)(&other.m_b); unsigned int i = 0; - for (; i < m_mask_len_bytes; i++) - { - if(this_bytes[i] != other_bytes[i]) - { + for(; i < m_mask_len_bytes; i++) { + if(this_bytes[i] != other_bytes[i]) { return false; } } diff --git a/userspace/libsinsp/tuples.h b/userspace/libsinsp/tuples.h index b82e88168c..acf98d0c82 100644 --- a/userspace/libsinsp/tuples.h +++ b/userspace/libsinsp/tuples.h @@ -26,34 +26,30 @@ limitations under the License. */ /*! - \brief An IPv4 tuple. + \brief An IPv4 tuple. */ -union ipv4tuple -{ - struct - { - uint32_t m_sip; ///< Source (i.e. client) address. - uint32_t m_dip; ///< Destination (i.e. server) address. - uint16_t m_sport; ///< Source (i.e. client) port. - uint16_t m_dport; ///< Destination (i.e. server) port. - uint8_t m_l4proto; ///< Layer 4 protocol (e.g. TCP, UDP...). +union ipv4tuple { + struct { + uint32_t m_sip; ///< Source (i.e. client) address. + uint32_t m_dip; ///< Destination (i.e. server) address. + uint16_t m_sport; ///< Source (i.e. client) port. + uint16_t m_dport; ///< Destination (i.e. server) port. + uint8_t m_l4proto; ///< Layer 4 protocol (e.g. TCP, UDP...). } m_fields; - uint8_t m_all[13]; ///< The fields as a raw array ob bytes. Used for hashing. + uint8_t m_all[13]; ///< The fields as a raw array ob bytes. Used for hashing. }; /*! - \brief An IPv4 network. + \brief An IPv4 network. */ -struct ipv4net -{ - uint32_t m_ip; ///< IP addr - uint32_t m_netmask; ///< Subnet mask +struct ipv4net { + uint32_t m_ip; ///< IP addr + uint32_t m_netmask; ///< Subnet mask }; -struct ipv6addr -{ +struct ipv6addr { ipv6addr() = default; - ipv6addr(const std::string& str_addr); + ipv6addr(const std::string &str_addr); uint32_t m_b[4]; bool operator==(const ipv6addr &other) const; @@ -64,65 +60,59 @@ struct ipv6addr static struct ipv6addr empty_address; }; -class ipv6net -{ +class ipv6net { private: ipv6addr m_addr; uint32_t m_mask_len_bytes; uint32_t m_mask_tail_bits; void init(const std::string &str); + public: ipv6net(const std::string &str); bool in_cidr(const ipv6addr &other) const; }; /*! - \brief An IPv6 tuple. + \brief An IPv6 tuple. */ -union ipv6tuple -{ +union ipv6tuple { struct { - - ipv6addr m_sip; ///< source (i.e. client) address. - ipv6addr m_dip; ///< destination (i.e. server) address. - uint16_t m_sport; ///< source (i.e. client) port. - uint16_t m_dport; ///< destination (i.e. server) port. - uint8_t m_l4proto; ///< Layer 4 protocol (e.g. TCP, UDP...) + ipv6addr m_sip; ///< source (i.e. client) address. + ipv6addr m_dip; ///< destination (i.e. server) address. + uint16_t m_sport; ///< source (i.e. client) port. + uint16_t m_dport; ///< destination (i.e. server) port. + uint8_t m_l4proto; ///< Layer 4 protocol (e.g. TCP, UDP...) } m_fields; - uint8_t m_all[37]; ///< The fields as a raw array ob bytes. Used for hashing. + uint8_t m_all[37]; ///< The fields as a raw array ob bytes. Used for hashing. }; /*! - \brief An IPv4 server address. + \brief An IPv4 server address. */ -struct ipv4serverinfo -{ - uint32_t m_ip; ///< address - uint16_t m_port; ///< port - uint8_t m_l4proto; ///< IP protocol +struct ipv4serverinfo { + uint32_t m_ip; ///< address + uint16_t m_port; ///< port + uint8_t m_l4proto; ///< IP protocol }; /*! - \brief An IPv6 server address. + \brief An IPv6 server address. */ -struct ipv6serverinfo -{ - ipv6addr m_ip; ///< address - uint16_t m_port; ///< port +struct ipv6serverinfo { + ipv6addr m_ip; ///< address + uint16_t m_port; ///< port uint8_t m_l4proto; ///< IP protocol }; /*! - \brief A unix socket tuple. + \brief A unix socket tuple. */ -union unix_tuple -{ - struct - { +union unix_tuple { + struct { uint64_t m_source; ///< source OS pointer. - uint64_t m_dest; ///< destination OS pointer. + uint64_t m_dest; ///< destination OS pointer. } m_fields; - uint8_t m_all[16]; ///< The fields as a raw array ob bytes. Used for hashing. + uint8_t m_all[16]; ///< The fields as a raw array ob bytes. Used for hashing. }; /*@}*/ diff --git a/userspace/libsinsp/user.cpp b/userspace/libsinsp/user.cpp index 7a83260707..6ae8af3794 100644 --- a/userspace/libsinsp/user.cpp +++ b/userspace/libsinsp/user.cpp @@ -45,10 +45,8 @@ limitations under the License. #endif #ifdef HAVE_PWD_H -static struct passwd *__getpwuid(uint32_t uid, const std::string &host_root) -{ - if(host_root.empty()) - { +static struct passwd *__getpwuid(uint32_t uid, const std::string &host_root) { + if(host_root.empty()) { // When we don't have any host root set, // leverage NSS (see man nsswitch.conf) return getpwuid(uid); @@ -60,13 +58,10 @@ static struct passwd *__getpwuid(uint32_t uid, const std::string &host_root) static std::string filename(host_root + "/etc/passwd"); auto f = fopen(filename.c_str(), "r"); - if(f) - { + if(f) { struct passwd *p = nullptr; - while((p = fgetpwent(f))) - { - if(uid == p->pw_uid) - { + while((p = fgetpwent(f))) { + if(uid == p->pw_uid) { break; } } @@ -80,10 +75,8 @@ static struct passwd *__getpwuid(uint32_t uid, const std::string &host_root) #endif #ifdef HAVE_GRP_H -static struct group *__getgrgid(uint32_t gid, const std::string &host_root) -{ - if(host_root.empty()) - { +static struct group *__getgrgid(uint32_t gid, const std::string &host_root) { + if(host_root.empty()) { // When we don't have any host root set, // leverage NSS (see man nsswitch.conf) return getgrgid(gid); @@ -95,13 +88,10 @@ static struct group *__getgrgid(uint32_t gid, const std::string &host_root) static std::string filename(host_root + "/etc/group"); auto f = fopen(filename.c_str(), "r"); - if(f) - { + if(f) { struct group *p = nullptr; - while((p = fgetgrent(f))) - { - if(gid == p->gr_gid) - { + while((p = fgetgrent(f))) { + if(gid == p->gr_gid) { break; } } @@ -136,38 +126,37 @@ sinsp_usergroup_manager::sinsp_usergroup_manager(sinsp* inspector) } // clang-format on -void sinsp_usergroup_manager::subscribe_container_mgr() -{ +void sinsp_usergroup_manager::subscribe_container_mgr() { // Do nothing if subscribe_container_mgr() is called in capture mode, because // events shall not be sent as they will be loaded from capture file. - if (m_import_users && (m_inspector->is_live() || m_inspector->is_syscall_plugin())) - { + if(m_import_users && (m_inspector->is_live() || m_inspector->is_syscall_plugin())) { // Emplace container manager listener to delete container users upon container deletion - m_inspector->m_container_manager.subscribe_on_remove_container([&](const sinsp_container_info &cinfo) -> void { - delete_container_users_groups(cinfo); - }); + m_inspector->m_container_manager.subscribe_on_remove_container( + [&](const sinsp_container_info &cinfo) -> void { + delete_container_users_groups(cinfo); + }); } } -void sinsp_usergroup_manager::dump_users_groups(sinsp_dumper& dumper) { - for (const auto &it: m_userlist) { +void sinsp_usergroup_manager::dump_users_groups(sinsp_dumper &dumper) { + for(const auto &it : m_userlist) { std::string container_id = it.first; - const auto& usrlist = m_userlist[container_id]; - for (const auto &user: usrlist) { + const auto &usrlist = m_userlist[container_id]; + for(const auto &user : usrlist) { sinsp_evt evt; - if (user_to_sinsp_event(&user.second, &evt, container_id, PPME_USER_ADDED_E)) { + if(user_to_sinsp_event(&user.second, &evt, container_id, PPME_USER_ADDED_E)) { evt.get_scap_evt()->ts = m_inspector->get_new_ts(); dumper.dump(&evt); } } } - for (const auto &it: m_grouplist) { + for(const auto &it : m_grouplist) { std::string container_id = it.first; - const auto& grplist = m_grouplist[container_id]; - for (const auto &group: grplist) { + const auto &grplist = m_grouplist[container_id]; + for(const auto &group : grplist) { sinsp_evt evt; - if (group_to_sinsp_event(&group.second, &evt, container_id, PPME_GROUP_ADDED_E)) { + if(group_to_sinsp_event(&group.second, &evt, container_id, PPME_GROUP_ADDED_E)) { evt.get_scap_evt()->ts = m_inspector->get_new_ts(); dumper.dump(&evt); } @@ -175,13 +164,10 @@ void sinsp_usergroup_manager::dump_users_groups(sinsp_dumper& dumper) { } } -void sinsp_usergroup_manager::delete_container_users_groups(const sinsp_container_info &cinfo) -{ +void sinsp_usergroup_manager::delete_container_users_groups(const sinsp_container_info &cinfo) { auto usrlist = get_userlist(cinfo.m_id); - if (usrlist) - { - for (auto &u : *usrlist) - { + if(usrlist) { + for(auto &u : *usrlist) { // We do not have a thread id here, as a removed container // means that it has no tIDs anymore. notify_user_changed(&u.second, cinfo.m_id, false); @@ -189,10 +175,8 @@ void sinsp_usergroup_manager::delete_container_users_groups(const sinsp_containe } auto grplist = get_grouplist(cinfo.m_id); - if (grplist) - { - for (auto &g : *grplist) - { + if(grplist) { + for(auto &g : *grplist) { // We do not have a thread id here, as a removed container // means that it has no tIDs anymore. notify_group_changed(&g.second, cinfo.m_id, false); @@ -203,23 +187,21 @@ void sinsp_usergroup_manager::delete_container_users_groups(const sinsp_containe m_grouplist.erase(cinfo.m_id); } -bool sinsp_usergroup_manager::clear_host_users_groups() -{ - if (!m_import_users) - { +bool sinsp_usergroup_manager::clear_host_users_groups() { + if(!m_import_users) { return false; } bool res = false; - if(m_last_flush_time_ns == 0) - { - m_last_flush_time_ns = m_inspector->get_lastevent_ts() - m_inspector->m_usergroups_purging_scan_time_ns + 60 * ONE_SECOND_IN_NS; + if(m_last_flush_time_ns == 0) { + m_last_flush_time_ns = m_inspector->get_lastevent_ts() - + m_inspector->m_usergroups_purging_scan_time_ns + + 60 * ONE_SECOND_IN_NS; } if(m_inspector->get_lastevent_ts() > - m_last_flush_time_ns + m_inspector->m_usergroups_purging_scan_time_ns) - { + m_last_flush_time_ns + m_inspector->m_usergroups_purging_scan_time_ns) { res = true; m_last_flush_time_ns = m_inspector->get_lastevent_ts(); @@ -232,61 +214,69 @@ bool sinsp_usergroup_manager::clear_host_users_groups() return res; } -scap_userinfo *sinsp_usergroup_manager::userinfo_map_insert( - userinfo_map &map, - uint32_t uid, - uint32_t gid, - std::string_view name, - std::string_view home, - std::string_view shell) -{ +scap_userinfo *sinsp_usergroup_manager::userinfo_map_insert(userinfo_map &map, + uint32_t uid, + uint32_t gid, + std::string_view name, + std::string_view home, + std::string_view shell) { auto &usr = map[uid]; usr.uid = uid; usr.gid = gid; // In case the node is configured to use NIS, // some struct passwd* fields may be set to NULL. - strlcpy(usr.name, (name.data() != nullptr) ? std::string(name).c_str() : "", MAX_CREDENTIALS_STR_LEN); - strlcpy(usr.homedir, (home.data() != nullptr) ? std::string(home).c_str() : "", SCAP_MAX_PATH_SIZE); - strlcpy(usr.shell, (shell.data() != nullptr) ? std::string(shell).c_str() : "", SCAP_MAX_PATH_SIZE); + strlcpy(usr.name, + (name.data() != nullptr) ? std::string(name).c_str() : "", + MAX_CREDENTIALS_STR_LEN); + strlcpy(usr.homedir, + (home.data() != nullptr) ? std::string(home).c_str() : "", + SCAP_MAX_PATH_SIZE); + strlcpy(usr.shell, + (shell.data() != nullptr) ? std::string(shell).c_str() : "", + SCAP_MAX_PATH_SIZE); return &usr; } -scap_groupinfo *sinsp_usergroup_manager::groupinfo_map_insert( - groupinfo_map &map, - uint32_t gid, - std::string_view name) -{ +scap_groupinfo *sinsp_usergroup_manager::groupinfo_map_insert(groupinfo_map &map, + uint32_t gid, + std::string_view name) { auto &grp = map[gid]; grp.gid = gid; - strlcpy(grp.name, (name.data() != nullptr) ? std::string(name).c_str() : "", MAX_CREDENTIALS_STR_LEN); + strlcpy(grp.name, + (name.data() != nullptr) ? std::string(name).c_str() : "", + MAX_CREDENTIALS_STR_LEN); return &grp; } -scap_userinfo *sinsp_usergroup_manager::add_user(const std::string &container_id, int64_t pid, uint32_t uid, uint32_t gid, std::string_view name, std::string_view home, std::string_view shell, bool notify) -{ +scap_userinfo *sinsp_usergroup_manager::add_user(const std::string &container_id, + int64_t pid, + uint32_t uid, + uint32_t gid, + std::string_view name, + std::string_view home, + std::string_view shell, + bool notify) { // ignore NSS entries - if(!name.empty() && (name[0] == '+' || name[0] == '-')) - { + if(!name.empty() && (name[0] == '+' || name[0] == '-')) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "NSS user ignored: %.*s", static_cast(name.length()), name.data()); + "NSS user ignored: %.*s", + static_cast(name.length()), + name.data()); return nullptr; } - if (!m_import_users) - { + if(!m_import_users) { m_fallback_user.uid = uid; m_fallback_user.gid = gid; return &m_fallback_user; } scap_userinfo *usr = get_user(container_id, uid); - if(usr) - { + if(usr) { // Update user if it was already there - if (name.data() != nullptr) - { + if(name.data() != nullptr) { strlcpy(usr->name, std::string(name).c_str(), MAX_CREDENTIALS_STR_LEN); strlcpy(usr->homedir, std::string(home).c_str(), SCAP_MAX_PATH_SIZE); strlcpy(usr->shell, std::string(shell).c_str(), SCAP_MAX_PATH_SIZE); @@ -294,90 +284,81 @@ scap_userinfo *sinsp_usergroup_manager::add_user(const std::string &container_id return usr; } - if (container_id.empty()) - { + if(container_id.empty()) { return add_host_user(uid, gid, name, home, shell, notify); } return add_container_user(container_id, pid, uid, notify); } -scap_userinfo *sinsp_usergroup_manager::add_host_user(uint32_t uid, uint32_t gid, std::string_view name, std::string_view home, std::string_view shell, bool notify) -{ +scap_userinfo *sinsp_usergroup_manager::add_host_user(uint32_t uid, + uint32_t gid, + std::string_view name, + std::string_view home, + std::string_view shell, + bool notify) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "adding host user: name: %.*s", static_cast(name.length()), name.data()); + "adding host user: name: %.*s", + static_cast(name.length()), + name.data()); scap_userinfo *retval{nullptr}; - if (name.data() != nullptr) - { - retval = userinfo_map_insert( - m_userlist[""], - uid, - gid, - name, - home, - shell); - } - else - { + if(name.data() != nullptr) { + retval = userinfo_map_insert(m_userlist[""], uid, gid, name, home, shell); + } else { #ifdef HAVE_PWD_H // On Host, try to load info from db - auto* p = __getpwuid(uid, m_host_root); - if (p) - { - retval = userinfo_map_insert( - m_userlist[""], - p->pw_uid, - p->pw_gid, - p->pw_name, - p->pw_dir, - p->pw_shell); + auto *p = __getpwuid(uid, m_host_root); + if(p) { + retval = userinfo_map_insert(m_userlist[""], + p->pw_uid, + p->pw_gid, + p->pw_name, + p->pw_dir, + p->pw_shell); } #endif } - if (notify && retval) - { + if(notify && retval) { notify_user_changed(retval, ""); } return retval; } -scap_userinfo *sinsp_usergroup_manager::add_container_user(const std::string &container_id, int64_t pid, uint32_t uid, bool notify) -{ +scap_userinfo *sinsp_usergroup_manager::add_container_user(const std::string &container_id, + int64_t pid, + uint32_t uid, + bool notify) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "adding container [%s] user %d", container_id.c_str(), uid); + "adding container [%s] user %d", + container_id.c_str(), + uid); scap_userinfo *retval{nullptr}; #if defined(__linux__) && defined HAVE_PWD_H && defined HAVE_FGET__ENT - if(!m_ns_helper->in_own_ns_mnt(pid)) - { + if(!m_ns_helper->in_own_ns_mnt(pid)) { return retval; } std::string path = m_ns_helper->get_pid_root(pid) + "/etc/passwd"; auto pwd_file = fopen(path.c_str(), "r"); - if(pwd_file) - { + if(pwd_file) { auto &userlist = m_userlist[container_id]; - while(auto p = fgetpwent(pwd_file)) - { + while(auto p = fgetpwent(pwd_file)) { // Here we cache all container users - auto *usr = userinfo_map_insert( - userlist, - p->pw_uid, - p->pw_gid, - p->pw_name, - p->pw_dir, - p->pw_shell); - - if(notify) - { + auto *usr = userinfo_map_insert(userlist, + p->pw_uid, + p->pw_gid, + p->pw_name, + p->pw_dir, + p->pw_shell); + + if(notify) { notify_user_changed(usr, container_id); } - if(uid == p->pw_uid) - { + if(uid == p->pw_uid) { retval = usr; } } @@ -388,17 +369,15 @@ scap_userinfo *sinsp_usergroup_manager::add_container_user(const std::string &co return retval; } -bool sinsp_usergroup_manager::rm_user(const string &container_id, uint32_t uid, bool notify) -{ +bool sinsp_usergroup_manager::rm_user(const string &container_id, uint32_t uid, bool notify) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "removing user: container: %s, uid: %d", - container_id.c_str(), uid); + "removing user: container: %s, uid: %d", + container_id.c_str(), + uid); bool res = false; scap_userinfo *usr = get_user(container_id, uid); - if (usr) - { - if (notify) - { + if(usr) { + if(notify) { notify_user_changed(usr, container_id, false); } m_userlist[container_id].erase(uid); @@ -407,99 +386,96 @@ bool sinsp_usergroup_manager::rm_user(const string &container_id, uint32_t uid, return res; } -scap_groupinfo *sinsp_usergroup_manager::add_group(const string &container_id, int64_t pid, uint32_t gid, std::string_view name, bool notify) -{ +scap_groupinfo *sinsp_usergroup_manager::add_group(const string &container_id, + int64_t pid, + uint32_t gid, + std::string_view name, + bool notify) { // ignore NSS entries - if(!name.empty() && (name[0] == '+' || name[0] == '-')) - { + if(!name.empty() && (name[0] == '+' || name[0] == '-')) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "NSS group ignored: %.*s", static_cast(name.length()), name.data()); + "NSS group ignored: %.*s", + static_cast(name.length()), + name.data()); return nullptr; } - if (!m_import_users) - { + if(!m_import_users) { m_fallback_grp.gid = gid; return &m_fallback_grp; } scap_groupinfo *gr = get_group(container_id, gid); - if (gr) - { + if(gr) { // Update group if it was already there - if (name.data() != nullptr) - { + if(name.data() != nullptr) { strlcpy(gr->name, std::string(name).c_str(), MAX_CREDENTIALS_STR_LEN); } return gr; } - if (container_id.empty()) - { + if(container_id.empty()) { return add_host_group(gid, name, notify); } return add_container_group(container_id, pid, gid, notify); } -scap_groupinfo *sinsp_usergroup_manager::add_host_group(uint32_t gid, std::string_view name, bool notify) -{ +scap_groupinfo *sinsp_usergroup_manager::add_host_group(uint32_t gid, + std::string_view name, + bool notify) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "adding host group: name: %.*s", static_cast(name.length()), name.data()); + "adding host group: name: %.*s", + static_cast(name.length()), + name.data()); scap_groupinfo *gr = nullptr; - if (name.data()) - { + if(name.data()) { gr = groupinfo_map_insert(m_grouplist[""], gid, name); - } - else - { + } else { #ifdef HAVE_GRP_H // On Host, try to load info from db - auto* g = __getgrgid(gid, m_host_root); - if (g) - { + auto *g = __getgrgid(gid, m_host_root); + if(g) { gr = groupinfo_map_insert(m_grouplist[""], g->gr_gid, g->gr_name); } #endif } - if (notify && gr) - { + if(notify && gr) { notify_group_changed(gr, "", true); } return gr; } -scap_groupinfo *sinsp_usergroup_manager::add_container_group(const std::string &container_id, int64_t pid, uint32_t gid, bool notify) -{ +scap_groupinfo *sinsp_usergroup_manager::add_container_group(const std::string &container_id, + int64_t pid, + uint32_t gid, + bool notify) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "adding container [%s] group: %d", container_id.c_str(), gid); + "adding container [%s] group: %d", + container_id.c_str(), + gid); scap_groupinfo *retval{nullptr}; #if defined(__linux__) && defined HAVE_GRP_H && defined HAVE_FGET__ENT - if(!m_ns_helper->in_own_ns_mnt(pid)) - { + if(!m_ns_helper->in_own_ns_mnt(pid)) { return retval; } std::string path = m_ns_helper->get_pid_root(pid) + "/etc/group"; auto group_file = fopen(path.c_str(), "r"); - if(group_file) - { + if(group_file) { auto &grouplist = m_grouplist[container_id]; - while(auto g = fgetgrent(group_file)) - { + while(auto g = fgetgrent(group_file)) { // Here we cache all container groups auto *gr = groupinfo_map_insert(grouplist, g->gr_gid, g->gr_name); - if(notify) - { + if(notify) { notify_group_changed(gr, container_id, true); } - if(gid == g->gr_gid) - { + if(gid == g->gr_gid) { retval = gr; } } @@ -510,17 +486,15 @@ scap_groupinfo *sinsp_usergroup_manager::add_container_group(const std::string & return retval; } -bool sinsp_usergroup_manager::rm_group(const string &container_id, uint32_t gid, bool notify) -{ +bool sinsp_usergroup_manager::rm_group(const string &container_id, uint32_t gid, bool notify) { libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "removing group: container: %s, gid: %d", - container_id.c_str(), gid); + "removing group: container: %s, gid: %d", + container_id.c_str(), + gid); bool res = false; scap_groupinfo *gr = get_group(container_id, gid); - if (gr) - { - if (notify) - { + if(gr) { + if(notify) { notify_group_changed(gr, container_id, false); } m_grouplist[container_id].erase(gid); @@ -529,84 +503,75 @@ bool sinsp_usergroup_manager::rm_group(const string &container_id, uint32_t gid, return res; } -const unordered_map* sinsp_usergroup_manager::get_userlist(const string &container_id) -{ - if (m_userlist.find(container_id) == m_userlist.end()) - { +const unordered_map *sinsp_usergroup_manager::get_userlist( + const string &container_id) { + if(m_userlist.find(container_id) == m_userlist.end()) { return nullptr; } return &m_userlist[container_id]; } -scap_userinfo* sinsp_usergroup_manager::get_user(const string &container_id, uint32_t uid) -{ - if (m_userlist.find(container_id) == m_userlist.end()) - { +scap_userinfo *sinsp_usergroup_manager::get_user(const string &container_id, uint32_t uid) { + if(m_userlist.find(container_id) == m_userlist.end()) { return nullptr; } auto &userlist = m_userlist[container_id]; auto it = userlist.find(uid); - if(it == userlist.end()) - { + if(it == userlist.end()) { return nullptr; } return &it->second; } -const unordered_map* sinsp_usergroup_manager::get_grouplist(const string &container_id) -{ - if (m_grouplist.find(container_id) == m_grouplist.end()) - { +const unordered_map *sinsp_usergroup_manager::get_grouplist( + const string &container_id) { + if(m_grouplist.find(container_id) == m_grouplist.end()) { return nullptr; } return &m_grouplist[container_id]; } -scap_groupinfo* sinsp_usergroup_manager::get_group(const std::string &container_id, uint32_t gid) -{ - if (m_grouplist.find(container_id) == m_grouplist.end()) - { +scap_groupinfo *sinsp_usergroup_manager::get_group(const std::string &container_id, uint32_t gid) { + if(m_grouplist.find(container_id) == m_grouplist.end()) { return nullptr; } auto &grplist = m_grouplist[container_id]; auto it = grplist.find(gid); - if(it == grplist.end()) - { + if(it == grplist.end()) { return nullptr; } return &it->second; } -bool sinsp_usergroup_manager::user_to_sinsp_event(const scap_userinfo *user, sinsp_evt* evt, const string &container_id, uint16_t ev_type) -{ +bool sinsp_usergroup_manager::user_to_sinsp_event(const scap_userinfo *user, + sinsp_evt *evt, + const string &container_id, + uint16_t ev_type) { // 6 lens, uid, gid, name, home, shell, container_id - size_t totlen = sizeof(scap_evt) + 6 * sizeof(uint16_t) + - sizeof(uint32_t) + sizeof(uint32_t) + - strlen(user->name) + 1 + - strlen(user->homedir) + 1 + - strlen(user->shell) + 1 + - container_id.length() + 1; + size_t totlen = sizeof(scap_evt) + 6 * sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint32_t) + + strlen(user->name) + 1 + strlen(user->homedir) + 1 + strlen(user->shell) + 1 + + container_id.length() + 1; ASSERT(evt->get_scap_evt_storage() == nullptr); evt->set_scap_evt_storage(new char[totlen]); - evt->set_scap_evt((scap_evt *) evt->get_scap_evt_storage()); + evt->set_scap_evt((scap_evt *)evt->get_scap_evt_storage()); evt->set_cpuid(0); evt->set_num(0); evt->set_inspector(m_inspector); - scap_evt* scapevt = evt->get_scap_evt(); + scap_evt *scapevt = evt->get_scap_evt(); - scapevt->ts = (uint64_t) - 1; + scapevt->ts = (uint64_t)-1; scapevt->tid = -1; scapevt->len = (uint32_t)totlen; scapevt->type = ev_type; scapevt->nparams = 6; - auto* lens = (uint16_t*)((char *)scapevt + sizeof(ppm_evt_hdr)); - char* valptr = (char*)lens + scapevt->nparams * sizeof(uint16_t); + auto *lens = (uint16_t *)((char *)scapevt + sizeof(ppm_evt_hdr)); + char *valptr = (char *)lens + scapevt->nparams * sizeof(uint16_t); lens[0] = sizeof(uint32_t); lens[1] = sizeof(uint32_t); @@ -631,32 +596,32 @@ bool sinsp_usergroup_manager::user_to_sinsp_event(const scap_userinfo *user, sin return true; } -bool sinsp_usergroup_manager::group_to_sinsp_event(const scap_groupinfo *group, sinsp_evt* evt, const string &container_id, uint16_t ev_type) -{ +bool sinsp_usergroup_manager::group_to_sinsp_event(const scap_groupinfo *group, + sinsp_evt *evt, + const string &container_id, + uint16_t ev_type) { // gid, name, container_id - size_t totlen = sizeof(scap_evt) + 3 * sizeof(uint16_t) + - sizeof(uint32_t) + - strlen(group->name) + 1 + - container_id.length() + 1; + size_t totlen = sizeof(scap_evt) + 3 * sizeof(uint16_t) + sizeof(uint32_t) + + strlen(group->name) + 1 + container_id.length() + 1; ASSERT(evt->get_scap_evt_storage() == nullptr); evt->set_scap_evt_storage(new char[totlen]); - evt->set_scap_evt((scap_evt *) evt->get_scap_evt_storage()); + evt->set_scap_evt((scap_evt *)evt->get_scap_evt_storage()); evt->set_cpuid(0); evt->set_num(0); evt->set_inspector(m_inspector); - scap_evt* scapevt = evt->get_scap_evt(); + scap_evt *scapevt = evt->get_scap_evt(); - scapevt->ts = (uint64_t) - 1; + scapevt->ts = (uint64_t)-1; scapevt->tid = -1; scapevt->len = (uint32_t)totlen; scapevt->type = ev_type; scapevt->nparams = 3; - auto* lens = (uint16_t*)((char *)scapevt + sizeof(ppm_evt_hdr)); - char* valptr = (char*)lens + scapevt->nparams * sizeof(uint16_t); + auto *lens = (uint16_t *)((char *)scapevt + sizeof(ppm_evt_hdr)); + char *valptr = (char *)lens + scapevt->nparams * sizeof(uint16_t); lens[0] = sizeof(uint32_t); lens[1] = strlen(group->name) + 1; @@ -672,51 +637,45 @@ bool sinsp_usergroup_manager::group_to_sinsp_event(const scap_groupinfo *group, return true; } -void sinsp_usergroup_manager::notify_user_changed(const scap_userinfo *user, const string &container_id, bool added) -{ - if (!m_inspector->m_inited || !m_import_users) - { +void sinsp_usergroup_manager::notify_user_changed(const scap_userinfo *user, + const string &container_id, + bool added) { + if(!m_inspector->m_inited || !m_import_users) { return; } std::unique_ptr evt(new sinsp_evt()); - if (added) - { + if(added) { user_to_sinsp_event(user, evt.get(), container_id, PPME_USER_ADDED_E); - } - else - { + } else { user_to_sinsp_event(user, evt.get(), container_id, PPME_USER_DELETED_E); } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "notify_user_changed (%d): USER event, queuing to inspector", - user->uid); + "notify_user_changed (%d): USER event, queuing to inspector", + user->uid); m_inspector->handle_async_event(std::move(evt)); } -void sinsp_usergroup_manager::notify_group_changed(const scap_groupinfo *group, const string &container_id, bool added) -{ - if (!m_inspector->m_inited || !m_import_users) - { +void sinsp_usergroup_manager::notify_group_changed(const scap_groupinfo *group, + const string &container_id, + bool added) { + if(!m_inspector->m_inited || !m_import_users) { return; } std::unique_ptr evt(new sinsp_evt()); - if (added) - { + if(added) { group_to_sinsp_event(group, evt.get(), container_id, PPME_GROUP_ADDED_E); - } - else - { + } else { group_to_sinsp_event(group, evt.get(), container_id, PPME_GROUP_DELETED_E); } libsinsp_logger()->format(sinsp_logger::SEV_DEBUG, - "notify_group_changed (%d): GROUP event, queuing to inspector", - group->gid); + "notify_group_changed (%d): GROUP event, queuing to inspector", + group->gid); m_inspector->handle_async_event(std::move(evt)); } diff --git a/userspace/libsinsp/user.h b/userspace/libsinsp/user.h index b9b9c04463..12c5436596 100644 --- a/userspace/libsinsp/user.h +++ b/userspace/libsinsp/user.h @@ -29,7 +29,11 @@ limitations under the License. class sinsp; class sinsp_dumper; class sinsp_evt; -namespace libsinsp { namespace procfs_utils { class ns_helper; }} +namespace libsinsp { +namespace procfs_utils { +class ns_helper; +} +} // namespace libsinsp /* * Basic idea: @@ -38,21 +42,22 @@ namespace libsinsp { namespace procfs_utils { class ns_helper; }} * * if the thread itself is on the HOST, it will call getpwuid/getgrgid, * and store the new user/group together with informations, * eventually notifying any change in users and groups. - * If no information can be retrieved, only uid/gid will be stored as informations, with "" for everything else. - * * if the thread is on a container, the new user/group will be stored using the container id as key, - * without additional info (ie: username, homedir etc etc will be left "") - * because they cannot be retrieved from a container. - * Then, a PPME_{USER,GROUP}_ADDED event is emitted, to allow capture files to rebuild the state. + * If no information can be retrieved, only uid/gid will be stored as informations, with "" + * for everything else. + * * if the thread is on a container, the new user/group will be stored using the container id as + * key, without additional info (ie: username, homedir etc etc will be left "") because they + * cannot be retrieved from a container. Then, a PPME_{USER,GROUP}_ADDED event is emitted, to allow + * capture files to rebuild the state. * - * * on PPME_{USER,GROUP}_ADDED, the new user/group is stored in the m_{user,group}_list, if not present. + * * on PPME_{USER,GROUP}_ADDED, the new user/group is stored in the + * m_{user,group}_list, if not present. * - * * Host users and groups lists are cleared once every DEFAULT_DELETED_USERS_GROUPS_SCAN_TIME_S (1 min by default), - * see sinsp::m_usergroups_purging_scan_time_ns. - * Then, the users and groups will be refreshed as explained above, every time a threadinfo is created. - * This is needed to fetch deleted users/groups, or overwritten ones. - * Note: PPME_USER_DELETED_E is never sent for host users; we miss - * the mechanism to undestand when an user is removed (without calling scap_get_userlist - * and comparing to the already stored one; but that is an heavy operation). + * * Host users and groups lists are cleared once every DEFAULT_DELETED_USERS_GROUPS_SCAN_TIME_S (1 + * min by default), see sinsp::m_usergroups_purging_scan_time_ns. Then, the users and groups will be + * refreshed as explained above, every time a threadinfo is created. This is needed to fetch deleted + * users/groups, or overwritten ones. Note: PPME_USER_DELETED_E is never sent for host users; we + * miss the mechanism to undestand when an user is removed (without calling scap_get_userlist and + * comparing to the already stored one; but that is an heavy operation). * * Containers users and groups gets bulk deleted once the container is cleaned up and * PPME_{USER,GROUP}_DELETED_E event is sent for each of them. * @@ -61,20 +66,19 @@ namespace libsinsp { namespace procfs_utils { class ns_helper; }} * Then, uid 1000 is deleted, and a new uid 1000 is created, named "bar". * We need to be able to tell that the threadinfo user is still "foo". */ -class sinsp_usergroup_manager -{ +class sinsp_usergroup_manager { public: - explicit sinsp_usergroup_manager(sinsp* inspector); + explicit sinsp_usergroup_manager(sinsp *inspector); ~sinsp_usergroup_manager() = default; // Do not call subscribe_container_mgr() in capture mode, because // events shall not be sent as they will be loaded from capture file. void subscribe_container_mgr(); - void dump_users_groups(sinsp_dumper& dumper); + void dump_users_groups(sinsp_dumper &dumper); /*! - \brief Return the table with all the machine users. + \brief Return the table with all the machine users. \return a hash table with the user ID (UID) as the key and the user information as the data. @@ -82,7 +86,8 @@ class sinsp_usergroup_manager table is stored in the trace files. In that case, the returned user list is the one of the machine where the capture happened. */ - const std::unordered_map* get_userlist(const std::string &container_id); + const std::unordered_map *get_userlist( + const std::string &container_id); /*! \brief Lookup for user in the user table. @@ -94,7 +99,7 @@ class sinsp_usergroup_manager table is stored in the trace files. In that case, the returned user list is the one of the machine where the capture happened. */ - scap_userinfo* get_user(const std::string &container_id, uint32_t uid); + scap_userinfo *get_user(const std::string &container_id, uint32_t uid); /*! \brief Return the table with all the machine user groups. @@ -106,7 +111,8 @@ class sinsp_usergroup_manager table is stored in the trace files. In that case, the returned user table is the one of the machine where the capture happened. */ - const std::unordered_map* get_grouplist(const std::string &container_id); + const std::unordered_map *get_grouplist( + const std::string &container_id); /*! \brief Lookup for group in the group table for a container. @@ -118,12 +124,23 @@ class sinsp_usergroup_manager table is stored in the trace files. In that case, the returned group list is the one of the machine where the capture happened. */ - scap_groupinfo* get_group(const std::string &container_id, uint32_t gid); + scap_groupinfo *get_group(const std::string &container_id, uint32_t gid); // Note: pid is an unused parameter when container_id is an empty string // ie: it is only used when adding users/groups from containers. - scap_userinfo *add_user(const std::string &container_id, int64_t pid, uint32_t uid, uint32_t gid, std::string_view name, std::string_view home, std::string_view shell, bool notify = false); - scap_groupinfo *add_group(const std::string &container_id, int64_t pid, uint32_t gid, std::string_view name, bool notify = false); + scap_userinfo *add_user(const std::string &container_id, + int64_t pid, + uint32_t uid, + uint32_t gid, + std::string_view name, + std::string_view home, + std::string_view shell, + bool notify = false); + scap_groupinfo *add_group(const std::string &container_id, + int64_t pid, + uint32_t gid, + std::string_view name, + bool notify = false); bool rm_user(const std::string &container_id, uint32_t uid, bool notify = false); bool rm_group(const std::string &container_id, uint32_t gid, bool notify = false); @@ -138,35 +155,52 @@ class sinsp_usergroup_manager bool m_user_details_enabled; private: - scap_userinfo *add_host_user(uint32_t uid, uint32_t gid, std::string_view name, std::string_view home, std::string_view shell, bool notify); - scap_userinfo *add_container_user(const std::string &container_id, int64_t pid, uint32_t uid, bool notify); + scap_userinfo *add_host_user(uint32_t uid, + uint32_t gid, + std::string_view name, + std::string_view home, + std::string_view shell, + bool notify); + scap_userinfo *add_container_user(const std::string &container_id, + int64_t pid, + uint32_t uid, + bool notify); scap_groupinfo *add_host_group(uint32_t gid, std::string_view name, bool notify); - scap_groupinfo *add_container_group(const std::string &container_id, int64_t pid, uint32_t gid, bool notify); - - bool user_to_sinsp_event(const scap_userinfo *user, sinsp_evt* evt, const std::string &container_id, uint16_t ev_type); - bool group_to_sinsp_event(const scap_groupinfo *group, sinsp_evt* evt, const std::string &container_id, uint16_t ev_type); + scap_groupinfo *add_container_group(const std::string &container_id, + int64_t pid, + uint32_t gid, + bool notify); + + bool user_to_sinsp_event(const scap_userinfo *user, + sinsp_evt *evt, + const std::string &container_id, + uint16_t ev_type); + bool group_to_sinsp_event(const scap_groupinfo *group, + sinsp_evt *evt, + const std::string &container_id, + uint16_t ev_type); void delete_container_users_groups(const sinsp_container_info &cinfo); - void notify_user_changed(const scap_userinfo *user, const std::string &container_id, bool added = true); - void notify_group_changed(const scap_groupinfo *group, const std::string &container_id, bool added = true); + void notify_user_changed(const scap_userinfo *user, + const std::string &container_id, + bool added = true); + void notify_group_changed(const scap_groupinfo *group, + const std::string &container_id, + bool added = true); using userinfo_map = std::unordered_map; using groupinfo_map = std::unordered_map; - scap_userinfo *userinfo_map_insert( - userinfo_map &map, - uint32_t uid, - uint32_t gid, - std::string_view name, - std::string_view home, - std::string_view shell); + scap_userinfo *userinfo_map_insert(userinfo_map &map, + uint32_t uid, + uint32_t gid, + std::string_view name, + std::string_view home, + std::string_view shell); - scap_groupinfo *groupinfo_map_insert( - groupinfo_map &map, - uint32_t gid, - std::string_view name); + scap_groupinfo *groupinfo_map_insert(groupinfo_map &map, uint32_t gid, std::string_view name); std::unordered_map m_userlist; std::unordered_map m_grouplist; @@ -181,4 +215,4 @@ class sinsp_usergroup_manager std::unique_ptr m_ns_helper; }; -#endif // FALCOSECURITY_LIBS_USER_H +#endif // FALCOSECURITY_LIBS_USER_H diff --git a/userspace/libsinsp/utils.cpp b/userspace/libsinsp/utils.cpp index 77a59869b9..4ed6a87a19 100644 --- a/userspace/libsinsp/utils.cpp +++ b/userspace/libsinsp/utils.cpp @@ -30,23 +30,23 @@ limitations under the License. #endif #ifndef _WIN32 - #include - #include - #include - #ifdef __GLIBC__ - #include - #endif - #include - #include - #include - #include - #include - #include +#include +#include +#include +#ifdef __GLIBC__ +#include +#endif +#include +#include +#include +#include +#include +#include #else - #pragma comment(lib, "Ws2_32.lib") - #include - #include "Shlwapi.h" - #pragma comment(lib,"shlwapi.lib") +#pragma comment(lib, "Ws2_32.lib") +#include +#include "Shlwapi.h" +#pragma comment(lib, "shlwapi.lib") #endif #include @@ -71,8 +71,7 @@ sinsp_initializer g_initializer; // // loading time initializations // -sinsp_initializer::sinsp_initializer() -{ +sinsp_initializer::sinsp_initializer() { // // Init the event tables // @@ -88,8 +87,8 @@ sinsp_initializer::sinsp_initializer() // #ifdef _WIN32 WSADATA wsaData; - WORD version = MAKEWORD( 2, 0 ); - WSAStartup( version, &wsaData ); + WORD version = MAKEWORD(2, 0); + WSAStartup(version, &wsaData); #endif } @@ -100,10 +99,8 @@ sinsp_initializer::sinsp_initializer() // // errno to string conversion. // -const char* sinsp_utils::errno_to_str(int32_t code) -{ - switch(-code) - { +const char* sinsp_utils::errno_to_str(int32_t code) { + switch(-code) { case SE_EPERM: return "EPERM"; case SE_ENOENT: @@ -390,10 +387,8 @@ const char* sinsp_utils::errno_to_str(int32_t code) // signal to string conversion. // Only non-extremely-obscure signals are implemented // -const char* sinsp_utils::signal_to_str(uint8_t code) -{ - switch(code) - { +const char* sinsp_utils::signal_to_str(uint8_t code) { + switch(code) { case SE_SIGHUP: return "SIGHUP"; case SE_SIGINT: @@ -461,16 +456,17 @@ const char* sinsp_utils::signal_to_str(uint8_t code) } } -bool sinsp_utils::sockinfo_to_str(sinsp_sockinfo* sinfo, scap_fd_type stype, char* targetbuf, uint32_t targetbuf_size, bool resolve) -{ - if(stype == SCAP_FD_IPV4_SOCK) - { +bool sinsp_utils::sockinfo_to_str(sinsp_sockinfo* sinfo, + scap_fd_type stype, + char* targetbuf, + uint32_t targetbuf_size, + bool resolve) { + if(stype == SCAP_FD_IPV4_SOCK) { uint8_t* sb = (uint8_t*)&sinfo->m_ipv4info.m_fields.m_sip; uint8_t* db = (uint8_t*)&sinfo->m_ipv4info.m_fields.m_dip; if(sinfo->m_ipv4info.m_fields.m_l4proto == SCAP_L4_TCP || - sinfo->m_ipv4info.m_fields.m_l4proto == SCAP_L4_UDP) - { + sinfo->m_ipv4info.m_fields.m_l4proto == SCAP_L4_UDP) { ipv4tuple addr; addr.m_fields.m_sip = sinfo->m_ipv4info.m_fields.m_sip; addr.m_fields.m_sport = sinfo->m_ipv4info.m_fields.m_sport; @@ -478,45 +474,32 @@ bool sinsp_utils::sockinfo_to_str(sinsp_sockinfo* sinfo, scap_fd_type stype, cha addr.m_fields.m_dport = sinfo->m_ipv4info.m_fields.m_dport; addr.m_fields.m_l4proto = sinfo->m_ipv4info.m_fields.m_l4proto; std::string straddr = ipv4tuple_to_string(&addr, resolve); + snprintf(targetbuf, targetbuf_size, "%s", straddr.c_str()); + } else if(sinfo->m_ipv4info.m_fields.m_l4proto == SCAP_L4_ICMP || + sinfo->m_ipv4info.m_fields.m_l4proto == SCAP_L4_RAW) { snprintf(targetbuf, - targetbuf_size, - "%s", - straddr.c_str()); - } - else if(sinfo->m_ipv4info.m_fields.m_l4proto == SCAP_L4_ICMP || - sinfo->m_ipv4info.m_fields.m_l4proto == SCAP_L4_RAW) - { - snprintf(targetbuf, - targetbuf_size, - "%u.%u.%u.%u->%u.%u.%u.%u", - (unsigned int)(uint8_t)sb[0], - (unsigned int)(uint8_t)sb[1], - (unsigned int)(uint8_t)sb[2], - (unsigned int)(uint8_t)sb[3], - (unsigned int)(uint8_t)db[0], - (unsigned int)(uint8_t)db[1], - (unsigned int)(uint8_t)db[2], - (unsigned int)(uint8_t)db[3]); - } - else - { - snprintf(targetbuf, - targetbuf_size, - ""); + targetbuf_size, + "%u.%u.%u.%u->%u.%u.%u.%u", + (unsigned int)(uint8_t)sb[0], + (unsigned int)(uint8_t)sb[1], + (unsigned int)(uint8_t)sb[2], + (unsigned int)(uint8_t)sb[3], + (unsigned int)(uint8_t)db[0], + (unsigned int)(uint8_t)db[1], + (unsigned int)(uint8_t)db[2], + (unsigned int)(uint8_t)db[3]); + } else { + snprintf(targetbuf, targetbuf_size, ""); } - } - else if(stype == SCAP_FD_IPV6_SOCK) - { + } else if(stype == SCAP_FD_IPV6_SOCK) { uint8_t* sip6 = (uint8_t*)sinfo->m_ipv6info.m_fields.m_sip.m_b; uint8_t* dip6 = (uint8_t*)sinfo->m_ipv6info.m_fields.m_dip.m_b; uint8_t* sip = ((uint8_t*)(sinfo->m_ipv6info.m_fields.m_sip.m_b)) + 12; uint8_t* dip = ((uint8_t*)(sinfo->m_ipv6info.m_fields.m_dip.m_b)) + 12; if(sinfo->m_ipv6info.m_fields.m_l4proto == SCAP_L4_TCP || - sinfo->m_ipv6info.m_fields.m_l4proto == SCAP_L4_UDP) - { - if(sinsp_utils::is_ipv4_mapped_ipv6(sip6) && sinsp_utils::is_ipv4_mapped_ipv6(dip6)) - { + sinfo->m_ipv6info.m_fields.m_l4proto == SCAP_L4_UDP) { + if(sinsp_utils::is_ipv4_mapped_ipv6(sip6) && sinsp_utils::is_ipv4_mapped_ipv6(dip6)) { ipv4tuple addr; memcpy(&addr.m_fields.m_sip, sip, sizeof(uint32_t)); addr.m_fields.m_sport = sinfo->m_ipv4info.m_fields.m_sport; @@ -524,70 +507,56 @@ bool sinsp_utils::sockinfo_to_str(sinsp_sockinfo* sinfo, scap_fd_type stype, cha addr.m_fields.m_dport = sinfo->m_ipv4info.m_fields.m_dport; addr.m_fields.m_l4proto = sinfo->m_ipv4info.m_fields.m_l4proto; std::string straddr = ipv4tuple_to_string(&addr, resolve); - snprintf(targetbuf, - targetbuf_size, - "%s", - straddr.c_str()); + snprintf(targetbuf, targetbuf_size, "%s", straddr.c_str()); return true; - } - else - { + } else { char srcstr[INET6_ADDRSTRLEN]; char dststr[INET6_ADDRSTRLEN]; if(inet_ntop(AF_INET6, sip6, srcstr, sizeof(srcstr)) && - inet_ntop(AF_INET6, dip6, dststr, sizeof(dststr))) - { + inet_ntop(AF_INET6, dip6, dststr, sizeof(dststr))) { snprintf(targetbuf, - targetbuf_size, - "%s:%s->%s:%s", - srcstr, - port_to_string(sinfo->m_ipv6info.m_fields.m_sport, sinfo->m_ipv6info.m_fields.m_l4proto, resolve).c_str(), - dststr, - port_to_string(sinfo->m_ipv6info.m_fields.m_dport, sinfo->m_ipv6info.m_fields.m_l4proto, resolve).c_str()); + targetbuf_size, + "%s:%s->%s:%s", + srcstr, + port_to_string(sinfo->m_ipv6info.m_fields.m_sport, + sinfo->m_ipv6info.m_fields.m_l4proto, + resolve) + .c_str(), + dststr, + port_to_string(sinfo->m_ipv6info.m_fields.m_dport, + sinfo->m_ipv6info.m_fields.m_l4proto, + resolve) + .c_str()); return true; } } - } - else if(sinfo->m_ipv6info.m_fields.m_l4proto == SCAP_L4_ICMP) - { - if(sinsp_utils::is_ipv4_mapped_ipv6(sip6) && sinsp_utils::is_ipv4_mapped_ipv6(dip6)) - { + } else if(sinfo->m_ipv6info.m_fields.m_l4proto == SCAP_L4_ICMP) { + if(sinsp_utils::is_ipv4_mapped_ipv6(sip6) && sinsp_utils::is_ipv4_mapped_ipv6(dip6)) { snprintf(targetbuf, - targetbuf_size, - "%u.%u.%u.%u->%u.%u.%u.%u", - (unsigned int)sip[0], - (unsigned int)sip[1], - (unsigned int)sip[2], - (unsigned int)sip[3], - (unsigned int)dip[0], - (unsigned int)dip[1], - (unsigned int)dip[2], - (unsigned int)dip[3]); + targetbuf_size, + "%u.%u.%u.%u->%u.%u.%u.%u", + (unsigned int)sip[0], + (unsigned int)sip[1], + (unsigned int)sip[2], + (unsigned int)sip[3], + (unsigned int)dip[0], + (unsigned int)dip[1], + (unsigned int)dip[2], + (unsigned int)dip[3]); return true; - } - else - { + } else { char srcstr[INET6_ADDRSTRLEN]; char dststr[INET6_ADDRSTRLEN]; if(inet_ntop(AF_INET6, sip6, srcstr, sizeof(srcstr)) && - inet_ntop(AF_INET6, dip6, dststr, sizeof(dststr))) - { - snprintf(targetbuf, - targetbuf_size, - "%s->%s", - srcstr, - dststr); + inet_ntop(AF_INET6, dip6, dststr, sizeof(dststr))) { + snprintf(targetbuf, targetbuf_size, "%s->%s", srcstr, dststr); return true; } } - } - else - { - snprintf(targetbuf, - targetbuf_size, - ""); + } else { + snprintf(targetbuf, targetbuf_size, ""); } } @@ -597,18 +566,18 @@ bool sinsp_utils::sockinfo_to_str(sinsp_sockinfo* sinfo, scap_fd_type stype, cha // // Helper function to move a directory up in a path string // -static inline void rewind_to_parent_path(const char* targetbase, char** tc, const char** pc, uint32_t delta) -{ - if(*tc <= targetbase + 1) - { +static inline void rewind_to_parent_path(const char* targetbase, + char** tc, + const char** pc, + uint32_t delta) { + if(*tc <= targetbase + 1) { (*pc) += delta; return; } (*tc)--; - while((*tc) >= targetbase + 1 && *((*tc) - 1) != '/') - { + while((*tc) >= targetbase + 1 && *((*tc) - 1) != '/') { (*tc)--; } @@ -622,89 +591,77 @@ static inline void rewind_to_parent_path(const char* targetbase, char** tc, cons // following parent directories // - path: the path to copy // -static inline void copy_and_sanitize_path(char* target, char* targetbase, const char *path, char separator) -{ +static inline void copy_and_sanitize_path(char* target, + char* targetbase, + const char* path, + char separator) { char* tc = target; const char* pc = path; g_invalidchar ic; const bool empty_base = target == targetbase; - while(true) - { - if(*pc == 0) - { + while(true) { + if(*pc == 0) { *tc = 0; // // If the path ends with a separator, remove it, as the OS does. // Properly manage case where path is just "/". // - if((tc > (targetbase + 1)) && (*(tc - 1) == separator)) - { + if((tc > (targetbase + 1)) && (*(tc - 1) == separator)) { *(tc - 1) = 0; } return; } - if(ic(*pc)) - { + if(ic(*pc)) { // // Invalid char, substitute with a '.' // *tc = '.'; tc++; pc++; - } - else - { + } else { // // If path begins with '.' or '.' is the first char after a '/' // - if(*pc == '.' && (tc == targetbase || *(tc - 1) == separator)) - { + if(*pc == '.' && (tc == targetbase || *(tc - 1) == separator)) { // // '../', rewind to the previous separator // - if(*(pc + 1) == '.' && *(pc + 2) == separator) - { + if(*(pc + 1) == '.' && *(pc + 2) == separator) { rewind_to_parent_path(targetbase, &tc, &pc, 3); } // // '..', with no separator. // This is valid if we are at the end of the string, and in that case we rewind. // - else if(*(pc + 1) == '.' && *(pc + 2) == 0) - { + else if(*(pc + 1) == '.' && *(pc + 2) == 0) { rewind_to_parent_path(targetbase, &tc, &pc, 2); } // // './', just skip it // - else if(*(pc + 1) == separator) - { + else if(*(pc + 1) == separator) { pc += 2; } // // '.', with no separator. // This is valid if we are at the end of the string, and in that case we rewind. // - else if(*(pc + 1) == 0) - { + else if(*(pc + 1) == 0) { pc++; } // // Otherwise, we leave the string intact. // - else - { + else { *tc = *pc; pc++; tc++; } - } - else if(*pc == separator) - { + } else if(*pc == separator) { // // separator: // * if the last char is already a separator, skip it @@ -713,19 +670,15 @@ static inline void copy_and_sanitize_path(char* target, char* targetbase, const // Example: "/foo/../a" -> "/a" BUT "foo/../a" -> "a" // -> Otherwise: "foo/../a" -> "/a" // - if((tc > targetbase && *(tc - 1) == separator) || (tc == targetbase && !empty_base)) - { + if((tc > targetbase && *(tc - 1) == separator) || + (tc == targetbase && !empty_base)) { pc++; - } - else - { + } else { *tc = *pc; tc++; pc++; } - } - else - { + } else { // // Normal char, copy it // @@ -743,79 +696,70 @@ static inline void copy_and_sanitize_path(char* target, char* targetbase, const * path1 is not sanitized. * If path2 is absolute, we only account for it. */ -static inline bool concatenate_paths_(char* target, uint32_t targetlen, const char* path1, uint32_t len1, - const char* path2, uint32_t len2) -{ - if(targetlen < (len1 + len2 + 1)) - { +static inline bool concatenate_paths_(char* target, + uint32_t targetlen, + const char* path1, + uint32_t len1, + const char* path2, + uint32_t len2) { + if(targetlen < (len1 + len2 + 1)) { strlcpy(target, "/PATH_TOO_LONG", targetlen); return false; } - if(len2 != 0 && path2[0] != '/') - { + if(len2 != 0 && path2[0] != '/') { memcpy(target, path1, len1); copy_and_sanitize_path(target + len1, target, path2, '/'); return true; - } - else - { + } else { target[0] = 0; copy_and_sanitize_path(target, target, path2, '/'); return false; } } -std::string sinsp_utils::concatenate_paths(std::string_view path1, std::string_view path2) -{ +std::string sinsp_utils::concatenate_paths(std::string_view path1, std::string_view path2) { char fullpath[SCAP_MAX_PATH_SIZE]; - concatenate_paths_(fullpath, SCAP_MAX_PATH_SIZE, path1.data(), (uint32_t)path1.length(), path2.data(), - path2.size()); + concatenate_paths_(fullpath, + SCAP_MAX_PATH_SIZE, + path1.data(), + (uint32_t)path1.length(), + path2.data(), + path2.size()); return std::string(fullpath); } - -bool sinsp_utils::is_ipv4_mapped_ipv6(uint8_t* paddr) -{ +bool sinsp_utils::is_ipv4_mapped_ipv6(uint8_t* paddr) { if(paddr[0] == 0 && paddr[1] == 0 && paddr[2] == 0 && paddr[3] == 0 && paddr[4] == 0 && - paddr[5] == 0 && paddr[6] == 0 && paddr[7] == 0 && paddr[8] == 0 && paddr[9] == 0 && - ( - ( paddr[10] == 0xff && paddr[11] == 0xff) || // A real IPv4 address - (paddr[10] == 0 && paddr[11] == 0 && paddr[12] == 0 && paddr[13] == 0 && paddr[14] == 0 && paddr[15] == 0) // all zero address, assume IPv4 as well - ) - ) - { + paddr[5] == 0 && paddr[6] == 0 && paddr[7] == 0 && paddr[8] == 0 && paddr[9] == 0 && + ((paddr[10] == 0xff && paddr[11] == 0xff) || // A real IPv4 address + (paddr[10] == 0 && paddr[11] == 0 && paddr[12] == 0 && paddr[13] == 0 && paddr[14] == 0 && + paddr[15] == 0) // all zero address, assume IPv4 as well + )) { return true; - } - else - { + } else { return false; } } -const ppm_param_info* sinsp_utils::find_longest_matching_evt_param(std::string_view name) -{ +const ppm_param_info* sinsp_utils::find_longest_matching_evt_param(std::string_view name) { uint32_t maxlen = 0; const ppm_param_info* res = nullptr; const auto name_len = name.size(); - for(uint32_t j = 0; j < PPM_EVENT_MAX; j++) - { + for(uint32_t j = 0; j < PPM_EVENT_MAX; j++) { const ppm_event_info* ei = &g_infotables.m_event_info[j]; - for(uint32_t k = 0; k < ei->nparams; k++) - { + for(uint32_t k = 0; k < ei->nparams; k++) { const ppm_param_info* pi = &ei->params[k]; const char* an = pi->name; const auto alen = strlen(an); - if (alen > name_len || alen <= maxlen) - { + if(alen > name_len || alen <= maxlen) { continue; } - if (name.compare(0, alen, pi->name) == 0) - { + if(name.compare(0, alen, pi->name) == 0) { res = pi; maxlen = alen; } @@ -825,16 +769,16 @@ const ppm_param_info* sinsp_utils::find_longest_matching_evt_param(std::string_v return res; } -uint64_t sinsp_utils::get_current_time_ns() -{ - struct timeval tv; - gettimeofday(&tv, NULL); +uint64_t sinsp_utils::get_current_time_ns() { + struct timeval tv; + gettimeofday(&tv, NULL); - return tv.tv_sec * (uint64_t) 1000000000 + tv.tv_usec * 1000; + return tv.tv_sec * (uint64_t)1000000000 + tv.tv_usec * 1000; } -bool sinsp_utils::glob_match(const char *pattern, const char *string, const bool& case_insensitive) -{ +bool sinsp_utils::glob_match(const char* pattern, + const char* string, + const bool& case_insensitive) { #ifdef _WIN32 return PathMatchSpec(string, pattern) == TRUE; #else @@ -843,21 +787,21 @@ bool sinsp_utils::glob_match(const char *pattern, const char *string, const bool #endif } -void sinsp_utils::split_container_image(const std::string &image, - std::string &hostname, - std::string &port, - std::string &name, - std::string &tag, - std::string &digest, - bool split_repo) -{ - auto split = [](const std::string &src, std::string &part1, std::string &part2, const std::string& sep) - { +void sinsp_utils::split_container_image(const std::string& image, + std::string& hostname, + std::string& port, + std::string& name, + std::string& tag, + std::string& digest, + bool split_repo) { + auto split = [](const std::string& src, + std::string& part1, + std::string& part2, + const std::string& sep) { size_t pos = src.find(sep); - if(pos != std::string::npos) - { + if(pos != std::string::npos) { part1 = src.substr(0, pos); - part2 = src.substr(pos+1); + part2 = src.substr(pos + 1); return true; } return false; @@ -867,75 +811,60 @@ void sinsp_utils::split_container_image(const std::string &image, hostname = port = name = tag = digest = ""; - if(split(image, hostport, rem, "/")) - { + if(split(image, hostport, rem, "/")) { repo = hostport + "/"; - if(!split(hostport, hostname, port, ":")) - { + if(!split(hostport, hostname, port, ":")) { hostname = hostport; port = ""; } - } - else - { + } else { hostname = ""; port = ""; rem = image; } - if(split(rem, rem2, digest, "@")) - { - if(!split(rem2, name, tag, ":")) - { + if(split(rem, rem2, digest, "@")) { + if(!split(rem2, name, tag, ":")) { name = rem2; tag = ""; } - } - else - { + } else { digest = ""; - if(!split(rem, name, tag, ":")) - { + if(!split(rem, name, tag, ":")) { name = rem; tag = ""; } } - if(!split_repo) - { + if(!split_repo) { name = repo + name; } } -static int32_t gmt2local(time_t t) -{ +static int32_t gmt2local(time_t t) { int dt, dir; struct tm *gmt, *tmp_gmt, *loc; struct tm sgmt; - if(t == 0) - { + if(t == 0) { t = time(NULL); } gmt = &sgmt; tmp_gmt = gmtime(&t); - if (tmp_gmt == NULL) - { + if(tmp_gmt == NULL) { throw sinsp_exception("cannot get gmtime"); } *gmt = *tmp_gmt; loc = localtime(&t); - if(loc == NULL) - { + if(loc == NULL) { throw sinsp_exception("cannot get localtime"); } dt = (loc->tm_hour - gmt->tm_hour) * 60 * 60 + (loc->tm_min - gmt->tm_min) * 60; dir = loc->tm_year - gmt->tm_year; - if(dir == 0) - { + if(dir == 0) { dir = loc->tm_yday - gmt->tm_yday; } @@ -944,9 +873,8 @@ static int32_t gmt2local(time_t t) return dt; } -void sinsp_utils::ts_to_string(uint64_t ts, std::string* res, bool date, bool ns) -{ - struct tm *tm; +void sinsp_utils::ts_to_string(uint64_t ts, std::string* res, bool date, bool ns) { + struct tm* tm; time_t Time; uint64_t sec = ts / ONE_SECOND_IN_NS; uint64_t nsec = ts % ONE_SECOND_IN_NS; @@ -955,58 +883,53 @@ void sinsp_utils::ts_to_string(uint64_t ts, std::string* res, bool date, bool ns int32_t bufsize = 0; char buf[256]; - if(date) - { + if(date) { Time = (sec + thiszone) - s; - tm = gmtime (&Time); - if(!tm) - { + tm = gmtime(&Time); + if(!tm) { bufsize = sprintf(buf, " "); - } - else - { - bufsize = sprintf(buf, "%04d-%02d-%02d ", - tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday); + } else { + bufsize = sprintf(buf, + "%04d-%02d-%02d ", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday); } } - if(ns) - { - sprintf(buf + bufsize, "%02d:%02d:%02d.%09u", - s / 3600, (s % 3600) / 60, s % 60, (unsigned)nsec); - } - else - { - sprintf(buf + bufsize, "%02d:%02d:%02d", - s / 3600, (s % 3600) / 60, s % 60); + if(ns) { + sprintf(buf + bufsize, + "%02d:%02d:%02d.%09u", + s / 3600, + (s % 3600) / 60, + s % 60, + (unsigned)nsec); + } else { + sprintf(buf + bufsize, "%02d:%02d:%02d", s / 3600, (s % 3600) / 60, s % 60); } *res = buf; } #define TS_STR_FMT "YYYY-MM-DDTHH:MM:SS-0000" -void sinsp_utils::ts_to_iso_8601(uint64_t ts, std::string* res) -{ - static const char *fmt = TS_STR_FMT; +void sinsp_utils::ts_to_iso_8601(uint64_t ts, std::string* res) { + static const char* fmt = TS_STR_FMT; char buf[sizeof(TS_STR_FMT)]; uint64_t ns = ts % ONE_SECOND_IN_NS; time_t sec = ts / ONE_SECOND_IN_NS; - if(strftime(buf, sizeof(buf), "%FT%T", gmtime(&sec)) == 0) - { + if(strftime(buf, sizeof(buf), "%FT%T", gmtime(&sec)) == 0) { *res = fmt; return; } *res = buf; - if(sprintf(buf, ".%09u", (unsigned) ns) < 0) - { + if(sprintf(buf, ".%09u", (unsigned)ns) < 0) { *res = fmt; return; } *res += buf; - if(strftime(buf, sizeof(buf), "%z", gmtime(&sec)) == 0) - { + if(strftime(buf, sizeof(buf), "%z", gmtime(&sec)) == 0) { *res = fmt; return; } @@ -1017,31 +940,28 @@ void sinsp_utils::ts_to_iso_8601(uint64_t ts, std::string* res) // Time utility functions. /////////////////////////////////////////////////////////////////////////////// -time_t get_epoch_utc_seconds(const std::string& time_str, const std::string& fmt) -{ +time_t get_epoch_utc_seconds(const std::string& time_str, const std::string& fmt) { #ifndef _WIN32 - if(time_str.empty() || fmt.empty()) - { + if(time_str.empty() || fmt.empty()) { throw sinsp_exception("get_epoch_utc_seconds(): empty time or format string."); } tm tm_time{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; strptime(time_str.c_str(), fmt.c_str(), &tm_time); - tm_time.tm_isdst = -1; // strptime does not set this, signal timegm to determine DST + tm_time.tm_isdst = -1; // strptime does not set this, signal timegm to determine DST return timegm(&tm_time); #else throw sinsp_exception("get_epoch_utc_seconds() not implemented on Windows"); -#endif // _WIN32 +#endif // _WIN32 } -time_t get_epoch_utc_seconds_now() -{ +time_t get_epoch_utc_seconds_now() { #ifndef _WIN32 time_t rawtime; time(&rawtime); return timegm(gmtime(&rawtime)); #else throw sinsp_exception("get_now_seconds() not implemented on Windows"); -#endif // _WIN32 +#endif // _WIN32 } // gettimeofday() windows implementation @@ -1052,15 +972,14 @@ time_t get_epoch_utc_seconds_now() const __int64 DELTA_EPOCH_IN_MICROSECS = 11644473600000000; -int gettimeofday(struct timeval *tv, struct timezone2 *tz) -{ +int gettimeofday(struct timeval* tv, struct timezone2* tz) { FILETIME ft; __int64 tmpres = 0; TIME_ZONE_INFORMATION tz_winapi; - int rez=0; + int rez = 0; - ZeroMemory(&ft,sizeof(ft)); - ZeroMemory(&tz_winapi,sizeof(tz_winapi)); + ZeroMemory(&ft, sizeof(ft)); + ZeroMemory(&tz_winapi, sizeof(tz_winapi)); GetSystemTimeAsFileTime(&ft); @@ -1073,37 +992,32 @@ int gettimeofday(struct timeval *tv, struct timezone2 *tz) // tmpres /= 10; // convert into microseconds tmpres -= DELTA_EPOCH_IN_MICROSECS; - tv->tv_sec = (__int32)(tmpres*0.000001); - tv->tv_usec =(tmpres%1000000); + tv->tv_sec = (__int32)(tmpres * 0.000001); + tv->tv_usec = (tmpres % 1000000); // // _tzset(),don't work properly, so we use GetTimeZoneInformation // - if(tz) - { - rez=GetTimeZoneInformation(&tz_winapi); - tz->tz_dsttime=(rez==2)?true:false; - tz->tz_minuteswest = tz_winapi.Bias + ((rez==2)?tz_winapi.DaylightBias:0); + if(tz) { + rez = GetTimeZoneInformation(&tz_winapi); + tz->tz_dsttime = (rez == 2) ? true : false; + tz->tz_minuteswest = tz_winapi.Bias + ((rez == 2) ? tz_winapi.DaylightBias : 0); } return 0; } -#endif // _WIN32 +#endif // _WIN32 /////////////////////////////////////////////////////////////////////////////// // gethostname wrapper /////////////////////////////////////////////////////////////////////////////// -std::string sinsp_gethostname() -{ +std::string sinsp_gethostname() { char hname[256]; int res = gethostname(hname, sizeof(hname) / sizeof(hname[0])); - if(res == 0) - { + if(res == 0) { return hname; - } - else - { + } else { ASSERT(false); return ""; } @@ -1112,57 +1026,49 @@ std::string sinsp_gethostname() /////////////////////////////////////////////////////////////////////////////// // tuples to string /////////////////////////////////////////////////////////////////////////////// -std::string port_to_string(uint16_t port, uint8_t l4proto, bool resolve) -{ +std::string port_to_string(uint16_t port, uint8_t l4proto, bool resolve) { std::string ret = ""; - if(resolve) - { + if(resolve) { std::string proto = ""; - if(l4proto == SCAP_L4_TCP) - { + if(l4proto == SCAP_L4_TCP) { proto = "tcp"; - } - else if(l4proto == SCAP_L4_UDP) - { + } else if(l4proto == SCAP_L4_UDP) { proto = "udp"; } // `port` is saved with network byte order - struct servent * res; - res = getservbyport(ntohs(port), (proto != "") ? proto.c_str() : NULL); // best effort! - if (res) - { + struct servent* res; + res = getservbyport(ntohs(port), (proto != "") ? proto.c_str() : NULL); // best effort! + if(res) { ret = res->s_name; - } - else - { + } else { ret = std::to_string(port); } - } - else - { + } else { ret = std::to_string(port); } return ret; } -std::string ipv4serveraddr_to_string(ipv4serverinfo* addr, bool resolve) -{ +std::string ipv4serveraddr_to_string(ipv4serverinfo* addr, bool resolve) { char buf[50]; - uint8_t *ip = (uint8_t *)&addr->m_ip; + uint8_t* ip = (uint8_t*)&addr->m_ip; // IP address is in network byte order regardless of host endianness snprintf(buf, - sizeof(buf), - "%d.%d.%d.%d:%s", ip[0], ip[1], ip[2], ip[3], - port_to_string(addr->m_port, addr->m_l4proto, resolve).c_str()); + sizeof(buf), + "%d.%d.%d.%d:%s", + ip[0], + ip[1], + ip[2], + ip[3], + port_to_string(addr->m_port, addr->m_l4proto, resolve).c_str()); return std::string(buf); } -std::string ipv4tuple_to_string(ipv4tuple* tuple, bool resolve) -{ +std::string ipv4tuple_to_string(ipv4tuple* tuple, bool resolve) { char buf[100]; ipv4serverinfo info; @@ -1182,51 +1088,48 @@ std::string ipv4tuple_to_string(ipv4tuple* tuple, bool resolve) return std::string(buf); } -std::string ipv6serveraddr_to_string(ipv6serverinfo* addr, bool resolve) -{ +std::string ipv6serveraddr_to_string(ipv6serverinfo* addr, bool resolve) { char address[100]; char buf[200]; - if(NULL == inet_ntop(AF_INET6, addr->m_ip.m_b, address, 100)) - { + if(NULL == inet_ntop(AF_INET6, addr->m_ip.m_b, address, 100)) { return std::string(); } - snprintf(buf,200,"%s:%s", - address, - port_to_string(addr->m_port, addr->m_l4proto, resolve).c_str()); + snprintf(buf, + 200, + "%s:%s", + address, + port_to_string(addr->m_port, addr->m_l4proto, resolve).c_str()); return std::string(buf); } -std::string ipv6tuple_to_string(ipv6tuple* tuple, bool resolve) -{ +std::string ipv6tuple_to_string(ipv6tuple* tuple, bool resolve) { char source_address[INET6_ADDRSTRLEN]; - if(NULL == inet_ntop(AF_INET6, tuple->m_fields.m_sip.m_b, source_address, 100)) - { + if(NULL == inet_ntop(AF_INET6, tuple->m_fields.m_sip.m_b, source_address, 100)) { return std::string(); } char destination_address[INET6_ADDRSTRLEN]; - if(NULL == inet_ntop(AF_INET6, tuple->m_fields.m_dip.m_b, destination_address, 100)) - { + if(NULL == inet_ntop(AF_INET6, tuple->m_fields.m_dip.m_b, destination_address, 100)) { return std::string(); } char buf[200]; - snprintf(buf, sizeof(buf), "%s:%s->%s:%s", - source_address, - port_to_string(tuple->m_fields.m_sport, tuple->m_fields.m_l4proto, resolve).c_str(), - destination_address, - port_to_string(tuple->m_fields.m_dport, tuple->m_fields.m_l4proto, resolve).c_str()); + snprintf(buf, + sizeof(buf), + "%s:%s->%s:%s", + source_address, + port_to_string(tuple->m_fields.m_sport, tuple->m_fields.m_l4proto, resolve).c_str(), + destination_address, + port_to_string(tuple->m_fields.m_dport, tuple->m_fields.m_l4proto, resolve).c_str()); return std::string(buf); } -const char* param_type_to_string(ppm_param_type pt) -{ - switch(pt) - { +const char* param_type_to_string(ppm_param_type pt) { + switch(pt) { case PT_NONE: return "NONE"; case PT_INT8: @@ -1323,10 +1226,8 @@ const char* param_type_to_string(ppm_param_type pt) } } -const char* print_format_to_string(ppm_print_format fmt) -{ - switch(fmt) - { +const char* print_format_to_string(ppm_print_format fmt) { + switch(fmt) { case PF_DEC: return "DEC"; case PF_HEX: @@ -1353,27 +1254,22 @@ const char* print_format_to_string(ppm_print_format fmt) // // String split // -std::vector sinsp_split(std::string_view sv, char delim) -{ +std::vector sinsp_split(std::string_view sv, char delim) { std::vector res; - if(sv.length() == 0) - { + if(sv.length() == 0) { return {}; } std::string_view::size_type start = 0; - for (std::string_view::size_type i = 0; i < sv.size(); i++) - { - if (sv[i] == delim) - { + for(std::string_view::size_type i = 0; i < sv.size(); i++) { + if(sv[i] == delim) { res.push_back(std::string(sv.substr(start, i - start))); start = i + 1; } } - if (start <= sv.length()) - { + if(start <= sv.length()) { res.push_back(std::string(sv.substr(start))); } @@ -1383,53 +1279,49 @@ std::vector sinsp_split(std::string_view sv, char delim) // // trim from start // -std::string& ltrim(std::string &s) -{ - s.erase(s.begin(), find_if(s.begin(), s.end(), [](int c) {return !std::isspace(c);})); +std::string& ltrim(std::string& s) { + s.erase(s.begin(), find_if(s.begin(), s.end(), [](int c) { return !std::isspace(c); })); return s; } // // trim from end // -std::string& rtrim(std::string &s) -{ - s.erase(find_if(s.rbegin(), s.rend(), [](int c) {return !std::isspace(c);}).base(), s.end()); +std::string& rtrim(std::string& s) { + s.erase(find_if(s.rbegin(), s.rend(), [](int c) { return !std::isspace(c); }).base(), s.end()); return s; } // // trim from both ends // -std::string& trim(std::string &s) -{ +std::string& trim(std::string& s) { return ltrim(rtrim(s)); } -std::string_view ltrim_sv(std::string_view s) -{ - return s.substr( - std::find_if(s.begin(), s.end(), [](int c) { return !std::isspace(c); }) - s.begin()); +std::string_view ltrim_sv(std::string_view s) { + return s.substr(std::find_if(s.begin(), s.end(), [](int c) { return !std::isspace(c); }) - + s.begin()); } -std::string_view rtrim_sv(std::string_view s) -{ - return s.substr(0, - std::find_if(s.rbegin(), s.rend(), [](int c) { return !std::isspace(c); }).base() - s.begin()); +std::string_view rtrim_sv(std::string_view s) { + return s.substr( + 0, + std::find_if(s.rbegin(), s.rend(), [](int c) { return !std::isspace(c); }).base() - + s.begin()); } -std::string_view trim_sv(std::string_view s) -{ +std::string_view trim_sv(std::string_view s) { return ltrim_sv(rtrim_sv(s)); } -std::string& replace_in_place(std::string& str, const std::string& search, const std::string& replacement) -{ +std::string& replace_in_place(std::string& str, + const std::string& search, + const std::string& replacement) { std::string::size_type ssz = search.length(); std::string::size_type rsz = replacement.length(); std::string::size_type pos = 0; - while((pos = str.find(search, pos)) != std::string::npos) - { + while((pos = str.find(search, pos)) != std::string::npos) { str.replace(pos, ssz, replacement); pos += rsz; ASSERT(pos <= str.length()); @@ -1437,40 +1329,37 @@ std::string& replace_in_place(std::string& str, const std::string& search, const return str; } -std::string replace(const std::string& str, const std::string& search, const std::string& replacement) -{ +std::string replace(const std::string& str, + const std::string& search, + const std::string& replacement) { std::string s(str); replace_in_place(s, search, replacement); return s; } -bool sinsp_utils::startswith(std::string_view s, std::string_view prefix) -{ - if(prefix.empty()) - { +bool sinsp_utils::startswith(std::string_view s, std::string_view prefix) { + if(prefix.empty()) { return false; } size_t prefix_len = prefix.length(); - if(s.length() < prefix_len) - { + if(s.length() < prefix_len) { return false; } return s.compare(0, prefix_len, prefix) == 0; } -bool sinsp_utils::unhex(std::string_view hex_chars, std::vector& hex_bytes) -{ +bool sinsp_utils::unhex(std::string_view hex_chars, std::vector& hex_bytes) { if(hex_chars.size() % 2 != 0 || - !std::all_of(hex_chars.begin(), hex_chars.end(), [](unsigned char c){ return std::isxdigit(c); })) - { + !std::all_of(hex_chars.begin(), hex_chars.end(), [](unsigned char c) { + return std::isxdigit(c); + })) { return false; } std::stringstream ss; - for(size_t i = 0; i < hex_chars.size(); i += 2) - { + for(size_t i = 0; i < hex_chars.size(); i += 2) { int byte; ss << std::hex << hex_chars.at(i) << hex_chars.at(i + 1); ss >> byte; @@ -1482,247 +1371,213 @@ bool sinsp_utils::unhex(std::string_view hex_chars, std::vector& hex_bytes return true; } -const std::vector capabilities { - {"CAP_CHOWN"}, - {"CAP_DAC_OVERRIDE"}, - {"CAP_DAC_READ_SEARCH"}, - {"CAP_FOWNER"}, - {"CAP_FSETID"}, - {"CAP_KILL"}, - {"CAP_SETGID"}, - {"CAP_SETUID"}, - {"CAP_SETPCAP"}, - {"CAP_LINUX_IMMUTABLE"}, - {"CAP_NET_BIND_SERVICE"}, - {"CAP_NET_BROADCAST"}, - {"CAP_NET_ADMIN"}, - {"CAP_NET_RAW"}, - {"CAP_IPC_LOCK"}, - {"CAP_IPC_OWNER"}, - {"CAP_SYS_MODULE"}, - {"CAP_SYS_RAWIO"}, - {"CAP_SYS_CHROOT"}, - {"CAP_SYS_PTRACE"}, - {"CAP_SYS_PACCT"}, - {"CAP_SYS_ADMIN"}, - {"CAP_SYS_BOOT"}, - {"CAP_SYS_NICE"}, - {"CAP_SYS_RESOURCE"}, - {"CAP_SYS_TIME"}, - {"CAP_SYS_TTY_CONFIG"}, - {"CAP_MKNOD"}, - {"CAP_LEASE"}, - {"CAP_AUDIT_WRITE"}, - {"CAP_AUDIT_CONTROL"}, - {"CAP_SETFCAP"}, - {"CAP_MAC_OVERRIDE"}, - {"CAP_MAC_ADMIN"}, - {"CAP_SYSLOG"}, - {"CAP_WAKE_ALARM"}, - {"CAP_BLOCK_SUSPEND"}, - {"CAP_AUDIT_READ"}, - {"CAP_PERFMON"}, - {"CAP_BPF"}, - {"CAP_CHECKPOINT_RESTORE"}, +const std::vector capabilities{ + {"CAP_CHOWN"}, + {"CAP_DAC_OVERRIDE"}, + {"CAP_DAC_READ_SEARCH"}, + {"CAP_FOWNER"}, + {"CAP_FSETID"}, + {"CAP_KILL"}, + {"CAP_SETGID"}, + {"CAP_SETUID"}, + {"CAP_SETPCAP"}, + {"CAP_LINUX_IMMUTABLE"}, + {"CAP_NET_BIND_SERVICE"}, + {"CAP_NET_BROADCAST"}, + {"CAP_NET_ADMIN"}, + {"CAP_NET_RAW"}, + {"CAP_IPC_LOCK"}, + {"CAP_IPC_OWNER"}, + {"CAP_SYS_MODULE"}, + {"CAP_SYS_RAWIO"}, + {"CAP_SYS_CHROOT"}, + {"CAP_SYS_PTRACE"}, + {"CAP_SYS_PACCT"}, + {"CAP_SYS_ADMIN"}, + {"CAP_SYS_BOOT"}, + {"CAP_SYS_NICE"}, + {"CAP_SYS_RESOURCE"}, + {"CAP_SYS_TIME"}, + {"CAP_SYS_TTY_CONFIG"}, + {"CAP_MKNOD"}, + {"CAP_LEASE"}, + {"CAP_AUDIT_WRITE"}, + {"CAP_AUDIT_CONTROL"}, + {"CAP_SETFCAP"}, + {"CAP_MAC_OVERRIDE"}, + {"CAP_MAC_ADMIN"}, + {"CAP_SYSLOG"}, + {"CAP_WAKE_ALARM"}, + {"CAP_BLOCK_SUSPEND"}, + {"CAP_AUDIT_READ"}, + {"CAP_PERFMON"}, + {"CAP_BPF"}, + {"CAP_CHECKPOINT_RESTORE"}, }; -std::string sinsp_utils::caps_to_string(const uint64_t caps) -{ +std::string sinsp_utils::caps_to_string(const uint64_t caps) { std::string res; - for(size_t i = 0; i < capabilities.size(); ++i) - { + for(size_t i = 0; i < capabilities.size(); ++i) { uint64_t current_cap = (uint64_t)1 << i; - if(caps & current_cap) - { + if(caps & current_cap) { res += capabilities[i]; res += " "; } } - if(res.length() > 0) - { + if(res.length() > 0) { res = res.substr(0, res.length() - 1); } return res; } -uint64_t sinsp_utils::get_max_caps() -{ +uint64_t sinsp_utils::get_max_caps() { return ((uint64_t)1 << capabilities.size()) - 1; } /////////////////////////////////////////////////////////////////////////////// // sinsp_numparser implementation /////////////////////////////////////////////////////////////////////////////// -uint8_t sinsp_numparser::parseu8(const std::string& str) -{ +uint8_t sinsp_numparser::parseu8(const std::string& str) { uint32_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRIu32 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRIu32 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return (uint8_t)res; } -int8_t sinsp_numparser::parsed8(const std::string& str) -{ +int8_t sinsp_numparser::parsed8(const std::string& str) { int32_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRId32 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRId32 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return (int8_t)res; } -uint16_t sinsp_numparser::parseu16(const std::string& str) -{ +uint16_t sinsp_numparser::parseu16(const std::string& str) { uint32_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRIu32 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRIu32 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return (uint16_t)res; } -int16_t sinsp_numparser::parsed16(const std::string& str) -{ +int16_t sinsp_numparser::parsed16(const std::string& str) { int32_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRId32 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRId32 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return (int16_t)res; } -uint32_t sinsp_numparser::parseu32(const std::string& str) -{ +uint32_t sinsp_numparser::parseu32(const std::string& str) { uint32_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRIu32 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRIu32 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return res; } -int32_t sinsp_numparser::parsed32(const std::string& str) -{ +int32_t sinsp_numparser::parsed32(const std::string& str) { int32_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRId32 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRId32 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return res; } -uint64_t sinsp_numparser::parseu64(const std::string& str) -{ +uint64_t sinsp_numparser::parseu64(const std::string& str) { uint64_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRIu64 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRIu64 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return res; } -int64_t sinsp_numparser::parsed64(const std::string& str) -{ +int64_t sinsp_numparser::parsed64(const std::string& str) { int64_t res; char temp; - if(std::sscanf(str.c_str(), "%" PRId64 "%c", &res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRId64 "%c", &res, &temp) != 1) { throw sinsp_exception(str + " is not a valid number"); } return res; } -bool sinsp_numparser::tryparseu32(const std::string& str, uint32_t* res) -{ +bool sinsp_numparser::tryparseu32(const std::string& str, uint32_t* res) { char temp; - if(std::sscanf(str.c_str(), "%" PRIu32 "%c", res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRIu32 "%c", res, &temp) != 1) { return false; } return true; } -bool sinsp_numparser::tryparsed32(const std::string& str, int32_t* res) -{ +bool sinsp_numparser::tryparsed32(const std::string& str, int32_t* res) { char temp; - if(std::sscanf(str.c_str(), "%" PRId32 "%c", res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRId32 "%c", res, &temp) != 1) { return false; } return true; } -bool sinsp_numparser::tryparseu64(const std::string& str, uint64_t* res) -{ +bool sinsp_numparser::tryparseu64(const std::string& str, uint64_t* res) { char temp; - if(std::sscanf(str.c_str(), "%" PRIu64 "%c", res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRIu64 "%c", res, &temp) != 1) { return false; } return true; } -bool sinsp_numparser::tryparsed64(const std::string& str, int64_t* res) -{ +bool sinsp_numparser::tryparsed64(const std::string& str, int64_t* res) { char temp; - if(std::sscanf(str.c_str(), "%" PRId64 "%c", res, &temp) != 1) - { + if(std::sscanf(str.c_str(), "%" PRId64 "%c", res, &temp) != 1) { return false; } return true; } -bool sinsp_numparser::tryparseu32_fast(const char* str, uint32_t strlen, uint32_t* res) -{ +bool sinsp_numparser::tryparseu32_fast(const char* str, uint32_t strlen, uint32_t* res) { const char* p = str; const char* end = str + strlen; *res = 0; - while(p < end) - { - if(*p >= '0' && *p <= '9') - { + while(p < end) { + if(*p >= '0' && *p <= '9') { *res = (*res) * 10 + (*p - '0'); - } - else - { + } else { return false; } @@ -1732,21 +1587,16 @@ bool sinsp_numparser::tryparseu32_fast(const char* str, uint32_t strlen, uint32_ return true; } -bool sinsp_numparser::tryparsed32_fast(const char* str, uint32_t strlen, int32_t* res) -{ +bool sinsp_numparser::tryparsed32_fast(const char* str, uint32_t strlen, int32_t* res) { const char* p = str; const char* end = str + strlen; *res = 0; - while(p < end) - { - if(*p >= '0' && *p <= '9') - { + while(p < end) { + if(*p >= '0' && *p <= '9') { *res = (*res) * 10 + (*p - '0'); - } - else - { + } else { return false; } @@ -1760,35 +1610,33 @@ bool sinsp_numparser::tryparsed32_fast(const char* str, uint32_t strlen, int32_t // socket helpers /////////////////////////////////////////////////////////////////////////////// -bool set_socket_blocking(int sock, bool block) -{ +bool set_socket_blocking(int sock, bool block) { #ifndef _WIN32 int arg = block ? 0 : 1; if(ioctl(sock, FIONBIO, &arg) == -1) #else u_long arg = block ? 0 : 1; if(ioctlsocket(sock, FIONBIO, &arg) == -1) -#endif // _WIN32 +#endif // _WIN32 { return false; } return true; } -unsigned int read_num_possible_cpus(void) -{ - static const char *fcpu = "/sys/devices/system/cpu/possible"; +unsigned int read_num_possible_cpus(void) { + static const char* fcpu = "/sys/devices/system/cpu/possible"; unsigned int start, end, possible_cpus = 0; char buff[128]; - FILE *fp; + FILE* fp; fp = fopen(fcpu, "r"); - if (!fp) { + if(!fp) { return possible_cpus; } - while (fgets(buff, sizeof(buff), fp)) { - if (sscanf(buff, "%u-%u", &start, &end) == 2) { + while(fgets(buff, sizeof(buff), fp)) { + if(sscanf(buff, "%u-%u", &start, &end) == 2) { possible_cpus = start == 0 ? end + 1 : 0; break; } @@ -1802,8 +1650,7 @@ unsigned int read_num_possible_cpus(void) /////////////////////////////////////////////////////////////////////////////// // Log helper /////////////////////////////////////////////////////////////////////////////// -void sinsp_scap_log_fn(const char* component, const char* msg, falcosecurity_log_severity sev) -{ +void sinsp_scap_log_fn(const char* component, const char* msg, falcosecurity_log_severity sev) { std::string prefix = (component == NULL) ? "" : std::string(component) + ": "; libsinsp_logger()->log(prefix + msg, (sinsp_logger::severity)sev); } @@ -1814,139 +1661,140 @@ void sinsp_scap_log_fn(const char* component, const char* msg, falcosecurity_log // unordered_set_to_ordered template -std::set unordered_set_to_ordered(const std::unordered_set& unordered_set) -{ +std::set unordered_set_to_ordered(const std::unordered_set& unordered_set) { std::set s; - for(const auto& val : unordered_set) - { + for(const auto& val : unordered_set) { s.insert(val); } return s; } -template std::set unordered_set_to_ordered(const std::unordered_set& unordered_set); -template std::set unordered_set_to_ordered(const std::unordered_set& unordered_set); +template std::set unordered_set_to_ordered( + const std::unordered_set& unordered_set); +template std::set unordered_set_to_ordered( + const std::unordered_set& unordered_set); // unordered_set_difference, equivalent to SQL left_anti join operation template -std::unordered_set unordered_set_difference(const std::unordered_set& a, const std::unordered_set& b) -{ +std::unordered_set unordered_set_difference(const std::unordered_set& a, + const std::unordered_set& b) { std::unordered_set s; - for(const auto& val : a) - { - if (b.find(val) == b.end()) - { + for(const auto& val : a) { + if(b.find(val) == b.end()) { s.insert(val); } } return s; } -template std::unordered_set unordered_set_difference(const std::unordered_set& a, const std::unordered_set& b); -template std::unordered_set unordered_set_difference(const std::unordered_set& a, const std::unordered_set& b); +template std::unordered_set unordered_set_difference( + const std::unordered_set& a, + const std::unordered_set& b); +template std::unordered_set unordered_set_difference( + const std::unordered_set& a, + const std::unordered_set& b); // set_difference, equivalent to SQL left_anti join operation template -std::set set_difference(const std::set& a, const std::set& b) -{ +std::set set_difference(const std::set& a, const std::set& b) { std::set out; std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(out, out.begin())); return out; } -template std::set set_difference(const std::set& a, const std::set& b); -template std::set set_difference(const std::set& a, const std::set& b); +template std::set set_difference(const std::set& a, + const std::set& b); +template std::set set_difference(const std::set& a, + const std::set& b); // unordered_set_union template -std::unordered_set unordered_set_union(const std::unordered_set& a, const std::unordered_set& b) -{ +std::unordered_set unordered_set_union(const std::unordered_set& a, + const std::unordered_set& b) { std::unordered_set s = a; - for(const auto& val : b) - { + for(const auto& val : b) { s.insert(val); } return s; } -template std::unordered_set unordered_set_union(const std::unordered_set& a, const std::unordered_set& b); -template std::unordered_set unordered_set_union(const std::unordered_set& a, const std::unordered_set& b); +template std::unordered_set unordered_set_union( + const std::unordered_set& a, + const std::unordered_set& b); +template std::unordered_set unordered_set_union(const std::unordered_set& a, + const std::unordered_set& b); // set_union template -std::set set_union(const std::set& a, const std::set& b) -{ +std::set set_union(const std::set& a, const std::set& b) { std::set out; std::set_union(a.begin(), a.end(), b.begin(), b.end(), std::inserter(out, out.begin())); return out; } -template std::set set_union(const std::set& a, const std::set& b); +template std::set set_union(const std::set& a, + const std::set& b); template std::set set_union(const std::set& a, const std::set& b); // unordered_set_intersection template -std::unordered_set unordered_set_intersection(const std::unordered_set& a, const std::unordered_set& b) -{ +std::unordered_set unordered_set_intersection(const std::unordered_set& a, + const std::unordered_set& b) { std::unordered_set s; - for(const auto& val : a) - { - if (b.find(val) != b.end()) - { + for(const auto& val : a) { + if(b.find(val) != b.end()) { s.insert(val); } } return s; } -template std::unordered_set unordered_set_intersection(const std::unordered_set& a, const std::unordered_set& b); -template std::unordered_set unordered_set_intersection(const std::unordered_set& a, const std::unordered_set& b); +template std::unordered_set unordered_set_intersection( + const std::unordered_set& a, + const std::unordered_set& b); +template std::unordered_set unordered_set_intersection( + const std::unordered_set& a, + const std::unordered_set& b); // set_intersection template -std::set set_intersection(const std::set& a, const std::set& b) -{ +std::set set_intersection(const std::set& a, const std::set& b) { std::set out; std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(out, out.begin())); return out; } -template std::set set_intersection(const std::set& a, const std::set& b); -template std::set set_intersection(const std::set& a, const std::set& b); +template std::set set_intersection(const std::set& a, + const std::set& b); +template std::set set_intersection(const std::set& a, + const std::set& b); -std::string concat_set_in_order(const std::unordered_set& s, const std::string& delim) -{ - if (s.empty()) - { +std::string concat_set_in_order(const std::unordered_set& s, + const std::string& delim) { + if(s.empty()) { return ""; } std::set s_ordered = unordered_set_to_ordered(s); std::stringstream ss; - std::copy(s_ordered.begin(), s_ordered.end(), - std::ostream_iterator(ss, delim.c_str())); + std::copy(s_ordered.begin(), + s_ordered.end(), + std::ostream_iterator(ss, delim.c_str())); std::string s_str = ss.str(); return s_str.substr(0, s_str.size() - delim.size()); } -std::string concat_set_in_order(const std::set& s, const std::string& delim) -{ - if (s.empty()) - { +std::string concat_set_in_order(const std::set& s, const std::string& delim) { + if(s.empty()) { return ""; } std::stringstream ss; - std::copy(s.begin(), s.end(), - std::ostream_iterator(ss, delim.c_str())); + std::copy(s.begin(), s.end(), std::ostream_iterator(ss, delim.c_str())); std::string s_str = ss.str(); return s_str.substr(0, s_str.size() - delim.size()); } #define SINSP_UTILS_FORMATBUF_LEN 32 -std::string buffer_to_multiline_hex(const char *buf, size_t size) -{ +std::string buffer_to_multiline_hex(const char* buf, size_t size) { char format_buf[SINSP_UTILS_FORMATBUF_LEN]; std::stringstream ss; - for(size_t i = 0; i < size; i++) - { - if (i % 16 == 0) - { - if (i != 0) - { + for(size_t i = 0; i < size; i++) { + if(i % 16 == 0) { + if(i != 0) { ss << "\n"; } snprintf(format_buf, SINSP_UTILS_FORMATBUF_LEN, "%03lx | ", i); diff --git a/userspace/libsinsp/utils.h b/userspace/libsinsp/utils.h index 4eeaf3cb20..5632dc95ea 100644 --- a/userspace/libsinsp/utils.h +++ b/userspace/libsinsp/utils.h @@ -52,8 +52,7 @@ extern sinsp_evttables g_infotables; // ONE-SHOT INIT-TIME OPERATIONS SHOULD BE DONE IN THE CONSTRUCTOR OF THIS // CLASS TO KEEP THEM UNDER A SINGLE PLACE. /////////////////////////////////////////////////////////////////////////////// -class sinsp_initializer -{ +class sinsp_initializer { public: sinsp_initializer(); }; @@ -61,8 +60,7 @@ class sinsp_initializer /////////////////////////////////////////////////////////////////////////////// // A collection of useful functions /////////////////////////////////////////////////////////////////////////////// -class sinsp_utils -{ +class sinsp_utils { public: // // Convert an errno number into the corresponding compact code @@ -77,24 +75,24 @@ class sinsp_utils // // // - static bool sockinfo_to_str(sinsp_sockinfo* sinfo, scap_fd_type stype, char* targetbuf, uint32_t targetbuf_size, bool resolve = false); + static bool sockinfo_to_str(sinsp_sockinfo* sinfo, + scap_fd_type stype, + char* targetbuf, + uint32_t targetbuf_size, + bool resolve = false); // // Check if string ends with another // - static inline bool endswith(std::string_view str, std::string_view ending) - { - if (ending.size() <= str.size()) - { + static inline bool endswith(std::string_view str, std::string_view ending) { + if(ending.size() <= str.size()) { return (0 == str.compare(str.length() - ending.length(), ending.length(), ending)); } return false; } - static inline bool endswith(const char *str, const char *ending, uint32_t lstr, uint32_t lend) - { - if (lstr >= lend) - { + static inline bool endswith(const char* str, const char* ending, uint32_t lstr, uint32_t lend) { + if(lstr >= lend) { return (0 == memcmp(ending, str + (lstr - lend), lend)); } return 0; @@ -124,37 +122,40 @@ class sinsp_utils static bool is_ipv4_mapped_ipv6(uint8_t* paddr); // - // Given a string, scan the event list and find the longest argument that the input string contains + // Given a string, scan the event list and find the longest argument that the input string + // contains // static const ppm_param_info* find_longest_matching_evt_param(std::string_view name); static uint64_t get_current_time_ns(); - static bool glob_match(const char *pattern, const char *string, const bool& case_insensitive = false); + static bool glob_match(const char* pattern, + const char* string, + const bool& case_insensitive = false); #ifndef _WIN32 // // Print the call stack // static void bt(void); -#endif // _WIN32 +#endif // _WIN32 - static void split_container_image(const std::string &image, - std::string &hostname, - std::string &port, - std::string &name, - std::string &tag, - std::string &digest, - bool split_repo = true); + static void split_container_image(const std::string& image, + std::string& hostname, + std::string& port, + std::string& name, + std::string& tag, + std::string& digest, + bool split_repo = true); /* - * \param res [out] the generated string representation of the provided timestamp - */ + * \param res [out] the generated string representation of the provided timestamp + */ static void ts_to_string(uint64_t ts, std::string* res, bool date, bool ns); /* - * \param res [out] the generated string representation of the provided timestamp - */ + * \param res [out] the generated string representation of the provided timestamp + */ static void ts_to_iso_8601(uint64_t ts, std::string* res); // @@ -169,10 +170,8 @@ class sinsp_utils // little STL thing to sanitize strings /////////////////////////////////////////////////////////////////////////////// -struct g_invalidchar -{ - bool operator()(char c) const - { +struct g_invalidchar { + bool operator()(char c) const { unsigned char uc = static_cast(c); // Exclude all non-printable characters and control characters while // including a wide range of languages (emojis, cyrillic, chinese etc) @@ -180,8 +179,7 @@ struct g_invalidchar } }; -inline void sanitize_string(std::string &str) -{ +inline void sanitize_string(std::string& str) { // It turns out with -O3 (release flags) using erase and // remove_if is slightly faster than the inline version that // was here. It's not faster for -O2, and is actually much @@ -191,49 +189,44 @@ inline void sanitize_string(std::string &str) str.erase(remove_if(str.begin(), str.end(), g_invalidchar()), str.end()); } -inline void remove_duplicate_path_separators(std::string &str) -{ - // Light fd name sanitization if fd is a file - only remove consecutive duplicate separators - if(str.size() < 2) - { - // There is nothing to do if there are 0 or 1 chars in the string, protecting dereference operations - return; - } - - char prev_char = *str.begin(); - - for (auto cur_char_it = str.begin() + 1; cur_char_it != str.end();) - { - if (prev_char == *cur_char_it && prev_char == '/') - { - cur_char_it = str.erase(cur_char_it); - } - else - { - prev_char = *cur_char_it; - cur_char_it++; - } - } +inline void remove_duplicate_path_separators(std::string& str) { + // Light fd name sanitization if fd is a file - only remove consecutive duplicate separators + if(str.size() < 2) { + // There is nothing to do if there are 0 or 1 chars in the string, protecting dereference + // operations + return; + } + + char prev_char = *str.begin(); + + for(auto cur_char_it = str.begin() + 1; cur_char_it != str.end();) { + if(prev_char == *cur_char_it && prev_char == '/') { + cur_char_it = str.erase(cur_char_it); + } else { + prev_char = *cur_char_it; + cur_char_it++; + } + } } /////////////////////////////////////////////////////////////////////////////// // Time utility functions. /////////////////////////////////////////////////////////////////////////////// -time_t get_epoch_utc_seconds(const std::string& time_str, const std::string& fmt = "%Y-%m-%dT%H:%M:%SZ"); +time_t get_epoch_utc_seconds(const std::string& time_str, + const std::string& fmt = "%Y-%m-%dT%H:%M:%SZ"); time_t get_epoch_utc_seconds_now(); // Time functions for Windows #ifdef _WIN32 -struct timezone2 -{ - int32_t tz_minuteswest; - bool tz_dsttime; +struct timezone2 { + int32_t tz_minuteswest; + bool tz_dsttime; }; -SINSP_PUBLIC int gettimeofday(struct timeval *tv, struct timezone2 *tz); -#endif // _WIN32 +SINSP_PUBLIC int gettimeofday(struct timeval* tv, struct timezone2* tz); +#endif // _WIN32 /////////////////////////////////////////////////////////////////////////////// // gethostname wrapper @@ -270,17 +263,14 @@ const char* print_format_to_string(ppm_print_format fmt); std::vector sinsp_split(std::string_view sv, char delim); template -std::string sinsp_join(It begin, It end, char delim) -{ - if(begin == end) - { +std::string sinsp_join(It begin, It end, char delim) { + if(begin == end) { return ""; } std::stringstream ss; ss << *begin; ++begin; - for(auto it = begin; it != end; ++it) - { + for(auto it = begin; it != end; ++it) { ss << delim << *it; } return ss.str(); @@ -294,16 +284,19 @@ std::string& trim(std::string& s); [[nodiscard]] std::string_view rtrim_sv(std::string_view); [[nodiscard]] std::string_view trim_sv(std::string_view); -std::string& replace_in_place(std::string& s, const std::string& search, const std::string& replacement); -std::string replace(const std::string& str, const std::string& search, const std::string& replacement); +std::string& replace_in_place(std::string& s, + const std::string& search, + const std::string& replacement); +std::string replace(const std::string& str, + const std::string& search, + const std::string& replacement); -std::string buffer_to_multiline_hex(const char *buf, size_t size); +std::string buffer_to_multiline_hex(const char* buf, size_t size); /////////////////////////////////////////////////////////////////////////////// // number parser /////////////////////////////////////////////////////////////////////////////// -class sinsp_numparser -{ +class sinsp_numparser { public: static uint8_t parseu8(const std::string& str); static int8_t parsed8(const std::string& str); @@ -336,42 +329,46 @@ unsigned int read_num_possible_cpus(void); /////////////////////////////////////////////////////////////////////////////// // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3876.pdf -template -inline void hash_combine(std::size_t &seed, const T& val) -{ - seed ^= std::hash()(val) + 0x9e3779b9 + (seed<<6) + (seed>>2); +template +inline void hash_combine(std::size_t& seed, const T& val) { + seed ^= std::hash()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } /////////////////////////////////////////////////////////////////////////////// // Log helpers /////////////////////////////////////////////////////////////////////////////// -void sinsp_scap_log_fn(const char* component, const char* msg, const enum falcosecurity_log_severity sev); +void sinsp_scap_log_fn(const char* component, + const char* msg, + const enum falcosecurity_log_severity sev); /////////////////////////////////////////////////////////////////////////////// // Set operation functions. /////////////////////////////////////////////////////////////////////////////// - template std::set unordered_set_to_ordered(const std::unordered_set& unordered_set); template -std::unordered_set unordered_set_difference(const std::unordered_set& a, const std::unordered_set& b); +std::unordered_set unordered_set_difference(const std::unordered_set& a, + const std::unordered_set& b); template std::set set_difference(const std::set& a, const std::set& b); template -std::unordered_set unordered_set_union(const std::unordered_set& a, const std::unordered_set& b); +std::unordered_set unordered_set_union(const std::unordered_set& a, + const std::unordered_set& b); template std::set set_union(const std::set& a, const std::set& b); template -std::unordered_set unordered_set_intersection(const std::unordered_set& a, const std::unordered_set& b); +std::unordered_set unordered_set_intersection(const std::unordered_set& a, + const std::unordered_set& b); template std::set set_intersection(const std::set& a, const std::set& b); -std::string concat_set_in_order(const std::unordered_set& s, const std::string& delim = ", "); +std::string concat_set_in_order(const std::unordered_set& s, + const std::string& delim = ", "); std::string concat_set_in_order(const std::set& s, const std::string& delim = ", "); diff --git a/userspace/libsinsp/value_parser.cpp b/userspace/libsinsp/value_parser.cpp index 7285cfbc6a..d283005a58 100644 --- a/userspace/libsinsp/value_parser.cpp +++ b/userspace/libsinsp/value_parser.cpp @@ -26,246 +26,211 @@ limitations under the License. #include #endif -static inline void check_storage_size( - const char* str, std::string::size_type storage_len, std::string::size_type used_len) -{ - if (used_len > storage_len) { - throw sinsp_exception( - + "filter parameter too long (used=" - + std::to_string(used_len) - + ", available=" - + std::to_string(storage_len) - + "):" - + std::string(str)); +static inline void check_storage_size(const char* str, + std::string::size_type storage_len, + std::string::size_type used_len) { + if(used_len > storage_len) { + throw sinsp_exception(+"filter parameter too long (used=" + std::to_string(used_len) + + ", available=" + std::to_string(storage_len) + + "):" + std::string(str)); } } -size_t sinsp_filter_value_parser::string_to_rawval(const char* str, uint32_t len, uint8_t *storage, std::string::size_type max_len, ppm_param_type ptype) -{ +size_t sinsp_filter_value_parser::string_to_rawval(const char* str, + uint32_t len, + uint8_t* storage, + std::string::size_type max_len, + ppm_param_type ptype) { size_t parsed_len; - switch(ptype) - { - case PT_INT8: - check_storage_size(str, max_len, sizeof(int8_t)); - *(int8_t*)storage = sinsp_numparser::parsed8(str); - parsed_len = sizeof(int8_t); - break; - case PT_INT16: - check_storage_size(str, max_len, sizeof(int16_t)); - *(int16_t*)storage = sinsp_numparser::parsed16(str); - parsed_len = sizeof(int16_t); - break; - case PT_INT32: - check_storage_size(str, max_len, sizeof(int32_t)); - *(int32_t*)storage = sinsp_numparser::parsed32(str); - parsed_len = sizeof(int32_t); - break; - case PT_INT64: - case PT_FD: - case PT_ERRNO: - check_storage_size(str, max_len, sizeof(int64_t)); - *(int64_t*)storage = sinsp_numparser::parsed64(str); - parsed_len = sizeof(int64_t); - break; - case PT_L4PROTO: // This can be resolved in the future - case PT_FLAGS8: - case PT_UINT8: - case PT_ENUMFLAGS8: - check_storage_size(str, max_len, sizeof(uint8_t)); - *(uint8_t*)storage = sinsp_numparser::parseu8(str); - parsed_len = sizeof(int8_t); - break; - case PT_PORT: - { - check_storage_size(str, max_len, sizeof(uint16_t)); - std::string in(str); - - if(in.empty()) - { - *(uint16_t*)storage = 0; - } - else - { - // if the string is made only of numbers - if(strspn(in.c_str(), "0123456789") == in.size()) - { - *(uint16_t*)storage = stoi(in); - } - else - { - struct servent* se = getservbyname(in.c_str(), NULL); - - if(se == NULL) - { - throw sinsp_exception("unrecognized protocol " + in); - } - else - { - *(uint16_t*)storage = ntohs(getservbyname(in.c_str(), NULL)->s_port); - } + switch(ptype) { + case PT_INT8: + check_storage_size(str, max_len, sizeof(int8_t)); + *(int8_t*)storage = sinsp_numparser::parsed8(str); + parsed_len = sizeof(int8_t); + break; + case PT_INT16: + check_storage_size(str, max_len, sizeof(int16_t)); + *(int16_t*)storage = sinsp_numparser::parsed16(str); + parsed_len = sizeof(int16_t); + break; + case PT_INT32: + check_storage_size(str, max_len, sizeof(int32_t)); + *(int32_t*)storage = sinsp_numparser::parsed32(str); + parsed_len = sizeof(int32_t); + break; + case PT_INT64: + case PT_FD: + case PT_ERRNO: + check_storage_size(str, max_len, sizeof(int64_t)); + *(int64_t*)storage = sinsp_numparser::parsed64(str); + parsed_len = sizeof(int64_t); + break; + case PT_L4PROTO: // This can be resolved in the future + case PT_FLAGS8: + case PT_UINT8: + case PT_ENUMFLAGS8: + check_storage_size(str, max_len, sizeof(uint8_t)); + *(uint8_t*)storage = sinsp_numparser::parseu8(str); + parsed_len = sizeof(int8_t); + break; + case PT_PORT: { + check_storage_size(str, max_len, sizeof(uint16_t)); + std::string in(str); + + if(in.empty()) { + *(uint16_t*)storage = 0; + } else { + // if the string is made only of numbers + if(strspn(in.c_str(), "0123456789") == in.size()) { + *(uint16_t*)storage = stoi(in); + } else { + struct servent* se = getservbyname(in.c_str(), NULL); + + if(se == NULL) { + throw sinsp_exception("unrecognized protocol " + in); + } else { + *(uint16_t*)storage = ntohs(getservbyname(in.c_str(), NULL)->s_port); } } - - parsed_len = sizeof(int16_t); - break; } - case PT_FLAGS16: - case PT_UINT16: - case PT_ENUMFLAGS16: - check_storage_size(str, max_len, sizeof(uint16_t)); - *(uint16_t*)storage = sinsp_numparser::parseu16(str); - parsed_len = sizeof(uint16_t); - break; - case PT_FLAGS32: - case PT_UINT32: - case PT_MODE: - case PT_ENUMFLAGS32: - check_storage_size(str, max_len, sizeof(uint32_t)); - *(uint32_t*)storage = sinsp_numparser::parseu32(str); - parsed_len = sizeof(uint32_t); - break; - case PT_UINT64: - check_storage_size(str, max_len, sizeof(uint64_t)); - *(uint64_t*)storage = sinsp_numparser::parseu64(str); - parsed_len = sizeof(uint64_t); - break; - case PT_RELTIME: - case PT_ABSTIME: - check_storage_size(str, max_len, sizeof(uint64_t)); - *(uint64_t*)storage = sinsp_numparser::parseu64(str); - parsed_len = sizeof(uint64_t); - break; - case PT_CHARBUF: - case PT_SOCKADDR: - case PT_SOCKFAMILY: - case PT_FSPATH: - case PT_FSRELPATH: - { - len = (uint32_t)strlen(str); - check_storage_size(str, max_len, len + 1); - memcpy(storage, str, len); - *(uint8_t*)(&storage[len]) = 0; - parsed_len = len; - } - break; - case PT_BOOL: - check_storage_size(str, max_len, sizeof(uint32_t)); - parsed_len = sizeof(uint32_t); - if(std::string(str) == "true") - { - *(uint32_t*)storage = 1; - } - else if(std::string(str) == "false") - { - *(uint32_t*)storage = 0; - } - else - { - throw sinsp_exception("filter error: unrecognized boolean value " + std::string(str)); - } - - break; - case PT_DOUBLE: - { - check_storage_size(str, max_len, sizeof(double)); - // note(jasondellaluce): we historically never supported parsing - // floating point number values, so as a starter we just stick to - // integer numberd - // todo(jasondellaluce): support floating point (double) value parsing - *(double*)storage = (double)sinsp_numparser::parsed32(str); - parsed_len = sizeof(double); - break; + parsed_len = sizeof(int16_t); + break; + } + case PT_FLAGS16: + case PT_UINT16: + case PT_ENUMFLAGS16: + check_storage_size(str, max_len, sizeof(uint16_t)); + *(uint16_t*)storage = sinsp_numparser::parseu16(str); + parsed_len = sizeof(uint16_t); + break; + case PT_FLAGS32: + case PT_UINT32: + case PT_MODE: + case PT_ENUMFLAGS32: + check_storage_size(str, max_len, sizeof(uint32_t)); + *(uint32_t*)storage = sinsp_numparser::parseu32(str); + parsed_len = sizeof(uint32_t); + break; + case PT_UINT64: + check_storage_size(str, max_len, sizeof(uint64_t)); + *(uint64_t*)storage = sinsp_numparser::parseu64(str); + parsed_len = sizeof(uint64_t); + break; + case PT_RELTIME: + case PT_ABSTIME: + check_storage_size(str, max_len, sizeof(uint64_t)); + *(uint64_t*)storage = sinsp_numparser::parseu64(str); + parsed_len = sizeof(uint64_t); + break; + case PT_CHARBUF: + case PT_SOCKADDR: + case PT_SOCKFAMILY: + case PT_FSPATH: + case PT_FSRELPATH: { + len = (uint32_t)strlen(str); + check_storage_size(str, max_len, len + 1); + + memcpy(storage, str, len); + *(uint8_t*)(&storage[len]) = 0; + parsed_len = len; + } break; + case PT_BOOL: + check_storage_size(str, max_len, sizeof(uint32_t)); + parsed_len = sizeof(uint32_t); + if(std::string(str) == "true") { + *(uint32_t*)storage = 1; + } else if(std::string(str) == "false") { + *(uint32_t*)storage = 0; + } else { + throw sinsp_exception("filter error: unrecognized boolean value " + std::string(str)); } - case PT_IPADDR: - if(memchr(str, '.', len) != NULL) - { - return string_to_rawval(str, len, storage, max_len, PT_IPV4ADDR); - } - else - { - return string_to_rawval(str, len, storage, max_len, PT_IPV6ADDR); - } - break; - case PT_IPV4ADDR: - check_storage_size(str, max_len, sizeof(struct in_addr)); - if(inet_pton(AF_INET, str, storage) != 1) - { - throw sinsp_exception("unrecognized IPv4 address " + std::string(str)); - } - parsed_len = sizeof(struct in_addr); - break; - case PT_IPV6ADDR: - { - check_storage_size(str, max_len, sizeof(ipv6addr)); - new (storage) ipv6addr(str); - parsed_len = sizeof(ipv6addr); - break; + break; + case PT_DOUBLE: { + check_storage_size(str, max_len, sizeof(double)); + // note(jasondellaluce): we historically never supported parsing + // floating point number values, so as a starter we just stick to + // integer numberd + // todo(jasondellaluce): support floating point (double) value parsing + *(double*)storage = (double)sinsp_numparser::parsed32(str); + parsed_len = sizeof(double); + break; + } + case PT_IPADDR: + if(memchr(str, '.', len) != NULL) { + return string_to_rawval(str, len, storage, max_len, PT_IPV4ADDR); + } else { + return string_to_rawval(str, len, storage, max_len, PT_IPV6ADDR); } - case PT_IPNET: - if(memchr(str, '.', len) != NULL) - { - return string_to_rawval(str, len, storage, max_len, PT_IPV4NET); - } - else - { - return string_to_rawval(str, len, storage, max_len, PT_IPV6NET); - } - break; - case PT_IPV4NET: - { - check_storage_size(str, max_len, sizeof(ipv4net)); - std::stringstream ss(str); - std::string ip, mask; - ipv4net* net = (ipv4net*)storage; - if (strchr(str, '/') == NULL) - { - throw sinsp_exception("unrecognized IP network " + std::string(str)); - } + break; + case PT_IPV4ADDR: + check_storage_size(str, max_len, sizeof(struct in_addr)); + if(inet_pton(AF_INET, str, storage) != 1) { + throw sinsp_exception("unrecognized IPv4 address " + std::string(str)); + } + parsed_len = sizeof(struct in_addr); + break; + case PT_IPV6ADDR: { + check_storage_size(str, max_len, sizeof(ipv6addr)); + new(storage) ipv6addr(str); + parsed_len = sizeof(ipv6addr); + break; + } + case PT_IPNET: + if(memchr(str, '.', len) != NULL) { + return string_to_rawval(str, len, storage, max_len, PT_IPV4NET); + } else { + return string_to_rawval(str, len, storage, max_len, PT_IPV6NET); + } + break; + case PT_IPV4NET: { + check_storage_size(str, max_len, sizeof(ipv4net)); + std::stringstream ss(str); + std::string ip, mask; + ipv4net* net = (ipv4net*)storage; + + if(strchr(str, '/') == NULL) { + throw sinsp_exception("unrecognized IP network " + std::string(str)); + } - getline(ss, ip, '/'); - getline(ss, mask); + getline(ss, ip, '/'); + getline(ss, mask); - if(inet_pton(AF_INET, ip.c_str(), &net->m_ip) != 1) - { - throw sinsp_exception("unrecognized IP address " + std::string(str)); - } + if(inet_pton(AF_INET, ip.c_str(), &net->m_ip) != 1) { + throw sinsp_exception("unrecognized IP address " + std::string(str)); + } - uint32_t cidrlen = sinsp_numparser::parseu8(mask); + uint32_t cidrlen = sinsp_numparser::parseu8(mask); - if (cidrlen > 32) - { - throw sinsp_exception("invalid netmask " + mask); - } + if(cidrlen > 32) { + throw sinsp_exception("invalid netmask " + mask); + } - uint32_t j; - net->m_netmask = 0; + uint32_t j; + net->m_netmask = 0; - for(j = 0; j < cidrlen; j++) - { - net->m_netmask |= 1<<(31-j); - } + for(j = 0; j < cidrlen; j++) { + net->m_netmask |= 1 << (31 - j); + } - net->m_netmask = htonl(net->m_netmask); + net->m_netmask = htonl(net->m_netmask); - parsed_len = sizeof(ipv4net); - break; - } - case PT_IPV6NET: - { - check_storage_size(str, max_len, sizeof(ipv6net)); - new (storage) ipv6net(str); - parsed_len = sizeof(ipv6net); - break; - } - default: - ASSERT(false); - throw sinsp_exception("wrong parameter type " + std::to_string((long long) ptype)); + parsed_len = sizeof(ipv4net); + break; + } + case PT_IPV6NET: { + check_storage_size(str, max_len, sizeof(ipv6net)); + new(storage) ipv6net(str); + parsed_len = sizeof(ipv6net); + break; + } + default: + ASSERT(false); + throw sinsp_exception("wrong parameter type " + std::to_string((long long)ptype)); } return parsed_len; } - diff --git a/userspace/libsinsp/value_parser.h b/userspace/libsinsp/value_parser.h index ac9b0c98dd..398e49df64 100644 --- a/userspace/libsinsp/value_parser.h +++ b/userspace/libsinsp/value_parser.h @@ -22,8 +22,11 @@ limitations under the License. // Doesn't return the field length because the filtering engine can calculate it. // -class sinsp_filter_value_parser -{ - public: - static size_t string_to_rawval(const char* str, uint32_t len, uint8_t *storage, std::string::size_type max_len, ppm_param_type ptype); +class sinsp_filter_value_parser { +public: + static size_t string_to_rawval(const char* str, + uint32_t len, + uint8_t* storage, + std::string::size_type max_len, + ppm_param_type ptype); }; diff --git a/userspace/libsinsp/version.h b/userspace/libsinsp/version.h old mode 100755 new mode 100644 index 83194f562f..39fb90f0cb --- a/userspace/libsinsp/version.h +++ b/userspace/libsinsp/version.h @@ -25,49 +25,44 @@ limitations under the License. #include /*! - \brief Represents a version number + \brief Represents a version number */ -class sinsp_version -{ +class sinsp_version { public: - inline sinsp_version() : sinsp_version("0.0.0") { } - - inline explicit sinsp_version(const std::string &version_str) - { - m_valid = sscanf(version_str.c_str(), "%" PRIu32 ".%" PRIu32 ".%" PRIu32, - &m_version_major, &m_version_minor, &m_version_patch) == 3; + inline sinsp_version(): sinsp_version("0.0.0") {} + + inline explicit sinsp_version(const std::string& version_str) { + m_valid = sscanf(version_str.c_str(), + "%" PRIu32 ".%" PRIu32 ".%" PRIu32, + &m_version_major, + &m_version_minor, + &m_version_patch) == 3; } sinsp_version(sinsp_version&&) = default; - sinsp_version& operator = (sinsp_version&&) = default; + sinsp_version& operator=(sinsp_version&&) = default; sinsp_version(const sinsp_version& s) = default; - sinsp_version& operator = (const sinsp_version& s) = default; + sinsp_version& operator=(const sinsp_version& s) = default; ~sinsp_version() = default; - inline std::string as_string() const - { - return std::to_string(m_version_major) - + "." + std::to_string(m_version_minor) - + "." + std::to_string(m_version_patch); + inline std::string as_string() const { + return std::to_string(m_version_major) + "." + std::to_string(m_version_minor) + "." + + std::to_string(m_version_patch); } - inline bool operator<(sinsp_version const& right) const - { - if(this->m_version_major > right.m_version_major) - { + inline bool operator<(sinsp_version const& right) const { + if(this->m_version_major > right.m_version_major) { return false; } - if(this->m_version_major == right.m_version_major) - { - if(this->m_version_minor > right.m_version_minor) - { + if(this->m_version_major == right.m_version_major) { + if(this->m_version_minor > right.m_version_minor) { return false; } - if(this->m_version_minor == right.m_version_minor && this->m_version_patch >= right.m_version_patch) - { + if(this->m_version_minor == right.m_version_minor && + this->m_version_patch >= right.m_version_patch) { return false; } } @@ -75,67 +70,45 @@ class sinsp_version return true; } - inline bool operator>(sinsp_version const& right) const - { + inline bool operator>(sinsp_version const& right) const { return (*this != right && !(*this < right)); } - inline bool operator==(sinsp_version const& right) const - { - if(this->m_version_major == right.m_version_major - && this->m_version_minor == right.m_version_minor - && this->m_version_patch == right.m_version_patch) - { + inline bool operator==(sinsp_version const& right) const { + if(this->m_version_major == right.m_version_major && + this->m_version_minor == right.m_version_minor && + this->m_version_patch == right.m_version_patch) { return true; } return false; } - inline bool operator!=(sinsp_version const& right) const - { - return !(*this == right); - } + inline bool operator!=(sinsp_version const& right) const { return !(*this == right); } - inline bool operator>=(sinsp_version const& right) const - { + inline bool operator>=(sinsp_version const& right) const { return ((*this == right) || (*this > right)); } - inline bool operator<=(sinsp_version const& right) const - { + inline bool operator<=(sinsp_version const& right) const { return ((*this == right) || (*this < right)); } - inline bool compatible_with(const sinsp_version &requested) const - { - if(!m_valid || !requested.m_valid) - { + inline bool compatible_with(const sinsp_version& requested) const { + if(!m_valid || !requested.m_valid) { return false; } return (this->m_version_major == requested.m_version_major) && (*this >= requested); } - inline bool is_valid() const - { - return m_valid; - } + inline bool is_valid() const { return m_valid; } - inline uint32_t major() const - { - return m_version_major; - } + inline uint32_t major() const { return m_version_major; } - inline uint32_t minor() const - { - return m_version_minor; - } + inline uint32_t minor() const { return m_version_minor; } - inline uint32_t patch() const - { - return m_version_patch; - } + inline uint32_t patch() const { return m_version_patch; } private: bool m_valid; diff --git a/userspace/plugin/plugin_api.h b/userspace/plugin/plugin_api.h index b173efcf1a..9ec187d47c 100644 --- a/userspace/plugin/plugin_api.h +++ b/userspace/plugin/plugin_api.h @@ -24,7 +24,6 @@ limitations under the License. extern "C" { #endif - // // API versions of this plugin framework // @@ -36,32 +35,35 @@ extern "C" { // // Just some not so smart defines to retrieve plugin api version as string // -#define QUOTE(str) #str -#define EXPAND_AND_QUOTE(str) QUOTE(str) -#define PLUGIN_API_VERSION PLUGIN_API_VERSION_MAJOR.PLUGIN_API_VERSION_MINOR.PLUGIN_API_VERSION_PATCH -#define PLUGIN_API_VERSION_STR EXPAND_AND_QUOTE(PLUGIN_API_VERSION) +#define QUOTE(str) #str +#define EXPAND_AND_QUOTE(str) QUOTE(str) +#define PLUGIN_API_VERSION \ + PLUGIN_API_VERSION_MAJOR.PLUGIN_API_VERSION_MINOR.PLUGIN_API_VERSION_PATCH +#define PLUGIN_API_VERSION_STR EXPAND_AND_QUOTE(PLUGIN_API_VERSION) // // The max length of errors returned by a plugin in some of its API symbols. // -#define PLUGIN_MAX_ERRLEN 1024 +#define PLUGIN_MAX_ERRLEN 1024 -// Supported by the API but deprecated. Use the extended version ss_plugin_table_reader_vtable_ext instead. -// todo(jasondellaluce): when/if major changes to v4, remove this and -// give this name to the associated *_ext struct. -typedef struct -{ +// Supported by the API but deprecated. Use the extended version ss_plugin_table_reader_vtable_ext +// instead. todo(jasondellaluce): when/if major changes to v4, remove this and give this name to the +// associated *_ext struct. +typedef struct { const ss_plugin_table_fieldinfo* (*list_table_fields)(ss_plugin_table_t* t, uint32_t* nfields); - ss_plugin_table_field_t* (*get_table_field)(ss_plugin_table_t* t, const char* name, ss_plugin_state_type data_type); - ss_plugin_table_field_t* (*add_table_field)(ss_plugin_table_t* t, const char* name, ss_plugin_state_type data_type); + ss_plugin_table_field_t* (*get_table_field)(ss_plugin_table_t* t, + const char* name, + ss_plugin_state_type data_type); + ss_plugin_table_field_t* (*add_table_field)(ss_plugin_table_t* t, + const char* name, + ss_plugin_state_type data_type); } ss_plugin_table_fields_vtable; // Vtable for controlling and the fields for the entries of a state table. // This allows discovering the fields available in the table, defining new ones, // and obtaining accessors usable at runtime for reading and writing the fields' // data from each entry of a given state table. -typedef struct -{ +typedef struct { // Returns a pointer to an array containing info about all the fields // available in the entries of the table. nfields will be filled with the number // of elements of the returned array. The array's memory is owned by the @@ -74,7 +76,9 @@ typedef struct // the table. The pointer is owned by the table's owner. // Returns NULL in case of issues (including when the field is not defined // or it has a type different than the specified one). - ss_plugin_table_field_t* (*get_table_field)(ss_plugin_table_t* t, const char* name, ss_plugin_state_type data_type); + ss_plugin_table_field_t* (*get_table_field)(ss_plugin_table_t* t, + const char* name, + ss_plugin_state_type data_type); // // Defines a new field in the table given its name and data type, // which will then be available in all entries contained in the table. @@ -83,18 +87,23 @@ typedef struct // the table. The pointer is owned by the table's owner. // Returns NULL in case of issues (including when a field is defined multiple // times with different data types). - ss_plugin_table_field_t* (*add_table_field)(ss_plugin_table_t* t, const char* name, ss_plugin_state_type data_type); + ss_plugin_table_field_t* (*add_table_field)(ss_plugin_table_t* t, + const char* name, + ss_plugin_state_type data_type); } ss_plugin_table_fields_vtable_ext; -// Supported by the API but deprecated. Use the extended version ss_plugin_table_reader_vtable_ext instead. -// todo(jasondellaluce): when/if major changes to v4, remove this and -// give this name to the associated *_ext struct. -typedef struct -{ - const char* (*get_table_name)(ss_plugin_table_t* t); +// Supported by the API but deprecated. Use the extended version ss_plugin_table_reader_vtable_ext +// instead. todo(jasondellaluce): when/if major changes to v4, remove this and give this name to the +// associated *_ext struct. +typedef struct { + const char* (*get_table_name)(ss_plugin_table_t* t); uint64_t (*get_table_size)(ss_plugin_table_t* t); - ss_plugin_table_entry_t* (*get_table_entry)(ss_plugin_table_t* t, const ss_plugin_state_data* key); - ss_plugin_rc (*read_entry_field)(ss_plugin_table_t* t, ss_plugin_table_entry_t* e, const ss_plugin_table_field_t* f, ss_plugin_state_data* out); + ss_plugin_table_entry_t* (*get_table_entry)(ss_plugin_table_t* t, + const ss_plugin_state_data* key); + ss_plugin_rc (*read_entry_field)(ss_plugin_table_t* t, + ss_plugin_table_entry_t* e, + const ss_plugin_table_field_t* f, + ss_plugin_state_data* out); } ss_plugin_table_reader_vtable; // Opaque pointer to the state data relative to a state table iteration. @@ -105,13 +114,13 @@ typedef void ss_plugin_table_iterator_state_t; // Iterator function callback used by a plugin for looping through all the // entries of a given state table. Returns true if the iteration should // proceed to the next element, or false in case of break out. -typedef ss_plugin_bool (*ss_plugin_table_iterator_func_t)(ss_plugin_table_iterator_state_t* s, ss_plugin_table_entry_t* e); +typedef ss_plugin_bool (*ss_plugin_table_iterator_func_t)(ss_plugin_table_iterator_state_t* s, + ss_plugin_table_entry_t* e); -typedef struct -{ +typedef struct { // Returns the table's name, or NULL in case of error. // The returned pointer is owned by the table's owner. - const char* (*get_table_name)(ss_plugin_table_t* t); + const char* (*get_table_name)(ss_plugin_table_t* t); // // Returns the number of entries in the table, or ((uint64_t) -1) in // case of error. @@ -122,13 +131,17 @@ typedef struct // given key). The returned pointer is owned by the table's owner. // Every non-NULL returned entry must be released by invoking release_table_entry() // once it becomes no more used by the invoker. - ss_plugin_table_entry_t* (*get_table_entry)(ss_plugin_table_t* t, const ss_plugin_state_data* key); + ss_plugin_table_entry_t* (*get_table_entry)(ss_plugin_table_t* t, + const ss_plugin_state_data* key); // // Reads the value of an entry field from a table's entry. // The field accessor must be obtainied during plugin_init(). // The read value is stored in the "out" parameter. // Returns SS_PLUGIN_SUCCESS if successful, and SS_PLUGIN_FAILURE otherwise. - ss_plugin_rc (*read_entry_field)(ss_plugin_table_t* t, ss_plugin_table_entry_t* e, const ss_plugin_table_field_t* f, ss_plugin_state_data* out); + ss_plugin_rc (*read_entry_field)(ss_plugin_table_t* t, + ss_plugin_table_entry_t* e, + const ss_plugin_table_field_t* f, + ss_plugin_state_data* out); // // Releases a table entry obtained by from previous invocation of get_table_entry(). // After being released, the same table entry cannot be reused by the invoker. @@ -138,25 +151,30 @@ typedef struct // Iterates through all the entries of a table, invoking the interation // callback function for each of them. Returns false in case of failure or // iteration break-out, and true otherwise. - ss_plugin_bool (*iterate_entries)(ss_plugin_table_t* t, ss_plugin_table_iterator_func_t it, ss_plugin_table_iterator_state_t* s); + ss_plugin_bool (*iterate_entries)(ss_plugin_table_t* t, + ss_plugin_table_iterator_func_t it, + ss_plugin_table_iterator_state_t* s); } ss_plugin_table_reader_vtable_ext; -// Supported by the API but deprecated. Use the extended version ss_plugin_table_writer_vtable_ext instead. -// todo(jasondellaluce): when/if major changes to v4, remove this and -// give this name to the associated *_ext struct. -typedef struct -{ +// Supported by the API but deprecated. Use the extended version ss_plugin_table_writer_vtable_ext +// instead. todo(jasondellaluce): when/if major changes to v4, remove this and give this name to the +// associated *_ext struct. +typedef struct { ss_plugin_rc (*clear_table)(ss_plugin_table_t* t); ss_plugin_rc (*erase_table_entry)(ss_plugin_table_t* t, const ss_plugin_state_data* key); ss_plugin_table_entry_t* (*create_table_entry)(ss_plugin_table_t* t); void (*destroy_table_entry)(ss_plugin_table_t* t, ss_plugin_table_entry_t* e); - ss_plugin_table_entry_t* (*add_table_entry)(ss_plugin_table_t* t, const ss_plugin_state_data* key, ss_plugin_table_entry_t* entry); - ss_plugin_rc (*write_entry_field)(ss_plugin_table_t* t, ss_plugin_table_entry_t* e, const ss_plugin_table_field_t* f, const ss_plugin_state_data* in); + ss_plugin_table_entry_t* (*add_table_entry)(ss_plugin_table_t* t, + const ss_plugin_state_data* key, + ss_plugin_table_entry_t* entry); + ss_plugin_rc (*write_entry_field)(ss_plugin_table_t* t, + ss_plugin_table_entry_t* e, + const ss_plugin_table_field_t* f, + const ss_plugin_state_data* in); } ss_plugin_table_writer_vtable; // Vtable for controlling a state table for write operations. -typedef struct -{ +typedef struct { // Erases all the entries of the table. // Returns SS_PLUGIN_SUCCESS if successful, and SS_PLUGIN_FAILURE otherwise. ss_plugin_rc (*clear_table)(ss_plugin_table_t* t); @@ -183,13 +201,18 @@ typedef struct // entry's pointer. Returns an opaque pointer to the newly-added table's entry, // or NULL in case of error. Every non-NULL returned entry must be released // by invoking release_table_entry() once it becomes no more used by the invoker. - ss_plugin_table_entry_t* (*add_table_entry)(ss_plugin_table_t* t, const ss_plugin_state_data* key, ss_plugin_table_entry_t* entry); + ss_plugin_table_entry_t* (*add_table_entry)(ss_plugin_table_t* t, + const ss_plugin_state_data* key, + ss_plugin_table_entry_t* entry); // // Updates a table's entry by writing a value for one of its fields. // The field accessor must be obtainied during plugin_init(). // The written value is read from the "in" parameter. // Returns SS_PLUGIN_SUCCESS if successful, and SS_PLUGIN_FAILURE otherwise. - ss_plugin_rc (*write_entry_field)(ss_plugin_table_t* t, ss_plugin_table_entry_t* e, const ss_plugin_table_field_t* f, const ss_plugin_state_data* in); + ss_plugin_rc (*write_entry_field)(ss_plugin_table_t* t, + ss_plugin_table_entry_t* e, + const ss_plugin_table_field_t* f, + const ss_plugin_state_data* in); } ss_plugin_table_writer_vtable_ext; // Plugin-provided input passed to the add_table() callback of @@ -199,8 +222,7 @@ typedef struct // of implementing all the API functions. These will be used by other // plugins loaded by the falcosecurity libraries to interact with the state // of a given plugin to implement cross-plugin state access. -typedef struct -{ +typedef struct { // The name of the state table. const char* name; // @@ -239,8 +261,7 @@ typedef struct // Initialization-time input related to the event parsing or field extraction capability. // This provides the plugin with callback functions implemented by its owner // that can be used to discover, access, and define state tables. -typedef struct -{ +typedef struct { // Returns a pointer to an array containing info about all the tables // registered in the plugin's owner. ntables will be filled with the number // of elements of the returned array. The array's memory is owned by the @@ -249,7 +270,9 @@ typedef struct // // Returns an opaque accessor to a state table registered in the plugin's // owner, given its name and key type. Returns NULL if an case of error. - ss_plugin_table_t* (*get_table)(ss_plugin_owner_t* o, const char* name, ss_plugin_state_type key_type); + ss_plugin_table_t* (*get_table)(ss_plugin_owner_t* o, + const char* name, + ss_plugin_state_type key_type); // // Registers a new state table in the plugin's owner. Returns // SS_PLUGIN_SUCCESS in case of success, and SS_PLUGIN_FAILURE otherwise. @@ -279,17 +302,19 @@ typedef struct // Arguments: // - component: name of the component that is logging // (if set to NULL automatically falls back to the plugin name in the log) -// - msg: message to log +// - msg: message to log // (it doesn't have to be '\n' terminated) // - sev: message severity as defined in ss_plugin_log_severity -typedef void (*ss_plugin_log_fn_t)(ss_plugin_owner_t* o, const char* component, const char* msg, ss_plugin_log_severity sev); +typedef void (*ss_plugin_log_fn_t)(ss_plugin_owner_t* o, + const char* component, + const char* msg, + ss_plugin_log_severity sev); // Input passed at the plugin through plugin_init(). This contain information // common to any plugin, and also information useful only in case the plugin // implements a given capability. If a certain capability is not implemented // by the plugin, its information is set to NULL. -typedef struct ss_plugin_init_input -{ +typedef struct ss_plugin_init_input { // An opaque string representing the plugin init configuration. // The format of the string is arbitrary and defined by the plugin itself. const char* config; @@ -302,7 +327,7 @@ typedef struct ss_plugin_init_input // Return a string with the error that was last generated by the plugin's // owner, or NULL if no error is present. // The string pointer is owned by the plugin's owenr. - const char *(*get_owner_last_error)(ss_plugin_owner_t *o); + const char* (*get_owner_last_error)(ss_plugin_owner_t* o); // // Init input related to the event parsing or field extraction capability. // It's set to NULL if the plugin does not implement at least one of the two @@ -317,8 +342,7 @@ typedef struct ss_plugin_init_input // Input passed to the plugin when extracting a field from an event for // the field extraction capability. -typedef struct ss_plugin_field_extract_input -{ +typedef struct ss_plugin_field_extract_input { // // The plugin's owner. Can be passed by the plugin to the callbacks available // in this struct in order to invoke functions of its owner. @@ -327,7 +351,7 @@ typedef struct ss_plugin_field_extract_input // Return a string with the error that was last generated by the plugin's // owner, or NULL if no error is present. // The string pointer is owned by the plugin's owenr. - const char *(*get_owner_last_error)(ss_plugin_owner_t *o); + const char* (*get_owner_last_error)(ss_plugin_owner_t* o); // // The length of the fields array. uint32_t num_fields; @@ -337,7 +361,7 @@ typedef struct ss_plugin_field_extract_input // extracted value as output. Memory pointers set as output must be allocated // by the plugin and must not be deallocated or modified until the next // extract_fields() call. - ss_plugin_extract_field *fields; + ss_plugin_extract_field* fields; // // Supported but deprecated. Use the extended version table_reader_ext. // todo(jasondellaluce): when/if major changes to v4, remove this and @@ -350,8 +374,7 @@ typedef struct ss_plugin_field_extract_input // Input passed to the plugin when parsing an event for the event parsing // capability. -typedef struct ss_plugin_event_parse_input -{ +typedef struct ss_plugin_event_parse_input { // // The plugin's owner. Can be passed by the plugin to the callbacks available // in this struct in order to invoke functions of its owner. @@ -360,7 +383,7 @@ typedef struct ss_plugin_event_parse_input // Return a string with the error that was last generated by the plugin's // owner, or NULL if no error is present. // The string pointer is owned by the plugin's owenr. - const char *(*get_owner_last_error)(ss_plugin_owner_t *o); + const char* (*get_owner_last_error)(ss_plugin_owner_t* o); // // Supported but deprecated. Use the extended version table_reader_ext. // todo(jasondellaluce): when/if major changes to v4, remove this and @@ -380,8 +403,7 @@ typedef struct ss_plugin_event_parse_input } ss_plugin_event_parse_input; // Input passed to the plugin when setting a new configuration -typedef struct ss_plugin_set_config_input -{ +typedef struct ss_plugin_set_config_input { // // An opaque string representing the new configuration provided by the framework const char* config; @@ -407,8 +429,7 @@ typedef ss_plugin_bool (*ss_plugin_routine_fn_t)(ss_plugin_t* s, ss_plugin_routi // // Vtable used by the plugin to subscribe and unsubscribe recurring loop-like routines // to the framework-provide thread pool -typedef struct -{ +typedef struct { // // Subscribes a routine to the framework-provided thread pool. // Arguments: @@ -416,8 +437,11 @@ typedef struct // - f: the function executed by the routine on each iteration // - i: the routine's state // - // Return value: A routine handle that can be used to later unsubscribe the routine. Returns null in case of failure. - ss_plugin_routine_t* (*subscribe)(ss_plugin_owner_t* o, ss_plugin_routine_fn_t f, ss_plugin_routine_state_t* i); + // Return value: A routine handle that can be used to later unsubscribe the routine. Returns + // null in case of failure. + ss_plugin_routine_t* (*subscribe)(ss_plugin_owner_t* o, + ss_plugin_routine_fn_t f, + ss_plugin_routine_state_t* i); // // Unsubscribes a routine from the framework-provided thread pool. @@ -430,8 +454,7 @@ typedef struct } ss_plugin_routine_vtable; // Input passed to the plugin when the framework start and stops the capture. -typedef struct ss_plugin_capture_listen_input -{ +typedef struct ss_plugin_capture_listen_input { // // The plugin's owner. Can be passed by the plugin to the callbacks available // in this struct in order to invoke functions of its owner. @@ -468,7 +491,9 @@ typedef struct ss_plugin_capture_listen_input // in case the handler function returns SS_PLUGIN_FAILURE. The error string // has a max length of PLUGIN_MAX_ERRLEN (termination char included) and its // memory must be allocated and owned by the plugin. -typedef ss_plugin_rc (*ss_plugin_async_event_handler_t)(ss_plugin_owner_t* o, const ss_plugin_event *evt, char* err); +typedef ss_plugin_rc (*ss_plugin_async_event_handler_t)(ss_plugin_owner_t* o, + const ss_plugin_event* evt, + char* err); // // The struct below define the functions and arguments for plugins capabilities: @@ -500,8 +525,7 @@ typedef ss_plugin_rc (*ss_plugin_async_event_handler_t)(ss_plugin_owner_t* o, co // // Plugins API vtable // -typedef struct -{ +typedef struct { // // Return the version of the plugin API used by this plugin. // Required: yes @@ -512,7 +536,7 @@ typedef struct // of the API they run against, and the framework will take care of checking // and enforcing compatibility. // - const char *(*get_required_api_version)(); + const char* (*get_required_api_version)(); // // Return a string representation of a schema describing the data expected @@ -533,7 +557,7 @@ typedef struct // This also serves as a piece of documentation for users about how the // plugin needs to be configured. // - const char *(*get_init_schema)(ss_plugin_schema_type *schema_type); + const char* (*get_init_schema)(ss_plugin_schema_type* schema_type); // // Initialize the plugin and allocate its state. @@ -545,17 +569,17 @@ typedef struct // by the framework and passed to the other plugin functions. // If rc is SS_PLUGIN_FAILURE, this function may return NULL or a state to // later retrieve the error string. - // + // // If a non-NULL ss_plugin_t* state is returned, then subsequent invocations // of init() must not return the same ss_plugin_t* value again, if not after // it has been disposed with destroy() first. - ss_plugin_t *(*init)(const ss_plugin_init_input *input, ss_plugin_rc *rc); + ss_plugin_t* (*init)(const ss_plugin_init_input* input, ss_plugin_rc* rc); // // Destroy the plugin and, if plugin state was allocated, free it. // Required: yes // - void (*destroy)(ss_plugin_t *s); + void (*destroy)(ss_plugin_t* s); // // Return a string with the error that was last generated by @@ -567,28 +591,28 @@ typedef struct // string with more context for the error. The framework // calls get_last_error() to access that string. // - const char *(*get_last_error)(ss_plugin_t *s); + const char* (*get_last_error)(ss_plugin_t* s); // // Return the name of the plugin, which will be printed when displaying // information about the plugin. // Required: yes // - const char *(*get_name)(); + const char* (*get_name)(); // // Return the descriptions of the plugin, which will be printed when displaying // information about the plugin. // Required: yes // - const char *(*get_description)(); + const char* (*get_description)(); // // Return a string containing contact info (url, email, etc) for // the plugin authors. // Required: yes // - const char *(*get_contact)(); + const char* (*get_contact)(); // // Return the version of this plugin itself @@ -602,15 +626,15 @@ typedef struct // in pre-existing capture files must always be readable by newer versions // of the plugin. // - const char *(*get_version)(); + const char* (*get_version)(); // Event sourcing capability API - struct - { + struct { // // Return the unique ID of the plugin. - // Required: yes if get_event_source is defined and returns a non-empty string, no otherwise. - // + // Required: yes if get_event_source is defined and returns a non-empty string, no + // otherwise. + // // If the plugin has a specific ID and event source, then its next_batch() // function is allowed to only return events of plugin type (code 322) // with its own plugin ID and event source. @@ -626,7 +650,7 @@ typedef struct // Return a string representing the name of the event source generated // by this plugin. // Required: yes if get_id is defined and returns a non-zero number, no otherwise. - // + // // If the plugin has a specific ID and event source, then its next_batch() // function is allowed to only return events of plugin type (code 322) // with its own plugin ID and event source. @@ -717,7 +741,7 @@ typedef struct // event sourcing capability. Even if defined, this function is not // used by the framework if the plugin does not implement a specific // event source (get_id() is zero or get_event_source() is empty). - // + // // Required: no // // Arguments: @@ -736,7 +760,7 @@ typedef struct // If the returned pointer is non-NULL, then it must be uniquely // attached to the ss_plugin_t* parameter value. The pointer must not // be shared across multiple distinct ss_plugin_t* values. - const char* (*event_to_string)(ss_plugin_t *s, const ss_plugin_event_input *evt); + const char* (*event_to_string)(ss_plugin_t* s, const ss_plugin_event_input* evt); // // Return the next batch of events. @@ -764,25 +788,27 @@ typedef struct // The value of the ss_plugin_event** output parameter must be uniquely // attached to the ss_instance_t* parameter value. The pointer must not // be shared across multiple distinct ss_instance_t* values. - ss_plugin_rc (*next_batch)(ss_plugin_t* s, ss_instance_t* h, uint32_t *nevts, ss_plugin_event ***evts); + ss_plugin_rc (*next_batch)(ss_plugin_t* s, + ss_instance_t* h, + uint32_t* nevts, + ss_plugin_event*** evts); }; // Field extraction capability API - struct - { + struct { // // Return the list of event types that this plugin will receive // for field extraction. The event types follow the libscap specific. // This will be invoked only once by the framework after the plugin's // initialization. Events that are not included in the returned list // will not be received by the plugin. - // + // // This is a non-functional filter that should not influence the plugin's // functional behavior. Instead, this is a performance optimization // with the goal of avoiding unnecessary communication between the // framework and the plugin for events that are known to be not used for - // field extraction. - // + // field extraction. + // // Required: no // // This function is optional--if NULL or an empty array, then: @@ -801,9 +827,9 @@ typedef struct // Return value: a json array of strings containing event // sources returned by a plugin with event sourcing capabilities get_event_source() // function, or "syscall" for indicating support to non-plugin events. - // This function is optional--if NULL or an empty array, then if plugin has sourcing capability, - // and implements a specific event source, it will only receive events matching its event source, - // otherwise it will receive events from all event sources. + // This function is optional--if NULL or an empty array, then if plugin has sourcing + // capability, and implements a specific event source, it will only receive events matching + // its event source, otherwise it will receive events from all event sources. // const char* (*get_extract_event_sources)(); @@ -837,7 +863,8 @@ typedef struct // Example return value: // [ // {"type": "uint64", "name": "field1", "desc": "Describing field 1"}, - // {"type": "string", "name": "field2", "arg": {"isRequired": true, "isIndex": true}, "desc": "Describing field 2"}, + // {"type": "string", "name": "field2", "arg": {"isRequired": true, "isIndex": true}, + // "desc": "Describing field 2"}, // ] const char* (*get_fields)(); @@ -863,24 +890,25 @@ typedef struct // The value of the ss_plugin_extract_field* output parameter must be // uniquely attached to the ss_plugin_t* parameter value. The pointer // must not be shared across multiple distinct ss_plugin_t* values. - ss_plugin_rc (*extract_fields)(ss_plugin_t *s, const ss_plugin_event_input *evt, const ss_plugin_field_extract_input* in); + ss_plugin_rc (*extract_fields)(ss_plugin_t* s, + const ss_plugin_event_input* evt, + const ss_plugin_field_extract_input* in); }; // Event parsing capability API - struct - { + struct { // // Return the list of event types that this plugin will receive // for event parsing. The event types follow the libscap specific. // This will be invoked only once by the framework after the plugin's // initialization. Events that are not included in the returned list // will not be received by the plugin. - // + // // This is a non-functional filter that should not influence the plugin's // functional behavior. Instead, this is a performance optimization // with the goal of avoiding unnecessary communication between the // framework and the plugin for events that are known to be not used for - // event parsing. + // event parsing. // // Required: no // @@ -901,9 +929,9 @@ typedef struct // Return value: a json array of strings containing event // sources returned by a plugin with event sourcing capabilities get_event_source() // function, or "syscall" for indicating support to non-plugin events. - // This function is optional--if NULL or an empty array, then if plugin has sourcing capability, - // and implements a specific event source, it will only receive events matching its event source, - // otherwise it will receive events from all event sources. + // This function is optional--if NULL or an empty array, then if plugin has sourcing + // capability, and implements a specific event source, it will only receive events matching + // its event source, otherwise it will receive events from all event sources. // const char* (*get_parse_event_sources)(); // @@ -932,16 +960,17 @@ typedef struct // The value of the ss_plugin_event_parse_input* output parameter must be // uniquely attached to the ss_plugin_t* parameter value. The pointer // must not be shared across multiple distinct ss_plugin_t* values. - ss_plugin_rc (*parse_event)(ss_plugin_t *s, const ss_plugin_event_input *evt, const ss_plugin_event_parse_input* in); + ss_plugin_rc (*parse_event)(ss_plugin_t* s, + const ss_plugin_event_input* evt, + const ss_plugin_event_parse_input* in); }; // Async events capability API - struct - { + struct { // // Return a string describing the event sources for which this plugin // is capable of injecting async events in the event stream of a capture. - // + // // Required: no // // Return value: a json array of strings containing event @@ -1000,9 +1029,9 @@ typedef struct // expressed in the list returned by get_async_events(). The name // of an async event acts as a contract on the encoding of the data // payload of all async events with the same name. - // + // // Required: yes - // + // // Arguments: // - owner: Opaque pointer to the plugin's owner. Must be passed // as an argument to the async event function handler. @@ -1014,7 +1043,9 @@ typedef struct // // Return value: A ss_plugin_rc with values SS_PLUGIN_SUCCESS or SS_PLUGIN_FAILURE. // - ss_plugin_rc (*set_async_event_handler)(ss_plugin_t* s, ss_plugin_owner_t* owner, const ss_plugin_async_event_handler_t handler); + ss_plugin_rc (*set_async_event_handler)(ss_plugin_t* s, + ss_plugin_owner_t* owner, + const ss_plugin_async_event_handler_t handler); }; // Sets a new plugin configuration when provided by the framework. @@ -1040,16 +1071,16 @@ typedef struct // and it can be set to 0 if no metrics are provided. ss_plugin_metric* (*get_metrics)(ss_plugin_t* s, uint32_t* num_metrics); - //Capture listening capability API - struct - { + // Capture listening capability API + struct { // // Called by the framework when the event capture opens. // // Required: no // Arguments: // - s: the plugin state, returned by init(). Can be NULL. - // - i: input containing vtables for performing table operations and subscribe/unsubscribe async routines + // - i: input containing vtables for performing table operations and subscribe/unsubscribe + // async routines // // Return value: A ss_plugin_rc with values SS_PLUGIN_SUCCESS or SS_PLUGIN_FAILURE. ss_plugin_rc (*capture_open)(ss_plugin_t* s, const ss_plugin_capture_listen_input* i); @@ -1060,7 +1091,8 @@ typedef struct // Required: yes if capture_open is defined // Arguments: // - s: the plugin state, returned by init(). Can be NULL. - // - i: input containing vtables for performing table operations and subscribe/unsubscribe async routines + // - i: input containing vtables for performing table operations and subscribe/unsubscribe + // async routines // // Return value: A ss_plugin_rc with values SS_PLUGIN_SUCCESS or SS_PLUGIN_FAILURE. ss_plugin_rc (*capture_close)(ss_plugin_t* s, const ss_plugin_capture_listen_input* i); diff --git a/userspace/plugin/plugin_loader.c b/userspace/plugin/plugin_loader.c index 8361f121bb..0de84ee864 100644 --- a/userspace/plugin/plugin_loader.c +++ b/userspace/plugin/plugin_loader.c @@ -17,11 +17,11 @@ limitations under the License. */ #ifdef _WIN32 - #include - typedef HINSTANCE library_handle_t; +#include +typedef HINSTANCE library_handle_t; #else - #include - typedef void* library_handle_t; +#include +typedef void* library_handle_t; #endif #include @@ -30,156 +30,136 @@ limitations under the License. #include #include -static inline void err_prepend(char* s, const char* prefix, const char* sep) -{ - char tmp[PLUGIN_MAX_ERRLEN]; - size_t prefix_len = strlcpy(tmp, prefix, PLUGIN_MAX_ERRLEN); - if (*s != '\0') - { - strlcpy(&tmp[prefix_len], sep, PLUGIN_MAX_ERRLEN - prefix_len); - prefix_len += strlen(sep); - } - strlcpy(&tmp[prefix_len], s, PLUGIN_MAX_ERRLEN - prefix_len); - strlcpy(s, tmp, PLUGIN_MAX_ERRLEN); +static inline void err_prepend(char* s, const char* prefix, const char* sep) { + char tmp[PLUGIN_MAX_ERRLEN]; + size_t prefix_len = strlcpy(tmp, prefix, PLUGIN_MAX_ERRLEN); + if(*s != '\0') { + strlcpy(&tmp[prefix_len], sep, PLUGIN_MAX_ERRLEN - prefix_len); + prefix_len += strlen(sep); + } + strlcpy(&tmp[prefix_len], s, PLUGIN_MAX_ERRLEN - prefix_len); + strlcpy(s, tmp, PLUGIN_MAX_ERRLEN); } -static inline void err_append(char* s, const char* suffix, const char* sep) -{ - if (*s != '\0') - { - strlcat(s, sep, PLUGIN_MAX_ERRLEN); - } - strlcat(s, suffix, PLUGIN_MAX_ERRLEN); +static inline void err_append(char* s, const char* suffix, const char* sep) { + if(*s != '\0') { + strlcat(s, sep, PLUGIN_MAX_ERRLEN); + } + strlcat(s, suffix, PLUGIN_MAX_ERRLEN); } -static void* getsym(library_handle_t handle, const char* name) -{ +static void* getsym(library_handle_t handle, const char* name) { #ifdef _WIN32 - return (void*) GetProcAddress(handle, name); + return (void*)GetProcAddress(handle, name); #else - return (void*) dlsym(handle, name); + return (void*)dlsym(handle, name); #endif } // little hack for simplifying the plugin_load function -#define SYM_RESOLVE(h, s) \ - *(void **)(&(h->api.s)) = getsym(h->handle, "plugin_"#s) - -plugin_handle_t* plugin_load(const char* path, char* err) -{ - // alloc and init memory - err[0] = '\0'; - plugin_handle_t* ret = (plugin_handle_t*) calloc (1, sizeof(plugin_handle_t)); - if (!ret) - { - strlcpy(err, "error allocating plugin handle", PLUGIN_MAX_ERRLEN); - return NULL; - } - - // open dynamic library +#define SYM_RESOLVE(h, s) *(void**)(&(h->api.s)) = getsym(h->handle, "plugin_" #s) + +plugin_handle_t* plugin_load(const char* path, char* err) { + // alloc and init memory + err[0] = '\0'; + plugin_handle_t* ret = (plugin_handle_t*)calloc(1, sizeof(plugin_handle_t)); + if(!ret) { + strlcpy(err, "error allocating plugin handle", PLUGIN_MAX_ERRLEN); + return NULL; + } + + // open dynamic library #ifdef _WIN32 - ret->handle = LoadLibrary(path); - if(ret->handle == NULL) - { - DWORD flg = FORMAT_MESSAGE_ALLOCATE_BUFFER - | FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS; - LPTSTR msg_buf = 0; - if (FormatMessageA(flg, 0, GetLastError(), 0, (LPTSTR) &msg_buf, 0, NULL) && msg_buf) - { - strlcpy(err, msg_buf, PLUGIN_MAX_ERRLEN); - LocalFree(msg_buf); - } - } + ret->handle = LoadLibrary(path); + if(ret->handle == NULL) { + DWORD flg = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS; + LPTSTR msg_buf = 0; + if(FormatMessageA(flg, 0, GetLastError(), 0, (LPTSTR)&msg_buf, 0, NULL) && msg_buf) { + strlcpy(err, msg_buf, PLUGIN_MAX_ERRLEN); + LocalFree(msg_buf); + } + } #else - ret->handle = dlopen(path, RTLD_LAZY); - if (ret->handle == NULL) - { - strlcpy(err, (const char*) dlerror(), PLUGIN_MAX_ERRLEN); - } + ret->handle = dlopen(path, RTLD_LAZY); + if(ret->handle == NULL) { + strlcpy(err, (const char*)dlerror(), PLUGIN_MAX_ERRLEN); + } #endif - // return NULL if library loading had errors - if (ret->handle == NULL) - { - err_prepend(err, "can't load plugin dynamic library:", " "); - free(ret); - return NULL; - } - - // load all library symbols - SYM_RESOLVE(ret, get_required_api_version); - SYM_RESOLVE(ret, get_version); - SYM_RESOLVE(ret, get_last_error); - SYM_RESOLVE(ret, get_name); - SYM_RESOLVE(ret, get_description); - SYM_RESOLVE(ret, get_contact); - SYM_RESOLVE(ret, get_init_schema); - SYM_RESOLVE(ret, init); - SYM_RESOLVE(ret, destroy); - SYM_RESOLVE(ret, get_id); - SYM_RESOLVE(ret, get_event_source); - SYM_RESOLVE(ret, open); - SYM_RESOLVE(ret, close); - SYM_RESOLVE(ret, next_batch); - SYM_RESOLVE(ret, get_progress); - SYM_RESOLVE(ret, list_open_params); - SYM_RESOLVE(ret, event_to_string); - SYM_RESOLVE(ret, get_fields); - SYM_RESOLVE(ret, extract_fields); - SYM_RESOLVE(ret, get_extract_event_sources); - SYM_RESOLVE(ret, get_extract_event_types); - SYM_RESOLVE(ret, get_parse_event_types); - SYM_RESOLVE(ret, get_parse_event_sources); - SYM_RESOLVE(ret, parse_event); - SYM_RESOLVE(ret, get_async_event_sources); - SYM_RESOLVE(ret, get_async_events); - SYM_RESOLVE(ret, set_async_event_handler); - SYM_RESOLVE(ret, set_config); - SYM_RESOLVE(ret, get_metrics); - SYM_RESOLVE(ret, capture_open); - SYM_RESOLVE(ret, capture_close); - return ret; + // return NULL if library loading had errors + if(ret->handle == NULL) { + err_prepend(err, "can't load plugin dynamic library:", " "); + free(ret); + return NULL; + } + + // load all library symbols + SYM_RESOLVE(ret, get_required_api_version); + SYM_RESOLVE(ret, get_version); + SYM_RESOLVE(ret, get_last_error); + SYM_RESOLVE(ret, get_name); + SYM_RESOLVE(ret, get_description); + SYM_RESOLVE(ret, get_contact); + SYM_RESOLVE(ret, get_init_schema); + SYM_RESOLVE(ret, init); + SYM_RESOLVE(ret, destroy); + SYM_RESOLVE(ret, get_id); + SYM_RESOLVE(ret, get_event_source); + SYM_RESOLVE(ret, open); + SYM_RESOLVE(ret, close); + SYM_RESOLVE(ret, next_batch); + SYM_RESOLVE(ret, get_progress); + SYM_RESOLVE(ret, list_open_params); + SYM_RESOLVE(ret, event_to_string); + SYM_RESOLVE(ret, get_fields); + SYM_RESOLVE(ret, extract_fields); + SYM_RESOLVE(ret, get_extract_event_sources); + SYM_RESOLVE(ret, get_extract_event_types); + SYM_RESOLVE(ret, get_parse_event_types); + SYM_RESOLVE(ret, get_parse_event_sources); + SYM_RESOLVE(ret, parse_event); + SYM_RESOLVE(ret, get_async_event_sources); + SYM_RESOLVE(ret, get_async_events); + SYM_RESOLVE(ret, set_async_event_handler); + SYM_RESOLVE(ret, set_config); + SYM_RESOLVE(ret, get_metrics); + SYM_RESOLVE(ret, capture_open); + SYM_RESOLVE(ret, capture_close); + return ret; } -plugin_handle_t* plugin_load_api(const plugin_api* api, char* err) -{ - // alloc and init memory - err[0] = '\0'; - if (!api) - { - strlcpy(err, "can't allocate plugin handle with invalid API table", PLUGIN_MAX_ERRLEN); - return NULL; - } - - plugin_handle_t* ret = (plugin_handle_t*) calloc (1, sizeof(plugin_handle_t)); - if (!ret) - { - strlcpy(err, "error allocating plugin handle", PLUGIN_MAX_ERRLEN); - return NULL; - } - ret->api = *api; - return ret; +plugin_handle_t* plugin_load_api(const plugin_api* api, char* err) { + // alloc and init memory + err[0] = '\0'; + if(!api) { + strlcpy(err, "can't allocate plugin handle with invalid API table", PLUGIN_MAX_ERRLEN); + return NULL; + } + + plugin_handle_t* ret = (plugin_handle_t*)calloc(1, sizeof(plugin_handle_t)); + if(!ret) { + strlcpy(err, "error allocating plugin handle", PLUGIN_MAX_ERRLEN); + return NULL; + } + ret->api = *api; + return ret; } -void plugin_unload(plugin_handle_t* h) -{ - if (h) - { - if (h->handle) - { +void plugin_unload(plugin_handle_t* h) { + if(h) { + if(h->handle) { #ifdef _WIN32 - FreeLibrary(h->handle); + FreeLibrary(h->handle); #else - dlclose(h->handle); + dlclose(h->handle); #endif - } - free(h); - } + } + free(h); + } } -bool plugin_is_loaded(const char* path) -{ +bool plugin_is_loaded(const char* path) { #ifdef _WIN32 /* * LoadLibrary maps the module into the address space of the calling process, if necessary, @@ -202,132 +182,125 @@ bool plugin_is_loaded(const char* path) #endif } -bool plugin_check_required_api_version(const plugin_handle_t* h, char* err) -{ - uint32_t major, minor, patch; - const char *ver, *failmsg; - if (h->api.get_required_api_version == NULL) - { - strlcpy(err, "plugin_get_required_api_version symbol not implemented", PLUGIN_MAX_ERRLEN); - return false; - } - - ver = h->api.get_required_api_version(); - if (sscanf(ver, "%" PRIu32 ".%" PRIu32 ".%" PRIu32, &major, &minor, &patch) != 3) - { - snprintf(err, PLUGIN_MAX_ERRLEN, "plugin provided an invalid required API version: '%s'", ver); - return false; - } - - failmsg = NULL; +bool plugin_check_required_api_version(const plugin_handle_t* h, char* err) { + uint32_t major, minor, patch; + const char *ver, *failmsg; + if(h->api.get_required_api_version == NULL) { + strlcpy(err, "plugin_get_required_api_version symbol not implemented", PLUGIN_MAX_ERRLEN); + return false; + } + + ver = h->api.get_required_api_version(); + if(sscanf(ver, "%" PRIu32 ".%" PRIu32 ".%" PRIu32, &major, &minor, &patch) != 3) { + snprintf(err, + PLUGIN_MAX_ERRLEN, + "plugin provided an invalid required API version: '%s'", + ver); + return false; + } + + failmsg = NULL; /* The plugin requires a minimum framework version */ - if(PLUGIN_API_VERSION_MAJOR != major) - { - failmsg = "major versions disagree"; - } - else if(PLUGIN_API_VERSION_MINOR < minor) - { - failmsg = "framework's minor is less than the requested one"; - } - else if(PLUGIN_API_VERSION_MINOR == minor && PLUGIN_API_VERSION_PATCH < patch) - { - failmsg = "framework's patch is less than the requested one"; - } - - if (failmsg != NULL) - { - snprintf(err, PLUGIN_MAX_ERRLEN, - "plugin required API version '%s' not compatible with the framework's API version '%s': %s", - ver, PLUGIN_API_VERSION_STR, failmsg); - return false; - } - - return true; + if(PLUGIN_API_VERSION_MAJOR != major) { + failmsg = "major versions disagree"; + } else if(PLUGIN_API_VERSION_MINOR < minor) { + failmsg = "framework's minor is less than the requested one"; + } else if(PLUGIN_API_VERSION_MINOR == minor && PLUGIN_API_VERSION_PATCH < patch) { + failmsg = "framework's patch is less than the requested one"; + } + + if(failmsg != NULL) { + snprintf(err, + PLUGIN_MAX_ERRLEN, + "plugin required API version '%s' not compatible with the framework's API version " + "'%s': %s", + ver, + PLUGIN_API_VERSION_STR, + failmsg); + return false; + } + + return true; } - -plugin_caps_t plugin_get_capabilities(const plugin_handle_t* h, char* err) -{ - plugin_caps_t caps = CAP_NONE; - strlcpy(err, "", PLUGIN_MAX_ERRLEN); - - if (h->api.open != NULL && h->api.close != NULL && h->api.next_batch != NULL) - { - bool has_id = h->api.get_id != NULL && h->api.get_id() != 0; - bool has_source = h->api.get_event_source != NULL && strlen(h->api.get_event_source()) > 0; - if ((has_id && has_source) || (!has_id && !has_source)) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_SOURCING); - } - else - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_BROKEN); - err_append(err, "must implement both 'plugin_get_id' and 'plugin_get_event_source' or neither (event sourcing)", ", "); - } - } - else if (h->api.open != NULL || h->api.close != NULL || h->api.next_batch != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_BROKEN); - err_append(err, "must implement all of 'plugin_open', 'plugin_close', and 'plugin_next_batch' (event sourcing)", ", "); - } - - if (h->api.get_fields != NULL && h->api.extract_fields != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_EXTRACTION); - } - else if (h->api.extract_fields != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_BROKEN); - err_append(err, "must implement both 'plugin_get_fields' and 'plugin_extract_fields' (field extraction)", ", "); - } - - if (h->api.parse_event != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_PARSING); - } - - if (h->api.get_async_events != NULL && h->api.set_async_event_handler != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_ASYNC); - } - else if (h->api.set_async_event_handler != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_BROKEN); - err_append(err, "must implement both 'plugin_get_async_events' and 'plugin_set_async_event_handler' (async events)", ", "); - } - - if (h->api.capture_open != NULL && h->api.capture_close != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_CAPTURE_LISTENING); - } - else if (h->api.capture_open != NULL) - { - caps = (plugin_caps_t)((uint32_t) caps | (uint32_t) CAP_BROKEN); - err_append(err, "must implement both 'plugin_capture_open' and 'plugin_capture_close' (capture listening)", ", "); - } - - return caps; +plugin_caps_t plugin_get_capabilities(const plugin_handle_t* h, char* err) { + plugin_caps_t caps = CAP_NONE; + strlcpy(err, "", PLUGIN_MAX_ERRLEN); + + if(h->api.open != NULL && h->api.close != NULL && h->api.next_batch != NULL) { + bool has_id = h->api.get_id != NULL && h->api.get_id() != 0; + bool has_source = h->api.get_event_source != NULL && strlen(h->api.get_event_source()) > 0; + if((has_id && has_source) || (!has_id && !has_source)) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_SOURCING); + } else { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_BROKEN); + err_append(err, + "must implement both 'plugin_get_id' and 'plugin_get_event_source' or " + "neither (event sourcing)", + ", "); + } + } else if(h->api.open != NULL || h->api.close != NULL || h->api.next_batch != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_BROKEN); + err_append(err, + "must implement all of 'plugin_open', 'plugin_close', and 'plugin_next_batch' " + "(event sourcing)", + ", "); + } + + if(h->api.get_fields != NULL && h->api.extract_fields != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_EXTRACTION); + } else if(h->api.extract_fields != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_BROKEN); + err_append(err, + "must implement both 'plugin_get_fields' and 'plugin_extract_fields' (field " + "extraction)", + ", "); + } + + if(h->api.parse_event != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_PARSING); + } + + if(h->api.get_async_events != NULL && h->api.set_async_event_handler != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_ASYNC); + } else if(h->api.set_async_event_handler != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_BROKEN); + err_append(err, + "must implement both 'plugin_get_async_events' and " + "'plugin_set_async_event_handler' (async events)", + ", "); + } + + if(h->api.capture_open != NULL && h->api.capture_close != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_CAPTURE_LISTENING); + } else if(h->api.capture_open != NULL) { + caps = (plugin_caps_t)((uint32_t)caps | (uint32_t)CAP_BROKEN); + err_append(err, + "must implement both 'plugin_capture_open' and 'plugin_capture_close' (capture " + "listening)", + ", "); + } + + return caps; } // little hack for simplifying the plugin_check_required_symbols function -#define SYM_REQCHECK(a, e, s) \ - do { \ - if(a->api.s == NULL) \ - { \ - snprintf(e, PLUGIN_MAX_ERRLEN, "required symbol not implemented: '%s'", #s); \ - return false; \ - } \ - } while(0) - -bool plugin_check_required_symbols(const plugin_handle_t* h, char* err) -{ - SYM_REQCHECK(h, err, get_required_api_version); - SYM_REQCHECK(h, err, get_version); - SYM_REQCHECK(h, err, get_name); - SYM_REQCHECK(h, err, get_description); - SYM_REQCHECK(h, err, get_contact); - SYM_REQCHECK(h, err, init); - SYM_REQCHECK(h, err, destroy); - SYM_REQCHECK(h, err, get_last_error); - return true; +#define SYM_REQCHECK(a, e, s) \ + do { \ + if(a->api.s == NULL) { \ + snprintf(e, PLUGIN_MAX_ERRLEN, "required symbol not implemented: '%s'", #s); \ + return false; \ + } \ + } while(0) + +bool plugin_check_required_symbols(const plugin_handle_t* h, char* err) { + SYM_REQCHECK(h, err, get_required_api_version); + SYM_REQCHECK(h, err, get_version); + SYM_REQCHECK(h, err, get_name); + SYM_REQCHECK(h, err, get_description); + SYM_REQCHECK(h, err, get_contact); + SYM_REQCHECK(h, err, init); + SYM_REQCHECK(h, err, destroy); + SYM_REQCHECK(h, err, get_last_error); + return true; } diff --git a/userspace/plugin/plugin_loader.h b/userspace/plugin/plugin_loader.h index f33b553bc1..e6e833333b 100644 --- a/userspace/plugin/plugin_loader.h +++ b/userspace/plugin/plugin_loader.h @@ -37,15 +37,14 @@ extern "C" { the field extraction phase * ability to inject events asynchronously in the event loop */ -typedef enum -{ - CAP_NONE = 0, - CAP_SOURCING = 1 << 0, - CAP_EXTRACTION = 1 << 1, - CAP_PARSING = 1 << 2, - CAP_ASYNC = 1 << 3, - CAP_CAPTURE_LISTENING = 1 << 4, - CAP_BROKEN = 1 << 31, // used to report inconsistencies +typedef enum { + CAP_NONE = 0, + CAP_SOURCING = 1 << 0, + CAP_EXTRACTION = 1 << 1, + CAP_PARSING = 1 << 2, + CAP_ASYNC = 1 << 3, + CAP_CAPTURE_LISTENING = 1 << 4, + CAP_BROKEN = 1 << 31, // used to report inconsistencies } plugin_caps_t; /*! @@ -53,14 +52,13 @@ typedef enum Pointers to this struct must be obtained through the plugin_load() and released through plugin_unload(). */ -typedef struct plugin_handle_t -{ +typedef struct plugin_handle_t { #ifdef _WIN32 - HINSTANCE handle; ///< Handle of the dynamic library + HINSTANCE handle; ///< Handle of the dynamic library #else - void* handle; ///< Handle of the dynamic library + void* handle; ///< Handle of the dynamic library #endif - plugin_api api; ///< The vtable method of the plugin that define its API + plugin_api api; ///< The vtable method of the plugin that define its API } plugin_handle_t; /*! @@ -78,7 +76,7 @@ plugin_handle_t* plugin_load_api(const plugin_api* api, char* err); plugin_handle_t* plugin_load(const char* path, char* err); /*! - \brief Destroys a plugin_handle_t* previously allocated by + \brief Destroys a plugin_handle_t* previously allocated by invoking plugin_load(). */ void plugin_unload(plugin_handle_t* h); diff --git a/userspace/plugin/plugin_types.h b/userspace/plugin/plugin_types.h index 8cb2edcc9a..b1094e0529 100644 --- a/userspace/plugin/plugin_types.h +++ b/userspace/plugin/plugin_types.h @@ -30,30 +30,28 @@ typedef uint32_t ss_plugin_bool; // The noncontinguous numbers are to maintain equality with underlying // falcosecurity libs types. -typedef enum ss_plugin_field_type -{ +typedef enum ss_plugin_field_type { // A 64bit unsigned integer. - FTYPE_UINT64 = 8, + FTYPE_UINT64 = 8, // A printable buffer of bytes, NULL terminated - FTYPE_STRING = 9, + FTYPE_STRING = 9, // A relative time. Seconds * 10^9 + nanoseconds. 64bit. - FTYPE_RELTIME = 20, + FTYPE_RELTIME = 20, // An absolute time interval. Seconds from epoch * 10^9 + nanoseconds. 64bit. - FTYPE_ABSTIME = 21, + FTYPE_ABSTIME = 21, // A boolean value, 4 bytes. - FTYPE_BOOL = 25, + FTYPE_BOOL = 25, // Either an IPv4 or IPv6 address. The length indicates which one it is. - FTYPE_IPADDR = 40, + FTYPE_IPADDR = 40, // Either an IPv4 or IPv6 network. The length indicates which one it is. // The field encodes only the IP address, so this differs from FTYPE_IPADDR, // from the way the framework perform runtime checks and comparisons. - FTYPE_IPNET = 41, + FTYPE_IPNET = 41, } ss_plugin_field_type; // Values to return from init() / open() / next_batch() / // extract_fields(). -typedef enum ss_plugin_rc -{ +typedef enum ss_plugin_rc { SS_PLUGIN_SUCCESS = 0, SS_PLUGIN_FAILURE = 1, SS_PLUGIN_TIMEOUT = -1, @@ -62,8 +60,7 @@ typedef enum ss_plugin_rc } ss_plugin_rc; // The supported schema formats for the init configuration. -typedef enum ss_plugin_schema_type -{ +typedef enum ss_plugin_schema_type { // The schema is undefined and the init configuration // is an opaque string. SS_PLUGIN_SCHEMA_NONE = 0, @@ -79,7 +76,8 @@ typedef enum ss_plugin_schema_type // An event is represented as a contiguous region of memory composed by // a header and a list of parameters appended, in the form of: // -// | evt header | len param 1 (2B/4B) | ... | len param N (2B/4B) | data param 1 | ... | data param N | +// | evt header | len param 1 (2B/4B) | ... | len param N (2B/4B) | data param 1 | ... | data param +// N | // // The event header is composed of: // - ts: the event timestamp, in nanoseconds since the epoch. @@ -103,10 +101,10 @@ struct ss_plugin_event { #ifdef PPM_ENABLE_SENTINEL uint32_t sentinel_begin; #endif - uint64_t ts; /* timestamp, in nanoseconds from epoch */ - uint64_t tid; /* the tid of the thread that generated this event */ - uint32_t len; /* the event len, including the header */ - uint16_t type; /* the event type */ + uint64_t ts; /* timestamp, in nanoseconds from epoch */ + uint64_t tid; /* the tid of the thread that generated this event */ + uint32_t len; /* the event len, including the header */ + uint16_t type; /* the event type */ uint32_t nparams; /* the number of parameters of the event */ }; #pragma pack(pop) @@ -119,14 +117,13 @@ typedef struct ss_plugin_event ss_plugin_event; // Might not be contiguous. // - evtsrc: The name of the event's source. Can be "syscall" or any other // event source name implemented by a plugin. -typedef struct ss_plugin_event_input -{ +typedef struct ss_plugin_event_input { const ss_plugin_event* evt; uint64_t evtnum; const char* evtsrc; } ss_plugin_event_input; -typedef struct ss_plugin_byte_buffer{ +typedef struct ss_plugin_byte_buffer { uint32_t len; const void* ptr; } ss_plugin_byte_buffer; @@ -139,16 +136,16 @@ typedef struct ss_plugin_byte_buffer{ // arg_key: the field argument, if a 'key' argument has been specified // for the field (isKey=true), otherwise it's NULL. // For example: -// * if the field specified by the user is foo.bar[pippo], arg_key +// * if the field specified by the user is foo.bar[pippo], arg_key // will be the string "pippo" // * if the field specified by the user is foo.bar, arg will be NULL // arg_index: the field argument, if a 'index' argument has been specified // for the field (isIndex=true), otherwise it's 0. // For example: -// * if the field specified by the user is foo.bar[1], arg_index -// will be the uint64_t '1'. +// * if the field specified by the user is foo.bar[1], arg_index +// will be the uint64_t '1'. // Please note the ambiguity with a 0 -// argument which could be a real argument of just the default +// argument which could be a real argument of just the default // value to point out the absence. The `arg_present` field resolves // this ambiguity. // arg_present: helps to understand if the arg is there since arg_index is @@ -169,14 +166,12 @@ typedef struct ss_plugin_byte_buffer{ // If the field is a list type, then res_len can must be any value from 0 to N, depending // on how many values can be extracted from a given event. // Setting res_len to 0 means that no value of this field can be extracted from a given event. -typedef struct ss_plugin_extract_field -{ +typedef struct ss_plugin_extract_field { // NOTE: For a given architecture, this has always the same size which // is sizeof(uintptr_t). Adding new value types will not create breaking // changes in the plugin API. However, we must make sure that each added // type is always a pointer. - union - { + union { const char** str; uint64_t* u64; uint32_t* u32; @@ -211,8 +206,7 @@ typedef void ss_plugin_table_field_t; // The noncontinguous numbers are to maintain equality with underlying // falcosecurity libs types. // todo(jasondellaluce): should we merge this with ss_plugin_field_type? -typedef enum ss_plugin_state_type -{ +typedef enum ss_plugin_state_type { SS_PLUGIN_ST_INT8 = 1, SS_PLUGIN_ST_INT16 = 2, SS_PLUGIN_ST_INT32 = 3, @@ -228,8 +222,7 @@ typedef enum ss_plugin_state_type // Data representation of entry fields of state tables. // todo(jasondellaluce): should we merge this with what we have for field extraction? -typedef union ss_plugin_state_data -{ +typedef union ss_plugin_state_data { int8_t s8; int16_t s16; int32_t s32; @@ -244,15 +237,13 @@ typedef union ss_plugin_state_data } ss_plugin_state_data; // Info about a state table. -typedef struct ss_plugin_table_info -{ +typedef struct ss_plugin_table_info { const char* name; ss_plugin_state_type key_type; } ss_plugin_table_info; // Info about a data field contained in the entires of a state table. -typedef struct ss_plugin_table_fieldinfo -{ +typedef struct ss_plugin_table_fieldinfo { const char* name; ss_plugin_state_type field_type; ss_plugin_bool read_only; @@ -283,8 +274,7 @@ typedef void ss_instance_t; // // Severity available in the logging facility provided by the framework -typedef enum ss_plugin_log_severity -{ +typedef enum ss_plugin_log_severity { SS_PLUGIN_LOG_SEV_FATAL = 1, SS_PLUGIN_LOG_SEV_CRITICAL = 2, SS_PLUGIN_LOG_SEV_ERROR = 3, @@ -296,8 +286,7 @@ typedef enum ss_plugin_log_severity } ss_plugin_log_severity; // Types supported by the by the metric values -typedef enum ss_plugin_metric_value_type -{ +typedef enum ss_plugin_metric_value_type { SS_PLUGIN_METRIC_VALUE_TYPE_U32 = 0, SS_PLUGIN_METRIC_VALUE_TYPE_S32 = 1, SS_PLUGIN_METRIC_VALUE_TYPE_U64 = 2, @@ -308,8 +297,7 @@ typedef enum ss_plugin_metric_value_type } ss_plugin_metric_value_type; // Data representation of metric values -typedef union ss_plugin_metric_value -{ +typedef union ss_plugin_metric_value { uint32_t u32; int32_t s32; uint64_t u64; @@ -320,16 +308,14 @@ typedef union ss_plugin_metric_value } ss_plugin_metric_value; // Metric types -typedef enum ss_plugin_metric_type -{ +typedef enum ss_plugin_metric_type { SS_PLUGIN_METRIC_TYPE_MONOTONIC = 0, SS_PLUGIN_METRIC_TYPE_NON_MONOTONIC = 1, } ss_plugin_metric_type; // // Struct representing a metric to be provided to the plugin framework -typedef struct ss_plugin_metric -{ +typedef struct ss_plugin_metric { // // Opaque string representing the metric name const char* name;