{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "79b74928-f4b4-4320-96e3-d973997de2f4", "metadata": {}, "outputs": [], "source": [ "from pythonbpf import bpf, map, struct, section, bpfglobal, BPF\n", "from pythonbpf.helper import ktime, pid, comm\n", "from pythonbpf.maps import PerfEventArray\n", "from ctypes import c_void_p, c_int64" ] }, { "cell_type": "code", "execution_count": null, "id": "5bdb0329-ae2d-45e8-808e-5ed5b1374204", "metadata": {}, "outputs": [], "source": [ "@bpf\n", "@struct\n", "class data_t:\n", " pid: c_int64\n", " ts: c_int64\n", " comm: str(16)\n", "\n", "\n", "@bpf\n", "@map\n", "def events() -> PerfEventArray:\n", " return PerfEventArray(key_size=c_int64, value_size=c_int64)\n", "\n", "\n", "@bpf\n", "@section(\"tracepoint/syscalls/sys_enter_clone\")\n", "def hello(ctx: c_void_p) -> c_int64:\n", " dataobj = data_t()\n", " dataobj.pid, dataobj.ts = pid(), ktime()\n", " comm(dataobj.comm)\n", " events.output(dataobj)\n", " return 0\n", "\n", "\n", "@bpf\n", "@bpfglobal\n", "def LICENSE() -> str:\n", " return \"GPL\"\n", "\n", "\n", "# Compile and load\n", "b = BPF()\n", "b.load()\n", "b.attach_all()" ] }, { "cell_type": "code", "execution_count": null, "id": "4bcc7d57-6cc4-48a3-bbd2-42ad6263afdf", "metadata": {}, "outputs": [], "source": [ "start = 0\n", "\n", "\n", "def callback(cpu, event):\n", " global start\n", " if start == 0:\n", " start = event.ts\n", " ts = (event.ts - start) / 1e9\n", " print(f\"[CPU {cpu}] PID: {event.pid}, TS: {ts}, COMM: {event.comm.decode()}\")\n", "\n", "\n", "perf = b[\"events\"].open_perf_buffer(callback, struct_name=\"data_t\")\n", "print(\"Starting to poll... (Ctrl+C to stop)\")\n", "print(\"Try running: fork() or clone() system calls to trigger events\")\n", "\n", "try:\n", " while True:\n", " b[\"events\"].poll(1000)\n", "except KeyboardInterrupt:\n", " print(\"Stopping...\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.3" } }, "nbformat": 4, "nbformat_minor": 5 }