-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
b_frontend_action.cc
1745 lines (1608 loc) · 66.7 KB
/
b_frontend_action.cc
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
/*
* Copyright (c) 2015 PLUMgrid, 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.
*/
#include <linux/bpf.h>
#include <linux/version.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <stdlib.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecordLayout.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/MultiplexConsumer.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Lex/Lexer.h>
#include "frontend_action_common.h"
#include "b_frontend_action.h"
#include "bpf_module.h"
#include "common.h"
#include "loader.h"
#include "table_storage.h"
#include "arch_helper.h"
#include "bcc_libbpf_inc.h"
#include "libbpf.h"
#include "bcc_syms.h"
namespace ebpf {
constexpr int MAX_CALLING_CONV_REGS = 6;
const char *calling_conv_regs_x86[] = {
"di", "si", "dx", "cx", "r8", "r9"
};
const char *calling_conv_syscall_regs_x86[] = {
"di", "si", "dx", "r10", "r8", "r9"
};
const char *calling_conv_regs_ppc[] = {"gpr[3]", "gpr[4]", "gpr[5]",
"gpr[6]", "gpr[7]", "gpr[8]"};
const char *calling_conv_regs_s390x[] = {"gprs[2]", "gprs[3]", "gprs[4]",
"gprs[5]", "gprs[6]" };
const char *calling_conv_regs_arm64[] = {"regs[0]", "regs[1]", "regs[2]",
"regs[3]", "regs[4]", "regs[5]"};
void *get_call_conv_cb(bcc_arch_t arch, bool for_syscall)
{
const char **ret;
switch(arch) {
case BCC_ARCH_PPC:
case BCC_ARCH_PPC_LE:
ret = calling_conv_regs_ppc;
break;
case BCC_ARCH_S390X:
ret = calling_conv_regs_s390x;
break;
case BCC_ARCH_ARM64:
ret = calling_conv_regs_arm64;
break;
default:
if (for_syscall)
ret = calling_conv_syscall_regs_x86;
else
ret = calling_conv_regs_x86;
}
return (void *)ret;
}
const char **get_call_conv(bool for_syscall = false) {
const char **ret;
ret = (const char **)run_arch_callback(get_call_conv_cb, for_syscall);
return ret;
}
/* Use resolver only once per translation */
static void *kresolver = NULL;
static void *get_symbol_resolver(void) {
if (!kresolver)
kresolver = bcc_symcache_new(-1, nullptr);
return kresolver;
}
static std::string check_bpf_probe_read_kernel(void) {
bool is_probe_read_kernel;
void *resolver = get_symbol_resolver();
uint64_t addr = 0;
is_probe_read_kernel = bcc_symcache_resolve_name(resolver, nullptr,
"bpf_probe_read_kernel", &addr) >= 0 ? true: false;
/* If bpf_probe_read is not found (ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE) is
* not set in newer kernel, then bcc would anyway fail */
if (is_probe_read_kernel)
return "bpf_probe_read_kernel";
else
return "bpf_probe_read";
}
static std::string check_bpf_probe_read_user(llvm::StringRef probe,
bool& overlap_addr) {
if (probe.str() == "bpf_probe_read_user" ||
probe.str() == "bpf_probe_read_user_str") {
// Check for probe_user symbols in backported kernel before fallback
void *resolver = get_symbol_resolver();
uint64_t addr = 0;
bool found = bcc_symcache_resolve_name(resolver, nullptr,
"bpf_probe_read_user", &addr) >= 0 ? true: false;
if (found)
return probe.str();
/* For arch with overlapping address space, dont use bpf_probe_read for
* user read. Just error out */
#if defined(__s390x__)
overlap_addr = true;
return "";
#endif
if (probe.str() == "bpf_probe_read_user")
return "bpf_probe_read";
else
return "bpf_probe_read_str";
}
return "";
}
using std::map;
using std::move;
using std::set;
using std::tuple;
using std::make_tuple;
using std::string;
using std::to_string;
using std::unique_ptr;
using std::vector;
using namespace clang;
class ProbeChecker : public RecursiveASTVisitor<ProbeChecker> {
public:
explicit ProbeChecker(Expr *arg, const set<tuple<Decl *, int>> &ptregs,
bool track_helpers, bool is_assign)
: needs_probe_(false), is_transitive_(false), ptregs_(ptregs),
track_helpers_(track_helpers), nb_derefs_(0), is_assign_(is_assign) {
if (arg) {
TraverseStmt(arg);
if (arg->getType()->isPointerType())
is_transitive_ = needs_probe_;
}
}
explicit ProbeChecker(Expr *arg, const set<tuple<Decl *, int>> &ptregs,
bool is_transitive)
: ProbeChecker(arg, ptregs, is_transitive, false) {}
bool VisitCallExpr(CallExpr *E) {
needs_probe_ = false;
if (is_assign_) {
// We're looking for a function that returns an external pointer,
// regardless of the number of dereferences.
for(auto p : ptregs_) {
if (std::get<0>(p) == E->getDirectCallee()) {
needs_probe_ = true;
// ptregs_ stores the number of dereferences needed to get the external
// pointer, while nb_derefs_ stores the number of dereferences
// encountered. So, any dereference encountered is one less
// dereference needed to get the external pointer.
nb_derefs_ -= std::get<1>(p);
return false;
}
}
} else {
tuple<Decl *, int> pt = make_tuple(E->getDirectCallee(), nb_derefs_);
if (ptregs_.find(pt) != ptregs_.end())
needs_probe_ = true;
}
if (!track_helpers_)
return false;
if (VarDecl *V = dyn_cast<VarDecl>(E->getCalleeDecl()))
needs_probe_ = V->getName() == "bpf_get_current_task";
return false;
}
bool VisitMemberExpr(MemberExpr *M) {
tuple<Decl *, int> pt = make_tuple(M->getMemberDecl(), nb_derefs_);
if (ptregs_.find(pt) != ptregs_.end()) {
needs_probe_ = true;
return false;
}
if (M->isArrow()) {
/* In A->b, if A is an external pointer, then A->b should be considered
* one too. However, if we're taking the address of A->b
* (nb_derefs_ < 0), we should take it into account for the number of
* indirections; &A->b is a pointer to A with an offset. */
if (nb_derefs_ >= 0) {
ProbeChecker checker = ProbeChecker(M->getBase(), ptregs_,
track_helpers_, is_assign_);
if (checker.needs_probe() && checker.get_nb_derefs() == 0) {
needs_probe_ = true;
return false;
}
}
nb_derefs_++;
}
return true;
}
bool VisitUnaryOperator(UnaryOperator *E) {
if (E->getOpcode() == UO_Deref) {
/* In *A, if A is an external pointer, then *A should be considered one
* too. */
ProbeChecker checker = ProbeChecker(E->getSubExpr(), ptregs_,
track_helpers_, is_assign_);
if (checker.needs_probe() && checker.get_nb_derefs() == 0) {
needs_probe_ = true;
return false;
}
nb_derefs_++;
} else if (E->getOpcode() == UO_AddrOf) {
nb_derefs_--;
}
return true;
}
bool VisitDeclRefExpr(DeclRefExpr *E) {
if (is_assign_) {
// We're looking for an external pointer, regardless of the number of
// dereferences.
for(auto p : ptregs_) {
if (std::get<0>(p) == E->getDecl()) {
needs_probe_ = true;
// ptregs_ stores the number of dereferences needed to get the external
// pointer, while nb_derefs_ stores the number of dereferences
// encountered. So, any dereference encountered is one less
// dereference needed to get the external pointer.
nb_derefs_ -= std::get<1>(p);
return false;
}
}
} else {
tuple<Decl *, int> pt = make_tuple(E->getDecl(), nb_derefs_);
if (ptregs_.find(pt) != ptregs_.end())
needs_probe_ = true;
}
return true;
}
bool needs_probe() const { return needs_probe_; }
bool is_transitive() const { return is_transitive_; }
int get_nb_derefs() const { return nb_derefs_; }
private:
bool needs_probe_;
bool is_transitive_;
const set<tuple<Decl *, int>> &ptregs_;
bool track_helpers_;
// Nb of dereferences we go through before finding the external pointer.
// A negative number counts the number of addrof.
int nb_derefs_;
bool is_assign_;
};
// Visit a piece of the AST and mark it as needing probe reads
class ProbeSetter : public RecursiveASTVisitor<ProbeSetter> {
public:
explicit ProbeSetter(set<tuple<Decl *, int>> *ptregs, int nb_derefs)
: ptregs_(ptregs), nb_derefs_(nb_derefs) {}
bool VisitDeclRefExpr(DeclRefExpr *E) {
tuple<Decl *, int> pt = make_tuple(E->getDecl(), nb_derefs_);
ptregs_->insert(pt);
return true;
}
explicit ProbeSetter(set<tuple<Decl *, int>> *ptregs)
: ProbeSetter(ptregs, 0) {}
bool VisitUnaryOperator(UnaryOperator *E) {
if (E->getOpcode() == UO_Deref)
nb_derefs_++;
return true;
}
bool VisitMemberExpr(MemberExpr *M) {
tuple<Decl *, int> pt = make_tuple(M->getMemberDecl(), nb_derefs_);
ptregs_->insert(pt);
return false;
}
private:
set<tuple<Decl *, int>> *ptregs_;
// Nb of dereferences we go through before getting to the actual variable.
int nb_derefs_;
};
MapVisitor::MapVisitor(set<Decl *> &m) : m_(m) {}
bool MapVisitor::VisitCallExpr(CallExpr *Call) {
if (MemberExpr *Memb = dyn_cast<MemberExpr>(Call->getCallee()->IgnoreImplicit())) {
StringRef memb_name = Memb->getMemberDecl()->getName();
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Memb->getBase())) {
if (SectionAttr *A = Ref->getDecl()->getAttr<SectionAttr>()) {
if (!A->getName().startswith("maps"))
return true;
if (memb_name == "update" || memb_name == "insert") {
ProbeChecker checker = ProbeChecker(Call->getArg(1), ptregs_, true,
true);
if (checker.needs_probe())
m_.insert(Ref->getDecl());
}
}
}
}
return true;
}
ProbeVisitor::ProbeVisitor(ASTContext &C, Rewriter &rewriter,
set<Decl *> &m, bool track_helpers) :
C(C), rewriter_(rewriter), m_(m), track_helpers_(track_helpers),
addrof_stmt_(nullptr), is_addrof_(false) {
const char **calling_conv_regs = get_call_conv();
has_overlap_kuaddr_ = calling_conv_regs == calling_conv_regs_s390x;
}
bool ProbeVisitor::assignsExtPtr(Expr *E, int *nbDerefs) {
if (IsContextMemberExpr(E)) {
*nbDerefs = 0;
return true;
}
/* If the expression contains a call to another function, we need to visit
* that function first to know if a rewrite is necessary (i.e., if the
* function returns an external pointer). */
if (!TraverseStmt(E))
return false;
ProbeChecker checker = ProbeChecker(E, ptregs_, track_helpers_,
true);
if (checker.is_transitive()) {
// The negative of the number of dereferences is the number of addrof. In
// an assignment, if we went through n addrof before getting the external
// pointer, then we'll need n dereferences on the left-hand side variable
// to get to the external pointer.
*nbDerefs = -checker.get_nb_derefs();
return true;
}
if (E->IgnoreParenCasts()->getStmtClass() == Stmt::CallExprClass) {
CallExpr *Call = dyn_cast<CallExpr>(E->IgnoreParenCasts());
if (MemberExpr *Memb = dyn_cast<MemberExpr>(Call->getCallee()->IgnoreImplicit())) {
StringRef memb_name = Memb->getMemberDecl()->getName();
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Memb->getBase())) {
if (SectionAttr *A = Ref->getDecl()->getAttr<SectionAttr>()) {
if (!A->getName().startswith("maps"))
return false;
if (memb_name == "lookup" || memb_name == "lookup_or_init" ||
memb_name == "lookup_or_try_init") {
if (m_.find(Ref->getDecl()) != m_.end()) {
// Retrieved an ext. pointer from a map, mark LHS as ext. pointer.
// Pointers from maps always need a single dereference to get the
// actual value. The value may be an external pointer but cannot
// be a pointer to an external pointer as the verifier prohibits
// storing known pointers (to map values, context, the stack, or
// the packet) in maps.
*nbDerefs = 1;
return true;
}
}
}
}
}
}
return false;
}
bool ProbeVisitor::VisitVarDecl(VarDecl *D) {
if (Expr *E = D->getInit()) {
int nbDerefs;
if (assignsExtPtr(E, &nbDerefs)) {
// The negative of the number of addrof is the number of dereferences.
tuple<Decl *, int> pt = make_tuple(D, nbDerefs);
set_ptreg(pt);
}
}
return true;
}
bool ProbeVisitor::TraverseStmt(Stmt *S) {
if (whitelist_.find(S) != whitelist_.end())
return true;
auto ret = RecursiveASTVisitor<ProbeVisitor>::TraverseStmt(S);
if (addrof_stmt_ == S) {
addrof_stmt_ = nullptr;
is_addrof_ = false;
}
return ret;
}
bool ProbeVisitor::VisitCallExpr(CallExpr *Call) {
// Skip bpf_probe_read for the third argument if it is an AddrOf.
if (VarDecl *V = dyn_cast<VarDecl>(Call->getCalleeDecl())) {
if (V->getName() == "bpf_probe_read" && Call->getNumArgs() >= 3) {
const Expr *E = Call->getArg(2)->IgnoreParenCasts();
whitelist_.insert(E);
return true;
}
}
if (FunctionDecl *F = dyn_cast<FunctionDecl>(Call->getCalleeDecl())) {
if (F->hasBody()) {
unsigned i = 0;
for (auto arg : Call->arguments()) {
ProbeChecker checker = ProbeChecker(arg, ptregs_, track_helpers_,
true);
if (checker.needs_probe()) {
tuple<Decl *, int> pt = make_tuple(F->getParamDecl(i),
-checker.get_nb_derefs());
ptregs_.insert(pt);
}
++i;
}
if (fn_visited_.find(F) == fn_visited_.end()) {
fn_visited_.insert(F);
/* Maintains a stack of the number of dereferences for the external
* pointers returned by each function in the call stack or -1 if the
* function didn't return an external pointer. */
ptregs_returned_.push_back(-1);
TraverseDecl(F);
int nb_derefs = ptregs_returned_.back();
ptregs_returned_.pop_back();
if (nb_derefs != -1) {
tuple<Decl *, int> pt = make_tuple(F, nb_derefs);
ptregs_.insert(pt);
}
}
}
}
return true;
}
bool ProbeVisitor::VisitReturnStmt(ReturnStmt *R) {
/* If this function wasn't called by another, there's no need to check the
* return statement for external pointers. */
if (ptregs_returned_.size() == 0)
return true;
/* Reverse order of traversals. This is needed if, in the return statement,
* we're calling a function that's returning an external pointer: we need to
* know what the function is returning to decide what this function is
* returning. */
if (!TraverseStmt(R->getRetValue()))
return false;
ProbeChecker checker = ProbeChecker(R->getRetValue(), ptregs_,
track_helpers_, true);
if (checker.needs_probe()) {
int curr_nb_derefs = ptregs_returned_.back();
int nb_derefs = -checker.get_nb_derefs();
/* If the function returns external pointers with different levels of
* indirection, we handle the case with the highest level of indirection
* and leave it to the user to manually handle other cases. */
if (nb_derefs > curr_nb_derefs) {
ptregs_returned_.pop_back();
ptregs_returned_.push_back(nb_derefs);
}
}
return true;
}
bool ProbeVisitor::VisitBinaryOperator(BinaryOperator *E) {
if (!E->isAssignmentOp())
return true;
// copy probe attribute from RHS to LHS if present
int nbDerefs;
if (assignsExtPtr(E->getRHS(), &nbDerefs)) {
ProbeSetter setter(&ptregs_, nbDerefs);
setter.TraverseStmt(E->getLHS());
}
return true;
}
bool ProbeVisitor::VisitUnaryOperator(UnaryOperator *E) {
if (E->getOpcode() == UO_AddrOf) {
addrof_stmt_ = E;
is_addrof_ = true;
}
if (E->getOpcode() != UO_Deref)
return true;
if (memb_visited_.find(E) != memb_visited_.end())
return true;
Expr *sub = E->getSubExpr();
if (!ProbeChecker(sub, ptregs_, track_helpers_).needs_probe())
return true;
memb_visited_.insert(E);
string pre, post;
pre = "({ typeof(" + E->getType().getAsString() + ") _val; __builtin_memset(&_val, 0, sizeof(_val));";
if (has_overlap_kuaddr_)
pre += " bpf_probe_read_kernel(&_val, sizeof(_val), (u64)";
else
pre += " bpf_probe_read(&_val, sizeof(_val), (u64)";
post = "); _val; })";
rewriter_.ReplaceText(expansionLoc(E->getOperatorLoc()), 1, pre);
rewriter_.InsertTextAfterToken(expansionLoc(GET_ENDLOC(sub)), post);
return true;
}
bool ProbeVisitor::VisitMemberExpr(MemberExpr *E) {
if (memb_visited_.find(E) != memb_visited_.end()) return true;
Expr *base;
SourceLocation rhs_start, member;
bool found = false;
for (MemberExpr *M = E; M; M = dyn_cast<MemberExpr>(M->getBase())) {
memb_visited_.insert(M);
rhs_start = GET_ENDLOC(M);
base = M->getBase();
member = M->getMemberLoc();
if (M->isArrow()) {
found = true;
break;
}
}
if (!found)
return true;
if (member.isInvalid()) {
error(GET_ENDLOC(base), "internal error: MemberLoc is invalid while preparing probe rewrite");
return false;
}
if (!rewriter_.isRewritable(GET_BEGINLOC(E)))
return true;
// parent expr has addrof, skip the rewrite, set is_addrof_ to flase so
// it won't affect next level of indirect address
if (is_addrof_) {
is_addrof_ = false;
return true;
}
/* If the base of the dereference is a call to another function, we need to
* visit that function first to know if a rewrite is necessary (i.e., if the
* function returns an external pointer). */
if (base->IgnoreParenCasts()->getStmtClass() == Stmt::CallExprClass) {
CallExpr *Call = dyn_cast<CallExpr>(base->IgnoreParenCasts());
if (!TraverseStmt(Call))
return false;
}
// Checks to see if the expression references something that needs to be run
// through bpf_probe_read.
if (!ProbeChecker(base, ptregs_, track_helpers_).needs_probe())
return true;
// If the base is an array, we will skip rewriting. See issue #2352.
if (E->getType()->isArrayType())
return true;
string rhs = rewriter_.getRewrittenText(expansionRange(SourceRange(rhs_start, GET_ENDLOC(E))));
string base_type = base->getType()->getPointeeType().getAsString();
string pre, post;
pre = "({ typeof(" + E->getType().getAsString() + ") _val; __builtin_memset(&_val, 0, sizeof(_val));";
if (has_overlap_kuaddr_)
pre += " bpf_probe_read_kernel(&_val, sizeof(_val), (u64)&";
else
pre += " bpf_probe_read(&_val, sizeof(_val), (u64)&";
post = rhs + "); _val; })";
rewriter_.InsertText(expansionLoc(GET_BEGINLOC(E)), pre);
rewriter_.ReplaceText(expansionRange(SourceRange(member, GET_ENDLOC(E))), post);
return true;
}
bool ProbeVisitor::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
if (memb_visited_.find(E) != memb_visited_.end()) return true;
if (!ProbeChecker(E, ptregs_, track_helpers_).needs_probe())
return true;
// Parent expr has addrof, skip the rewrite.
if (is_addrof_)
return true;
// If the base is an array, we will skip rewriting. See issue #2352.
if (E->getType()->isArrayType())
return true;
if (!rewriter_.isRewritable(GET_BEGINLOC(E)))
return true;
Expr *base = E->getBase();
Expr *idx = E->getIdx();
memb_visited_.insert(E);
if (!rewriter_.isRewritable(GET_BEGINLOC(base)))
return true;
if (!rewriter_.isRewritable(GET_BEGINLOC(idx)))
return true;
string pre, lbracket, rbracket;
LangOptions opts;
SourceLocation lbracket_start, lbracket_end;
SourceRange lbracket_range;
/* For cases like daddr->s6_addr[4], clang encodes the end location of "base"
* as "]". This makes it hard to rewrite the expression like
* "daddr->s6_addr [ 4 ]" since we do not know the end location
* of "addr->s6_addr". Let us abort the operation if this is the case.
*/
lbracket_start = Lexer::getLocForEndOfToken(GET_ENDLOC(base), 1,
rewriter_.getSourceMgr(),
opts).getLocWithOffset(1);
lbracket_end = GET_BEGINLOC(idx).getLocWithOffset(-1);
lbracket_range = expansionRange(SourceRange(lbracket_start, lbracket_end));
if (rewriter_.getRewrittenText(lbracket_range).size() == 0)
return true;
pre = "({ typeof(" + E->getType().getAsString() + ") _val; __builtin_memset(&_val, 0, sizeof(_val));";
if (has_overlap_kuaddr_)
pre += " bpf_probe_read_kernel(&_val, sizeof(_val), (u64)((";
else
pre += " bpf_probe_read(&_val, sizeof(_val), (u64)((";
if (isMemberDereference(base)) {
pre += "&";
// If the base of the array subscript is a member dereference, we'll rewrite
// both at the same time.
addrof_stmt_ = base;
is_addrof_ = true;
}
rewriter_.InsertText(expansionLoc(GET_BEGINLOC(base)), pre);
/* Replace left bracket and any space around it. Since Clang doesn't provide
* a method to retrieve the left bracket, replace everything from the end of
* the base to the start of the index. */
lbracket = ") + (";
rewriter_.ReplaceText(lbracket_range, lbracket);
rbracket = "))); _val; })";
rewriter_.ReplaceText(expansionLoc(E->getRBracketLoc()), 1, rbracket);
return true;
}
bool ProbeVisitor::isMemberDereference(Expr *E) {
if (E->IgnoreParenCasts()->getStmtClass() != Stmt::MemberExprClass)
return false;
for (MemberExpr *M = dyn_cast<MemberExpr>(E->IgnoreParenCasts()); M;
M = dyn_cast<MemberExpr>(M->getBase()->IgnoreParenCasts())) {
if (M->isArrow())
return true;
}
return false;
}
bool ProbeVisitor::IsContextMemberExpr(Expr *E) {
if (!E->getType()->isPointerType())
return false;
Expr *base;
SourceLocation member;
bool found = false;
MemberExpr *M;
Expr *Ex = E->IgnoreParenCasts();
while (Ex->getStmtClass() == Stmt::ArraySubscriptExprClass
|| Ex->getStmtClass() == Stmt::MemberExprClass) {
if (Ex->getStmtClass() == Stmt::ArraySubscriptExprClass) {
Ex = dyn_cast<ArraySubscriptExpr>(Ex)->getBase()->IgnoreParenCasts();
} else if (Ex->getStmtClass() == Stmt::MemberExprClass) {
M = dyn_cast<MemberExpr>(Ex);
base = M->getBase()->IgnoreParenCasts();
member = M->getMemberLoc();
if (M->isArrow()) {
found = true;
break;
}
Ex = base;
}
}
if (!found) {
return false;
}
if (member.isInvalid()) {
return false;
}
if (DeclRefExpr *base_expr = dyn_cast<DeclRefExpr>(base)) {
if (base_expr->getDecl() == ctx_) {
return true;
}
}
return false;
}
SourceRange
ProbeVisitor::expansionRange(SourceRange range) {
#if LLVM_MAJOR_VERSION >= 7
return rewriter_.getSourceMgr().getExpansionRange(range).getAsRange();
#else
return rewriter_.getSourceMgr().getExpansionRange(range);
#endif
}
SourceLocation
ProbeVisitor::expansionLoc(SourceLocation loc) {
return rewriter_.getSourceMgr().getExpansionLoc(loc);
}
template <unsigned N>
DiagnosticBuilder ProbeVisitor::error(SourceLocation loc, const char (&fmt)[N]) {
unsigned int diag_id = C.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, fmt);
return C.getDiagnostics().Report(loc, diag_id);
}
BTypeVisitor::BTypeVisitor(ASTContext &C, BFrontendAction &fe)
: C(C), diag_(C.getDiagnostics()), fe_(fe), rewriter_(fe.rewriter()), out_(llvm::errs()) {
const char **calling_conv_regs = get_call_conv();
has_overlap_kuaddr_ = calling_conv_regs == calling_conv_regs_s390x;
}
void BTypeVisitor::genParamDirectAssign(FunctionDecl *D, string& preamble,
const char **calling_conv_regs) {
for (size_t idx = 0; idx < fn_args_.size(); idx++) {
ParmVarDecl *arg = fn_args_[idx];
if (idx >= 1) {
// Move the args into a preamble section where the same params are
// declared and initialized from pt_regs.
// Todo: this init should be done only when the program requests it.
string text = rewriter_.getRewrittenText(expansionRange(arg->getSourceRange()));
arg->addAttr(UnavailableAttr::CreateImplicit(C, "ptregs"));
size_t d = idx - 1;
const char *reg = calling_conv_regs[d];
preamble += " " + text + " = " + fn_args_[0]->getName().str() + "->" +
string(reg) + ";";
}
}
}
void BTypeVisitor::genParamIndirectAssign(FunctionDecl *D, string& preamble,
const char **calling_conv_regs) {
string new_ctx;
for (size_t idx = 0; idx < fn_args_.size(); idx++) {
ParmVarDecl *arg = fn_args_[idx];
if (idx == 0) {
new_ctx = "__" + arg->getName().str();
preamble += " struct pt_regs * " + new_ctx + " = " +
arg->getName().str() + "->" +
string(calling_conv_regs[0]) + ";";
} else {
// Move the args into a preamble section where the same params are
// declared and initialized from pt_regs.
// Todo: this init should be done only when the program requests it.
string text = rewriter_.getRewrittenText(expansionRange(arg->getSourceRange()));
size_t d = idx - 1;
const char *reg = calling_conv_regs[d];
preamble += "\n " + text + ";";
if (has_overlap_kuaddr_)
preamble += " bpf_probe_read_kernel";
else
preamble += " bpf_probe_read";
preamble += "(&" + arg->getName().str() + ", sizeof(" +
arg->getName().str() + "), &" + new_ctx + "->" +
string(reg) + ");";
}
}
}
void BTypeVisitor::rewriteFuncParam(FunctionDecl *D) {
const char **calling_conv_regs = get_call_conv(true);
string preamble = "{\n";
if (D->param_size() > 1) {
// If function prefix is "syscall__" or "kprobe____x64_sys_",
// the function will attach to a kprobe syscall function.
// Guard parameter assiggnment with CONFIG_ARCH_HAS_SYSCALL_WRAPPER.
// For __x64_sys_* syscalls, this is always true, but we guard
// it in case of "syscall__" for other architectures.
if (strncmp(D->getName().str().c_str(), "syscall__", 9) == 0 ||
strncmp(D->getName().str().c_str(), "kprobe____x64_sys_", 18) == 0) {
preamble += "#if defined(CONFIG_ARCH_HAS_SYSCALL_WRAPPER) && !defined(__s390x__)\n";
genParamIndirectAssign(D, preamble, calling_conv_regs);
preamble += "\n#else\n";
genParamDirectAssign(D, preamble, calling_conv_regs);
preamble += "\n#endif\n";
} else {
genParamDirectAssign(D, preamble, calling_conv_regs);
}
rewriter_.ReplaceText(
expansionRange(SourceRange(GET_ENDLOC(D->getParamDecl(0)),
GET_ENDLOC(D->getParamDecl(D->getNumParams() - 1)))),
fn_args_[0]->getName());
}
// for each trace argument, convert the variable from ptregs to something on stack
if (CompoundStmt *S = dyn_cast<CompoundStmt>(D->getBody()))
rewriter_.ReplaceText(S->getLBracLoc(), 1, preamble);
}
bool BTypeVisitor::VisitFunctionDecl(FunctionDecl *D) {
// put each non-static non-inline function decl in its own section, to be
// extracted by the MemoryManager
auto real_start_loc = rewriter_.getSourceMgr().getFileLoc(GET_BEGINLOC(D));
if (fe_.is_rewritable_ext_func(D)) {
current_fn_ = string(D->getName());
string bd = rewriter_.getRewrittenText(expansionRange(D->getSourceRange()));
fe_.func_src_.set_src(current_fn_, bd);
fe_.func_range_[current_fn_] = expansionRange(D->getSourceRange());
string attr = string("__attribute__((section(\"") + BPF_FN_PREFIX + D->getName().str() + "\")))\n";
rewriter_.InsertText(real_start_loc, attr);
if (D->param_size() > MAX_CALLING_CONV_REGS + 1) {
error(GET_BEGINLOC(D->getParamDecl(MAX_CALLING_CONV_REGS + 1)),
"too many arguments, bcc only supports in-register parameters");
return false;
}
fn_args_.clear();
for (auto arg_it = D->param_begin(); arg_it != D->param_end(); arg_it++) {
auto *arg = *arg_it;
if (arg->getName() == "") {
error(GET_ENDLOC(arg), "arguments to BPF program definition must be named");
return false;
}
fn_args_.push_back(arg);
}
rewriteFuncParam(D);
} else if (D->hasBody() &&
rewriter_.getSourceMgr().getFileID(real_start_loc)
== rewriter_.getSourceMgr().getMainFileID()) {
// rewritable functions that are static should be always treated as helper
rewriter_.InsertText(real_start_loc, "__attribute__((always_inline))\n");
}
return true;
}
// Reverse the order of call traversal so that parameters inside of
// function calls will get rewritten before the call itself, otherwise
// text mangling will result.
bool BTypeVisitor::TraverseCallExpr(CallExpr *Call) {
for (auto child : Call->children())
if (!TraverseStmt(child))
return false;
if (!WalkUpFromCallExpr(Call))
return false;
return true;
}
// convert calls of the type:
// table.foo(&key)
// to:
// bpf_table_foo_elem(bpf_pseudo_fd(table), &key [,&leaf])
bool BTypeVisitor::VisitCallExpr(CallExpr *Call) {
// make sure node is a reference to a bpf table, which is assured by the
// presence of the section("maps/<typename>") GNU __attribute__
if (MemberExpr *Memb = dyn_cast<MemberExpr>(Call->getCallee()->IgnoreImplicit())) {
StringRef memb_name = Memb->getMemberDecl()->getName();
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Memb->getBase())) {
if (SectionAttr *A = Ref->getDecl()->getAttr<SectionAttr>()) {
if (!A->getName().startswith("maps"))
return true;
string args = rewriter_.getRewrittenText(expansionRange(SourceRange(GET_BEGINLOC(Call->getArg(0)),
GET_ENDLOC(Call->getArg(Call->getNumArgs() - 1)))));
// find the table fd, which was opened at declaration time
TableStorage::iterator desc;
Path local_path({fe_.id(), string(Ref->getDecl()->getName())});
Path global_path({string(Ref->getDecl()->getName())});
if (!fe_.table_storage().Find(local_path, desc)) {
if (!fe_.table_storage().Find(global_path, desc)) {
error(GET_ENDLOC(Ref), "bpf_table %0 failed to open") << Ref->getDecl()->getName();
return false;
}
}
string fd = to_string(desc->second.fd >= 0 ? desc->second.fd : desc->second.fake_fd);
string prefix, suffix;
string txt;
auto rewrite_start = GET_BEGINLOC(Call);
auto rewrite_end = GET_ENDLOC(Call);
if (memb_name == "lookup_or_init" || memb_name == "lookup_or_try_init") {
string name = string(Ref->getDecl()->getName());
string arg0 = rewriter_.getRewrittenText(expansionRange(Call->getArg(0)->getSourceRange()));
string arg1 = rewriter_.getRewrittenText(expansionRange(Call->getArg(1)->getSourceRange()));
string lookup = "bpf_map_lookup_elem_(bpf_pseudo_fd(1, " + fd + ")";
string update = "bpf_map_update_elem_(bpf_pseudo_fd(1, " + fd + ")";
txt = "({typeof(" + name + ".leaf) *leaf = " + lookup + ", " + arg0 + "); ";
txt += "if (!leaf) {";
txt += " " + update + ", " + arg0 + ", " + arg1 + ", BPF_NOEXIST);";
txt += " leaf = " + lookup + ", " + arg0 + ");";
if (memb_name == "lookup_or_init") {
txt += " if (!leaf) return 0;";
}
txt += "}";
txt += "leaf;})";
} else if (memb_name == "increment") {
string name = string(Ref->getDecl()->getName());
string arg0 = rewriter_.getRewrittenText(expansionRange(Call->getArg(0)->getSourceRange()));
string increment_value = "1";
if (Call->getNumArgs() == 2) {
increment_value = rewriter_.getRewrittenText(expansionRange(Call->getArg(1)->getSourceRange()));
}
string lookup = "bpf_map_lookup_elem_(bpf_pseudo_fd(1, " + fd + ")";
string update = "bpf_map_update_elem_(bpf_pseudo_fd(1, " + fd + ")";
txt = "({ typeof(" + name + ".key) _key = " + arg0 + "; ";
txt += "typeof(" + name + ".leaf) *_leaf = " + lookup + ", &_key); ";
txt += "if (_leaf) (*_leaf) += " + increment_value + ";";
if (desc->second.type == BPF_MAP_TYPE_HASH) {
txt += "else { typeof(" + name + ".leaf) _zleaf; __builtin_memset(&_zleaf, 0, sizeof(_zleaf)); ";
txt += "_zleaf += " + increment_value + ";";
txt += update + ", &_key, &_zleaf, BPF_NOEXIST); } ";
}
txt += "})";
} else if (memb_name == "perf_submit") {
string name = string(Ref->getDecl()->getName());
string arg0 = rewriter_.getRewrittenText(expansionRange(Call->getArg(0)->getSourceRange()));
string args_other = rewriter_.getRewrittenText(expansionRange(SourceRange(GET_BEGINLOC(Call->getArg(1)),
GET_ENDLOC(Call->getArg(2)))));
txt = "bpf_perf_event_output(" + arg0 + ", bpf_pseudo_fd(1, " + fd + ")";
txt += ", CUR_CPU_IDENTIFIER, " + args_other + ")";
// e.g.
// struct data_t { u32 pid; }; data_t data;
// events.perf_submit(ctx, &data, sizeof(data));
// ...
// &data -> data -> typeof(data) -> data_t
auto type_arg1 = Call->getArg(1)->IgnoreCasts()->getType().getTypePtr()->getPointeeType().getTypePtr();
if (type_arg1->isStructureType()) {
auto event_type = type_arg1->getAsTagDecl();
const auto *r = dyn_cast<RecordDecl>(event_type);
std::vector<std::string> perf_event;
for (auto it = r->field_begin(); it != r->field_end(); ++it) {
perf_event.push_back(it->getNameAsString() + "#" + it->getType().getAsString()); //"pid#u32"
}
fe_.perf_events_[name] = perf_event;
}
} else if (memb_name == "perf_submit_skb") {
string skb = rewriter_.getRewrittenText(expansionRange(Call->getArg(0)->getSourceRange()));
string skb_len = rewriter_.getRewrittenText(expansionRange(Call->getArg(1)->getSourceRange()));
string meta = rewriter_.getRewrittenText(expansionRange(Call->getArg(2)->getSourceRange()));
string meta_len = rewriter_.getRewrittenText(expansionRange(Call->getArg(3)->getSourceRange()));
txt = "bpf_perf_event_output(" +
skb + ", " +
"bpf_pseudo_fd(1, " + fd + "), " +
"((__u64)" + skb_len + " << 32) | BPF_F_CURRENT_CPU, " +
meta + ", " +
meta_len + ");";
} else if (memb_name == "get_stackid") {
if (desc->second.type == BPF_MAP_TYPE_STACK_TRACE) {
string arg0 =
rewriter_.getRewrittenText(expansionRange(Call->getArg(0)->getSourceRange()));
txt = "bcc_get_stackid(";
txt += "bpf_pseudo_fd(1, " + fd + "), " + arg0;
rewrite_end = GET_ENDLOC(Call->getArg(0));
} else {
error(GET_BEGINLOC(Call), "get_stackid only available on stacktrace maps");
return false;
}
} else if (memb_name == "sock_map_update" || memb_name == "sock_hash_update") {
string ctx = rewriter_.getRewrittenText(expansionRange(Call->getArg(0)->getSourceRange()));
string keyp = rewriter_.getRewrittenText(expansionRange(Call->getArg(1)->getSourceRange()));
string flag = rewriter_.getRewrittenText(expansionRange(Call->getArg(2)->getSourceRange()));
txt = "bpf_" + string(memb_name) + "(" + ctx + ", " +
"bpf_pseudo_fd(1, " + fd + "), " + keyp + ", " + flag + ");";
} else if (memb_name == "ringbuf_output") {
string name = string(Ref->getDecl()->getName());
string args = rewriter_.getRewrittenText(expansionRange(SourceRange(GET_BEGINLOC(Call->getArg(0)),
GET_ENDLOC(Call->getArg(2)))));
txt = "bpf_ringbuf_output(bpf_pseudo_fd(1, " + fd + ")";
txt += ", " + args + ")";
// e.g.
// struct data_t { u32 pid; }; data_t data;
// events.ringbuf_output(&data, sizeof(data), 0);
// ...
// &data -> data -> typeof(data) -> data_t
auto type_arg0 = Call->getArg(0)->IgnoreCasts()->getType().getTypePtr()->getPointeeType().getTypePtr();
if (type_arg0->isStructureType()) {
auto event_type = type_arg0->getAsTagDecl();
const auto *r = dyn_cast<RecordDecl>(event_type);
std::vector<std::string> perf_event;
for (auto it = r->field_begin(); it != r->field_end(); ++it) {
perf_event.push_back(it->getNameAsString() + "#" + it->getType().getAsString()); //"pid#u32"
}
fe_.perf_events_[name] = perf_event;
}
} else if (memb_name == "ringbuf_reserve") {
string name = string(Ref->getDecl()->getName());
string arg0 = rewriter_.getRewrittenText(expansionRange(Call->getArg(0)->getSourceRange()));
txt = "bpf_ringbuf_reserve(bpf_pseudo_fd(1, " + fd + ")";
txt += ", " + arg0 + ", 0)"; // Flags in reserve are meaningless
} else if (memb_name == "ringbuf_discard") {
string name = string(Ref->getDecl()->getName());
string args = rewriter_.getRewrittenText(expansionRange(SourceRange(GET_BEGINLOC(Call->getArg(0)),
GET_ENDLOC(Call->getArg(1)))));
txt = "bpf_ringbuf_discard(" + args + ")";
} else if (memb_name == "ringbuf_submit") {