blob: 89c37c3074a96ff7e475ed4cc7fd490f62c48783 [file] [log] [blame]
Brendan Greggaa879972016-01-28 22:43:37 -08001#!/usr/bin/python
2#
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
mcaleavyaee5f8232016-02-12 20:06:38 +000017import ctypes as ct
Brendan Greggaa879972016-01-28 22:43:37 -080018
19# load BPF program
20bpf_text = """
21#include <uapi/linux/ptrace.h>
mcaleavyaee5f8232016-02-12 20:06:38 +000022
23struct str_t {
24 u64 pid;
25 char str[80];
26};
27
28BPF_PERF_OUTPUT(events);
29
Brendan Greggaa879972016-01-28 22:43:37 -080030int printret(struct pt_regs *ctx) {
mcaleavyaee5f8232016-02-12 20:06:38 +000031 struct str_t data = {};
32 u32 pid;
Naveen N. Rao4afa96a2016-05-03 14:54:21 +053033 if (!PT_REGS_RC(ctx))
Brendan Greggaa879972016-01-28 22:43:37 -080034 return 0;
mcaleavyaee5f8232016-02-12 20:06:38 +000035 pid = bpf_get_current_pid_tgid();
36 data.pid = pid;
Naveen N. Rao4afa96a2016-05-03 14:54:21 +053037 bpf_probe_read(&data.str, sizeof(data.str), (void *)PT_REGS_RC(ctx));
mcaleavyaee5f8232016-02-12 20:06:38 +000038 events.perf_submit(ctx,&data,sizeof(data));
Brendan Greggaa879972016-01-28 22:43:37 -080039
40 return 0;
41};
42"""
mcaleavyaee5f8232016-02-12 20:06:38 +000043STR_DATA = 80
44
45class Data(ct.Structure):
46 _fields_ = [
47 ("pid", ct.c_ulonglong),
48 ("str", ct.c_char * STR_DATA)
49 ]
50
Brendan Greggaa879972016-01-28 22:43:37 -080051b = BPF(text=bpf_text)
52b.attach_uretprobe(name="/bin/bash", sym="readline", fn_name="printret")
53
54# header
55print("%-9s %-6s %s" % ("TIME", "PID", "COMMAND"))
56
mcaleavyaee5f8232016-02-12 20:06:38 +000057def print_event(cpu, data, size):
58 event = ct.cast(data, ct.POINTER(Data)).contents
Paul Chaignonae0e0252017-10-07 11:52:30 +020059 print("%-9s %-6d %s" % (strftime("%H:%M:%S"), event.pid,
jeromemarchandb96ebcd2018-10-10 01:58:15 +020060 event.str.decode('utf-8', 'replace')))
mcaleavyaee5f8232016-02-12 20:06:38 +000061
62b["events"].open_perf_buffer(print_event)
Brendan Greggaa879972016-01-28 22:43:37 -080063while 1:
Teng Qindbf00292018-02-28 21:47:50 -080064 b.perf_buffer_poll()