Commit df11f321 authored by Vicent Marti's avatar Vicent Marti

Add a few examples written in Lua

parent 39468d9b
#include <uapi/linux/ptrace.h>
struct str_t {
u64 pid;
char str[80];
};
BPF_PERF_OUTPUT(events);
int printret(struct pt_regs *ctx)
{
struct str_t data = {};
u32 pid;
if (!ctx->ax)
return 0;
pid = bpf_get_current_pid_tgid();
data.pid = pid;
bpf_probe_read(&data.str, sizeof(data.str), (void *)ctx->ax);
events.perf_submit(ctx,&data,sizeof(data));
return 0;
};
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require("ffi")
return function(BPF)
local b = BPF:new{src_file="bashreadline.c", debug=true}
b:attach_uprobe{name="/bin/bash", sym="readline", fn_name="printret", retprobe=true}
local function print_readline(cpu, event)
print("%-9s %-6d %s" % {os.date("%H:%M:%S"), tonumber(event.pid), ffi.string(event.str)})
end
b:get_table("events"):open_perf_buffer(print_readline, "struct { uint64_t pid; char str[80]; }")
print("%-9s %-6s %s" % {"TIME", "PID", "COMMAND"})
b:kprobe_poll_loop()
end
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local bpf_source = [[
#include <uapi/linux/ptrace.h>
struct alloc_info_t {
u64 size;
u64 timestamp_ns;
int stack_id;
};
BPF_HASH(sizes, u64);
BPF_HASH(allocs, u64, struct alloc_info_t);
BPF_STACK_TRACE(stack_traces, 10240)
int alloc_enter(struct pt_regs *ctx, size_t size)
{
SIZE_FILTER
if (SAMPLE_EVERY_N > 1) {
u64 ts = bpf_ktime_get_ns();
if (ts % SAMPLE_EVERY_N != 0)
return 0;
}
u64 pid = bpf_get_current_pid_tgid();
u64 size64 = size;
sizes.update(&pid, &size64);
if (SHOULD_PRINT)
bpf_trace_printk("alloc entered, size = %u\n", size);
return 0;
}
int alloc_exit(struct pt_regs *ctx)
{
u64 address = ctx->ax;
u64 pid = bpf_get_current_pid_tgid();
u64* size64 = sizes.lookup(&pid);
struct alloc_info_t info = {0};
if (size64 == 0)
return 0; // missed alloc entry
info.size = *size64;
sizes.delete(&pid);
info.timestamp_ns = bpf_ktime_get_ns();
info.stack_id = stack_traces.get_stackid(ctx, STACK_FLAGS);
allocs.update(&address, &info);
if (SHOULD_PRINT) {
bpf_trace_printk("alloc exited, size = %lu, result = %lx\n",
info.size, address);
}
return 0;
}
int free_enter(struct pt_regs *ctx, void *address)
{
u64 addr = (u64)address;
struct alloc_info_t *info = allocs.lookup(&addr);
if (info == 0)
return 0;
allocs.delete(&addr);
if (SHOULD_PRINT) {
bpf_trace_printk("free entered, address = %lx, size = %lu\n",
address, info->size);
}
return 0;
}
]]
return function(BPF, utils)
local parser = utils.argparse("memleak", "Catch memory leaks")
parser:flag("-t --trace")
parser:flag("-a --show-allocs")
parser:option("-p --pid"):convert(tonumber)
parser:option("-i --interval", "", 5):convert(tonumber)
parser:option("-o --older", "", 500):convert(tonumber)
parser:option("-s --sample-rate", "", 1):convert(tonumber)
parser:option("-z --min-size", ""):convert(tonumber)
parser:option("-Z --max-size", ""):convert(tonumber)
parser:option("-T --top", "", 10):convert(tonumber)
local args = parser:parse()
local size_filter = ""
if args.min_size and args.max_size then
size_filter = "if (size < %d || size > %d) return 0;" % {args.min_size, args.max_size}
elseif args.min_size then
size_filter = "if (size < %d) return 0;" % args.min_size
elseif args.max_size then
size_filter = "if (size > %d) return 0;" % args.max_size
end
local stack_flags = "BPF_F_REUSE_STACKID"
if args.pid then
stack_flags = stack_flags .. "|BPF_F_USER_STACK"
end
local text = bpf_source
text = text:gsub("SIZE_FILTER", size_filter)
text = text:gsub("STACK_FLAGS", stack_flags)
text = text:gsub("SHOULD_PRINT", args.trace and "1" or "0")
text = text:gsub("SAMPLE_EVERY_N", tostring(args.sample_rate))
local bpf = BPF:new{text=text, debug=true}
local syms = nil
local min_age_ns = args.older * 1e6
if args.pid then
print("Attaching to malloc and free in pid %d, Ctrl+C to quit." % args.pid)
bpf:attach_uprobe{name="c", sym="malloc", fn_name="alloc_enter", pid=args.pid}
bpf:attach_uprobe{name="c", sym="malloc", fn_name="alloc_exit", pid=args.pid, retprobe=true}
bpf:attach_uprobe{name="c", sym="free", fn_name="free_enter", pid=args.pid}
else
print("Attaching to kmalloc and kfree, Ctrl+C to quit.")
bpf:attach_kprobe{event="__kmalloc", fn_name="alloc_enter"}
bpf:attach_kprobe{event="__kmalloc", fn_name="alloc_exit", retprobe=true} -- TODO
bpf:attach_kprobe{event="kfree", fn_name="free_enter"}
end
local syms = args.pid and utils.sym.ProcSymbols:new(args.pid) or utils.sym.KSymbols:new()
local allocs = bpf:get_table("allocs")
local stack_traces = bpf:get_table("stack_traces")
local function resolve(addr)
local sym = syms:lookup(addr)
if args.pid == nil then
sym = sym .. " [kernel]"
end
return string.format("%s (%x)", sym, addr)
end
local function print_outstanding()
local alloc_info = {}
local now = utils.posix.time_ns()
print("[%s] Top %d stacks with outstanding allocations:" %
{os.date("%H:%M:%S"), args.top})
for address, info in allocs:items() do
if now - min_age_ns >= tonumber(info.timestamp_ns) then
local stack_id = tonumber(info.stack_id)
if stack_id >= 0 then
if alloc_info[stack_id] then
local s = alloc_info[stack_id]
s.count = s.count + 1
s.size = s.size + tonumber(info.size)
else
local stack = stack_traces:get(stack_id, resolve)
alloc_info[stack_id] = { stack=stack, count=1, size=tonumber(info.size) }
end
end
if args.show_allocs then
print("\taddr = %x size = %s" % {tonumber(address), tonumber(info.size)})
end
end
end
local top = table.values(alloc_info)
table.sort(top, function(a, b) return a.size > b.size end)
for n, alloc in ipairs(top) do
print("\t%d bytes in %d allocations from stack\n\t\t%s" %
{alloc.size, alloc.count, table.concat(alloc.stack, "\n\t\t")})
if n == args.top then break end
end
end
if args.trace then
local pipe = bpf:pipe()
while true do
print(pipe:trace_fields())
end
else
while true do
utils.posix.sleep(args.interval)
syms:refresh()
print_outstanding()
end
end
end
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local program = [[
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
#define MINBLOCK_US 1
struct key_t {
char name[TASK_COMM_LEN];
int stack_id;
};
BPF_HASH(counts, struct key_t);
BPF_HASH(start, u32);
BPF_STACK_TRACE(stack_traces, 10240)
int oncpu(struct pt_regs *ctx, struct task_struct *prev) {
u32 pid;
u64 ts, *tsp;
// record previous thread sleep time
if (FILTER) {
pid = prev->pid;
ts = bpf_ktime_get_ns();
start.update(&pid, &ts);
}
// calculate current thread's delta time
pid = bpf_get_current_pid_tgid();
tsp = start.lookup(&pid);
if (tsp == 0)
return 0; // missed start or filtered
u64 delta = bpf_ktime_get_ns() - *tsp;
start.delete(&pid);
delta = delta / 1000;
if (delta < MINBLOCK_US)
return 0;
// create map key
u64 zero = 0, *val;
struct key_t key = {};
int stack_flags = BPF_F_REUSE_STACKID;
/*
if (!(prev->flags & PF_KTHREAD))
stack_flags |= BPF_F_USER_STACK;
*/
bpf_get_current_comm(&key.name, sizeof(key.name));
key.stack_id = stack_traces.get_stackid(ctx, stack_flags);
val = counts.lookup_or_init(&key, &zero);
(*val) += delta;
return 0;
}
]]
return function(BPF, utils)
local ffi = require("ffi")
local parser = utils.argparse("offcputime", "Summarize off-cpu time")
parser:flag("-u --user-only")
parser:option("-p --pid"):convert(tonumber)
parser:flag("-f --folded")
parser:option("-d --duration", "duration to trace for", 9999999):convert(tonumber)
local args = parser:parse()
local ksym = utils.sym.KSymbols:new()
local filter = "1"
local MAXDEPTH = 20
if args.pid then
filter = "pid == %d" % args.pid
elseif args.user_only then
filter = "!(prev->flags & PF_KTHREAD)"
end
local text = program:gsub("FILTER", filter)
local b = BPF:new{text=text}
b:attach_kprobe{event="finish_task_switch", fn_name="oncpu"}
if BPF.num_open_kprobes() == 0 then
print("no functions matched. quitting...")
return
end
print("Sleeping for %d seconds..." % args.duration)
pcall(utils.posix.sleep, args.duration)
print("Tracing...")
local counts = b:get_table("counts")
local stack_traces = b:get_table("stack_traces")
for k, v in counts:items() do
for addr in stack_traces:walk(tonumber(k.stack_id)) do
print(" %-16x %s" % {addr, ksym:lookup(addr)})
end
print(" %-16s %s" % {"-", ffi.string(k.name)})
print(" %d\n" % tonumber(v))
end
end
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
assert(arg[1], "usage: strlen_count PID")
local program = string.gsub([[
#include <uapi/linux/ptrace.h>
int printarg(struct pt_regs *ctx) {
if (!ctx->di)
return 0;
u32 pid = bpf_get_current_pid_tgid();
if (pid != PID)
return 0;
char str[128] = {};
bpf_probe_read(&str, sizeof(str), (void *)ctx->di);
bpf_trace_printk("strlen(\"%s\")\n", &str);
return 0;
};
]], "PID", arg[1])
return function(BPF)
local b = BPF:new{text=program, debug=true}
b:attach_uprobe{name="c", sym="strlen", fn_name="printarg"}
local pipe = b:pipe()
while true do
local task, pid, cpu, flags, ts, msg = pipe:trace_fields()
print("%-18.9f %-16s %-6d %s" % {ts, task, pid, msg})
end
end
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local program = [[
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
struct key_t {
u32 prev_pid;
u32 curr_pid;
};
// map_type, key_type, leaf_type, table_name, num_entry
BPF_TABLE("hash", struct key_t, u64, stats, 1024);
int count_sched(struct pt_regs *ctx, struct task_struct *prev) {
struct key_t key = {};
u64 zero = 0, *val;
key.curr_pid = bpf_get_current_pid_tgid();
key.prev_pid = prev->pid;
val = stats.lookup_or_init(&key, &zero);
(*val)++;
return 0;
}
]]
return function(BPF)
local b = BPF:new{text=program, debug=true}
b:attach_kprobe{event="finish_task_switch", fn_name="count_sched"}
print("Press any key...")
io.read()
local t = b:get_table("stats")
for k, v in t:items() do
print("task_switch[%d -> %d] = %d" % {k.prev_pid, k.curr_pid, tonumber(v)})
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment