blob: 2e84e0220ad9e6aaeed38549d6c3ea46c377fc9a [file] [log] [blame]
Brendan Greggbedd1502015-09-17 21:52:52 -07001#!/usr/bin/python
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08002# @lint-avoid-python-3-compatibility-imports
Brendan Greggbedd1502015-09-17 21:52:52 -07003#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08004# opensnoop Trace open() syscalls.
5# For Linux, uses BCC, eBPF. Embedded C.
Brendan Greggbedd1502015-09-17 21:52:52 -07006#
Paul Chaignon702de382018-01-28 13:41:35 +01007# USAGE: opensnoop [-h] [-T] [-x] [-p PID] [-d DURATION] [-t TID] [-n NAME]
Brendan Greggbedd1502015-09-17 21:52:52 -07008#
9# Copyright (c) 2015 Brendan Gregg.
10# Licensed under the Apache License, Version 2.0 (the "License")
11#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080012# 17-Sep-2015 Brendan Gregg Created this.
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030013# 29-Apr-2016 Allan McAleavy Updated for BPF_PERF_OUTPUT.
14# 08-Oct-2016 Dina Goldshtein Support filtering by PID and TID.
Tim Douglasd3583a82018-12-30 13:18:54 -050015# 28-Dec-2018 Tim Douglas Print flags argument, enable filtering
takumakumef8990372019-01-02 17:12:14 +090016# 06-Jan-2019 Takuma Kume Support filtering by UID
Brendan Greggbedd1502015-09-17 21:52:52 -070017
18from __future__ import print_function
Gary Lin40fd6692018-02-12 16:51:14 +080019from bcc import ArgString, BPF
Brendan Greggbedd1502015-09-17 21:52:52 -070020import argparse
mcaleavya3c446c72016-04-29 13:38:51 +010021import ctypes as ct
Paul Chaignon702de382018-01-28 13:41:35 +010022from datetime import datetime, timedelta
Tim Douglasd3583a82018-12-30 13:18:54 -050023import os
Brendan Greggbedd1502015-09-17 21:52:52 -070024
25# arguments
26examples = """examples:
27 ./opensnoop # trace all open() syscalls
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030028 ./opensnoop -T # include timestamps
takumakumef8990372019-01-02 17:12:14 +090029 ./opensnoop -U # include UID
Brendan Greggbedd1502015-09-17 21:52:52 -070030 ./opensnoop -x # only show failed opens
31 ./opensnoop -p 181 # only trace PID 181
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030032 ./opensnoop -t 123 # only trace TID 123
takumakumef8990372019-01-02 17:12:14 +090033 ./opensnoop -u 1000 # only trace UID 1000
Paul Chaignon702de382018-01-28 13:41:35 +010034 ./opensnoop -d 10 # trace for 10 seconds only
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020035 ./opensnoop -n main # only print process names containing "main"
Tim Douglasd3583a82018-12-30 13:18:54 -050036 ./opensnoop -e # show extended fields
37 ./opensnoop -f O_WRONLY -f O_RDWR # only print calls for writing
Brendan Greggbedd1502015-09-17 21:52:52 -070038"""
39parser = argparse.ArgumentParser(
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080040 description="Trace open() syscalls",
41 formatter_class=argparse.RawDescriptionHelpFormatter,
42 epilog=examples)
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030043parser.add_argument("-T", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080044 help="include timestamp on output")
takumakumef8990372019-01-02 17:12:14 +090045parser.add_argument("-U", "--print-uid", action="store_true",
46 help="print UID column")
Brendan Greggbedd1502015-09-17 21:52:52 -070047parser.add_argument("-x", "--failed", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080048 help="only show failed opens")
Brendan Greggbedd1502015-09-17 21:52:52 -070049parser.add_argument("-p", "--pid",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080050 help="trace this PID only")
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030051parser.add_argument("-t", "--tid",
52 help="trace this TID only")
takumakumef8990372019-01-02 17:12:14 +090053parser.add_argument("-u", "--uid",
54 help="trace this UID only")
Paul Chaignon702de382018-01-28 13:41:35 +010055parser.add_argument("-d", "--duration",
56 help="total duration of trace in seconds")
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020057parser.add_argument("-n", "--name",
Gary Lin40fd6692018-02-12 16:51:14 +080058 type=ArgString,
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020059 help="only print process names containing this name")
Nathan Scottcf0792f2018-02-02 16:56:50 +110060parser.add_argument("--ebpf", action="store_true",
61 help=argparse.SUPPRESS)
Tim Douglasd3583a82018-12-30 13:18:54 -050062parser.add_argument("-e", "--extended_fields", action="store_true",
63 help="show extended fields")
64parser.add_argument("-f", "--flag_filter", action="append",
65 help="filter on flags argument (e.g., O_WRONLY)")
Brendan Greggbedd1502015-09-17 21:52:52 -070066args = parser.parse_args()
67debug = 0
Paul Chaignon702de382018-01-28 13:41:35 +010068if args.duration:
69 args.duration = timedelta(seconds=int(args.duration))
Tim Douglasd3583a82018-12-30 13:18:54 -050070flag_filter_mask = 0
71for flag in args.flag_filter or []:
72 if not flag.startswith('O_'):
73 exit("Bad flag: %s" % flag)
74 try:
75 flag_filter_mask |= getattr(os, flag)
76 except AttributeError:
77 exit("Bad flag: %s" % flag)
Brendan Greggbedd1502015-09-17 21:52:52 -070078
79# define BPF program
80bpf_text = """
81#include <uapi/linux/ptrace.h>
mcaleavya3c446c72016-04-29 13:38:51 +010082#include <uapi/linux/limits.h>
83#include <linux/sched.h>
84
85struct val_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030086 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010087 char comm[TASK_COMM_LEN];
88 const char *fname;
Tim Douglasd3583a82018-12-30 13:18:54 -050089 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +010090};
91
92struct data_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030093 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010094 u64 ts;
takumakumef8990372019-01-02 17:12:14 +090095 u32 uid;
mcaleavya3c446c72016-04-29 13:38:51 +010096 int ret;
97 char comm[TASK_COMM_LEN];
98 char fname[NAME_MAX];
Tim Douglasd3583a82018-12-30 13:18:54 -050099 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +0100100};
Brendan Greggbedd1502015-09-17 21:52:52 -0700101
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300102BPF_HASH(infotmp, u64, struct val_t);
mcaleavya3c446c72016-04-29 13:38:51 +0100103BPF_PERF_OUTPUT(events);
Brendan Greggbedd1502015-09-17 21:52:52 -0700104
Tim Douglasd3583a82018-12-30 13:18:54 -0500105int trace_entry(struct pt_regs *ctx, int dfd, const char __user *filename, int flags)
Brendan Greggbedd1502015-09-17 21:52:52 -0700106{
mcaleavya3c446c72016-04-29 13:38:51 +0100107 struct val_t val = {};
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300108 u64 id = bpf_get_current_pid_tgid();
109 u32 pid = id >> 32; // PID is higher part
110 u32 tid = id; // Cast and get the lower part
takumakumef8990372019-01-02 17:12:14 +0900111 u32 uid = bpf_get_current_uid_gid();
Brendan Greggbedd1502015-09-17 21:52:52 -0700112
Tim Douglasd3583a82018-12-30 13:18:54 -0500113 PID_TID_FILTER
takumakumef8990372019-01-02 17:12:14 +0900114 UID_FILTER
Tim Douglasd3583a82018-12-30 13:18:54 -0500115 FLAGS_FILTER
mcaleavya3c446c72016-04-29 13:38:51 +0100116 if (bpf_get_current_comm(&val.comm, sizeof(val.comm)) == 0) {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300117 val.id = id;
mcaleavya3c446c72016-04-29 13:38:51 +0100118 val.fname = filename;
Tim Douglasd3583a82018-12-30 13:18:54 -0500119 val.flags = flags; // EXTENDED_STRUCT_MEMBER
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300120 infotmp.update(&id, &val);
mcaleavya3c446c72016-04-29 13:38:51 +0100121 }
Brendan Greggbedd1502015-09-17 21:52:52 -0700122
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800123 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700124};
125
mcaleavya3c446c72016-04-29 13:38:51 +0100126int trace_return(struct pt_regs *ctx)
Brendan Greggbedd1502015-09-17 21:52:52 -0700127{
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300128 u64 id = bpf_get_current_pid_tgid();
mcaleavya3c446c72016-04-29 13:38:51 +0100129 struct val_t *valp;
130 struct data_t data = {};
Brendan Greggbedd1502015-09-17 21:52:52 -0700131
mcaleavya3c446c72016-04-29 13:38:51 +0100132 u64 tsp = bpf_ktime_get_ns();
133
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300134 valp = infotmp.lookup(&id);
mcaleavya3c446c72016-04-29 13:38:51 +0100135 if (valp == 0) {
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800136 // missed entry
137 return 0;
138 }
mcaleavya3c446c72016-04-29 13:38:51 +0100139 bpf_probe_read(&data.comm, sizeof(data.comm), valp->comm);
140 bpf_probe_read(&data.fname, sizeof(data.fname), (void *)valp->fname);
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300141 data.id = valp->id;
mcaleavya3c446c72016-04-29 13:38:51 +0100142 data.ts = tsp / 1000;
takumakumef8990372019-01-02 17:12:14 +0900143 data.uid = bpf_get_current_uid_gid();
Tim Douglasd3583a82018-12-30 13:18:54 -0500144 data.flags = valp->flags; // EXTENDED_STRUCT_MEMBER
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530145 data.ret = PT_REGS_RC(ctx);
Brendan Greggbedd1502015-09-17 21:52:52 -0700146
mcaleavya3c446c72016-04-29 13:38:51 +0100147 events.perf_submit(ctx, &data, sizeof(data));
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300148 infotmp.delete(&id);
Brendan Greggbedd1502015-09-17 21:52:52 -0700149
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800150 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700151}
152"""
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300153if args.tid: # TID trumps PID
Tim Douglasd3583a82018-12-30 13:18:54 -0500154 bpf_text = bpf_text.replace('PID_TID_FILTER',
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300155 'if (tid != %s) { return 0; }' % args.tid)
156elif args.pid:
Tim Douglasd3583a82018-12-30 13:18:54 -0500157 bpf_text = bpf_text.replace('PID_TID_FILTER',
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800158 'if (pid != %s) { return 0; }' % args.pid)
Brendan Greggbedd1502015-09-17 21:52:52 -0700159else:
Tim Douglasd3583a82018-12-30 13:18:54 -0500160 bpf_text = bpf_text.replace('PID_TID_FILTER', '')
takumakumef8990372019-01-02 17:12:14 +0900161if args.uid:
162 bpf_text = bpf_text.replace('UID_FILTER',
163 'if (uid != %s) { return 0; }' % args.uid)
164else:
165 bpf_text = bpf_text.replace('UID_FILTER', '')
Tim Douglasd3583a82018-12-30 13:18:54 -0500166if args.flag_filter:
167 bpf_text = bpf_text.replace('FLAGS_FILTER',
168 'if (!(flags & %d)) { return 0; }' % flag_filter_mask)
169else:
170 bpf_text = bpf_text.replace('FLAGS_FILTER', '')
171if not (args.extended_fields or args.flag_filter):
172 bpf_text = '\n'.join(x for x in bpf_text.split('\n')
173 if 'EXTENDED_STRUCT_MEMBER' not in x)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100174if debug or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800175 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100176 if args.ebpf:
177 exit()
Brendan Greggbedd1502015-09-17 21:52:52 -0700178
179# initialize BPF
180b = BPF(text=bpf_text)
Joel Fernandes9af548f2018-01-07 11:59:09 -0800181b.attach_kprobe(event="do_sys_open", fn_name="trace_entry")
182b.attach_kretprobe(event="do_sys_open", fn_name="trace_return")
mcaleavya3c446c72016-04-29 13:38:51 +0100183
184TASK_COMM_LEN = 16 # linux/sched.h
185NAME_MAX = 255 # linux/limits.h
186
187class Data(ct.Structure):
188 _fields_ = [
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300189 ("id", ct.c_ulonglong),
mcaleavya3c446c72016-04-29 13:38:51 +0100190 ("ts", ct.c_ulonglong),
takumakumef8990372019-01-02 17:12:14 +0900191 ("uid", ct.c_uint32),
mcaleavya3c446c72016-04-29 13:38:51 +0100192 ("ret", ct.c_int),
193 ("comm", ct.c_char * TASK_COMM_LEN),
Tim Douglasd3583a82018-12-30 13:18:54 -0500194 ("fname", ct.c_char * NAME_MAX),
195 ("flags", ct.c_int),
mcaleavya3c446c72016-04-29 13:38:51 +0100196 ]
197
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200198initial_ts = 0
Brendan Greggbedd1502015-09-17 21:52:52 -0700199
200# header
201if args.timestamp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800202 print("%-14s" % ("TIME(s)"), end="")
takumakumef8990372019-01-02 17:12:14 +0900203if args.print_uid:
204 print("%-6s" % ("UID"), end="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500205print("%-6s %-16s %4s %3s " %
206 ("TID" if args.tid else "PID", "COMM", "FD", "ERR"), end="")
207if args.extended_fields:
208 print("%-9s" % ("FLAGS"), end="")
209print("PATH")
Brendan Greggbedd1502015-09-17 21:52:52 -0700210
mcaleavya3c446c72016-04-29 13:38:51 +0100211# process event
212def print_event(cpu, data, size):
213 event = ct.cast(data, ct.POINTER(Data)).contents
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200214 global initial_ts
Brendan Greggbedd1502015-09-17 21:52:52 -0700215
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800216 # split return value into FD and errno columns
mcaleavya3c446c72016-04-29 13:38:51 +0100217 if event.ret >= 0:
218 fd_s = event.ret
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800219 err = 0
220 else:
mcaleavya3c446c72016-04-29 13:38:51 +0100221 fd_s = -1
222 err = - event.ret
Brendan Greggbedd1502015-09-17 21:52:52 -0700223
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200224 if not initial_ts:
225 initial_ts = event.ts
mcaleavya3c446c72016-04-29 13:38:51 +0100226
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200227 if args.failed and (event.ret >= 0):
mcaleavya3c446c72016-04-29 13:38:51 +0100228 return
229
Gary Lin40fd6692018-02-12 16:51:14 +0800230 if args.name and bytes(args.name) not in event.comm:
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +0200231 return
232
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800233 if args.timestamp:
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200234 delta = event.ts - initial_ts
235 print("%-14.9f" % (float(delta) / 1000000), end="")
mcaleavya3c446c72016-04-29 13:38:51 +0100236
takumakumef8990372019-01-02 17:12:14 +0900237 if args.print_uid:
238 print("%-6d" % event.uid, end="")
239
Tim Douglasd3583a82018-12-30 13:18:54 -0500240 print("%-6d %-16s %4d %3d " %
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300241 (event.id & 0xffffffff if args.tid else event.id >> 32,
Tim Douglasd3583a82018-12-30 13:18:54 -0500242 event.comm.decode('utf-8', 'replace'), fd_s, err), end="")
243
244 if args.extended_fields:
245 print("%08o " % event.flags, end="")
246
247 print(event.fname.decode('utf-8', 'replace'))
mcaleavya3c446c72016-04-29 13:38:51 +0100248
249# loop with callback to print_event
Mark Drayton5f5687e2017-02-20 18:13:03 +0000250b["events"].open_perf_buffer(print_event, page_cnt=64)
Paul Chaignon702de382018-01-28 13:41:35 +0100251start_time = datetime.now()
252while not args.duration or datetime.now() - start_time < args.duration:
Jerome Marchand51671272018-12-19 01:57:24 +0100253 try:
254 b.perf_buffer_poll()
255 except KeyboardInterrupt:
256 exit()