Skip to content

Instantly share code, notes, and snippets.

@jvns
Last active October 25, 2021 12:43
Show Gist options
  • Save jvns/b81991a29a2a595a197709ed47055a2c to your computer and use it in GitHub Desktop.
Save jvns/b81991a29a2a595a197709ed47055a2c to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# to try this you'll need to edit in the name of your ruby binary and install bcc-tools
# bcc installation instructions are at https://github.com/iovisor/bcc/blob/master/INSTALL.md
from __future__ import print_function
from bcc import BPF
from time import sleep
import os
# load BPF program
b = BPF(text="""
#include <uapi/linux/ptrace.h>
BPF_HASH(counts, size_t);
int count(struct pt_regs *ctx) {
u64 zero = 0, *val;
u64 key = 1;
size_t ptr = PT_REGS_PARM1(ctx);
val = counts.lookup_or_init(&ptr, &zero);
(*val)++;
return 0;
};
""")
b.attach_uprobe(name="/home/bork/.rbenv/versions/2.4.0/bin/ruby", sym="newobj_slowpath", fn_name="count")
# header
print("Tracing newobj_slowpath()... Hit Ctrl-C to end.")
counts = b.get_table("counts")
while True:
sleep(1)
os.system('clear')
print("%20s | %s" % ("CLASS POINTER", "COUNT"))
print("%20s | %s" % ("", ""))
top = list(reversed(sorted([(counts.get(key).value, key.value) for key in counts.keys()])))
top = top[:10]
for (count, ptr) in top:
print("%20s | %s" % (ptr, count))
counts.clear()
@purpleP
Copy link

purpleP commented Feb 1, 2018

This can be written more compactly

for count, ptr in islice(sorted(counts.items(), reversed=True)), 10)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment