-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadsnoop.py
executable file
·87 lines (72 loc) · 2.25 KB
/
threadsnoop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python
# @lint-avoid-python-3-compatibility-imports
#
# threadsnoop List new thread creation.
# For Linux, uses BCC, eBPF. Embedded C.
#
# Copyright (c) 2019 Brendan Gregg.
# Licensed under the Apache License, Version 2.0 (the "License").
# This was originally created for the BPF Performance Tools book
# published by Addison Wesley. ISBN-13: 9780136554820
# When copying or porting, include this comment.
#
# 02-Jul-2019 Brendan Gregg Ported from bpftrace to BCC.
from __future__ import print_function
from bcc import BPF
import argparse
examples = """
EXAMPLES:
./threadsnoop -O /lib/libpthread-2.33.so
"""
description = """
List new thread creation.
"""
parser = argparse.ArgumentParser(description=description,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=examples)
parser.add_argument("-O", "--obj", type=str, default="pthread",
help="attach to pthread functions in the specified object")
args = parser.parse_args()
# load BPF program
b = BPF(text="""
#include <linux/sched.h>
struct data_t {
u64 ts;
u32 pid;
u64 start;
char comm[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(events);
void do_entry(struct pt_regs *ctx) {
struct data_t data = {};
data.ts = bpf_ktime_get_ns();
data.pid = bpf_get_current_pid_tgid() >> 32;
data.start = PT_REGS_PARM3(ctx);
bpf_get_current_comm(&data.comm, sizeof(data.comm));
events.perf_submit(ctx, &data, sizeof(data));
};
""")
# Since version 2.34, pthread features are integrated in libc
try:
b.attach_uprobe(name=args.obj, sym="pthread_create", fn_name="do_entry")
except Exception:
b.attach_uprobe(name="c", sym="pthread_create", fn_name="do_entry")
print("%-10s %-7s %-16s %s" % ("TIME(ms)", "PID", "COMM", "FUNC"))
start_ts = 0
# process event
def print_event(cpu, data, size):
global start_ts
event = b["events"].event(data)
if start_ts == 0:
start_ts = event.ts
func = b.sym(event.start, event.pid)
if (func == "[unknown]"):
func = hex(event.start)
print("%-10d %-7d %-16s %s" % ((event.ts - start_ts) / 1000000,
event.pid, event.comm, func))
b["events"].open_perf_buffer(print_event)
while 1:
try:
b.perf_buffer_poll()
except KeyboardInterrupt:
exit()