-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLifetimePsetBuilder.cpp
More file actions
1916 lines (1670 loc) · 65.3 KB
/
LifetimePsetBuilder.cpp
File metadata and controls
1916 lines (1670 loc) · 65.3 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
//=- LifetimePsetBuilder.cpp - Diagnose lifetime violations -*- C++ -*-=======//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "cppsafe/lifetime/LifetimePsetBuilder.h"
#include "cppsafe/lifetime/Debug.h"
#include "cppsafe/lifetime/Lifetime.h"
#include "cppsafe/lifetime/LifetimeAttrData.h"
#include "cppsafe/lifetime/LifetimePset.h"
#include "cppsafe/lifetime/LifetimeTypeCategory.h"
#include "cppsafe/lifetime/contract/Annotation.h"
#include "cppsafe/lifetime/contract/CallVisitor.h"
#include "cppsafe/lifetime/type/Aggregate.h"
#include "cppsafe/util/assert.h"
#include "cppsafe/util/type.h"
#include <clang/AST/Attr.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclBase.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/OperationKinds.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/StmtVisitor.h>
#include <clang/AST/Type.h>
#include <clang/Analysis/CFG.h>
#include <clang/Basic/LLVM.h>
#include <clang/Basic/Lambda.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Lex/Lexer.h>
#include <llvm/ADT/APInt.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/STLFunctionalExtras.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/ADT/StringSwitch.h>
#include <llvm/Support/ErrorHandling.h>
#include <llvm/Support/raw_ostream.h>
#include <functional>
#include <map>
#include <optional>
#include <utility>
#include <vector>
namespace clang::lifetime {
namespace {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage): just for convevience
#define VERBOSE_DEBUG 0
#if VERBOSE_DEBUG
#define DBG(x) llvm::errs() << x
#else
#define DBG(x)
#endif
inline bool isPointer(const Expr* E)
{
auto TC = classifyTypeCategory(E->getType());
return TC == TypeCategory::Pointer;
}
/// Collection of methods to update/check PSets from statements/expressions
/// Conceptually, for each Expr where Expr::isLValue() is true,
/// we put an entry into the RefersTo map, which contains the set
/// of Variables that an lvalue might refer to, e.g.
/// RefersTo(var) = {var}
/// RefersTo(*p) = pset(p)
/// RefersTo(a = b) = {a}
/// RefersTo(a, b) = {b}
///
/// For every expression whose Type is a Pointer or an Owner,
/// we also track the pset (points-to set), e.g.
/// pset(&v) = {v}
///
/// In return statement, DeclRefExpr, LValueToRValueCast will move RefersTo to PSetsOfExpr
class PSetsBuilder final : public ConstStmtVisitor<PSetsBuilder, void>, public PSBuilder {
const FunctionDecl* AnalyzedFD;
LifetimeReporterBase& Reporter;
ASTContext& ASTCtxt;
/// Returns true if the first argument is implicitly convertible
/// into the second argument.
IsConvertibleTy IsConvertible;
/// psets of all memory locations, which are identified
/// by their non-reference variable declaration or
/// MaterializedTemporaryExpr plus (optional) FieldDecls.
PSetsMap& PMap;
PSetsMap& ExprMemberPMap;
std::map<const Expr*, PSet>& PSetsOfExpr;
std::map<const Expr*, PSet>& RefersTo;
const CFGBlock* CurrentBlock = nullptr;
public:
/// Ignore parentheses and most implicit casts.
/// Does not go through implicit cast that convert a literal into a pointer,
/// because there the type category changes.
/// Does not ignore LValueToRValue casts by default, because they
/// move psets from RefersTo into PsetOfExpr.
/// Does not ignore MaterializeTemporaryExpr as Expr::IgnoreParenImpCasts
/// would.
// NOLINTBEGIN(readability-else-after-return)
const Expr* ignoreTransparentExprs(const Expr* E, bool IgnoreLValueToRValue = false) const override
{
while (true) {
E = E->IgnoreParens();
if (const auto* P = dyn_cast<CastExpr>(E)) {
switch (P->getCastKind()) {
case CK_BitCast:
case CK_LValueBitCast:
case CK_IntegralToPointer:
case CK_NullToPointer:
case CK_ArrayToPointerDecay:
case CK_Dynamic:
return E;
case CK_LValueToRValue:
if (!IgnoreLValueToRValue) {
return E;
}
break;
default:
break;
}
E = P->getSubExpr();
continue;
} else if (const auto* C = dyn_cast<ExprWithCleanups>(E)) {
E = C->getSubExpr();
continue;
} else if (const auto* C = dyn_cast<OpaqueValueExpr>(E)) {
E = C->getSourceExpr();
continue;
} else if (const auto* C = dyn_cast<UnaryOperator>(E)) {
if (C->getOpcode() == UO_Extension) {
E = C->getSubExpr();
continue;
}
} else if (const auto* C = dyn_cast<CXXBindTemporaryExpr>(E)) {
E = C->getSubExpr();
continue;
}
return E;
}
// NOLINTEND(readability-else-after-return)
}
bool isIgnoredStmt(const Stmt* S)
{
const Expr* E = dyn_cast<Expr>(S);
return E && ignoreTransparentExprs(E) != E;
}
void VisitStringLiteral(const StringLiteral* SL) { setPSet(SL, PSet::globalVar(false)); }
void VisitPredefinedExpr(const PredefinedExpr* E) { setPSet(E, PSet::globalVar(false)); }
void VisitDeclStmt(const DeclStmt* DS)
{
for (const auto* DeclIt : DS->decls()) {
if (const auto* VD = dyn_cast<VarDecl>(DeclIt)) {
VisitVarDecl(VD);
}
}
}
void VisitCXXNewExpr(const CXXNewExpr* E)
{
Reporter.warnNakedNewDelete(E->getSourceRange());
setPSet(E, PSet::globalVar(false));
}
void VisitCXXDeleteExpr(const CXXDeleteExpr* DE)
{
Reporter.warnNakedNewDelete(DE->getSourceRange());
if (hasPSet(DE->getArgument())) {
const PSet PS = getPSet(DE->getArgument());
auto PSWithoutNull = PS;
PSWithoutNull.removeNull();
if (!checkPSetValidity(PSWithoutNull, DE->getSourceRange())) {
return;
}
// TODO: add strict mode check
for (const auto& Var : PS.vars()) {
// TODO: diagnose if we are deleting the buffer of on owner?
invalidateVar(Var, InvalidationReason::deleted(DE->getSourceRange(), CurrentBlock));
}
setPSet(getPSet(DE->getArgument()->IgnoreImplicit()),
PSet::invalid(InvalidationReason::deleted(DE->getSourceRange(), CurrentBlock)), DE->getSourceRange());
}
}
void VisitAddrLabelExpr(const AddrLabelExpr* E) { setPSet(E, PSet::globalVar(false)); }
void VisitCXXDefaultInitExpr(const CXXDefaultInitExpr* E)
{
if (hasPSet(E)) {
setPSet(E, getPSet(E->getExpr()));
}
}
PSet varRefersTo(const Variable& V, SourceRange Range) const
{
// HACK for DecompositionDecl without reference
if (V.getType()->isReferenceType() || isa_and_present<DecompositionDecl>(V.asVarDecl())) {
auto P = getPSet(V);
if (checkPSetValidity(P, Range)) {
return P;
}
return {};
}
return PSet::singleton(V);
}
void VisitDeclRefExpr(const DeclRefExpr* DeclRef)
{
if (isa<FunctionDecl>(DeclRef->getDecl()) || DeclRef->refersToEnclosingVariableOrCapture()) {
setPSet(DeclRef, PSet::globalVar(false));
} else if (const auto* VD = dyn_cast<VarDecl>(DeclRef->getDecl())) {
setPSet(DeclRef, varRefersTo(VD, DeclRef->getSourceRange()));
} else if (const auto* B = dyn_cast<BindingDecl>(DeclRef->getDecl())) {
if (const auto* Var = B->getHoldingVar()) {
setPSet(DeclRef, getPSet(Var));
} else {
setPSet(DeclRef, derefPSet(varRefersTo(B, DeclRef->getSourceRange())));
}
} else if (const auto* FD = dyn_cast<FieldDecl>(DeclRef->getDecl())) {
Variable V = Variable::thisPointer(FD->getParent());
V.deref(); // *this
V.addFieldRef(FD); // this->field
setPSet(DeclRef, varRefersTo(V, DeclRef->getSourceRange()));
}
}
void VisitMemberExpr(const MemberExpr* ME)
{
const PSet BaseRefersTo = getPSet(ME->getBase());
// Make sure that derefencing a dangling pointer is diagnosed unless
// the member is a member function. In that case, the invalid
// base will be diagnosed in VisitCallExpr().
if (ME->getBase()->getType()->isPointerType() && !ME->hasPlaceholderType(BuiltinType::BoundMember)) {
checkPSetValidity(BaseRefersTo, ME->getSourceRange());
}
if (auto* FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
PSet Ret = BaseRefersTo;
Ret.addFieldRefIfTypeMatch(FD);
if (FD->getType()->isReferenceType()) {
// The field has reference type, apply the deref.
Ret = derefPSet(Ret);
if (!checkPSetValidity(Ret, ME->getSourceRange())) {
Ret = {};
}
}
setPSet(ME, Ret);
} else if (isa<VarDecl>(ME->getMemberDecl())) {
// A static data member of this class
setPSet(ME, PSet::globalVar(false));
}
}
void VisitArraySubscriptExpr(const ArraySubscriptExpr* E)
{
// By the bounds profile, ArraySubscriptExpr is only allowed on arrays
// (not on pointers).
if (!E->getBase()->IgnoreParenImpCasts()->getType()->isArrayType()) {
Reporter.warnPointerArithmetic(E->getSourceRange());
}
setPSet(E, getPSet(E->getBase()));
}
void VisitCXXThisExpr(const CXXThisExpr* E)
{
// ThisExpr is an RValue. It points to *this.
setPSet(E, PSet::singleton(Variable::thisPointer(E->getType()->getPointeeCXXRecordDecl()).deref()));
}
void VisitCXXTypeidExpr(const CXXTypeidExpr* E)
{
// The typeid expression is an lvalue expression which refers to an object
// with static storage duration, of the polymorphic type const
// std::type_info or of some type derived from it.
setPSet(E, PSet::globalVar());
}
void VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr* E)
{
// Non-type template parameters that are pointers must point to something
// static (because only addresses known at compiler time are allowed)
if (hasPSet(E)) {
setPSet(E, PSet::globalVar());
}
}
void VisitAbstractConditionalOperator(const AbstractConditionalOperator* E)
{
if (!hasPSet(E)) {
return;
}
// If the condition is trivially true/false, the corresponding branch
// will be pruned from the CFG and we will not find a pset of it.
// With AllowNonExisting, getPSet() will then return (unknown).
// Note that a pset could also be explicitly unknown to suppress
// further warnings after the first violation was diagnosed.
auto LHS = getPSet(E->getTrueExpr(), /*AllowNonExisting=*/true);
auto RHS = getPSet(E->getFalseExpr(), /*AllowNonExisting=*/true);
setPSet(E, LHS + RHS);
}
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr* E)
{
const PSet Singleton = PSet::singleton(E);
setPSet(E, Singleton);
if (classifyTypeCategory(E->getType()).isAggregate()) {
// [[types.aggr.init]]
handleAggregateCopy(E, E->getSubExpr(), *this);
return;
}
if (hasPSet(E->getSubExpr())) {
const auto TC = classifyTypeCategory(E->getSubExpr()->getType());
if (TC == TypeCategory::Owner) {
setPSet(Singleton, PSet::singleton(E, 1), E->getSourceRange());
} else {
setPSet(Singleton, getPSet(E->getSubExpr()), E->getSourceRange());
}
}
}
// T{};
// T t = {};
void VisitInitListExpr(const InitListExpr* I)
{
I = !I->isSemanticForm() ? I->getSemanticForm() : I;
const auto TC = classifyTypeCategory(I->getType());
// [[types.pointer.init.assign]]
if (TC.isPointer()) {
// TODO: Instead of assuming that the pset comes from the first argument
// use the same logic we have in call modelling.
if (I->getNumInits() == 1) {
setPSet(I, getPSet(I->getInit(0)));
return;
}
// HACK
// non-null non-record type is just for parameter contract inference
if (isNullableType(I->getType()) || !I->getType()->isRecordType()) {
setPSet(I, PSet::null(NullReason::defaultConstructed(I->getSourceRange(), CurrentBlock)));
} else {
// non-null pointer record type is defaulted to {global}
setPSet(I, PSet::globalVar());
}
return;
}
// [[types.aggr.init]]
if (TC.isAggregate()) {
handleAggregateInit(
Variable(I), I->getType()->getAsCXXRecordDecl(), I, CurrentBlock, I->getSourceRange(), *this);
// nonsense, just make handleAggregateCopy works
setPSet(I, PSet::singleton(Variable(I)));
return;
}
setPSet(I, {});
}
void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr* E)
{
// Appears for `T()` in a template specialisation, where
// T is a simple type.
if (E->getType()->isPointerType()) {
setPSet(E, PSet::null(NullReason::defaultConstructed(E->getSourceRange(), CurrentBlock)));
}
}
void VisitCastExpr(const CastExpr* E)
{
// Some casts are transparent, see IgnoreTransparentExprs()
switch (E->getCastKind()) {
case CK_BitCast:
case CK_LValueBitCast:
// Those casts are forbidden by the type profile
Reporter.warnUnsafeCast(E->getSourceRange());
setPSet(E, getPSet(E->getSubExpr()));
return;
case CK_Dynamic: {
auto P = getPSet(E->getSubExpr());
if (E->getType()->isPointerType()) {
const auto* ToType = E->getType()->getPointeeCXXRecordDecl();
const auto* FromType = E->getSubExpr()->getType()->getPointeeCXXRecordDecl();
if (ToType && FromType && ToType->isDerivedFrom(FromType)) {
P.addNull(NullReason::dynamicCastToDerived(E->getSourceRange(), CurrentBlock));
}
}
setPSet(E, P);
return;
}
case CK_IntegralToPointer:
// Those casts are forbidden by the type profile
Reporter.warnUnsafeCast(E->getSourceRange());
setPSet(E, {});
return;
case CK_ArrayToPointerDecay:
// Decaying an array into a pointer is like taking the address of the
// first array member. The result is a pointer to the array elements,
// which are '*array'.
setPSet(E, derefPSet(getPSet(E->getSubExpr())));
return;
case CK_NullToPointer:
setPSet(E, PSet::null(NullReason::nullptrConstant(E->getSourceRange(), CurrentBlock)));
return;
case CK_LValueToRValue:
// For L-values, the pset refers to the memory location,
// which in turn points to the pointee. For R-values,
// the pset just refers to the pointee.
if (hasPSet(E)) {
// vector<int*> vec; // pset(vec) = {*this}
// auto* p = vec.front();
if (isPointer(E)) {
auto P = getPSet(E->getSubExpr());
P.eraseIf([](const Variable& V) {
const auto Vt = V.getType();
return Vt.isNull() || !Vt->isPointerType();
});
setPSet(E, derefPSet(P));
return;
}
setPSet(E, derefPSet(getPSet(E->getSubExpr())));
}
return;
default:
llvm_unreachable("Should have been ignored in IgnoreTransparentExprs()");
return;
}
}
/// Returns true if all of the following is true
/// 1) BO is an addition,
/// 2) LHS is ImplicitCastExpr <ArrayToPointerDecay> of DeclRefExpr of array
/// type 3) RHS is IntegerLiteral 4) The value of the IntegerLiteral is
/// between 0 and the size of the array type
static bool isArrayPlusIndex(const BinaryOperator* BO)
{
if (BO->getOpcode() != BO_Add) {
return false;
}
auto* ImplCast = dyn_cast<ImplicitCastExpr>(BO->getLHS());
if (!ImplCast) {
return false;
}
if (ImplCast->getCastKind() != CK_ArrayToPointerDecay) {
return false;
}
auto* DeclRef = dyn_cast<DeclRefExpr>(ImplCast->getSubExpr());
if (!DeclRef) {
return false;
}
const auto* ArrayType = dyn_cast_or_null<ConstantArrayType>(DeclRef->getType()->getAsArrayTypeUnsafe());
if (!ArrayType) {
return false;
}
llvm::APInt ArrayBound = ArrayType->getSize();
auto* Integer = dyn_cast<IntegerLiteral>(BO->getRHS());
if (!Integer) {
return false;
}
llvm::APInt Offset = Integer->getValue();
if (Offset.isNegative()) {
return false;
}
// ule() comparison requires both APInt to have the same bit width.
if (ArrayBound.getBitWidth() > Offset.getBitWidth()) {
Offset = Offset.zext(ArrayBound.getBitWidth());
} else if (ArrayBound.getBitWidth() < Offset.getBitWidth()) {
ArrayBound = ArrayBound.zext(Offset.getBitWidth());
}
// We explicitly allow to form the pointer one element after the array
// to support the compiler-generated code for the end iterator in a
// for-range loop.
// TODO: this allows to form an invalid pointer, where we would not detect
// dereferencing.
return Offset.ule(ArrayBound);
}
void VisitBinaryOperator(const BinaryOperator* BO)
{
if (BO->getOpcode() == BO_Assign) {
// Owners usually are user defined types. We should see a function call.
// Do we need to handle raw pointers annotated as owners?
const auto TC = classifyTypeCategory(BO->getType());
if (TC.isPointer()) {
// This assignment updates a Pointer.
const SourceRange Range = BO->getRHS()->getSourceRange();
const PSet LHS = handlePointerAssign(BO->getLHS()->getType(), getPSet(BO->getRHS()), Range);
setPSet(getPSet(BO->getLHS()), LHS, Range);
}
setPSet(BO, getPSet(BO->getLHS()));
} else if (isArrayPlusIndex(BO)) { // NOLINT(bugprone-branch-clone)
setPSet(BO, getPSet(BO->getLHS()));
} else if (BO->getType()->isPointerType()) {
Reporter.warnPointerArithmetic(BO->getOperatorLoc());
const auto* LHS = BO->getLHS();
const auto* RHS = BO->getRHS();
// consider `++idx, ptr = x`
// consider `a.*memberptr()`
if (llvm::is_contained({ BO_Add, BO_AddAssign, BO_Sub, BO_SubAssign }, BO->getOpcode())) {
if (LHS->getType()->isPointerType()) {
setPSet(BO, getPSet(LHS));
} else {
setPSet(BO, getPSet(RHS));
}
} else {
setPSet(BO, {});
}
} else if (BO->isLValue() && BO->isCompoundAssignmentOp()) {
setPSet(BO, getPSet(BO->getLHS()));
} else if (BO->isLValue() && BO->getOpcode() == BO_Comma) {
setPSet(BO, getPSet(BO->getRHS()));
} else if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI) {
setPSet(BO, {}); // TODO, not specified in paper
}
}
void VisitUnaryOperator(const UnaryOperator* UO)
{
switch (UO->getOpcode()) {
case UO_AddrOf:
break;
case UO_Deref: {
auto PS = getPSet(UO->getSubExpr());
checkPSetValidity(PS, UO->getSourceRange());
setPSet(UO, PS);
return;
}
default:
// Workaround: detecting compiler generated AST node.
if (isPointer(UO) && UO->getBeginLoc() != UO->getEndLoc()) {
Reporter.warnPointerArithmetic(UO->getOperatorLoc());
}
}
if (hasPSet(UO)) {
auto P = getPSet(UO->getSubExpr());
if (!UO->isLValue() && isPointer(UO) && (llvm::is_contained({ UO_PostDec, UO_PostInc }, UO->getOpcode()))) {
P = derefPSet(P);
}
setPSet(UO, P);
}
}
void VisitReturnStmt(const ReturnStmt* R)
{
const Expr* RetVal = R->getRetValue();
if (!RetVal) {
return;
}
const auto TC = classifyTypeCategory(AnalyzedFD->getReturnType());
if (TC.isAggregate()) {
PSetsMap PostConditions;
getLifetimeContracts(
PostConditions, AnalyzedFD, ASTCtxt, CurrentBlock, IsConvertible, Reporter, /*Pre=*/false);
visitAggregateReturn(ignoreTransparentExprs(RetVal), PostConditions);
return;
}
if (!TC.isPointer() && !RetVal->isLValue()) {
return;
}
auto RetPSet = getPSet(RetVal);
if (RetVal->isLValue() && isa<MemberExpr>(ignoreTransparentExprs(RetVal))) {
RetPSet = derefPSetForMemberIfNecessary(RetPSet);
}
// TODO: Would be nicer if the LifetimeEnds CFG nodes would appear before
// the ReturnStmt node
invalidateLocaVarsReferencedByReturn(RetPSet, R->getSourceRange());
PSetsMap PostConditions;
getLifetimeContracts(PostConditions, AnalyzedFD, ASTCtxt, CurrentBlock, IsConvertible, Reporter, /*Pre=*/false);
RetPSet.checkSubstitutableFor(
PostConditions[Variable::returnVal(AnalyzedFD)], R->getSourceRange(), Reporter, ValueSource::Return);
}
void visitAggregateReturn(const Expr* RetVal, PSetsMap& PostConditions)
{
expandAggregate(Variable(RetVal), RetVal->getType()->getAsCXXRecordDecl(),
[this, RetVal, PostConditions](
const Variable& SubVar, const SubVarPath& Path, TypeClassification TC) mutable {
if (!TC.isPointer()) {
return;
}
const auto Range = RetVal->getSourceRange();
auto RetSubVarPSet = getVarPSet(SubVar);
CPPSAFE_ASSERT(RetSubVarPSet);
invalidateLocaVarsReferencedByReturn(*RetSubVarPSet, Range);
const auto OutVar = Variable::returnVal(AnalyzedFD).chainFields(Path);
auto& OutPSet = PostConditions[OutVar];
if (OutPSet.isUnknown()) {
OutPSet = PSet(ContractPSet({}, true), AnalyzedFD);
}
RetSubVarPSet->checkSubstitutableFor(OutPSet, Range, Reporter, ValueSource::Return);
});
}
void invalidateLocaVarsReferencedByReturn(PSet& RetPSet, const SourceRange Range)
{
for (const auto& Var : RetPSet.vars()) {
if (Var.isTemporary()) {
RetPSet = PSet::invalid(InvalidationReason::temporaryLeftScope(Range, CurrentBlock));
break;
}
if (const auto* VD = Var.asVarDecl()) {
// Allow to return a pointer to *p (then p is a parameter).
if (VD->hasLocalStorage()
&& (!Var.isDeref() || classifyTypeCategory(VD->getType()) == TypeCategory::Owner)) {
RetPSet = PSet::invalid(InvalidationReason::pointeeLeftScope(Range, CurrentBlock, VD));
break;
}
}
}
}
void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr* E)
{
const auto ExprTy = classifyTypeCategory(E->getType());
if (ExprTy.isAggregate()) {
const auto* Ctor = E->getConstructor();
if (Ctor->isDefaultConstructor()) {
handleAggregateDefaultInit(
Variable(E), E->getType()->getAsCXXRecordDecl(), CurrentBlock, E->getSourceRange(), *this);
} else if (Ctor->isCopyOrMoveConstructor()) {
handleAggregateCopy(E, E->getArg(0), *this);
CallVisitor C(*this, Reporter, CurrentBlock);
C.enforcePreAndPostConditions(E, ASTCtxt, IsConvertible);
}
setPSet(E, PSet::singleton(Variable(E)));
return;
}
if (ExprTy.isPointer()) {
visitPointerConstructExpr(E);
return;
}
// Default, will be overwritten if it makes sense.
setPSet(E, {});
}
void VisitCXXConstructExpr(const CXXConstructExpr* E)
{
const auto ExprTy = classifyTypeCategory(E->getType());
if (ExprTy.isAggregate()) {
const auto* Ctor = E->getConstructor();
if (Ctor->isDefaultConstructor()) {
handleAggregateDefaultInit(
Variable(E), E->getType()->getAsCXXRecordDecl(), CurrentBlock, E->getSourceRange(), *this);
} else if (Ctor->isCopyOrMoveConstructor()) {
handleAggregateCopy(E, E->getArg(0), *this);
CallVisitor C(*this, Reporter, CurrentBlock);
C.enforcePreAndPostConditions(E, ASTCtxt, IsConvertible);
}
setPSet(E, PSet::singleton(Variable(E)));
return;
}
if (ExprTy.isPointer()) {
visitPointerConstructExpr(E);
return;
}
// Default, will be overwritten if it makes sense.
setPSet(E, {});
// Constructing a temporary owner/value
CallVisitor C(*this, Reporter, CurrentBlock);
C.enforcePreAndPostConditions(E, ASTCtxt, IsConvertible);
}
void visitPointerConstructExpr(const CXXConstructExpr* E)
{
// [[types.pointer.init.default]]
if (E->getNumArgs() == 0) {
PSet P;
if (isNullableType(E->getType())) {
P = PSet::null(NullReason::defaultConstructed(E->getSourceRange(), CurrentBlock));
} else {
P = PSet::globalVar(false);
}
setPSet(E, P);
return;
}
auto* Ctor = E->getConstructor();
auto ParmTy = Ctor->getParamDecl(0)->getType();
auto TC = classifyTypeCategory(E->getArg(0)->getType());
// For ctors taking a const reference we assume that we will not take the
// address of the argument but copy it.
// TODO: Use the function call rules here.
if (TC == TypeCategory::Owner || Ctor->isCopyOrMoveConstructor()
|| (ParmTy->isReferenceType() && ParmTy->getPointeeType().isConstQualified())) {
setPSet(E, derefPSet(getPSet(E->getArg(0))));
} else if (TC == TypeCategory::Pointer || isa<CXXNullPtrLiteralExpr>(E->getArg(0))) {
setPSet(E, getPSet(E->getArg(0)));
} else {
// eg. std::function<void()> f(Callable{});
setPSet(E, PSet::globalVar());
}
}
void visitCXXCtorInitializer(const CXXCtorInitializer* I)
{
if (!I->isAnyMemberInitializer()) {
return;
}
// TODO: add aggr support
if (!classifyTypeCategory(I->getMember()->getType()).isPointer()) {
return;
}
const auto* MD = dyn_cast<CXXMethodDecl>(AnalyzedFD);
CPPSAFE_ASSERT(MD);
auto V = Variable::thisPointer(MD->getParent());
V.deref();
V.addFieldRef(I->getMember());
setPSet(PSet::singleton(V), getPSet(I->getInit()), I->getSourceRange());
}
void VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr* E)
{
if (hasPSet(E)) {
setPSet(E, getPSet(E->getSubExpr()));
}
}
void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr* E)
{
if (hasPSet(E)) {
// FIXME: We should do setPSet(E, getPSet(E->getSubExpr())),
// but the getSubExpr() is not visited as part of the CFG,
// so it does not have a pset.
setPSet(E, PSet::globalVar(false));
}
}
void VisitImplicitValueInitExpr(const ImplicitValueInitExpr* E)
{
// We don't really care, because this expression is not referenced
// anywhere. But still set it to satisfy the VisitStmt() post-condition.
// ImplicitValueInitExpr does not have a valid SourceRange
setPSet(E, {});
}
void VisitCompoundLiteralExpr(const CompoundLiteralExpr* E)
{
// C99 construct. We ignore it, but still set the pset to satisfy the
// VisitStmt() post-condition.
setPSet(E, {});
}
void VisitVAArgExpr(const VAArgExpr* E) { setPSet(E, {}); }
void VisitStmtExpr(const StmtExpr* E)
{
// TODO: not yet suppported.
setPSet(E, {});
}
void VisitCXXThrowExpr(const CXXThrowExpr* TE)
{
if (!TE->getSubExpr()) {
return;
}
if (!isPointer(TE->getSubExpr())) {
return;
}
const PSet ThrownPSet = getPSet(TE->getSubExpr());
if (!ThrownPSet.isGlobal()) {
Reporter.warnNonStaticThrow(TE->getSourceRange(), ThrownPSet.str());
}
}
/// Evaluates the CallExpr for effects on psets.
/// When a non-const pointer to pointer or reference to pointer is passed
/// into a function, it's pointee's are invalidated.
/// Returns true if CallExpr was handled.
void VisitCallExpr(const CallExpr* CallE)
{
if (handleDebugFunctions(CallE)) {
return;
}
CallVisitor C(*this, Reporter, CurrentBlock);
C.run(CallE, ASTCtxt, IsConvertible);
}
bool checkPSetValidity(const PSet& PS, SourceRange Range) const;
void invalidateVar(const Variable& V, const InvalidationReason& Reason) override
{
for (const auto& [Var, PS] : PMap) {
if (PS.containsInvalid()) {
continue; // Nothing to invalidate
}
if (PS.containsParent(V)) {
// WORKAROUND: https://github.com/qqiangwu/cppsafe/issues/82
//
// when move var with pset {*container}, only invalidate the var itself,
// containers and iterators are not invalidated.
// <code>
// void foo(std::vector<std::unique_ptr<int>>& cont, std::unique_ptr<int>& p)
//{
// for (auto& x : cont) {
// p = std::move(x);
//}
// for (auto& x: cont) {
// use(x);
//}
//}
//</code>
if (V.isDeref() && isIteratorOrContainer(Var.getType())) {
continue;
}
setPSet(PSet::singleton(Var), PSet::invalid(Reason), Reason.getRange());
}
}
}
void invalidateOwner(const Variable& V, const InvalidationReason& Reason) override
{
for (const auto& I : PMap) {
const auto& Var = I.first;
if (V == Var) {
continue; // Invalidating Owner' should not change the pset of Owner
}
const PSet& PS = I.second;
if (PS.containsInvalid()) {
continue; // Nothing to invalidate
}
auto DerefV = V;
DerefV.deref();
if (PS.containsParent(DerefV)) {
setPSet(PSet::singleton(Var), PSet::invalid(Reason), Reason.getRange());
}
}
std::erase_if(PMap, [&V](const auto& Item) {
const Variable& Var = Item.first;
return V != Var && Var.isField() && V.isParent(Var);
});
}
const CFGBlock* getCurrentBlock() override { return CurrentBlock; }
LifetimeReporterBase& getReporter() override { return Reporter; }
// Remove the variable from the pset together with the materialized
// temporaries extended by that variable. It also invalidates the pointers
// pointing to these.
// If VD is nullptr, invalidates all psets that contain
// MaterializeTemporaryExpr without extending decl.
void eraseVariable(const VarDecl* VD, SourceRange Range)
{
const InvalidationReason Reason = VD ? InvalidationReason::pointeeLeftScope(Range, CurrentBlock, VD)
: InvalidationReason::temporaryLeftScope(Range, CurrentBlock);
if (VD) {
std::erase_if(PMap, [VD](const auto& E) { return Variable(VD).isParent(E.first); });
invalidateVar(VD, Reason);
}
// Remove all materialized temporaries that were extended by this
// variable (or a lifetime extended temporary without an extending
// declaration) and do the invalidation.
for (auto I = PMap.begin(); I != PMap.end();) {
if (I->first.isTemporaryExtendedBy(VD)) {
I = PMap.erase(I);
} else {
const auto& Var = I->first;
auto& Pset = I->second;
const bool PsetContainsTemporary
= llvm::any_of(Pset.vars(), [VD](const Variable& V) { return V.isTemporaryExtendedBy(VD); });
if (PsetContainsTemporary) {
setPSet(PSet::singleton(Var), PSet::invalid(Reason), Reason.getRange());
}
++I;
}
}
}
PSet getPSetOfField(const Variable& P) const;
PSet getPSet(const Variable& P) const override;
PSet getPSet(const Expr* E, bool AllowNonExisting = false) const override
{
E = ignoreTransparentExprs(E);
if (E->isLValue()) {
auto I = RefersTo.find(E);
if (I != RefersTo.end()) {
return I->second;
}
if (AllowNonExisting) {
return {};
}
E->getSourceRange().dump(ASTCtxt.getSourceManager());
E->dump();
CPPSAFE_ASSERT(!"Expression has no entry in RefersTo");
}
// handle Ctor(nullptr_t)
if (isa<CXXNullPtrLiteralExpr>(E)) {
return PSet::null(NullReason::nullptrConstant(E->getSourceRange(), CurrentBlock));
}
auto I = PSetsOfExpr.find(E);
if (I != PSetsOfExpr.end()) {
return I->second;
}
if (AllowNonExisting) {
return {};
}
E->getSourceRange().dump(ASTCtxt.getSourceManager());
E->dump();
CPPSAFE_ASSERT(!"Expression has no entry in PSetsOfExpr");
}
PSet getPSet(const PSet& P) const override
{
PSet Ret;
if (P.containsInvalid()) {
return PSet::invalid(P.invReasons());
}
for (const auto& Var : P.vars()) {
Ret.merge(getPSet(Var));
}
if (P.containsGlobal()) {
Ret.merge(PSet::globalVar(false));
}
if (P.containsNull()) {
for (const auto& R : P.nullReasons()) {
Ret.addNull(R);
}
}
return Ret;
}
void setPSet(const Expr* E, const PSet& PS) override
{
if (E->isLValue()) {
DBG("Set RefersTo[" << E->getStmtClassName() << "] = " << PS.str() << "\n");
RefersTo[E] = PS;
} else {