blob: af4f18ec8917b2a54c35dca079c82a1ff3cbb405 [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Brendan Greggaa879972016-01-28 22:43:37 -08002#
3# bashreadline Print entered bash commands from all running shells.
4# For Linux, uses BCC, eBPF. Embedded C.
5#
6# This works by tracing the readline() function using a uretprobe (uprobes).
7#
8# Copyright 2016 Netflix, Inc.
9# Licensed under the Apache License, Version 2.0 (the "License")
10#
11# 28-Jan-2016 Brendan Gregg Created this.
mcaleavyaee5f8232016-02-12 20:06:38 +000012# 12-Feb-2016 Allan McAleavy migrated to BPF_PERF_OUTPUT
Brendan Greggaa879972016-01-28 22:43:37 -080013
14from __future__ import print_function
15from bcc import BPF
16from time import strftime
17
18# load BPF program
19bpf_text = """
20#include <uapi/linux/ptrace.h>
mcaleavyaee5f8232016-02-12 20:06:38 +000021
22struct str_t {
23 u64 pid;
24 char str[80];
25};
26
27BPF_PERF_OUTPUT(events);
28
Brendan Greggaa879972016-01-28 22:43:37 -080029int printret(struct pt_regs *ctx) {
mcaleavyaee5f8232016-02-12 20:06:38 +000030 struct str_t data = {};
31 u32 pid;
Naveen N. Rao4afa96a2016-05-03 14:54:21 +053032 if (!PT_REGS_RC(ctx))
Brendan Greggaa879972016-01-28 22:43:37 -080033 return 0;
mcaleavyaee5f8232016-02-12 20:06:38 +000034 pid = bpf_get_current_pid_tgid();
35 data.pid = pid;
Naveen N. Rao4afa96a2016-05-03 14:54:21 +053036 bpf_probe_read(&data.str, sizeof(data.str), (void *)PT_REGS_RC(ctx));
mcaleavyaee5f8232016-02-12 20:06:38 +000037 events.perf_submit(ctx,&data,sizeof(data));
Brendan Greggaa879972016-01-28 22:43:37 -080038
39 return 0;
40};
41"""
mcaleavyaee5f8232016-02-12 20:06:38 +000042
Brendan Greggaa879972016-01-28 22:43:37 -080043b = BPF(text=bpf_text)
44b.attach_uretprobe(name="/bin/bash", sym="readline", fn_name="printret")
45
46# header
47print("%-9s %-6s %s" % ("TIME", "PID", "COMMAND"))
48
mcaleavyaee5f8232016-02-12 20:06:38 +000049def print_event(cpu, data, size):
Xiaozhou Liu51d62d32019-02-15 13:03:05 +080050 event = b["events"].event(data)
Paul Chaignonae0e0252017-10-07 11:52:30 +020051 print("%-9s %-6d %s" % (strftime("%H:%M:%S"), event.pid,
jeromemarchandb96ebcd2018-10-10 01:58:15 +020052 event.str.decode('utf-8', 'replace')))
mcaleavyaee5f8232016-02-12 20:06:38 +000053
54b["events"].open_perf_buffer(print_event)
Brendan Greggaa879972016-01-28 22:43:37 -080055while 1:
Jerome Marchand51671272018-12-19 01:57:24 +010056 try:
57 b.perf_buffer_poll()
58 except KeyboardInterrupt:
59 exit()