Repository navigation
Expand file tree
/
Copy pathbpftrace.cpp
More file actions
2016 lines (1788 loc) · 55.7 KB
/
Copy pathbpftrace.cpp
File metadata and controls
2016 lines (1788 loc) · 55.7 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 <arpa/inet.h>
#include <cassert>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/personality.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#ifdef HAVE_BCC_ELF_FOREACH_SYM
#include <linux/elf.h>
#include "bcc_elf.h"
#endif
#include "bcc_syms.h"
#include "perf_reader.h"
#include "bpforc.h"
#include "bpftrace.h"
#include "attached_probe.h"
#include "printf.h"
#include "triggers.h"
#include "resolve_cgroupid.h"
#include "utils.h"
extern char** environ;
namespace bpftrace {
DebugLevel bt_debug = DebugLevel::kNone;
bool bt_verbose = false;
volatile sig_atomic_t BPFtrace::exitsig_recv = false;
constexpr char CHILD_EXIT_QUIETLY = '\0';
constexpr char CHILD_GO = 'g';
int format(char * s, size_t n, const char * fmt, std::vector<std::unique_ptr<IPrintable>> &args) {
int ret = -1;
switch(args.size()) {
case 0:
ret = snprintf(s, n, "%s", fmt);
break;
case 1:
ret = snprintf(s, n, fmt, args.at(0)->value());
break;
case 2:
ret = snprintf(s, n, fmt, args.at(0)->value(), args.at(1)->value());
break;
case 3:
ret = snprintf(s, n, fmt, args.at(0)->value(), args.at(1)->value(), args.at(2)->value());
break;
case 4:
ret = snprintf(s, n, fmt, args.at(0)->value(), args.at(1)->value(), args.at(2)->value(), args.at(3)->value());
break;
case 5:
ret = snprintf(s, n, fmt, args.at(0)->value(), args.at(1)->value(), args.at(2)->value(),
args.at(3)->value(), args.at(4)->value());
break;
case 6:
ret = snprintf(s, n, fmt, args.at(0)->value(), args.at(1)->value(), args.at(2)->value(),
args.at(3)->value(), args.at(4)->value(), args.at(5)->value());
break;
default:
std::cerr << "format() can only take up to 7 arguments (" << args.size() << ") provided" << std::endl;
abort();
}
if (ret < 0 && errno != 0) {
std::cerr << "format() error occurred: " << std::strerror(errno) << std::endl;
abort();
}
return ret;
}
BPFtrace::~BPFtrace()
{
kill_child();
if (child_pid() != 0)
{
// We don't care if waitpid returns any errors. We're just trying
// to make a best effort here. It's not like we could recover from
// an error.
int status;
waitpid(child_pid(), &status, 0);
}
for (const auto& pair : exe_sym_)
{
if (pair.second.second)
bcc_free_symcache(pair.second.second, pair.second.first);
}
if (ksyms_)
bcc_free_symcache(ksyms_, -1);
}
int BPFtrace::add_probe(ast::Probe &p)
{
for (auto attach_point : *p.attach_points)
{
if (attach_point->provider == "BEGIN" || attach_point->provider == "END")
{
Probe probe;
probe.path = "/proc/self/exe";
probe.attach_point = attach_point->provider + "_trigger";
probe.type = probetype(attach_point->provider);
probe.log_size = log_size_;
probe.orig_name = p.name();
probe.name = p.name();
probe.loc = 0;
probe.pid = getpid();
probe.index = attach_point->index(probe.name) > 0 ?
attach_point->index(probe.name) : p.index();
special_probes_.push_back(probe);
continue;
}
std::vector<std::string> attach_funcs;
bool underspecified_usdt_probe = (probetype(attach_point->provider) == ProbeType::usdt && attach_point->ns.empty());
if (attach_point->need_expansion && (has_wildcard(attach_point->func) || underspecified_usdt_probe))
{
std::set<std::string> matches;
try
{
matches = find_wildcard_matches(*attach_point);
}
catch (const WildcardException &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
attach_funcs.insert(attach_funcs.end(), matches.begin(), matches.end());
}
else
{
if (probetype(attach_point->provider) == ProbeType::usdt && !attach_point->ns.empty())
attach_funcs.push_back(attach_point->ns + ":" + attach_point->func);
else
attach_funcs.push_back(attach_point->func);
}
for (auto func_ : attach_funcs)
{
std::string full_func_id = func_;
std::string func_id = func_;
// USDT probes must specify both a provider and a function name for full id
// So we will extract out the provider namespace to get just the function name
if (probetype(attach_point->provider) == ProbeType::usdt )
{
std::string ns = func_id.substr(0, func_id.find(":"));
func_id.erase(0, func_id.find(":")+1);
// Set attach_point ns to be a resolved namespace in case of wildcard
attach_point->ns = ns;
// Set the function name to be a resolved function id in case of wildcard
attach_point->func = func_id;
}
Probe probe;
probe.path = attach_point->target;
probe.attach_point = func_id;
probe.type = probetype(attach_point->provider);
probe.log_size = log_size_;
probe.orig_name = p.name();
probe.ns = attach_point->ns;
probe.name = attach_point->name(func_id);
probe.freq = attach_point->freq;
probe.address = attach_point->address;
probe.func_offset = attach_point->func_offset;
probe.loc = 0;
probe.index = attach_point->index(full_func_id) > 0 ?
attach_point->index(full_func_id) : p.index();
probe.addr = attach_point->addr;
probe.len = attach_point->len;
probe.mode = attach_point->mode;
probes_.push_back(probe);
}
}
return 0;
}
std::set<std::string> BPFtrace::find_wildcard_matches(
const ast::AttachPoint &attach_point) const
{
std::unique_ptr<std::istream> symbol_stream;
std::string prefix, func;
switch (probetype(attach_point.provider))
{
case ProbeType::kprobe:
case ProbeType::kretprobe:
{
symbol_stream = get_symbols_from_file(
"/sys/kernel/debug/tracing/available_filter_functions");
prefix = "";
func = attach_point.func;
break;
}
case ProbeType::uprobe:
case ProbeType::uretprobe:
{
symbol_stream = std::make_unique<std::istringstream>(
extract_func_symbols_from_path(attach_point.target));
prefix = "";
func = attach_point.func;
break;
}
case ProbeType::tracepoint:
{
symbol_stream = get_symbols_from_file(
"/sys/kernel/debug/tracing/available_events");
prefix = attach_point.target;
func = attach_point.func;
break;
}
case ProbeType::usdt:
{
symbol_stream = get_symbols_from_usdt(pid_, attach_point.target);
prefix = "";
if (attach_point.ns == "")
func = "*:" + attach_point.func;
else
func = attach_point.ns + ":" + attach_point.func;
break;
}
default:
{
throw WildcardException("Wildcard matches aren't available on probe type '"
+ attach_point.provider + "'");
}
}
return find_wildcard_matches(prefix, func, *symbol_stream);
}
/*
* Finds all matches of func in the provided input stream.
*
* If an optional prefix is provided, lines must start with it to count as a
* match, but the prefix is stripped from entries in the result set.
* Wildcard tokens ("*") are accepted in func.
*/
std::set<std::string> BPFtrace::find_wildcard_matches(
const std::string &prefix,
const std::string &func,
std::istream &symbol_stream) const
{
if (!has_wildcard(func))
return std::set<std::string>({func});
bool start_wildcard = func[0] == '*';
bool end_wildcard = func[func.length() - 1] == '*';
std::vector<std::string> tokens = split_string(func, '*');
tokens.erase(std::remove(tokens.begin(), tokens.end(), ""), tokens.end());
std::string line;
std::set<std::string> matches;
std::string full_prefix = prefix.empty() ? "" : (prefix + ":");
while (std::getline(symbol_stream, line))
{
if (!full_prefix.empty()) {
if (line.find(full_prefix, 0) != 0)
continue;
line = line.substr(full_prefix.length());
}
if (!wildcard_match(line, tokens, start_wildcard, end_wildcard))
continue;
// skip the ".part.N" kprobe variants, as they can't be traced:
if (line.find(".part.") != std::string::npos)
continue;
matches.insert(line);
}
return matches;
}
std::unique_ptr<std::istream> BPFtrace::get_symbols_from_file(const std::string &path) const
{
auto file = std::make_unique<std::ifstream>(path);
if (file->fail())
{
throw std::runtime_error("Could not read symbols from " + path +
": " + strerror(errno));
}
return file;
}
std::unique_ptr<std::istream> BPFtrace::get_symbols_from_usdt(
int pid,
const std::string &target) const
{
std::string probes;
usdt_probe_list usdt_probes;
if (pid > 0)
usdt_probes = USDTHelper::probes_for_pid(pid);
else
usdt_probes = USDTHelper::probes_for_path(target);
for (auto const& usdt_probe : usdt_probes)
{
std::string path = std::get<USDT_PATH_INDEX>(usdt_probe);
std::string provider = std::get<USDT_PROVIDER_INDEX>(usdt_probe);
std::string fname = std::get<USDT_FNAME_INDEX>(usdt_probe);
probes += provider + ":" + fname + "\n";
}
return std::make_unique<std::istringstream>(probes);
}
int BPFtrace::num_probes() const
{
return special_probes_.size() + probes_.size();
}
void BPFtrace::kill_child()
{
if (child_pid() == 0)
return;
if (child_running_) {
kill(child_pid(), SIGTERM);
} else {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
// We need to disable this warning for some GCC/libc combinations despite
// using the void cast: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425
(void)write(child_start_pipe_, &CHILD_EXIT_QUIETLY, 1);
#pragma GCC diagnostic pop
close(child_start_pipe_);
}
}
void BPFtrace::request_finalize()
{
finalize_ = true;
attached_probes_.clear();
kill_child();
}
void perf_event_printer(void *cb_cookie, void *data, int size __attribute__((unused)))
{
auto bpftrace = static_cast<BPFtrace*>(cb_cookie);
auto printf_id = *static_cast<uint64_t*>(data);
auto arg_data = static_cast<uint8_t*>(data);
int err;
// Ignore the remaining events if perf_event_printer is called during finalization
// stage (exit() builtin has been called)
if (bpftrace->finalize_)
return;
if (bpftrace->exitsig_recv)
{
bpftrace->request_finalize();
return;
}
// async actions
if (printf_id == asyncactionint(AsyncAction::exit))
{
bpftrace->request_finalize();
return;
}
else if (printf_id == asyncactionint(AsyncAction::print))
{
std::string arg = (const char *)(static_cast<uint8_t*>(data) + sizeof(uint64_t) + 2 * sizeof(uint64_t));
uint64_t top = (uint64_t) * (static_cast<uint64_t *>(data) + 1);
uint64_t div = (uint64_t) * (static_cast<uint64_t *>(data) + 2);
err = bpftrace->print_map_ident(arg, top, div);
if (err)
throw std::runtime_error("Could not print map with ident \"" + arg + "\", err=" + std::to_string(err));
return;
}
else if (printf_id == asyncactionint(AsyncAction::clear))
{
std::string arg = (const char *)(arg_data+sizeof(uint64_t));
err = bpftrace->clear_map_ident(arg);
if (err)
throw std::runtime_error("Could not clear map with ident \"" + arg + "\", err=" + std::to_string(err));
return;
}
else if (printf_id == asyncactionint(AsyncAction::zero))
{
std::string arg = (const char *)(arg_data+sizeof(uint64_t));
err = bpftrace->zero_map_ident(arg);
if (err)
throw std::runtime_error("Could not zero map with ident \"" + arg + "\", err=" + std::to_string(err));
return;
}
else if (printf_id == asyncactionint(AsyncAction::time))
{
char timestr[STRING_SIZE];
time_t t;
struct tm *tmp;
t = time(NULL);
tmp = localtime(&t);
if (tmp == NULL) {
std::cerr << "localtime: " << strerror(errno) << std::endl;
return;
}
uint64_t time_id = (uint64_t) * (static_cast<uint64_t *>(data) + 1);
auto fmt = bpftrace->time_args_[time_id].c_str();
if (strftime(timestr, sizeof(timestr), fmt, tmp) == 0) {
std::cerr << "strftime returned 0" << std::endl;
return;
}
bpftrace->out_->message(MessageType::time, timestr, false);
return;
}
else if (printf_id == asyncactionint(AsyncAction::join))
{
uint64_t join_id = (uint64_t) * (static_cast<uint64_t *>(data) + 1);
auto delim = bpftrace->join_args_[join_id].c_str();
std::stringstream joined;
for (unsigned int i = 0; i < bpftrace->join_argnum_; i++) {
auto *arg = arg_data + 2*sizeof(uint64_t) + i * bpftrace->join_argsize_;
if (arg[0] == 0)
break;
if (i)
joined << delim;
joined << arg;
}
bpftrace->out_->message(MessageType::join, joined.str());
return;
}
else if ( printf_id >= asyncactionint(AsyncAction::syscall) &&
printf_id < asyncactionint(AsyncAction::syscall) + RESERVED_IDS_PER_ASYNCACTION)
{
if (bpftrace->safe_mode_)
{
std::cerr << "syscall() not allowed in safe mode" << std::endl;
abort();
}
auto id = printf_id - asyncactionint(AsyncAction::syscall);
auto fmt = std::get<0>(bpftrace->system_args_[id]).c_str();
auto args = std::get<1>(bpftrace->system_args_[id]);
auto arg_values = bpftrace->get_arg_values(args, arg_data);
const int BUFSIZE = 512;
char buffer[BUFSIZE];
int size = format(buffer, BUFSIZE, fmt, arg_values);
// Return value is required size EXCLUDING null byte
if (size >= BUFSIZE) {
std::cerr << "syscall() command to long (" << size << " bytes): ";
std::cerr << buffer << std::endl;
return;
}
bpftrace->out_->message(MessageType::syscall, exec_system(buffer), false);
return;
}
else if ( printf_id >= asyncactionint(AsyncAction::cat))
{
auto id = printf_id - asyncactionint(AsyncAction::cat);
auto fmt = std::get<0>(bpftrace->cat_args_[id]).c_str();
auto args = std::get<1>(bpftrace->cat_args_[id]);
auto arg_values = bpftrace->get_arg_values(args, arg_data);
const int BUFSIZE = 512;
char buffer[BUFSIZE];
int size = format(buffer, BUFSIZE, fmt, arg_values);
// Return value is required size EXCLUDING null byte
if (size >= BUFSIZE) {
std::cerr << "cat() command to long (" << size << " bytes): ";
std::cerr << buffer << std::endl;
return;
}
std::stringstream buf;
cat_file(buffer, bpftrace->cat_bytes_max_, buf);
bpftrace->out_->message(MessageType::cat, buf.str(), false);
return;
}
// printf
auto fmt = std::get<0>(bpftrace->printf_args_[printf_id]).c_str();
auto args = std::get<1>(bpftrace->printf_args_[printf_id]);
auto arg_values = bpftrace->get_arg_values(args, arg_data);
// First try with a stack buffer, if that fails use a heap buffer
const int BUFSIZE=512;
char buffer[BUFSIZE];
int required_size = format(buffer, BUFSIZE, fmt, arg_values);
// Return value is required size EXCLUDING null byte
if (required_size < BUFSIZE) {
bpftrace->out_->message(MessageType::printf, std::string(buffer), false);
} else {
auto buf = std::make_unique<char[]>(required_size+1);
// if for some reason the size is still wrong the string
// will just be silently truncated
format(buf.get(), required_size, fmt, arg_values);
bpftrace->out_->message(MessageType::printf, std::string(buf.get()), false);
}
}
std::vector<std::unique_ptr<IPrintable>> BPFtrace::get_arg_values(const std::vector<Field> &args, uint8_t* arg_data)
{
std::vector<std::unique_ptr<IPrintable>> arg_values;
for (auto arg : args)
{
switch (arg.type.type)
{
case Type::integer:
switch (arg.type.size)
{
case 8:
arg_values.push_back(
std::make_unique<PrintableInt>(
*reinterpret_cast<uint64_t*>(arg_data+arg.offset)));
break;
case 4:
arg_values.push_back(
std::make_unique<PrintableInt>(
*reinterpret_cast<uint32_t*>(arg_data+arg.offset)));
break;
case 2:
arg_values.push_back(
std::make_unique<PrintableInt>(
*reinterpret_cast<uint16_t*>(arg_data+arg.offset)));
break;
case 1:
arg_values.push_back(
std::make_unique<PrintableInt>(
*reinterpret_cast<uint8_t*>(arg_data+arg.offset)));
break;
default:
std::cerr << "get_arg_values: invalid integer size. 8, 4, 2 and byte supported. " << arg.type.size << "provided" << std::endl;
abort();
}
break;
case Type::string:
{
auto p = reinterpret_cast<char *>(arg_data + arg.offset);
arg_values.push_back(std::make_unique<PrintableString>(
std::string(p, strnlen(p, arg.type.size))));
break;
}
case Type::ksym:
arg_values.push_back(
std::make_unique<PrintableString>(
resolve_ksym(*reinterpret_cast<uint64_t*>(arg_data+arg.offset))));
break;
case Type::usym:
arg_values.push_back(
std::make_unique<PrintableString>(
resolve_usym(
*reinterpret_cast<uint64_t*>(arg_data+arg.offset),
*reinterpret_cast<uint64_t*>(arg_data+arg.offset + 8))));
break;
case Type::inet:
arg_values.push_back(
std::make_unique<PrintableString>(
resolve_inet(
*reinterpret_cast<int64_t*>(arg_data+arg.offset),
reinterpret_cast<uint8_t*>(arg_data+arg.offset + 8))));
break;
case Type::username:
arg_values.push_back(
std::make_unique<PrintableString>(
resolve_uid(
*reinterpret_cast<uint64_t*>(arg_data+arg.offset))));
break;
case Type::probe:
arg_values.push_back(
std::make_unique<PrintableString>(
resolve_probe(
*reinterpret_cast<uint64_t*>(arg_data+arg.offset))));
break;
case Type::kstack:
arg_values.push_back(
std::make_unique<PrintableString>(
get_stack(
*reinterpret_cast<uint64_t*>(arg_data+arg.offset),
false,
arg.type.stack_type, 8)));
break;
case Type::ustack:
arg_values.push_back(
std::make_unique<PrintableString>(
get_stack(
*reinterpret_cast<uint64_t*>(arg_data+arg.offset),
true,
arg.type.stack_type, 8)));
break;
case Type::cast:
if (arg.type.is_pointer) {
arg_values.push_back(
std::make_unique<PrintableInt>(
*reinterpret_cast<uint64_t*>(arg_data+arg.offset)));
break;
}
// fall through
default:
std::cerr << "invalid argument type" << std::endl;
abort();
}
}
return arg_values;
}
void BPFtrace::add_param(const std::string ¶m)
{
params_.emplace_back(param);
}
std::string BPFtrace::get_param(size_t i, bool is_str) const
{
if (params_.size() < i) {
return is_str ? "" : "0";
}
return params_.at(i-1);
}
size_t BPFtrace::num_params() const
{
return params_.size();
}
void perf_event_lost(void *cb_cookie, uint64_t lost)
{
auto bpftrace = static_cast<BPFtrace*>(cb_cookie);
bpftrace->out_->lost_events(lost);
}
std::unique_ptr<AttachedProbe> BPFtrace::attach_probe(Probe &probe, const BpfOrc &bpforc)
{
// use the single-probe program if it exists (as is the case with wildcards
// and the name builtin, which must be expanded into separate programs per
// probe), else try to find a the program based on the original probe name
// that includes wildcards.
std::string index_str = "_" + std::to_string(probe.index);
auto func = bpforc.sections_.find("s_" + probe.name + index_str);
if (func == bpforc.sections_.end())
func = bpforc.sections_.find("s_" + probe.orig_name + index_str);
if (func == bpforc.sections_.end())
{
if (probe.name != probe.orig_name)
std::cerr << "Code not generated for probe: " << probe.name << " from: " << probe.orig_name << std::endl;
else
std::cerr << "Code not generated for probe: " << probe.name << std::endl;
return nullptr;
}
try
{
if (probe.type == ProbeType::usdt || probe.type == ProbeType::watchpoint)
return std::make_unique<AttachedProbe>(probe, func->second, pid_);
else
return std::make_unique<AttachedProbe>(probe, func->second, safe_mode_);
}
catch (std::runtime_error &e)
{
std::cerr << e.what() << std::endl;
}
return nullptr;
}
bool attach_reverse(const Probe &p)
{
switch(p.type)
{
case ProbeType::kprobe:
case ProbeType::uprobe:
case ProbeType::uretprobe:
case ProbeType::usdt:
case ProbeType::software:
return true;
case ProbeType::kretprobe:
case ProbeType::tracepoint:
case ProbeType::profile:
case ProbeType::interval:
case ProbeType::watchpoint:
case ProbeType::hardware:
return false;
default:
abort();
}
}
int BPFtrace::run(std::unique_ptr<BpfOrc> bpforc)
{
auto r_special_probes = special_probes_.rbegin();
for (; r_special_probes != special_probes_.rend(); ++r_special_probes)
{
auto attached_probe = attach_probe(*r_special_probes, *bpforc.get());
if (attached_probe == nullptr)
return -1;
special_attached_probes_.push_back(std::move(attached_probe));
}
int epollfd = setup_perf_events();
if (epollfd < 0)
return epollfd;
if (elapsed_map_)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
auto nsec = 1000000000ULL * ts.tv_sec + ts.tv_nsec;
uint64_t key = 0;
if (bpf_update_elem(elapsed_map_->mapfd_, &key, &nsec, 0) < 0)
{
perror("Failed to write start time to elapsed map");
return -1;
}
}
BEGIN_trigger();
// The kernel appears to fire some probes in the order that they were
// attached and others in reverse order. In order to make sure that blocks
// are executed in the same order they were declared, iterate over the probes
// twice: in the first pass iterate forward and attach the probes that will
// be fired in the same order they were attached, and in the second pass
// iterate in reverse and attach the rest.
for (auto probes = probes_.begin(); probes != probes_.end(); ++probes)
{
if (!attach_reverse(*probes)) {
auto attached_probe = attach_probe(*probes, *bpforc.get());
if (attached_probe == nullptr)
{
kill_child();
return -1;
}
attached_probes_.push_back(std::move(attached_probe));
}
}
for (auto r_probes = probes_.rbegin(); r_probes != probes_.rend(); ++r_probes)
{
if (attach_reverse(*r_probes)) {
auto attached_probe = attach_probe(*r_probes, *bpforc.get());
if (attached_probe == nullptr)
{
kill_child();
return -1;
}
attached_probes_.push_back(std::move(attached_probe));
}
}
// Kick the child to execute the command.
if (has_child_cmd())
{
int ret = write(child_start_pipe_, &CHILD_GO, 1);
if (ret < 0)
{
perror("unable to write to 'go' pipe");
return ret;
}
child_running_ = true;
close(child_start_pipe_);
}
if (bt_verbose)
std::cerr << "Running..." << std::endl;
poll_perf_events(epollfd);
attached_probes_.clear();
// finalize_ and exitsig_recv should be false from now on otherwise
// perf_event_printer() can ignore the END_trigger() events.
finalize_ = false;
exitsig_recv = false;
END_trigger();
poll_perf_events(epollfd, true);
special_attached_probes_.clear();
return 0;
}
int BPFtrace::setup_perf_events()
{
int epollfd = epoll_create1(EPOLL_CLOEXEC);
if (epollfd == -1)
{
std::cerr << "Failed to create epollfd" << std::endl;
return -1;
}
std::vector<int> cpus = get_online_cpus();
online_cpus_ = cpus.size();
for (int cpu : cpus)
{
int page_cnt = 64;
void *reader = bpf_open_perf_buffer(&perf_event_printer, &perf_event_lost, this, -1, cpu, page_cnt);
if (reader == nullptr)
{
std::cerr << "Failed to open perf buffer" << std::endl;
return -1;
}
struct epoll_event ev = {};
ev.events = EPOLLIN;
ev.data.ptr = reader;
int reader_fd = perf_reader_fd((perf_reader*)reader);
bpf_update_elem(perf_event_map_->mapfd_, &cpu, &reader_fd, 0);
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reader_fd, &ev) == -1)
{
std::cerr << "Failed to add perf reader to epoll" << std::endl;
return -1;
}
}
return epollfd;
}
void BPFtrace::poll_perf_events(int epollfd, bool drain)
{
auto events = std::vector<struct epoll_event>(online_cpus_);
while (true)
{
int ready = epoll_wait(epollfd, events.data(), online_cpus_, 100);
if (ready < 0 && errno == EINTR && !BPFtrace::exitsig_recv) {
// We received an interrupt not caused by SIGINT, skip and run again
continue;
}
// Return if either
// * epoll_wait has encountered an error (eg signal delivery)
// * There's no events left and we've been instructed to drain or
// finalization has been requested through exit() builtin.
if (ready < 0 || (ready == 0 && (drain || finalize_)))
{
return;
}
for (int i=0; i<ready; i++)
{
perf_reader_event_read((perf_reader*)events[i].data.ptr);
}
// If we are tracing a specific pid and it has exited, we should exit
// as well b/c otherwise we'd be tracing nothing.
//
// Note that there technically is a race with a new process using the
// same pid, but we're polling at 100ms and it would be unlikely that
// the pids wrap around that fast.
if (pid_ > 0 && !is_pid_alive(pid_))
{
return;
}
}
return;
}
int BPFtrace::print_maps()
{
for(auto &mapmap : maps_)
{
IMap &map = *mapmap.second.get();
int err;
if (map.type_.type == Type::hist || map.type_.type == Type::lhist)
err = print_map_hist(map, 0, 0);
else if (map.type_.type == Type::avg || map.type_.type == Type::stats)
err = print_map_stats(map);
else
err = print_map(map, 0, 0);
if (err)
return err;
}
return 0;
}
// print a map given an ident string
int BPFtrace::print_map_ident(const std::string &ident, uint32_t top, uint32_t div)
{
int err = 0;
for(auto &mapmap : maps_)
{
IMap &map = *mapmap.second.get();
if (map.name_ == ident) {
if (map.type_.type == Type::hist || map.type_.type == Type::lhist)
err = print_map_hist(map, top, div);
else if (map.type_.type == Type::avg || map.type_.type == Type::stats)
err = print_map_stats(map);
else
err = print_map(map, top, div);
return err;
}
}
return -2;
}
// clear a map (delete all keys) given an ident string
int BPFtrace::clear_map_ident(const std::string &ident)
{
int err = 0;
for(auto &mapmap : maps_)
{
IMap &map = *mapmap.second.get();
if (map.name_ == ident) {
err = clear_map(map);
return err;
}
}
return -2;
}
// zero a map (set all keys to zero) given an ident string
int BPFtrace::zero_map_ident(const std::string &ident)
{
int err = 0;
for(auto &mapmap : maps_)
{
IMap &map = *mapmap.second.get();
if (map.name_ == ident) {
err = zero_map(map);
return err;
}
}
return -2;
}
// clear a map
int BPFtrace::clear_map(IMap &map)
{
std::vector<uint8_t> old_key;
try
{
if (map.type_.type == Type::hist || map.type_.type == Type::lhist ||
map.type_.type == Type::stats || map.type_.type == Type::avg)
// hist maps have 8 extra bytes for the bucket number
old_key = find_empty_key(map, map.key_.size() + 8);
else
old_key = find_empty_key(map, map.key_.size());
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);
// snapshot keys, then operate on them
std::vector<std::vector<uint8_t>> keys;
while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0)
{
keys.push_back(key);
old_key = key;
}
for (auto &key : keys)
{
int err = bpf_delete_elem(map.mapfd_, key.data());
if (err)
{
std::cerr << "Error looking up elem: " << err << std::endl;
return -1;
}
}
return 0;
}
// zero a map
int BPFtrace::zero_map(IMap &map)
{
uint32_t nvalues = map.is_per_cpu_type() ? ncpus_ : 1;
std::vector<uint8_t> old_key;
try
{
if (map.type_.type == Type::hist || map.type_.type == Type::lhist ||
map.type_.type == Type::stats || map.type_.type == Type::avg)
// hist maps have 8 extra bytes for the bucket number
old_key = find_empty_key(map, map.key_.size() + 8);
else
old_key = find_empty_key(map, map.key_.size());
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);