blob: 1510d7b724f8d2aa5544c206f825f7603c310bd9 [file] [log] [blame]
Brendan Gregg6049d3f2016-10-16 12:33:50 -07001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
4# ttysnoop Watch live output from a tty or pts device.
5# For Linux, uses BCC, eBPF. Embedded C.
6#
7# Due to a limited buffer size (see BUFSIZE), some commands (eg, a vim
8# session) are likely to be printed a little messed up.
9#
10# Copyright (c) 2016 Brendan Gregg.
11# Licensed under the Apache License, Version 2.0 (the "License")
12#
13# Idea: from ttywatcher.
14#
15# 15-Oct-2016 Brendan Gregg Created this.
16
17from __future__ import print_function
18from bcc import BPF
19import ctypes as ct
20from subprocess import call
21import argparse
22from sys import argv
23import sys
24from os import stat
25
26def usage():
27 print("USAGE: %s [-Ch] {PTS | /dev/ttydev} # try -h for help" % argv[0])
28 exit()
29
30# arguments
31examples = """examples:
32 ./ttysnoop /dev/pts/2 # snoop output from /dev/pts/2
33 ./ttysnoop 2 # snoop output from /dev/pts/2 (shortcut)
34 ./ttysnoop /dev/console # snoop output from the system console
35 ./ttysnoop /dev/tty0 # snoop output from /dev/tty0
36"""
37parser = argparse.ArgumentParser(
38 description="Snoop output from a pts or tty device, eg, a shell",
39 formatter_class=argparse.RawDescriptionHelpFormatter,
40 epilog=examples)
41parser.add_argument("-C", "--noclear", action="store_true",
42 help="don't clear the screen")
43parser.add_argument("device", default="-1",
44 help="path to a tty device (eg, /dev/tty0) or pts number")
45args = parser.parse_args()
46debug = 0
47
48if args.device == "-1":
49 usage()
50
51path = args.device
52if path.find('/') != 0:
53 path = "/dev/pts/" + path
54try:
55 pi = stat(path)
56except:
57 print("Unable to read device %s. Exiting." % path)
58 exit()
59
60# define BPF program
61bpf_text = """
62#include <uapi/linux/ptrace.h>
63#include <linux/fs.h>
64
65#define BUFSIZE 256
66struct data_t {
67 int count;
68 char buf[BUFSIZE];
69};
70
71BPF_PERF_OUTPUT(events);
72
73int kprobe__tty_write(struct pt_regs *ctx, struct file *file,
74 const char __user *buf, size_t count)
75{
76 if (file->f_inode->i_ino != PTS)
77 return 0;
78
79 // bpf_probe_read() can only use a fixed size, so truncate to count
80 // in user space:
81 struct data_t data = {};
82 bpf_probe_read(&data.buf, BUFSIZE, (void *)buf);
83 if (count > BUFSIZE)
84 data.count = BUFSIZE;
85 else
86 data.count = count;
87 events.perf_submit(ctx, &data, sizeof(data));
88
89 return 0;
90};
91"""
92
93bpf_text = bpf_text.replace('PTS', str(pi.st_ino))
94if debug:
95 print(bpf_text)
96
97# initialize BPF
98b = BPF(text=bpf_text)
99
100BUFSIZE = 256
101
102class Data(ct.Structure):
103 _fields_ = [
104 ("count", ct.c_int),
105 ("buf", ct.c_char * BUFSIZE)
106 ]
107
108if not args.noclear:
109 call("clear")
110
111# process event
112def print_event(cpu, data, size):
113 event = ct.cast(data, ct.POINTER(Data)).contents
Rafael F78948e42017-03-26 14:54:25 +0200114 print("%s" % event.buf[0:event.count].decode(), end="")
Brendan Gregg6049d3f2016-10-16 12:33:50 -0700115 sys.stdout.flush()
116
117# loop with callback to print_event
118b["events"].open_perf_buffer(print_event)
119while 1:
120 b.kprobe_poll()