forked from bpftrace/bpftrace
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
1219 lines (1127 loc) · 39.4 KB
/
Copy pathmain.cpp
File metadata and controls
1219 lines (1127 loc) · 39.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <bpf/libbpf.h>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <limits>
#include <memory>
#include <optional>
#include <sys/resource.h>
#include <sys/utsname.h>
#include <unistd.h>
#include "aot/aot.h"
#include "ast/diagnostic.h"
#include "ast/helpers.h"
#include "ast/pass_manager.h"
#include "ast/passes/attachpoint_passes.h"
#include "ast/passes/clang_build.h"
#include "ast/passes/clang_parser.h"
#include "ast/passes/codegen_llvm.h"
#include "ast/passes/control_flow_analyser.h"
#include "ast/passes/macro_expansion.h"
#include "ast/passes/map_sugar.h"
#include "ast/passes/named_param.h"
#include "ast/passes/parse_passes.h"
#include "ast/passes/pid_filter_pass.h"
#include "ast/passes/portability_analyser.h"
#include "ast/passes/printer.h"
#include "ast/passes/recursion_check.h"
#include "ast/passes/resource_analyser.h"
#include "ast/passes/types/pre_type_check.h"
#include "ast/passes/types/type_resolver.h"
#include "ast/passes/types/type_system.h"
#include "benchmark.h"
#include "bpffeature.h"
#include "bpftrace.h"
#include "btf.h"
#include "build_info.h"
#include "config.h"
#include "globalvars.h"
#include "lockdown.h"
#include "log.h"
#include "output/buffer_mode.h"
#include "probe_matcher.h"
#include "run_bpftrace.h"
#include "symbols/kernel.h"
#include "symbols/user.h"
#include "util/env.h"
#include "util/int_parser.h"
#include "util/proc.h"
#include "util/strings.h"
#include "util/temp.h"
#include "version.h"
using namespace bpftrace;
namespace {
enum class Mode {
NONE = 0,
CODEGEN,
COMPILER_BENCHMARK,
BPF_BENCHMARK,
BPF_TEST,
FORMAT,
};
enum class BuildMode {
// Compile script and run immediately
DYNAMIC = 0,
// Compile script into portable executable
AHEAD_OF_TIME,
};
enum Options {
AOT = 2000,
BENCH, // Alias for --mode=bench.
BTF,
CMD,
DEBUG,
DEBUGINFO,
DRY_RUN,
DWARF_PID,
EMIT_ELF,
EMIT_LLVM,
FMT, // Alias for --mode=format.
HELP,
INCLUDE,
INFO,
LIST,
NO_FEATURE,
NO_WARNING,
MODE,
OUTPUT,
PID,
PROBE_FILTER,
QUIET,
TEST, // Alias for --mode=test.
TRACEABLE_FUNCTIONS,
UNSAFE,
USDT_SEMAPHORE,
VERBOSE,
VERIFY_LLVM_IR,
VERSION,
WARNINGS,
};
constexpr auto FULL_SEARCH = "*:*";
constexpr auto DEFAULT_DEBUG_INFO_PATHS = ":.debug:/usr/lib/debug";
} // namespace
void usage(std::ostream& out)
{
// clang-format off
out << "bpftrace - a high-level tracing language for Linux powered by BPF" << std::endl;
out << std::endl;
out << "USAGE:" << std::endl;
out << " bpftrace [options] filename" << std::endl;
out << " bpftrace [options] - <stdin input>" << std::endl;
out << " bpftrace [options] -e 'program'" << std::endl;
out << " use -- after filename/-e 'program' for named script parameters" << std::endl;
out << std::endl;
out << "OPTIONS:" << std::endl;
out << " -e 'program' execute this program" << std::endl;
out << " -l, --list [search|filename]" << std::endl;
out << " list kernel probes or probes in a program" << std::endl;
out << " -v, --verbose enable verbose messages; with -l, also show probe arguments" << std::endl;
out << " -h, --help show this help message" << std::endl;
out << " -V, --version bpftrace version" << std::endl;
out << " --info print information about kernel BPF support" << std::endl;
out << std::endl;
out << " -p, --pid PID filter actions and enable USDT probes on PID" << std::endl;
out << " -c, --cmd CMD run CMD and enable USDT probes on resulting process" << std::endl;
#ifdef HAVE_DW_UNWIND
out << " --dwarf-pid PID" << std::endl;
out << " add additional pids to the DWARF-unwinder" << std::endl;
#endif
out << " --usdt-file-activation" << std::endl;
out << " activate usdt semaphores based on file path" << std::endl;
out << std::endl;
out << " -o, --output FILE" << std::endl;
out << " redirect bpftrace output to FILE" << std::endl;
out << " -f FORMAT output format ('text', 'json')" << std::endl;
out << " -B MODE output buffering mode ('line', 'full', 'none')" << std::endl;
out << " -q, --quiet keep messages quiet" << std::endl;
out << " -k, --warnings emit a warning when probe read helpers return an error" << std::endl;
out << " --no-warnings disable all warning messages" << std::endl;
out << std::endl;
out << " -I DIR add the directory to the include search path" << std::endl;
out << " --include FILE add an #include file before preprocessing" << std::endl;
out << " --debuginfo DIR[:DIR]" << std::endl;
out << " add directories to the debug info search path" << std::endl;
out << " --traceable-functions FILE" << std::endl;
out << " load the list of traceable kernel functions from FILE" << std::endl;
out << std::endl;
out << " --unsafe allow unsafe/destructive functionality" << std::endl;
out << " --no-feature FEATURE[,FEATURE]" << std::endl;
out << " disable use of detected features" << std::endl;
out << std::endl;
out << "DEVELOPER OPTIONS:" << std::endl;
out << " --mode MODE used for benchmarking and testing" << std::endl;
out << " ('codegen', 'compiler-bench', 'bench', 'test', 'format')" << std::endl;
out << " --test run all test: probes (same as --mode test)" << std::endl;
out << " --bench run all bench: probes (same as --mode bench)" << std::endl;
out << " --probe-filter REGEX" << std::endl;
out << " only run probes whose name matches REGEX" << std::endl;
out << " --fmt format the input script and print it" << std::endl;
out << std::endl;
out << "TROUBLESHOOTING OPTIONS:" << std::endl;
out << " --dry-run terminate execution right after attaching all the probes" << std::endl;
out << " --verify-llvm-ir" << std::endl;
out << " check that the generated LLVM IR is valid" << std::endl;
out << " -d, --debug STAGE" << std::endl;
out << " debug info for various stages of bpftrace execution" << std::endl;
out << " ('all', 'ast', 'types', 'codegen', 'codegen-opt', 'libbpf', 'verifier')" << std::endl;
out << " ('parse', 'dis') - available on debug builds" << std::endl;
out << " --emit-elf FILE" << std::endl;
out << " (dry run) generate ELF file with bpf programs and write to FILE" << std::endl;
out << " --emit-llvm FILE" << std::endl;
out << " write LLVM IR to FILE.original.ll and FILE.optimized.ll" << std::endl;
out << std::endl;
out << "CONFIGURATION:" << std::endl;
out << " bpftrace also supports environment variables and config options" << std::endl;
out << " for tuning behavior. See 'man bpftrace' or the online documentation" << std::endl;
out << " for the full list." << std::endl;
out << std::endl;
out << "EXAMPLES:" << std::endl;
out << R"( bpftrace -e 'kprobe:do_nanosleep { printf("PID %d sleeping...\n", pid); }')" << std::endl;
out << " trace processes calling sleep" << std::endl;
out << " bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'" << std::endl;
out << " count syscalls by process name" << std::endl;
out << R"( bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%s %s\n", comm, str(args.filename)); }')" << std::endl;
out << " trace file opens with process name and path" << std::endl;
out << " bpftrace -e 'profile:hz:99 { @[kstack] = count(); }'" << std::endl;
out << " profile kernel stacks at 99 Hertz" << std::endl;
out << " bpftrace -e 'tracepoint:block:block_rq_issue { @ = hist(args.bytes); }'" << std::endl;
out << " histogram of block I/O request sizes" << std::endl;
out << R"( bpftrace -p 1337 -e 'uprobe:/usr/lib/libc.so.6:malloc { @[ustack] = count(); }')" << std::endl;
out << " count malloc calls by user stack for a specific process" << std::endl;
out << " bpftrace -l '*sleep*'" << std::endl;
out << " list probes containing \"sleep\"" << std::endl;
out << " bpftrace -lv 'kprobe:do_nanosleep'" << std::endl;
out << " show the arguments for the do_nanosleep kprobe" << std::endl;
out << std::endl;
out << "DOCUMENTATION:" << std::endl;
out << " https://bpftrace.org" << std::endl;
out << " https://github.com/bpftrace/bpftrace" << std::endl;
// clang-format on
}
static void enforce_infinite_rlimit_memlock()
{
struct rlimit rl = {};
int err;
rl.rlim_max = RLIM_INFINITY;
rl.rlim_cur = rl.rlim_max;
err = setrlimit(RLIMIT_MEMLOCK, &rl);
if (err)
LOG(WARNING) << std::strerror(err) << ": couldn't set RLIMIT_MEMLOCK for "
<< "bpftrace. If your program is not loading, you can try "
<< "\"ulimit -l 8192\" to fix the problem";
}
static void info(BPFnofeature no_feature)
{
struct utsname utsname;
uname(&utsname);
auto btf = bpftrace::BTF();
std::cout << "System" << std::endl
<< " OS: " << utsname.sysname << " " << utsname.release << " "
<< utsname.version << std::endl
<< " Arch: " << utsname.machine << std::endl;
std::cout << std::endl;
std::cout << BuildInfo::report();
std::cout << std::endl;
std::cout << BPFfeature(no_feature, btf).report();
}
static std::optional<struct timespec> get_delta_with_boottime(int clock_type)
{
std::optional<struct timespec> ret = std::nullopt;
long lowest_delta = std::numeric_limits<long>::max();
// Run the "triple vdso sandwich" 5 times, taking the result from the
// iteration with the lowest delta between first and last clock_gettime()
// calls.
for (int i = 0; i < 5; ++i) {
struct timespec before, after, boottime;
long delta;
if (::clock_gettime(clock_type, &before))
continue;
if (::clock_gettime(CLOCK_BOOTTIME, &boottime))
continue;
if (::clock_gettime(clock_type, &after))
continue;
// There's no way 3 VDSO calls should take more than 1s. We'll
// also ignore the case where we cross a 1s boundary b/c that
// can only happen once and we're running this loop 5 times.
// This helps keep the math simple.
if (before.tv_sec != after.tv_sec)
continue;
delta = after.tv_nsec - before.tv_nsec;
// Time went backwards
if (delta < 0)
continue;
// Lowest delta seen so far, compute boot realtime and store it
if (delta < lowest_delta) {
struct timespec delta_with_boottime;
long nsec_avg = (before.tv_nsec + after.tv_nsec) / 2;
if (nsec_avg - boottime.tv_nsec < 0) {
delta_with_boottime.tv_sec = after.tv_sec - boottime.tv_sec - 1;
delta_with_boottime.tv_nsec = nsec_avg - boottime.tv_nsec + 1e9;
} else {
delta_with_boottime.tv_sec = after.tv_sec - boottime.tv_sec;
delta_with_boottime.tv_nsec = nsec_avg - boottime.tv_nsec;
}
lowest_delta = delta;
ret = delta_with_boottime;
}
}
if (ret && lowest_delta >= 1e5)
LOG(WARNING) << (lowest_delta / 1e3)
<< "us skew detected when calculating boot time. strftime() "
"builtin may be inaccurate";
return ret;
}
static std::optional<struct timespec> get_boottime()
{
return get_delta_with_boottime(CLOCK_REALTIME);
}
static std::optional<struct timespec> get_delta_taitime()
{
return get_delta_with_boottime(CLOCK_TAI);
}
std::vector<std::string> extra_flags(
BPFtrace& bpftrace,
const std::vector<std::string>& include_dirs,
const std::vector<std::string>& include_files)
{
std::string ksrc, kobj;
struct utsname utsname;
std::vector<std::string> extra_flags;
uname(&utsname);
bool found_kernel_headers = symbols::get_kernel_dirs(utsname, ksrc, kobj);
if (found_kernel_headers)
extra_flags = get_kernel_cflags(
utsname.machine, ksrc, kobj, bpftrace.kconfig);
for (auto dir : include_dirs) {
extra_flags.emplace_back("-I");
extra_flags.push_back(dir);
}
for (auto file : include_files) {
extra_flags.emplace_back("-include");
extra_flags.push_back(file);
}
return extra_flags;
}
struct Args {
std::string pid_str;
std::vector<std::string> dwarf_pids_str;
std::string cmd_str;
bool listing = false;
bool safe_mode = true;
bool usdt_file_activation = false;
int warning_level = 1;
bool verify_llvm_ir = false;
Mode mode = Mode::NONE;
std::string script;
std::string search;
std::string filename;
std::string debuginfo_path;
std::string output_file;
std::string output_format;
std::string output_elf;
std::string output_llvm;
std::string aot;
BPFnofeature no_feature;
OutputBufferConfig obc = OutputBufferConfig::UNSET;
BuildMode build_mode = BuildMode::DYNAMIC;
std::vector<std::string> include_dirs;
std::vector<std::string> include_files;
std::vector<std::string> params;
std::vector<std::string> debug_stages;
std::vector<std::string> named_params;
std::string probe_filter;
std::string traceable_functions_file;
};
void CreateDynamicPasses(std::function<void(ast::Pass&& pass)> add)
{
add(ast::CreateClangBuildPass());
add(ast::CreateTypeSystemPass());
add(ast::CreatePreTypeCheckPass());
add(ast::CreateTypeResolverPass());
add(ast::CreateResourcePass());
}
void CreateAotPasses(std::function<void(ast::Pass&& pass)> add)
{
add(ast::CreatePortabilityPass());
add(ast::CreateClangBuildPass());
add(ast::CreateTypeSystemPass());
add(ast::CreatePreTypeCheckPass());
add(ast::CreateTypeResolverPass());
add(ast::CreateResourcePass());
}
ast::Pass printPass(const std::string& name)
{
return ast::Pass::create("print-" + name, [=](ast::ASTContext& ast) {
std::cerr << "AST after: " << name << std::endl;
std::cerr << "-------------------" << std::endl;
ast::Printer printer(ast, std::cerr);
printer.visit(ast.root);
std::cerr << std::endl;
});
};
static bool parse_debug_stages(const std::string& arg)
{
auto stages = util::split_string(arg, ',', /* remove_empty= */ true);
for (const auto& stage : stages) {
if (debug_stages.contains(stage)) {
bt_debug.insert(debug_stages.at(stage));
} else if (stage == "all") {
for (const auto& [_, s] : debug_stages)
bt_debug.insert(s);
} else {
LOG(ERROR) << "USAGE: invalid option for -d: " << stage;
return false;
}
}
return true;
}
Args parse_args(int argc, char* argv[])
{
Args args;
const char* const short_options = "d:bB:f:e:hlp:vqc:Vo:I:k";
option long_options[] = {
option{ .name = "aot",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::AOT },
option{ .name = "bench",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::BENCH },
option{ .name = "btf",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::BTF },
option{ .name = "cmd",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::CMD },
option{ .name = "debug",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::DEBUG },
option{ .name = "debuginfo",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::DEBUGINFO },
option{ .name = "dry-run",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::DRY_RUN },
option{ .name = "emit-elf",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::EMIT_ELF },
option{ .name = "emit-llvm",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::EMIT_LLVM },
option{ .name = "fmt",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::FMT },
option{ .name = "help",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::HELP },
option{ .name = "include",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::INCLUDE },
option{ .name = "info",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::INFO },
option{ .name = "list",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::LIST },
option{ .name = "no-feature",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::NO_FEATURE },
option{ .name = "no-warnings",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::NO_WARNING },
option{ .name = "output",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::OUTPUT },
option{ .name = "pid",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::PID },
option{ .name = "probe-filter",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::PROBE_FILTER },
option{ .name = "quiet",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::QUIET },
option{ .name = "test",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::TEST },
option{ .name = "mode",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::MODE },
option{ .name = "unsafe",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::UNSAFE },
option{ .name = "dwarf-pid",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::DWARF_PID },
option{ .name = "usdt-file-activation",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::USDT_SEMAPHORE },
option{ .name = "verbose",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::VERBOSE },
option{ .name = "verify-llvm-ir",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::VERIFY_LLVM_IR },
option{ .name = "version",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::VERSION },
option{ .name = "warnings",
.has_arg = no_argument,
.flag = nullptr,
.val = Options::WARNINGS },
option{ .name = "traceable-functions",
.has_arg = required_argument,
.flag = nullptr,
.val = Options::TRACEABLE_FUNCTIONS },
option{ .name = nullptr, .has_arg = 0, .flag = nullptr, .val = 0 }, // Must
// be
// last
};
int c;
while ((c = getopt_long(argc, argv, short_options, long_options, nullptr)) !=
-1) {
switch (c) {
case Options::INFO: // --info
check_privileges();
info(args.no_feature);
exit(0);
break;
case Options::EMIT_ELF: // --emit-elf
args.output_elf = optarg;
break;
case Options::EMIT_LLVM:
args.output_llvm = optarg;
break;
case Options::NO_WARNING: // --no-warnings
if (args.warning_level == 2) {
LOG(ERROR) << "USAGE: -k, --warnings conflicts with --no-warnings";
exit(1);
}
DISABLE_LOG(WARNING);
args.warning_level = 0;
break;
case Options::MODE: // --mode
if (std::strcmp(optarg, "codegen") == 0) {
args.mode = Mode::CODEGEN;
} else if (std::strcmp(optarg, "compiler-bench") == 0) {
args.mode = Mode::COMPILER_BENCHMARK;
} else if (std::strcmp(optarg, "bench") == 0) {
args.mode = Mode::BPF_BENCHMARK;
} else if (std::strcmp(optarg, "test") == 0) {
args.mode = Mode::BPF_TEST;
} else if (std::strcmp(optarg, "format") == 0) {
args.mode = Mode::FORMAT;
} else {
LOG(ERROR) << "USAGE: --mode can only be 'codegen', "
"'compiler-bench', 'bench', 'test' or 'format'.";
exit(1);
}
break;
case Options::TEST: // --test
if (args.mode != Mode::NONE) {
LOG(ERROR) << "USAGE: --test conflicts with existing --mode";
exit(1);
}
args.mode = Mode::BPF_TEST;
break;
case Options::BENCH: // --bench
if (args.mode != Mode::NONE) {
LOG(ERROR) << "USAGE: --bench conflicts with existing --mode";
exit(1);
}
args.mode = Mode::BPF_BENCHMARK;
break;
case Options::FMT: // --fmt
if (args.mode != Mode::NONE) {
LOG(ERROR) << "USAGE: --fmt conflicts with existing --mode";
exit(1);
}
args.mode = Mode::FORMAT;
break;
case Options::AOT: // --aot
args.aot = optarg;
args.build_mode = BuildMode::AHEAD_OF_TIME;
break;
case Options::NO_FEATURE: // --no-feature
if (args.no_feature.parse(optarg)) {
LOG(ERROR) << "USAGE: --no-feature can only have values "
"'kprobe_multi,kprobe_session,uprobe_multi'.";
exit(1);
}
break;
case Options::DRY_RUN:
dry_run = true;
break;
case Options::VERIFY_LLVM_IR:
args.verify_llvm_ir = true;
break;
case 'o':
case Options::OUTPUT:
args.output_file = optarg;
break;
case 'd':
case Options::DEBUG:
if (!parse_debug_stages(optarg))
exit(1);
break;
case 'q':
case Options::QUIET:
bt_quiet = true;
break;
case 'v':
case Options::VERBOSE:
ENABLE_LOG(V1);
bt_verbose = true;
break;
case 'B':
if (std::strcmp(optarg, "line") == 0) {
args.obc = OutputBufferConfig::LINE;
} else if (std::strcmp(optarg, "full") == 0) {
args.obc = OutputBufferConfig::FULL;
} else if (std::strcmp(optarg, "none") == 0) {
args.obc = OutputBufferConfig::NONE;
} else {
LOG(ERROR) << "USAGE: -B must be either 'line', 'full', or 'none'.";
exit(1);
}
break;
case 'f':
args.output_format = optarg;
break;
case 'e':
args.script = optarg;
break;
case 'p':
case Options::PID:
args.pid_str = optarg;
break;
case Options::PROBE_FILTER:
args.probe_filter = optarg;
break;
#ifdef HAVE_DW_UNWIND
case Options::DWARF_PID:
args.dwarf_pids_str.emplace_back(optarg);
break;
#endif
case 'I':
args.include_dirs.emplace_back(optarg);
break;
case Options::INCLUDE:
args.include_files.emplace_back(optarg);
break;
case 'l':
case Options::LIST:
args.listing = true;
break;
case 'c':
case Options::CMD:
args.cmd_str = optarg;
break;
case Options::USDT_SEMAPHORE:
args.usdt_file_activation = true;
break;
case Options::UNSAFE:
args.safe_mode = false;
break;
case 'b':
case Options::BTF:
break;
case Options::DEBUGINFO:
args.debuginfo_path += optarg;
args.debuginfo_path += ":";
break;
case 'h':
case Options::HELP:
usage(std::cout);
exit(0);
case 'V':
case Options::VERSION:
std::cout << "bpftrace " << BPFTRACE_VERSION << std::endl;
exit(0);
case 'k':
case Options::WARNINGS:
if (args.warning_level == 2) {
LOG(ERROR) << "USAGE: -kk has been deprecated. Use a single -k for "
"runtime warnings for errors in map "
"lookups and probe reads.";
exit(1);
}
if (args.warning_level == 0) {
LOG(ERROR) << "USAGE: -k, --warnings conflicts with --no-warnings";
exit(1);
}
args.warning_level = 2;
break;
case Options::TRACEABLE_FUNCTIONS:
args.traceable_functions_file = optarg;
break;
default:
usage(std::cerr);
exit(1);
}
}
if (argc == 1) {
usage(std::cerr);
exit(1);
}
if (!args.cmd_str.empty() && !args.pid_str.empty()) {
LOG(ERROR) << "USAGE: Cannot use both -c and -p.";
usage(std::cerr);
exit(1);
}
// Difficult to serialize flex generated types
if (args.warning_level == 2 && args.build_mode == BuildMode::AHEAD_OF_TIME) {
LOG(ERROR) << "Cannot use -k with --aot";
exit(1);
}
if (args.listing) {
// Expect zero or one positional arguments
if (optind == argc) {
args.search = FULL_SEARCH;
} else if (optind == argc - 1) {
std::string val(argv[optind]);
if (std::filesystem::exists(val)) {
args.filename = val;
} else {
if (val == "*") {
args.search = FULL_SEARCH;
} else {
args.search = val;
}
}
optind++;
} else {
usage(std::cerr);
exit(1);
}
} else {
// Expect to find a script either through -e or filename
if (args.script.empty() && argv[optind] == nullptr) {
LOG(ERROR) << "USAGE: filename or -e 'program' required.";
exit(1);
}
// If no script was specified with -e, then we expect to find a script file
if (args.script.empty()) {
args.filename = argv[optind];
optind++;
}
// Parse positional and named parameters.
while (optind < argc) {
auto pos_arg = std::string(argv[optind]);
if (pos_arg.starts_with("--")) {
args.named_params.emplace_back(pos_arg.substr(2));
} else {
args.params.emplace_back(argv[optind]);
}
optind++;
}
}
return args;
}
bool is_colorize()
{
const char* color_env = std::getenv("BPFTRACE_COLOR");
if (!color_env) {
return isatty(STDOUT_FILENO) && isatty(STDERR_FILENO);
}
std::string_view mode(color_env);
if (mode == "always") {
return true;
} else if (mode == "never") {
return false;
} else {
if (mode != "auto") {
LOG(WARNING) << "Invalid env value! The valid values of `BPFTRACE_COLOR` "
"are [auto|always|never]. The current value is "
<< mode << "!";
}
return isatty(STDOUT_FILENO) && isatty(STDERR_FILENO);
}
}
void list_probes(BPFtrace& bpftrace,
const std::string& search,
const symbols::KernelInfo& kernel_func_info,
const symbols::UserInfoImpl& user_func_info)
{
if (search.find(".") != std::string::npos &&
search.find_first_of(":*") == std::string::npos) {
LOG(WARNING) << "It appears that \'" << search
<< "\' is a filename but the file does not exist. Treating \'"
<< search << "\' as a search pattern.";
}
for (auto& rawprobe : util::split_string(search, ',')) {
std::string probe = util::normalize_whitespace(rawprobe);
bool is_search_a_type = is_type_name(probe);
// Ensure that BTF is loaded for all listing.
auto parts = util::split_string(probe, ':');
if (is_search_a_type || parts.empty() || parts.size() < 3) {
bpftrace.btf_->load_module_btfs(kernel_func_info.get_modules());
} else {
bpftrace.btf_->load_module_btfs(kernel_func_info.get_modules(parts[1]));
}
// Use ProbeMatcher directly to list probes matching the search pattern.
ProbeMatcher probe_matcher(&bpftrace, kernel_func_info, user_func_info);
if (is_search_a_type) {
for (const auto& s : probe_matcher.get_structs_for_listing(probe)) {
std::cout << s << std::endl;
}
} else {
// For patterns without a colon (like "*do_nanosleep*"), treat as
// wildcard probe type with the pattern as function match.
std::string value = probe;
if (value.empty()) {
value = "*:*";
} else if (value.find(':') == std::string::npos) {
value = "*:" + value;
}
for (const auto& probe :
probe_matcher.get_probes_for_listing(value, bpftrace.pid())) {
std::cout << probe << std::endl;
}
}
}
}
uint64_t parse_pid(std::string const& pid_str)
{
auto maybe_pid = util::to_uint(pid_str);
if (!maybe_pid) {
LOG(ERROR) << "Failed to parse pid: " << maybe_pid.takeError();
exit(1);
}
if (*maybe_pid > 0x400000) {
// The actual maximum pid depends on the configuration for the specific
// system, i.e. read from `/proc/sys/kernel/pid_max`. We can impose a
// basic sanity check here against the nominal maximum for 64-bit
// systems.
LOG(ERROR) << "Pid out of range: " << *maybe_pid;
exit(1);
}
return *maybe_pid;
}
int main(int argc, char* argv[])
{
Log::get().set_colorize(is_colorize());
Args args = parse_args(argc, argv);
switch (args.obc) {
case OutputBufferConfig::UNSET:
case OutputBufferConfig::LINE:
std::setvbuf(stdout, nullptr, _IOLBF, BUFSIZ);
break;
case OutputBufferConfig::FULL:
std::setvbuf(stdout, nullptr, _IOFBF, BUFSIZ);
break;
case OutputBufferConfig::NONE:
std::setvbuf(stdout, nullptr, _IONBF, BUFSIZ);
break;
}
libbpf_set_print(libbpf_print);
auto config = std::make_unique<Config>(!args.cmd_str.empty());
BPFtrace bpftrace(args.no_feature, std::move(config));
check_privileges();
// Create function info objects for probe matching and pass state.
auto kernel_func_info = symbols::KernelInfoImpl::open(
args.traceable_functions_file);
if (!kernel_func_info) {
LOG(ERROR) << "Failed to open kernel function info: "
<< kernel_func_info.takeError();
return 1;
}
symbols::UserInfoImpl user_func_info;
ast::FunctionInfo func_info_state(*kernel_func_info, user_func_info);
bpftrace.usdt_file_activation_ = args.usdt_file_activation;
bpftrace.safe_mode_ = args.safe_mode;
bpftrace.warning_level_ = args.warning_level;
bpftrace.boottime_ = get_boottime();
bpftrace.delta_taitime_ = get_delta_taitime();
bpftrace.run_tests_ = args.mode == Mode::BPF_TEST;
bpftrace.run_benchmarks_ = args.mode == Mode::BPF_BENCHMARK;
bpftrace.probe_filter_ = args.probe_filter;
bpftrace.debuginfo_path_ = args.debuginfo_path + DEFAULT_DEBUG_INFO_PATHS;
if (!args.pid_str.empty()) {
auto pid = parse_pid(args.pid_str);
auto proc = util::create_proc(pid);
if (!proc) {
LOG(ERROR) << "Failed to attach to pid: " << proc.takeError();
exit(1);
}
bpftrace.procmon_ = std::move(*proc);
}
for (auto const& pid_str : args.dwarf_pids_str) {
auto pid = parse_pid(pid_str);
bpftrace.dwarf_pids_.emplace_back(pid);
}
if (!args.cmd_str.empty()) {
bpftrace.cmd_ = args.cmd_str;
auto child = util::create_child(args.cmd_str);
if (!child) {
LOG(ERROR) << "Failed to fork child: " << child.takeError();
exit(1);
}
bpftrace.child_ = std::move(*child);
}
// This is our primary program AST context. Initially it is empty, i.e.
// there is no filename set or source file. The way we set it up depends on
// the mode of execution below, and we expect that it will be reinitialized.
ast::ASTContext ast;
// Listing probes when there is no program.
if (args.listing && args.script.empty() && args.filename.empty()) {
list_probes(bpftrace, args.search, *kernel_func_info, user_func_info);
return 0;
}
if (!args.filename.empty()) {
std::stringstream buf;
if (args.filename == "-") {
std::string line;
while (std::getline(std::cin, line)) {
// Note we may add an extra newline if the input doesn't end in a new
// line. This should not matter because bpftrace (the language) is not
// whitespace sensitive.
buf << line << std::endl;
}
ast = ast::ASTContext("stdin", buf.str());
} else {
std::ifstream file(args.filename);
if (file.fail()) {
LOG(ERROR) << "failed to open file '" << args.filename
<< "': " << std::strerror(errno);
exit(1);
}
buf << file.rdbuf();
ast = ast::ASTContext(args.filename, buf.str());
}
} else {
// Script is provided as a command line argument.
ast = ast::ASTContext("stdin", args.script);