1#!/usr/bin/env python3 2# Copyright (c) Sasha Goldshtein 3# Licensed under the Apache License, Version 2.0 (the "License") 4 5import bcc 6import unittest 7from time import sleep 8from utils import kernel_version_ge 9import os 10import subprocess 11 12@unittest.skipUnless(kernel_version_ge(4,7), "requires kernel >= 4.7") 13class TestTracepoint(unittest.TestCase): 14 def test_tracepoint(self): 15 text = b""" 16 BPF_HASH(switches, u32, u64); 17 TRACEPOINT_PROBE(sched, sched_switch) { 18 u64 val = 0; 19 u32 pid = args->next_pid; 20 u64 *existing = switches.lookup_or_init(&pid, &val); 21 (*existing)++; 22 return 0; 23 } 24 """ 25 b = bcc.BPF(text=text) 26 sleep(1) 27 total_switches = 0 28 for k, v in b[b"switches"].items(): 29 total_switches += v.value 30 self.assertNotEqual(0, total_switches) 31 32@unittest.skipUnless(kernel_version_ge(4,7), "requires kernel >= 4.7") 33class TestTracepointDataLoc(unittest.TestCase): 34 def test_tracepoint_data_loc(self): 35 text = b""" 36 struct value_t { 37 char filename[64]; 38 }; 39 BPF_HASH(execs, u32, struct value_t); 40 TRACEPOINT_PROBE(sched, sched_process_exec) { 41 struct value_t val = {0}; 42 char fn[64]; 43 u32 pid = args->pid; 44 struct value_t *existing = execs.lookup_or_init(&pid, &val); 45 TP_DATA_LOC_READ_CONST(fn, filename, 64); 46 __builtin_memcpy(existing->filename, fn, 64); 47 return 0; 48 } 49 """ 50 b = bcc.BPF(text=text) 51 subprocess.check_output(["/bin/ls"]) 52 sleep(1) 53 self.assertTrue("/bin/ls" in [v.filename.decode() 54 for v in b[b"execs"].values()]) 55 56if __name__ == "__main__": 57 unittest.main() 58