#!/usr/bin/python

from bcc import BPF
from time import sleep
from ctypes import c_ushort, c_int, c_ulonglong
from sys import argv


print("Hit Ctrl-C to end.")
count = 100
interval = 5
loop = 0
# load BPF program
bpf_text="""
#include <hostcompat/linux/sched.h>
#include <hostcompat/uapi/linux/ptrace.h>

struct p_name{
	char buf[TASK_COMM_LEN];
	u32 pid;
};

BPF_HASH(counter, struct p_name);
BPF_HASH(licznik);

int sending_message(struct pt_regs *ctx, void *ptri, void *message){
	struct p_name process = {' ', 0};
	u64 zero = 0;
	u32 ret = PT_REGS_RC(ctx);
	process.pid = bpf_get_current_pid_tgid();
	bpf_get_current_comm(&(process.buf), sizeof(process.buf));
	counter.increment(process);
	return 0;
}

"""
bpf_text = bpf_text.replace('INTERVAL', '%d' % interval)
b = BPF(text=bpf_text)

b.attach_uprobe(name="dbus-1", sym="dbus_connection_send", fn_name="sending_message")
b.attach_uprobe(name="dbus-1", sym="dbus_connection_send_preallocated", fn_name="sending_message")
b.attach_uprobe(name="dbus-1", sym="dbus_connection_send_with_reply", fn_name="sending_message")

while (1):
	if count > 0:
		loop += 1
		if loop > count:
			exit()
	sleep(interval)
	print ("%d:" % loop)
	stats = b["counter"]
	print("%10s %20s %20s" % ("PID", "NAME", "MESSAGES SENT"))
	for k, v in stats.items():
		print("%10d %20s %20d\n" % (k.pid, k.buf.encode('string-escape'), v.value ))
