forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GCChecker.cpp
1544 lines (1461 loc) · 61 KB
/
GCChecker.cpp
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
// This file is a part of Julia. License is MIT: https://julialang.org/license
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
#include "clang/StaticAnalyzer/Checkers/SValExplainer.h"
#if LLVM_VERSION_MAJOR >= 9
#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
#else
#include "clang/StaticAnalyzer/Core/CheckerRegistry.h"
#endif
#include <iostream>
namespace {
using namespace clang;
using namespace ento;
#define PDP std::shared_ptr<PathDiagnosticPiece>
#define MakePDP llvm::make_unique<PathDiagnosticEventPiece>
class GCChecker : public Checker<eval::Call,
check::BeginFunction,
check::EndFunction,
check::PostCall,
check::PreCall,
check::PostStmt<CStyleCastExpr>,
check::PostStmt<ArraySubscriptExpr>,
check::PostStmt<MemberExpr>,
check::PostStmt<UnaryOperator>,
check::Bind,
check::Location
> {
mutable std::unique_ptr<BugType> BT;
template <typename callback>
void report_error(callback f, CheckerContext &C, const char *message) const;
void report_error(CheckerContext &C, const char *message) const {
return report_error([](BugReport *){}, C, message);
}
void report_value_error(CheckerContext &C, SymbolRef Sym, const char *message, clang::SourceRange range = clang::SourceRange()) const;
public:
struct ValueState {
enum State { Allocated, Rooted, PotentiallyFreed, Untracked } S;
const MemRegion *Root;
int RootDepth;
// Optional Metadata (for error messages)
const FunctionDecl *FD;
const ParmVarDecl *PVD;
ValueState(State InS, const MemRegion *Root, int Depth) : S(InS), Root(Root), RootDepth(Depth), FD(nullptr), PVD(nullptr) {}
ValueState() : S(Untracked), Root(nullptr), RootDepth(0), FD(nullptr), PVD(nullptr) {}
void dump() const {
llvm::dbgs() << ((S == Allocated) ? "Allocated" :
(S == Rooted) ? "Rooted" :
(S == PotentiallyFreed) ? "PotentiallyFreed" :
(S == Untracked) ? "Untracked" : "Error");
if (S == Rooted)
llvm::dbgs() << "(" << RootDepth << ")";
llvm::dbgs() << "\n";
}
bool operator==(const ValueState &VS) const {
return S == VS.S && Root == VS.Root && RootDepth == VS.RootDepth;
}
bool operator!=(const ValueState &VS) const {
return S != VS.S || Root != VS.Root || RootDepth != VS.RootDepth;
}
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddInteger(S);
ID.AddPointer(Root);
ID.AddInteger(RootDepth);
}
bool isRooted() const { return S == Rooted; }
bool isPotentiallyFreed() const { return S == PotentiallyFreed; }
bool isJustAllocated() const { return S == Allocated; }
bool isUntracked() const { return S == Untracked; }
bool isRootedBy(const MemRegion *R) const {
assert(R != nullptr);
return isRooted() && R == Root;
}
static ValueState getAllocated() { return ValueState(Allocated, nullptr, -1); }
static ValueState getFreed() { return ValueState(PotentiallyFreed, nullptr, -1); }
static ValueState getUntracked() { return ValueState(Untracked, nullptr, -1); }
static ValueState getRooted(const MemRegion *Root, int Depth) { return ValueState(Rooted, Root, Depth); }
static ValueState getForArgument(const FunctionDecl *FD,
const ParmVarDecl *PVD) {
bool isFunctionSafepoint = !isFDAnnotatedNotSafepoint(FD);
bool maybeUnrooted = declHasAnnotation(PVD, "julia_maybe_unrooted");
if (!isFunctionSafepoint || maybeUnrooted) {
ValueState VS = getAllocated();
VS.PVD = PVD; VS.FD = FD;
return VS;
}
return getRooted(nullptr, -1);
}
};
struct RootState {
enum Kind { Root, RootArray } K;
int RootedAtDepth;
RootState(Kind InK, int Depth) : K(InK), RootedAtDepth(Depth) {}
bool operator==(const RootState &VS) const {
return K == VS.K && RootedAtDepth == VS.RootedAtDepth;
}
bool operator!=(const RootState &VS) const {
return K != VS.K || RootedAtDepth != VS.RootedAtDepth;
}
bool shouldPopAtDepth(int Depth) const { return Depth == RootedAtDepth; }
bool isRootArray() const { return K == RootArray; }
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddInteger(K);
ID.AddInteger(RootedAtDepth);
}
static RootState getRoot(int Depth) { return RootState(Root, Depth); }
static RootState getRootArray(int Depth) { return RootState(RootArray, Depth); }
};
private:
template <typename callback>
static bool isJuliaType(callback f, QualType QT) {
if (QT->isPointerType() || QT->isArrayType())
return isJuliaType(f, clang::QualType(QT->getPointeeOrArrayElementType(),0));
const TypedefType *TT = QT->getAs<TypedefType>();
if (TT) {
if (f(TT->getDecl()->getName()))
return true;
}
const TagDecl *TD = QT->getUnqualifiedDesugaredType()->getAsTagDecl();
if (!TD) {
return false;
}
return f(TD->getName());
}
static bool isValueCollection(QualType QT) {
if (QT->isPointerType() || QT->isArrayType())
return isValueCollection(clang::QualType(QT->getPointeeOrArrayElementType(), 0));
const TagDecl *TD = QT->getUnqualifiedDesugaredType()->getAsTagDecl();
if (!TD)
return false;
return declHasAnnotation(TD, "julia_rooted_value_collection");
}
template <typename callback>
static SymbolRef walkToRoot(callback f, const ProgramStateRef &State, const MemRegion *Region);
static bool isGCTrackedType(QualType Type);
bool isGloballyRootedType(QualType Type) const;
bool isBundleOfGCValues(QualType QT) const;
static void dumpState(const ProgramStateRef &State);
static bool declHasAnnotation(const clang::Decl *D, const char *which);
static bool isFDAnnotatedNotSafepoint(const clang::FunctionDecl *FD);
bool isSafepoint(const CallEvent &Call) const;
bool processPotentialSafepoint(const CallEvent &Call, CheckerContext &C, ProgramStateRef &State) const;
bool processAllocationOfResult(const CallEvent &Call, CheckerContext &C, ProgramStateRef &State) const;
bool processArgumentRooting(const CallEvent &Call, CheckerContext &C, ProgramStateRef &State) const;
bool rootRegionIfGlobal(const MemRegion *R, ProgramStateRef &, CheckerContext &C, ValueState *ValS = nullptr) const;
static const ValueState *getValStateForRegion(ASTContext &AstC, const ProgramStateRef &State, const MemRegion *R, bool Debug = false);
bool gcEnabledHere(CheckerContext &C) const;
bool safepointEnabledHere(CheckerContext &C) const;
bool propagateArgumentRootedness(CheckerContext &C, ProgramStateRef &State) const;
SymbolRef getSymbolForResult(const Expr *Result, const ValueState *OldValS, ProgramStateRef &State, CheckerContext &C) const;
public:
void checkBeginFunction(CheckerContext &Ctx) const;
#if LLVM_VERSION_MAJOR >= 7
void checkEndFunction(const clang::ReturnStmt* RS, CheckerContext &Ctx) const;
#else
void checkEndFunction(CheckerContext &Ctx) const;
#endif
bool evalCall(const CallExpr *CE, CheckerContext &C) const;
void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
void checkPostStmt(const CStyleCastExpr *CE, CheckerContext &C) const;
void checkPostStmt(const ArraySubscriptExpr *CE, CheckerContext &C) const;
void checkPostStmt(const MemberExpr *ME, CheckerContext &C) const;
void checkPostStmt(const UnaryOperator *UO, CheckerContext &C) const;
void checkDerivingExpr(const Expr *Result, const Expr *Parent, bool ParentIsLoc, CheckerContext &C) const;
void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &) const;
void checkLocation(SVal Loc, bool IsLoad, const Stmt *S, CheckerContext &) const;
class GCBugVisitor
#if LLVM_VERSION_MAJOR >= 7
: public BugReporterVisitor {
#else
: public BugReporterVisitorImpl<GCBugVisitor> {
#endif
public:
GCBugVisitor() {}
void Profile(llvm::FoldingSetNodeID &ID) const override {
static int X = 0;
ID.AddPointer(&X);
}
PDP VisitNode(const ExplodedNode *N,
#if LLVM_VERSION_MAJOR <= 8
const ExplodedNode *PrevN,
#endif
BugReporterContext &BRC,
BugReport &BR) override;
};
class GCValueBugVisitor
#if LLVM_VERSION_MAJOR >= 7
: public BugReporterVisitor {
#else
: public BugReporterVisitorImpl<GCValueBugVisitor> {
#endif
protected:
SymbolRef Sym;
public:
GCValueBugVisitor(SymbolRef S) : Sym(S) {}
void Profile(llvm::FoldingSetNodeID &ID) const override {
static int X = 0;
ID.AddPointer(&X);
ID.AddPointer(Sym);
}
PDP ExplainNoPropagation(
const ExplodedNode *N, PathDiagnosticLocation Pos, BugReporterContext &BRC, BugReport &BR);
PDP ExplainNoPropagationFromExpr(const clang::Expr *FromWhere,
const ExplodedNode *N, PathDiagnosticLocation Pos, BugReporterContext &BRC, BugReport &BR);
PDP VisitNode(const ExplodedNode *N,
#if LLVM_VERSION_MAJOR <= 8
const ExplodedNode *PrevN,
#endif
BugReporterContext &BRC,
BugReport &BR) override;
};
};
}
REGISTER_TRAIT_WITH_PROGRAMSTATE(GCDepth, unsigned)
REGISTER_TRAIT_WITH_PROGRAMSTATE(GCDisabledAt, unsigned)
REGISTER_TRAIT_WITH_PROGRAMSTATE(SafepointDisabledAt, unsigned)
REGISTER_TRAIT_WITH_PROGRAMSTATE(MayCallSafepoint, bool)
REGISTER_MAP_WITH_PROGRAMSTATE(GCValueMap, SymbolRef, GCChecker::ValueState)
REGISTER_MAP_WITH_PROGRAMSTATE(GCRootMap, const MemRegion *, GCChecker::RootState)
template <typename callback>
SymbolRef GCChecker::walkToRoot(callback f, const ProgramStateRef &State, const MemRegion *Region)
{
if (!Region)
return nullptr;
while (true) {
const SymbolicRegion *SR = Region->getSymbolicBase();
if (!SR) {
return nullptr;
}
SymbolRef Sym = SR->getSymbol();
const ValueState *OldVState = State->get<GCValueMap>(Sym);
if (f(Sym, OldVState)) {
if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(Sym)) {
Region = SRV->getRegion();
continue;
} else if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(Sym)) {
Region = SD->getRegion();
continue;
}
return nullptr;
}
return Sym;
}
}
namespace Helpers {
static SymbolRef trySuperRegion(SValExplainer &Ex, ProgramStateRef State, SVal Val) {
const MemRegion *R = Val.getAsRegion();
const SubRegion *SR = R->getAs<SubRegion>();
return SR ? State->getSVal(SR->getSuperRegion()).getAsSymbol() : nullptr;
}
static const VarRegion *walk_back_to_global_VR(const MemRegion *Region) {
if (!Region)
return nullptr;
while (true) {
const VarRegion *VR = Region->getAs<VarRegion>();
if (VR && VR->getDecl()->hasGlobalStorage()) {
return VR;
}
const SymbolicRegion *SymR = Region->getAs<SymbolicRegion>();
if (SymR) {
const SymbolRegionValue *SymRV = dyn_cast<SymbolRegionValue>(SymR->getSymbol());
if (!SymRV) {
const SymbolDerived *SD = dyn_cast<SymbolDerived>(SymR->getSymbol());
if (SD) {
Region = SD->getRegion();
continue;
}
break;
}
Region = SymRV->getRegion();
continue;
}
const SubRegion *SR = Region->getAs<SubRegion>();
if (!SR)
break;
Region = SR->getSuperRegion();
}
return nullptr;
}
}
PDP GCChecker::GCBugVisitor::VisitNode(
const ExplodedNode *N,
#if LLVM_VERSION_MAJOR <= 8
const ExplodedNode *,
#endif
BugReporterContext &BRC, BugReport &BR) {
const ExplodedNode *PrevN = N->getFirstPred();
unsigned NewGCDepth = N->getState()->get<GCDepth>();
unsigned OldGCDepth = PrevN->getState()->get<GCDepth>();
if (NewGCDepth != OldGCDepth) {
PathDiagnosticLocation Pos(PathDiagnosticLocation::getStmt(N),
BRC.getSourceManager(),
N->getLocationContext());
return MakePDP(Pos, "GC frame changed here.");
}
unsigned NewGCState = N->getState()->get<GCDisabledAt>();
unsigned OldGCState = PrevN->getState()->get<GCDisabledAt>();
if (false /*NewGCState != OldGCState*/) {
PathDiagnosticLocation Pos(PathDiagnosticLocation::getStmt(N),
BRC.getSourceManager(),
N->getLocationContext());
return MakePDP(Pos, "GC enabledness changed here.");
}
return nullptr;
}
PDP GCChecker::GCValueBugVisitor::ExplainNoPropagationFromExpr(const clang::Expr *FromWhere,
const ExplodedNode *N, PathDiagnosticLocation Pos, BugReporterContext &BRC, BugReport &BR)
{
const MemRegion *Region = N->getState()->getSVal(FromWhere, N->getLocationContext()).getAsRegion();
SValExplainer Ex(BRC.getASTContext());
SymbolRef Parent = walkToRoot([&](SymbolRef Sym, const ValueState *OldVState) {
return !OldVState;
},
N->getState(), Region);
if (!Parent && Region) {
Parent = walkToRoot([&](SymbolRef Sym, const ValueState *OldVState) {
return !OldVState;
},
N->getState(), N->getState()->getSVal(Region).getAsRegion());
}
if (!Parent) {
// May have been derived from a global. Check that
const VarRegion *VR = Helpers::walk_back_to_global_VR(Region);
if (VR) {
BR.addNote("Derivation root was here", PathDiagnosticLocation::create(VR->getDecl(), BRC.getSourceManager()));
const VarDecl *VD = VR->getDecl();
if (VD) {
if (!declHasAnnotation(VD,"julia_globally_rooted")) {
return MakePDP(Pos, "Argument value was derived from unrooted global. May need GLOBALLY_ROOTED annotation.");
} else if (!isGCTrackedType(VD->getType())) {
return MakePDP(Pos, "Argument value was derived global with untracked type. You may want to update the checker's type list");
}
}
return MakePDP(Pos, "Argument value was derived from global, but the checker did not propagate the root. This may be a bug");
}
return MakePDP(Pos, "Could not propagate root. Argument value was untracked.");
}
const ValueState *ValS = N->getState()->get<GCValueMap>(Parent);
assert(ValS);
if (ValS->isPotentiallyFreed()) {
BR.addVisitor(llvm::make_unique<GCValueBugVisitor>(Parent));
return MakePDP(Pos, "Root not propagated because it may have been freed. Tracking.");
} else if (ValS->isRooted()) {
BR.addVisitor(llvm::make_unique<GCValueBugVisitor>(Parent));
return MakePDP(Pos, "Root was not propagated due to a bug. Tracking base value.");
} else {
BR.addVisitor(llvm::make_unique<GCValueBugVisitor>(Parent));
return MakePDP(Pos, "No Root to propagate. Tracking.");
}
}
PDP GCChecker::GCValueBugVisitor::ExplainNoPropagation(
const ExplodedNode *N, PathDiagnosticLocation Pos, BugReporterContext &BRC, BugReport &BR)
{
if (N->getLocation().getAs<StmtPoint>()) {
const clang::Stmt *TheS = N->getLocation().castAs<StmtPoint>().getStmt();
const clang::CallExpr *CE = dyn_cast<CallExpr>(TheS);
const clang::MemberExpr *ME = dyn_cast<MemberExpr>(TheS);
if (ME)
return ExplainNoPropagationFromExpr(ME->getBase(), N, Pos, BRC, BR);
const clang::ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(TheS);
if (ASE)
return ExplainNoPropagationFromExpr(ASE->getLHS(), N, Pos, BRC, BR);
if (!CE)
return nullptr;
const clang::FunctionDecl *FD = CE->getDirectCallee();
if (!FD)
return nullptr;
for (unsigned i = 0; i < FD->getNumParams(); ++i) {
if (!declHasAnnotation(FD->getParamDecl(i), "julia_propagates_root"))
continue;
return ExplainNoPropagationFromExpr(CE->getArg(i), N, Pos, BRC, BR);
}
return nullptr;
}
return nullptr;
}
PDP GCChecker::GCValueBugVisitor::VisitNode(
const ExplodedNode *N,
#if LLVM_VERSION_MAJOR <= 8
const ExplodedNode *,
#endif
BugReporterContext &BRC, BugReport &BR) {
const ExplodedNode *PrevN = N->getFirstPred();
const ValueState *NewValueState = N->getState()->get<GCValueMap>(Sym);
const ValueState *OldValueState = PrevN->getState()->get<GCValueMap>(Sym);
const Stmt *Stmt = PathDiagnosticLocation::getStmt(N);
PathDiagnosticLocation Pos;
if (Stmt)
Pos = PathDiagnosticLocation{Stmt,
BRC.getSourceManager(),
N->getLocationContext()};
else
Pos = PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
BRC.getSourceManager());
if (!NewValueState)
return nullptr;
if (!OldValueState) {
if (NewValueState->isRooted()) {
return MakePDP(Pos, "Started tracking value here (root was inherited).");
} else {
if (NewValueState->FD) {
bool isFunctionSafepoint = !isFDAnnotatedNotSafepoint(NewValueState->FD);
bool maybeUnrooted = declHasAnnotation(NewValueState->PVD, "julia_maybe_unrooted");
assert(isFunctionSafepoint || maybeUnrooted);
Pos = PathDiagnosticLocation{NewValueState->PVD,
BRC.getSourceManager()};
if (!isFunctionSafepoint)
return MakePDP(Pos, "Argument not rooted, because function was annotated as not a safepoint");
else
return MakePDP(Pos, "Argument was annotated as MAYBE_UNROOTED.");
} else {
PDP Diag = ExplainNoPropagation(N, Pos, BRC, BR);
if (Diag)
return Diag;
return MakePDP(Pos, "Started tracking value here.");
}
}
}
if (!OldValueState->isUntracked() &&
NewValueState->isUntracked()) {
PDP Diag = ExplainNoPropagation(N, Pos, BRC, BR);
if (Diag)
return Diag;
return MakePDP(Pos, "Created untracked derivative.");
} else if (NewValueState->isPotentiallyFreed() &&
OldValueState->isJustAllocated()) {
// std::make_shared< in later LLVM
return MakePDP(Pos, "Value may have been GCed here.");
} else if (NewValueState->isPotentiallyFreed() &&
!OldValueState->isPotentiallyFreed()) {
// std::make_shared< in later LLVM
return MakePDP(Pos, "Value may have been GCed here (though I don't know why).");
} else if (NewValueState->isRooted() &&
OldValueState->isJustAllocated()) {
return MakePDP(Pos, "Value was rooted here.");
} else if (!NewValueState->isRooted() &&
OldValueState->isRooted()) {
return MakePDP(Pos, "Root was released here.");
} else if (NewValueState->RootDepth !=
OldValueState->RootDepth) {
return MakePDP(Pos, "Rooting Depth changed here.");
}
return nullptr;
}
template <typename callback>
void GCChecker::report_error(callback f, CheckerContext &C, const char *message) const
{
// Generate an error node.
ExplodedNode *N = C.generateErrorNode();
if (!N)
return;
if (!BT)
BT.reset(new BugType(this, "Invalid GC thingy",
categories::LogicError));
auto Report = llvm::make_unique<BugReport>(*BT, message, N);
Report->addVisitor(llvm::make_unique<GCBugVisitor>());
f(Report.get());
C.emitReport(std::move(Report));
}
void GCChecker::report_value_error(CheckerContext &C, SymbolRef Sym, const char *message, SourceRange range) const
{
// Generate an error node.
ExplodedNode *N = C.generateErrorNode();
if (!N)
return;
if (!BT)
BT.reset(new BugType(this, "Invalid GC thingy",
categories::LogicError));
auto Report = llvm::make_unique<BugReport>(*BT, message, N);
Report->addVisitor(llvm::make_unique<GCValueBugVisitor>(Sym));
Report->addVisitor(llvm::make_unique<GCBugVisitor>());
Report->addVisitor(llvm::make_unique<ConditionBRVisitor>());
if (!range.isInvalid()) {
Report->addRange(range);
}
C.emitReport(std::move(Report));
}
bool GCChecker::gcEnabledHere(CheckerContext &C) const {
unsigned disabledAt = C.getState()->get<GCDisabledAt>();
return disabledAt == (unsigned)-1;
}
bool GCChecker::safepointEnabledHere(CheckerContext &C) const {
unsigned disabledAt = C.getState()->get<SafepointDisabledAt>();
return disabledAt == (unsigned)-1;
}
bool GCChecker::propagateArgumentRootedness(CheckerContext &C, ProgramStateRef &State) const {
const auto *LCtx = C.getLocationContext();
const auto *Site = cast<StackFrameContext>(LCtx)->getCallSite();
if (!Site)
return false;
const auto *FD = dyn_cast<FunctionDecl>(LCtx->getDecl());
if (!FD)
return false;
const auto *CE = dyn_cast<CallExpr>(Site);
if (!CE)
return false;
//FD->dump();
bool Change = false;
int idx = 0;
SValExplainer Ex(C.getASTContext());
for (const auto P : FD->parameters()) {
if (!isGCTrackedType(P->getType())) {
continue;
}
auto Arg = State->getSVal(CE->getArg(idx++), LCtx->getParent());
SymbolRef ArgSym = walkToRoot([](SymbolRef Sym, const ValueState *OldVState) {return !OldVState;},
State, Arg.getAsRegion());
if (!ArgSym) {
continue;
}
const ValueState *ValS = State->get<GCValueMap>(ArgSym);
if (!ValS) {
report_error([&](BugReport *Report) {
Report->addNote(
"Tried to find root for this parameter in inlined call",
PathDiagnosticLocation::create(P, C.getSourceManager()));
}, C, "Missed allocation of parameter");
continue;
}
auto Param = State->getLValue(P, LCtx);
SymbolRef ParamSym = State->getSVal(Param).getAsSymbol();
if (!ParamSym) {
continue;
}
if (isGloballyRootedType(P->getType())) {
State = State->set<GCValueMap>(ParamSym, ValueState::getRooted(nullptr, -1));
Change = true;
continue;
}
State = State->set<GCValueMap>(ParamSym, *ValS);
Change = true;
}
return Change;
}
void GCChecker::checkBeginFunction(CheckerContext &C) const {
// Consider top-level argument values rooted, unless an annotation says otherwise
const auto *LCtx = C.getLocationContext();
const auto *FD = dyn_cast<FunctionDecl>(LCtx->getDecl());
if (!FD)
return;
ProgramStateRef State = C.getState();
bool Change = false;
if (C.inTopFrame()) {
State = State->set<GCDisabledAt>((unsigned)-1);
State = State->set<SafepointDisabledAt>((unsigned)-1);
Change = true;
}
if (State->get<GCDisabledAt>() == (unsigned)-1) {
if (declHasAnnotation(FD, "julia_gc_disabled")) {
State = State->set<GCDisabledAt>(C.getStackFrame()->getIndex());
Change = true;
}
}
if (State->get<SafepointDisabledAt>() == (unsigned)-1 && isFDAnnotatedNotSafepoint(FD))
{
State = State->set<SafepointDisabledAt>(C.getStackFrame()->getIndex());
Change = true;
}
if (!C.inTopFrame())
{
if (propagateArgumentRootedness(C, State) || Change)
C.addTransition(State);
return;
}
SValExplainer Ex(C.getASTContext());
for (const auto P : FD->parameters()) {
if (declHasAnnotation(P, "julia_require_rooted_slot")) {
auto Param = State->getLValue(P, LCtx);
const MemRegion *Root = State->getSVal(Param).getAsRegion();
State = State->set<GCRootMap>(Root,
RootState::getRoot(-1));
} else if (isGCTrackedType(P->getType())) {
auto Param = State->getLValue(P, LCtx);
SymbolRef AssignedSym = State->getSVal(Param).getAsSymbol();
if (!AssignedSym)
continue;
assert(AssignedSym);
State = State->set<GCValueMap>(AssignedSym,
ValueState::getForArgument(FD, P));
Change = true;
}
}
if (Change) {
C.addTransition(State);
}
}
#if LLVM_VERSION_MAJOR >= 7
void GCChecker::checkEndFunction(const clang::ReturnStmt* RS, CheckerContext &C) const {
#else
void GCChecker::checkEndFunction(CheckerContext &C) const {
#endif
ProgramStateRef State = C.getState();
bool Changed = false;
if (State->get<GCDisabledAt>() == C.getStackFrame()->getIndex())
{
State = State->set<GCDisabledAt>((unsigned)-1);
Changed = true;
}
if (State->get<SafepointDisabledAt>() == C.getStackFrame()->getIndex()) {
State = State->set<SafepointDisabledAt>((unsigned)-1);
Changed = true;
}
if (Changed)
C.addTransition(State);
if (!C.inTopFrame())
return;
if (C.getState()->get<GCDepth>() > 0)
report_error(C, "Non-popped GC frame present at end of function");
}
bool GCChecker::declHasAnnotation(const clang::Decl *D, const char *which) {
for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
if (Ann->getAnnotation() == which)
return true;
}
return false;
}
bool GCChecker::isFDAnnotatedNotSafepoint(const clang::FunctionDecl *FD) {
return declHasAnnotation(FD, "julia_not_safepoint");
}
bool GCChecker::isBundleOfGCValues(QualType QT) const {
return isJuliaType([](StringRef Name) {
if (Name.endswith_lower("typemap_intersection_env"))
return true;
return false;
}, QT);
}
bool GCChecker::isGCTrackedType(QualType QT) {
return isValueCollection(QT) || isJuliaType([](StringRef Name) {
if (Name.endswith_lower("jl_value_t") ||
Name.endswith_lower("jl_svec_t") ||
Name.endswith_lower("jl_sym_t") ||
Name.endswith_lower("jl_expr_t") ||
Name.endswith_lower("jl_code_info_t") ||
Name.endswith_lower("jl_array_t") ||
Name.endswith_lower("jl_method_t") ||
Name.endswith_lower("jl_method_instance_t") ||
Name.endswith_lower("jl_tupletype_t") ||
Name.endswith_lower("jl_datatype_t") ||
Name.endswith_lower("jl_typemap_entry_t") ||
Name.endswith_lower("jl_typemap_level_t") ||
Name.endswith_lower("jl_typename_t") ||
Name.endswith_lower("jl_module_t") ||
Name.endswith_lower("jl_tupletype_t") ||
Name.endswith_lower("jl_gc_tracked_buffer_t") ||
Name.endswith_lower("jl_tls_states_t") ||
Name.endswith_lower("jl_binding_t") ||
Name.endswith_lower("jl_ordereddict_t") ||
Name.endswith_lower("jl_tvar_t") ||
Name.endswith_lower("jl_typemap_t") ||
Name.endswith_lower("jl_unionall_t") ||
Name.endswith_lower("jl_methtable_t") ||
Name.endswith_lower("jl_cgval_t") ||
Name.endswith_lower("jl_codectx_t") ||
Name.endswith_lower("jl_ast_context_t") ||
Name.endswith_lower("jl_code_instance_t") ||
Name.endswith_lower("jl_excstack_t") ||
Name.endswith_lower("jl_task_t") ||
Name.endswith_lower("jl_uniontype_t") ||
// Probably not technically true for these, but let's allow it
Name.endswith_lower("typemap_intersection_env") ||
Name.endswith_lower("interpreter_state") ||
Name.endswith_lower("jl_typeenv_t") ||
Name.endswith_lower("jl_stenv_t") ||
Name.endswith_lower("jl_varbinding_t") ||
Name.endswith_lower("set_world") ||
Name.endswith_lower("jl_codectx_t"))
{
return true;
}
return false;
},
QT);
}
bool GCChecker::isGloballyRootedType(QualType QT) const {
return isJuliaType([](StringRef Name) {
return Name.endswith_lower("jl_sym_t");
}, QT);
}
bool GCChecker::isSafepoint(const CallEvent &Call) const
{
bool isCalleeSafepoint = true;
if (Call.isGlobalCFunction("malloc") ||
Call.isGlobalCFunction("memcpy") ||
Call.isGlobalCFunction("memset") ||
Call.isGlobalCFunction("memcmp") ||
Call.isGlobalCFunction("mmap") ||
Call.isGlobalCFunction("munmap") ||
Call.isGlobalCFunction("mprotect") ||
Call.isGlobalCFunction("madvise") ||
Call.isGlobalCFunction("write") ||
Call.isGlobalCFunction("vasprintf") ||
Call.isGlobalCFunction("strrchr") ||
Call.isGlobalCFunction("free") ||
Call.isGlobalCFunction("__assert_fail") ||
Call.isGlobalCFunction("fflush") ||
Call.isGlobalCFunction("__isnan") ||
Call.isGlobalCFunction("__isnanf"))
{
isCalleeSafepoint = false;
} else {
auto *Decl = Call.getDecl();
const DeclContext *DC = Decl ? Decl->getDeclContext() : nullptr;
while (DC) {
// Anything in llvm or std is not a safepoint
if (const NamespaceDecl *NDC = dyn_cast<NamespaceDecl>(DC))
if (NDC->getName() == "llvm" || NDC->getName() == "std")
return false;
DC = DC->getParent();
}
const FunctionDecl *FD = Decl ? Decl->getAsFunction() : nullptr;
if (!Decl || !FD) {
const clang::Expr *Callee = dyn_cast<CallExpr>(Call.getOriginExpr())->getCallee();
if (const TypedefType *TDT = dyn_cast<TypedefType>(Callee->getType())) {
isCalleeSafepoint = !declHasAnnotation(TDT->getDecl(), "julia_not_safepoint");
}
} else if (FD) {
if (FD->getBuiltinID() != 0)
isCalleeSafepoint = false;
else if ((FD->getName().startswith_lower("uv_") ||
FD->getName().startswith_lower("unw_") ||
FD->getName().startswith("_U")) &&
FD->getName() != "uv_run")
isCalleeSafepoint = false;
else
isCalleeSafepoint = !isFDAnnotatedNotSafepoint(FD);
}
}
return isCalleeSafepoint;
}
bool GCChecker::processPotentialSafepoint(const CallEvent &Call, CheckerContext &C, ProgramStateRef &State) const
{
if (!isSafepoint(Call))
return false;
bool DidChange = false;
SValExplainer Ex(C.getASTContext());
if (!gcEnabledHere(C))
return false;
const Decl *D = Call.getDecl();
const FunctionDecl *FD = D ? D->getAsFunction() : nullptr;
SymbolRef SpeciallyRootedSymbol = nullptr;
if (FD) {
for (unsigned i = 0; i < FD->getNumParams(); ++i) {
QualType ParmType = FD->getParamDecl(i)->getType();
if (declHasAnnotation(FD->getParamDecl(i), "julia_temporarily_roots")) {
if (ParmType->isPointerType() && ParmType->getPointeeType()->isPointerType() &&
isGCTrackedType(ParmType->getPointeeType())) {
// This is probably an out parameter. Find the value it refers to now.
SVal Loaded = State->getSVal(Call.getArgSVal(i).getAs<Loc>().getValue());
SpeciallyRootedSymbol = Loaded.getAsSymbol();
continue;
}
SVal Test = Call.getArgSVal(i);
// Walk backwards to find the symbol that we're tracking for this
// value
const MemRegion *Region = Test.getAsRegion();
SpeciallyRootedSymbol = walkToRoot([&](SymbolRef Sym, const ValueState *OldVState) {
return !OldVState;
}, State, Region);
break;
}
}
}
// Symbolically free all unrooted values.
GCValueMapTy AMap = State->get<GCValueMap>();
for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
if (I.getData().isJustAllocated()) {
if (SpeciallyRootedSymbol == I.getKey())
continue;
State = State->set<GCValueMap>(I.getKey(), ValueState::getFreed());
DidChange = true;
}
}
return DidChange;
}
const GCChecker::ValueState *GCChecker::getValStateForRegion(ASTContext &AstC,
const ProgramStateRef &State, const MemRegion *Region, bool Debug) {
if (!Region)
return nullptr;
SValExplainer Ex(AstC);
SymbolRef Sym = walkToRoot([&](SymbolRef Sym, const ValueState *OldVState) {
return !OldVState || !OldVState->isRooted();
},
State, Region);
if (!Sym)
return nullptr;
return State->get<GCValueMap>(Sym);
}
bool GCChecker::processArgumentRooting(const CallEvent &Call, CheckerContext &C, ProgramStateRef &State) const {
auto *Decl = Call.getDecl();
const FunctionDecl *FD = Decl ? Decl->getAsFunction() : nullptr;
if (!FD)
return false;
const MemRegion *RootingRegion = nullptr;
SymbolRef RootedSymbol = nullptr;
for (unsigned i = 0; i < FD->getNumParams(); ++i) {
if (declHasAnnotation(FD->getParamDecl(i), "julia_rooting_argument")) {
RootingRegion = Call.getArgSVal(i).getAsRegion();
} else if (declHasAnnotation(FD->getParamDecl(i), "julia_rooted_argument")) {
RootedSymbol = Call.getArgSVal(i).getAsSymbol();
}
}
if (!RootingRegion || !RootedSymbol)
return false;
SValExplainer Ex(C.getASTContext());
const ValueState *OldVState = getValStateForRegion(C.getASTContext(), State, RootingRegion);
if (!OldVState)
return false;
State = State->set<GCValueMap>(RootedSymbol, *OldVState);
return true;
}
bool GCChecker::processAllocationOfResult(const CallEvent &Call, CheckerContext &C, ProgramStateRef &State) const {
QualType QT = Call.getResultType();
if (!isGCTrackedType(QT))
return false;
if (!Call.getOriginExpr()) {
return false;
}
SymbolRef Sym = Call.getReturnValue().getAsSymbol();
SValExplainer Ex(C.getASTContext());
if (!Sym) {
SVal S = C.getSValBuilder().conjureSymbolVal(Call.getOriginExpr(),
C.getLocationContext(), QT, C.blockCount());
State = State->BindExpr(Call.getOriginExpr(), C.getLocationContext(), S);
Sym = S.getAsSymbol();
}
if (isGloballyRootedType(QT))
State = State->set<GCValueMap>(Sym, ValueState::getRooted(nullptr, -1));
else {
const ValueState *ValS = State->get<GCValueMap>(Sym);
ValueState NewVState = ValueState::getAllocated();
if (ValS) {
// If the call was inlined, we may have accidentally killed the return
// value above. Revive it here.
const ValueState *PrevValState = C.getState()->get<GCValueMap>(Sym);
if (!ValS->isPotentiallyFreed() || (PrevValState && PrevValState->isPotentiallyFreed())) {
return false;
}
NewVState = *PrevValState;
}
auto *Decl = Call.getDecl();
const FunctionDecl *FD = Decl ? Decl->getAsFunction() : nullptr;
if (FD) {
if (declHasAnnotation(FD, "julia_globally_rooted")) {
NewVState = ValueState::getRooted(nullptr, -1);
} else {
// Special case for jl_box_ functions which have value-dependent
// global roots.
StringRef FDName = FD->getDeclName().isIdentifier() ? FD->getName() : "";
if (FDName.startswith_lower("jl_box_")) {
SVal Arg = Call.getArgSVal(0);
if (auto CI = Arg.getAs<nonloc::ConcreteInt>()) {
const llvm::APSInt &Value = CI->getValue();
bool GloballyRooted = false;
const int64_t NBOX_C = 1024;
if (FDName.startswith_lower("jl_box_u")) {
if (Value < NBOX_C) {
GloballyRooted = true;
}
} else {
if (-NBOX_C/2 < Value && Value < (NBOX_C - NBOX_C/2)) {
GloballyRooted = true;
}
}
if (GloballyRooted) {
NewVState = ValueState::getRooted(nullptr, -1);
}
}
} else {
for (unsigned i = 0; i < FD->getNumParams(); ++i) {
if (declHasAnnotation(FD->getParamDecl(i), "julia_propagates_root")) {
SVal Test = Call.getArgSVal(i);
// Walk backwards to find the region that roots this value
const MemRegion *Region = Test.getAsRegion();
const ValueState *OldVState = getValStateForRegion(C.getASTContext(), State, Region);
if (OldVState)
NewVState = *OldVState;
break;
}
}
}
}
}
State = State->set<GCValueMap>(Sym, NewVState);
}
return true;
}
void GCChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
ProgramStateRef State = C.getState();
bool didChange = processArgumentRooting(Call, C, State);
didChange |= processPotentialSafepoint(Call, C, State);
didChange |= processAllocationOfResult(Call, C, State);
if (didChange)
C.addTransition(State);
}
// Implicitly root values that were casted to globally rooted values
void GCChecker::checkPostStmt(const CStyleCastExpr *CE, CheckerContext &C) const {
if (!isGloballyRootedType(CE->getTypeAsWritten()))
return;
SymbolRef Sym = C.getSVal(CE).getAsSymbol();
if (!Sym)
return;
C.addTransition(C.getState()->set<GCValueMap>(Sym, ValueState::getRooted(nullptr, -1)));
}
SymbolRef GCChecker::getSymbolForResult(const Expr *Result, const ValueState *OldValS, ProgramStateRef &State, CheckerContext &C) const
{
auto ValLoc = C.getSVal(Result).getAs<Loc>();
if (!ValLoc) {
return nullptr;
}
SVal Loaded = State->getSVal(*ValLoc);
SValExplainer Ex(C.getASTContext());
if (Loaded.isUnknown()) {
QualType QT = Result->getType();
if (!QT->isPointerType())
return nullptr;
if (OldValS || GCChecker::isGCTrackedType(QT)) {
Loaded = C.getSValBuilder().conjureSymbolVal(nullptr, Result, C.getLocationContext(),
Result->getType(),
C.blockCount());
State = State->bindLoc(*ValLoc, Loaded, C.getLocationContext());