• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/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")
45parser.add_argument("--ebpf", action="store_true",
46    help=argparse.SUPPRESS)
47args = parser.parse_args()
48debug = 0
49
50if args.device == "-1":
51    usage()
52
53path = args.device
54if path.find('/') != 0:
55    path = "/dev/pts/" + path
56try:
57    pi = stat(path)
58except:
59    print("Unable to read device %s. Exiting." % path)
60    exit()
61
62# define BPF program
63bpf_text = """
64#include <uapi/linux/ptrace.h>
65#include <linux/fs.h>
66
67#define BUFSIZE 256
68struct data_t {
69    int count;
70    char buf[BUFSIZE];
71};
72
73BPF_PERF_OUTPUT(events);
74
75int kprobe__tty_write(struct pt_regs *ctx, struct file *file,
76    const char __user *buf, size_t count)
77{
78    if (file->f_inode->i_ino != PTS)
79        return 0;
80
81    // bpf_probe_read() can only use a fixed size, so truncate to count
82    // in user space:
83    struct data_t data = {};
84    bpf_probe_read(&data.buf, BUFSIZE, (void *)buf);
85    if (count > BUFSIZE)
86        data.count = BUFSIZE;
87    else
88        data.count = count;
89    events.perf_submit(ctx, &data, sizeof(data));
90
91    return 0;
92};
93"""
94
95bpf_text = bpf_text.replace('PTS', str(pi.st_ino))
96if debug or args.ebpf:
97    print(bpf_text)
98    if args.ebpf:
99        exit()
100
101# initialize BPF
102b = BPF(text=bpf_text)
103
104BUFSIZE = 256
105
106class Data(ct.Structure):
107    _fields_ = [
108        ("count", ct.c_int),
109        ("buf", ct.c_char * BUFSIZE)
110    ]
111
112if not args.noclear:
113    call("clear")
114
115# process event
116def print_event(cpu, data, size):
117    event = ct.cast(data, ct.POINTER(Data)).contents
118    print("%s" % event.buf[0:event.count].decode('utf-8', 'replace'), end="")
119    sys.stdout.flush()
120
121# loop with callback to print_event
122b["events"].open_perf_buffer(print_event)
123while 1:
124    b.perf_buffer_poll()
125